Subversion Repositories SmartDukaan

Rev

Rev 8195 | Rev 8790 | 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
 
101
    '''
102
    A - All such orders for which we have attempted the recharge and recharge is either successful or unknown.
103
    B - All such orders for which we have attempted the recharge and we received the refund after this time window.
104
    C - All such orders for which we have received the refund in this time window, although the recharge was attempted before this window.
105
    X1 = A + B - C         Net amount debited for all the customers in this time window.
106
    X2 - Total amount credited to all customers in their wallet under some promotion.
107
    X3 - Net difference in wallet amount between this time window.
108
    X4 - Payment received through gateway from all customer in this time window.
109
    X5 - Payment refunded through gateway by all customer in this time window.
110
    '''
111
 
112
    A = 0
113
    B = 0
114
    C = 0
115
    X1 = 0
116
    X2 = 0
117
    X3 = 0
118
    X4 = 0
119
    X5 = 0
120
    D = 0
121
 
122
    sorder = session.query(func.sum(RechargeOrder.totalAmount - RechargeOrder.couponAmount), 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()    
123
    if sorder and sorder[0]:
124
        A = int(sorder[0])
125
 
126
    forder = session.query(func.sum(RechargeOrder.totalAmount - RechargeOrder.couponAmount), 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()
127
    if forder and forder[0]:
128
        B = int(forder[0])
129
 
130
    rorder = session.query(func.sum(RechargeOrder.totalAmount - RechargeOrder.couponAmount), 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()
131
    if rorder and rorder[0]:
132
        C = int(rorder[0])
133
 
134
    X1 = X1 + A + B - C
135
 
136
    rv = session.query(func.sum(RechargeVoucherTracker.amount)).filter(RechargeVoucherTracker.issuedOn.between(startTime,endTime)).first()
137
    if rv and rv[0]:
138
        X2 = int(rv[0])
139
 
140
    uw = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.timestamp.between(startTime,endTime)).first()
141
    if uw and uw[0]:
142
        X3 = int(uw[0])
143
 
144
 
145
 
146
    pc = PaymentClient().get_client()
147
    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)
148
    for payment in payments:
149
        if payment.isDigital and to_py_date(payment.successTimestamp) >= startTime and to_py_date(payment.successTimestamp) <= endTime:  
150
            X4 = X4 + payment.amount
151
 
152
 
153
 
154
    refunds = RechargeOrder.query.filter(RechargeOrder.status.in_([RechargeOrderStatus.PARTIALLY_REFUNDED, RechargeOrderStatus.REFUNDED])).filter(RechargeOrder.refundTimestamp.between(startTime, endTime)).all()
155
    pc = PaymentClient().get_client()
156
    for refund in refunds:
157
        payments = pc.getPaymentForRechargeTxnId(refund.transaction_id)
158
        for payment in payments:
159
            if payment.gatewayId in (1,2) and payment.status == 8 and payment.isDigital:
160
                X5 = X5 + payment.refundAmount
161
 
162
    D = X1+X3+X5-X2-X4
163
 
164
    maildata = "<html><body><table border='1'><thead><th>Symbol</th><th>Type</th><th>Amount</th></thead><tbody>"
165
    maildata += "<tr><td>A</td><td>Recharge Amount</td><td>" + str(A) + "</td></tr>"
166
    maildata += "<tr><td>B</td><td>Recharge Amount (Refunded in Future)</td><td>" + str(B) + "</td></tr>"
167
    maildata += "<tr><td>C</td><td>Recharge Refund Amount</td><td>" + str(C) + "</td></tr>"
168
    maildata += "<tr><td>X1=A+B-C</td><td>Net Recharge Amount</td><td>" + str(X1) + "</td></tr>"
169
    maildata += "<tr><td>X2</td><td>Gift Amount</td><td>" + str(X2) + "</td></tr>"
170
    maildata += "<tr><td>X3</td><td>Wallet Difference</td><td>" + str(X3) + "</td></tr>"
171
    maildata += "<tr><td>X4</td><td>Payment Amount</td><td>" + str(X4) + "</td></tr>"
172
    maildata += "<tr><td>X5</td><td>Payment Refund Amount</td><td>" + str(X5) + "</td></tr>"
173
    maildata += "<tr><td>D=X1+X3+X5-X2-X4</td><td>Net Reconciliation Difference</td><td>" + str(D) + "</td></tr>"
174
    maildata += "</tbody></table>"
175
 
176
    if D != 0:
177
        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()
178
        if mismatches and len(mismatches) > 0:
179
            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>"
180
            for mismatch in mismatches:
181
                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>"        
182
            maildata += "</tbody></table>"
183
 
184
    maildata += "</body></html>"
185
    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, [])
