Subversion Repositories SmartDukaan

Rev

Rev 5561 | Rev 5635 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#!/usr/bin/python 

'''
If a order has been marked as delivered for more than
5 days and it has spicedeck voucher issuance penning, voucher should be issued.

@author: Rajveer
'''

import datetime
from datetime import date
import optparse
import sys
import urllib2
from string import Template


if __name__ == '__main__' and __package__ is None:
    import os
    sys.path.insert(0, os.getcwd())

from shop2020.clients.HelperClient import HelperClient
from shop2020.clients.PromotionClient import PromotionClient
from shop2020.thriftpy.model.v1.order.ttypes import OrderStatus
from shop2020.model.v1.order.impl import DataService
from shop2020.model.v1.order.impl.DataService import RechargeVoucherTracker
from shop2020.thriftpy.model.v1.user.ttypes import Voucher, VoucherType
from elixir import session

voucherGenerationUrl = "http://www.spicedeck.com/couponregister.sdesk"
voucherActivationUrl = "http://www.spicedeck.com/couponassign.sdesk"
voucherDeactivationUrl = "http://www.spicedeck.com/coupondeact.sdesk"
voucherStatusUrl = "http://www.spicedeck.com/couponstatus.sdesk"
username = "saholic"
password = "abc1234"

def issue_voucher_to_orders(db_hostname):
    DataService.initialize(db_hostname=db_hostname, echoOn=True)
    vouchers = RechargeVoucherTracker.query.filter_by(voucherIssued=False).all()
    for voucher in vouchers:
        order = voucher.order
        if order.status == OrderStatus.DELIVERY_SUCCESS:
            storeVoucher(voucher.amount)
            coupon = issueVoucher(order.customer_id, order.customer_email, voucher.amount)
            voucher.issuedOn = datetime.datetime.now()
            voucher.voucherIssued = True
            voucher.voucherCode = coupon
            session.commit()
            #sendEmail(order.customer_email, voucher.amount, order.id, coupon)


def storeVoucher(amount):
    coupon = generateVoucher(amount)
    voucher = Voucher()
    voucher.voucherCode = coupon
    voucher.voucherType = VoucherType.SPICEDECK_MOBILE
    voucher.amount = amount
    pc = PromotionClient().get_client()
    pc.addVoucher(voucher)

def generateVoucher(amount):
    params = "userid=" + username + "&password=" + password + "&amount=" + str(amount) 
    returnValue = urllib2.urlopen(voucherGenerationUrl + "?" + params).read()
    if "-1" == returnValue:
        raise Exception("Credit balance low.")
    
    elif "0" == returnValue:
        raise Exception("Network or some other failure.")
    
    return returnValue;

def issueVoucher(userId, userEmail, amount):
    pc = PromotionClient().get_client()
    voucher = pc.assignVoucher(userId, userEmail, VoucherType.SPICEDECK_MOBILE, amount)
    isActivated = activateVoucher(voucher.voucherCode, voucher.userEmail);
    if not isActivated:
        raise Exception("Voucher could not get activated.");
    return voucher.voucherCode

def activateVoucher(voucherCode, userEmail):
    today = date.today() + datetime.timedelta(365/4)
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&email=" + userEmail + "&expiry=" + today.strftime('%d-%b-%y') 
    returnValue = urllib2.urlopen(voucherActivationUrl + "?" + params).read()
    if "1" == returnValue:
        return True;
    elif "-1" == returnValue:
        raise Exception("Invalid voucher.")
    elif "0" == returnValue:
        raise Exception("Network or some other failure.")
    return False

def deactivateVoucher(voucherCode, reason):
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&comment=" + reason 
    returnValue = urllib2.urlopen(voucherDeactivationUrl + "?" + params).read()
    print returnValue
    ## 0#2#2#pankaj.kankar@shop2020.in
    tokens = returnValue.split('#')
    status = tokens[0]
    actualAmount = int(tokens[1])
    availableAmount = int(tokens[2])
    email = tokens[3] 
    if "1" == status:
        return True;
    elif "0" == status:
        raise Exception("Voucher could not be deactivated")
    elif "-1" == status:
        raise Exception("Network or some other failure.")
    return False


def checkVoucherStatus(voucherCode):
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode
    returnValue = urllib2.urlopen(voucherStatusUrl + "?" + params).read()
    print returnValue
    ## ACTIVATE#2#2#pankaj.kankar@shop2020.in
    ## DEACTIVATED#2#2#pankaj.kankar@shop2020.in
    ## CONSUMED
    ## EXPIRED
    if "-1" == returnValue:
        raise Exception("Network or some other failure.")
    else:
        tokens = returnValue.split('#')
        status = tokens[0]
        actualAmount = int(tokens[1])
        availableAmount = int(tokens[2])
        email = tokens[3]
def sendEmail(email, amount, orderId, voucherCode):
    html = """
        <html>
        <body>
        <div>
        <p>
            Hi,<br /><br />
            Recharge voucher of $amount against order id $orderId is mentioned below. You can use it to recharge mobile through www.spicedeck.com. 
        </p>
            
        <p>    
        <strong>Product: $voucherCode </strong>
        </p>
        
        
        <p>
        Regards,<br/>
        Saholic Customer Support Team<br/>
        www.saholic.com<br/>
        Email: help@saholic.com<br/>
        </p>
        </div>
        </body>
        </html>
        """

    html = Template(html).substitute(dict(orderId=orderId,amount=amount,voucherCode=voucherCode))
    
    try:
        helper_client = HelperClient().get_client()
        helper_client.saveUserEmailForSending(email, "", "Recharge voucher against order id " + str(orderId), html, str(orderId), "RechargeVoucher")
    except Exception as e:
        print e

    
def main():
    parser = optparse.OptionParser()
    #    parser.add_option("-d", "--days", dest="days",
    #                   default=5, type="int",
    #                   help="issue voucher to the delivered orders before NUM days",
    #                   metavar="NUM")
    parser.add_option("-H", "--host", dest="hostname",
                      default="localhost",
                      type="string", help="The HOST where the DB server is running",
                      metavar="HOST")
    (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?")
    #issue_voucher_to_orders(options.days, options.hostname)
    issue_voucher_to_orders(options.hostname)
    #checkVoucherStatus('SHL1340973067027')
    #deactivateVoucher('SHL1340973067027', 'Order not delivered')

if __name__ == '__main__':
    main()