Subversion Repositories SmartDukaan

Rev

Rev 6355 | Rev 6433 | 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
1976 varun.gupt 17
 
3187 rajveer 18
def initialize(dbname = 'user', db_hostname="localhost"):
19
    Dataservice.initialize(dbname, db_hostname)
1976 varun.gupt 20
 
21
def create_promotion(name, rule_execution_src, start_on, end_on):
22
    promotion = Promotion()
23
    promotion.name = name
24
    promotion.rule_execution_src = rule_execution_src
25
    promotion.start_on = to_py_date(start_on)
26
    promotion.end_on = to_py_date(end_on)
27
    promotion.created_on = datetime.datetime.now()
28
    session.commit()
29
 
30
def get_all_promotions():
31
    return Promotion.query.all()
32
 
33
def generate_coupons_for_promotion(promotion_id, coupon_code):
34
    promotion = Promotion.get_by(id = promotion_id)
35
 
36
    coupon = Coupon()
37
    coupon.promotion = promotion
38
    coupon.coupon_code = coupon_code
39
    coupon.arguments = ""
40
    session.commit()
41
 
6355 amit.gupta 42
def create_coupon(promotionId, endOn, email, amount, isCod, usage):
6367 amit.gupta 43
    if promotionId not in (26,27):
44
        raise PromotionException(101, 'Only promotion ids 26 and 27 are expected')
6250 amit.gupta 45
    promotion = Promotion.get_by(id = promotionId)
46
    if promotion:     
47
        coupon_code = uuid.uuid4().hex[:10]
48
        coupon = Coupon.get_by(coupon_code = coupon_code)
49
        while coupon is not None:
50
            coupon_code = uuid.uuid4().hex[:10]
51
            coupon = Coupon.get_by(coupon_code = coupon_code)
6355 amit.gupta 52
        s=Template('{"emails":["$email"],"discount":$amount,"usage_limit_for_user":$usage,"endOn":$endOn, "isCod":$isCod}')
6250 amit.gupta 53
        coupon = Coupon()
54
        coupon.promotion = promotion
55
        coupon.coupon_code = coupon_code
6355 amit.gupta 56
        coupon.arguments = s.substitute(email=email, amount=amount, usage=usage, endOn=endOn, isCod=isCod)
6250 amit.gupta 57
        session.commit()
58
        return coupon_code
59
    else:
60
        raise PromotionException(101, 'Could not find Promotion for id' + str(promotionId))
6301 amit.gupta 61
 
62
def get_coupon(coupon_code):
63
    return Coupon.get_by(coupon_code = coupon_code)
6250 amit.gupta 64
 
1976 varun.gupt 65
def apply_coupon(coupon_code, cart_id):
66
    coupon = Coupon.get_by(coupon_code = coupon_code)
67
 
68
    if coupon:
6011 rajveer 69
        todate = datetime.datetime.now()
70
        if not (coupon.promotion.start_on <=  todate and coupon.promotion.end_on >= todate):
71
            raise PromotionException(101, 'Promotion has been expired')
72
 
1976 varun.gupt 73
        user_client = UserClient().get_client()
74
        cart = user_client.getCart(cart_id)
3554 varun.gupt 75
 
2389 varun.gupt 76
        coupon_module = coupon.promotion.rule_execution_src.strip()
77
 
78
        try:
3554 varun.gupt 79
            user_client.deleteDiscountsFromCart(cart_id)
2389 varun.gupt 80
            imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [coupon_module])
81
            rule = eval("imported_coupon_module." + coupon_module)
2466 varun.gupt 82
 
83
            args = eval(coupon.arguments) if coupon.arguments is not None else {}
84
 
3554 varun.gupt 85
            updated_cart, discounts = rule.execute(cart, coupon_code, args)
86
 
87
            if discounts and len(discounts) > 0:    user_client.saveDiscounts(discounts)
88
 
2389 varun.gupt 89
            user_client.applyCouponToCart(cart_id, coupon_code, updated_cart.totalPrice, updated_cart.discountedPrice)
3554 varun.gupt 90
 
2389 varun.gupt 91
            return updated_cart
92
 
93
        except ImportError as e:
94
            traceback.print_stack()
95
            #TODO: Better message
96
            raise PromotionException(100, 'Internal error occurred.')
1976 varun.gupt 97
    else:
98
        print 'Invalid Coupon Code'
99
        raise PromotionException(101, 'Invalid Coupon Code')
100
 
101
def track_coupon_usage(coupon_code, transaction_id, user_id):
102
    promotion_tracker = PromotionTracker()
103
    promotion_tracker.coupon_code = coupon_code
