Subversion Repositories SmartDukaan

Rev

Rev 8837 | Rev 8875 | 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
8788 rajveer 17
from shop2020.model.v1.order.impl.model.UserWalletHistory import UserWalletHistory
18
from shop2020.utils.Utils import to_java_date, to_py_date
19
from shop2020.clients.PaymentClient import PaymentClient
6147 rajveer 20
 
21
 
22
 
23
if __name__ == '__main__' and __package__ is None:
24
    import os
25
    sys.path.insert(0, os.getcwd())
7986 anupam.sin 26
from datetime import date, timedelta
7967 anupam.sin 27
from shop2020.clients.HelperClient import HelperClient
7167 rajveer 28
from shop2020.thriftpy.model.v1.order.ttypes import RechargeOrderStatus,\
29
    OrderType
6254 rajveer 30
from shop2020.model.v1.order.impl.DataAccessors import get_recharge_orders_for_status, update_recharge_order_status,\
7147 rajveer 31
    update_recharge_transaction_status, get_next_invoice_number
7128 rajveer 32
from shop2020.model.v1.order.impl import DataService
7147 rajveer 33
from shop2020.model.v1.order.impl.DataService import RechargeTransaction, HotspotStore,\
8788 rajveer 34
    WalletForCompany, WalletHistoryForCompany, RechargeCollection, Company, HotspotServiceMatrix,\
35
    RechargeVoucherTracker
6235 rajveer 36
from shop2020.model.v1.order.impl.model.RechargeOrder import RechargeOrder
7983 rajveer 37
from shop2020.model.v1.order.impl.RechargeService import checkTransactionStatus, getRefunds, getBalance 
8788 rajveer 38
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, between
6147 rajveer 39
 
40
def main():
41
    parser = optparse.OptionParser()
42
    parser.add_option("-H", "--host", dest="hostname",
43
                      default="localhost",
44
                      type="string", help="The HOST where the DB server is running",
45
                      metavar="HOST")
6235 rajveer 46
    parser.add_option("-r", "--refund", dest="refund",
47
                      action="store_true",
48
                      help="")
49
    parser.add_option("-u", "--unknown", dest="unknown",
50
                      action="store_true",
51
                      help="")
6452 rajveer 52
    parser.add_option("-a", "--authorized", dest="authorized",
6451 rajveer 53
                      action="store_true",
54
                      help="")
7141 rajveer 55
    parser.add_option("-c", "--collection", dest="collection",
56
                      action="store_true",
57
                      help="")
8788 rajveer 58
    parser.add_option("-R", "--recon", dest="recon",
59
                      action="store_true",
60
                      help="")
7147 rajveer 61
    parser.add_option("-T", "--topup", dest="topup",
62
                      action="store_true",
63
                      help="")    
6451 rajveer 64
    parser.add_option("-t", "--txn-id", dest="txn_id",
65
                   type="int",
66
                   help="mark the transaction(recharge order id) TXN_ID as successful",
67
                   metavar="TXN_ID")
6235 rajveer 68
 
6147 rajveer 69
    (options, args) = parser.parse_args()
70
    if len(args) != 0:
71
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
6254 rajveer 72
    DataService.initialize(db_hostname=options.hostname, echoOn=True)
73
 
6235 rajveer 74
    if options.refund:
75
        processRefunds()
8788 rajveer 76
    if options.recon:
77
        processRecon()
6235 rajveer 78
    if options.unknown:
79
        processUnknownTransactions()
6451 rajveer 80
    if options.authorized:
81
        processAuthorizedTransactions(options.txn_id)
7141 rajveer 82
    if options.collection:
7983 rajveer 83
        wallet = WalletForCompany.query.filter(WalletForCompany.id == 3).one()
84
        oldBalance = wallet.amount
85
        newBalance = getBalance()  
86
        wallet.amount = newBalance
87
        session.commit()
88
 
7141 rajveer 89
        d = datetime.datetime.now()
7144 rajveer 90
        d = d + timedelta(days = -1)
7141 rajveer 91
        compute_recharge_collection(d)
7983 rajveer 92
        compute_website_recharge_collection(d, oldBalance, newBalance)
7147 rajveer 93
    if options.topup:
