Subversion Repositories SmartDukaan

Rev

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

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