Subversion Repositories SmartDukaan

Rev

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