Subversion Repositories SmartDukaan

Rev

Rev 7982 | Rev 7986 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
6147 rajveer 1
#!/usr/bin/python
2
'''
3
It is used to process transactions for which the payment 
4
was received but the order was not processed.
5
 
6
@author: Rajveer
7
'''
8
import optparse
9
import sys
6219 rajveer 10
import datetime
7141 rajveer 11
from datetime import timedelta
6235 rajveer 12
from elixir import *
7141 rajveer 13
from sqlalchemy.sql import func
14
import urllib
15
import httplib
7175 rajveer 16
from shop2020.utils.EmailAttachmentSender import mail, mail_html
6147 rajveer 17
 
18
 
19
 
20
if __name__ == '__main__' and __package__ is None:
21
    import os
22
    sys.path.insert(0, os.getcwd())
7967 anupam.sin 23
from shop2020.clients.HelperClient import HelperClient
7167 rajveer 24
from shop2020.thriftpy.model.v1.order.ttypes import RechargeOrderStatus,\
25
    OrderType
6254 rajveer 26
from shop2020.model.v1.order.impl.DataAccessors import get_recharge_orders_for_status, update_recharge_order_status,\
7147 rajveer 27
    update_recharge_transaction_status, get_next_invoice_number
7128 rajveer 28
from shop2020.model.v1.order.impl import DataService
7147 rajveer 29
from shop2020.model.v1.order.impl.DataService import RechargeTransaction, HotspotStore,\
7967 anupam.sin 30
    WalletForCompany, WalletHistoryForCompany, RechargeCollection, Company, HotspotServiceMatrix
6235 rajveer 31
from shop2020.model.v1.order.impl.model.RechargeOrder import RechargeOrder
7983 rajveer 32
from shop2020.model.v1.order.impl.RechargeService import checkTransactionStatus, getRefunds, getBalance 
6147 rajveer 33
 
34
 
35
def main():
36
    parser = optparse.OptionParser()
37
    parser.add_option("-H", "--host", dest="hostname",
38
                      default="localhost",
39
                      type="string", help="The HOST where the DB server is running",
40
                      metavar="HOST")
6235 rajveer 41
    parser.add_option("-r", "--refund", dest="refund",
42
                      action="store_true",
43
                      help="")
44
    parser.add_option("-u", "--unknown", dest="unknown",
45
                      action="store_true",
46
                      help="")
6452 rajveer 47
    parser.add_option("-a", "--authorized", dest="authorized",
6451 rajveer 48
                      action="store_true",
49
                      help="")
7141 rajveer 50
    parser.add_option("-c", "--collection", dest="collection",
51
                      action="store_true",
52
                      help="")
7147 rajveer 53
    parser.add_option("-T", "--topup", dest="topup",
54
                      action="store_true",
55
                      help="")    
6451 rajveer 56
    parser.add_option("-t", "--txn-id", dest="txn_id",
57
                   type="int",
58
                   help="mark the transaction(recharge order id) TXN_ID as successful",
59
                   metavar="TXN_ID")
6235 rajveer 60
 
6147 rajveer 61
    (options, args) = parser.parse_args()
62
    if len(args) != 0:
63
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
6254 rajveer 64
    DataService.initialize(db_hostname=options.hostname, echoOn=True)
65
 
6235 rajveer 66
    if options.refund:
67
        processRefunds()
68
    if options.unknown:
69
        processUnknownTransactions()
6451 rajveer 70
    if options.authorized:
71
        processAuthorizedTransactions(options.txn_id)
7141 rajveer 72
    if options.collection:
7983 rajveer 73
        wallet = WalletForCompany.query.filter(WalletForCompany.id == 3).one()
74
        oldBalance = wallet.amount
75
        newBalance = getBalance()  
76
        wallet.amount = newBalance
77
        session.commit()
78
 
7141 rajveer 79
        d = datetime.datetime.now()
7144 rajveer 80
        d = d + timedelta(days = -1)
7141 rajveer 81
        compute_recharge_collection(d)
7983 rajveer 82
        compute_website_recharge_collection(d, oldBalance, newBalance)
7147 rajveer 83
    if options.topup:
84
        topup_company_wallet(1,100000)
6235 rajveer 85
 