94
        topup_company_wallet(1,100000)
6235 rajveer 95
 
8788 rajveer 96
def processRecon():
97
    cdate = datetime.datetime.now() + timedelta(days = -1)
98
    startTime = datetime.datetime(cdate.year, cdate.month, cdate.day)
99
    endTime = startTime + timedelta(days=1)
100
 
8795 rajveer 101
 
8788 rajveer 102
    '''
103
    A - All such orders for which we have attempted the recharge and recharge is either successful or unknown.
104
    B - All such orders for which we have attempted the recharge and we received the refund after this time window.
105
    C - All such orders for which we have received the refund in this time window, although the recharge was attempted before this window.
106
    X1 = A + B - C         Net amount debited for all the customers in this time window.
107
    X2 - Total amount credited to all customers in their wallet under some promotion.
108
    X3 - Net difference in wallet amount between this time window.
109
    X4 - Payment received through gateway from all customer in this time window.
110
    X5 - Payment refunded through gateway by all customer in this time window.
111
    '''
112
 
8790 rajveer 113
    A1 = 0
114
    B1 = 0
115
    C1 = 0
116
    A2 = 0
117
    B2 = 0
118
    C2 = 0
119
    R = 0
120
    P = 0
8788 rajveer 121
    X1 = 0
122
    X2 = 0
123
    X3 = 0
124
    X4 = 0
125
    X5 = 0
8790 rajveer 126
    X6 = 0
8788 rajveer 127
    D = 0
128
 
8790 rajveer 129
    sorder = session.query(func.sum(RechargeOrder.totalAmount), func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL])).filter(RechargeOrder.creationTimestamp.between(startTime,endTime)).first()    
8788 rajveer 130
    if sorder and sorder[0]:
8790 rajveer 131
        A1 = int(sorder[0])
132
        A2 = int(sorder[1])
8788 rajveer 133
 
8790 rajveer 134
    forder = session.query(func.sum(RechargeOrder.totalAmount), func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_FAILED, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.REFUNDED, RechargeOrderStatus.PARTIALLY_REFUNDED])).filter(RechargeOrder.creationTimestamp.between(startTime,endTime)).filter(not_(RechargeOrder.responseTimestamp.between(startTime,endTime))).first()
8788 rajveer 135
    if forder and forder[0]:
8790 rajveer 136
        B1 = int(forder[0])
137
        B2 = int(forder[1])
8788 rajveer 138
 
8790 rajveer 139
    rorder = session.query(func.sum(RechargeOrder.totalAmount), func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_FAILED, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.REFUNDED, RechargeOrderStatus.PARTIALLY_REFUNDED])).filter(RechargeOrder.responseTimestamp.between(startTime,endTime)).filter(not_(RechargeOrder.creationTimestamp.between(startTime,endTime))).first()
8788 rajveer 140
    if rorder and rorder[0]:
8790 rajveer 141
        C1 = int(rorder[0])
142
        C2 = int(rorder[1])
8788 rajveer 143
 
8790 rajveer 144
    R = R + A1 + B1 - C1
145
    X2 = X2 + A2 + B2 - C2
8788 rajveer 146
 
147
    rv = session.query(func.sum(RechargeVoucherTracker.amount)).filter(RechargeVoucherTracker.issuedOn.between(startTime,endTime)).first()
148
    if rv and rv[0]:
8790 rajveer 149
        X3 = int(rv[0])
8788 rajveer 150
 
151
    uw = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.timestamp.between(startTime,endTime)).first()
152
    if uw and uw[0]:
8790 rajveer 153
        X4 = int(uw[0])
8788 rajveer 154
 
8795 rajveer 155
    #X4 = 191497
8788 rajveer 156
 
157
    pc = PaymentClient().get_client()
158
    payments = pc.getPayments(to_java_date(startTime - datetime.timedelta(minutes = 30)), to_java_date(endTime + datetime.timedelta(minutes = 30)), 2, 1) + pc.getPayments(to_java_date(startTime - datetime.timedelta(minutes = 30)), to_java_date(endTime + datetime.timedelta(minutes = 30)), 2, 2) + pc.getPayments(to_java_date(startTime - datetime.timedelta(minutes = 30)), to_java_date(endTime + datetime.timedelta(minutes = 30)), 8, 1) + pc.getPayments(to_java_date(startTime - datetime.timedelta(minutes = 30)), to_java_date(endTime + datetime.timedelta(minutes = 30)), 8, 2)
