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 than5 days and it has spicedeck voucher issuance penning, voucher should be issued.@author: Rajveer'''import datetimefrom datetime import dateimport optparseimport sysimport urllibimport urllib2import tracebackfrom string import Templatefrom shop2020.model.v1.order.impl.DataAccessors import update_amount_in_walletif __name__ == '__main__' and __package__ is None:import ossys.path.insert(0, os.getcwd())from shop2020.clients.HelperClient import HelperClientfrom shop2020.clients.PromotionClient import PromotionClientfrom shop2020.clients.CRMClient import CRMClientfrom 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 shop2020.thriftpy.crm.ttypes import Ticket, Activity, TicketCategory, TicketStatus, TicketPriority, ActivityTypefrom 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: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 = Truevoucher.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.orderticket.category = TicketCategory.OTHERticket.customerEmailId = order.customer_emailticket.customerId = order.customer_idticket.customerMobileNumber = order.customer_mobilenumberticket.customerName = order.customer_nameticket.description = "Amount : " + str(voucher.amount) + " Issue date : " + str(voucher.issuedOn) + " Code : " + str(voucher.voucherCode)ticket.orderId = order.idticket.creatorId = 1ticket.priority = TicketPriority.LOWticket.status = TicketStatus.OPENactivity.creatorId = 1activity.ticketAssigneeId = ticket.assigneeIdactivity.type = ActivityType.OTHERactivity.description = "Creating Ticket"activity.ticketCategory = ticket.categoryactivity.ticketDescription = ticket.descriptionactivity.ticketPriority = ticket.priorityactivity.ticketStatus = ticket.statusactivity.customerEmailId = order.customer_emailactivity.customerId = order.customer_idactivity.customerMobileNumber = order.customer_mobilenumberactivity.customerName = order.customer_namecc.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 = 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 = 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.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 = 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 Falsedef deactivateVoucher(voucherCode, reason):params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&comment=" + reasonreturnValue = urllib.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 = urllib.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, 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 edef 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()