86
def processRefunds():
87
    todate = datetime.datetime.now()
88
    for i in range(15):
89
        orderDate = todate + datetime.timedelta(days= -i)
90
        refunds = getRefunds(orderDate)
91
        for key in refunds.keys():
92
            refund = refunds.get(key)
93
            refundAmount = refund[0]
94
            refundDate = refund[1]
95
            order = RechargeOrder.get_by(spiceTID = key)
7127 rajveer 96
            if order:
97
                amount = order.totalAmount
98
                isStoreOrder = False
99
            else:
100
                order = RechargeTransaction.get_by(spiceTID = key)
7188 rajveer 101
                if not order:
102
                    continue
7127 rajveer 103
                isStoreOrder = True
104
                amount = order.amount
6235 rajveer 105
            if order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
106
                print "Refund is already processed."
107
                continue
7188 rajveer 108
            if order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
7075 rajveer 109
                print "Recharge/Payment is not successful. There is something wrong."
6235 rajveer 110
                continue
7127 rajveer 111
            if amount != refundAmount:
6235 rajveer 112
                print "Refund amount is not same as transaction amount"
113
                continue
7127 rajveer 114
            if isStoreOrder:
7244 rajveer 115
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7127 rajveer 116
            else:
7780 rajveer 117
                update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
6235 rajveer 118
 
119
def processUnknownTransactions():    
120
    orders = get_recharge_orders_for_status(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6219 rajveer 121
    for order in orders:
6276 rajveer 122
        try:
123
            if order.creationTimestamp + datetime.timedelta(minutes=10) < datetime.datetime.now():
124
                status, description = checkTransactionStatus('', str(order.id))
125
                print status, description
126
                if status:
127
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
128
                else:
129
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
130
        except:
131
            print "Do Nothing"
6451 rajveer 132
 
7163 rajveer 133
    ## For store transactions
7245 rajveer 134
    rorders = RechargeTransaction.query.filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_UNKNOWN, RechargeOrderStatus.INIT])).all()
7166 rajveer 135
    for order in rorders:
7163 rajveer 136
        try:
137
            if order.transactionTime + datetime.timedelta(minutes=10) < datetime.datetime.now():
138
                status, description = checkTransactionStatus('', str(order.id))
139
                print status, description
140
                if status:
141
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
7245 rajveer 142
                elif order.status == RechargeOrderStatus.INIT:
143
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
7163 rajveer 144
                else:
7244 rajveer 145
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7163 rajveer 146
        except:
147
            print "Do Nothing"
148
 
149
 
6451 rajveer 150
def processAuthorizedTransactions(txn_id):
151
    update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6235 rajveer 152
 
7141 rajveer 153
 
154
def compute_recharge_collection(cdate):
155
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
156
    tomorrow = todate + timedelta(days=1)
7244 rajveer 157
    txns = session.query(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status, func.sum(RechargeTransaction.amount), func.sum(RechargeTransaction.discount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_UNKNOWN])).filter(RechargeTransaction.transactionTime >= todate).filter(RechargeTransaction.transactionTime < tomorrow).group_by(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status).order_by(RechargeTransaction.storeId).all()
7141 rajveer 158
    storeData = {}
159
    for txn in txns:
160
        print txn
161
        if not storeData.has_key(txn[0]):
162
            data = [0,0,0,0,0]
163
            storeData[txn[0]] = data
164
        else:
165
            data = storeData[txn[0]]
7155 rajveer 166
        if txn[1] == 1:
7141 rajveer 167
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 168
        if txn[1] == 2:
7141 rajveer 169
            data[1] += int(txn[3]) - int(txn[4])
7244 rajveer 170
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_UNKNOWN):
7141 rajveer 171
            data[2] += int(txn[3])
172
            data[3] += int(txn[4])
173
            data[4] += int(txn[3]) - int(txn[4])
174
        storeData[txn[0]] = data
175
 
176
    reftxns = session.query(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status, func.sum(RechargeTransaction.amount), func.sum(RechargeTransaction.discount)).filter(RechargeTransaction.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED).filter(RechargeTransaction.responseTime >= todate).filter(RechargeTransaction.responseTime < tomorrow).group_by(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status).order_by(RechargeTransaction.storeId).all()  
177
    for txn in reftxns:
178
        print txn
