Subversion Repositories SmartDukaan

Rev

Rev 7166 | Rev 7175 | 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
 
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
181
 
182
    push_recharge_collection_to_ocr(storeData, todate)
7163 rajveer 183
 
184
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).filter(RechargeTransaction.transactionTime >= todate).filter(RechargeTransaction.transactionTime < tomorrow).one()
185
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()
186
    if int(dt[0]) != wallet.amount:
7166 rajveer 187
        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 188
 
7141 rajveer 189
def push_recharge_collection_to_ocr(storeData, todate):
190
 
191
    for storeId in storeData.keys():
192
        store = HotspotStore.get_by(id = storeId)
193
        store.collectedAmount = 0
194
        store.availableLimit = store.creditLimit
7142 rajveer 195
        session.commit()
196
 
7141 rajveer 197
        data = storeData.get(storeId)
198
 
7144 rajveer 199
 
7141 rajveer 200
        store_string = "<Store>" + store.hotspotId + "</Store>"
201
        date_string = "<ReconDate>" + todate.strftime("%Y%m%d") + "</ReconDate>"
202
        cash_string = "<Cash>" + str(data[0]) + "</Cash>"
203
        card_string = "<Hdfc>" + str(data[1]) + "</Hdfc>"
204
        type_string = "<Type>RechargeSale</Type>"
205
        amount_string = "<GrossRechargeAmount>" + str(data[2]) + "</GrossRechargeAmount><Discount>" + str(data[3]) +  "</Discount><NetCollection>" + str(data[4]) + "</NetCollection>";
206
 
207
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
208
 
209
        conn = httplib.HTTPConnection("182.71.104.182")
210
        XML="""
211
        <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/">
212
          <soap:Body>
213
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
214
        """
215
 
216
        XML = XML + store_string + date_string + cash_string + card_string + type_string + amount_string 
217
 
218
        footer = """
219
            </SaholicRechargeSaleTransfer>
220
          </soap:Body>
221
        </soap:Envelope>
222
        """
223
        XML = XML + footer
224
 
225
        print XML
226
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
227
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
228
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
229
        conn.send(XML)
230
        response = conn.getresponse()
231
        print response.status, response.reason
232
        resp = response.read()
233
        conn.close()
234
        print resp
235
 
7147 rajveer 236
def topup_company_wallet(companyId, amount):
237
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
238
 
239
    wh = WalletHistoryForCompany()
240
    wh.walletId = wallet.id
241
    wh.openingBal = wallet.amount
242
    wh.closingBal = wallet.amount +  amount
243
    wh.amount = amount
244
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 245
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 246
    wh.description = "Wallet Credited"
247
 
248
    wallet.amount += amount
249
    session.commit()
7166 rajveer 250
    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 251
 
6147 rajveer 252
if __name__ == '__main__':
253
    main()