159
    for payment in payments:
160
        if payment.isDigital and to_py_date(payment.successTimestamp) >= startTime and to_py_date(payment.successTimestamp) <= endTime:  
8790 rajveer 161
            X5 = X5 + payment.amount
8788 rajveer 162
 
163
 
164
 
165
    refunds = RechargeOrder.query.filter(RechargeOrder.status.in_([RechargeOrderStatus.PARTIALLY_REFUNDED, RechargeOrderStatus.REFUNDED])).filter(RechargeOrder.refundTimestamp.between(startTime, endTime)).all()
166
    pc = PaymentClient().get_client()
167
    for refund in refunds:
168
        payments = pc.getPaymentForRechargeTxnId(refund.transaction_id)
169
        for payment in payments:
170
            if payment.gatewayId in (1,2) and payment.status == 8 and payment.isDigital:
8790 rajveer 171
                X6 = X6 + payment.refundAmount
8788 rajveer 172
 
8790 rajveer 173
    P = X2+X3+X5-X4-X6
174
    D = R - P
8788 rajveer 175
 
176
    maildata = "<html><body><table border='1'><thead><th>Symbol</th><th>Type</th><th>Amount</th></thead><tbody>"
8790 rajveer 177
    maildata += "<tr><td>A</td><td>Recharge Amount</td><td>" + str(A1) + "</td></tr>"
178
    maildata += "<tr><td>B</td><td>Recharge Amount (Refunded in Future)</td><td>" + str(B1) + "</td></tr>"
179
    maildata += "<tr><td>C</td><td>Recharge Refund Amount</td><td>" + str(C1) + "</td></tr>"
180
    maildata += "<tr><td>R=A1+B1-C1</td><td>Net Recharge Amount</td><td>" + str(R) + "</td></tr>"
181
    maildata += "<tr><td></td><td></td><td></td></tr>"
182
 
183
    maildata += "<tr><td>A</td><td>Recharge Coupon Amount</td><td>" + str(A2) + "</td></tr>"
184
    maildata += "<tr><td>B</td><td>Recharge Coupon Amount (Refunded in Future)</td><td>" + str(B2) + "</td></tr>"
185
    maildata += "<tr><td>C</td><td>Recharge Coupon Refund Amount</td><td>" + str(C2) + "</td></tr>"    
186
    maildata += "<tr><td>X2=A2+B2-C2</td><td>Net Coupon Amount</td><td>" + str(X2) + "</td></tr>"
187
 
188
    maildata += "<tr><td>X3</td><td>Gift Amount</td><td>" + str(X3) + "</td></tr>"
189
    maildata += "<tr><td>X4</td><td>Wallet Difference</td><td>" + str(X4) + "</td></tr>"
190
    maildata += "<tr><td>X5</td><td>Payment Amount</td><td>" + str(X5) + "</td></tr>"
191
    maildata += "<tr><td>X6</td><td>Payment Refund Amount</td><td>" + str(X6) + "</td></tr>"
192
    maildata += "<tr><td>P=X2+X3+X5-X4-X6</td><td>Net Payments</td><td>" + str(P) + "</td></tr>"
193
    maildata += "<tr><td></td><td></td><td></td></tr>"
194
 
195
    maildata += "<tr><td>D=R-P</td><td>Net Reconciliation Difference</td><td>" + str(D) + "</td></tr>"
8788 rajveer 196
    maildata += "</tbody></table>"
197
 
198
    if D != 0:
8837 rajveer 199
        mismatches = []
200
        mismatches += RechargeOrder.query.filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL])).filter(RechargeOrder.creationTimestamp.between(startTime, endTime)).filter(RechargeOrder.responseTimestamp.between(endTime, endTime + timedelta(minutes = 10))).all()
201
        mismatches += RechargeOrder.query.filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL])).filter(RechargeOrder.responseTimestamp.between(startTime, endTime)).filter(RechargeOrder.creationTimestamp.between(startTime - timedelta(minutes = 10), startTime)).all()