186
 
187
 
6235 rajveer 188
def processRefunds():
189
    todate = datetime.datetime.now()
8788 rajveer 190
    for i in range(10):
6235 rajveer 191
        orderDate = todate + datetime.timedelta(days= -i)
192
        refunds = getRefunds(orderDate)
193
        for key in refunds.keys():
194
            refund = refunds.get(key)
195
            refundAmount = refund[0]
196
            refundDate = refund[1]
197
            order = RechargeOrder.get_by(spiceTID = key)
7127 rajveer 198
            if order:
199
                amount = order.totalAmount
200
                isStoreOrder = False
201
            else:
202
                order = RechargeTransaction.get_by(spiceTID = key)
7188 rajveer 203
                if not order:
204
                    continue
7127 rajveer 205
                isStoreOrder = True
206
                amount = order.amount
6235 rajveer 207
            if order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
208
                print "Refund is already processed."
209
                continue
7188 rajveer 210
            if order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
7075 rajveer 211
                print "Recharge/Payment is not successful. There is something wrong."
6235 rajveer 212
                continue
7127 rajveer 213
            if amount != refundAmount:
6235 rajveer 214
                print "Refund amount is not same as transaction amount"
215
                continue
7127 rajveer 216
            if isStoreOrder:
7244 rajveer 217
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7127 rajveer 218
            else:
7780 rajveer 219
                update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
6235 rajveer 220
 
221
def processUnknownTransactions():    
222
    orders = get_recharge_orders_for_status(RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6219 rajveer 223
    for order in orders:
6276 rajveer 224
        try:
225
            if order.creationTimestamp + datetime.timedelta(minutes=10) < datetime.datetime.now():
226
                status, description = checkTransactionStatus('', str(order.id))
227
                print status, description
228
                if status:
229
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
230
                else:
231
                    update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
232
        except:
233
            print "Do Nothing"
6451 rajveer 234
 
7163 rajveer 235
    ## For store transactions
7245 rajveer 236
    rorders = RechargeTransaction.query.filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_UNKNOWN, RechargeOrderStatus.INIT])).all()
7166 rajveer 237
    for order in rorders:
7163 rajveer 238
        try:
239
            if order.transactionTime + datetime.timedelta(minutes=10) < datetime.datetime.now():
240
                status, description = checkTransactionStatus('', str(order.id))
241
                print status, description
242
                if status:
243
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)
7245 rajveer 244
                elif order.status == RechargeOrderStatus.INIT:
245
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)
7163 rajveer 246
                else:
7244 rajveer 247
                    update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
7163 rajveer 248
        except:
249
            print "Do Nothing"
250
 
251
 
6451 rajveer 252
def processAuthorizedTransactions(txn_id):
253
    update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)
6235 rajveer 254
 
7141 rajveer 255
 
256
def compute_recharge_collection(cdate):
257
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
258
    tomorrow = todate + timedelta(days=1)
7244 rajveer 259
    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 260
    storeData = {}
261
    for txn in txns:
262
        print txn
263
        if not storeData.has_key(txn[0]):
264
            data = [0,0,0,0,0]
265
            storeData[txn[0]] = data
266
        else:
267
            data = storeData[txn[0]]
7155 rajveer 268
        if txn[1] == 1:
7141 rajveer 269
            data[0] += int(txn[3]) - int(txn[4])
7155 rajveer 270
        if txn[1] == 2:
7141 rajveer 271
            data[1] += int(txn[3]) - int(txn[4])
7244 rajveer 272
        if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_UNKNOWN):
7141 rajveer 273
            data[2] += int(txn[3])
274
            data[3] += int(txn[4])
275
            data[4] += int(txn[3]) - int(txn[4])
276
        storeData[txn[0]] = data
277
 
278
    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()  
279
    for txn in reftxns:
280
        print txn
281
        if not storeData.has_key(txn[0]):
282
            data = [0,0,0,0,0]
283
            storeData[txn[0]] = data
284
        else:
285
            data = storeData[txn[0]]
7155 rajveer 286
        if txn[1] == 1:
7148 rajveer 287
            data[0] -= int(txn[3]) - int(txn[4])
7155 rajveer 288
        if txn[1] == 2:
7148 rajveer 289
            data[1] -= int(txn[3]) - int(txn[4])
7141 rajveer 290
        data[2] -= int(txn[3])
291
        data[3] -= int(txn[4])
292
        data[4] -= int(txn[3]) - int(txn[4])
293
    print storeData
7163 rajveer 294
 
7175 rajveer 295
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()    
296
 
297
    dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()
298
 
7511 rajveer 299
#    if int(dt[0]) != wallet.amount:
300
#        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 301
 
7175 rajveer 302
    maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"
303
    trecharge = 0
7967 anupam.sin 304
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
305
    hotspotServiceMatrixMap = {}
306
 
307
    for hotspotServiceMatrix in hotspotServiceMatrices:
308
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
309
 
7141 rajveer 310
    for storeId in storeData.keys():
311
        store = HotspotStore.get_by(id = storeId)
7967 anupam.sin 312
        if hotspotServiceMatrixMap.has_key(storeId):
313
            del hotspotServiceMatrixMap[storeId]
7141 rajveer 314
        store.collectedAmount = 0
315
        store.availableLimit = store.creditLimit
7142 rajveer 316
        session.commit()
317
 
7141 rajveer 318
        data = storeData.get(storeId)
7250 rajveer 319
        rc = RechargeCollection()
320
        rc.hotspotId = store.hotspotId
321
        rc.reconDate = int(todate.strftime("%Y%m%d"))
322
        rc.cash = data[0]
323
        rc.hdfc = data[1]
324
        rc.grossAmount = data[2]
325
        rc.discount = data[3]
326
        rc.netCollection = data[4]
327
        rc.addedAt = datetime.datetime.now()
328
        rc.pushedToOcr = False
329
        session.commit()
330
 
7175 rajveer 331
        maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"
332
        trecharge +=  data[2]
7250 rajveer 333
 
7276 rajveer 334
    dit = session.query(func.sum(RechargeCollection.grossAmount)).one()
7821 rajveer 335
    dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
7276 rajveer 336
    wamt = int(dit2[0])- int(dit[0])
337
    wallet.amount = wamt
338
    session.commit()
339
 
7250 rajveer 340
    maildata += "</tbody></table></body></html>"
7821 rajveer 341
    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 342
    try:
343
        push_recharge_collection_to_ocr()
344
    except:
345
        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 346
    finally:
7986 anupam.sin 347
        msg = "<html><body>"
7967 anupam.sin 348
        for storeId in hotspotServiceMatrixMap.keys():
349
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
350
                store = HotspotStore.get_by(id = storeId)
7986 anupam.sin 351
                msg = msg + str(store.hotspotId) + ' - ' + str(store.email) + '<br>'
352
        msg = msg + '</body></html>'
353
        helper_client = HelperClient().get_client()
8020 rajveer 354
        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 355
 
7967 anupam.sin 356
 
7250 rajveer 357
 
358
def push_recharge_collection_to_ocr():
359
    rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()
360
 
361
    for rc in rcs:
362
        store_string = "<Store>" + rc.hotspotId + "</Store>"