104
    promotion_tracker.transaction_id = transaction_id
105
    promotion_tracker.user_id = user_id
106
    promotion_tracker.applied_on = datetime.datetime.now()
107
    session.commit()
108
 
3386 varun.gupt 109
def get_active_coupons():
110
    return Coupon.query.all()
111
 
112
def get_successful_payment_count_for_coupon(coupon_code):
113
    return PromotionTracker.query.filter_by(coupon_code = coupon_code).count()
114
 
115
def get_rule_doc_string(rule_name):
116
    imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [rule_name])
117
    rule = eval("imported_coupon_module." + rule_name)
118
    return rule.__doc__
4189 varun.gupt 119
 
1976 varun.gupt 120
def close_session():
121
    if session.is_active:
3376 rajveer 122
        session.close()
4189 varun.gupt 123
 
3376 rajveer 124
def is_alive():
125
    try:
126
        session.query(Promotion.id).limit(1).one()
127
        return True
128
    except:
4189 varun.gupt 129
        return False
130
 
4494 varun.gupt 131
def get_discounts_for_entity(entity_id):
132
    catalog_client = CatalogClient().get_client()
133
    items = catalog_client.getItemsByCatalogId(entity_id)
134
 
135
    discount_finder = ItemDiscountFinder()
136
    discounts = discount_finder.getCouponsAndDiscountsOnItem(items[0])
137
 
138
    if len(discounts) > 0:
139
        return {discounts[0][0]: discounts[0][1]}
140
    else:
141
        return {}
142
 
4189 varun.gupt 143
def get_item_discount_map(item_ids):
144
 
145
    discount_finder = ItemDiscountFinder()
146
    item_coupons_discounts = []
147
 
148
    catalog_client = CatalogClient().get_client()
149
 
150
    for item_id in item_ids:
151
        item = catalog_client.getItem(item_id)
152
 
153
        discounts = discount_finder.getCouponsAndDiscountsOnItem(item)
154
 
155
        for discount in discounts:
156
            item_coupons_discounts.append((item_id, discount[0], discount[1]))
157
            break
158
 
159
    return item_coupons_discounts
160
 
5469 rajveer 161
def add_voucher(t_voucher):
162
    voucher = RechargeVoucher()
163
    voucher.available = True
164
    voucher.amount = t_voucher.amount
165
    voucher.voucherCode = t_voucher.voucherCode
166
    voucher.voucherType = t_voucher.voucherType
167
    if t_voucher.issuedOn:
168
        voucher.issuedOn = to_py_date(t_voucher.issuedOn)
169
    if t_voucher.expiredOn:
170
        voucher.expiredOn = to_py_date(t_voucher.expiredOn)
171
    session.commit()
172
 
173
def assign_voucher(userId, userEmail, voucherType, amount):
174
    voucher = RechargeVoucher.query.filter_by(voucherType = voucherType, amount = amount, available = True).first()
175
    if not voucher:
176
        raise PromotionException(501, 'Voucher of this type is not available.')
177
    voucher.userId = userId
178
    voucher.available = False
179
    voucher.issuedOn = datetime.datetime.now()
180
    voucher.email = userEmail
181
    session.commit()
182
    return voucher
183
 
184
def mark_voucher_as_redeemed(voucherCode, redeemedOn):
185
    voucher = RechargeVoucher.query.filter_by(voucherCode = voucherCode).first()
186
    voucher.redeemedOn = to_py_date(redeemedOn)
187
    voucher.redeemed = True
188
    session.commit()
189
    return True
190
 
4189 varun.gupt 191
class ItemDiscountFinder:
192
 
193
    def __init__(self):
194
        self.coupon_modules = {}
195
        coupons = get_active_coupons()
196
 
197
        for coupon in coupons:
5996 amit.gupta 198
            if coupon.coupon_code not in ('SAHOLIC4RS', 'SAndroid', 'SAHOLIC4MJ', 'SAHOLIC4SS', 'SJunglee'):
4189 varun.gupt 199
                coupon_rule = coupon.promotion.rule_execution_src.strip()
200
 
201
                imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [coupon_rule])
202
                self.coupon_modules[coupon.coupon_code] = eval("imported_coupon_module." + coupon_rule)
203
 
204
    def getCouponsAndDiscountsOnItem(self, item):
205
        discounts = []
206
 
207
        for coupon_code, coupon_rule_module in self.coupon_modules.iteritems():
208
 
209
            discount = coupon_rule_module.getDiscountOnItem(item)
210
 
211
            if discount is not None:
212
                discounts.append((coupon_code, discount))
213
 
214
        return discounts