8788 rajveer 202
        if mismatches and len(mismatches) > 0:
203
            maildata += "<h3>Possible mismatch orders</h3><table style='margin-top:30px;' border='1'><thead><th>OrderId</th><th>Total Amount</th><th>Wallet Amount</th><th>Coupon Amount</th><th>Creation Time</th><th>Response Time</th></thead><tbody>"
204
            for mismatch in mismatches:
205
                maildata += "<tr><td>" + str(mismatch.id) + "</td><td>" + str(mismatch.totalAmount) + "</td><td>" + str(mismatch.walletAmount) + "</td><td>" + str(mismatch.couponAmount) + "</td><td>" + str(mismatch.creationTimestamp) + "</td><td>" + str(mismatch.responseTimestamp) + "</td></tr>"        
206
            maildata += "</tbody></table>"
207
 
208
    maildata += "</body></html>"
8795 rajveer 209
    mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "rajneesh.arora@shop2020.in"], "Customer Recharge Reconciliation for Date:- " + startTime.strftime("%d-%m-%Y"), maildata, [])
8790 rajveer 210
 
8788 rajveer 211
 
6235 rajveer 212
def processRefunds():
213
    todate = datetime.datetime.now()
8788 rajveer 214
    for i in range(10):
6235 rajveer 215
        orderDate = todate + datetime.timedelta(days= -i)
216
        refunds = getRefunds(orderDate)
217
        for key in refunds.keys():
218
            refund = refunds.get(key)
219
            refundAmount = refund[0]
220
            refundDate = refund[1]
221
            order = RechargeOrder.get_by(spiceTID = key)
7127 rajveer 222
            if order:
223
                amount = order.totalAmount
224
                isStoreOrder = False
225
            else:
226
                order = RechargeTransaction.get_by(spiceTID = key)
7188 rajveer 227
                if not order:
228
                    continue
7127 rajveer 229
                isStoreOrder = True
230
                amount = order.amount
6235 rajveer 231
            if order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
232
                print "Refund is already processed."
233
                continue
7188 rajveer 234
            if order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
7075 rajveer 235
                print "Recharge/Payment is not successful. There is something wrong."
6235 rajveer 236
                continue
7127 rajveer 237
            if amount != refundAmount:
6235 rajveer 238
                print "Refund amount is not same as transaction amount"
239
                continue
7127 rajveer 240
            if isStoreOrder:
7244 rajveer 241
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7127 rajveer 242
            else:
7780 rajveer 243
                update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
6235 rajveer 244
 
245
def processUnknownTransactions():    
246
    orders = get_recharge_orders_for_status(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6219 rajveer 247
    for order in orders:
6276 rajveer 248
        try:
249
            if order.creationTimestamp + datetime.timedelta(minutes=10) < datetime.datetime.now():
250
                status, description = checkTransactionStatus('', str(order.id))
251
                print status, description
252
                if status:
253
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
254
                else:
255
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
256
        except:
257
            print "Do Nothing"
6451 rajveer 258
 
7163 rajveer 259
    ## For store transactions
7245 rajveer 260
    rorders = RechargeTransaction.query.filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_UNKNOWN, RechargeOrderStatus.INIT])).all()
7166 rajveer 261
    for order in rorders:
7163 rajveer 262
        try:
263
            if order.transactionTime + datetime.timedelta(minutes=10) < datetime.datetime.now():
264
                status, description = checkTransactionStatus('', str(order.id))
265
                print status, description
266
                if status:
267
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
7245 rajveer 268
                elif order.status == RechargeOrderStatus.INIT:
269
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
7163 rajveer 270
                else:
7244 rajveer 271
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7163 rajveer 272
        except:
273
            print "Do Nothing"
274
 
275
 
6451 rajveer 276
def processAuthorizedTransactions(txn_id):
277
    update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6235 rajveer 278
 
7141 rajveer 279
 
280
def compute_recharge_collection(cdate):
281
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
282
    tomorrow = todate + timedelta(days=1)
8868 rajveer 283
 
284
    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_UNKNOWN])).filter(RechargeTransaction.transactionTime.between(todate, tomorrow)).group_by(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status).order_by(RechargeTransaction.storeId).all()
