Subversion Repositories SmartDukaan

Rev

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