Rev 5537 | Rev 5618 | 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 than5 days and it has spicedeck voucher issuance penning, voucher should be issued.@author: Rajveer'''import datetimefrom datetime import dateimport optparseimport sysimport urllib2from string import Templatefrom shop2020.clients.HelperClient import HelperClientif __name__ == '__main__' and __package__ is None:import ossys.path.insert(0, os.getcwd())from shop2020.clients.PromotionClient import PromotionClientfrom shop2020.thriftpy.model.v1.order.ttypes import OrderStatusfrom shop2020.model.v1.order.impl import DataServicefrom shop2020.model.v1.order.impl.DataService import RechargeVoucherTrackerfrom shop2020.thriftpy.model.v1.user.ttypes import Voucher, VoucherTypefrom elixir import sessionvoucherGenerationUrl = "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.orderif 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 = Truevoucher.voucherCode = coupon#sendEmail(order.customer_email, voucher.amount, order.id, coupon)session.commit()def storeVoucher(amount):coupon = generateVoucher(amount)voucher = Voucher()voucher.voucherCode = couponvoucher.voucherType = VoucherType.SPICEDECK_MOBILEvoucher.amount = amountpc = 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.voucherCodedef 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 Falsedef deactivateVoucher(voucherCode, reason):params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&comment=" + reasonreturnValue = urllib2.urlopen(voucherDeactivationUrl + "?" + params).read()print returnValue## 0#2#2#pankaj.kankar@shop2020.intokens = 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 Falsedef checkVoucherStatus(voucherCode):params = "userid=" + username + "&password=" + password + "&cid=" + voucherCodereturnValue = urllib2.urlopen(voucherStatusUrl + "?" + params).read()print returnValue## ACTIVATE#2#2#pankaj.kankar@shop2020.in## DEACTIVATED#2#2#pankaj.kankar@shop2020.in## CONSUMED## EXPIREDif "-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 edef 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()