Subversion Repositories SmartDukaan

Rev

Rev 8795 | Rev 8837 | 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:
199
        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()
200
        if mismatches and len(mismatches) > 0:
201
            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>"
202
            for mismatch in mismatches:
203
                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>"        
204
            maildata += "</tbody></table>"
205
 
206
    maildata += "</body></html>"
8795 rajveer 207
    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 208
 
8788 rajveer 209
 
6235 rajveer 210
def processRefunds():
211
    todate = datetime.datetime.now()
8788 rajveer 212
    for i in range(10):
6235 rajveer 213
        orderDate = todate + datetime.timedelta(days= -i)
214
        refunds = getRefunds(orderDate)
215
        for key in refunds.keys():
216
            refund = refunds.get(key)
217
            refundAmount = refund[0]
218
            refundDate = refund[1]
219
            order = RechargeOrder.get_by(spiceTID = key)
7127 rajveer 220
            if order:
221
                amount = order.totalAmount
222
                isStoreOrder = False
223
            else:
224
                order = RechargeTransaction.get_by(spiceTID = key)
7188 rajveer 225
                if not order:
226
                    continue
7127 rajveer 227
                isStoreOrder = True
228
                amount = order.amount
6235 rajveer 229
            if order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
230
                print "Refund is already processed."
231
                continue
7188 rajveer 232
            if order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
7075 rajveer 233
                print "Recharge/Payment is not successful. There is something wrong."
6235 rajveer 234
                continue
7127 rajveer 235
            if amount != refundAmount:
6235 rajveer 236
                print "Refund amount is not same as transaction amount"
237
                continue
7127 rajveer 238
            if isStoreOrder:
7244 rajveer 239
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7127 rajveer 240
            else:
7780 rajveer 241
                update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
6235 rajveer 242
 
243
def processUnknownTransactions():    
244
    orders = get_recharge_orders_for_status(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6219 rajveer 245
    for order in orders:
6276 rajveer 246
        try:
247
            if order.creationTimestamp + datetime.timedelta(minutes=10) < datetime.datetime.now():
248
                status, description = checkTransactionStatus('', str(order.id))
249
                print status, description
250
                if status:
251
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
252
                else:
253
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
254
        except:
255
            print "Do Nothing"
6451 rajveer 256
 
7163 rajveer 257
    ## For store transactions
7245 rajveer 258
    rorders = RechargeTransaction.query.filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_UNKNOWN, RechargeOrderStatus.INIT])).all()
7166 rajveer 259
    for order in rorders:
7163 rajveer 260
        try:
261
            if order.transactionTime + datetime.timedelta(minutes=10) < datetime.datetime.now():
262
                status, description = checkTransactionStatus('', str(order.id))
263
                print status, description
264
                if status:
265
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
7245 rajveer 266
                elif order.status == RechargeOrderStatus.INIT:
267
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
7163 rajveer 268
                else:
7244 rajveer 269
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7163 rajveer 270
        except:
271
            print "Do Nothing"
272
 
273
 
6451 rajveer 274
def processAuthorizedTransactions(txn_id):
275
    update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6235 rajveer 276
 
7141 rajveer 277
 
278
def compute_recharge_collection(cdate):
279
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
280
    tomorrow = todate + timedelta(days=1)
7244 rajveer 281
    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, RechargeOrderStatus.RECHARGE_UNKNOWN])).filter(RechargeTransaction.transactionTime >= todate).filter(RechargeTransaction.transactionTime < tomorrow).group_by(RechargeTransaction.storeId, RechargeTransaction.payMethod, RechargeTransaction.status).order_by(RechargeTransaction.storeId).all()
7141 rajveer 282
    storeData = {}
283
    for txn in txns:
284
        print txn
285
        if not storeData.has_key(txn[0]):
286
            data = [0,0,0,0,0]
287
            storeData[txn[0]] = data
288
        else:
289
            data = storeData[txn[0]]
7155 rajveer 290
        if txn[1] == 1:
7141 rajveer 291
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 292
        if txn[1] == 2:
7141 rajveer 293
            data[1] += int(txn[3]) - int(txn[4])
7244 rajveer 294
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_UNKNOWN):
7141 rajveer 295
            data[2] += int(txn[3])
296
            data[3] += int(txn[4])
297
            data[4] += int(txn[3]) - int(txn[4])
298
        storeData[txn[0]] = data
299
 
300
    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()  
301
    for txn in reftxns:
302
        print txn
303
        if not storeData.has_key(txn[0]):
304
            data = [0,0,0,0,0]
305
            storeData[txn[0]] = data
306
        else:
307
            data = storeData[txn[0]]
7155 rajveer 308
        if txn[1] == 1:
7148 rajveer 309
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 310
        if txn[1] == 2:
7148 rajveer 311
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 312
        data[2] -= int(txn[3])
313
        data[3] -= int(txn[4])
314
        data[4] -= int(txn[3]) - int(txn[4])
315
    print storeData
7163 rajveer 316
 
7175 rajveer 317
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
318
 
319
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
320
 
7511 rajveer 321
#    if int(dt[0]) != wallet.amount:
322
#        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 323
 
7175 rajveer 324
    maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"
325
    trecharge = 0
7967 anupam.sin 326
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
327
    hotspotServiceMatrixMap = {}
328
 
329
    for hotspotServiceMatrix in hotspotServiceMatrices:
330
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
331
 
7141 rajveer 332
    for storeId in storeData.keys():
333
        store = HotspotStore.get_by(id = storeId)
7967 anupam.sin 334
        if hotspotServiceMatrixMap.has_key(storeId):
335
            del hotspotServiceMatrixMap[storeId]
7141 rajveer 336
        store.collectedAmount = 0
