Subversion Repositories SmartDukaan

Rev

Rev 5508 | Rev 5561 | 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
11
import optparse
12
import sys
13
import urllib2
14
from string import Template
15
from shop2020.clients.HelperClient import HelperClient
16
 
17
if __name__ == '__main__' and __package__ is None:
18
    import os
19
    sys.path.insert(0, os.getcwd())
20
 
21
from shop2020.clients.PromotionClient import PromotionClient
22
from shop2020.thriftpy.model.v1.order.ttypes import OrderStatus
23
from shop2020.model.v1.order.impl import DataService
24
from shop2020.model.v1.order.impl.DataService import RechargeVoucherTracker
25
from shop2020.thriftpy.model.v1.user.ttypes import Voucher, VoucherType
26
from elixir import session
27
 
5537 rajveer 28
voucherGenerationUrl = "http://www.spicedeck.com/couponregister.sdesk"
29
voucherActivationUrl = "http://www.spicedeck.com/couponassign.sdesk"
30
voucherDeactivationUrl = "http://www.spicedeck.com/coupondeact.sdesk"
31
voucherStatusUrl = "http://www.spicedeck.com/couponstatus.sdesk"
32
username = "saholic"
33
password = "abc1234"
34
 
5508 rajveer 35
def issue_voucher_to_orders(days, db_hostname):
36
    DataService.initialize(db_hostname=db_hostname, echoOn=True)
37
    current_time = datetime.datetime.now()
38
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
39
    to_datetime = to_datetime - datetime.timedelta(days-1)
40
    vouchers = RechargeVoucherTracker.query.filter_by(voucherIssued=False).all()
41
    for voucher in vouchers:
42
        order = voucher.order
43
        if order.status == OrderStatus.DELIVERY_SUCCESS and order.delivery_timestamp <= to_datetime:
5537 rajveer 44
            storeVoucher(voucher.amount)
45
            coupon = issueVoucher(order.customer_id, order.customer_email, voucher.amount)
5508 rajveer 46
            voucher.issuedOn = current_time
47
            voucher.voucherIssued = True
48
            voucher.voucherCode = coupon
5537 rajveer 49
            #sendEmail(order.customer_email, voucher.amount, order.id, coupon)
5508 rajveer 50
    session.commit()
51
 
52
 
5537 rajveer 53
def storeVoucher(amount):
54
    coupon = generateVoucher(amount)
5508 rajveer 55
    voucher = Voucher()
56
    voucher.voucherCode = coupon
57
    voucher.voucherType = VoucherType.SPICEDECK_MOBILE
58
    voucher.amount = amount
59
    pc = PromotionClient().get_client()
60
    pc.addVoucher(voucher)
61
 
5537 rajveer 62
def generateVoucher(amount):
5508 rajveer 63
    params = "userid=" + username + "&password=" + password + "&amount=" + str(amount) 
64
    returnValue = urllib2.urlopen(voucherGenerationUrl + "?" + params).read()
65
    if "-1" == returnValue:
66
        raise Exception("Credit balance low.")
67
 
68
    elif "0" == returnValue:
69
        raise Exception("Network or some other failure.")
70
 
71
    return returnValue;
72
 
5537 rajveer 73
def issueVoucher(userId, userEmail, amount):
5508 rajveer 74
    pc = PromotionClient().get_client()
75
    voucher = pc.assignVoucher(userId, userEmail, VoucherType.SPICEDECK_MOBILE, amount)
5537 rajveer 76
    isActivated = activateVoucher(voucher.voucherCode, voucher.userEmail);
5508 rajveer 77
    if not isActivated:
78
        raise Exception("Voucher could not get activated.");
79
    return voucher.voucherCode
5537 rajveer 80
 
81
def activateVoucher(voucherCode, userEmail):
82
    params = "userid=" + username + "&password=" + password + "&cid=" + voucherCode + "&email=" + userEmail + "&expiry=" + "30-AUG-12" 
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()
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")
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?")
175
    issue_voucher_to_orders(options.days, options.hostname)
5537 rajveer 176
    #checkVoucherStatus('SHL1340973067027')
177
    #deactivateVoucher('SHL1340973067027', 'Order not delivered')
5508 rajveer 178
 
179
if __name__ == '__main__':
180
    main()