Subversion Repositories SmartDukaan

Rev

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