Subversion Repositories SmartDukaan

Rev

Rev 6367 | Rev 6443 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1976 varun.gupt 1
'''
2
Created on May 24, 2010
3
@author: Varun Gupta
4
'''
5
from shop2020.clients.UserClient import UserClient
3133 rajveer 6
from shop2020.clients.CatalogClient import CatalogClient
1976 varun.gupt 7
from shop2020.thriftpy.model.v1.user.ttypes import PromotionException
8
from shop2020.model.v1.user.impl import Dataservice
5469 rajveer 9
from shop2020.model.v1.user.impl.Dataservice import Promotion, Coupon, PromotionTracker,\
10
    RechargeVoucher
1976 varun.gupt 11
from shop2020.utils.Utils import to_py_date
6250 amit.gupta 12
import uuid
1976 varun.gupt 13
 
14
from elixir import session
2389 varun.gupt 15
import datetime, traceback
6250 amit.gupta 16
from string import Template
6433 anupam.sin 17
from shop2020.model.v1.user.impl.PromotionRuleDataUtilities import get_coupon_usage_count, get_coupon_usage_count_by_user
1976 varun.gupt 18
 
3187 rajveer 19
def initialize(dbname = 'user', db_hostname="localhost"):
20
    Dataservice.initialize(dbname, db_hostname)
1976 varun.gupt 21
 
22
def create_promotion(name, rule_execution_src, start_on, end_on):
23
    promotion = Promotion()
24
    promotion.name = name
25
    promotion.rule_execution_src = rule_execution_src
26
    promotion.start_on = to_py_date(start_on)
27
    promotion.end_on = to_py_date(end_on)
28
    promotion.created_on = datetime.datetime.now()
29
    session.commit()
30
 
31
def get_all_promotions():
32
    return Promotion.query.all()
33
 
34
def generate_coupons_for_promotion(promotion_id, coupon_code):
35
    promotion = Promotion.get_by(id = promotion_id)
36
 
37
    coupon = Coupon()
38
    coupon.promotion = promotion
39
    coupon.coupon_code = coupon_code
40
    coupon.arguments = ""
41
    session.commit()
42
 
6355 amit.gupta 43
def create_coupon(promotionId, endOn, email, amount, isCod, usage):
6367 amit.gupta 44
    if promotionId not in (26,27):
45
        raise PromotionException(101, 'Only promotion ids 26 and 27 are expected')
6250 amit.gupta 46
    promotion = Promotion.get_by(id = promotionId)
47
    if promotion:     
48
        coupon_code = uuid.uuid4().hex[:10]
49
        coupon = Coupon.get_by(coupon_code = coupon_code)
50
        while coupon is not None:
51
            coupon_code = uuid.uuid4().hex[:10]
52
            coupon = Coupon.get_by(coupon_code = coupon_code)
6355 amit.gupta 53
        s=Template('{"emails":["$email"],"discount":$amount,"usage_limit_for_user":$usage,"endOn":$endOn, "isCod":$isCod}')
6250 amit.gupta 54
        coupon = Coupon()
55
        coupon.promotion = promotion
56
        coupon.coupon_code = coupon_code
6355 amit.gupta 57
        coupon.arguments = s.substitute(email=email, amount=amount, usage=usage, endOn=endOn, isCod=isCod)
6250 amit.gupta 58
        session.commit()
59
        return coupon_code
60
    else:
61
        raise PromotionException(101, 'Could not find Promotion for id' + str(promotionId))
6301 amit.gupta 62
 
63
def get_coupon(coupon_code):
64
    return Coupon.get_by(coupon_code = coupon_code)
6250 amit.gupta 65
 
6433 anupam.sin 66
def apply_recharge_coupon(coupon_code, total_amount, user_id):
67
    coupon = Coupon.get_by(coupon_code = coupon_code)
68
    discount = 0
69
 
70
    if coupon:
71
 
72
        args = eval(coupon.arguments) if coupon.arguments is not None else {}
73
 
74
        if 'minDiscountableVal' in args and total_amount < int(args['minDiscountableVal']):
75
            return {0:'This coupon is valid for recharges equal to or more than Rs.' + (args['minDiscountableVal'])}
76
 
77
        if 'couponType' in args and (args['couponType']) == 'RECHARGE':
78
            discount = round(total_amount * 0.1)
