Subversion Repositories SmartDukaan

Rev

Rev 7188 | Rev 7244 | 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,\
30
    WalletForCompany, WalletHistoryForCompany
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:
108
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, refundDate)
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
7166 rajveer 127
    rorders = RechargeTransaction.query.filter_by(status = RechargeOrderStatus.RECHARGE_UNKNOWN).all()
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)
135
                else:
136
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
137
        except:
138
            print "Do Nothing"
139
 
140
 
6451 rajveer 141
def processAuthorizedTransactions(txn_id):
142
    update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6235 rajveer 143
 
7141 rajveer 144
 
145
def compute_recharge_collection(cdate):
146
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
147
    tomorrow = todate + timedelta(days=1)
148
    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])).filter(RechargeTransaction.transactionTime >= todate).filter(RechargeTransaction.transactionTime < tomorrow).group_by(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status).order_by(RechargeTransaction.storeId).all()
149
    storeData = {}
150
    for txn in txns:
151
        print txn
152
        if not storeData.has_key(txn[0]):
153
            data = [0,0,0,0,0]
154
            storeData[txn[0]] = data
155
        else:
156
            data = storeData[txn[0]]
7155 rajveer 157
        if txn[1] == 1:
7141 rajveer 158
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 159
        if txn[1] == 2:
7141 rajveer 160
            data[1] += int(txn[3]) - int(txn[4])
161
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED):
162
            data[2] += int(txn[3])
163
            data[3] += int(txn[4])
164
            data[4] += int(txn[3]) - int(txn[4])
165
        storeData[txn[0]] = data
166
 
167
    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()  
168
    for txn in reftxns:
169
        print txn
170
        if not storeData.has_key(txn[0]):
171
            data = [0,0,0,0,0]
172
            storeData[txn[0]] = data
173
        else:
174
            data = storeData[txn[0]]
7155 rajveer 175
        if txn[1] == 1:
7148 rajveer 176
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 177
        if txn[1] == 2:
7148 rajveer 178
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 179
        data[2] -= int(txn[3])
180
        data[3] -= int(txn[4])
181
        data[4] -= int(txn[3]) - int(txn[4])
182
    print storeData
7163 rajveer 183
 
7175 rajveer 184
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
185
    push_recharge_collection_to_ocr(storeData, todate, wallet.amount)
186
 
187
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
188
 
7163 rajveer 189
    if int(dt[0]) != wallet.amount:
7166 rajveer 190
        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])) , "", [], [], [])    
7163 rajveer 191
 
7175 rajveer 192
def push_recharge_collection_to_ocr(storeData, todate, wamount):
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
195
 
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)
203
 
7144 rajveer 204
 
7141 rajveer 205
        store_string = "<Store>" + store.hotspotId + "</Store>"
206
        date_string = "<ReconDate>" + todate.strftime("%Y%m%d") + "</ReconDate>"
207
        cash_string = "<Cash>" + str(data[0]) + "</Cash>"
208
        card_string = "<Hdfc>" + str(data[1]) + "</Hdfc>"
209
        type_string = "<Type>RechargeSale</Type>"
210
        amount_string = "<GrossRechargeAmount>" + str(data[2]) + "</GrossRechargeAmount><Discount>" + str(data[3]) +  "</Discount><NetCollection>" + str(data[4]) + "</NetCollection>";
211
 
7175 rajveer 212
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
213
        trecharge +=  data[2]
214
 
7141 rajveer 215
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
216
 
217
        conn = httplib.HTTPConnection("182.71.104.182")
218
        XML="""
219
        <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/">
220
          <soap:Body>
221
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
222
        """
223
 
224
        XML = XML + store_string + date_string + cash_string + card_string + type_string + amount_string 
225
 
226
        footer = """
227
            </SaholicRechargeSaleTransfer>
228
          </soap:Body>
229
        </soap:Envelope>
230
        """
231
        XML = XML + footer
232
 
233
        print XML
234
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
235
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
236
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
237
        conn.send(XML)
238
        response = conn.getresponse()
239
        print response.status, response.reason
240
        resp = response.read()
241
        conn.close()
242
        print resp
243
 
7175 rajveer 244
    maildata += "</tbody></table></body></html>"
7209 rajveer 245
    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(wamount) + ")    (Total Recharge - " + str(trecharge) + ")", maildata, [])
7175 rajveer 246
 
7147 rajveer 247
def topup_company_wallet(companyId, amount):
248
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
249
 
250
    wh = WalletHistoryForCompany()
251
    wh.walletId = wallet.id
252
    wh.openingBal = wallet.amount
253
    wh.closingBal = wallet.amount +  amount
254
    wh.amount = amount
255
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 256
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 257
    wh.description = "Wallet Credited"
258
 
259
    wallet.amount += amount
260
    session.commit()
7166 rajveer 261
    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 262
 
6147 rajveer 263
if __name__ == '__main__':
264
    main()