Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
17812 amit.gupta 1
'''
2
Created on 10-May-2010
3
 
4
@author: ashish
5
'''
6
from elixir import *
7
from shop2020.clients.CatalogClient import CatalogClient
8
from shop2020.clients.InventoryClient import InventoryClient
9
from shop2020.clients.LogisticsClient import LogisticsClient
10
from shop2020.clients.PromotionClient import PromotionClient
11
from shop2020.clients.TransactionClient import TransactionClient
12
from shop2020.model.v1 import user
13
from shop2020.model.v1.user.impl.Converters import to_t_cart, to_t_line
14
from shop2020.model.v1.user.impl.Dataservice import Cart, Line, Address, User, \
15
    Discount, InsuranceDetails, PrivateDealUser
16
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, \
17
    DeliveryType
18
from shop2020.thriftpy.model.v1.catalog.ttypes import Item, InsurerType
19
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as TTransaction, \
20
    TransactionStatus as TTransactionStatus, Order as TOrder, LineItem as TLineItem, \
21
    OrderStatus, OrderSource
22
from shop2020.thriftpy.model.v1.user.ttypes import CartStatus, LineStatus, \
23
    ShoppingCartException, PromotionException, CartPlus
24
from shop2020.utils.Utils import to_py_date, to_java_date
25
import datetime
26
import json
27
import math
28
import traceback
29
 
30
 
31
 
32
 
33
def get_cart(userId):
34
    user = User.get_by(id=userId)
35
    return user.active_cart
36
 
37
def get_cart_by_id(id):
38
    cart = Cart.get_by(id=id)
39
    return cart
40
 
41
def create_cart():
42
    cart = Cart()
43
    cart.created_on = datetime.datetime.now()
44
    cart.updated_on = datetime.datetime.now()
45
    cart.cart_status = CartStatus.ACTIVE
46
    return cart
47
 
48
def get_carts_between(start_time, end_time, status):
49
    init_time = to_py_date(start_time)
50
    finish_time = to_py_date(end_time)
557 chandransh 51
 
17812 amit.gupta 52
    query = Cart.query
53
    if status:
54
        query = query.filter(Cart.cart_status==status)
55
    if init_time:
56
        query = query.filter(Cart.created_on >= init_time)
57
    if finish_time:
58
        query = query.filter(Cart.created_on <= finish_time)
557 chandransh 59
 
17812 amit.gupta 60
    carts = query.all()
61
    return carts
62
 
63
def get_line(item_id, cart_id, status, single):
64
    #get cart first 
65
    try:
66
        found_cart = Cart.get_by(id=cart_id)
67
    except:
68
        raise ShoppingCartException(101, "cart not found ")
69
    query = Line.query.filter_by(cart = found_cart, item_id = item_id)
557 chandransh 70
 
17812 amit.gupta 71
    if status:
72
        query = query.filter_by(line_status = status)
73
    else:
74
        query = query.filter_by(line_status = LineStatus.LINE_ACTIVE)
75
    try:
76
        if single:
77
            return query.one()
78
        else:
79
            return query.all()
80
    except:
81
        return None
82
 
83
def add_item_to_cart(cart_id, item_id, quantity, sourceId):
84
    if not item_id:
85
        raise ShoppingCartException(101, "item_id cannot be null")
557 chandransh 86
 
17812 amit.gupta 87
    if not quantity:
88
        raise ShoppingCartException(101, "quantity cannot be null")    
89
 
90
    cart = Cart.get_by(id = cart_id)    
91
    if not cart:
92
        raise ShoppingCartException(101, "no cart attached to this id" + str(cart_id))
93
    retval = ""
94
    catalog_client = CatalogClient().get_client()
95
    item = catalog_client.getItemForSource(item_id, sourceId)
96
    dataProtectionInsurer = catalog_client.getPrefferedInsurerForItem(item_id,InsurerType._NAMES_TO_VALUES.get("DATA"))
97
    item_shipping_info = catalog_client.isActive(item_id)
98
    if not item_shipping_info.isActive:
99
        return catalog_client.getItemStatusDescription(item_id)
557 chandransh 100
 
17812 amit.gupta 101
    current_time = datetime.datetime.now()
102
    cart.updated_on = current_time
103
    line = get_line(item_id, cart_id, None,True)
104
    if line:
105
        #change the quantity only
106
        line.insuranceAmount = (line.insuranceAmount/line.quantity) * quantity
107
        line.quantity = quantity
108
        line.updated_on = current_time
109
        line.dataProtectionAmount = (line.dataProtectionAmount/line.quantity) * quantity
110
    else:
111
        line = Line()
112
        line.cart = cart
113
        line.item_id = item_id
114
        line.quantity = quantity
115
        line.created_on = current_time
116
        line.updated_on = current_time
117
        line.actual_price = item.sellingPrice
118
        line.line_status = LineStatus.LINE_ACTIVE
119
        line.insurer = 0
120
        line.insuranceAmount = 0
121
        #DATA INSURER IS SET UPON ADD TO CART
122
        line.dataProtectionInsurer = dataProtectionInsurer
123
    session.commit()
124
    return retval
125
 
126
def delete_item_from_cart(cart_id, item_id):
127
    if not item_id:
128
        raise ShoppingCartException(101, "item_id cannot be null")
129
    cart = Cart.get_by(id = cart_id)
130
    if not cart:
131
        raise ShoppingCartException(101, "no cart attached to this id")
132
    item = get_line(item_id, cart_id, None, True)
133
    count_deleted_discounts = delete_discounts_for_line(item)
134
    item.delete()
135
    current_time = datetime.datetime.now()
136
    cart.updated_on = current_time
137
    session.commit()
138
 
139
def delete_discounts_for_line(item_line):
140
    count_deleted = Discount.query.filter_by(line = item_line).delete()
141
    session.commit()
142
    return count_deleted
143
 
144
def delete_discounts_from_cart(cart_id, cart = None):
145
    if cart is None:
146
        if cart_id is None:
147
            raise ShoppingCartException(101, 'cart_id and cart, both cannot be null')
148
        else:
149
            cart = Cart.get_by(id = cart_id)
3554 varun.gupt 150
 
17812 amit.gupta 151
    if cart.lines:
152
        for line in cart.lines:
153
            delete_discounts_for_line(line)
154
 
155
def save_discounts(discounts):
156
    if not discounts:
157
        raise ShoppingCartException(101, 'discounts be null')
3554 varun.gupt 158
 
17812 amit.gupta 159
    if len(discounts) > 0:
160
        cart = Cart.get_by(id = discounts[0].cart_id)
161
 
162
        for t_discount in discounts:
163
            line = Line.query.filter_by(cart = cart, item_id = t_discount.item_id).first()
164
            if line is not None:
165
                discount = Discount()
166
                discount.line = line
167
                discount.discount = t_discount.discount
168
                discount.quantity = t_discount.quantity
169
                session.commit()
170
 
171
def add_address_to_cart(cart_id, address_id):
172
    if not cart_id:
173
        raise ShoppingCartException(101, "cart id cannot be made null")
557 chandransh 174
 
17812 amit.gupta 175
    if not address_id:
176
        raise ShoppingCartException(101, "address id cannot be made null")
177
 
178
    cart = get_cart_by_id(cart_id)
179
    if not cart:
180
        raise ShoppingCartException(101, "no cart for this id")
181
 
182
    address = Address.get_by(id=address_id)
183
    if not address:
184
        raise ShoppingCartException(101, "No address for this id")
185
 
186
    cart.address_id = address_id
187
    current_time = datetime.datetime.now()
188
    #cart.updated_on = current_time
189
    session.commit()
190
 
191
def add_store_to_cart(cartId, storeId):
192
    if not cartId:
193
        raise ShoppingCartException(101, "cart id cannot be made null")
194
 
195
    cart = get_cart_by_id(cartId)
196
    if not cart:
197
        raise ShoppingCartException(101, "no cart for this id")
198
 
199
    if storeId:
200
        cart.pickupStoreId = storeId
201
    else:
202
        cart.pickupStoreId = None
5555 rajveer 203
 
17812 amit.gupta 204
    session.commit()
205
 
206
def apply_coupon_to_cart(t_cart, coupon_code):
207
    cart = get_cart_by_id(t_cart.id)
208
    if not cart:
209
        raise ShoppingCartException(101, "no cart attached to this id")
210
    pc = PromotionClient().get_client()
211
    for t_line in t_cart.lines:
212
        line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
213
        line.discounted_price = None
214
        if not pc.isGiftVoucher(coupon_code):
215
            line.discounted_price = t_line.discountedPrice
216
        #line.dealText = t_line.dealText
217
        #line.freebieId = t_line.freebieId
218
 
219
    cart.total_price = t_cart.totalPrice
220
    cart.discounted_price = t_cart.discountedPrice
221
    cart.coupon_code = coupon_code
222
    session.commit()
223
 
224
def remove_coupon(cart_id):
225
    cart = get_cart_by_id(cart_id)
226
    if not cart:
227
        raise ShoppingCartException(101, "no cart attached to this id")
228
 
229
    #Resetting discounted price of each line in cart to Null
230
    for line in cart.lines:
231
        line.discounted_price = None
232
        line.dealText = None
233
        line.freebieId = None
234
 
235
    delete_discounts_from_cart(cart.id, cart=cart)
236
    cart.discounted_price = None
237
    cart.coupon_code = None
238
    session.commit()
239
 
240
def commit_cart(cart_id, sessionSource, sessionTime, firstSource, firstSourceTime, userId, schemeId, orderSource):   
241
    cart = get_cart_by_id(cart_id)   
242
    #now we have a cart. Need to create a transaction with it
243
    totalCartVal = 0
20616 amit.gupta 244
    totalQty = 0
21003 amit.gupta 245
    itemIds = []
246
    for line in cart.lines:
247
        itemIds.append(line.item_id) 
248
    inventory_client = CatalogClient().get_client()
249
    itemsMap = inventory_client.getItems(itemIds)
17812 amit.gupta 250
    for lineObj in cart.lines:
21003 amit.gupta 251
        item = itemsMap.get(lineObj.item_id)
17812 amit.gupta 252
        totalCartVal += lineObj.actual_price * lineObj.quantity
21081 amit.gupta 253
        #if item.category in [10006, 10010]:
254
        totalQty += lineObj.quantity
17812 amit.gupta 255
    txn = TTransaction()
256
    txn.shoppingCartid = cart_id
257
    txn.customer_id = userId
258
    txn.createdOn = to_java_date(datetime.datetime.now())
259
    txn.transactionStatus = TTransactionStatus.INIT
260
    txn.statusDescription = "New Order"
261
    txn.coupon_code = cart.coupon_code
262
    txn.sessionSource = sessionSource
263
    txn.sessionStartTime = sessionTime
264
    txn.firstSource = firstSource
265
    txn.firstSourceTime = firstSourceTime
18634 manish.sha 266
    txn.payment_option = schemeId
17812 amit.gupta 267
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
20616 amit.gupta 268
    perUnitShippingCost = 0
17812 amit.gupta 269
    if privateDealUser is not None:
20616 amit.gupta 270
        if totalQty >= 5:
271
            perUnitShippingCost = 30
272
        else:
273
            perUnitShippingCost = 60
274
 
17470 manish.sha 275
 
20616 amit.gupta 276
    txn.totalShippingCost = perUnitShippingCost * totalQty
277
 
21003 amit.gupta 278
    txnOrders = create_orders(cart, userId, orderSource, perUnitShippingCost, totalCartVal, itemsMap)
20873 kshitij.so 279
#    shippingCostInOrders = 0
280
#    for order in txnOrders:
281
#        shippingCostInOrders = shippingCostInOrders + order.shippingCost
576 chandransh 282
 
20621 amit.gupta 283
    #diff = totalshippingCost - shippingCostInOrders
284
    #txnOrders[0].shippingCost = txnOrders[0].shippingCost + diff
17812 amit.gupta 285
 
286
 
287
    txn.orders = txnOrders
288
 
289
    transaction_client = TransactionClient().get_client()
290
    txn_id = transaction_client.createTransaction(txn)
291
 
292
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
293
    if privateDealUser is not None and privateDealUser.counter is not None:
294
        privateDealUser.counter.lastPurchasedOn = datetime.datetime.now()
295
    session.commit()
296
 
297
    return txn_id
298
 
21003 amit.gupta 299
def create_orders(cart, userId, orderSource, perUnitShippingCost, totalCartVal, itemsMap):
17812 amit.gupta 300
    cart_lines = cart.lines
301
    orders = []
302
    isGv = False
303
    if cart.coupon_code:
6318 rajveer 304
        try:
17812 amit.gupta 305
            pc = PromotionClient().get_client()
306
            isGv = pc.isGiftVoucher(cart.coupon_code)
6318 rajveer 307
        except:
17812 amit.gupta 308
            isGv = False
6318 rajveer 309
 
