Subversion Repositories SmartDukaan

Rev

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