179
        if not storeData.has_key(txn[0]):
180
            data = [0,0,0,0,0]
181
            storeData[txn[0]] = data
182
        else:
183
            data = storeData[txn[0]]
7155 rajveer 184
        if txn[1] == 1:
7148 rajveer 185
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 186
        if txn[1] == 2:
7148 rajveer 187
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 188
        data[2] -= int(txn[3])
189
        data[3] -= int(txn[4])
190
        data[4] -= int(txn[3]) - int(txn[4])
191
    print storeData
7163 rajveer 192
 
7175 rajveer 193
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
194
 
195
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
196
 
7511 rajveer 197
#    if int(dt[0]) != wallet.amount:
198
#        mail("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in"], "Wallet amount: " + str(wallet.amount) + " does not match with transaction amount: " + str(int(dt[0])) , "", [], [], [])    
7250 rajveer 199
 
7175 rajveer 200
    maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"
201
    trecharge = 0
7967 anupam.sin 202
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
203
    hotspotServiceMatrixMap = {}
204
 
205
    for hotspotServiceMatrix in hotspotServiceMatrices:
206
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
207
 
7141 rajveer 208
    for storeId in storeData.keys():
209
        store = HotspotStore.get_by(id = storeId)
7967 anupam.sin 210
        if hotspotServiceMatrixMap.has_key(storeId):
211
            del hotspotServiceMatrixMap[storeId]
7141 rajveer 212
        store.collectedAmount = 0
213
        store.availableLimit = store.creditLimit
7142 rajveer 214
        session.commit()
215
 
7141 rajveer 216
        data = storeData.get(storeId)
7250 rajveer 217
        rc = RechargeCollection()
218
        rc.hotspotId = store.hotspotId
219
        rc.reconDate = int(todate.strftime("%Y%m%d"))
220
        rc.cash = data[0]
221
        rc.hdfc = data[1]
222
        rc.grossAmount = data[2]
223
        rc.discount = data[3]
224
        rc.netCollection = data[4]
225
        rc.addedAt = datetime.datetime.now()
226
        rc.pushedToOcr = False
227
        session.commit()
228
 
7175 rajveer 229
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
230
        trecharge +=  data[2]
7250 rajveer 231
 
7276 rajveer 232
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 233
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 234
    wamt = int(dit2[0])- int(dit[0])
235
    wallet.amount = wamt
236
    session.commit()
237
 
7250 rajveer 238
    maildata += "</tbody></table></body></html>"
7821 rajveer 239
    mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "Ashwani.Kumar@spiceretail.co.in","parveen.mittal@spiceretail.co.in","pardeep.panwar@spiceretail.co.in","gagan.sharma@spiceretail.co.in","j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in", "amit.tyagi@spiceretail.co.in"], "MIS :- SpiceRetail  (Date - " + todate.strftime("%d-%m-%Y") + ")   (Wallet Amount - " + str(wallet.amount) + ")    (Total Recharge - " + str(trecharge) + ")", maildata, []) 
7252 rajveer 240
    try:
241
        push_recharge_collection_to_ocr()
242
    except:
243
        mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "rajneesh.arora@shop2020.in"], "Problem while pushing recharge collection to OCR", "", [])
7967 anupam.sin 244
    finally:
245
        for storeId in hotspotServiceMatrixMap.keys():
246
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
247
                store = HotspotStore.get_by(id = storeId)
248
                helper_client = HelperClient().get_client()
249
                helper_client.saveUserEmailForSending([store.clusterEmail], "cnc.center@shop2020.in", "No Recharge happened for store " + store.hotspotId + " yesterday", "", "NRM", "NoRechargeMail", [store.email], ["anupam.singh@shop2020.in"])
250
 
7250 rajveer 251
 
252
def push_recharge_collection_to_ocr():
253
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
254
 
255
    for rc in rcs:
256
        store_string = "<Store>" + rc.hotspotId + "</Store>"
257
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
258
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
259
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
260
        type_string = "<Type>RechargeSale</Type>"
261
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
262
 
7141 rajveer 263
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
264
 
7253 rajveer 265
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 266
        XML="""
267
        <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
268
          <soap:Body>
269
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
270
        """
271
 
272
        XML = XML + store_string + date_string + cash_string + card_string + type_string + amount_string 
