Subversion Repositories SmartDukaan

Rev

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