Subversion Repositories SmartDukaan

Rev

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