Subversion Repositories SmartDukaan

Rev

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