Subversion Repositories SmartDukaan

Rev

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