79
        else :
80
            return {0:'Invalid Coupon'}
81
 
82
        todate = datetime.datetime.now()
83
        if 'endOn' in args and todate > to_py_date(args['endOn']) :
84
            return {0:'This coupon is expired.'}
85
 
86
        if 'startHour' in args :
87
            startHour = int(args['startHour'])
88
        else :
89
            return {0 : 'Currently this coupon is unavailable'}
90
 
91
        if 'startMinute' in args :
92
            startMinute = int(args['startMinute'])
93
        else :
94
            return {0 : 'Currently this coupon is unavailable'}
95
 
96
        if 'endHour' in args :
97
            endHour = int(args['endHour'])
98
        else :
99
            return {0 : 'Currently this coupon is unavailable'}
100
 
101
        if 'endMinute' in args :
102
            endMinute = int(args['endMinute'])
103
        else :
104
            return {0 : 'Currently this coupon is unavailable'}
105
 
106
        now = datetime.datetime.now()
107
        curtime = datetime.time(now.hour, now.minute, now.second)
108
        starttime = datetime.time(startHour, startMinute, 0)
109
        endtime = datetime.time(endHour, endMinute, 0)
110
        if (curtime < starttime or curtime > endtime):
111
            return {0:'Currently this coupon is unavailable'}
112
 
113
        count_coupon_usage_by_user = get_coupon_usage_count_by_user(coupon_code, user_id)
114
        if count_coupon_usage_by_user >=2:
115
            return {0:'This coupon is applicable only twice per user'}
116
 
117
        count_coupon_usage = get_coupon_usage_count(coupon_code)
118
        if count_coupon_usage >= 1000:
119
            return {0:'This promotion is over.'}
120
 
121
        if 'maxDiscount' in args and discount > int(args['maxDiscount']):
122
            return {int(args['maxDiscount']):"Coupon Applied"}
123
 
124
        return {discount:'Coupon Applied'}
125
    else:
126
        return {0:'Invalid Coupon'}
127
 
1976 varun.gupt 128
def apply_coupon(coupon_code, cart_id):
129
    coupon = Coupon.get_by(coupon_code = coupon_code)
130
 
131
    if coupon:
6011 rajveer 132
        todate = datetime.datetime.now()
133
        if not (coupon.promotion.start_on <=  todate and coupon.promotion.end_on >= todate):
6433 anupam.sin 134
            raise PromotionException(101, 'Promotion has expired')
6011 rajveer 135
 
1976 varun.gupt 136
        user_client = UserClient().get_client()
137
        cart = user_client.getCart(cart_id)
3554 varun.gupt 138
 
2389 varun.gupt 139
        coupon_module = coupon.promotion.rule_execution_src.strip()
140
 
141
        try:
3554 varun.gupt 142
            user_client.deleteDiscountsFromCart(cart_id)
2389 varun.gupt 143
            imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [coupon_module])
144
            rule = eval("imported_coupon_module." + coupon_module)
2466 varun.gupt 145
 
146
            args = eval(coupon.arguments) if coupon.arguments is not None else {}
147
 
3554 varun.gupt 148
            updated_cart, discounts = rule.execute(cart, coupon_code, args)
149
 
150
            if discounts and len(discounts) > 0:    user_client.saveDiscounts(discounts)
151
 
2389 varun.gupt 152
            user_client.applyCouponToCart(cart_id, coupon_code, updated_cart.totalPrice, updated_cart.discountedPrice)
3554 varun.gupt 153
 
2389 varun.gupt 154
            return updated_cart
155
 
156
        except ImportError as e:
157
            traceback.print_stack()
158
            #TODO: Better message
159
            raise PromotionException(100, 'Internal error occurred.')
1976 varun.gupt 160
    else:
161
        print 'Invalid Coupon Code'
162
        raise PromotionException(101, 'Invalid Coupon Code')
163
 
164
def track_coupon_usage(coupon_code, transaction_id, user_id):
165
    promotion_tracker = PromotionTracker()
166
    promotion_tracker.coupon_code = coupon_code
167
    promotion_tracker.transaction_id = transaction_id
168
    promotion_tracker.user_id = user_id
169
    promotion_tracker.applied_on = datetime.datetime.now()
170
    session.commit()
171
 
3386 varun.gupt 172
def get_active_coupons():
173
    return Coupon.query.all()
