Subversion Repositories SmartDukaan

Rev

Rev 8790 | Rev 8815 | 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
    startTime = datetime.datetime.strptime('2012-10-10 00:00:00', "%Y-%m-%d %H:%M:%S");
102
    endTime = datetime.datetime.strptime('2013-11-13 17:43:43', "%Y-%m-%d %H:%M:%S");
103
 
8788 rajveer 104
    '''
105
    A - All such orders for which we have attempted the recharge and recharge is either successful or unknown.
106
    B - All such orders for which we have attempted the recharge and we received the refund after this time window.
107
    C - All such orders for which we have received the refund in this time window, although the recharge was attempted before this window.
108
    X1 = A + B - C         Net amount debited for all the customers in this time window.
109
    X2 - Total amount credited to all customers in their wallet under some promotion.
110
    X3 - Net difference in wallet amount between this time window.
111
    X4 - Payment received through gateway from all customer in this time window.
112
    X5 - Payment refunded through gateway by all customer in this time window.
113
    '''
114
 
8790 rajveer 115
    A1 = 0
116
    B1 = 0
117
    C1 = 0
118
    A2 = 0
119
    B2 = 0
120
    C2 = 0
121
    R = 0
122
    P = 0
8788 rajveer 123
    X1 = 0
124
    X2 = 0
125
    X3 = 0
126
    X4 = 0
127
    X5 = 0
8790 rajveer 128
    X6 = 0
8788 rajveer 129
    D = 0
130
 
8790 rajveer 131
    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 132
    if sorder and sorder[0]:
8790 rajveer 133
        A1 = int(sorder[0])
134
        A2 = int(sorder[1])
8788 rajveer 135
 
8790 rajveer 136
    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 137
    if forder and forder[0]:
8790 rajveer 138
        B1 = int(forder[0])
139
        B2 = int(forder[1])
8788 rajveer 140
 
8790 rajveer 141
    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 142
    if rorder and rorder[0]:
8790 rajveer 143
        C1 = int(rorder[0])
144
        C2 = int(rorder[1])
8788 rajveer 145
 
8790 rajveer 146
    R = R + A1 + B1 - C1
147
    X2 = X2 + A2 + B2 - C2
8788 rajveer 148
 
149
    rv = session.query(func.sum(RechargeVoucherTracker.amount)).filter(RechargeVoucherTracker.issuedOn.between(startTime,endTime)).first()
150
    if rv and rv[0]:
8790 rajveer 151
        X3 = int(rv[0])
8788 rajveer 152
 
153
    uw = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.timestamp.between(startTime,endTime)).first()
154
    if uw and uw[0]:
8790 rajveer 155
        X4 = int(uw[0])
8788 rajveer 156
 
8795 rajveer 157
    #X4 = 191497
8788 rajveer 158
 
159
    pc = PaymentClient().get_client()
160
    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)
161
    for payment in payments:
162
        if payment.isDigital and to_py_date(payment.successTimestamp) >= startTime and to_py_date(payment.successTimestamp) <= endTime:  
8790 rajveer 163
            X5 = X5 + payment.amount
8788 rajveer 164
 
165
 
166
 
167
    refunds = RechargeOrder.query.filter(RechargeOrder.status.in_([RechargeOrderStatus.PARTIALLY_REFUNDED, RechargeOrderStatus.REFUNDED])).filter(RechargeOrder.refundTimestamp.between(startTime, endTime)).all()
168
    pc = PaymentClient().get_client()
169
    for refund in refunds:
170
        payments = pc.getPaymentForRechargeTxnId(refund.transaction_id)
171
        for payment in payments:
172
            if payment.gatewayId in (1,2) and payment.status == 8 and payment.isDigital:
8790 rajveer 173
                X6 = X6 + payment.refundAmount
8788 rajveer 174
 
8790 rajveer 175
    P = X2+X3+X5-X4-X6
176
    D = R - P
8788 rajveer 177
 
178
    maildata = "<html><body><table border='1'><thead><th>Symbol</th><th>Type</th><th>Amount</th></thead><tbody>"
8790 rajveer 179
    maildata += "<tr><td>A</td><td>Recharge Amount</td><td>" + str(A1) + "</td></tr>"
180
    maildata += "<tr><td>B</td><td>Recharge Amount (Refunded in Future)</td><td>" + str(B1) + "</td></tr>"
181
    maildata += "<tr><td>C</td><td>Recharge Refund Amount</td><td>" + str(C1) + "</td></tr>"
182
    maildata += "<tr><td>R=A1+B1-C1</td><td>Net Recharge Amount</td><td>" + str(R) + "</td></tr>"