285
    txns += session.query(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status, func.sum(RechargeTransaction.amount), func.sum(RechargeTransaction.discount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_FAILED, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED])).filter(RechargeTransaction.transactionTime.between(todate, tomorrow)).filter(not_(RechargeTransaction.responseTime.between(todate, tomorrow)).group_by(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status).order_by(RechargeTransaction.storeId).all()
7141 rajveer 286
    storeData = {}
287
    for txn in txns:
288
        print txn
289
        if not storeData.has_key(txn[0]):
290
            data = [0,0,0,0,0]
291
            storeData[txn[0]] = data
292
        else:
293
            data = storeData[txn[0]]
7155 rajveer 294
        if txn[1] == 1:
7141 rajveer 295
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 296
        if txn[1] == 2:
7141 rajveer 297
            data[1] += int(txn[3]) - int(txn[4])
8868 rajveer 298
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
7141 rajveer 299
            data[2] += int(txn[3])
300
            data[3] += int(txn[4])
301
            data[4] += int(txn[3]) - int(txn[4])
302
        storeData[txn[0]] = data
8868 rajveer 303
 
304
 
305
    reftxns = session.query(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status, func.sum(RechargeTransaction.amount), func.sum(RechargeTransaction.discount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_FAILED, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED])).filter(RechargeTransaction.responseTime.between(todate, tomorrow)).filter(not_(RechargeTransaction.transactionTime.between(todate, tomorrow)).group_by(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status).order_by(RechargeTransaction.storeId).all()
7141 rajveer 306
    for txn in reftxns:
307
        print txn
308
        if not storeData.has_key(txn[0]):
309
            data = [0,0,0,0,0]
310
            storeData[txn[0]] = data
311
        else:
312
            data = storeData[txn[0]]
7155 rajveer 313
        if txn[1] == 1:
7148 rajveer 314
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 315
        if txn[1] == 2:
7148 rajveer 316
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 317
        data[2] -= int(txn[3])
318
        data[3] -= int(txn[4])
319
        data[4] -= int(txn[3]) - int(txn[4])
320
    print storeData
7163 rajveer 321
 
7175 rajveer 322
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
323
 
324
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
325
 
7511 rajveer 326
#    if int(dt[0]) != wallet.amount:
327
#        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])) , "", [], [], [])    
7250 rajveer 328
 
7175 rajveer 329
    maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"
330
    trecharge = 0
7967 anupam.sin 331
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
332
    hotspotServiceMatrixMap = {}
333
 
334
    for hotspotServiceMatrix in hotspotServiceMatrices:
335
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
336
 
7141 rajveer 337
    for storeId in storeData.keys():
338
        store = HotspotStore.get_by(id = storeId)
7967 anupam.sin 339
        if hotspotServiceMatrixMap.has_key(storeId):
340
            del hotspotServiceMatrixMap[storeId]
7141 rajveer 341
        store.collectedAmount = 0
342
        store.availableLimit = store.creditLimit
7142 rajveer 343
        session.commit()
344
 
7141 rajveer 345
        data = storeData.get(storeId)
7250 rajveer 346
        rc = RechargeCollection()
347
        rc.hotspotId = store.hotspotId
348
        rc.reconDate = int(todate.strftime("%Y%m%d"))
349
        rc.cash = data[0]
350
        rc.hdfc = data[1]
351
        rc.grossAmount = data[2]
352
        rc.discount = data[3]
353
        rc.netCollection = data[4]
354
        rc.addedAt = datetime.datetime.now()
355
        rc.pushedToOcr = False
356
        session.commit()
357
 
7175 rajveer 358
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
359
        trecharge +=  data[2]
7250 rajveer 360
 
7276 rajveer 361
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 362
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 363
    wamt = int(dit2[0])- int(dit[0])
364
    wallet.amount = wamt
365
    session.commit()
366
 
7250 rajveer 367
    maildata += "</tbody></table></body></html>"
7821 rajveer 368
    mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "Ashwani.Kumar@spiceretail.co.in","parveen.mittal@spiceretail.co.in","pardeep.panwar@spiceretail.co.in","gagan.sharma@spiceretail.co.in","j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in", "amit.tyagi@spiceretail.co.in"], "MIS :- SpiceRetail  (Date - " + todate.strftime("%d-%m-%Y") + ")   (Wallet Amount - " + str(wallet.amount) + ")    (Total Recharge - " + str(trecharge) + ")", maildata, []) 
