Subversion Repositories SmartDukaan

Rev

Rev 8020 | 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 urllib
import urllib2
import traceback
from string import Template
from shop2020.model.v1.order.impl.DataAccessors import update_amount_in_wallet


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.clients.CRMClient import CRMClient
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 shop2020.thriftpy.crm.ttypes import Ticket, Activity, TicketCategory, TicketStatus, TicketPriority, ActivityType
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:
            update_amount_in_wallet(order.customer_id, voucher.amount, order.id, 0)
            #storeVoucher(voucher.amount)
            #coupon = issueVoucher(order.customer_id, order.customer_email, voucher.amount)
            voucher.issuedOn = datetime.datetime.now()
            voucher.voucherIssued = True
            voucher.voucherCode = 'RECHARGE_WALLET'
            session.commit()
            sendEmail(order.customer_email, voucher.amount, order.id, order.customer_name)
            createCrmTicket(voucher)

def createCrmTicket(voucher):
    try :
        cc = CRMClient().get_client()
        ticket = Ticket()
        activity = Activity()
        order = voucher.order
        ticket.category = TicketCategory.OTHER
        ticket.customerEmailId = order.customer_email
        ticket.customerId = order.customer_id
        ticket.customerMobileNumber = order.customer_mobilenumber
        ticket.customerName = order.customer_name
        ticket.description = "Amount : " + str(voucher.amount) + " Issue date : " + str(voucher.issuedOn) + " Code : " + str(voucher.voucherCode)
        ticket.orderId = order.id
        ticket.creatorId = 1
        ticket.priority = TicketPriority.LOW
        ticket.status = TicketStatus.OPEN
        
        activity.creatorId = 1
        activity.ticketAssigneeId = ticket.assigneeId
        activity.type = ActivityType.OTHER
        activity.description = "Creating Ticket"
        activity.ticketCategory = ticket.category
        activity.ticketDescription = ticket.description
        activity.ticketPriority = ticket.priority
        activity.ticketStatus = ticket.status
        activity.customerEmailId = order.customer_email
        activity.customerId = order.customer_id
        activity.customerMobileNumber = order.customer_mobilenumber
        activity.customerName = order.customer_name
        
        cc.insertTicket(ticket, activity)
        
    except:
        print "Some issue while creating crm tickets for orders in FIRST_DELIVERY_ATTEMPT_MADE status"
        traceback.print_exc()

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 = urllib.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 = urllib.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 = urllib.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 = urllib.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, customer_name):
    html = """
        <html>
        <body>
        <div>
        <p>
        Hi $customer_name, <br>
        Thanks for your order Id: $orderId placed at Saholic.com. As promised you have received a recharge worth Rs $amount. This amount has been added to your <a href="www.saholic.com/my-wallet">Recharge Wallet</a>.You can use this to  <a href="www.saholic.com/recharge">recharge</a> your mobile or DTH.

        <a href="http://www.saholic.com/static/recharge-faq#Q3">Learn </a> how to use your wallet. In case of any questions please feel free to <a href="www.saholic.com/contact-us>Contact Us </a> 


        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,customer_name=customer_name))
    
    try:
        helper_client = HelperClient().get_client()
        helper_client.saveUserEmailForSending([email], "", "Your Free Mobile/DTH Recharge", html, str(orderId), "RechargeVoucher", [], [], 1)
    except Exception as e:
        print e

    
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")
    (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.hostname)

if __name__ == '__main__':
    main()