Subversion Repositories SmartDukaan

Rev

Rev 19282 | Rev 20621 | 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
244
    totalshippingCost = 0
20616 amit.gupta 245
    totalQty = 0
17812 amit.gupta 246
    for lineObj in cart.lines:
247
        totalCartVal += lineObj.actual_price * lineObj.quantity
20616 amit.gupta 248
        totalQty += lineObj.quantity
17812 amit.gupta 249
    txn = TTransaction()
250
    txn.shoppingCartid = cart_id
251
    txn.customer_id = userId
252
    txn.createdOn = to_java_date(datetime.datetime.now())
253
    txn.transactionStatus = TTransactionStatus.INIT
254
    txn.statusDescription = "New Order"
255
    txn.coupon_code = cart.coupon_code
256
    txn.sessionSource = sessionSource
257
    txn.sessionStartTime = sessionTime
258
    txn.firstSource = firstSource
259
    txn.firstSourceTime = firstSourceTime
18634 manish.sha 260
    txn.payment_option = schemeId
17812 amit.gupta 261
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
20616 amit.gupta 262
    perUnitShippingCost = 0
17812 amit.gupta 263
    if privateDealUser is not None:
20616 amit.gupta 264
        if totalQty >= 5:
265
            perUnitShippingCost = 30
266
        else:
267
            perUnitShippingCost = 60
268
 
17470 manish.sha 269
 
20616 amit.gupta 270
    txn.totalShippingCost = perUnitShippingCost * totalQty
271
 
272
    txnOrders = create_orders(cart, userId, orderSource, perUnitShippingCost, totalCartVal)
17812 amit.gupta 273
    shippingCostInOrders = 0
274
    for order in txnOrders:
275
        shippingCostInOrders = shippingCostInOrders + order.shippingCost
576 chandransh 276
 
17812 amit.gupta 277
    diff = totalshippingCost - shippingCostInOrders
18061 manish.sha 278
    txnOrders[0].shippingCost = txnOrders[0].shippingCost + diff
17812 amit.gupta 279
 
280
 
281
    txn.orders = txnOrders
282
 
283
    transaction_client = TransactionClient().get_client()
284
    txn_id = transaction_client.createTransaction(txn)
285
 
286
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
287
    if privateDealUser is not None and privateDealUser.counter is not None:
288
        privateDealUser.counter.lastPurchasedOn = datetime.datetime.now()
289
    session.commit()
290
 
291
    return txn_id
292
 
20616 amit.gupta 293
def create_orders(cart, userId, orderSource, perUnitShippingCost, totalCartVal):
17812 amit.gupta 294
    cart_lines = cart.lines
295
    orders = []
296
    isGv = False
297
    if cart.coupon_code:
6318 rajveer 298
        try:
17812 amit.gupta 299
            pc = PromotionClient().get_client()
300
            isGv = pc.isGiftVoucher(cart.coupon_code)
6318 rajveer 301
        except:
17812 amit.gupta 302
            isGv = False
6318 rajveer 303
 
17812 amit.gupta 304
    insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
19278 amit.gupta 305
    itemIds = []
17812 amit.gupta 306
    for line in cart_lines:
19278 amit.gupta 307
        itemIds.append(line.item_id) 
308
    inventory_client = CatalogClient().get_client()
19282 amit.gupta 309
    itemsMap = inventory_client.getItems(itemIds)
19278 amit.gupta 310
    for line in cart_lines:
17812 amit.gupta 311
        if line.line_status == LineStatus.LINE_ACTIVE:
312
            quantity_remaining_for_order = line.quantity
3554 varun.gupt 313
 
17812 amit.gupta 314
            for discount in line.discounts:
315
                #i = 0
316
                #while i < discount.quantity:
19278 amit.gupta 317
                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))
20616 amit.gupta 318
                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, totalCartVal)
17812 amit.gupta 319
                orders.append(t_order)
320
                    #i += 1
321
                quantity_remaining_for_order -= discount.quantity
322
 
323
            if quantity_remaining_for_order > 0:
19278 amit.gupta 324
                t_line_item = create_line_item(line, line.actual_price, quantity_remaining_for_order, itemsMap.get(line.item_id))
17812 amit.gupta 325
                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, totalshippingCost, totalCartVal)
326
                orders.append(t_order)
327
            '''
328
            i = 0
329
            while i < quantity_remaining_for_order:
330
                t_line_item = create_line_item(line, line.actual_price)
331
                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)
332
                orders.append(t_order)
333
                i += 1
334
            '''
335
    return orders
336
 
20616 amit.gupta 337
def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails, dataProtectionInsurer, dataProtectionAmount, orderSource, freebieId, perUnitShippingCost, totalCartVal):
17812 amit.gupta 338
    user = User.get_by(id=userId)
339
    address = Address.get_by(id=address_id)
340
    t_order = TOrder()
557 chandransh 341
 
17812 amit.gupta 342
    t_order.customer_id = user.id
