Subversion Repositories SmartDukaan

Rev

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