Subversion Repositories SmartDukaan

Rev

Rev 13205 | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on 06-Jul-2011

@author: Varun Gupta
'''
from math import floor
from shop2020.clients.CatalogClient import CatalogClient
from shop2020.model.v1.user.impl import UserDataAccessors
from shop2020.model.v1.user.impl.PromotionRuleDataUtilities import \
    get_coupon_usage_count, get_coupon_usage_count_by_user
from shop2020.thriftpy.model.v1.user.ttypes import PromotionException, Discount
import datetime

def execute(cart, coupon_code, args):
    
    
    if 'handset_display_name' not in args:
        raise PromotionException(109, 'Error in rule arguments.')
            
    if 'end_on' in args and datetime.datetime.strptime(args['end_on'], '%Y-%m-%d') <= datetime.datetime.now():
        raise PromotionException(112, 'This promotion is expired.')
         
    if 'usage_limit' in args and args['usage_limit'] is not None:
        if args['usage_limit'] <= get_coupon_usage_count(coupon_code):
            raise PromotionException(112, 'This promotion is over.')
    
    user = UserDataAccessors.get_user_by_cart_id(cart.id)
        


    if 'usage_limit_for_user' in args and args['usage_limit_for_user'] is not None:
        if args['usage_limit_for_user'] <= get_coupon_usage_count_by_user(coupon_code, user.id):
            raise PromotionException(111, 'You have already used this coupon maximum possible times.')
    
    if not cart.lines:
        return cart
    
    appliedOnce = args['appliedOnce'] if 'appliedOnce' in args else True

    dealItems = []
    if not (args['dealer_flag'] if 'dealer_flag' in args else False):
        privateDealUser = UserDataAccessors.get_private_deal_user(user.id)
        if privateDealUser is not None and privateDealUser.isActive:
            catalog_client = CatalogClient().get_client() 
            items = [line.itemId for line in cart.lines]
            dealItems = catalog_client.getAllActivePrivateDeals(items, 0)
            
        

    discountJ = None
    if 'discount' in args:
        discountJ  = args ['discount']

    min_amount = None
    if 'min_amount' in args:
        min_amount  = args ['min_amount']

    max_discount = 10000
    if 'max_discount' in args:
        max_discount  = args ['max_discount']
    
    discount_left = max_discount
    
    isPercentageDiscount = False
    if 'is_percentage_discount' in args:
        isPercentageDiscount = args['is_percentage_discount']

    total_discounts = 0
    cart_has_specified_item = False
    discounts = []
    
    foundDeal=False
    
    for line in cart.lines:
        if line.itemId in dealItems:
            foundDeal = True 
            continue
        if discount_left > 0 :
            discount_value = 0
            
            if min_amount is not None and line.actualPrice < min_amount:
                continue
    
            if 'items' in args:
                if line.itemId in args['items'] or '*' in args['items']:
                    if type(args['items'])==dict: 
                        discount_value = args['items'][line.itemId]
                        cart_has_specified_item = True
                    elif discountJ is not None:
                        discount_value = discountJ
                        cart_has_specified_item = True
                else:
                    continue
            elif 'categories' in args:
                catalog_client = CatalogClient().get_client()
                category = catalog_client.getItem(line.itemId).category
                if category in args['categories']:
                    if type(args['categories'])==dict: 
                        discount_value = args['categories'][category]
                        cart_has_specified_item = True
                    elif discountJ is not None:
                        discount_value = discountJ 
                        cart_has_specified_item = True
                else:
                    continue

            elif 'categoriesexcept' in args:
                catalog_client = CatalogClient().get_client()
                category = catalog_client.getItem(line.itemId).category
                if category not in args['categoriesexcept']:
                        discount_value = discountJ 
                        cart_has_specified_item = True
                else:
                    continue

            elif 'brands' in args:
                catalog_client = CatalogClient().get_client()
                brand = catalog_client.getItem(line.itemId).brand
                if brand in args['brands']:
                    if type(args['brands'])==dict: 
                        discount_value = args['brands'][brand]
                        cart_has_specified_item = True
                    elif discountJ is not None:
                        discount_value = discountJ 
                        cart_has_specified_item = True
                else:
                    continue
            
            elif discountJ is not None:
                discount_value = discountJ 
                cart_has_specified_item = True
            else :
                continue
        
            if isPercentageDiscount:
                discount_value = round((line.actualPrice*discount_value)/100, 0)
                    
            if appliedOnce:
                quantity = 1
            else:
                quantity = min(floor(discount_left/discount_value), line.quantity)
            
            if quantity > 0:
                discount = Discount()
                discount.cart_id = cart.id
                discount.item_id = line.itemId
                discount.quantity = quantity
                discount.discount = discount_value
                discounts.append(discount)
                
                discount_left = discount_left - quantity*discount_value
                total_discounts += discount_value * quantity
            
            if appliedOnce :
                break
            
            if discount_left > 0 and line.quantity - quantity > 0:
                discountOne = Discount()
                discountOne.cart_id = cart.id
                discountOne.item_id = line.itemId
                discountOne.quantity = 1
                discountOne.discount = discount_left
                discounts.append(discountOne)

                discount_left = 0
                total_discounts = max_discount
        
        else:
            break
            
        
    if cart_has_specified_item is False:
        if foundDeal:
            raise PromotionException(115, '''Deal items can't be discounted''')
        else:
            raise PromotionException(115, 'This coupon is applicable only for ' + args['handset_display_name'])
            
    
    
    cart.discountedPrice = cart.totalPrice - round(total_discounts, 0)
    return cart, discounts

def getDiscountOnItem(item):
    return None