183
    maildata += "<tr><td></td><td></td><td></td></tr>"
184
 
185
    maildata += "<tr><td>A</td><td>Recharge Coupon Amount</td><td>" + str(A2) + "</td></tr>"
186
    maildata += "<tr><td>B</td><td>Recharge Coupon Amount (Refunded in Future)</td><td>" + str(B2) + "</td></tr>"
187
    maildata += "<tr><td>C</td><td>Recharge Coupon Refund Amount</td><td>" + str(C2) + "</td></tr>"    
188
    maildata += "<tr><td>X2=A2+B2-C2</td><td>Net Coupon Amount</td><td>" + str(X2) + "</td></tr>"
189
 
190
    maildata += "<tr><td>X3</td><td>Gift Amount</td><td>" + str(X3) + "</td></tr>"
191
    maildata += "<tr><td>X4</td><td>Wallet Difference</td><td>" + str(X4) + "</td></tr>"
192
    maildata += "<tr><td>X5</td><td>Payment Amount</td><td>" + str(X5) + "</td></tr>"
193
    maildata += "<tr><td>X6</td><td>Payment Refund Amount</td><td>" + str(X6) + "</td></tr>"
194
    maildata += "<tr><td>P=X2+X3+X5-X4-X6</td><td>Net Payments</td><td>" + str(P) + "</td></tr>"
195
    maildata += "<tr><td></td><td></td><td></td></tr>"
196
 
197
    maildata += "<tr><td>D=R-P</td><td>Net Reconciliation Difference</td><td>" + str(D) + "</td></tr>"
8788 rajveer 198
    maildata += "</tbody></table>"
199
 
200
    if D != 0:
201
        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()
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)
7244 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_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 284
    storeData = {}
285
    for txn in txns:
286
        print txn
287
        if not storeData.has_key(txn[0]):
288
            data = [0,0,0,0,0]
289
            storeData[txn[0]] = data
290
        else:
291
            data = storeData[txn[0]]
7155 rajveer 292
        if txn[1] == 1:
7141 rajveer 293
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 294
        if txn[1] == 2:
7141 rajveer 295
            data[1] += int(txn[3]) - int(txn[4])
7244 rajveer 296
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_UNKNOWN):
7141 rajveer 297
            data[2] += int(txn[3])
298
            data[3] += int(txn[4])
299
            data[4] += int(txn[3]) - int(txn[4])
300
        storeData[txn[0]] = data
301
 
302
    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()  
303
    for txn in reftxns:
304
        print txn
305
        if not storeData.has_key(txn[0]):
306
            data = [0,0,0,0,0]
307
            storeData[txn[0]] = data
308
        else:
309
            data = storeData[txn[0]]
7155 rajveer 310
        if txn[1] == 1:
7148 rajveer 311
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 312
        if txn[1] == 2:
7148 rajveer 313
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 314
        data[2] -= int(txn[3])
315
        data[3] -= int(txn[4])
316
        data[4] -= int(txn[3]) - int(txn[4])
317
    print storeData
7163 rajveer 318
 
7175 rajveer 319
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
320
 
321
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
322
 
7511 rajveer 323
#    if int(dt[0]) != wallet.amount:
324
#        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 325
 
7175 rajveer 326
    maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"
327
    trecharge = 0
7967 anupam.sin 328
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
329
    hotspotServiceMatrixMap = {}
330
 
331
    for hotspotServiceMatrix in hotspotServiceMatrices:
332
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
333
 
7141 rajveer 334
    for storeId in storeData.keys():
335
        store = HotspotStore.get_by(id = storeId)
7967 anupam.sin 336
        if hotspotServiceMatrixMap.has_key(storeId):
337
            del hotspotServiceMatrixMap[storeId]
7141 rajveer 338
        store.collectedAmount = 0
339
        store.availableLimit = store.creditLimit
7142 rajveer 340
        session.commit()
341
 
7141 rajveer 342
        data = storeData.get(storeId)
7250 rajveer 343
        rc = RechargeCollection()
344
        rc.hotspotId = store.hotspotId
345
        rc.reconDate = int(todate.strftime("%Y%m%d"))
346
        rc.cash = data[0]
347
        rc.hdfc = data[1]
348
        rc.grossAmount = data[2]
349
        rc.discount = data[3]
350
        rc.netCollection = data[4]
351
        rc.addedAt = datetime.datetime.now()
352
        rc.pushedToOcr = False
353
        session.commit()
354
 
7175 rajveer 355
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
356
        trecharge +=  data[2]
7250 rajveer 357
 
7276 rajveer 358
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 359
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 360
    wamt = int(dit2[0])- int(dit[0])