17812 amit.gupta 310
    insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
21003 amit.gupta 311
 
17812 amit.gupta 312
    for line in cart_lines:
313
        if line.line_status == LineStatus.LINE_ACTIVE:
314
            quantity_remaining_for_order = line.quantity
3554 varun.gupt 315
 
17812 amit.gupta 316
            for discount in line.discounts:
317
                #i = 0
318
                #while i < discount.quantity:
19278 amit.gupta 319
                t_line_item = create_line_item(line, line.actual_price if isGv else (line.actual_price - discount.discount), line.quantity, itemsMap.get(line.item_id))
21003 amit.gupta 320
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, discount.discount if isGv else 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails,line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, perUnitShippingCost, itemsMap.get(line.item_id))
17812 amit.gupta 321
                orders.append(t_order)
322
                    #i += 1
323
                quantity_remaining_for_order -= discount.quantity
324
 
325
            if quantity_remaining_for_order > 0:
19278 amit.gupta 326
                t_line_item = create_line_item(line, line.actual_price, quantity_remaining_for_order, itemsMap.get(line.item_id))
21005 amit.gupta 327
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails, line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, perUnitShippingCost, itemsMap.get(line.item_id))
17812 amit.gupta 328
                orders.append(t_order)
21003 amit.gupta 329
 
20873 kshitij.so 330
 
331
    wallet_amount = cart.wallet_amount
20940 kshitij.so 332
    if wallet_amount is None:
333
        wallet_amount = 0
20875 kshitij.so 334
    print "adjusting wallet_amount ***",wallet_amount
20873 kshitij.so 335
    for order in orders:
20875 kshitij.so 336
        if ((order.total_amount+ order.shippingCost - order.gvAmount) >= wallet_amount):
20873 kshitij.so 337
            order.wallet_amount = wallet_amount
338
        else:
20875 kshitij.so 339
            order.wallet_amount = order.total_amount+ order.shippingCost - order.gvAmount
20873 kshitij.so 340
 
20875 kshitij.so 341
        order.net_payable_amount = order.total_amount+ order.shippingCost - order.gvAmount - order.wallet_amount
20873 kshitij.so 342
        wallet_amount = wallet_amount - order.wallet_amount
17812 amit.gupta 343
    return orders
344
 
21003 amit.gupta 345
def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails, dataProtectionInsurer, dataProtectionAmount, orderSource, freebieId, perUnitShippingCost, item):
17812 amit.gupta 346
    user = User.get_by(id=userId)
347
    address = Address.get_by(id=address_id)
348
    t_order = TOrder()
557 chandransh 349
 
17812 amit.gupta 350
    t_order.customer_id = user.id
351
    t_order.customer_email = user.email
576 chandransh 352
 
17812 amit.gupta 353
    t_order.customer_name = address.name
354
    t_order.customer_pincode = address.pin
355
    t_order.customer_address1 = address.line_1
356
    t_order.customer_address2 = address.line_2
357
    t_order.customer_city = address.city
358
    t_order.customer_state = address.state
359
    t_order.customer_mobilenumber = address.phone
576 chandransh 360
 
17812 amit.gupta 361
    t_order.total_amount = t_line_item.total_price + insuranceAmount + dataProtectionAmount
362
    t_order.gvAmount = gvAmount
1976 varun.gupt 363
 
17812 amit.gupta 364
    t_order.total_weight = t_line_item.total_weight
365
    t_order.lineitems = [t_line_item]
576 chandransh 366
 
17812 amit.gupta 367
    t_order.status = OrderStatus.PAYMENT_PENDING
368
    t_order.statusDescription = "Payment Pending"
369
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
576 chandransh 370
 
17812 amit.gupta 371
    t_order.pickupStoreId = pickupStoreId 
372
    t_order.insuranceAmount = insuranceAmount 
373
    t_order.insurer = insurer
374
    if insuranceDetails:
375
        t_order.dob = insuranceDetails.dob
376
        t_order.guardianName = insuranceDetails.guardianName
7190 amar.kumar 377
 
17812 amit.gupta 378
    catalog_client = CatalogClient().get_client()
11669 amit.gupta 379
 
17812 amit.gupta 380
    if freebieId is None:
381
        freebie_item_id = catalog_client.getFreebieForItem(t_line_item.item_id)
382
        if freebie_item_id:
383
            t_order.freebieItemId = freebie_item_id
384
    else:
385
        freebie_item_id = None if freebieId == 0 else freebieId  
386
    t_order.source = orderSource
387
    t_order.dataProtectionInsurer = dataProtectionInsurer
388
    t_order.dataProtectionAmount = dataProtectionAmount
21081 amit.gupta 389
    #if item.category in [10006, 10010]:
390
    t_order.shippingCost = perUnitShippingCost*t_line_item.quantity
391
    #else:
392
    #    t_order.shippingCost = 0
17812 amit.gupta 393
    return t_order
576 chandransh 394
 
19278 amit.gupta 395
def create_line_item(line, final_price, quantity=1, item=None):
396
    if item is None:
397
        inventory_client = CatalogClient().get_client()
398
        item = inventory_client.getItem(line.item_id)
17812 amit.gupta 399
    t_line_item = TLineItem()
400
    t_line_item.productGroup = item.productGroup
401
    t_line_item.brand = item.brand
402
    t_line_item.model_number = item.modelNumber
403
    if item.color is None or item.color == "NA":
404
        t_line_item.color = ""
405
    else:
406
        t_line_item.color = item.color
407
    t_line_item.model_name = item.modelName
20847 amit.gupta 408
    t_line_item.model_name = item.modelName
409
    t_line_item.mrp = item.mrp
17812 amit.gupta 410
    t_line_item.extra_info = item.featureDescription
411
    t_line_item.item_id = item.id
412
    t_line_item.quantity = quantity
1983 varun.gupt 413
 
17812 amit.gupta 414
    t_line_item.unit_price = final_price
415
    t_line_item.total_price = final_price * quantity
416
 
417
    t_line_item.unit_weight = item.weight
418
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
419
    if line.dealText is None:
420
        t_line_item.dealText = item.bestDealText
421
    elif line.dealText == '':
422
        t_line_item.dealText = None
423
    else:
424
        t_line_item.dealText = line.dealText
11915 amit.gupta 425
 
17812 amit.gupta 426
    if item.warrantyPeriod:
427
        #Computing Manufacturer Warranty expiry date
428
        today = datetime.date.today()
429
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
430
        expiry_month = (today.month + item.warrantyPeriod) % 12
4312 rajveer 431
 
