Subversion Repositories SmartDukaan

Rev

Rev 8868 | Rev 9052 | 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
    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()
8875 rajveer 284
    txns = 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 285
    storeData = {}
286
    for txn in txns:
287
        print txn
288
        if not storeData.has_key(txn[0]):
289
            data = [0,0,0,0,0]
290
            storeData[txn[0]] = data
291
        else:
292
            data = storeData[txn[0]]
7155 rajveer 293
        if txn[1] == 1:
7141 rajveer 294
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 295
        if txn[1] == 2:
7141 rajveer 296
            data[1] += int(txn[3]) - int(txn[4])
8868 rajveer 297
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
7141 rajveer 298
            data[2] += int(txn[3])
299
            data[3] += int(txn[4])
300
            data[4] += int(txn[3]) - int(txn[4])
301
        storeData[txn[0]] = data
8868 rajveer 302
 
303
 
8875 rajveer 304
    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 305
    for txn in reftxns:
306
        print txn
307
        if not storeData.has_key(txn[0]):
308
            data = [0,0,0,0,0]
309
            storeData[txn[0]] = data
310
        else:
311
            data = storeData[txn[0]]
7155 rajveer 312
        if txn[1] == 1:
7148 rajveer 313
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 314
        if txn[1] == 2:
7148 rajveer 315
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 316
        data[2] -= int(txn[3])
317
        data[3] -= int(txn[4])
318
        data[4] -= int(txn[3]) - int(txn[4])
319
    print storeData
7163 rajveer 320
 
7175 rajveer 321
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
322
 
323
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
324
 
7511 rajveer 325
#    if int(dt[0]) != wallet.amount:
326
#        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 327
 
7175 rajveer 328
    maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"
329
    trecharge = 0
7967 anupam.sin 330
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
331
    hotspotServiceMatrixMap = {}
332
 
333
    for hotspotServiceMatrix in hotspotServiceMatrices:
334
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
335
 
7141 rajveer 336
    for storeId in storeData.keys():
337
        store = HotspotStore.get_by(id = storeId)
7967 anupam.sin 338
        if hotspotServiceMatrixMap.has_key(storeId):
339
            del hotspotServiceMatrixMap[storeId]
7141 rajveer 340
        store.collectedAmount = 0
341
        store.availableLimit = store.creditLimit
7142 rajveer 342
        session.commit()
343
 
7141 rajveer 344
        data = storeData.get(storeId)
7250 rajveer 345
        rc = RechargeCollection()
346
        rc.hotspotId = store.hotspotId
347
        rc.reconDate = int(todate.strftime("%Y%m%d"))
348
        rc.cash = data[0]
349
        rc.hdfc = data[1]
350
        rc.grossAmount = data[2]
351
        rc.discount = data[3]
352
        rc.netCollection = data[4]
353
        rc.addedAt = datetime.datetime.now()
354
        rc.pushedToOcr = False
355
        session.commit()
356
 
7175 rajveer 357
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
358
        trecharge +=  data[2]
7250 rajveer 359
 
7276 rajveer 360
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 361
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 362
    wamt = int(dit2[0])- int(dit[0])
363
    wallet.amount = wamt
364
    session.commit()
365
 
7250 rajveer 366
    maildata += "</tbody></table></body></html>"
7821 rajveer 367
    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 368
    try:
369
        push_recharge_collection_to_ocr()
370
    except:
371
        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 372
    finally:
7986 anupam.sin 373
        msg = "<html><body>"
7967 anupam.sin 374
        for storeId in hotspotServiceMatrixMap.keys():
375
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
376
                store = HotspotStore.get_by(id = storeId)
7986 anupam.sin 377
                msg = msg + str(store.hotspotId) + ' - ' + str(store.email) + '<br>'
378
        msg = msg + '</body></html>'
379
        helper_client = HelperClient().get_client()
8020 rajveer 380
        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 381
 
7967 anupam.sin 382
 
7250 rajveer 383
 
384
def push_recharge_collection_to_ocr():
385
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
386
 
