Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
5508 rajveer 1
#!/usr/bin/python 
2
 
3
'''
4
If a order has been marked as delivered for more than
5
5 days and it has spicedeck voucher issuance penning, voucher should be issued.
6
 
7
@author: Rajveer
8
'''
9
 
10
import datetime
5561 rajveer 11
from datetime import date
5508 rajveer 12
import optparse
13
import sys
14
import urllib2
15
from string import Template
16
 
5618 rajveer 17
 
5508 rajveer 18
if __name__ == '__main__' and __package__ is None:
19
    import os
20
    sys.path.insert(0, os.getcwd())
21
 
5618 rajveer 22
from shop2020.clients.HelperClient import HelperClient
5508 rajveer 23
from shop2020.clients.PromotionClient import PromotionClient
24
from shop2020.thriftpy.model.v1.order.ttypes import OrderStatus
25
from shop2020.model.v1.order.impl import DataService
26
from shop2020.model.v1.order.impl.DataService import RechargeVoucherTracker
27
from shop2020.thriftpy.model.v1.user.ttypes import Voucher, VoucherType
28
from elixir import session
29
 
5537 rajveer 30
voucherGenerationUrl = "http://www.spicedeck.com/couponregister.sdesk"
31
voucherActivationUrl = "http://www.spicedeck.com/couponassign.sdesk"
32
voucherDeactivationUrl = "http://www.spicedeck.com/coupondeact.sdesk"
33
voucherStatusUrl = "http://www.spicedeck.com/couponstatus.sdesk"
34
username = "saholic"
35
password = "abc1234"
36
 
5561 rajveer 37
def issue_voucher_to_orders(db_hostname):
5508 rajveer 38
    DataService.initialize(db_hostname=db_hostname, echoOn=True)
39
    vouchers = RechargeVoucherTracker.query.filter_by(voucherIssued=False).all()
40
    for voucher in vouchers:
41
        order = voucher.order
5561 rajveer 42
        if order.status == OrderStatus.DELIVERY_SUCCESS:
5537 rajveer 43
            storeVoucher(voucher.amount)
44
            coupon = issueVoucher(order.customer_id, order.customer_email, voucher.amount)
5561 rajveer 45
            voucher.issuedOn = datetime.datetime.now()
5508 rajveer 46
            voucher.voucherIssued = True
47
            voucher.voucherCode = coupon
5618 rajveer 48
            session.commit()
5537 rajveer 49
            #sendEmail(order.customer_email, voucher.amount, order.id, coupon)
5508 rajveer 50
 
51
 
5537 rajveer 52
def storeVoucher(amount):
53
    coupon = generateVoucher(amount)
5508 rajveer 54
    voucher = Voucher()
55
    voucher.voucherCode = coupon
56
    voucher.voucherType = VoucherType.SPICEDECK_MOBILE
57
    voucher.amount = amount
58
    pc = PromotionClient().get_client()
59
    pc.addVoucher(voucher)
60
 
5537 rajveer 61
def generateVoucher(amount):
5508 rajveer 62
    params = "userid=" + username + "&password=" + password + "&amount=" + str(amount) 
63
    returnValue = urllib2.urlopen(voucherGenerationUrl + "?" + params).read()
64
    if "-1" == returnValue:
65
        raise Exception("Credit balance low.")
66
 
67
    elif "0" == returnValue:
68
        raise Exception("Network or some other failure.")
69
 
70
    return returnValue;
71
 
5537 rajveer 72
def issueVoucher(userId, userEmail, amount):
5508 rajveer 73
    pc = PromotionClient().get_client()
74
    voucher = pc.assignVoucher(userId, userEmail, VoucherType.SPICEDECK_MOBILE, amount)
5537 rajveer 75
    isActivated = activateVoucher(voucher.voucherCode, voucher.userEmail);
5508 rajveer 76
    if not isActivated:
77
        raise Exception("Voucher could not get activated.");
78
    return voucher.voucherCode
5537 rajveer 79
 
80
def activateVoucher(voucherCode, userEmail):
5561 rajveer 81
    today = date.today() + datetime.timedelta(365/4)
