Subversion Repositories SmartDukaan

Rev

Rev 17005 | Blame | Compare with Previous | Last modification | View Log | RSS feed

from datetime import datetime, timedelta
from dtr.storage.DataService import user_app_cashbacks
import sys
import traceback
import getopt
from dtr.main import tprint, refundToWallet
import time
from dtr.storage import DataService
from elixir import *
import pymongo
from dtr.utils import utils

DataService.initialize(db_hostname="localhost") 
con=None

def get_mongo_connection(host='localhost', port=27017):
    global con
    if con is None:
        print "Establishing connection %s host and port %d" %(host,port)
        try:
            con = pymongo.MongoClient(host, port)
        except Exception, e:
            print e
            return None
    return con

def settleAppOffersPayBack(runtype='dry'):
    if runtype == 'live':
        print 'Live Run:- Amount will be credited in the specific users'
        currentTimestamp = datetime.today()
        currentMonth = currentTimestamp.month
        currentDay = currentTimestamp.day
        currentYear = currentTimestamp.year
        sevenDaysBeforeTimestamp = datetime.today() - timedelta(days=7)
        sevenDaysBeforeYear = sevenDaysBeforeTimestamp.year
        if currentYear > sevenDaysBeforeYear:
            currentMonth = sevenDaysBeforeTimestamp.month
            currentDay = sevenDaysBeforeTimestamp.day
            currentYear = sevenDaysBeforeYear
            fortNight = (currentMonth - 1)*2 + (currentDay/15)+1
        else:
            fortNight = (currentMonth - 1)*2 + (currentDay/15)
            
        print "FortNight: ", fortNight, "Year: ", currentYear
        
        userCashbacksToBeCredited = user_app_cashbacks.query.filter(user_app_cashbacks.user_id>0).filter(user_app_cashbacks.status=='Approved').filter(user_app_cashbacks.fortnightOfYear<fortNight).filter(user_app_cashbacks.yearVal==currentYear).all()
        userCashbacksMap = {}
        for userCashback in userCashbacksToBeCredited:
            if userCashback.user_id >0:
                if userCashbacksMap.has_key(userCashback.user_id):
                    cashBackAmount = userCashbacksMap.get(userCashback.user_id) + userCashback.amount
                    userCashbacksMap[userCashback.user_id] = cashBackAmount
                else:
                    userCashbacksMap[userCashback.user_id] = userCashback.amount
        datetimeNow = datetime.now() 
        batchId = int(time.mktime(datetimeNow.timetuple()))
        if(refundToWallet(batchId, userCashbacksMap)):
            for userCashback in userCashbacksToBeCredited:
                userCashback.status = 'Credited'
                userCashback.batchCreditId = batchId
                userCashback.creditedDate = datetimeNow.date()
            session.commit()
            
            for key, value in userCashbacksMap.iteritems():
                print 'User Id:- ', key, ' Credited Amount:- ', value
                get_mongo_connection().Dtr.refund.insert({"userId": key, "batch":batchId, "userAmount":value, "timestamp":datetime.strftime(datetimeNow,"%Y-%m-%d %H:%M:%S"), "type":utils.CREDIT_TYPE_APP})
                get_mongo_connection().Dtr.user.update({"userId":key}, {"$inc": { "credited": value, utils.CREDIT_TYPE_APP:value}}, upsert=True)
        else:
            print 'Refund Process have been failed'
    else:
        print 'Dry Run:- Only showing user map for which cashback have been updated'
        currentTimestamp = datetime.today()
        currentMonth = currentTimestamp.month
        currentDay = currentTimestamp.day
        currentYear = currentTimestamp.year
        sevenDaysBeforeTimestamp = datetime.today() - timedelta(days=7)
        sevenDaysBeforeYear = sevenDaysBeforeTimestamp.year
        if currentYear > sevenDaysBeforeYear:
            currentMonth = sevenDaysBeforeTimestamp.month
            currentDay = sevenDaysBeforeTimestamp.day
            currentYear = sevenDaysBeforeYear
            fortNight = (currentMonth - 1)*2 + (currentDay/15)+1
        else:
            fortNight = (currentMonth - 1)*2 + (currentDay/15)
            
        print "FortNight: ", fortNight, "Year: ", currentYear
        
        userCashbacksToBeCredited = user_app_cashbacks.query.filter(user_app_cashbacks.user_id>0).filter(user_app_cashbacks.status=='Approved').filter(user_app_cashbacks.fortnightOfYear<fortNight).filter(user_app_cashbacks.yearVal==currentYear).all()
        userCashbacksMap = {}
        for userCashback in userCashbacksToBeCredited:
            if userCashback.user_id >0:
                if userCashbacksMap.has_key(userCashback.user_id):
                    cashBackAmount = userCashbacksMap.get(userCashback.user_id) + userCashback.amount
                    userCashbacksMap[userCashback.user_id] = cashBackAmount
                else:
                    userCashbacksMap[userCashback.user_id] = userCashback.amount
        
        datetimeNow = datetime.now() 
        batchId = int(time.mktime(datetimeNow.timetuple()))
        print 'BatchId:- ', batchId
        
        for key, value in userCashbacksMap.iteritems():
            print 'User Id:- ', key, ' Cashback Value:- ', value
        
def main(argv):
    runtype = 'dry'
    try:
        opts, args = getopt.getopt(argv,"ht:",["runtype="])
    except getopt.GetoptError:
        print 'settlementcron.py -t <dry|live>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'settlementcron.py -t <dry|live>'
            sys.exit()
        elif opt == '-t':
            runtype = arg
        
        tprint("Settling payback", runtype)
        try:
            settleAppOffersPayBack(runtype)
        except:
            tprint("Error")
            traceback.print_exc()
    session.close()
if __name__=='__main__':
    main(sys.argv[1:])