Subversion Repositories SmartDukaan

Rev

Rev 4941 | Rev 5500 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on May 24, 2010
@author: Varun Gupta
'''
from shop2020.clients.UserClient import UserClient
from shop2020.clients.CatalogClient import CatalogClient
from shop2020.thriftpy.model.v1.user.ttypes import PromotionException
from shop2020.model.v1.user.impl import Dataservice
from shop2020.model.v1.user.impl.Dataservice import Promotion, Coupon, PromotionTracker,\
    RechargeVoucher
from shop2020.utils.Utils import to_py_date

from elixir import session
import datetime, traceback

def initialize(dbname = 'user', db_hostname="localhost"):
    Dataservice.initialize(dbname, db_hostname)

def create_promotion(name, rule_execution_src, start_on, end_on):
    promotion = Promotion()
    promotion.name = name
    promotion.rule_execution_src = rule_execution_src
    promotion.start_on = to_py_date(start_on)
    promotion.end_on = to_py_date(end_on)
    promotion.created_on = datetime.datetime.now()
    session.commit()

def get_all_promotions():
    return Promotion.query.all()

def generate_coupons_for_promotion(promotion_id, coupon_code):
    promotion = Promotion.get_by(id = promotion_id)
    
    coupon = Coupon()
    coupon.promotion = promotion
    coupon.coupon_code = coupon_code
    coupon.arguments = ""
    session.commit()

def apply_coupon(coupon_code, cart_id):
    coupon = Coupon.get_by(coupon_code = coupon_code)
    
    if coupon:
        user_client = UserClient().get_client()
        cart = user_client.getCart(cart_id)
        
        coupon_module = coupon.promotion.rule_execution_src.strip()
        
        try:
            user_client.deleteDiscountsFromCart(cart_id)
            imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [coupon_module])
            rule = eval("imported_coupon_module." + coupon_module)
            
            args = eval(coupon.arguments) if coupon.arguments is not None else {}
            
            updated_cart, discounts = rule.execute(cart, coupon_code, args)
            
            if discounts and len(discounts) > 0:    user_client.saveDiscounts(discounts)
            
            user_client.applyCouponToCart(cart_id, coupon_code, updated_cart.totalPrice, updated_cart.discountedPrice)
            
            return updated_cart
        
        except ImportError as e:
            traceback.print_stack()
            #TODO: Better message
            raise PromotionException(100, 'Internal error occurred.')
    else:
        print 'Invalid Coupon Code'
        raise PromotionException(101, 'Invalid Coupon Code')

def track_coupon_usage(coupon_code, transaction_id, user_id):
    promotion_tracker = PromotionTracker()
    promotion_tracker.coupon_code = coupon_code
    promotion_tracker.transaction_id = transaction_id
    promotion_tracker.user_id = user_id
    promotion_tracker.applied_on = datetime.datetime.now()
    session.commit()

def get_active_coupons():
    return Coupon.query.all()

def get_successful_payment_count_for_coupon(coupon_code):
    return PromotionTracker.query.filter_by(coupon_code = coupon_code).count()

def get_rule_doc_string(rule_name):
    imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [rule_name])
    rule = eval("imported_coupon_module." + rule_name)
    return rule.__doc__

def close_session():
    if session.is_active:
        session.close()
    
def is_alive():
    try:
        session.query(Promotion.id).limit(1).one()
        return True
    except:
        return False

def get_discounts_for_entity(entity_id):
    catalog_client = CatalogClient().get_client()
    items = catalog_client.getItemsByCatalogId(entity_id)
    
    discount_finder = ItemDiscountFinder()
    discounts = discount_finder.getCouponsAndDiscountsOnItem(items[0])
    
    if len(discounts) > 0:
        return {discounts[0][0]: discounts[0][1]}
    else:
        return {}

def get_item_discount_map(item_ids):
    
    discount_finder = ItemDiscountFinder()
    item_coupons_discounts = []
    
    catalog_client = CatalogClient().get_client()
    
    for item_id in item_ids:
        item = catalog_client.getItem(item_id)

        discounts = discount_finder.getCouponsAndDiscountsOnItem(item)
        
        for discount in discounts:
            item_coupons_discounts.append((item_id, discount[0], discount[1]))
            break
    
    return item_coupons_discounts

def add_voucher(t_voucher):
    voucher = RechargeVoucher()
    voucher.available = True
    voucher.amount = t_voucher.amount
    voucher.voucherCode = t_voucher.voucherCode
    voucher.voucherType = t_voucher.voucherType
    if t_voucher.issuedOn:
        voucher.issuedOn = to_py_date(t_voucher.issuedOn)
    if t_voucher.expiredOn:
        voucher.expiredOn = to_py_date(t_voucher.expiredOn)
    session.commit()
    
def assign_voucher(userId, userEmail, voucherType, amount):
    voucher = RechargeVoucher.query.filter_by(voucherType = voucherType, amount = amount, available = True).first()
    if not voucher:
        raise PromotionException(501, 'Voucher of this type is not available.')
    voucher.userId = userId
    voucher.available = False
    voucher.issuedOn = datetime.datetime.now()
    voucher.email = userEmail
    session.commit()
    return voucher

def mark_voucher_as_redeemed(voucherCode, redeemedOn):
    voucher = RechargeVoucher.query.filter_by(voucherCode = voucherCode).first()
    voucher.redeemedOn = to_py_date(redeemedOn)
    voucher.redeemed = True
    session.commit()
    return True

class ItemDiscountFinder:
    
    def __init__(self):
        self.coupon_modules = {}
        coupons = get_active_coupons()
        
        for coupon in coupons:
            if coupon.coupon_code not in ('4B@R10DER5', 'SAHOLIC4RS', 'SGalaxy', 'SAHOLIC4MJ', 'SAHOLIC4SS'):
                coupon_rule = coupon.promotion.rule_execution_src.strip()
                
                imported_coupon_module = __import__("shop2020.model.v1.user.promotionrules", globals(), locals(), [coupon_rule])
                self.coupon_modules[coupon.coupon_code] = eval("imported_coupon_module." + coupon_rule)
    
    def getCouponsAndDiscountsOnItem(self, item):
        discounts = []
        
        for coupon_code, coupon_rule_module in self.coupon_modules.iteritems():
            
            discount = coupon_rule_module.getDiscountOnItem(item)
            
            if discount is not None:
                discounts.append((coupon_code, discount))
            
        return discounts