Subversion Repositories SmartDukaan

Rev

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