17812 amit.gupta 432
        try:
433
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
434
        except ValueError:
4295 varun.gupt 435
            try:
17812 amit.gupta 436
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
4295 varun.gupt 437
            except ValueError:
4312 rajveer 438
                try:
17812 amit.gupta 439
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
4312 rajveer 440
                except ValueError:
17812 amit.gupta 441
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
4312 rajveer 442
 
17812 amit.gupta 443
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
4312 rajveer 444
 
17812 amit.gupta 445
    return t_line_item
576 chandransh 446
 
17812 amit.gupta 447
def validate_cart(cartId, sourceId, couponCode):
448
    inventory_client = CatalogClient().get_client()
449
    logistics_client = LogisticsClient().get_client()
450
    promotion_client = PromotionClient().get_client()
451
    retval = ""
452
    emival = ""
453
    # No need to validate duplicate items since there are only two ways
454
    # to add items to a cart and both of them check whether the item being
455
    # added is a duplicate of an already existing item.
456
    cart = Cart.get_by(id=cartId)
457
    cart_lines = cart.lines
458
    customer_pincode = None
459
    current_time = datetime.datetime.now()
460
    if cart.pickupStoreId :
461
        store = logistics_client.getPickupStore(cart.pickupStoreId)
462
        customer_pincode = store.pin
463
    if cart.address_id != None and customer_pincode == None:
464
        address = Address.get_by(id=cart.address_id)
465
        customer_pincode = address.pin
466
 
467
    user = User.get_by(active_cart_id = cartId)
13136 amit.gupta 468
 
17812 amit.gupta 469
    dealItems = []
18418 kshitij.so 470
    bulkPricingMap ={}
471
    bulkPricingItems =[]
17812 amit.gupta 472
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
473
    if privateDealUser is not None and privateDealUser.isActive:
474
        itemIds = [cartLine.item_id for cartLine in cart.lines]
475
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
476
        dealItems = deals.keys()
18418 kshitij.so 477
        bulkPricingMap = inventory_client.getBulkPricingForItems(itemIds)
478
        bulkPricingItems = bulkPricingMap.keys() 
17812 amit.gupta 479
 
480
    if not customer_pincode:
481
        default_address_id = user.default_address_id
482
        if default_address_id:
483
            address = Address.get_by(id = default_address_id)
484
            customer_pincode = address.pin
485
    if not customer_pincode:
486
        #FIXME should not be hard coded. May be we can pick from config server.
487
        customer_pincode = "110001"
488
    cart.total_price = 0
489
    for line in cart_lines:
490
        old_estimate = line.estimate
491
        item_id = line.item_id
492
        item = inventory_client.getItemForSource(item_id, sourceId)
493
 
494
        item_shipping_info = inventory_client.isActive(item_id) 
495
        if item_shipping_info.isActive:
496
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
497
                line.quantity = 1
498
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
18418 kshitij.so 499
            bulkPrice = None
500
            if item_id in bulkPricingItems:
501
                #Check quantity qualifies or not
502
                bulkPricingList = bulkPricingMap.get(item_id)
503
                bulkPricingList = sorted(bulkPricingList, key=lambda x: x.quantity, reverse=False)
504
                for pricingItems in bulkPricingList:
505
                    if pricingItems.quantity <= line.quantity:
506
                        bulkPrice = pricingItems
507
                    else:
508
                        break
509
 
17812 amit.gupta 510
 
511
            if item_id in dealItems:
18418 kshitij.so 512
                if bulkPrice is None:
513
                    line.actual_price = deals[item_id].dealPrice
514
                else:
515
                    line.actual_price = bulkPrice.price
17812 amit.gupta 516
                if deals[item_id].dealTextOption==0:
517
                    line.dealText = ''
518
                if deals[item_id].dealTextOption==2:
519
                    line.dealText =  deals[item_id].dealText
520
 
521
                if deals[item_id].dealFreebieOption==0:
522
                    line.freebieId = 0
523
                if deals[item_id].dealFreebieOption==2:
524
                    line.freebieId =  deals[item_id].dealFreebieItemId
525
 
526
            else:
18418 kshitij.so 527
                if bulkPrice is None:
528
                    line.actual_price = item.sellingPrice
529
                else:
530
                    line.actual_price = bulkPrice.price 
17812 amit.gupta 531
                line.dealText = None
532
                line.freebieId = None
533
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
534
            try:
535
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
536
            except LogisticsServiceException:
537
                item_delivery_estimate = -1
538
                #TODO Use the exception clause to set the retval appropriately
539
            except :
540
                item_delivery_estimate = -1
541
 
542
            if item_delivery_estimate !=-1:
543
                inv_client = InventoryClient().get_client()
544
                itemAvailability = None
17803 amit.gupta 545
                try:
17812 amit.gupta 546
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
547
                except:
548
                    pass
549
 
550
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
551
                if itemAvailability is not None:
552
                    billingWarehouse = None
12893 manish.sha 553
                    try:
17812 amit.gupta 554
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
12893 manish.sha 555
                    except:
556
                        pass
12904 manish.sha 557
 
17812 amit.gupta 558
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
559
                    if billingWarehouse is not None:
560
                        estimateVal = None
561
                        if not logistics_client.isAlive() :
562
                            logistics_client = LogisticsClient().get_client()
12893 manish.sha 563
                        try:
17812 amit.gupta 564
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
565
                            if estimateVal ==-1:
566
                                item_delivery_estimate =-1
12893 manish.sha 567
                        except:
568
                            pass
17812 amit.gupta 569
                        print 'estimateVal Value ', estimateVal
570
            if old_estimate != item_delivery_estimate:
571
                line.estimate = item_delivery_estimate
572
                cart.updated_on = current_time
573
        else:
574
            Discount.query.filter(Discount.line==line).delete()
575
            line.delete()
576
    if cart.checked_out_on is not None:
577
        if cart.updated_on > cart.checked_out_on:
578
            cart.checked_out_on = None
579
    session.commit()
1976 varun.gupt 580
 
17812 amit.gupta 581
    if cart.coupon_code is not None:
582
        try:
583
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
584
            if updated_cart.message is not None:
585
                emival = updated_cart.message
586
        except PromotionException as ex:
587
            remove_coupon(cart.id)
588
            #retval = ex.message
589
    session.commit()
13136 amit.gupta 590
 
17812 amit.gupta 591
    cart = Cart.get_by(id=cartId)
592
    cart_lines = cart.lines
593
    map_lines = {}
13136 amit.gupta 594
 
