Subversion Repositories SmartDukaan

Rev

Rev 5537 | 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
import optparse
import sys
import urllib2
from string import Template
from shop2020.clients.HelperClient import HelperClient

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

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/mcommerce/couponregister.sdesk";
voucherActivationUrl = "http://www.spicedeck.com/mcommerce/couponassign.sdesk";
    
def issue_voucher_to_orders(days, db_hostname):
    DataService.initialize(db_hostname=db_hostname, echoOn=True)
    current_time = datetime.datetime.now()
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
    to_datetime = to_datetime - datetime.timedelta(days-1)
    vouchers = RechargeVoucherTracker.query.filter_by(voucherIssued=False).all()
    for voucher in vouchers:
        order = voucher.order
        if order.status == OrderStatus.DELIVERY_SUCCESS and order.delivery_timestamp <= to_datetime:
            storeVoucher("sachingyal", "abc1234", voucher.amount)
            coupon = issueVoucher("sachingyal", "abc1234", order.customer_id, order.customer_email, voucher.amount)
            voucher.issuedOn = current_time
            voucher.voucherIssued = True
            voucher.voucherCode = coupon
            sendEmail(order.customer_email, voucher.amount, order.id, coupon)
    session.commit()


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

def generateVoucher(username, password, 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(username, password, userId, userEmail, amount):
    pc = PromotionClient().get_client()
    voucher = pc.assignVoucher(userId, userEmail, VoucherType.SPICEDECK_MOBILE, amount)
    isActivated = activateVoucher(username, password, voucher.voucherCode, voucher.userEmail);
    if not isActivated:
        raise Exception("Voucher could not get activated.");
    return voucher.voucherCode
def activateVoucher(username, password, voucherCode, userEmail):
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&email=" + userEmail 
    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 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)

if __name__ == '__main__':
    main()