Subversion Repositories SmartDukaan

Rev

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