361
    wallet.amount = wamt
362
    session.commit()
363
 
7250 rajveer 364
    maildata += "</tbody></table></body></html>"
7821 rajveer 365
    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 366
    try:
367
        push_recharge_collection_to_ocr()
368
    except:
369
        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 370
    finally:
7986 anupam.sin 371
        msg = "<html><body>"
7967 anupam.sin 372
        for storeId in hotspotServiceMatrixMap.keys():
373
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
374
                store = HotspotStore.get_by(id = storeId)
7986 anupam.sin 375
                msg = msg + str(store.hotspotId) + ' - ' + str(store.email) + '<br>'
376
        msg = msg + '</body></html>'
377
        helper_client = HelperClient().get_client()
8020 rajveer 378
        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 379
 
7967 anupam.sin 380
 
7250 rajveer 381
 
382
def push_recharge_collection_to_ocr():
383
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
384
 
385
    for rc in rcs:
386
        store_string = "<Store>" + rc.hotspotId + "</Store>"
387
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
388
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
389
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
390
        type_string = "<Type>RechargeSale</Type>"
391
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
392
 
7141 rajveer 393
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
394
 
7253 rajveer 395
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 396
        XML="""
397
        <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/">
398
          <soap:Body>
399
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
400
        """
401
 
8195 rajveer 402
        XML = XML + store_string + date_string + cash_string + card_string + "<Cheque>0</Cheque>" + type_string + amount_string 
7141 rajveer 403
 
404
        footer = """
405
            </SaholicRechargeSaleTransfer>
406
          </soap:Body>
407
        </soap:Envelope>
408
        """
409
        XML = XML + footer
410
 
411
        print XML
412
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
413
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
414
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
415
        conn.send(XML)
416
        response = conn.getresponse()
417
        print response.status, response.reason
418
        resp = response.read()
419
        conn.close()
420
        print resp
7250 rajveer 421
        if "Saved Successfully" in resp:
422
            rc.pushedAt = datetime.datetime.now()
423
            rc.pushedToOcr = True
424
            session.commit()
425
        elif "Error in Saving Data" in resp:
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
        else: 
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
 
7141 rajveer 430
 
7175 rajveer 431
 
7147 rajveer 432
def topup_company_wallet(companyId, amount):
433
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 434
    company = Company.get_by(id = companyId)
7147 rajveer 435
    wh = WalletHistoryForCompany()
436
    wh.walletId = wallet.id
437
    wh.openingBal = wallet.amount
438
    wh.closingBal = wallet.amount +  amount
439
    wh.amount = amount
440
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 441
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 442
    wh.description = "Wallet Credited"
443
 
444
    wallet.amount += amount
445
    session.commit()
7285 rajveer 446
    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 447
 
7983 rajveer 448
def compute_website_recharge_collection(cdate, oldBalance, newBalance):
7821 rajveer 449
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
450
    tomorrow = todate + timedelta(days=1)
7147 rajveer 451
 
7823 rajveer 452
    txns = session.query(RechargeOrder.status, func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.PAYMENT_SUCCESSFUL])).filter(RechargeOrder.creationTimestamp >= todate).filter(RechargeOrder.creationTimestamp < tomorrow).group_by(RechargeOrder.status).all()
7821 rajveer 453
 
454
    tamount = 0
455
    for txn in txns:
456
        tamount += int(txn[1])
457
 
458
 
7823 rajveer 459
    reftxns = session.query(RechargeOrder.status, func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED).filter(RechargeOrder.responseTimestamp >= todate).filter(RechargeOrder.responseTimestamp < tomorrow).group_by(RechargeOrder.status).all()  
7821 rajveer 460
    for txn in reftxns:
461
        tamount -= int(txn[1])
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 = ""
7982 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 - " + todate.strftime("%d-%m-%Y") + ")   (Wallet Amount - " + str(wallet.amount) + ")    (Total Recharge - " + str(tamount) + ")", maildata, []) 
7821 rajveer 481
 
8012 rajveer 482
    rAmount = 0
8007 rajveer 483
    ramount = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.transactionTime >= todate).filter(WalletHistoryForCompany.amount >= 100000).one()
8012 rajveer 484
    if ramount[0]:
485
        rAmount = int(ramount[0])
486
    rcs = session.query(func.sum(RechargeCollection.grossAmount)).filter(RechargeCollection.reconDate == int(todate.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)
8007 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 - " + todate.strftime("%d-%m-%Y") + ")", maildata, [])
491
 
492
 
6147 rajveer 493
if __name__ == '__main__':
7967 anupam.sin 494
    main()
495