Subversion Repositories SmartDukaan

Rev

Rev 20982 | Rev 21000 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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