7252 rajveer 369
    try:
370
        push_recharge_collection_to_ocr()
371
    except:
372
        mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "rajneesh.arora@shop2020.in"], "Problem while pushing recharge collection to OCR", "", [])
7967 anupam.sin 373
    finally:
7986 anupam.sin 374
        msg = "<html><body>"
7967 anupam.sin 375
        for storeId in hotspotServiceMatrixMap.keys():
376
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
377
                store = HotspotStore.get_by(id = storeId)
7986 anupam.sin 378
                msg = msg + str(store.hotspotId) + ' - ' + str(store.email) + '<br>'
379
        msg = msg + '</body></html>'
380
        helper_client = HelperClient().get_client()
8020 rajveer 381
        helper_client.saveUserEmailForSending(["gagan.sharma@spiceretail.co.in"], "cnc.center@shop2020.in", "No Recharge happened for these stores on " + str(date.today()-timedelta(days=1)), msg, "NRM", "NoRechargeMail", ["anupam.singh@shop2020.in"], ["anupam.singh@shop2020.in"], 1)
7986 anupam.sin 382
 
7967 anupam.sin 383
 
7250 rajveer 384
 
385
def push_recharge_collection_to_ocr():
386
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
387
 
388
    for rc in rcs:
389
        store_string = "<Store>" + rc.hotspotId + "</Store>"
390
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
391
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
392
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
393
        type_string = "<Type>RechargeSale</Type>"
394
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
395
 
7141 rajveer 396
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
397
 
7253 rajveer 398
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 399
        XML="""
400
        <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/">
401
          <soap:Body>
402
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
403
        """
404
 
8195 rajveer 405
        XML = XML + store_string + date_string + cash_string + card_string + "<Cheque>0</Cheque>" + type_string + amount_string 
7141 rajveer 406
 
407
        footer = """
408
            </SaholicRechargeSaleTransfer>
409
          </soap:Body>
410
        </soap:Envelope>
411
        """
412
        XML = XML + footer
413
 
414
        print XML
415
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
416
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
417
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
418
        conn.send(XML)
419
        response = conn.getresponse()
420
        print response.status, response.reason
421
        resp = response.read()
422
        conn.close()
423
        print resp
7250 rajveer 424
        if "Saved Successfully" in resp:
425
            rc.pushedAt = datetime.datetime.now()
426
            rc.pushedToOcr = True
427
            session.commit()
428
        elif "Error in Saving Data" in resp:
7252 rajveer 429
            mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "rajneesh.arora@shop2020.in"], "Problem while pushing recharge collection to OCR", resp, [])
7250 rajveer 430
        else: 
7252 rajveer 431
            mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "rajneesh.arora@shop2020.in"], "Problem while pushing recharge collection to OCR", resp, [])
7250 rajveer 432
 
7141 rajveer 433
 
7175 rajveer 434
 
7147 rajveer 435
def topup_company_wallet(companyId, amount):
436
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 437
    company = Company.get_by(id = companyId)
7147 rajveer 438
    wh = WalletHistoryForCompany()
439
    wh.walletId = wallet.id
440
    wh.openingBal = wallet.amount
441
    wh.closingBal = wallet.amount +  amount
442
    wh.amount = amount
443
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 444
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 445
    wh.description = "Wallet Credited"
446
 
447
    wallet.amount += amount
448
    session.commit()
7285 rajveer 449
    mail("cnc.center@shop2020.in", "5h0p2o2o", ["rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "Ashwani.Kumar@spiceretail.co.in","parveen.mittal@spiceretail.co.in","pardeep.panwar@spiceretail.co.in","gagan.sharma@spiceretail.co.in","j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in", "amit.tyagi@spiceretail.co.in"] , company.name + " wallet topped up by " +  str(amount) + " rupees.", "", [], [], [])
7821 rajveer 450
 
7983 rajveer 451
def compute_website_recharge_collection(cdate, oldBalance, newBalance):
8815 rajveer 452
    startTime = datetime.datetime(cdate.year, cdate.month, cdate.day)
453
    endTime = startTime + timedelta(days=1)
454
    tamount = 0
7147 rajveer 455
 
8815 rajveer 456
    txns = session.query(func.sum(RechargeOrder.totalAmount), func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL])).filter(RechargeOrder.creationTimestamp.between(startTime,endTime)).first()    
