Subversion Repositories SmartDukaan

Rev

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