Subversion Repositories SmartDukaan

Rev

Rev 7982 | Rev 7986 | 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 payment 
was received but the order was not processed.

@author: Rajveer
'''
import optparse
import sys
import datetime
from datetime import timedelta
from elixir import *
from sqlalchemy.sql import func
import urllib
import httplib
from shop2020.utils.EmailAttachmentSender import mail, mail_html



if __name__ == '__main__' and __package__ is None:
    import os
    sys.path.insert(0, os.getcwd())
from shop2020.clients.HelperClient import HelperClient
from shop2020.thriftpy.model.v1.order.ttypes import RechargeOrderStatus,\
    OrderType
from shop2020.model.v1.order.impl.DataAccessors import get_recharge_orders_for_status, update_recharge_order_status,\
    update_recharge_transaction_status, get_next_invoice_number
from shop2020.model.v1.order.impl import DataService
from shop2020.model.v1.order.impl.DataService import RechargeTransaction, HotspotStore,\
    WalletForCompany, WalletHistoryForCompany, RechargeCollection, Company, HotspotServiceMatrix
from shop2020.model.v1.order.impl.model.RechargeOrder import RechargeOrder
from shop2020.model.v1.order.impl.RechargeService import checkTransactionStatus, getRefunds, getBalance 


def 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:
        wallet = WalletForCompany.query.filter(WalletForCompany.id == 3).one()
        oldBalance = wallet.amount
        newBalance = getBalance()  
        wallet.amount = newBalance
        session.commit()
                
        d = datetime.datetime.now()
        d = d + timedelta(days = -1)
        compute_recharge_collection(d)
        compute_website_recharge_collection(d, oldBalance, newBalance)
    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.totalAmount
                isStoreOrder = False
            else:
                order = RechargeTransaction.get_by(spiceTID = key)
                if not order:
                    continue
                isStoreOrder = True
                amount = order.amount
            if order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
                print "Refund is already processed."
                continue
            if order.status not in (RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_UNKNOWN):
                print "Recharge/Payment is not successful. There is something wrong."
                continue
            if amount != refundAmount:
                print "Refund amount is not same as transaction amount"
                continue
            if isStoreOrder:
                update_recharge_transaction_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)
            else:
                update_recharge_order_status(order.id, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)

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, description
                if 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 transactions
    rorders = 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, description
                if 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 txn
        if not storeData.has_key(txn[0]):
            data = [0,0,0,0,0]
            storeData[txn[0]] = data
        else:
            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]] = data
  
    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()  
    for txn in reftxns:
        print txn
        if not storeData.has_key(txn[0]):
            data = [0,0,0,0,0]
            storeData[txn[0]] = data
        else:
            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 storeData
    
    wallet = 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 = 0
    hotspotServiceMatrices = HotspotServiceMatrix.query.all()
    hotspotServiceMatrixMap = {}
    
    for hotspotServiceMatrix in hotspotServiceMatrices:
        hotspotServiceMatrixMap[hotspotServiceMatrix.storeId] = hotspotServiceMatrix
        
    for storeId in storeData.keys():
        store = HotspotStore.get_by(id = storeId)
        if hotspotServiceMatrixMap.has_key(storeId):
            del hotspotServiceMatrixMap[storeId]
        store.collectedAmount = 0
        store.availableLimit = store.creditLimit
        session.commit()
        
        data = storeData.get(storeId)
        rc = RechargeCollection()
        rc.hotspotId = store.hotspotId
        rc.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 = False
        session.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.walletId == 1).filter(WalletHistoryForCompany.amount >= 100000).one()
    wamt = int(dit2[0])- int(dit[0])
    wallet.amount = wamt
    session.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 :- SpiceRetail  (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", "", [])
    finally:
        for storeId in hotspotServiceMatrixMap.keys():
            if hotspotServiceMatrixMap.get(storeId).rechargeService:
                store = HotspotStore.get_by(id = storeId)
                helper_client = HelperClient().get_client()
                helper_client.saveUserEmailForSending([store.clusterEmail], "cnc.center@shop2020.in", "No Recharge happened for store " + store.hotspotId + " yesterday", "", "NRM", "NoRechargeMail", [store.email], ["anupam.singh@shop2020.in"])
            
         
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_string 
        
        footer = """
            </SaholicRechargeSaleTransfer>
          </soap:Body>
        </soap:Envelope>
        """
        XML = XML + footer
        
        print XML
        params = 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.reason
        resp = response.read()
        conn.close()
        print resp
        if "Saved Successfully" in resp:
            rc.pushedAt = datetime.datetime.now()
            rc.pushedToOcr = True
            session.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.id
    wh.openingBal = wallet.amount
    wh.closingBal = wallet.amount +  amount
    wh.amount = amount
    wh.transactionTime = datetime.datetime.now()
    wh.referenceNumber =  get_next_invoice_number(OrderType.WALLETCREDIT)
    wh.description = "Wallet Credited"
    
    wallet.amount += amount
    session.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.", "", [], [], [])

def compute_website_recharge_collection(cdate, oldBalance, newBalance):
    todate = datetime.datetime(cdate.year, cdate.month, cdate.day)
    tomorrow = todate + timedelta(days=1)
    
    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()
    
    tamount = 0
    for txn in txns:
        tamount += int(txn[1])
        
  
    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()  
    for txn in reftxns:
        tamount -= int(txn[1])
        
    wallet = WalletForCompany.query.filter(WalletForCompany.id == 2).with_lockmode("update").one()

    
    d = datetime.datetime.now()
    wh = WalletHistoryForCompany()
    wh.walletId = wallet.id
    wh.openingBal = wallet.amount
    wh.closingBal = wallet.amount - tamount
    wh.amount = -tamount
    wh.transactionTime = d
    wh.referenceNumber =  int(d.strftime("%Y%m%d"))
    wh.description = "Wallet Credited"
    wallet.amount = wallet.amount - tamount
    session.commit()


    maildata = "Old Wallet Amount is : " + str(oldBalance) + "<br>New Wallet Amount is : " + str(newBalance)
    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, []) 

    
if __name__ == '__main__':
    main()