Subversion Repositories SmartDukaan

Rev

Rev 7967 | Rev 7983 | 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
32
from shop2020.model.v1.order.impl.RechargeService import checkTransactionStatus, getRefunds
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:
73
        d = datetime.datetime.now()
7144 rajveer 74
        d = d + timedelta(days = -1)
7141 rajveer 75
        compute_recharge_collection(d)
7821 rajveer 76
        compute_website_recharge_collection(d)
7147 rajveer 77
    if options.topup:
78
        topup_company_wallet(1,100000)
6235 rajveer 79
 
80
def processRefunds():
81
    todate = datetime.datetime.now()
82
    for i in range(15):
83
        orderDate = todate + datetime.timedelta(days= -i)
84
        refunds = getRefunds(orderDate)
85
        for key in refunds.keys():
86
            refund = refunds.get(key)
87
            refundAmount = refund[0]
88
            refundDate = refund[1]
89
            order = RechargeOrder.get_by(spiceTID = key)
7127 rajveer 90
            if order:
91
                amount = order.totalAmount
92
                isStoreOrder = False
93
            else:
94
                order = RechargeTransaction.get_by(spiceTID = key)
7188 rajveer 95
                if not order:
96
                    continue
7127 rajveer 97
                isStoreOrder = True
98
                amount = order.amount
6235 rajveer 99
            if order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
100
                print "Refund is already processed."
101
                continue
7188 rajveer 102
            if order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
7075 rajveer 103
                print "Recharge/Payment is not successful. There is something wrong."
6235 rajveer 104
                continue
7127 rajveer 105
            if amount != refundAmount:
6235 rajveer 106
                print "Refund amount is not same as transaction amount"
107
                continue
7127 rajveer 108
            if isStoreOrder:
7244 rajveer 109
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7127 rajveer 110
            else:
7780 rajveer 111
                update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
6235 rajveer 112
 
113
def processUnknownTransactions():    
114
    orders = get_recharge_orders_for_status(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6219 rajveer 115
    for order in orders:
6276 rajveer 116
        try:
117
            if order.creationTimestamp + datetime.timedelta(minutes=10) < datetime.datetime.now():
118
                status, description = checkTransactionStatus('', str(order.id))
119
                print status, description
120
                if status:
121
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
122
                else:
123
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
124
        except:
125
            print "Do Nothing"
6451 rajveer 126
 
7163 rajveer 127
    ## For store transactions
7245 rajveer 128
    rorders = RechargeTransaction.query.filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_UNKNOWN, RechargeOrderStatus.INIT])).all()
7166 rajveer 129
    for order in rorders:
7163 rajveer 130
        try:
131
            if order.transactionTime + datetime.timedelta(minutes=10) < datetime.datetime.now():
132
                status, description = checkTransactionStatus('', str(order.id))
133
                print status, description
134
                if status:
135
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
7245 rajveer 136
                elif order.status == RechargeOrderStatus.INIT:
137
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
7163 rajveer 138
                else:
7244 rajveer 139
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7163 rajveer 140
        except:
141
            print "Do Nothing"
142
 
143
 
6451 rajveer 144
def processAuthorizedTransactions(txn_id):
145
    update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6235 rajveer 146
 
7141 rajveer 147
 
148
def compute_recharge_collection(cdate):
149
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
150
    tomorrow = todate + timedelta(days=1)
7244 rajveer 151
    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 152
    storeData = {}
153
    for txn in txns:
154
        print txn
155
        if not storeData.has_key(txn[0]):
156
            data = [0,0,0,0,0]
157
            storeData[txn[0]] = data
158
        else:
159
            data = storeData[txn[0]]
7155 rajveer 160
        if txn[1] == 1:
7141 rajveer 161
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 162
        if txn[1] == 2:
7141 rajveer 163
            data[1] += int(txn[3]) - int(txn[4])
7244 rajveer 164
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_UNKNOWN):
7141 rajveer 165
            data[2] += int(txn[3])
166
            data[3] += int(txn[4])
167
            data[4] += int(txn[3]) - int(txn[4])
168
        storeData[txn[0]] = data
169
 
170
    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()  
171
    for txn in reftxns:
172
        print txn
173
        if not storeData.has_key(txn[0]):
174
            data = [0,0,0,0,0]
175
            storeData[txn[0]] = data
176
        else:
177
            data = storeData[txn[0]]
7155 rajveer 178
        if txn[1] == 1:
7148 rajveer 179
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 180
        if txn[1] == 2:
7148 rajveer 181
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 182
        data[2] -= int(txn[3])
183
        data[3] -= int(txn[4])
184
        data[4] -= int(txn[3]) - int(txn[4])
185
    print storeData
7163 rajveer 186
 
7175 rajveer 187
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
188
 
189
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
190
 
7511 rajveer 191
#    if int(dt[0]) != wallet.amount:
192
#        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 193
 
7175 rajveer 194
    maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"
195
    trecharge = 0