343
    t_order.customer_email = user.email
576 chandransh 344
 
17812 amit.gupta 345
    t_order.customer_name = address.name
346
    t_order.customer_pincode = address.pin
347
    t_order.customer_address1 = address.line_1
348
    t_order.customer_address2 = address.line_2
349
    t_order.customer_city = address.city
350
    t_order.customer_state = address.state
351
    t_order.customer_mobilenumber = address.phone
576 chandransh 352
 
17812 amit.gupta 353
    t_order.total_amount = t_line_item.total_price + insuranceAmount + dataProtectionAmount
354
    t_order.gvAmount = gvAmount
1976 varun.gupt 355
 
17812 amit.gupta 356
    t_order.total_weight = t_line_item.total_weight
357
    t_order.lineitems = [t_line_item]
576 chandransh 358
 
17812 amit.gupta 359
    t_order.status = OrderStatus.PAYMENT_PENDING
360
    t_order.statusDescription = "Payment Pending"
361
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
576 chandransh 362
 
17812 amit.gupta 363
    t_order.pickupStoreId = pickupStoreId 
364
    t_order.insuranceAmount = insuranceAmount 
365
    t_order.insurer = insurer
366
    if insuranceDetails:
367
        t_order.dob = insuranceDetails.dob
368
        t_order.guardianName = insuranceDetails.guardianName
7190 amar.kumar 369
 
17812 amit.gupta 370
    catalog_client = CatalogClient().get_client()
11669 amit.gupta 371
 
17812 amit.gupta 372
    if freebieId is None:
373
        freebie_item_id = catalog_client.getFreebieForItem(t_line_item.item_id)
374
        if freebie_item_id:
375
            t_order.freebieItemId = freebie_item_id
376
    else:
377
        freebie_item_id = None if freebieId == 0 else freebieId  
378
    t_order.source = orderSource
379
    t_order.dataProtectionInsurer = dataProtectionInsurer
380
    t_order.dataProtectionAmount = dataProtectionAmount
20616 amit.gupta 381
    #t_order.shippingCost = round((t_line_item.total_price*totalshippingCost)/totalCartVal, 0)
382
    t_order.shippingCost = perUnitShippingCost*t_line_item.quantity
17812 amit.gupta 383
    return t_order
576 chandransh 384
 
19278 amit.gupta 385
def create_line_item(line, final_price, quantity=1, item=None):
386
    if item is None:
387
        inventory_client = CatalogClient().get_client()
388
        item = inventory_client.getItem(line.item_id)
17812 amit.gupta 389
    t_line_item = TLineItem()
390
    t_line_item.productGroup = item.productGroup
391
    t_line_item.brand = item.brand
392
    t_line_item.model_number = item.modelNumber
393
    if item.color is None or item.color == "NA":
394
        t_line_item.color = ""
395
    else:
396
        t_line_item.color = item.color
397
    t_line_item.model_name = item.modelName
398
    t_line_item.extra_info = item.featureDescription
399
    t_line_item.item_id = item.id
400
    t_line_item.quantity = quantity
1983 varun.gupt 401
 
17812 amit.gupta 402
    t_line_item.unit_price = final_price
403
    t_line_item.total_price = final_price * quantity
404
 
405
    t_line_item.unit_weight = item.weight
406
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
407
    if line.dealText is None:
408
        t_line_item.dealText = item.bestDealText
409
    elif line.dealText == '':
410
        t_line_item.dealText = None
411
    else:
412
        t_line_item.dealText = line.dealText
11915 amit.gupta 413
 
17812 amit.gupta 414
    if item.warrantyPeriod:
415
        #Computing Manufacturer Warranty expiry date
416
        today = datetime.date.today()
417
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
418
        expiry_month = (today.month + item.warrantyPeriod) % 12
4312 rajveer 419
 
17812 amit.gupta 420
        try:
421
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
422
        except ValueError:
4295 varun.gupt 423
            try:
17812 amit.gupta 424
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
4295 varun.gupt 425
            except ValueError:
4312 rajveer 426
                try:
17812 amit.gupta 427
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
4312 rajveer 428
                except ValueError:
17812 amit.gupta 429
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
4312 rajveer 430
 
17812 amit.gupta 431
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
4312 rajveer 432
 
17812 amit.gupta 433
    return t_line_item
576 chandransh 434
 
17812 amit.gupta 435
def validate_cart(cartId, sourceId, couponCode):
436
    inventory_client = CatalogClient().get_client()
437
    logistics_client = LogisticsClient().get_client()
438
    promotion_client = PromotionClient().get_client()
439
    retval = ""
440
    emival = ""
441
    # No need to validate duplicate items since there are only two ways
442
    # to add items to a cart and both of them check whether the item being
443
    # added is a duplicate of an already existing item.
444
    cart = Cart.get_by(id=cartId)
445
    cart_lines = cart.lines
446
    customer_pincode = None
447
    current_time = datetime.datetime.now()
448
    if cart.pickupStoreId :