17812 amit.gupta 595
    insurerFlag = False
596
    for line in cart_lines:
597
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
598
            line_map = {}
599
            line_map['insurer'] = line.insurer
600
            line_map['dpinsurer'] = line.dataProtectionInsurer
601
            line_map['amount'] = line.discounted_price if line.discounted_price else line.actual_price
602
            line_map['quantity'] = line.quantity
603
            insurerFlag = True
604
            map_lines[line.item_id] = line_map
605
 
606
    if insurerFlag:
607
        map_lines = inventory_client.checkServices(map_lines)
608
        for line in cart_lines :
609
            if map_lines.has_key(line.item_id):
610
                line_map = map_lines[line.item_id]
611
                if line_map['insurer'] > 0:
612
                    if cart.discounted_price:
613
                        cart.discounted_price = cart.discounted_price + line_map['insureramount']
614
                    line.insurer = line_map['insurer']
615
                    line.insuranceAmount = line_map['insureramount']
616
                    cart.total_price = cart.total_price + line_map['insureramount']
617
                if line_map['dpinsurer'] > 0:
618
                    if cart.discounted_price:
619
                        cart.discounted_price = cart.discounted_price + line_map['dpinsureramount']
620
                    line.dataProtectionInsurer = line_map['dpinsurer']
621
                    line.dataProtectionAmount = line_map['dpinsureramount']
622
                    cart.total_price = cart.total_price + line_map['dpinsureramount']
623
                line.updated_on = datetime.datetime.now()
17803 amit.gupta 624
        cart.updated_on = datetime.datetime.now()
13142 amit.gupta 625
        session.commit()
17812 amit.gupta 626
    session.close()
627
    return [retval, emival]
628
 
629
def merge_cart(fromCartId, toCartId):
630
    fromCart = Cart.get_by(id=fromCartId)
631
    toCart = Cart.get_by(id=toCartId)
557 chandransh 632
 
17812 amit.gupta 633
    old_lines = fromCart.lines
634
    new_lines = toCart.lines
557 chandransh 635
 
17812 amit.gupta 636
    for line in old_lines:
637
        for discount in line.discounts:
638
            discount.delete()
639
    session.commit()
640
 
641
    for line in old_lines:
642
        flag = True
643
        for new_line in new_lines:
644
            if line.item_id == new_line.item_id:
645
                flag = False
646
 
647
        if flag:
648
            line.cart_id = toCartId
649
        else:
650
            line.delete()
5345 rajveer 651
 
17812 amit.gupta 652
    if toCart.coupon_code is None:
653
        toCart.coupon_code = fromCart.coupon_code
2019 varun.gupt 654
 
17812 amit.gupta 655
    toCart.updated_on = datetime.datetime.now()
656
    fromCart.expired_on = datetime.datetime.now()
657
    fromCart.cart_status = CartStatus.INACTIVE
658
    session.commit()
659
 
660
def check_out(cartId):
661
    if cartId is None:
662
        raise ShoppingCartException(101, "Cart id not specified")
663
    cart = Cart.get_by(id = cartId)
664
    if cart is None:
665
        raise ShoppingCartException(102, "The specified cart couldn't be found")
666
    cart.checked_out_on = datetime.datetime.now()
667
    session.commit()
668
    return True
669
 
670
def reset_cart(cartId, items):
671
    if cartId is None:
672
        raise ShoppingCartException(101, "Cart id not specified")
673
    for item_id, quantity in items.iteritems():
674
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
675
        if line is not None:
676
            delete_discounts_for_line(line)
677
            line.discounted_price = None
678
            line.quantity = line.quantity - quantity
679
            if line.quantity == 0:
680
                line.delete()
681
    cart = Cart.get_by(id=cartId)
682
    cart.updated_on = datetime.datetime.now()
683
    cart.checked_out_on = None
1976 varun.gupt 684
 
17812 amit.gupta 685
    # Removing Coupon
686
    cart.total_price = None
687
    cart.discounted_price = None
688
    cart.coupon_code = None
20873 kshitij.so 689
    cart.wallet_amount = 0.0
17812 amit.gupta 690
 
691
    session.commit()
692
    return True
693
 
694
def get_carts_with_coupon_count(coupon_code):
695
    return Cart.query.filter_by(coupon_code = coupon_code).count()
696
 
697
def show_cod_option(cartId, sourceId, pincode):
698
    cart = Cart.get_by(id = cartId)
699
    cod_option = True
700
    logistics_client = LogisticsClient().get_client()
701
    if cart:
20981 amit.gupta 702
        itemIds = []
703
        for line in cart.lines:
704
            itemIds.append(line.item_id)
21081 amit.gupta 705
#        catalog_client = CatalogClient().get_client()
706
#        items = catalog_client.getItems(itemIds).values()
707
#        for item in items:
708
#            if item.category not in [10006, 10010]:
709
#                return False
20981 amit.gupta 710
 
17812 amit.gupta 711
        if cart.coupon_code:
712
            promotion_client = PromotionClient().get_client()
713
            cod_option = promotion_client.isCodApplicable(to_t_cart(cart))
5351 varun.gupt 714
 
17812 amit.gupta 715
        if cod_option and cart.lines:
716
            for line in cart.lines:
18844 amit.gupta 717
                try:
718
                    logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
719
                    if not logistics_info.codAllowed:
720
                        cod_option = False
721
                        break
722
                except:
723
                    pass    
21081 amit.gupta 724
            if cart.total_price > 150000:
17812 amit.gupta 725
                cod_option = False
726
    return cod_option
727
 
728
def get_products_added_to_cart(startDate, endDate):
729
    lines = session.query(Line.item_id).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).all()
730
    datas = []
731
    for line in lines:
732
        datas.append(line[0])
733
    return datas
734
 
735
def insure_item(itemId, cartId, toInsure, insurerType):
736
    cart = Cart.get_by(id = cartId)
737
    line = None
738
    for cartLine in cart.lines:
739
        if(cartLine.item_id == itemId):
740
            line = cartLine
741
            break
11655 amit.gupta 742
 
17812 amit.gupta 743
    if not line:
744
        print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
745
        return False
11655 amit.gupta 746
 
17812 amit.gupta 747
    try:
748
        if toInsure:
749
            csc = CatalogClient().get_client()
750
            item = csc.getItem(itemId)
751
            insurerId = csc.getPrefferedInsurerForItem(itemId,insurerType)
752
            insuranceAmount = csc.getInsuranceAmount(itemId, line.discounted_price if line.discounted_price else line.actual_price, insurerId, line.quantity)
