Subversion Repositories SmartDukaan

Rev

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