363
        date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"
364
        cash_string = "<Cash>" + str(rc.cash) + "</Cash>"
365
        card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"
366
        type_string = "<Type>RechargeSale</Type>"
367
        amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) +  "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";
368
 
7141 rajveer 369
        #SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)
370
 
7253 rajveer 371
        conn = httplib.HTTPConnection("182.71.104.186")
7141 rajveer 372
        XML="""
373
        <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/">
374
          <soap:Body>
375
            <SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">
376
        """
377
 
8195 rajveer 378
        XML = XML + store_string + date_string + cash_string + card_string + "<Cheque>0</Cheque>" + type_string + amount_string 
7141 rajveer 379
 
380
        footer = """
381
            </SaholicRechargeSaleTransfer>
382
          </soap:Body>
383
        </soap:Envelope>
384
        """
385
        XML = XML + footer
386
 
387
        print XML
388
        params = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})
389
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
390
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
391
        conn.send(XML)
392
        response = conn.getresponse()
393
        print response.status, response.reason
394
        resp = response.read()
395
        conn.close()
396
        print resp
7250 rajveer 397
        if "Saved Successfully" in resp:
398
            rc.pushedAt = datetime.datetime.now()
399
            rc.pushedToOcr = True
400
            session.commit()
401
        elif "Error in Saving Data" in resp:
7252 rajveer 402
            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 403
        else: 
7252 rajveer 404
            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 405
 
7141 rajveer 406
 
7175 rajveer 407
 
7147 rajveer 408
def topup_company_wallet(companyId, amount):
409
    wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()
7285 rajveer 410
    company = Company.get_by(id = companyId)
7147 rajveer 411
    wh = WalletHistoryForCompany()
412
    wh.walletId = wallet.id
413
    wh.openingBal = wallet.amount
414
    wh.closingBal = wallet.amount +  amount
415
    wh.amount = amount
416
    wh.transactionTime = datetime.datetime.now()
7167 rajveer 417
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
7147 rajveer 418
    wh.description = "Wallet Credited"
419
 
420
    wallet.amount += amount
421
    session.commit()
7285 rajveer 422
    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 423
 
7983 rajveer 424
def compute_website_recharge_collection(cdate, oldBalance, newBalance):
7821 rajveer 425
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
426
    tomorrow = todate + timedelta(days=1)
7147 rajveer 427
 
7823 rajveer 428
    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 429
 
430
    tamount = 0
431
    for txn in txns:
432
        tamount += int(txn[1])
433
 
434
 
7823 rajveer 435
    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 436
    for txn in reftxns:
437
        tamount -= int(txn[1])
438
 
439
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()
7823 rajveer 440
 
441
 
442
    d = datetime.datetime.now()
443
    wh = WalletHistoryForCompany()
444
    wh.walletId = wallet.id
445
    wh.openingBal = wallet.amount
446
    wh.closingBal = wallet.amount - tamount
7982 rajveer 447
    wh.amount = -tamount
7823 rajveer 448
    wh.transactionTime = d
449
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
450
    wh.description = "Wallet Credited"
451
    wallet.amount = wallet.amount - tamount
7821 rajveer 452
    session.commit()
453
 
7823 rajveer 454
 
8007 rajveer 455
    maildata = ""
7982 rajveer 456
    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 457
 
8012 rajveer 458
    rAmount = 0
8007 rajveer 459
    ramount = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.transactionTime >= todate).filter(WalletHistoryForCompany.amount >= 100000).one()
8012 rajveer 460
    if ramount[0]:
461
        rAmount = int(ramount[0])
462
    rcs = session.query(func.sum(RechargeCollection.grossAmount)).filter(RechargeCollection.reconDate == int(todate.strftime("%Y%m%d"))).one()
8007 rajveer 463
    hamount = int(rcs[0])
464
 
8012 rajveer 465
    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 466
    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, [])
467
 
468
 
6147 rajveer 469
if __name__ == '__main__':
7967 anupam.sin 470
    main()
471