Subversion Repositories SmartDukaan

Rev

Rev 7821 | Rev 7967 | 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())
23
 
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,\
7285 rajveer 30
    WalletForCompany, WalletHistoryForCompany, RechargeCollection, Company
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
7141 rajveer 196
    for storeId in storeData.keys():
197
        store = HotspotStore.get_by(id = storeId)
198
        store.collectedAmount = 0
199
        store.availableLimit = store.creditLimit
7142 rajveer 200
        session.commit()
201
 
7141 rajveer 202
        data = storeData.get(storeId)
7250 rajveer 203
        rc = RechargeCollection()
204
        rc.hotspotId = store.hotspotId
205
        rc.reconDate = int(todate.strftime("%Y%m%d"))
206
        rc.cash = data[0]
207
        rc.hdfc = data[1]
208
        rc.grossAmount = data[2]
209
        rc.discount = data[3]
210
        rc.netCollection = data[4]
211
        rc.addedAt = datetime.datetime.now()
212
        rc.pushedToOcr = False
213
        session.commit()
214
 
7175 rajveer 215
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
216
        trecharge +=  data[2]
7250 rajveer 217
 
7276 rajveer 218
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 219
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 220
    wamt = int(dit2[0])- int(dit[0])
221
    wallet.amount = wamt
222
    session.commit()
223
 
7250 rajveer 224
    maildata += "</tbody></table></body></html>"
7821 rajveer 225
    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 226
    try:
227
        push_recharge_collection_to_ocr()
228
    except:
229
        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", "", [])
7250 rajveer 230
 
231
def push_recharge_collection_to_ocr():
232
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
233
 
234
    for rc in rcs:
235
        store_string = "<Store>" + rc.hotspotId + "</Store>"
236
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
237
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
238
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
239
        type_string = "<Type>RechargeSale</Type>"
240
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
241
 
7141 rajveer 242
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
243
 
7253 rajveer 244
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 245
        XML="""
246
        <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/">
247
          <soap:Body>
248
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
249
        """
250
 
251
        XML = XML + store_string + date_string + cash_string + card_string + type_string + amount_string 
252
 
253
        footer = """
254
            </SaholicRechargeSaleTransfer>
255
          </soap:Body>
256
        </soap:Envelope>
257
        """
258
        XML = XML + footer
259
 
260
        print XML
261
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
262
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
263
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
264
        conn.send(XML)
265
        response = conn.getresponse()
266
        print response.status, response.reason
267
        resp = response.read()
268
        conn.close()
269
        print resp
7250 rajveer 270
        if "Saved Successfully" in resp:
271
            rc.pushedAt = datetime.datetime.now()
272
            rc.pushedToOcr = True
273
            session.commit()
274
        elif "Error in Saving Data" in resp:
7252 rajveer 275
            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 276
        else: 
7252 rajveer 277
            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 278
 
7141 rajveer 279
 
7175 rajveer 280
 
7147 rajveer 281
def topup_company_wallet(companyId, amount):
282
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 283
    company = Company.get_by(id = companyId)
7147 rajveer 284
    wh = WalletHistoryForCompany()
285
    wh.walletId = wallet.id
286
    wh.openingBal = wallet.amount
287
    wh.closingBal = wallet.amount +  amount
288
    wh.amount = amount
289
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 290
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 291
    wh.description = "Wallet Credited"
292
 
293
    wallet.amount += amount
294
    session.commit()
7285 rajveer 295
    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 296
 
297
def compute_website_recharge_collection(cdate):
298
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
299
    tomorrow = todate + timedelta(days=1)
7147 rajveer 300
 
7823 rajveer 301
    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 302
 
303
    tamount = 0
304
    for txn in txns:
305
        tamount += int(txn[1])
306
 
307
 
7823 rajveer 308
    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 309
    for txn in reftxns:
310
        tamount -= int(txn[1])
311
 
312
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()
7823 rajveer 313
 
314
 
315
    d = datetime.datetime.now()
316
    wh = WalletHistoryForCompany()
317
    wh.walletId = wallet.id
318
    wh.openingBal = wallet.amount
319
    wh.closingBal = wallet.amount - tamount
320
    wh.amount = tamount
321
    wh.transactionTime = d
322
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
323
    wh.description = "Wallet Credited"
324
    wallet.amount = wallet.amount - tamount
7821 rajveer 325
    session.commit()
326
 
7823 rajveer 327
 
7821 rajveer 328
    maildata = ""
7823 rajveer 329
    mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["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 330
 
331
 
6147 rajveer 332
if __name__ == '__main__':
333
    main()