Subversion Repositories SmartDukaan

Rev

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