Subversion Repositories SmartDukaan

Rev

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