337
        store.availableLimit = store.creditLimit
7142 rajveer 338
        session.commit()
339
 
7141 rajveer 340
        data = storeData.get(storeId)
7250 rajveer 341
        rc = RechargeCollection()
342
        rc.hotspotId = store.hotspotId
343
        rc.reconDate = int(todate.strftime("%Y%m%d"))
344
        rc.cash = data[0]
345
        rc.hdfc = data[1]
346
        rc.grossAmount = data[2]
347
        rc.discount = data[3]
348
        rc.netCollection = data[4]
349
        rc.addedAt = datetime.datetime.now()
350
        rc.pushedToOcr = False
351
        session.commit()
352
 
7175 rajveer 353
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
354
        trecharge +=  data[2]
7250 rajveer 355
 
7276 rajveer 356
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 357
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 358
    wamt = int(dit2[0])- int(dit[0])
359
    wallet.amount = wamt
360
    session.commit()
361
 
7250 rajveer 362
    maildata += "</tbody></table></body></html>"
7821 rajveer 363
    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 364
    try:
365
        push_recharge_collection_to_ocr()
366
    except:
367
        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 368
    finally:
7986 anupam.sin 369
        msg = "<html><body>"
7967 anupam.sin 370
        for storeId in hotspotServiceMatrixMap.keys():
371
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
372
                store = HotspotStore.get_by(id = storeId)
7986 anupam.sin 373
                msg = msg + str(store.hotspotId) + ' - ' + str(store.email) + '<br>'
374
        msg = msg + '</body></html>'
375
        helper_client = HelperClient().get_client()
8020 rajveer 376
        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 377
 
7967 anupam.sin 378
 
7250 rajveer 379
 
380
def push_recharge_collection_to_ocr():
381
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
382
 
383
    for rc in rcs:
384
        store_string = "<Store>" + rc.hotspotId + "</Store>"
385
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
386
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
387
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
388
        type_string = "<Type>RechargeSale</Type>"
389
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
390
 
7141 rajveer 391
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
392
 
7253 rajveer 393
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 394
        XML="""
395
        <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/">
396
          <soap:Body>
397
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
398
        """
399
 
8195 rajveer 400
        XML = XML + store_string + date_string + cash_string + card_string + "<Cheque>0</Cheque>" + type_string + amount_string 
7141 rajveer 401
 
402
        footer = """
403
            </SaholicRechargeSaleTransfer>
404
          </soap:Body>
405
        </soap:Envelope>
406
        """
407
        XML = XML + footer
408
 
409
        print XML
410
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
411
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
412
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
413
        conn.send(XML)
414
        response = conn.getresponse()
415
        print response.status, response.reason
416
        resp = response.read()
417
        conn.close()
418
        print resp
7250 rajveer 419
        if "Saved Successfully" in resp:
420
            rc.pushedAt = datetime.datetime.now()
421
            rc.pushedToOcr = True
422
            session.commit()
423
        elif "Error in Saving Data" in resp:
7252 rajveer 424
            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 425
        else: 
7252 rajveer 426
            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 427
 
7141 rajveer 428
 
7175 rajveer 429
 
7147 rajveer 430
def topup_company_wallet(companyId, amount):
431
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 432
    company = Company.get_by(id = companyId)
7147 rajveer 433
    wh = WalletHistoryForCompany()
434
    wh.walletId = wallet.id
435
    wh.openingBal = wallet.amount
436
    wh.closingBal = wallet.amount +  amount
437
    wh.amount = amount
438
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 439
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 440
    wh.description = "Wallet Credited"
441
 
442
    wallet.amount += amount
443
    session.commit()
7285 rajveer 444
    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 445
 
7983 rajveer 446
def compute_website_recharge_collection(cdate, oldBalance, newBalance):
8815 rajveer 447
    startTime = datetime.datetime(cdate.year, cdate.month, cdate.day)
448
    endTime = startTime + timedelta(days=1)
449
    tamount = 0
7147 rajveer 450
 
8815 rajveer 451
    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()    
452
    if txns and txns[0]:
453
        tamount += int(txns[0])
7821 rajveer 454
 
8815 rajveer 455
    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()
456
    if otxns and otxns[0]:
457
        tamount += int(otxns[0])
458
 
459
    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()
460
    if reftxns and reftxns[0]:
461
        tamount -= int(reftxns[0])
7821 rajveer 462
 
463
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()
7823 rajveer 464
 
465
 
466
    d = datetime.datetime.now()
467
    wh = WalletHistoryForCompany()
468
    wh.walletId = wallet.id
469
    wh.openingBal = wallet.amount
470
    wh.closingBal = wallet.amount - tamount
7982 rajveer 471
    wh.amount = -tamount
7823 rajveer 472
    wh.transactionTime = d
473
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
474
    wh.description = "Wallet Credited"
475
    wallet.amount = wallet.amount - tamount
7821 rajveer 476
    session.commit()
477
 
7823 rajveer 478
 
8007 rajveer 479
    maildata = ""
8815 rajveer 480
    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 481
 
8012 rajveer 482
    rAmount = 0
8815 rajveer 483
    ramount = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.transactionTime >= startTime).filter(WalletHistoryForCompany.amount >= 100000).one()
8012 rajveer 484
    if ramount[0]:
485
        rAmount = int(ramount[0])
8815 rajveer 486
    rcs = session.query(func.sum(RechargeCollection.grossAmount)).filter(RechargeCollection.reconDate == int(startTime.strftime("%Y%m%d"))).one()
8007 rajveer 487
    hamount = int(rcs[0])
488
 
8012 rajveer 489
    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 490
    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 491
 
492
 
6147 rajveer 493
if __name__ == '__main__':
7967 anupam.sin 494
    main()
495