449
        store = logistics_client.getPickupStore(cart.pickupStoreId)
450
        customer_pincode = store.pin
451
    if cart.address_id != None and customer_pincode == None:
452
        address = Address.get_by(id=cart.address_id)
453
        customer_pincode = address.pin
454
 
455
    user = User.get_by(active_cart_id = cartId)
13136 amit.gupta 456
 
17812 amit.gupta 457
    dealItems = []
18418 kshitij.so 458
    bulkPricingMap ={}
459
    bulkPricingItems =[]
17812 amit.gupta 460
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
461
    if privateDealUser is not None and privateDealUser.isActive:
462
        itemIds = [cartLine.item_id for cartLine in cart.lines]
463
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
464
        dealItems = deals.keys()
18418 kshitij.so 465
        bulkPricingMap = inventory_client.getBulkPricingForItems(itemIds)
466
        bulkPricingItems = bulkPricingMap.keys() 
17812 amit.gupta 467
 
468
    if not customer_pincode:
469
        default_address_id = user.default_address_id
470
        if default_address_id:
471
            address = Address.get_by(id = default_address_id)
472
            customer_pincode = address.pin
473
    if not customer_pincode:
474
        #FIXME should not be hard coded. May be we can pick from config server.
475
        customer_pincode = "110001"
476
    cart.total_price = 0
477
    for line in cart_lines:
478
        old_estimate = line.estimate
479
        item_id = line.item_id
480
        item = inventory_client.getItemForSource(item_id, sourceId)
481
 
482
        item_shipping_info = inventory_client.isActive(item_id) 
483
        if item_shipping_info.isActive:
484
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
485
                line.quantity = 1
486
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
18418 kshitij.so 487
            bulkPrice = None
488
            if item_id in bulkPricingItems:
489
                #Check quantity qualifies or not
490
                bulkPricingList = bulkPricingMap.get(item_id)
491
                bulkPricingList = sorted(bulkPricingList, key=lambda x: x.quantity, reverse=False)
492
                for pricingItems in bulkPricingList:
493
                    if pricingItems.quantity <= line.quantity:
494
                        bulkPrice = pricingItems
495
                    else:
496
                        break
497
 
17812 amit.gupta 498
 
499
            if item_id in dealItems:
18418 kshitij.so 500
                if bulkPrice is None:
501
                    line.actual_price = deals[item_id].dealPrice
502
                else:
503
                    line.actual_price = bulkPrice.price
17812 amit.gupta 504
                if deals[item_id].dealTextOption==0:
505
                    line.dealText = ''
506
                if deals[item_id].dealTextOption==2:
507
                    line.dealText =  deals[item_id].dealText
508
 
509
                if deals[item_id].dealFreebieOption==0:
510
                    line.freebieId = 0
511
                if deals[item_id].dealFreebieOption==2:
512
                    line.freebieId =  deals[item_id].dealFreebieItemId
513
 
514
            else:
18418 kshitij.so 515
                if bulkPrice is None:
516
                    line.actual_price = item.sellingPrice
517
                else:
518
                    line.actual_price = bulkPrice.price 
17812 amit.gupta 519
                line.dealText = None
520
                line.freebieId = None
521
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
522
            try:
523
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
524
            except LogisticsServiceException:
525
                item_delivery_estimate = -1
526
                #TODO Use the exception clause to set the retval appropriately
527
            except :
528
                item_delivery_estimate = -1
529
 
530
            if item_delivery_estimate !=-1:
531
                inv_client = InventoryClient().get_client()
532
                itemAvailability = None
17803 amit.gupta 533
                try:
17812 amit.gupta 534
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
535
                except:
536
                    pass
537
 
538
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
539
                if itemAvailability is not None:
540
                    billingWarehouse = None
12893 manish.sha 541
                    try:
17812 amit.gupta 542
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
12893 manish.sha 543
                    except:
544
                        pass
12904 manish.sha 545
 
17812 amit.gupta 546
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
547
                    if billingWarehouse is not None:
548
                        estimateVal = None
549
                        if not logistics_client.isAlive() :
550
                            logistics_client = LogisticsClient().get_client()
12893 manish.sha 551
                        try:
17812 amit.gupta 552
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
553
                            if estimateVal ==-1:
554
                                item_delivery_estimate =-1
12893 manish.sha 555
                        except:
556
                            pass
17812 amit.gupta 557
                        print 'estimateVal Value ', estimateVal
558
            if old_estimate != item_delivery_estimate:
559
                line.estimate = item_delivery_estimate
560
                cart.updated_on = current_time
561
        else:
562
            Discount.query.filter(Discount.line==line).delete()
563
            line.delete()
564
    if cart.checked_out_on is not None:
565
        if cart.updated_on > cart.checked_out_on:
566
            cart.checked_out_on = None
567
    session.commit()
1976 varun.gupt 568
 
17812 amit.gupta 569
    if cart.coupon_code is not None:
570
        try:
571
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
572
            if updated_cart.message is not None:
573
                emival = updated_cart.message
574
        except PromotionException as ex:
575
            remove_coupon(cart.id)
576
            #retval = ex.message
577
    session.commit()
13136 amit.gupta 578
 
17812 amit.gupta 579
    cart = Cart.get_by(id=cartId)
580
    cart_lines = cart.lines
581
    map_lines = {}
13136 amit.gupta 582
 
17812 amit.gupta 583
    insurerFlag = False
584
    for line in cart_lines:
585
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
586
            line_map = {}
587
            line_map['insurer'] = line.insurer
588
            line_map['dpinsurer'] = line.dataProtectionInsurer
589
            line_map['amount'] = line.discounted_price if line.discounted_price else line.actual_price
590
            line_map['quantity'] = line.quantity
591
            insurerFlag = True
592
            map_lines[line.item_id] = line_map
593
 
594
    if insurerFlag:
595
        map_lines = inventory_client.checkServices(map_lines)
596
        for line in cart_lines :
597
            if map_lines.has_key(line.item_id):
598
                line_map = map_lines[line.item_id]
599
                if line_map['insurer'] > 0:
600
                    if cart.discounted_price:
601
                        cart.discounted_price = cart.discounted_price + line_map['insureramount']
602
                    line.insurer = line_map['insurer']
603
                    line.insuranceAmount = line_map['insureramount']
604
                    cart.total_price = cart.total_price + line_map['insureramount']
605
                if line_map['dpinsurer'] > 0:
606
                    if cart.discounted_price:
607
                        cart.discounted_price = cart.discounted_price + line_map['dpinsureramount']
608
                    line.dataProtectionInsurer = line_map['dpinsurer']
609
                    line.dataProtectionAmount = line_map['dpinsureramount']
610
                    cart.total_price = cart.total_price + line_map['dpinsureramount']
611
                line.updated_on = datetime.datetime.now()
17803 amit.gupta 612
        cart.updated_on = datetime.datetime.now()
13142 amit.gupta 613
        session.commit()
17812 amit.gupta 614
    session.close()
615
    return [retval, emival]
616
 
617
def merge_cart(fromCartId, toCartId):
618
    fromCart = Cart.get_by(id=fromCartId)
619
    toCart = Cart.get_by(id=toCartId)
557 chandransh 620
 
17812 amit.gupta 621
    old_lines = fromCart.lines
622
    new_lines = toCart.lines
557 chandransh 623
 
17812 amit.gupta 624
    for line in old_lines:
625
        for discount in line.discounts:
626
            discount.delete()
627
    session.commit()
628
 
629
    for line in old_lines:
630
        flag = True
631
        for new_line in new_lines:
632
            if line.item_id == new_line.item_id:
633
                flag = False
634
 
635
        if flag:
636
            line.cart_id = toCartId
637
        else:
638
            line.delete()
5345 rajveer 639
 
17812 amit.gupta 640
    if toCart.coupon_code is None:
641
        toCart.coupon_code = fromCart.coupon_code
2019 varun.gupt 642
 
17812 amit.gupta 643
    toCart.updated_on = datetime.datetime.now()
644
    fromCart.expired_on = datetime.datetime.now()
645
    fromCart.cart_status = CartStatus.INACTIVE
646
    session.commit()
647
 
648
def check_out(cartId):
649
    if cartId is None:
650
        raise ShoppingCartException(101, "Cart id not specified")
651
    cart = Cart.get_by(id = cartId)
652
    if cart is None:
653
        raise ShoppingCartException(102, "The specified cart couldn't be found")
654
    cart.checked_out_on = datetime.datetime.now()
655
    session.commit()
656
    return True
657
 
658
def reset_cart(cartId, items):
659
    if cartId is None:
660
        raise ShoppingCartException(101, "Cart id not specified")
661
    for item_id, quantity in items.iteritems():
662
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
663
        if line is not None:
664
            delete_discounts_for_line(line)
665
            line.discounted_price = None
666
            line.quantity = line.quantity - quantity
667
            if line.quantity == 0:
668
                line.delete()
669
    cart = Cart.get_by(id=cartId)
670
    cart.updated_on = datetime.datetime.now()
671
    cart.checked_out_on = None
1976 varun.gupt 672
 
17812 amit.gupta 673
    # Removing Coupon
674
    cart.total_price = None
675
    cart.discounted_price = None
676
    cart.coupon_code = None
677
 
678
    session.commit()
679
    return True
680
 
681
def get_carts_with_coupon_count(coupon_code):
682
    return Cart.query.filter_by(coupon_code = coupon_code).count()
683
 
684
def show_cod_option(cartId, sourceId, pincode):
685
    cart = Cart.get_by(id = cartId)
686
    cod_option = True
687
    logistics_client = LogisticsClient().get_client()
688
    if cart:
689
        if cart.coupon_code:
690
            promotion_client = PromotionClient().get_client()
691
            cod_option = promotion_client.isCodApplicable(to_t_cart(cart))