82
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&email=" + userEmail + "&expiry=" + today.strftime('%d-%b-%y') 
5508 rajveer 83
    returnValue = urllib2.urlopen(voucherActivationUrl + "?" + params).read()
84
    if "1" == returnValue:
85
        return True;
86
    elif "-1" == returnValue:
87
        raise Exception("Invalid voucher.")
88
    elif "0" == returnValue:
89
        raise Exception("Network or some other failure.")
90
    return False
5537 rajveer 91
 
92
def deactivateVoucher(voucherCode, reason):
93
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&comment=" + reason 
94
    returnValue = urllib2.urlopen(voucherDeactivationUrl + "?" + params).read()
95
    print returnValue
96
    ## 0#2#2#pankaj.kankar@shop2020.in
97
    tokens = returnValue.split('#')
98
    status = tokens[0]
99
    actualAmount = int(tokens[1])
100
    availableAmount = int(tokens[2])
101
    email = tokens[3] 
102
    if "1" == status:
103
        return True;
104
    elif "0" == status:
105
        raise Exception("Voucher could not be deactivated")
106
    elif "-1" == status:
107
        raise Exception("Network or some other failure.")
108
    return False
109
 
110
 
111
def checkVoucherStatus(voucherCode):
112
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode
113
    returnValue = urllib2.urlopen(voucherStatusUrl + "?" + params).read()
114
    print returnValue
115
    ## ACTIVATE#2#2#pankaj.kankar@shop2020.in
116
    ## DEACTIVATED#2#2#pankaj.kankar@shop2020.in
117
    ## CONSUMED
118
    ## EXPIRED
119
    if "-1" == returnValue:
120
        raise Exception("Network or some other failure.")
121
    else:
122
        tokens = returnValue.split('#')
123
        status = tokens[0]
124
        actualAmount = int(tokens[1])
125
        availableAmount = int(tokens[2])
126
        email = tokens[3]
5508 rajveer 127
def sendEmail(email, amount, orderId, voucherCode):
128
    html = """
129
        <html>
130
        <body>
131
        <div>
132
        <p>
133
            Hi,<br /><br />
134
            Recharge voucher of $amount against order id $orderId is mentioned below. You can use it to recharge mobile through www.spicedeck.com. 
135
        </p>
136
 
137
        <p>    
138
        <strong>Product: $voucherCode </strong>
139
        </p>
140
 
141
 
142
        <p>
143
        Regards,<br/>
144
        Saholic Customer Support Team<br/>
145
        www.saholic.com<br/>
146
        Email: help@saholic.com<br/>
147
        </p>
148
        </div>
149
        </body>
150
        </html>
151
        """
152
 
153
    html = Template(html).substitute(dict(orderId=orderId,amount=amount,voucherCode=voucherCode))
154
 
155
    try:
156
        helper_client = HelperClient().get_client()
157
        helper_client.saveUserEmailForSending(email, "", "Recharge voucher against order id " + str(orderId), html, str(orderId), "RechargeVoucher")
158
    except Exception as e:
159
        print e
160
 
161
 
162
def main():
163
    parser = optparse.OptionParser()
5561 rajveer 164
    #    parser.add_option("-d", "--days", dest="days",
165
    #                   default=5, type="int",
166
    #                   help="issue voucher to the delivered orders before NUM days",
167
    #                   metavar="NUM")
5508 rajveer 168
    parser.add_option("-H", "--host", dest="hostname",
169
                      default="localhost",
170
                      type="string", help="The HOST where the DB server is running",
171
                      metavar="HOST")
172
    (options, args) = parser.parse_args()
173
    if len(args) != 0:
174
        parser.error("You've supplied extra arguments. Are you sure you want to run this program?")
5561 rajveer 175
    #issue_voucher_to_orders(options.days, options.hostname)
176
    issue_voucher_to_orders(options.hostname)
5537 rajveer 177
    #checkVoucherStatus('SHL1340973067027')
178
    #deactivateVoucher('SHL1340973067027', 'Order not delivered')
5508 rajveer 179
 
180
if __name__ == '__main__':
181
    main()