753
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
9299 kshitij.so 754
                if cart.discounted_price:
17812 amit.gupta 755
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount + insuranceAmount
756
                line.insurer = insurerId
757
                line.insuranceAmount = insuranceAmount
758
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
759
                if cart.discounted_price:
760
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount + insuranceAmount
761
                line.dataProtectionInsurer = insurerId
762
                line.dataProtectionAmount = insuranceAmount
763
            cart.total_price = cart.total_price + insuranceAmount
764
        else:
765
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
766
                cart.total_price = cart.total_price - line.insuranceAmount
767
                if cart.discounted_price:
768
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount
769
                line.insurer = 0
770
                line.insuranceAmount = 0
771
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
772
                cart.total_price = cart.total_price - line.dataProtectionAmount
773
                if cart.discounted_price:
774
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount
775
                line.dataProtectionInsurer = 0
776
                line.dataProtectionAmount = 0
777
        line.updated_on = datetime.datetime.now()
778
        cart.updated_on = datetime.datetime.now()
779
        session.commit()
780
    except:
781
        print("Error : Unable to insure")
782
        print("insurerId : " + str(insurerId) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
783
        return False
6903 anupam.sin 784
 
17812 amit.gupta 785
    return True
786
 
787
def cancel_insurance(cartId):
788
    try:
789
        cart = Cart.get_by(id = cartId)
790
        for cartLine in cart.lines:
791
            cart.total_price = cart.total_price - cartLine.insuranceAmount
792
            if cart.discounted_price:
793
                cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
794
            cartLine.insurer = 0
795
            cartLine.insuranceAmount = 0
796
            cartLine.updated_on = datetime.datetime.now()
797
        cart.updated_on = datetime.datetime.now()
798
        session.commit()
799
    except:
800
        print("Error : Unable to cancel insurance for cartId :" + str(cartId))
801
        return False
6903 anupam.sin 802
 
17812 amit.gupta 803
    return True
804
 
805
def store_insurance_specific_details(addressId, dob, guardianName):
806
    try:
807
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
808
        if insuranceDetails is None :
809
            insuranceDetails = InsuranceDetails()
810
        insuranceDetails.addressId = addressId
811
        insuranceDetails.dob = dob
812
        insuranceDetails.guardianName = guardianName
813
        session.commit()
814
    except:
815
        print("Error : Unable to store insurance details for addressId : " + str(addressId))
816
        return False
817
    return True
818
 
819
def is_insurance_detail_present(addressId):
820
    try:
821
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
822
        if insuranceDetails is None :
6903 anupam.sin 823
            return False
17812 amit.gupta 824
    except:
825
        print("Error : Unable to get insurance details for addressId : " + str(addressId))
826
        return False
827
    return True
828
 
829
 
830
def add_items_to_cart(cartId, itemQty, couponCode=None):
831
    try: 
832
        found_cart = Cart.get_by(id=cartId)
833
        itemQtyMap = {}
834
        current_time = datetime.datetime.now()
835
        for itemqty in itemQty:
836
            itemQtyMap[itemqty.itemId] = itemqty.qty 
837
 
838
        if found_cart.lines:
839
            for line in found_cart.lines:
840
                if itemQtyMap.has_key(line.item_id):
19161 amit.gupta 841
                    Discount.query.filter(Discount.line==line).delete()
17812 amit.gupta 842
                    line.delete()
843
        for itemId,qty in itemQtyMap.iteritems():
844
            #This condition will ensure that cart is only persisted with non-zero quantities.
845
            if qty==0:
846
                continue
847
            line = Line()
848
            line.cart = found_cart
849
            line.item_id = itemId
850
            line.quantity = qty
851
            line.created_on = current_time
852
            line.updated_on = current_time
853
            line.line_status = LineStatus.LINE_ACTIVE
854
            line.insurer = 0
855
            line.insuranceAmount = 0
856
        if couponCode:
857
            found_cart.coupon_code = couponCode
858
        else:
859
            found_cart.coupon_code = None
860
        session.commit()
17782 amit.gupta 861
        return True
17812 amit.gupta 862
    except:
863
        traceback.print_exc()
864
        return False
865
 
17782 amit.gupta 866
 
20981 amit.gupta 867
def validate_cart_new(cartId, customer_pincode, sourceId):
17782 amit.gupta 868
 
17812 amit.gupta 869
    inventory_client = CatalogClient().get_client()
870
    logistics_client = LogisticsClient().get_client()
871
    promotion_client = PromotionClient().get_client()
872
    # No need to validate duplicate items since there are only two ways
873
    # to add items to a cart and both of them check whether the item being
874
    # added is a duplicate of an already existing item.
875
    cart = Cart.get_by(id=cartId)
876
    cart_lines = cart.lines
877
    current_time = datetime.datetime.now()
878
 
879
    user = User.get_by(active_cart_id = cartId)
880
    responseMap = {}
881
    totalQty = 0
20990 amit.gupta 882
    nonAccessoryQuantity = 0
17812 amit.gupta 883
    totalAmount = 0 
884
    shippingCharges=0
885
    cartMessages=[]
886
    cartItems = []
887
    dealItems = []
18418 kshitij.so 888
    bulkPricingMap ={}
889
    bulkPricingItems =[]
17782 amit.gupta 890
 
17812 amit.gupta 891
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
892
    itemIds = [cartLine.item_id for cartLine in cart.lines]
893
    if privateDealUser is not None and privateDealUser.isActive:
894
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
895
        dealItems = deals.keys()
18418 kshitij.so 896
        bulkPricingMap = inventory_client.getBulkPricingForItems(itemIds)
897
        bulkPricingItems = bulkPricingMap.keys() 
17812 amit.gupta 898
 
899
    cart.total_price = 0
900
    itemsMap = inventory_client.getItems(itemIds)
17789 amit.gupta 901
 
17812 amit.gupta 902
    cartMessageChanged = 0
903
    cartMessageOOS = 0
904
    cartMessageUndeliverable = 0
17789 amit.gupta 905
 
18521 kshitij.so 906
 
907
 
17812 amit.gupta 908
    for line in cart_lines:
17865 amit.gupta 909
        itemQuantityChanged=False
17812 amit.gupta 910
        cartItem={}
18418 kshitij.so 911
        tempBulkItemList = []
17782 amit.gupta 912
 
17812 amit.gupta 913
        old_estimate = line.estimate
914
        item_id = line.item_id
915
        item = itemsMap.get(item_id)
18381 amit.gupta 916
        if item.itemStatus==0:
18375 amit.gupta 917
            Discount.query.filter(Discount.line==line).delete()
918
            line.delete()
919
            continue
17812 amit.gupta 920
        cartItem['itemId']=line.item_id
921
        cartItem['quantity']=0
17813 amit.gupta 922
        cartItem['cartItemMessages']=[]
923
        cartItemMessages = cartItem['cartItemMessages']
17812 amit.gupta 924
        cartItem['color'] = item.color
925
        cartItem['catalogItemId'] = item.catalogItemId
18006 manish.sha 926
        cartItem['packQuantity'] = item.packQuantity
18431 kshitij.so 927
        cartItem['minBuyQuantity'] = item.minimumBuyQuantity
928
        cartItem['quantityStep'] = item.quantityStep
18418 kshitij.so 929
        cartItem['bulkPricing'] = tempBulkItemList
18521 kshitij.so 930
 
931
        item_shipping_info = inventory_client.isActive(item_id) 
932
        if item_shipping_info.isActive:
933
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
934
                line.quantity = item_shipping_info.quantity
935
                itemQuantityChanged=True
18627 kshitij.so 936
            cartItem['maxQuantity'] = min(item_shipping_info.quantity,100)
18521 kshitij.so 937
            if item.maximumBuyQuantity is not None and item.maximumBuyQuantity >0:
938
                cartItem['maxQuantity'] = min(item_shipping_info.quantity, item.maximumBuyQuantity)
18534 kshitij.so 939
        else:
940
            cartItem['maxQuantity'] =0
941
 
18521 kshitij.so 942
 
943
        if item_shipping_info.quantity < cartItem['minBuyQuantity']:
944
            cartItem['minBuyQuantity'] = item_shipping_info.quantity 
945
 
946
        if line.quantity < cartItem['minBuyQuantity']:
947
            itemQuantityChanged=True
948
            line.quantity = cartItem['minBuyQuantity']
949
 
950
        if line.quantity > cartItem['maxQuantity']:
951
            itemQuantityChanged=True
952
            line.quantity = cartItem['maxQuantity']
18523 kshitij.so 953
 
954
        cartItem['quantity'] = line.quantity
955
 
18418 kshitij.so 956
        bulkPrice = None
18482 kshitij.so 957
        singleUnitPricing = False
18418 kshitij.so 958
        if item_id in bulkPricingItems:
959
            #Check quantity qualifies or not
960
            bulkPricingList = bulkPricingMap.get(item_id)
961
            bulkPricingList = sorted(bulkPricingList, key=lambda x: x.quantity, reverse=False)
962
            for pricingItems in bulkPricingList:
18482 kshitij.so 963
                if pricingItems.quantity ==1:
964
                    singleUnitPricing = True
18418 kshitij.so 965
                if pricingItems.quantity <= line.quantity:
966
                    bulkPrice = pricingItems
18482 kshitij.so 967
                tempBulkItemList.append({'quantity':pricingItems.quantity,'price':pricingItems.price})
18418 kshitij.so 968
 
17903 amit.gupta 969
        if item_id in dealItems:
18482 kshitij.so 970
            if not singleUnitPricing and item_id in bulkPricingItems:
971
                tempBulkItemList.append({'quantity':1,'price':deals[item_id].dealPrice})
18418 kshitij.so 972
            if bulkPrice is None:
973
                line.actual_price = deals[item_id].dealPrice
974
            else:
975
                line.actual_price = bulkPrice.price
17903 amit.gupta 976
            if deals[item_id].dealTextOption==0:
977
                line.dealText = ''
978
            if deals[item_id].dealTextOption==2:
979
                line.dealText = deals[item_id].dealText
980
 
981
            if deals[item_id].dealFreebieOption==0:
982
                line.freebieId = 0
983
            if deals[item_id].dealFreebieOption==2:
984
                line.freebieId =  deals[item_id].dealFreebieItemId
985
            cartItem['dealText'] = line.dealText
986
        else:
18482 kshitij.so 987
            if not singleUnitPricing and item_id in bulkPricingItems:
988
                tempBulkItemList.append({'quantity':1,'price':item.sellingPrice})
18418 kshitij.so 989
            if bulkPrice is None:
990
                line.actual_price = item.sellingPrice
991
            else:
992
                line.actual_price = bulkPrice.price
17903 amit.gupta 993
            if item.bestDealText:
994
                cartItem['dealText'] = item.bestDealText
995
            line.dealText = None
996
            line.freebieId = None
997
        cartItem['sellingPrice'] = line.actual_price
998
 
18539 kshitij.so 999
        toRemove = []
18536 kshitij.so 1000
        for dictbulkPricing in cartItem['bulkPricing']:
1001
            if dictbulkPricing['quantity'] < cartItem['minBuyQuantity'] or dictbulkPricing['quantity'] > cartItem['maxQuantity']:
18539 kshitij.so 1002
                toRemove.append(dictbulkPricing)
1003
        for removePricing in toRemove:
1004
            cartItem['bulkPricing'].remove(removePricing)
18541 kshitij.so 1005
        cartItem['bulkPricing'] = sorted(cartItem['bulkPricing'], key=lambda k: k['quantity'],reverse=False)
18536 kshitij.so 1006
 
17812 amit.gupta 1007
        if item_shipping_info.isActive:
1008
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
1009
            try:
1010
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
1011
            except LogisticsServiceException:
1012
                item_delivery_estimate = -1
1013
                #TODO Use the exception clause to set the retval appropriately
1014
            except :
1015
                item_delivery_estimate = -1
17782 amit.gupta 1016
 
17812 amit.gupta 1017
            if item_delivery_estimate !=-1:
1018
                inv_client = InventoryClient().get_client()
1019
                itemAvailability = None
1020
                try:
1021
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
1022
                except:
1023
                    pass
17803 amit.gupta 1024
 
17812 amit.gupta 1025
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
1026
                if itemAvailability is not None:
1027
                    billingWarehouse = None
17782 amit.gupta 1028
                    try:
17812 amit.gupta 1029
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
17782 amit.gupta 1030
                    except:
1031
                        pass
1032
 
17812 amit.gupta 1033
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
1034
                    if billingWarehouse is not None:
1035
                        estimateVal = None
1036
                        if not logistics_client.isAlive() :
1037
                            logistics_client = LogisticsClient().get_client()
17782 amit.gupta 1038
                        try:
17812 amit.gupta 1039
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
1040
                            if estimateVal ==-1:
1041
                                item_delivery_estimate =-1
17782 amit.gupta 1042
                        except:
1043
                            pass
17812 amit.gupta 1044
                        print 'estimateVal Value ', estimateVal
1045
            cartItem['estimate'] = item_delivery_estimate
1046
            if item_delivery_estimate == -1:
18951 amit.gupta 1047
                Discount.query.filter(Discount.line==line).delete()
1048
                line.delete()
17782 amit.gupta 1049
                cartItem['quantity'] = 0
17812 amit.gupta 1050
                cartMessageUndeliverable += 1
17836 amit.gupta 1051
                cartItemMessages.append({"type":"danger", "messageText":"Undeliverable"})
17865 amit.gupta 1052
            elif itemQuantityChanged:
1053
                cartMessageChanged += 1
1054
                cartItemMessages.append({"type":"danger", "messageText":"Only " + str(item_shipping_info.quantity) + " available"})
17812 amit.gupta 1055
            if old_estimate != item_delivery_estimate:
1056
                line.estimate = item_delivery_estimate
1057
                cart.updated_on = current_time
17903 amit.gupta 1058
            totalAmount += line.actual_price * cartItem['quantity']
17812 amit.gupta 1059
        else:
1060
            cartItem['quantity'] = 0
1061
            cartMessageOOS += 1
1062
            cartItemMessages.append({"type":"danger", "messageText":"Out of Stock"})
1063
            Discount.query.filter(Discount.line==line).delete()
1064
            line.delete()
1065
        totalQty += cartItem['quantity']
20990 amit.gupta 1066
        if item.category in [10006, 10010]:
1067
            nonAccessoryQuantity += cartItem['quantity']
17812 amit.gupta 1068
        if cartItemMessages:
1069
            cartItems.insert(0, cartItem)
1070
        else:
1071
            cartItems.append(cartItem)
1072
    if cart.checked_out_on is not None:
1073
        if cart.updated_on > cart.checked_out_on:
1074
            cart.checked_out_on = None
1075
    session.commit()
1076
 
1077
    if cart.coupon_code is not None:
1078
        try:
1079
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
1080
            if updated_cart.message is not None:
1081
                emival = updated_cart.message
1082
        except PromotionException as ex:
1083
            remove_coupon(cart.id)
1084
            #retval = ex.message
1085
    session.commit()
1086
 
1087
    cart = Cart.get_by(id=cartId)
1088
    cart_lines = cart.lines
1089
    insurerFlag = False
1090
    for line in cart_lines:
1091
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
1092
            line.insurer = 0
1093
            line.insuranceAmount = 0 
1094
            line.dataProtectionInsurer = 0
1095
            line.dataProtectionAmount = 0
1096
            insurerFlag = True
17782 amit.gupta 1097
 
17812 amit.gupta 1098
    if insurerFlag:
1099
        cart.updated_on = datetime.datetime.now()
17782 amit.gupta 1100
        session.commit()
17812 amit.gupta 1101
    session.close()
1102
    responseMap['totalQty']= totalQty
1103
    responseMap['totalAmount']= totalAmount
20990 amit.gupta 1104
 
1105
    #Levy charges for non Accessories
21083 amit.gupta 1106
    if totalQty >= 5:
21084 amit.gupta 1107
        shippingCharges = totalQty*30
20616 amit.gupta 1108
    else:
21084 amit.gupta 1109
        shippingCharges = totalQty*60
20990 amit.gupta 1110
 
1111
    hasAccessories = False
21083 amit.gupta 1112
 
21000 amit.gupta 1113
    #No charge for accessories
20990 amit.gupta 1114
    if totalQty > nonAccessoryQuantity:
1115
        hasAccessories = True
1116
 
21000 amit.gupta 1117
    responseMap['cartMessages']= cartMessages
1118
    responseMap['cartItems']= cartItems
1119
    responseMap['pincode']= customer_pincode
20990 amit.gupta 1120
    responseMap['hasAccessories']= hasAccessories  
17812 amit.gupta 1121
    responseMap['shippingCharge']=shippingCharges
1122
    responseMap['cartMessageChanged'] = cartMessageChanged
1123
    responseMap['cartMessageOOS'] = cartMessageOOS
1124
    responseMap['cartMessageUndeliverable'] = cartMessageUndeliverable
21000 amit.gupta 1125
    responseMap['nonAccessoryQuantity'] = nonAccessoryQuantity
17812 amit.gupta 1126
    return json.dumps(responseMap)
1127
 
1128
 
1129
def validate_cart_plus(cart_id, source_id, couponCode):
1130
    try:
1131
        cart_messages = validate_cart(cart_id, source_id, couponCode)
1132
        found_cart = Cart.get_by(id=cart_id)
1133
        pincode = "110001"
1134
        default_address_id = User.get_by(active_cart_id = cart_id).default_address_id
11598 amit.gupta 1135
 
17812 amit.gupta 1136
        default_address = None
1137
        if found_cart.address_id is not None and found_cart.address_id > 0:
1138
            pincode = Address.get_by(id=found_cart.address_id).pin
1139
        elif default_address_id is not None:
1140
            default_address = Address.get_by(id = default_address_id) 
1141
            pincode = default_address.pin
11592 amit.gupta 1142
 
18418 kshitij.so 1143
        needInsuranceInfo = False
17812 amit.gupta 1144
        if default_address_id is not None:
1145
            for line in found_cart.lines:
1146
                if line.insurer > 0:
18418 kshitij.so 1147
                    needInsuranceInfo = not is_insurance_detail_present(default_address_id)
17812 amit.gupta 1148
                    break
1149
        cartPlus = CartPlus()
1150
        cartPlus.cart = to_t_cart(found_cart)
1151
        cartPlus.pinCode = pincode
1152
        cartPlus.validateCartMessages = cart_messages
18418 kshitij.so 1153
        cartPlus.needInsuranceInfo = needInsuranceInfo
17812 amit.gupta 1154
        return cartPlus
1155
    finally:
1156
        close_session()
1157
 
1158
def close_session():
1159
    if session.is_active:
1160
        print "session is active. closing it."
18844 amit.gupta 1161
        session.close()
1162
 
20873 kshitij.so 1163
 
1164
def set_wallet_amount_in_cart(cartId, wallet_amount):
1165
    cart = Cart.get_by(id = cartId)
1166
    if cart is None:
1167
        raise ShoppingCartException(102, "The specified cart couldn't be found")
1168
    if wallet_amount < 0:
1169
        raise ShoppingCartException(103, "Wallet amount is negative")
1170
    cart.wallet_amount = wallet_amount
1171
    session.commit()
1172
    return True