457
    if txns and txns[0]:
458
        tamount += int(txns[0])
7821 rajveer 459
 
8815 rajveer 460
    otxns = session.query(func.sum(RechargeOrder.totalAmount), func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_FAILED, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.REFUNDED, RechargeOrderStatus.PARTIALLY_REFUNDED])).filter(RechargeOrder.creationTimestamp.between(startTime,endTime)).filter(not_(RechargeOrder.responseTimestamp.between(startTime,endTime))).first()
461
    if otxns and otxns[0]:
462
        tamount += int(otxns[0])
463
 
464
    reftxns = session.query(func.sum(RechargeOrder.totalAmount), func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_FAILED, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.REFUNDED, RechargeOrderStatus.PARTIALLY_REFUNDED])).filter(RechargeOrder.responseTimestamp.between(startTime,endTime)).filter(not_(RechargeOrder.creationTimestamp.between(startTime,endTime))).first()
465
    if reftxns and reftxns[0]:
466
        tamount -= int(reftxns[0])
7821 rajveer 467
 
468
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()
7823 rajveer 469
 
470
 
471
    d = datetime.datetime.now()
472
    wh = WalletHistoryForCompany()
473
    wh.walletId = wallet.id
474
    wh.openingBal = wallet.amount
475
    wh.closingBal = wallet.amount - tamount
7982 rajveer 476
    wh.amount = -tamount
7823 rajveer 477
    wh.transactionTime = d
478
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
479
    wh.description = "Wallet Credited"
480
    wallet.amount = wallet.amount - tamount
7821 rajveer 481
    session.commit()
482
 
7823 rajveer 483
 
8007 rajveer 484
    maildata = ""
8815 rajveer 485
    mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["pardeep.panwar@spiceretail.co.in>", "amit.tyagi@spiceretail.co.in", "rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in"], "MIS :- Saholic (Date - " + startTime.strftime("%d-%m-%Y") + ")   (Wallet Amount - " + str(wallet.amount) + ")    (Total Recharge - " + str(tamount) + ")", maildata, []) 
7821 rajveer 486
 
8012 rajveer 487
    rAmount = 0
8815 rajveer 488
    ramount = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.transactionTime >= startTime).filter(WalletHistoryForCompany.amount >= 100000).one()
8012 rajveer 489
    if ramount[0]:
490
        rAmount = int(ramount[0])
8815 rajveer 491
    rcs = session.query(func.sum(RechargeCollection.grossAmount)).filter(RechargeCollection.reconDate == int(startTime.strftime("%Y%m%d"))).one()
8007 rajveer 492
    hamount = int(rcs[0])
493
 
8012 rajveer 494
    maildata = "(A) Old Wallet Amount is : " + str(oldBalance) + "<br>(B) New Wallet Amount is : " + str(newBalance) + "<br>(C) Recharge Amount is : " + str(rAmount) + "<br>---------------------------<br>(D) Total Debit Amount for Recharge(A-B+C) is : " + str(oldBalance - newBalance + rAmount) + "<br><br><br>(E) Saholic Recharge Amount is :" + str(tamount) + "<br>(F) Hotspot Recharge Amount is :" + str(hamount) + "<br>---------------------------<br>(G) Total Recharge Amount (E+F) is : " + str(tamount + hamount)
8815 rajveer 495
    mail_html("cnc.center@shop2020.in", "5h0p2o2o", ["pardeep.panwar@spiceretail.co.in>", "amit.tyagi@spiceretail.co.in", "rajveer.singh@shop2020.in", "anupam.singh@shop2020.in", "j.p.gupta@shop2020.in", "rajneesh.arora@shop2020.in"], "MIS :- Wallet and Recharge (Date - " + startTime.strftime("%d-%m-%Y") + ")", maildata, [])
8007 rajveer 496
 
497
 
6147 rajveer 498
if __name__ == '__main__':
7967 anupam.sin 499
    main()
500