Subversion Repositories SmartDukaan

Rev

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