7967 anupam.sin 196
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
197
    hotspotServiceMatrixMap = {}
198
 
199
    for hotspotServiceMatrix in hotspotServiceMatrices:
200
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
201
 
7141 rajveer 202
    for storeId in storeData.keys():
203
        store = HotspotStore.get_by(id = storeId)
7967 anupam.sin 204
        if hotspotServiceMatrixMap.has_key(storeId):
205
            del hotspotServiceMatrixMap[storeId]
7141 rajveer 206
        store.collectedAmount = 0
207
        store.availableLimit = store.creditLimit
7142 rajveer 208
        session.commit()
209
 
7141 rajveer 210
        data = storeData.get(storeId)
7250 rajveer 211
        rc = RechargeCollection()
212
        rc.hotspotId = store.hotspotId
213
        rc.reconDate = int(todate.strftime("%Y%m%d"))
214
        rc.cash = data[0]
215
        rc.hdfc = data[1]
216
        rc.grossAmount = data[2]
217
        rc.discount = data[3]
218
        rc.netCollection = data[4]
219
        rc.addedAt = datetime.datetime.now()
220
        rc.pushedToOcr = False
221
        session.commit()
222
 
7175 rajveer 223
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
224
        trecharge +=  data[2]
7250 rajveer 225
 
7276 rajveer 226
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 227
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 228
    wamt = int(dit2[0])- int(dit[0])
229
    wallet.amount = wamt
230
    session.commit()
231
 
7250 rajveer 232
    maildata += "</tbody></table></body></html>"
7821 rajveer 233
    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 234
    try:
235
        push_recharge_collection_to_ocr()
236
    except:
237
        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 238
    finally:
239
        for storeId in hotspotServiceMatrixMap.keys():
240
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
241
                store = HotspotStore.get_by(id = storeId)
242
                helper_client = HelperClient().get_client()
243
                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"])
244
 
7250 rajveer 245
 
246
def push_recharge_collection_to_ocr():
247
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
248
 
249
    for rc in rcs:
250
        store_string = "<Store>" + rc.hotspotId + "</Store>"
251
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
252
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
253
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
254
        type_string = "<Type>RechargeSale</Type>"
255
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
256
 
7141 rajveer 257
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
258
 
7253 rajveer 259
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 260
        XML="""
261
        <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/">
262
          <soap:Body>
263
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
264
        """
265
 
266
        XML = XML + store_string + date_string + cash_string + card_string + type_string + amount_string 
267
 
268
        footer = """
269
            </SaholicRechargeSaleTransfer>
270
          </soap:Body>
271
        </soap:Envelope>
272
        """
273
        XML = XML + footer
274
 
275
        print XML
276
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
277
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
278
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
279
        conn.send(XML)
280
        response = conn.getresponse()
281
        print response.status, response.reason
282
        resp = response.read()
283
        conn.close()
284
        print resp
7250 rajveer 285
        if "Saved Successfully" in resp:
286
            rc.pushedAt = datetime.datetime.now()
287
            rc.pushedToOcr = True
288
            session.commit()
289
        elif "Error in Saving Data" in resp:
7252 rajveer 290
            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 291
        else: 
7252 rajveer 292
            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 293
 
7141 rajveer 294
 
7175 rajveer 295
 
7147 rajveer 296
def topup_company_wallet(companyId, amount):
297
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 298
    company = Company.get_by(id = companyId)
7147 rajveer 299
    wh = WalletHistoryForCompany()
300
    wh.walletId = wallet.id
301
    wh.openingBal = wallet.amount
302
    wh.closingBal = wallet.amount +  amount
303
    wh.amount = amount
304
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 305
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 306
    wh.description = "Wallet Credited"
307
 
308
    wallet.amount += amount
309
    session.commit()
7285 rajveer 310
    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 311
 
312
def compute_website_recharge_collection(cdate):
313
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
314
    tomorrow = todate + timedelta(days=1)
7147 rajveer 315
 
7823 rajveer 316
    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 317
 
318
    tamount = 0
319
    for txn in txns:
320
        tamount += int(txn[1])
321
 
322
 
7823 rajveer 323
    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 324
    for txn in reftxns:
325
        tamount -= int(txn[1])
326
 
327
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()
7823 rajveer 328
 
329
 
330
    d = datetime.datetime.now()
331
    wh = WalletHistoryForCompany()
332
    wh.walletId = wallet.id
333
    wh.openingBal = wallet.amount
334
    wh.closingBal = wallet.amount - tamount
7982 rajveer 335
    wh.amount = -tamount
7823 rajveer 336
    wh.transactionTime = d
337
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
338
    wh.description = "Wallet Credited"
339
    wallet.amount = wallet.amount - tamount
7821 rajveer 340
    session.commit()
341
 
7823 rajveer 342
 
7821 rajveer 343
    maildata = ""
7982 rajveer 344
    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 345
 
346
 
6147 rajveer 347
if __name__ == '__main__':
7967 anupam.sin 348
    main()
349