5351 varun.gupt 692
 
17812 amit.gupta 693
        if cod_option and cart.lines:
694
            for line in cart.lines:
18844 amit.gupta 695
                try:
696
                    logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
697
                    if not logistics_info.codAllowed:
698
                        cod_option = False
699
                        break
700
                except:
701
                    pass    
17812 amit.gupta 702
            if cart.total_price > 60000:# or cart.total_price <= 250:
703
                cod_option = False
704
    return cod_option
705
 
706
def get_products_added_to_cart(startDate, endDate):
707
    lines = session.query(Line.item_id).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).all()
708
    datas = []
709
    for line in lines:
710
        datas.append(line[0])
711
    return datas
712
 
713
def insure_item(itemId, cartId, toInsure, insurerType):
714
    cart = Cart.get_by(id = cartId)
715
    line = None
716
    for cartLine in cart.lines:
717
        if(cartLine.item_id == itemId):
718
            line = cartLine
719
            break
11655 amit.gupta 720
 
17812 amit.gupta 721
    if not line:
722
        print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
723
        return False
11655 amit.gupta 724
 
17812 amit.gupta 725
    try:
726
        if toInsure:
727
            csc = CatalogClient().get_client()
728
            item = csc.getItem(itemId)
729
            insurerId = csc.getPrefferedInsurerForItem(itemId,insurerType)
730
            insuranceAmount = csc.getInsuranceAmount(itemId, line.discounted_price if line.discounted_price else line.actual_price, insurerId, line.quantity)
731
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
9299 kshitij.so 732
                if cart.discounted_price:
17812 amit.gupta 733
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount + insuranceAmount
734
                line.insurer = insurerId
735
                line.insuranceAmount = insuranceAmount
736
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
737
                if cart.discounted_price:
738
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount + insuranceAmount
739
                line.dataProtectionInsurer = insurerId
740
                line.dataProtectionAmount = insuranceAmount
741
            cart.total_price = cart.total_price + insuranceAmount
742
        else:
743
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
744
                cart.total_price = cart.total_price - line.insuranceAmount
745
                if cart.discounted_price:
746
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount
747
                line.insurer = 0
748
                line.insuranceAmount = 0
749
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
750
                cart.total_price = cart.total_price - line.dataProtectionAmount
751
                if cart.discounted_price:
752
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount
753
                line.dataProtectionInsurer = 0
754
                line.dataProtectionAmount = 0
755
        line.updated_on = datetime.datetime.now()
756
        cart.updated_on = datetime.datetime.now()
757
        session.commit()
758
    except:
759
        print("Error : Unable to insure")
