Subversion Repositories SmartDukaan

Rev

Rev 7128 | Rev 7142 | 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
6147 rajveer 16
 
17
 
18
 
19
if __name__ == '__main__' and __package__ is None:
20
    import os
21
    sys.path.insert(0, os.getcwd())
22
 
23
from shop2020.thriftpy.model.v1.order.ttypes import RechargeOrderStatus
6254 rajveer 24
from shop2020.model.v1.order.impl.DataAccessors import get_recharge_orders_for_status, update_recharge_order_status,\
7127 rajveer 25
    update_amount_in_wallet, update_recharge_transaction_status
7128 rajveer 26
from shop2020.model.v1.order.impl import DataService
7141 rajveer 27
from shop2020.model.v1.order.impl.DataService import RechargeTransaction, HotspotStore
6235 rajveer 28
from shop2020.model.v1.order.impl.model.RechargeOrder import RechargeOrder
29
from shop2020.model.v1.order.impl.RechargeService import checkTransactionStatus, getRefunds
6147 rajveer 30
 
31
 
32
def main():
33
    parser = optparse.OptionParser()
34
    parser.add_option("-H", "--host", dest="hostname",
35
                      default="localhost",
36
                      type="string", help="The HOST where the DB server is running",
37
                      metavar="HOST")
6235 rajveer 38
    parser.add_option("-r", "--refund", dest="refund",
39
                      action="store_true",
40
                      help="")
41
    parser.add_option("-u", "--unknown", dest="unknown",
42
                      action="store_true",
43
                      help="")
6452 rajveer 44
    parser.add_option("-a", "--authorized", dest="authorized",
6451 rajveer 45
                      action="store_true",
46
                      help="")
7141 rajveer 47
    parser.add_option("-c", "--collection", dest="collection",
48
                      action="store_true",
49
                      help="")
6451 rajveer 50
    parser.add_option("-t", "--txn-id", dest="txn_id",
51
                   type="int",
52
                   help="mark the transaction(recharge order id) TXN_ID as successful",
53
                   metavar="TXN_ID")
6235 rajveer 54
 
6147 rajveer 55
    (options, args) = parser.parse_args()
56
    if len(args) != 0:
57
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
6254 rajveer 58
    DataService.initialize(db_hostname=options.hostname, echoOn=True)
59
 
6235 rajveer 60
    if options.refund:
61
        processRefunds()
62
    if options.unknown:
63
        processUnknownTransactions()
6451 rajveer 64
    if options.authorized:
65
        processAuthorizedTransactions(options.txn_id)
7141 rajveer 66
    if options.collection:
67
        d = datetime.datetime.now()
68
        #d = d + timedelta(days = -10)
69
        compute_recharge_collection(d)
6235 rajveer 70
 
71
def processRefunds():
72
    todate = datetime.datetime.now()
73
    for i in range(15):
74
        orderDate = todate + datetime.timedelta(days= -i)
75
        refunds = getRefunds(orderDate)
76
        for key in refunds.keys():
77
            refund = refunds.get(key)
78
            refundAmount = refund[0]
79
            refundDate = refund[1]
80
            order = RechargeOrder.get_by(spiceTID = key)
7127 rajveer 81
            if order:
82
                amount = order.totalAmount
83
                isStoreOrder = False
84
            else:
85
                order = RechargeTransaction.get_by(spiceTID = key)
86
                isStoreOrder = True
87
                amount = order.amount
6235 rajveer 88
            if order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
89
                print "Refund is already processed."
90
                continue
7075 rajveer 91
            if order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL):
92
                print "Recharge/Payment is not successful. There is something wrong."
6235 rajveer 93
                continue
7127 rajveer 94
            if amount != refundAmount:
6235 rajveer 95
                print "Refund amount is not same as transaction amount"
96
                continue
7127 rajveer 97
            if isStoreOrder:
98
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, refundDate)
99
            else:
100
                update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, refundDate)
