Rev 7278 | Rev 7511 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
#!/usr/bin/python'''It is used to process transactions for which the paymentwas received but the order was not processed.@author: Rajveer'''import optparseimport sysimport datetimefrom datetime import timedeltafrom elixir import *from sqlalchemy.sql import funcimport urllibimport httplibfrom shop2020.utils.EmailAttachmentSender import mail, mail_htmlif __name__ == '__main__' and __package__ is None:import ossys.path.insert(0, os.getcwd())from shop2020.thriftpy.model.v1.order.ttypes import RechargeOrderStatus,\OrderTypefrom shop2020.model.v1.order.impl.DataAccessors import get_recharge_orders_for_status, update_recharge_order_status,\update_recharge_transaction_status, get_next_invoice_numberfrom shop2020.model.v1.order.impl import DataServicefrom shop2020.model.v1.order.impl.DataService import RechargeTransaction, HotspotStore,\WalletForCompany, WalletHistoryForCompany, RechargeCollection, Companyfrom shop2020.model.v1.order.impl.model.RechargeOrder import RechargeOrderfrom shop2020.model.v1.order.impl.RechargeService import checkTransactionStatus, getRefundsdef main():parser = optparse.OptionParser()parser.add_option("-H", "--host", dest="hostname",default="localhost",type="string", help="The HOST where the DB server is running",metavar="HOST")parser.add_option("-r", "--refund", dest="refund",action="store_true",help="")parser.add_option("-u", "--unknown", dest="unknown",action="store_true",help="")parser.add_option("-a", "--authorized", dest="authorized",action="store_true",help="")parser.add_option("-c", "--collection", dest="collection",action="store_true",help="")parser.add_option("-T", "--topup", dest="topup",action="store_true",help="")parser.add_option("-t", "--txn-id", dest="txn_id",type="int",help="mark the transaction(recharge order id) TXN_ID as successful",metavar="TXN_ID")(options, args) = parser.parse_args()if len(args) != 0:parser.error("You've supplied extra arguments. Are you sure you want to run this program?")DataService.initialize(db_hostname=options.hostname, echoOn=True)if options.refund:processRefunds()if options.unknown:processUnknownTransactions()if options.authorized:processAuthorizedTransactions(options.txn_id)if options.collection:d = datetime.datetime.now()d = d + timedelta(days = -1)compute_recharge_collection(d)if options.topup:topup_company_wallet(1,100000)def processRefunds():todate = datetime.datetime.now()for i in range(15):orderDate = todate + datetime.timedelta(days= -i)refunds = getRefunds(orderDate)for key in refunds.keys():refund = refunds.get(key)refundAmount = refund[0]refundDate = refund[1]order = RechargeOrder.get_by(spiceTID = key)if order:amount = order.totalAmountisStoreOrder = Falseelse:order = RechargeTransaction.get_by(spiceTID = key)if not order:continueisStoreOrder = Trueamount = order.amountif order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:print "Refund is already processed."continueif order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):print "Recharge/Payment is not successful. There is something wrong."continueif amount != refundAmount:print "Refund amount is not same as transaction amount"continueif isStoreOrder:update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)else:update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, refundDate)def processUnknownTransactions():orders = get_recharge_orders_for_status(RechargeOrderStatus.PAYMENT_SUCCESSFUL)for order in orders:try:if order.creationTimestamp + datetime.timedelta(minutes=10) < datetime.datetime.now():status, description = checkTransactionStatus('', str(order.id))print status, descriptionif status:update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)else:update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)except:print "Do Nothing"## For store transactionsrorders = RechargeTransaction.query.filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_UNKNOWN, RechargeOrderStatus.INIT])).all()for order in rorders:try:if order.transactionTime + datetime.timedelta(minutes=10) < datetime.datetime.now():status, description = checkTransactionStatus('', str(order.id))print status, descriptionif status:update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_SUCCESSFUL)elif order.status == RechargeOrderStatus.INIT:update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED)else:update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)except:print "Do Nothing"def processAuthorizedTransactions(txn_id):update_recharge_order_status(txn_id, RechargeOrderStatus.PAYMENT_SUCCESSFUL)def compute_recharge_collection(cdate):todate = datetime.datetime(cdate.year, cdate.month, cdate.day)tomorrow = todate + timedelta(days=1)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()storeData = {}for txn in txns:print txnif not storeData.has_key(txn[0]):data = [0,0,0,0,0]storeData[txn[0]] = dataelse:data = storeData[txn[0]]if txn[1] == 1:data[0] += int(txn[3]) - int(txn[4])if txn[1] == 2:data[1] += int(txn[3]) - int(txn[4])if txn[2] in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED, RechargeOrderStatus.RECHARGE_UNKNOWN):data[2] += int(txn[3])data[3] += int(txn[4])data[4] += int(txn[3]) - int(txn[4])storeData[txn[0]] = datareftxns = 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()for txn in reftxns:print txnif not storeData.has_key(txn[0]):data = [0,0,0,0,0]storeData[txn[0]] = dataelse:data = storeData[txn[0]]if txn[1] == 1:data[0] -= int(txn[3]) - int(txn[4])if txn[1] == 2:data[1] -= int(txn[3]) - int(txn[4])data[2] -= int(txn[3])data[3] -= int(txn[4])data[4] -= int(txn[3]) - int(txn[4])print storeDatawallet = WalletForCompany.query.filter(WalletForCompany.id == 1).one()dt = session.query(func.sum(RechargeTransaction.amount)).filter(RechargeTransaction.status.in_([RechargeOrderStatus.RECHARGE_SUCCESSFUL])).one()if int(dt[0]) != wallet.amount: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])) , "", [], [], [])maildata = "<html><body><table border='1'><thead><th>StoreId</th><th>Gross</th><th>Discount</th><th>Net</th></thead><tbody>"trecharge = 0for storeId in storeData.keys():store = HotspotStore.get_by(id = storeId)store.collectedAmount = 0store.availableLimit = store.creditLimitsession.commit()data = storeData.get(storeId)rc = RechargeCollection()rc.hotspotId = store.hotspotIdrc.reconDate = int(todate.strftime("%Y%m%d"))rc.cash = data[0]rc.hdfc = data[1]rc.grossAmount = data[2]rc.discount = data[3]rc.netCollection = data[4]rc.addedAt = datetime.datetime.now()rc.pushedToOcr = Falsesession.commit()maildata += "<tr><td>" + store.hotspotId + "</td><td>" + str(data[2]) + "</td><td>" + str(data[3]) + "</td><td>" + str(data[4]) + "</td></tr>"trecharge += data[2]dit = session.query(func.sum(RechargeCollection.grossAmount)).one()dit2 = session.query(func.sum(WalletHistoryForCompany.amount)).filter(WalletHistoryForCompany.amount >= 100000).one()wamt = int(dit2[0])- int(dit[0])wallet.amount = wamtsession.commit()maildata += "</tbody></table></body></html>"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 (Date - " + todate.strftime("%d-%m-%Y") + ") (Wallet Amount - " + str(wallet.amount) + ") (Total Recharge - " + str(trecharge) + ")", maildata, [])try:push_recharge_collection_to_ocr()except: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", "", [])def push_recharge_collection_to_ocr():rcs = RechargeCollection.query.filter(RechargeCollection.pushedToOcr == False).all()for rc in rcs:store_string = "<Store>" + rc.hotspotId + "</Store>"date_string = "<ReconDate>" + str(rc.reconDate) + "</ReconDate>"cash_string = "<Cash>" + str(rc.cash) + "</Cash>"card_string = "<Hdfc>" + str(rc.hdfc) + "</Hdfc>"type_string = "<Type>RechargeSale</Type>"amount_string = "<GrossRechargeAmount>" + str(rc.grossAmount) + "</GrossRechargeAmount><Discount>" + str(rc.discount) + "</Discount><NetCollection>" + str(rc.netCollection) + "</NetCollection>";#SaholicRechargeSaleTransfer(string Store, int ReconDate, decimal Cash, decimal Hdfc, string Type, decimal GrossRechargeAmount, decimal Discount, decimal NetCollection)conn = httplib.HTTPConnection("182.71.104.186")XML="""<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/"><soap:Body><SaholicRechargeSaleTransfer xmlns="http://tempuri.org/">"""XML = XML + store_string + date_string + cash_string + card_string + type_string + amount_stringfooter = """</SaholicRechargeSaleTransfer></soap:Body></soap:Envelope>"""XML = XML + footerprint XMLparams = urllib.urlencode({'op': 'SaholicRechargeSaleTransfer'})headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)conn.send(XML)response = conn.getresponse()print response.status, response.reasonresp = response.read()conn.close()print respif "Saved Successfully" in resp:rc.pushedAt = datetime.datetime.now()rc.pushedToOcr = Truesession.commit()elif "Error in Saving Data" in resp: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, [])else: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, [])def topup_company_wallet(companyId, amount):wallet = WalletForCompany.query.filter(WalletForCompany.id == companyId).with_lockmode("update").one()company = Company.get_by(id = companyId)wh = WalletHistoryForCompany()wh.walletId = wallet.idwh.openingBal = wallet.amountwh.closingBal = wallet.amount + amountwh.amount = amountwh.transactionTime = datetime.datetime.now()wh.referenceNumber = get_next_invoice_number(OrderType.WALLETCREDIT)wh.description = "Wallet Credited"wallet.amount += amountsession.commit()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.", "", [], [], [])if __name__ == '__main__':main()