273
 
274
        footer = """
275
            </SaholicRechargeSaleTransfer>
276
          </soap:Body>
277
        </soap:Envelope>
278
        """
279
        XML = XML + footer
280
 
281
        print XML
282
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
283
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
284
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
285
        conn.send(XML)
286
        response = conn.getresponse()
287
        print response.status, response.reason
288
        resp = response.read()
289
        conn.close()
290
        print resp
7250 rajveer 291
        if "Saved Successfully" in resp:
292
            rc.pushedAt = datetime.datetime.now()
293
            rc.pushedToOcr = True
294
            session.commit()
295
        elif "Error in Saving Data" in resp:
7252 rajveer 296
            mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "rajneesh.arora@shop2020.in"], "Problem while pushing recharge collection to OCR", resp, [])
7250 rajveer 297
        else: 
7252 rajveer 298
            mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "rajneesh.arora@shop2020.in"], "Problem while pushing recharge collection to OCR", resp, [])
7250 rajveer 299
 
7141 rajveer 300
 
7175 rajveer 301
 
7147 rajveer 302
def topup_company_wallet(companyId, amount):
303
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 304
    company = Company.get_by(id = companyId)
7147 rajveer 305
    wh = WalletHistoryForCompany()
306
    wh.walletId = wallet.id
307
    wh.openingBal = wallet.amount
308
    wh.closingBal = wallet.amount +  amount
309
    wh.amount = amount
310
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 311
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 312
    wh.description = "Wallet Credited"
313
 
314
    wallet.amount += amount
315
    session.commit()
7285 rajveer 316
    mail("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "Ashwani.Kumar@spiceretail.co.in","parveen.mittal@spiceretail.co.in","pardeep.panwar@spiceretail.co.in","gagan.sharma@spiceretail.co.in","j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in", "amit.tyagi@spiceretail.co.in"] , company.name + " wallet topped up by " +  str(amount) + " rupees.", "", [], [], [])
7821 rajveer 317
 
7983 rajveer 318
def compute_website_recharge_collection(cdate, oldBalance, newBalance):
7821 rajveer 319
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
320
    tomorrow = todate + timedelta(days=1)
7147 rajveer 321
 
7823 rajveer 322
    txns = session.query(RechargeOrder.status, func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.PAYMENT_SUCCESSFUL])).filter(RechargeOrder.creationTimestamp >= todate).filter(RechargeOrder.creationTimestamp < tomorrow).group_by(RechargeOrder.status).all()
7821 rajveer 323
 
324
    tamount = 0
325
    for txn in txns:
326
        tamount += int(txn[1])
327
 
328
 
7823 rajveer 329
    reftxns = session.query(RechargeOrder.status, func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED).filter(RechargeOrder.responseTimestamp >= todate).filter(RechargeOrder.responseTimestamp < tomorrow).group_by(RechargeOrder.status).all()  
7821 rajveer 330
    for txn in reftxns:
331
        tamount -= int(txn[1])
332
 
333
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()
7823 rajveer 334
 
335
 
336
    d = datetime.datetime.now()
337
    wh = WalletHistoryForCompany()
338
    wh.walletId = wallet.id
339
    wh.openingBal = wallet.amount
340
    wh.closingBal = wallet.amount - tamount
7982 rajveer 341
    wh.amount = -tamount
7823 rajveer 342
    wh.transactionTime = d
343
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
344
    wh.description = "Wallet Credited"
345
    wallet.amount = wallet.amount - tamount
7821 rajveer 346
    session.commit()
347
 
7823 rajveer 348
 
7983 rajveer 349
    maildata = "Old Wallet Amount is : " + str(oldBalance) + "<br>New Wallet Amount is : " + str(newBalance)
7982 rajveer 350
    mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["pardeep.panwar@spiceretail.co.in>", "amit.tyagi@spiceretail.co.in", "rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in"], "MIS :- Saholic (Date - " + todate.strftime("%d-%m-%Y") + ")   (Wallet Amount - " + str(wallet.amount) + ")    (Total Recharge - " + str(tamount) + ")", maildata, []) 
7821 rajveer 351
 
352
 
6147 rajveer 353
if __name__ == '__main__':
7967 anupam.sin 354
    main()
355