6235 rajveer 101
 
102
def processUnknownTransactions():    
103
    orders = get_recharge_orders_for_status(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6219 rajveer 104
    for order in orders:
6276 rajveer 105
        try:
106
            if order.creationTimestamp + datetime.timedelta(minutes=10) < datetime.datetime.now():
107
                status, description = checkTransactionStatus('', str(order.id))
108
                print status, description
109
                if status:
110
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
111
                else:
112
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
113
        except:
114
            print "Do Nothing"
6451 rajveer 115
 
116
def processAuthorizedTransactions(txn_id):
117
    update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6235 rajveer 118
 
7141 rajveer 119
 
120
def compute_recharge_collection(cdate):
121
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
122
    tomorrow = todate + timedelta(days=1)
123
    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()
124
    storeData = {}
125
    for txn in txns:
126
        print txn
127
        if not storeData.has_key(txn[0]):
128
            data = [0,0,0,0,0]
129
            storeData[txn[0]] = data
130
        else:
131
            data = storeData[txn[0]]
132
        if txn[1] == 0:
133
            data[0] += int(txn[3]) - int(txn[4])
134
        if txn[1] == 1:
135
            data[1] += int(txn[3]) - int(txn[4])
136
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED):
137
            data[2] += int(txn[3])
138
            data[3] += int(txn[4])
139
            data[4] += int(txn[3]) - int(txn[4])
140
        storeData[txn[0]] = data
141
 
142
    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()  
143
    for txn in reftxns:
144
        print txn
145
        if not storeData.has_key(txn[0]):
146
            data = [0,0,0,0,0]
147
            storeData[txn[0]] = data
148
        else:
149
            data = storeData[txn[0]]
150
        if txn[1] == 0:
151
            data[0] += int(txn[3]) - int(txn[4])
152
        if txn[1] == 1:
153
            data[1] += int(txn[3]) - int(txn[4])
154
        data[2] -= int(txn[3])
155
        data[3] -= int(txn[4])
156
        data[4] -= int(txn[3]) - int(txn[4])
157
    print storeData
158
 
159
    push_recharge_collection_to_ocr(storeData, todate)
160
 
161
def push_recharge_collection_to_ocr(storeData, todate):
162
 
163
    for storeId in storeData.keys():
164
        store = HotspotStore.get_by(id = storeId)
165
        store.collectedAmount = 0
166
        store.availableLimit = store.creditLimit
167
 
168
        data = storeData.get(storeId)
169
 
170
        if store.hotspotId == 'C93':
171
            continue
172
        store_string = "<Store>" + store.hotspotId + "</Store>"
173
        date_string = "<ReconDate>" + todate.strftime("%Y%m%d") + "</ReconDate>"
174
        cash_string = "<Cash>" + str(data[0]) + "</Cash>"
175
        card_string = "<Hdfc>" + str(data[1]) + "</Hdfc>"
176
        type_string = "<Type>RechargeSale</Type>"
177
        amount_string = "<GrossRechargeAmount>" + str(data[2]) + "</GrossRechargeAmount><Discount>" + str(data[3]) +  "</Discount><NetCollection>" + str(data[4]) + "</NetCollection>";
178
 
179
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
180
 
181
        conn = httplib.HTTPConnection("182.71.104.182")
182
        XML="""
183
        <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/">
184
          <soap:Body>
185
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
186
        """
187
 
188
        XML = XML + store_string + date_string + cash_string + card_string + type_string + amount_string 
189
 
190
        footer = """
191
            </SaholicRechargeSaleTransfer>
192
          </soap:Body>
193
        </soap:Envelope>
194
        """
195
        XML = XML + footer
196
 
197
        print XML
198
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
199
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
200
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
201
        conn.send(XML)
202
        response = conn.getresponse()
203
        print response.status, response.reason
204
        resp = response.read()
205
        conn.close()
206
        print resp
207
 
6147 rajveer 208
if __name__ == '__main__':
209
    main()