174
 
175
def get_successful_payment_count_for_coupon(coupon_code):
176
    return PromotionTracker.query.filter_by(coupon_code = coupon_code).count()
177
 
178
def get_rule_doc_string(rule_name):
179
    imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [rule_name])
180
    rule = eval("imported_coupon_module." + rule_name)
181
    return rule.__doc__
4189 varun.gupt 182
 
1976 varun.gupt 183
def close_session():
184
    if session.is_active:
3376 rajveer 185
        session.close()
4189 varun.gupt 186
 
3376 rajveer 187
def is_alive():
188
    try:
189
        session.query(Promotion.id).limit(1).one()
190
        return True
191
    except:
4189 varun.gupt 192
        return False
193
 
4494 varun.gupt 194
def get_discounts_for_entity(entity_id):
195
    catalog_client = CatalogClient().get_client()
196
    items = catalog_client.getItemsByCatalogId(entity_id)
197
 
198
    discount_finder = ItemDiscountFinder()
199
    discounts = discount_finder.getCouponsAndDiscountsOnItem(items[0])
200
 
201
    if len(discounts) > 0:
202
        return {discounts[0][0]: discounts[0][1]}
203
    else:
204
        return {}
205
 
4189 varun.gupt 206
def get_item_discount_map(item_ids):
207
 
208
    discount_finder = ItemDiscountFinder()
209
    item_coupons_discounts = []
210
 
211
    catalog_client = CatalogClient().get_client()
212
 
213
    for item_id in item_ids:
214
        item = catalog_client.getItem(item_id)
215
 
216
        discounts = discount_finder.getCouponsAndDiscountsOnItem(item)
217
 
218
        for discount in discounts:
219
            item_coupons_discounts.append((item_id, discount[0], discount[1]))
220
            break
221
 
222
    return item_coupons_discounts
223
 
5469 rajveer 224
def add_voucher(t_voucher):
225
    voucher = RechargeVoucher()
226
    voucher.available = True
227
    voucher.amount = t_voucher.amount
228
    voucher.voucherCode = t_voucher.voucherCode
229
    voucher.voucherType = t_voucher.voucherType
230
    if t_voucher.issuedOn:
231
        voucher.issuedOn = to_py_date(t_voucher.issuedOn)
232
    if t_voucher.expiredOn:
233
        voucher.expiredOn = to_py_date(t_voucher.expiredOn)
234
    session.commit()
235
 
236
def assign_voucher(userId, userEmail, voucherType, amount):
237
    voucher = RechargeVoucher.query.filter_by(voucherType = voucherType, amount = amount, available = True).first()
238
    if not voucher:
239
        raise PromotionException(501, 'Voucher of this type is not available.')
240
    voucher.userId = userId
241
    voucher.available = False
242
    voucher.issuedOn = datetime.datetime.now()
243
    voucher.email = userEmail
244
    session.commit()
245
    return voucher
246
 
247
def mark_voucher_as_redeemed(voucherCode, redeemedOn):
248
    voucher = RechargeVoucher.query.filter_by(voucherCode = voucherCode).first()
249
    voucher.redeemedOn = to_py_date(redeemedOn)
250
    voucher.redeemed = True
251
    session.commit()
252
    return True
253
 
4189 varun.gupt 254
class ItemDiscountFinder:
255
 
256
    def __init__(self):
257
        self.coupon_modules = {}
258
        coupons = get_active_coupons()
259
 
260
        for coupon in coupons:
5996 amit.gupta 261
            if coupon.coupon_code not in ('SAHOLIC4RS', 'SAndroid', 'SAHOLIC4MJ', 'SAHOLIC4SS', 'SJunglee'):
4189 varun.gupt 262
                coupon_rule = coupon.promotion.rule_execution_src.strip()
263
 
264
                imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [coupon_rule])
265
                self.coupon_modules[coupon.coupon_code] = eval("imported_coupon_module." + coupon_rule)
266
 
267
    def getCouponsAndDiscountsOnItem(self, item):
268
        discounts = []
269
 
270
        for coupon_code, coupon_rule_module in self.coupon_modules.iteritems():
271
 
272
            discount = coupon_rule_module.getDiscountOnItem(item)
273
 
274
            if discount is not None:
275
                discounts.append((coupon_code, discount))
276
 
277
        return discounts