760
        print("insurerId : " + str(insurerId) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
761
        return False
6903 anupam.sin 762
 
17812 amit.gupta 763
    return True
764
 
765
def cancel_insurance(cartId):
766
    try:
767
        cart = Cart.get_by(id = cartId)
768
        for cartLine in cart.lines:
769
            cart.total_price = cart.total_price - cartLine.insuranceAmount
770
            if cart.discounted_price:
771
                cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
772
            cartLine.insurer = 0
773
            cartLine.insuranceAmount = 0
774
            cartLine.updated_on = datetime.datetime.now()
775
        cart.updated_on = datetime.datetime.now()
776
        session.commit()
777
    except:
778
        print("Error : Unable to cancel insurance for cartId :" + str(cartId))
779
        return False
6903 anupam.sin 780
 
17812 amit.gupta 781
    return True
782
 
783
def store_insurance_specific_details(addressId, dob, guardianName):
784
    try:
785
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
786
        if insuranceDetails is None :
787
            insuranceDetails = InsuranceDetails()
788
        insuranceDetails.addressId = addressId
789
        insuranceDetails.dob = dob
790
        insuranceDetails.guardianName = guardianName
791
        session.commit()
792
    except:
793
        print("Error : Unable to store insurance details for addressId : " + str(addressId))
794
        return False
795
    return True
796
 
797
def is_insurance_detail_present(addressId):
798
    try:
799
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
800
        if insuranceDetails is None :
6903 anupam.sin 801
            return False
17812 amit.gupta 802
    except:
803
        print("Error : Unable to get insurance details for addressId : " + str(addressId))
804
        return False
805
    return True
806
 
807
 
808
def add_items_to_cart(cartId, itemQty, couponCode=None):
809
    try: 
810
        found_cart = Cart.get_by(id=cartId)
811
        itemQtyMap = {}
812
        current_time = datetime.datetime.now()
813
        for itemqty in itemQty:
814
            itemQtyMap[itemqty.itemId] = itemqty.qty 
815
 
816
        if found_cart.lines:
817
            for line in found_cart.lines:
818
                if itemQtyMap.has_key(line.item_id):
19161 amit.gupta 819
                    Discount.query.filter(Discount.line==line).delete()
17812 amit.gupta 820
                    line.delete()
821
        for itemId,qty in itemQtyMap.iteritems():
822
            #This condition will ensure that cart is only persisted with non-zero quantities.
823
            if qty==0:
824
                continue
825
            line = Line()
826
            line.cart = found_cart
827
            line.item_id = itemId
828
            line.quantity = qty
829
            line.created_on = current_time
830
            line.updated_on = current_time
831
            line.line_status = LineStatus.LINE_ACTIVE
832
            line.insurer = 0
833
            line.insuranceAmount = 0
834
        if couponCode:
835
            found_cart.coupon_code = couponCode
836
        else:
837
            found_cart.coupon_code = None
838
        session.commit()
17782 amit.gupta 839
        return True
17812 amit.gupta 840
    except:
841
        traceback.print_exc()
842
        return False
843
 
17782 amit.gupta 844
 
17812 amit.gupta 845
def valiate_cart_new(cartId, customer_pincode, sourceId):
17782 amit.gupta 846
 
17812 amit.gupta 847
    inventory_client = CatalogClient().get_client()
848
    logistics_client = LogisticsClient().get_client()
849
    promotion_client = PromotionClient().get_client()
850
    # No need to validate duplicate items since there are only two ways
851
    # to add items to a cart and both of them check whether the item being
852
    # added is a duplicate of an already existing item.
853
    cart = Cart.get_by(id=cartId)
854
    cart_lines = cart.lines
855
    current_time = datetime.datetime.now()
856
 
857
    user = User.get_by(active_cart_id = cartId)
858
    responseMap = {}
859
    totalQty = 0
860
    totalAmount = 0 
861
    shippingCharges=0
862
    cartMessages=[]
863
    cartItems = []
864
    dealItems = []
18418 kshitij.so 865
    bulkPricingMap ={}
866
    bulkPricingItems =[]
17782 amit.gupta 867
 
17812 amit.gupta 868
    responseMap['shippingCharges']= shippingCharges
869
    responseMap['cartMessages']= cartMessages
870
    responseMap['cartItems']= cartItems
871
    responseMap['pincode']= customer_pincode
872
 
873
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
874
    itemIds = [cartLine.item_id for cartLine in cart.lines]
875
    if privateDealUser is not None and privateDealUser.isActive:
876
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
877
        dealItems = deals.keys()
18418 kshitij.so 878
        bulkPricingMap = inventory_client.getBulkPricingForItems(itemIds)
879
        bulkPricingItems = bulkPricingMap.keys() 
17812 amit.gupta 880
 
881
    cart.total_price = 0
882
    itemsMap = inventory_client.getItems(itemIds)
17789 amit.gupta 883
 
17812 amit.gupta 884
    cartMessageChanged = 0
885
    cartMessageOOS = 0
886
    cartMessageUndeliverable = 0
17789 amit.gupta 887
 
18521 kshitij.so 888
 
889
 
17812 amit.gupta 890
    for line in cart_lines:
17865 amit.gupta 891
        itemQuantityChanged=False
17812 amit.gupta 892
        cartItem={}
18418 kshitij.so 893
        tempBulkItemList = []
17782 amit.gupta 894
 
17812 amit.gupta 895
        old_estimate = line.estimate
896
        item_id = line.item_id
897
        item = itemsMap.get(item_id)
18381 amit.gupta 898
        if item.itemStatus==0:
18375 amit.gupta 899
            Discount.query.filter(Discount.line==line).delete()
900
            line.delete()
901
            continue
17812 amit.gupta 902
        cartItem['itemId']=line.item_id
903
        cartItem['quantity']=0
17813 amit.gupta 904
        cartItem['cartItemMessages']=[]
905
        cartItemMessages = cartItem['cartItemMessages']
17812 amit.gupta 906
        cartItem['color'] = item.color
907
        cartItem['catalogItemId'] = item.catalogItemId
18006 manish.sha 908
        cartItem['packQuantity'] = item.packQuantity
18431 kshitij.so 909
        cartItem['minBuyQuantity'] = item.minimumBuyQuantity
910
        cartItem['quantityStep'] = item.quantityStep
18418 kshitij.so 911
        cartItem['bulkPricing'] = tempBulkItemList
18521 kshitij.so 912
 
913
        item_shipping_info = inventory_client.isActive(item_id) 
914
        if item_shipping_info.isActive:
915
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
916
                line.quantity = item_shipping_info.quantity
917
                itemQuantityChanged=True
18627 kshitij.so 918
            cartItem['maxQuantity'] = min(item_shipping_info.quantity,100)
18521 kshitij.so 919
            if item.maximumBuyQuantity is not None and item.maximumBuyQuantity >0:
920
                cartItem['maxQuantity'] = min(item_shipping_info.quantity, item.maximumBuyQuantity)
18534 kshitij.so 921
        else:
922
            cartItem['maxQuantity'] =0
923
 
18521 kshitij.so 924
 
925
        if item_shipping_info.quantity < cartItem['minBuyQuantity']:
926
            cartItem['minBuyQuantity'] = item_shipping_info.quantity 
927
 
928
        if line.quantity < cartItem['minBuyQuantity']:
929
            itemQuantityChanged=True
930
            line.quantity = cartItem['minBuyQuantity']
931
 
932
        if line.quantity > cartItem['maxQuantity']:
933
            itemQuantityChanged=True
934
            line.quantity = cartItem['maxQuantity']
18523 kshitij.so 935
 
936
        cartItem['quantity'] = line.quantity
937
 
18418 kshitij.so 938
        bulkPrice = None
18482 kshitij.so 939
        singleUnitPricing = False
18418 kshitij.so 940
        if item_id in bulkPricingItems:
941
            #Check quantity qualifies or not
942
            bulkPricingList = bulkPricingMap.get(item_id)
943
            bulkPricingList = sorted(bulkPricingList, key=lambda x: x.quantity, reverse=False)
944
            for pricingItems in bulkPricingList:
18482 kshitij.so 945
                if pricingItems.quantity ==1:
946
                    singleUnitPricing = True
18418 kshitij.so 947
                if pricingItems.quantity <= line.quantity:
948
                    bulkPrice = pricingItems
18482 kshitij.so 949
                tempBulkItemList.append({'quantity':pricingItems.quantity,'price':pricingItems.price})
18418 kshitij.so 950
 
17903 amit.gupta 951
        if item_id in dealItems:
18482 kshitij.so 952
            if not singleUnitPricing and item_id in bulkPricingItems:
953
                tempBulkItemList.append({'quantity':1,'price':deals[item_id].dealPrice})
18418 kshitij.so 954
            if bulkPrice is None:
955
                line.actual_price = deals[item_id].dealPrice
956
            else:
957
                line.actual_price = bulkPrice.price
17903 amit.gupta 958
            if deals[item_id].dealTextOption==0:
959
                line.dealText = ''
960
            if deals[item_id].dealTextOption==2:
961
                line.dealText = deals[item_id].dealText
962
 
963
            if deals[item_id].dealFreebieOption==0:
964
                line.freebieId = 0
965
            if deals[item_id].dealFreebieOption==2:
966
                line.freebieId =  deals[item_id].dealFreebieItemId
967
            cartItem['dealText'] = line.dealText
968
        else:
18482 kshitij.so 969
            if not singleUnitPricing and item_id in bulkPricingItems:
970
                tempBulkItemList.append({'quantity':1,'price':item.sellingPrice})
18418 kshitij.so 971
            if bulkPrice is None:
972
                line.actual_price = item.sellingPrice
973
            else:
974
                line.actual_price = bulkPrice.price
17903 amit.gupta 975
            if item.bestDealText:
976
                cartItem['dealText'] = item.bestDealText
977
            line.dealText = None
978
            line.freebieId = None
979
        cartItem['sellingPrice'] = line.actual_price
980
 
18539 kshitij.so 981
        toRemove = []
18536 kshitij.so 982
        for dictbulkPricing in cartItem['bulkPricing']:
983
            if dictbulkPricing['quantity'] < cartItem['minBuyQuantity'] or dictbulkPricing['quantity'] > cartItem['maxQuantity']:
18539 kshitij.so 984
                toRemove.append(dictbulkPricing)
985
        for removePricing in toRemove:
986
            cartItem['bulkPricing'].remove(removePricing)
18541 kshitij.so 987
        cartItem['bulkPricing'] = sorted(cartItem['bulkPricing'], key=lambda k: k['quantity'],reverse=False)
18536 kshitij.so 988
 
17812 amit.gupta 989
        if item_shipping_info.isActive:
990
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
991
            try:
992
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
993
            except LogisticsServiceException:
994
                item_delivery_estimate = -1
995
                #TODO Use the exception clause to set the retval appropriately
996
            except :
997
                item_delivery_estimate = -1
17782 amit.gupta 998
 
17812 amit.gupta 999
            if item_delivery_estimate !=-1:
1000
                inv_client = InventoryClient().get_client()
1001
                itemAvailability = None
1002
                try:
1003
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
1004
                except:
1005
                    pass
17803 amit.gupta 1006
 
17812 amit.gupta 1007
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
1008
                if itemAvailability is not None:
1009
                    billingWarehouse = None
17782 amit.gupta 1010
                    try:
17812 amit.gupta 1011
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
17782 amit.gupta 1012
                    except:
1013
                        pass
1014
 
17812 amit.gupta 1015
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
1016
                    if billingWarehouse is not None:
1017
                        estimateVal = None
1018
                        if not logistics_client.isAlive() :
1019
                            logistics_client = LogisticsClient().get_client()
17782 amit.gupta 1020
                        try:
17812 amit.gupta 1021
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
1022
                            if estimateVal ==-1:
1023
                                item_delivery_estimate =-1
17782 amit.gupta 1024
                        except:
1025
                            pass
17812 amit.gupta 1026
                        print 'estimateVal Value ', estimateVal
1027
            cartItem['estimate'] = item_delivery_estimate
1028
            if item_delivery_estimate == -1:
18951 amit.gupta 1029
                Discount.query.filter(Discount.line==line).delete()
1030
                line.delete()
17782 amit.gupta 1031
                cartItem['quantity'] = 0
17812 amit.gupta 1032
                cartMessageUndeliverable += 1
17836 amit.gupta 1033
                cartItemMessages.append({"type":"danger", "messageText":"Undeliverable"})
17865 amit.gupta 1034
            elif itemQuantityChanged:
1035
                cartMessageChanged += 1
1036
                cartItemMessages.append({"type":"danger", "messageText":"Only " + str(item_shipping_info.quantity) + " available"})
17812 amit.gupta 1037
            if old_estimate != item_delivery_estimate:
1038
                line.estimate = item_delivery_estimate
1039
                cart.updated_on = current_time
17903 amit.gupta 1040
            totalAmount += line.actual_price * cartItem['quantity']
17812 amit.gupta 1041
        else:
1042
            cartItem['quantity'] = 0
1043
            cartMessageOOS += 1
1044
            cartItemMessages.append({"type":"danger", "messageText":"Out of Stock"})
1045
            Discount.query.filter(Discount.line==line).delete()
1046
            line.delete()
1047
        totalQty += cartItem['quantity']
1048
        if cartItemMessages:
1049
            cartItems.insert(0, cartItem)
1050
        else:
1051
            cartItems.append(cartItem)
1052
    if cart.checked_out_on is not None:
1053
        if cart.updated_on > cart.checked_out_on:
1054
            cart.checked_out_on = None
1055
    session.commit()
1056
 
1057
    if cart.coupon_code is not None:
1058
        try:
1059
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
1060
            if updated_cart.message is not None:
1061
                emival = updated_cart.message
1062
        except PromotionException as ex:
1063
            remove_coupon(cart.id)
1064
            #retval = ex.message
1065
    session.commit()
1066
 
1067
    cart = Cart.get_by(id=cartId)
1068
    cart_lines = cart.lines
1069
    insurerFlag = False
1070
    for line in cart_lines:
1071
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
1072
            line.insurer = 0
1073
            line.insuranceAmount = 0 
1074
            line.dataProtectionInsurer = 0
1075
            line.dataProtectionAmount = 0
1076
            insurerFlag = True
17782 amit.gupta 1077
 
17812 amit.gupta 1078
    if insurerFlag:
1079
        cart.updated_on = datetime.datetime.now()
17782 amit.gupta 1080
        session.commit()
17812 amit.gupta 1081
    session.close()
1082
    responseMap['totalQty']= totalQty
1083
    responseMap['totalAmount']= totalAmount
20616 amit.gupta 1084
    if totalQty >= 5:
1085
        shippingCharges = totalQty*30
1086
    else:
1087
        shippingCharges = totalQty*60
17812 amit.gupta 1088
    responseMap['shippingCharge']=shippingCharges
1089
    responseMap['cartMessageChanged'] = cartMessageChanged
1090
    responseMap['cartMessageOOS'] = cartMessageOOS
1091
    responseMap['cartMessageUndeliverable'] = cartMessageUndeliverable
1092
    return json.dumps(responseMap)
1093
 
1094
 
1095
def validate_cart_plus(cart_id, source_id, couponCode):
1096
    try:
1097
        cart_messages = validate_cart(cart_id, source_id, couponCode)
1098
        found_cart = Cart.get_by(id=cart_id)
1099
        pincode = "110001"
1100
        default_address_id = User.get_by(active_cart_id = cart_id).default_address_id
11598 amit.gupta 1101
 
17812 amit.gupta 1102
        default_address = None
1103
        if found_cart.address_id is not None and found_cart.address_id > 0:
1104
            pincode = Address.get_by(id=found_cart.address_id).pin
1105
        elif default_address_id is not None:
1106
            default_address = Address.get_by(id = default_address_id) 
1107
            pincode = default_address.pin
11592 amit.gupta 1108
 
18418 kshitij.so 1109
        needInsuranceInfo = False
17812 amit.gupta 1110
        if default_address_id is not None:
1111
            for line in found_cart.lines:
1112
                if line.insurer > 0:
18418 kshitij.so 1113
                    needInsuranceInfo = not is_insurance_detail_present(default_address_id)
17812 amit.gupta 1114
                    break
1115
        cartPlus = CartPlus()
1116
        cartPlus.cart = to_t_cart(found_cart)
1117
        cartPlus.pinCode = pincode
1118
        cartPlus.validateCartMessages = cart_messages
18418 kshitij.so 1119
        cartPlus.needInsuranceInfo = needInsuranceInfo
17812 amit.gupta 1120
        return cartPlus
1121
    finally:
1122
        close_session()
1123
 
1124
def close_session():
1125
    if session.is_active:
1126
        print "session is active. closing it."
18844 amit.gupta 1127
        session.close()
1128