387
    for rc in rcs:
388
        store_string = "<Store>" + rc.hotspotId + "</Store>"
389
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
390
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
391
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
392
        type_string = "<Type>RechargeSale</Type>"
393
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
394
 
7141 rajveer 395
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
396
 
7253 rajveer 397
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 398
        XML="""
399
        <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/">
400
          <soap:Body>
401
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
402
        """
403
 
8195 rajveer 404
        XML = XML + store_string + date_string + cash_string + card_string + "<Cheque>0</Cheque>" + type_string + amount_string 
7141 rajveer 405
 
406
        footer = """
407
            </SaholicRechargeSaleTransfer>
408
          </soap:Body>
409
        </soap:Envelope>
410
        """
411
        XML = XML + footer
412
 
413
        print XML
414
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
415
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
416
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
417
        conn.send(XML)
418
        response = conn.getresponse()
419
        print response.status, response.reason
420
        resp = response.read()
421
        conn.close()
422
        print resp
7250 rajveer 423
        if "Saved Successfully" in resp:
424
            rc.pushedAt = datetime.datetime.now()
425
            rc.pushedToOcr = True
426
            session.commit()
427
        elif "Error in Saving Data" in resp:
7252 rajveer 428
            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 429
        else: 
7252 rajveer 430
            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 431
 
7141 rajveer 432
 
7175 rajveer 433
 
7147 rajveer 434
def topup_company_wallet(companyId, amount):
435
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 436
    company = Company.get_by(id = companyId)
7147 rajveer 437
    wh = WalletHistoryForCompany()
438
    wh.walletId = wallet.id
439
    wh.openingBal = wallet.amount
440
    wh.closingBal = wallet.amount +  amount
441
    wh.amount = amount
442
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 443
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 444
    wh.description = "Wallet Credited"
445
 
446
    wallet.amount += amount
447
    session.commit()
7285 rajveer 448
    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 449
 
7983 rajveer 450
def compute_website_recharge_collection(cdate, oldBalance, newBalance):
8815 rajveer 451
    startTime = datetime.datetime(cdate.year, cdate.month, cdate.day)
452
    endTime = startTime + timedelta(days=1)
453
    tamount = 0
7147 rajveer 454
 
8815 rajveer 455
    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()    
456
    if txns and txns[0]:
457
        tamount += int(txns[0])
7821 rajveer 458
 
8815 rajveer 459
    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()
460
    if otxns and otxns[0]:
461
        tamount += int(otxns[0])
462
 
463
    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()
464
    if reftxns and reftxns[0]:
465
        tamount -= int(reftxns[0])
7821 rajveer 466
 
467
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()
7823 rajveer 468
 
469
 
470
    d = datetime.datetime.now()
471
    wh = WalletHistoryForCompany()
472
    wh.walletId = wallet.id
473
    wh.openingBal = wallet.amount
474
    wh.closingBal = wallet.amount - tamount
7982 rajveer 475
    wh.amount = -tamount
7823 rajveer 476
    wh.transactionTime = d
477
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
478
    wh.description = "Wallet Credited"
479
    wallet.amount = wallet.amount - tamount
7821 rajveer 480
    session.commit()
481
 
7823 rajveer 482
 
8007 rajveer 483
    maildata = ""
8815 rajveer 484
    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 485
 
8012 rajveer 486
    rAmount = 0
8815 rajveer 487
    ramount = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.transactionTime >= startTime).filter(WalletHistoryForCompany.amount >= 100000).one()
8012 rajveer 488
    if ramount[0]:
489
        rAmount = int(ramount[0])
8815 rajveer 490
    rcs = session.query(func.sum(RechargeCollection.grossAmount)).filter(RechargeCollection.reconDate == int(startTime.strftime("%Y%m%d"))).one()
8007 rajveer 491
    hamount = int(rcs[0])
492
 
8012 rajveer 493
    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 494
    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 495
 
496
 
6147 rajveer 497
if __name__ == '__main__':
7967 anupam.sin 498
    main()
499