Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
17812 amit.gupta 1
'''
2
Created on 10-May-2010
3
 
4
@author: ashish
5
'''
6
from elixir import *
7
from shop2020.clients.CatalogClient import CatalogClient
8
from shop2020.clients.InventoryClient import InventoryClient
9
from shop2020.clients.LogisticsClient import LogisticsClient
10
from shop2020.clients.PromotionClient import PromotionClient
11
from shop2020.clients.TransactionClient import TransactionClient
12
from shop2020.model.v1 import user
13
from shop2020.model.v1.user.impl.Converters import to_t_cart, to_t_line
14
from shop2020.model.v1.user.impl.Dataservice import Cart, Line, Address, User, \
15
    Discount, InsuranceDetails, PrivateDealUser
16
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, \
17
    DeliveryType
18
from shop2020.thriftpy.model.v1.catalog.ttypes import Item, InsurerType
19
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as TTransaction, \
20
    TransactionStatus as TTransactionStatus, Order as TOrder, LineItem as TLineItem, \
21
    OrderStatus, OrderSource
22
from shop2020.thriftpy.model.v1.user.ttypes import CartStatus, LineStatus, \
23
    ShoppingCartException, PromotionException, CartPlus
24
from shop2020.utils.Utils import to_py_date, to_java_date
25
import datetime
26
import json
27
import math
28
import traceback
29
 
30
 
22302 amit.gupta 31
 
17812 amit.gupta 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
22210 amit.gupta 244
    totalshippingCost = 0
17812 amit.gupta 245
    for lineObj in cart.lines:
246
        totalCartVal += lineObj.actual_price * lineObj.quantity
247
    txn = TTransaction()
248
    txn.shoppingCartid = cart_id
249
    txn.customer_id = userId
250
    txn.createdOn = to_java_date(datetime.datetime.now())
251
    txn.transactionStatus = TTransactionStatus.INIT
252
    txn.statusDescription = "New Order"
253
    txn.coupon_code = cart.coupon_code
254
    txn.sessionSource = sessionSource
255
    txn.sessionStartTime = sessionTime
256
    txn.firstSource = firstSource
257
    txn.firstSourceTime = firstSourceTime
18634 manish.sha 258
    txn.payment_option = schemeId
22210 amit.gupta 259
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
24227 amit.gupta 260
    if privateDealUser is not None and sessionSource!="BACKEND":
22210 amit.gupta 261
        if totalCartVal <1000:
23095 amit.gupta 262
            totalshippingCost = 100
22210 amit.gupta 263
    txn.totalShippingCost = totalshippingCost
17470 manish.sha 264
 
22210 amit.gupta 265
    txnOrders = create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal, selfPickup)
266
    shippingCostInOrders = 0
267
    for order in txnOrders:
268
        shippingCostInOrders = shippingCostInOrders + order.shippingCost
576 chandransh 269
 
22210 amit.gupta 270
    diff = totalshippingCost - shippingCostInOrders
271
    txnOrders[0].shippingCost = txnOrders[0].shippingCost + diff
272
 
273
 
274
    txn.orders = txnOrders
275
 
17812 amit.gupta 276
    transaction_client = TransactionClient().get_client()
277
    txn_id = transaction_client.createTransaction(txn)
278
 
279
    session.commit()
280
 
281
    return txn_id
282
 
22210 amit.gupta 283
def create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal, selfPickup):
17812 amit.gupta 284
    cart_lines = cart.lines
285
    orders = []
286
    isGv = False
287
    if cart.coupon_code:
6318 rajveer 288
        try:
17812 amit.gupta 289
            pc = PromotionClient().get_client()
290
            isGv = pc.isGiftVoucher(cart.coupon_code)
6318 rajveer 291
        except:
17812 amit.gupta 292
            isGv = False
6318 rajveer 293
 
17812 amit.gupta 294
    insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
22210 amit.gupta 295
    itemIds = []
17812 amit.gupta 296
    for line in cart_lines:
22210 amit.gupta 297
        itemIds.append(line.item_id) 
298
    inventory_client = CatalogClient().get_client()
299
    itemsMap = inventory_client.getItems(itemIds)
22239 amit.gupta 300
    print "cart_lines -", cart_lines
22210 amit.gupta 301
    for line in cart_lines:
17812 amit.gupta 302
        if line.line_status == LineStatus.LINE_ACTIVE:
303
            quantity_remaining_for_order = line.quantity
3554 varun.gupt 304
 
17812 amit.gupta 305
            for discount in line.discounts:
306
                #i = 0
307
                #while i < discount.quantity:
19278 amit.gupta 308
                t_line_item = create_line_item(line, line.actual_price if isGv else (line.actual_price - discount.discount), line.quantity, itemsMap.get(line.item_id))
22210 amit.gupta 309
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, discount.discount if isGv else 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails,line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, totalshippingCost, totalCartVal, selfPickup)
17812 amit.gupta 310
                orders.append(t_order)
311
                    #i += 1
312
                quantity_remaining_for_order -= discount.quantity
22239 amit.gupta 313
            print "quantity_remaining_for_order ", quantity_remaining_for_order 
17812 amit.gupta 314
            if quantity_remaining_for_order > 0:
19278 amit.gupta 315
                t_line_item = create_line_item(line, line.actual_price, quantity_remaining_for_order, itemsMap.get(line.item_id))
22210 amit.gupta 316
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails, line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, totalshippingCost, totalCartVal, selfPickup)
17812 amit.gupta 317
                orders.append(t_order)
21003 amit.gupta 318
 
20873 kshitij.so 319
 
320
    wallet_amount = cart.wallet_amount
20940 kshitij.so 321
    if wallet_amount is None:
322
        wallet_amount = 0
20875 kshitij.so 323
    print "adjusting wallet_amount ***",wallet_amount
20873 kshitij.so 324
    for order in orders:
20875 kshitij.so 325
        if ((order.total_amount+ order.shippingCost - order.gvAmount) >= wallet_amount):
20873 kshitij.so 326
            order.wallet_amount = wallet_amount
327
        else:
20875 kshitij.so 328
            order.wallet_amount = order.total_amount+ order.shippingCost - order.gvAmount
20873 kshitij.so 329
 
20875 kshitij.so 330
        order.net_payable_amount = order.total_amount+ order.shippingCost - order.gvAmount - order.wallet_amount
20873 kshitij.so 331
        wallet_amount = wallet_amount - order.wallet_amount
17812 amit.gupta 332
    return orders
333
 
22210 amit.gupta 334
def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails, dataProtectionInsurer, dataProtectionAmount, orderSource, freebieId, totalshippingCost, totalCartVal, selfPickup):
17812 amit.gupta 335
    user = User.get_by(id=userId)
336
    address = Address.get_by(id=address_id)
337
    t_order = TOrder()
557 chandransh 338
 
17812 amit.gupta 339
    t_order.customer_id = user.id
340
    t_order.customer_email = user.email
576 chandransh 341
 
17812 amit.gupta 342
    t_order.customer_name = address.name
343
    t_order.customer_pincode = address.pin
344
    t_order.customer_address1 = address.line_1
345
    t_order.customer_address2 = address.line_2
346
    t_order.customer_city = address.city
347
    t_order.customer_state = address.state
348
    t_order.customer_mobilenumber = address.phone
576 chandransh 349
 
17812 amit.gupta 350
    t_order.total_amount = t_line_item.total_price + insuranceAmount + dataProtectionAmount
351
    t_order.gvAmount = gvAmount
1976 varun.gupt 352
 
17812 amit.gupta 353
    t_order.total_weight = t_line_item.total_weight
354
    t_order.lineitems = [t_line_item]
576 chandransh 355
 
17812 amit.gupta 356
    t_order.status = OrderStatus.PAYMENT_PENDING
357
    t_order.statusDescription = "Payment Pending"
358
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
576 chandransh 359
 
17812 amit.gupta 360
    t_order.pickupStoreId = pickupStoreId 
361
    t_order.insuranceAmount = insuranceAmount 
362
    t_order.insurer = insurer
363
    if insuranceDetails:
364
        t_order.dob = insuranceDetails.dob
365
        t_order.guardianName = insuranceDetails.guardianName
7190 amar.kumar 366
 
17812 amit.gupta 367
    catalog_client = CatalogClient().get_client()
11669 amit.gupta 368
 
17812 amit.gupta 369
    if freebieId is None:
370
        freebie_item_id = catalog_client.getFreebieForItem(t_line_item.item_id)
371
        if freebie_item_id:
372
            t_order.freebieItemId = freebie_item_id
373
    else:
374
        freebie_item_id = None if freebieId == 0 else freebieId  
375
    t_order.source = orderSource
376
    t_order.dataProtectionInsurer = dataProtectionInsurer
377
    t_order.dataProtectionAmount = dataProtectionAmount
21081 amit.gupta 378
    #if item.category in [10006, 10010]:
21454 amit.gupta 379
    if selfPickup:
380
        t_order.logistics_provider_id = 4
21619 amit.gupta 381
        t_order.shippingCost = 0
21454 amit.gupta 382
    else:
22210 amit.gupta 383
        t_order.shippingCost = round((t_line_item.total_price*totalshippingCost)/totalCartVal, 0)
384
        #t_order.shippingCost = perUnitShippingCost*t_line_item.quantity
21081 amit.gupta 385
    #else:
386
    #    t_order.shippingCost = 0
17812 amit.gupta 387
    return t_order
576 chandransh 388
 
19278 amit.gupta 389
def create_line_item(line, final_price, quantity=1, item=None):
390
    if item is None:
391
        inventory_client = CatalogClient().get_client()
392
        item = inventory_client.getItem(line.item_id)
17812 amit.gupta 393
    t_line_item = TLineItem()
394
    t_line_item.productGroup = item.productGroup
395
    t_line_item.brand = item.brand
396
    t_line_item.model_number = item.modelNumber
397
    if item.color is None or item.color == "NA":
398
        t_line_item.color = ""
399
    else:
400
        t_line_item.color = item.color
401
    t_line_item.model_name = item.modelName
20847 amit.gupta 402
    t_line_item.mrp = item.mrp
17812 amit.gupta 403
    t_line_item.extra_info = item.featureDescription
404
    t_line_item.item_id = item.id
405
    t_line_item.quantity = quantity
1983 varun.gupt 406
 
17812 amit.gupta 407
    t_line_item.unit_price = final_price
408
    t_line_item.total_price = final_price * quantity
21854 amit.gupta 409
    t_line_item.hsnCode = item.hsnCode
17812 amit.gupta 410
 
411
    t_line_item.unit_weight = item.weight
412
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
413
    if line.dealText is None:
414
        t_line_item.dealText = item.bestDealText
415
    elif line.dealText == '':
416
        t_line_item.dealText = None
417
    else:
418
        t_line_item.dealText = line.dealText
11915 amit.gupta 419
 
17812 amit.gupta 420
    if item.warrantyPeriod:
421
        #Computing Manufacturer Warranty expiry date
422
        today = datetime.date.today()
423
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
424
        expiry_month = (today.month + item.warrantyPeriod) % 12
4312 rajveer 425
 
17812 amit.gupta 426
        try:
427
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
428
        except ValueError:
4295 varun.gupt 429
            try:
17812 amit.gupta 430
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
4295 varun.gupt 431
            except ValueError:
4312 rajveer 432
                try:
17812 amit.gupta 433
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
4312 rajveer 434
                except ValueError:
17812 amit.gupta 435
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
4312 rajveer 436
 
17812 amit.gupta 437
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
4312 rajveer 438
 
17812 amit.gupta 439
    return t_line_item
576 chandransh 440
 
17812 amit.gupta 441
def validate_cart(cartId, sourceId, couponCode):
442
    inventory_client = CatalogClient().get_client()
443
    logistics_client = LogisticsClient().get_client()
444
    promotion_client = PromotionClient().get_client()
445
    retval = ""
446
    emival = ""
447
    # No need to validate duplicate items since there are only two ways
448
    # to add items to a cart and both of them check whether the item being
449
    # added is a duplicate of an already existing item.
450
    cart = Cart.get_by(id=cartId)
451
    cart_lines = cart.lines
452
    customer_pincode = None
453
    current_time = datetime.datetime.now()
454
    if cart.pickupStoreId :
455
        store = logistics_client.getPickupStore(cart.pickupStoreId)
456
        customer_pincode = store.pin
457
    if cart.address_id != None and customer_pincode == None:
458
        address = Address.get_by(id=cart.address_id)
459
        customer_pincode = address.pin
460
 
461
    user = User.get_by(active_cart_id = cartId)
13136 amit.gupta 462
 
17812 amit.gupta 463
    dealItems = []
18418 kshitij.so 464
    bulkPricingMap ={}
465
    bulkPricingItems =[]
17812 amit.gupta 466
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
467
    if privateDealUser is not None and privateDealUser.isActive:
468
        itemIds = [cartLine.item_id for cartLine in cart.lines]
469
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
470
        dealItems = deals.keys()
18418 kshitij.so 471
        bulkPricingMap = inventory_client.getBulkPricingForItems(itemIds)
472
        bulkPricingItems = bulkPricingMap.keys() 
17812 amit.gupta 473
 
474
    if not customer_pincode:
475
        default_address_id = user.default_address_id
476
        if default_address_id:
477
            address = Address.get_by(id = default_address_id)
478
            customer_pincode = address.pin
479
    if not customer_pincode:
480
        #FIXME should not be hard coded. May be we can pick from config server.
481
        customer_pincode = "110001"
482
    cart.total_price = 0
483
    for line in cart_lines:
484
        old_estimate = line.estimate
485
        item_id = line.item_id
486
        item = inventory_client.getItemForSource(item_id, sourceId)
487
 
488
        item_shipping_info = inventory_client.isActive(item_id) 
489
        if item_shipping_info.isActive:
490
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
491
                line.quantity = 1
492
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
18418 kshitij.so 493
            bulkPrice = None
494
            if item_id in bulkPricingItems:
495
                #Check quantity qualifies or not
496
                bulkPricingList = bulkPricingMap.get(item_id)
497
                bulkPricingList = sorted(bulkPricingList, key=lambda x: x.quantity, reverse=False)
498
                for pricingItems in bulkPricingList:
499
                    if pricingItems.quantity <= line.quantity:
500
                        bulkPrice = pricingItems
501
                    else:
502
                        break
503
 
17812 amit.gupta 504
 
505
            if item_id in dealItems:
18418 kshitij.so 506
                if bulkPrice is None:
507
                    line.actual_price = deals[item_id].dealPrice
508
                else:
509
                    line.actual_price = bulkPrice.price
17812 amit.gupta 510
                if deals[item_id].dealTextOption==0:
511
                    line.dealText = ''
512
                if deals[item_id].dealTextOption==2:
513
                    line.dealText =  deals[item_id].dealText
514
 
515
                if deals[item_id].dealFreebieOption==0:
516
                    line.freebieId = 0
517
                if deals[item_id].dealFreebieOption==2:
518
                    line.freebieId =  deals[item_id].dealFreebieItemId
519
 
520
            else:
18418 kshitij.so 521
                if bulkPrice is None:
522
                    line.actual_price = item.sellingPrice
523
                else:
524
                    line.actual_price = bulkPrice.price 
17812 amit.gupta 525
                line.dealText = None
526
                line.freebieId = None
527
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
528
            try:
529
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
530
            except LogisticsServiceException:
531
                item_delivery_estimate = -1
532
                #TODO Use the exception clause to set the retval appropriately
533
            except :
534
                item_delivery_estimate = -1
535
 
536
            if item_delivery_estimate !=-1:
537
                inv_client = InventoryClient().get_client()
538
                itemAvailability = None
17803 amit.gupta 539
                try:
17812 amit.gupta 540
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
541
                except:
542
                    pass
543
 
544
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
545
                if itemAvailability is not None:
546
                    billingWarehouse = None
12893 manish.sha 547
                    try:
17812 amit.gupta 548
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
12893 manish.sha 549
                    except:
550
                        pass
12904 manish.sha 551
 
17812 amit.gupta 552
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
553
                    if billingWarehouse is not None:
554
                        estimateVal = None
555
                        if not logistics_client.isAlive() :
556
                            logistics_client = LogisticsClient().get_client()
12893 manish.sha 557
                        try:
17812 amit.gupta 558
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
559
                            if estimateVal ==-1:
560
                                item_delivery_estimate =-1
12893 manish.sha 561
                        except:
562
                            pass
17812 amit.gupta 563
                        print 'estimateVal Value ', estimateVal
564
            if old_estimate != item_delivery_estimate:
565
                line.estimate = item_delivery_estimate
566
                cart.updated_on = current_time
567
        else:
568
            Discount.query.filter(Discount.line==line).delete()
569
            line.delete()
570
    if cart.checked_out_on is not None:
571
        if cart.updated_on > cart.checked_out_on:
572
            cart.checked_out_on = None
573
    session.commit()
1976 varun.gupt 574
 
17812 amit.gupta 575
    if cart.coupon_code is not None:
576
        try:
577
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
578
            if updated_cart.message is not None:
579
                emival = updated_cart.message
580
        except PromotionException as ex:
581
            remove_coupon(cart.id)
582
            #retval = ex.message
583
    session.commit()
13136 amit.gupta 584
 
17812 amit.gupta 585
    cart = Cart.get_by(id=cartId)
586
    cart_lines = cart.lines
587
    map_lines = {}
13136 amit.gupta 588
 
17812 amit.gupta 589
    insurerFlag = False
590
    for line in cart_lines:
591
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
592
            line_map = {}
593
            line_map['insurer'] = line.insurer
594
            line_map['dpinsurer'] = line.dataProtectionInsurer
595
            line_map['amount'] = line.discounted_price if line.discounted_price else line.actual_price
596
            line_map['quantity'] = line.quantity
597
            insurerFlag = True
598
            map_lines[line.item_id] = line_map
599
 
600
    if insurerFlag:
601
        map_lines = inventory_client.checkServices(map_lines)
602
        for line in cart_lines :
603
            if map_lines.has_key(line.item_id):
604
                line_map = map_lines[line.item_id]
605
                if line_map['insurer'] > 0:
606
                    if cart.discounted_price:
607
                        cart.discounted_price = cart.discounted_price + line_map['insureramount']
608
                    line.insurer = line_map['insurer']
609
                    line.insuranceAmount = line_map['insureramount']
610
                    cart.total_price = cart.total_price + line_map['insureramount']
611
                if line_map['dpinsurer'] > 0:
612
                    if cart.discounted_price:
613
                        cart.discounted_price = cart.discounted_price + line_map['dpinsureramount']
614
                    line.dataProtectionInsurer = line_map['dpinsurer']
615
                    line.dataProtectionAmount = line_map['dpinsureramount']
616
                    cart.total_price = cart.total_price + line_map['dpinsureramount']
617
                line.updated_on = datetime.datetime.now()
17803 amit.gupta 618
        cart.updated_on = datetime.datetime.now()
13142 amit.gupta 619
        session.commit()
17812 amit.gupta 620
    session.close()
621
    return [retval, emival]
622
 
623
def merge_cart(fromCartId, toCartId):
624
    fromCart = Cart.get_by(id=fromCartId)
625
    toCart = Cart.get_by(id=toCartId)
557 chandransh 626
 
17812 amit.gupta 627
    old_lines = fromCart.lines
628
    new_lines = toCart.lines
557 chandransh 629
 
17812 amit.gupta 630
    for line in old_lines:
631
        for discount in line.discounts:
632
            discount.delete()
633
    session.commit()
634
 
635
    for line in old_lines:
636
        flag = True
637
        for new_line in new_lines:
638
            if line.item_id == new_line.item_id:
639
                flag = False
640
 
641
        if flag:
642
            line.cart_id = toCartId
643
        else:
644
            line.delete()
5345 rajveer 645
 
17812 amit.gupta 646
    if toCart.coupon_code is None:
647
        toCart.coupon_code = fromCart.coupon_code
2019 varun.gupt 648
 
17812 amit.gupta 649
    toCart.updated_on = datetime.datetime.now()
650
    fromCart.expired_on = datetime.datetime.now()
651
    fromCart.cart_status = CartStatus.INACTIVE
652
    session.commit()
653
 
654
def check_out(cartId):
655
    if cartId is None:
656
        raise ShoppingCartException(101, "Cart id not specified")
657
    cart = Cart.get_by(id = cartId)
658
    if cart is None:
659
        raise ShoppingCartException(102, "The specified cart couldn't be found")
660
    cart.checked_out_on = datetime.datetime.now()
661
    session.commit()
662
    return True
663
 
664
def reset_cart(cartId, items):
665
    if cartId is None:
666
        raise ShoppingCartException(101, "Cart id not specified")
667
    for item_id, quantity in items.iteritems():
668
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
669
        if line is not None:
670
            delete_discounts_for_line(line)
671
            line.discounted_price = None
672
            line.quantity = line.quantity - quantity
673
            if line.quantity == 0:
674
                line.delete()
675
    cart = Cart.get_by(id=cartId)
676
    cart.updated_on = datetime.datetime.now()
677
    cart.checked_out_on = None
1976 varun.gupt 678
 
17812 amit.gupta 679
    # Removing Coupon
680
    cart.total_price = None
681
    cart.discounted_price = None
682
    cart.coupon_code = None
20873 kshitij.so 683
    cart.wallet_amount = 0.0
17812 amit.gupta 684
 
685
    session.commit()
686
    return True
687
 
688
def get_carts_with_coupon_count(coupon_code):
689
    return Cart.query.filter_by(coupon_code = coupon_code).count()
690
 
691
def show_cod_option(cartId, sourceId, pincode):
692
    cart = Cart.get_by(id = cartId)
693
    cod_option = True
694
    logistics_client = LogisticsClient().get_client()
695
    if cart:
20981 amit.gupta 696
        itemIds = []
697
        for line in cart.lines:
698
            itemIds.append(line.item_id)
21081 amit.gupta 699
#        catalog_client = CatalogClient().get_client()
700
#        items = catalog_client.getItems(itemIds).values()
701
#        for item in items:
702
#            if item.category not in [10006, 10010]:
703
#                return False
20981 amit.gupta 704
 
17812 amit.gupta 705
        if cart.coupon_code:
706
            promotion_client = PromotionClient().get_client()
707
            cod_option = promotion_client.isCodApplicable(to_t_cart(cart))
5351 varun.gupt 708
 
17812 amit.gupta 709
        if cod_option and cart.lines:
710
            for line in cart.lines:
18844 amit.gupta 711
                try:
712
                    logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
713
                    if not logistics_info.codAllowed:
714
                        cod_option = False
715
                        break
716
                except:
717
                    pass    
21081 amit.gupta 718
            if cart.total_price > 150000:
17812 amit.gupta 719
                cod_option = False
720
    return cod_option
721
 
722
def get_products_added_to_cart(startDate, endDate):
723
    lines = session.query(Line.item_id).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).all()
724
    datas = []
725
    for line in lines:
726
        datas.append(line[0])
727
    return datas
728
 
729
def insure_item(itemId, cartId, toInsure, insurerType):
730
    cart = Cart.get_by(id = cartId)
731
    line = None
732
    for cartLine in cart.lines:
733
        if(cartLine.item_id == itemId):
734
            line = cartLine
735
            break
11655 amit.gupta 736
 
17812 amit.gupta 737
    if not line:
738
        print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
739
        return False
11655 amit.gupta 740
 
17812 amit.gupta 741
    try:
742
        if toInsure:
743
            csc = CatalogClient().get_client()
744
            item = csc.getItem(itemId)
745
            insurerId = csc.getPrefferedInsurerForItem(itemId,insurerType)
746
            insuranceAmount = csc.getInsuranceAmount(itemId, line.discounted_price if line.discounted_price else line.actual_price, insurerId, line.quantity)
747
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
9299 kshitij.so 748
                if cart.discounted_price:
17812 amit.gupta 749
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount + insuranceAmount
750
                line.insurer = insurerId
751
                line.insuranceAmount = insuranceAmount
752
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
753
                if cart.discounted_price:
754
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount + insuranceAmount
755
                line.dataProtectionInsurer = insurerId
756
                line.dataProtectionAmount = insuranceAmount
757
            cart.total_price = cart.total_price + insuranceAmount
758
        else:
759
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
760
                cart.total_price = cart.total_price - line.insuranceAmount
761
                if cart.discounted_price:
762
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount
763
                line.insurer = 0
764
                line.insuranceAmount = 0
765
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
766
                cart.total_price = cart.total_price - line.dataProtectionAmount
767
                if cart.discounted_price:
768
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount
769
                line.dataProtectionInsurer = 0
770
                line.dataProtectionAmount = 0
771
        line.updated_on = datetime.datetime.now()
772
        cart.updated_on = datetime.datetime.now()
773
        session.commit()
774
    except:
775
        print("Error : Unable to insure")
776
        print("insurerId : " + str(insurerId) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
777
        return False
6903 anupam.sin 778
 
17812 amit.gupta 779
    return True
780
 
781
def cancel_insurance(cartId):
782
    try:
783
        cart = Cart.get_by(id = cartId)
784
        for cartLine in cart.lines:
785
            cart.total_price = cart.total_price - cartLine.insuranceAmount
786
            if cart.discounted_price:
787
                cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
788
            cartLine.insurer = 0
789
            cartLine.insuranceAmount = 0
790
            cartLine.updated_on = datetime.datetime.now()
791
        cart.updated_on = datetime.datetime.now()
792
        session.commit()
793
    except:
794
        print("Error : Unable to cancel insurance for cartId :" + str(cartId))
795
        return False
6903 anupam.sin 796
 
17812 amit.gupta 797
    return True
798
 
799
def store_insurance_specific_details(addressId, dob, guardianName):
800
    try:
801
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
802
        if insuranceDetails is None :
803
            insuranceDetails = InsuranceDetails()
804
        insuranceDetails.addressId = addressId
805
        insuranceDetails.dob = dob
806
        insuranceDetails.guardianName = guardianName
807
        session.commit()
808
    except:
809
        print("Error : Unable to store insurance details for addressId : " + str(addressId))
810
        return False
811
    return True
812
 
813
def is_insurance_detail_present(addressId):
814
    try:
815
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
816
        if insuranceDetails is None :
6903 anupam.sin 817
            return False
17812 amit.gupta 818
    except:
819
        print("Error : Unable to get insurance details for addressId : " + str(addressId))
820
        return False
821
    return True
822
 
823
 
824
def add_items_to_cart(cartId, itemQty, couponCode=None):
825
    try: 
826
        found_cart = Cart.get_by(id=cartId)
827
        itemQtyMap = {}
828
        current_time = datetime.datetime.now()
829
        for itemqty in itemQty:
830
            itemQtyMap[itemqty.itemId] = itemqty.qty 
831
 
832
        if found_cart.lines:
833
            for line in found_cart.lines:
19161 amit.gupta 834
                    Discount.query.filter(Discount.line==line).delete()
17812 amit.gupta 835
                    line.delete()
836
        for itemId,qty in itemQtyMap.iteritems():
837
            #This condition will ensure that cart is only persisted with non-zero quantities.
838
            if qty==0:
839
                continue
840
            line = Line()
841
            line.cart = found_cart
842
            line.item_id = itemId
843
            line.quantity = qty
844
            line.created_on = current_time
845
            line.updated_on = current_time
846
            line.line_status = LineStatus.LINE_ACTIVE
847
            line.insurer = 0
848
            line.insuranceAmount = 0
849
        if couponCode:
850
            found_cart.coupon_code = couponCode
851
        else:
852
            found_cart.coupon_code = None
853
        session.commit()
17782 amit.gupta 854
        return True
17812 amit.gupta 855
    except:
856
        traceback.print_exc()
857
        return False
858
 
17782 amit.gupta 859
 
22721 amit.gupta 860
 
861
def validate_fofo_cart(cart, user, privateDealUser, customer_pincode):
862
    current_time = datetime.datetime.now()
863
    totalQty = 0
864
    totalAmount = 0
865
    cartMessages = []
866
    cartItems = []
867
    responseMap = {}
868
    cartMessageChanged = 0
869
    cartMessageOOS = 0
870
    codAllowed = False
871
    cartMessageUndeliverable = 0
872
 
873
    itemIds = [cartLine.item_id for cartLine in cart.lines]
874
 
875
    catalog_client = CatalogClient().get_client()
876
    #logistics_client = LogisticsClient().get_client()
877
    #promotion_client = PromotionClient().get_client()
878
    inv_client = InventoryClient().get_client()
879
 
880
    fofoDealsMap = catalog_client.getAllFofoDeals(itemIds, [4, 7])    
881
    fofoDealsAvailability = inv_client.getFofoAvailability(fofoDealsMap.keys())
882
 
883
 
884
 
885
    itemsMap = catalog_client.getItems(itemIds)
886
    cart_lines = cart.lines
887
    cart.total_price = 0
23478 amit.gupta 888
    nonAccessoryQuantity = 0
22721 amit.gupta 889
    for line in cart_lines:
890
        itemQuantityChanged=False
891
        cartItem={}
892
        tempBulkItemList = []
893
 
894
        old_estimate = line.estimate
895
        item_id = line.item_id
896
        item = itemsMap.get(item_id)
897
        #in case item is missing remove that line
898
        #lets silently remvoe fofoDealsMap as fofo customer is not allowed to orders with fofo
899
        if item is None or item.itemStatus==0 or not fofoDealsMap.has_key(item.id):
900
            Discount.query.filter(Discount.line==line).delete()
901
            line.delete()
902
            continue
903
        cartItem['itemId']=line.item_id
904
        cartItem['quantity']=0
905
        cartItem['cartItemMessages']=[]
906
        cartItemMessages = cartItem['cartItemMessages']
907
        cartItem['color'] = item.color
908
        cartItem['catalogItemId'] = item.catalogItemId
909
        cartItem['packQuantity'] = item.packQuantity
910
        cartItem['minBuyQuantity'] = item.minimumBuyQuantity
911
        cartItem['quantityStep'] = item.quantityStep
912
        cartItem['bulkPricing'] = tempBulkItemList
913
        cartItem['maxQuantity'] =0
23446 amit.gupta 914
        #This should be removed
915
        fofoDealsAvailability[item_id] = 10
22721 amit.gupta 916
        if not fofoDealsAvailability.has_key(item_id):
917
            continue
918
        else:
919
            availability = fofoDealsAvailability.get(item_id)
920
            if availability < line.quantity:
921
                line.quantity = availability
922
                itemQuantityChanged=True
923
            cartItem['maxQuantity'] = min(availability,100)
924
            if item.maximumBuyQuantity is not None and item.maximumBuyQuantity >0:
22723 amit.gupta 925
                cartItem['maxQuantity'] = min(availability, item.maximumBuyQuantity)
22721 amit.gupta 926
            if availability < cartItem['minBuyQuantity']:
927
                cartItem['minBuyQuantity'] = availability 
928
 
929
            if line.quantity < cartItem['minBuyQuantity']:
930
                itemQuantityChanged=True
931
                line.quantity = cartItem['minBuyQuantity']
932
 
933
            if line.quantity > cartItem['maxQuantity']:
934
                itemQuantityChanged=True
935
                line.quantity = cartItem['maxQuantity']
936
 
937
            cartItem['quantity'] = line.quantity
23478 amit.gupta 938
            line.actual_price = fofoDealsMap.get(item_id)
939
            if item.category in [10006, 10010]:
940
                nonAccessoryQuantity += cartItem['quantity'] 
23480 amit.gupta 941
                cartItem['categoryName'] = "mobile" 
22721 amit.gupta 942
 
943
        cartItem['sellingPrice'] = line.actual_price
944
        cartItem['bulkPricing'] = []
945
 
22723 amit.gupta 946
        if availability:
22721 amit.gupta 947
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
948
            ##Lets assign hardcoded deliveryestimate for fofo
949
            item_delivery_estimate = 2
950
            codAllowed = False
951
            cartItem['estimate'] = item_delivery_estimate
952
            if itemQuantityChanged:
953
                cartMessageChanged += 1
22723 amit.gupta 954
                cartItemMessages.append({"type":"danger", "messageText":"Only " + str(item.maximumBuyQuantity) + " available"})
22721 amit.gupta 955
            if old_estimate != item_delivery_estimate:
956
                line.estimate = item_delivery_estimate
957
                cart.updated_on = current_time
958
            totalAmount += line.actual_price * cartItem['quantity']
959
        else:
960
            cartItem['quantity'] = 0
961
            cartMessageOOS += 1
962
            cartItemMessages.append({"type":"danger", "messageText":"Out of Stock"})
963
            Discount.query.filter(Discount.line==line).delete()
964
            line.delete()
965
        totalQty += cartItem['quantity']
966
 
967
        if cartItemMessages:
968
            cartItems.insert(0, cartItem)
969
        else:
970
            cartItems.append(cartItem)
971
    if cart.checked_out_on is not None:
972
        if cart.updated_on > cart.checked_out_on:
973
            cart.checked_out_on = None
974
    session.commit()
975
 
976
    responseMap['totalQty']= totalQty
977
    responseMap['totalAmount']= totalAmount
23479 amit.gupta 978
    responseMap['nonAccessoryQuantity']= nonAccessoryQuantity
22721 amit.gupta 979
    responseMap['cartMessages']= cartMessages
980
    responseMap['cartItems']= cartItems
981
    responseMap['pincode']= customer_pincode
982
    responseMap['shippingCharge'] = 0
983
    responseMap['cartMessageChanged'] = cartMessageChanged
984
    responseMap['cartMessageOOS'] = cartMessageOOS
985
    responseMap['cartMessageUndeliverable'] = cartMessageUndeliverable
986
    responseMap['codAllowed'] = codAllowed
987
    return json.dumps(responseMap)         
988
 
989
 
990
 
20981 amit.gupta 991
def validate_cart_new(cartId, customer_pincode, sourceId):
17782 amit.gupta 992
 
17812 amit.gupta 993
    # No need to validate duplicate items since there are only two ways
994
    # to add items to a cart and both of them check whether the item being
995
    # added is a duplicate of an already existing item.
996
    cart = Cart.get_by(id=cartId)
997
    cart_lines = cart.lines
998
    current_time = datetime.datetime.now()
999
 
21454 amit.gupta 1000
    #if customer_pincode is 000000 pincode should be considered from address or
1001
    #is address is not present treat is as customer input
17812 amit.gupta 1002
    user = User.get_by(active_cart_id = cartId)
22721 amit.gupta 1003
    privateDealUser = PrivateDealUser.get_by(id=user.id)
21454 amit.gupta 1004
    if customer_pincode == "000000":
1005
        address = Address.get_by(id=cart.address_id)
1006
        if address:
1007
            customer_pincode = address.pin
1008
 
23081 amit.gupta 1009
    catalog_client = CatalogClient().get_client()
1010
    itemIds = [cartLine.item_id for cartLine in cart.lines]
22721 amit.gupta 1011
    if privateDealUser is not None and privateDealUser.isActive and privateDealUser.isFofo:
23081 amit.gupta 1012
        fofoDealsMap = catalog_client.getAllFofoDeals(itemIds, [4, 7])
1013
        if fofoDealsMap:
1014
            return validate_fofo_cart(cart, user, privateDealUser, customer_pincode)
1015
 
21454 amit.gupta 1016
 
1017
    logistics_client = LogisticsClient().get_client()
1018
 
17812 amit.gupta 1019
    responseMap = {}
1020
    totalQty = 0
20990 amit.gupta 1021
    nonAccessoryQuantity = 0
17812 amit.gupta 1022
    totalAmount = 0 
1023
    shippingCharges=0
1024
    cartMessages=[]
1025
    cartItems = []
1026
    dealItems = []
22583 amit.gupta 1027
    deals = {}
18418 kshitij.so 1028
    bulkPricingMap ={}
1029
    bulkPricingItems =[]
17782 amit.gupta 1030
 
21454 amit.gupta 1031
 
17812 amit.gupta 1032
    if privateDealUser is not None and privateDealUser.isActive:
22721 amit.gupta 1033
        deals = catalog_client.getAllActivePrivateDeals(itemIds, 0)
1034
        bulkPricingMap = catalog_client.getBulkPricingForItems(itemIds)
22571 amit.gupta 1035
        dealItems = deals.keys()
22566 amit.gupta 1036
        bulkPricingItems = bulkPricingMap.keys()
17812 amit.gupta 1037
 
1038
    cart.total_price = 0
22301 amit.gupta 1039
    itemsMap = catalog_client.getItems(itemIds)
17789 amit.gupta 1040
 
17812 amit.gupta 1041
    cartMessageChanged = 0
1042
    cartMessageOOS = 0
1043
    cartMessageUndeliverable = 0
21454 amit.gupta 1044
    codAllowed = True
17789 amit.gupta 1045
 
18521 kshitij.so 1046
 
1047
 
17812 amit.gupta 1048
    for line in cart_lines:
17865 amit.gupta 1049
        itemQuantityChanged=False
17812 amit.gupta 1050
        cartItem={}
18418 kshitij.so 1051
        tempBulkItemList = []
17782 amit.gupta 1052
 
17812 amit.gupta 1053
        old_estimate = line.estimate
1054
        item_id = line.item_id
1055
        item = itemsMap.get(item_id)
22239 amit.gupta 1056
        #in case item is missing remove that line
1057
        if item is None or item.itemStatus==0:
18375 amit.gupta 1058
            Discount.query.filter(Discount.line==line).delete()
1059
            line.delete()
1060
            continue
17812 amit.gupta 1061
        cartItem['itemId']=line.item_id
1062
        cartItem['quantity']=0
17813 amit.gupta 1063
        cartItem['cartItemMessages']=[]
1064
        cartItemMessages = cartItem['cartItemMessages']
17812 amit.gupta 1065
        cartItem['color'] = item.color
1066
        cartItem['catalogItemId'] = item.catalogItemId
18006 manish.sha 1067
        cartItem['packQuantity'] = item.packQuantity
18431 kshitij.so 1068
        cartItem['minBuyQuantity'] = item.minimumBuyQuantity
1069
        cartItem['quantityStep'] = item.quantityStep
18418 kshitij.so 1070
        cartItem['bulkPricing'] = tempBulkItemList
18521 kshitij.so 1071
 
22301 amit.gupta 1072
        item_shipping_info = catalog_client.isActive(item_id) 
18521 kshitij.so 1073
        if item_shipping_info.isActive:
1074
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
1075
                line.quantity = item_shipping_info.quantity
1076
                itemQuantityChanged=True
22461 amit.gupta 1077
            cartItem['maxQuantity'] = min(item_shipping_info.quantity,100)
1078
            if item.maximumBuyQuantity is not None and item.maximumBuyQuantity >0:
1079
                cartItem['maxQuantity'] = min(item_shipping_info.quantity, item.maximumBuyQuantity)
18534 kshitij.so 1080
        else:
1081
            cartItem['maxQuantity'] =0
1082
 
18521 kshitij.so 1083
 
1084
        if item_shipping_info.quantity < cartItem['minBuyQuantity']:
1085
            cartItem['minBuyQuantity'] = item_shipping_info.quantity 
1086
 
1087
        if line.quantity < cartItem['minBuyQuantity']:
1088
            itemQuantityChanged=True
1089
            line.quantity = cartItem['minBuyQuantity']
1090
 
1091
        if line.quantity > cartItem['maxQuantity']:
1092
            itemQuantityChanged=True
1093
            line.quantity = cartItem['maxQuantity']
18523 kshitij.so 1094
 
1095
        cartItem['quantity'] = line.quantity
1096
 
18418 kshitij.so 1097
        bulkPrice = None
18482 kshitij.so 1098
        singleUnitPricing = False
22461 amit.gupta 1099
        if item_id in bulkPricingItems:
18418 kshitij.so 1100
            #Check quantity qualifies or not
1101
            bulkPricingList = bulkPricingMap.get(item_id)
1102
            bulkPricingList = sorted(bulkPricingList, key=lambda x: x.quantity, reverse=False)
1103
            for pricingItems in bulkPricingList:
18482 kshitij.so 1104
                if pricingItems.quantity ==1:
1105
                    singleUnitPricing = True
18418 kshitij.so 1106
                if pricingItems.quantity <= line.quantity:
1107
                    bulkPrice = pricingItems
18482 kshitij.so 1108
                tempBulkItemList.append({'quantity':pricingItems.quantity,'price':pricingItems.price})
18418 kshitij.so 1109
 
17903 amit.gupta 1110
        if item_id in dealItems:
22461 amit.gupta 1111
            if not singleUnitPricing and item_id in bulkPricingItems:
18482 kshitij.so 1112
                tempBulkItemList.append({'quantity':1,'price':deals[item_id].dealPrice})
18418 kshitij.so 1113
            if bulkPrice is None:
1114
                line.actual_price = deals[item_id].dealPrice
1115
            else:
1116
                line.actual_price = bulkPrice.price
17903 amit.gupta 1117
            if deals[item_id].dealTextOption==0:
1118
                line.dealText = ''
1119
            if deals[item_id].dealTextOption==2:
1120
                line.dealText = deals[item_id].dealText
1121
 
1122
            if deals[item_id].dealFreebieOption==0:
1123
                line.freebieId = 0
1124
            if deals[item_id].dealFreebieOption==2:
1125
                line.freebieId =  deals[item_id].dealFreebieItemId
1126
            cartItem['dealText'] = line.dealText
1127
        else:
18482 kshitij.so 1128
            if not singleUnitPricing and item_id in bulkPricingItems:
1129
                tempBulkItemList.append({'quantity':1,'price':item.sellingPrice})
18418 kshitij.so 1130
            if bulkPrice is None:
1131
                line.actual_price = item.sellingPrice
1132
            else:
1133
                line.actual_price = bulkPrice.price
17903 amit.gupta 1134
            if item.bestDealText:
1135
                cartItem['dealText'] = item.bestDealText
1136
            line.dealText = None
1137
            line.freebieId = None
22566 amit.gupta 1138
 
17903 amit.gupta 1139
        cartItem['sellingPrice'] = line.actual_price
1140
 
18539 kshitij.so 1141
        toRemove = []
18536 kshitij.so 1142
        for dictbulkPricing in cartItem['bulkPricing']:
1143
            if dictbulkPricing['quantity'] < cartItem['minBuyQuantity'] or dictbulkPricing['quantity'] > cartItem['maxQuantity']:
18539 kshitij.so 1144
                toRemove.append(dictbulkPricing)
1145
        for removePricing in toRemove:
1146
            cartItem['bulkPricing'].remove(removePricing)
18541 kshitij.so 1147
        cartItem['bulkPricing'] = sorted(cartItem['bulkPricing'], key=lambda k: k['quantity'],reverse=False)
21454 amit.gupta 1148
 
1149
        print "item_shipping_info", item_shipping_info        
17812 amit.gupta 1150
        if item_shipping_info.isActive:
1151
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
1152
            try:
21454 amit.gupta 1153
                item_delivery_estimate_tuple = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID)
1154
                item_delivery_estimate = item_delivery_estimate_tuple.deliveryTime
1155
                print "item_delivery_estimate", item_delivery_estimate 
1156
                if item_delivery_estimate:
1157
                    codAllowed = codAllowed and item_delivery_estimate_tuple.codAllowed 
17812 amit.gupta 1158
            except LogisticsServiceException:
21454 amit.gupta 1159
                traceback.print_exc()
17812 amit.gupta 1160
                item_delivery_estimate = -1
1161
                #TODO Use the exception clause to set the retval appropriately
1162
            except :
21454 amit.gupta 1163
                traceback.print_exc()
17812 amit.gupta 1164
                item_delivery_estimate = -1
17782 amit.gupta 1165
 
17812 amit.gupta 1166
            if item_delivery_estimate !=-1:
1167
                inv_client = InventoryClient().get_client()
1168
                itemAvailability = None
1169
                try:
23450 amit.gupta 1170
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1, -1)
17812 amit.gupta 1171
                except:
1172
                    pass
17803 amit.gupta 1173
 
17812 amit.gupta 1174
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
1175
                if itemAvailability is not None:
1176
                    billingWarehouse = None
17782 amit.gupta 1177
                    try:
17812 amit.gupta 1178
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
17782 amit.gupta 1179
                    except:
21454 amit.gupta 1180
                        traceback.print_exc()
17782 amit.gupta 1181
                        pass
1182
 
17812 amit.gupta 1183
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
1184
                    if billingWarehouse is not None:
1185
                        estimateVal = None
1186
                        if not logistics_client.isAlive() :
1187
                            logistics_client = LogisticsClient().get_client()
17782 amit.gupta 1188
                        try:
22721 amit.gupta 1189
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.logisticsLocation)
17812 amit.gupta 1190
                            if estimateVal ==-1:
1191
                                item_delivery_estimate =-1
17782 amit.gupta 1192
                        except:
21454 amit.gupta 1193
                            traceback.print_exc()
17782 amit.gupta 1194
                            pass
17812 amit.gupta 1195
                        print 'estimateVal Value ', estimateVal
1196
            cartItem['estimate'] = item_delivery_estimate
1197
            if item_delivery_estimate == -1:
18951 amit.gupta 1198
                Discount.query.filter(Discount.line==line).delete()
1199
                line.delete()
17782 amit.gupta 1200
                cartItem['quantity'] = 0
17812 amit.gupta 1201
                cartMessageUndeliverable += 1
17836 amit.gupta 1202
                cartItemMessages.append({"type":"danger", "messageText":"Undeliverable"})
17865 amit.gupta 1203
            elif itemQuantityChanged:
1204
                cartMessageChanged += 1
1205
                cartItemMessages.append({"type":"danger", "messageText":"Only " + str(item_shipping_info.quantity) + " available"})
17812 amit.gupta 1206
            if old_estimate != item_delivery_estimate:
1207
                line.estimate = item_delivery_estimate
1208
                cart.updated_on = current_time
17903 amit.gupta 1209
            totalAmount += line.actual_price * cartItem['quantity']
17812 amit.gupta 1210
        else:
1211
            cartItem['quantity'] = 0
1212
            cartMessageOOS += 1
1213
            cartItemMessages.append({"type":"danger", "messageText":"Out of Stock"})
1214
            Discount.query.filter(Discount.line==line).delete()
1215
            line.delete()
1216
        totalQty += cartItem['quantity']
20990 amit.gupta 1217
        if item.category in [10006, 10010]:
1218
            nonAccessoryQuantity += cartItem['quantity']
17812 amit.gupta 1219
        if cartItemMessages:
1220
            cartItems.insert(0, cartItem)
1221
        else:
1222
            cartItems.append(cartItem)
1223
    if cart.checked_out_on is not None:
1224
        if cart.updated_on > cart.checked_out_on:
1225
            cart.checked_out_on = None
1226
    session.commit()
1227
 
1228
    if cart.coupon_code is not None:
1229
        try:
23194 amit.gupta 1230
            promotion_client = PromotionClient().get_client()
17812 amit.gupta 1231
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
1232
            if updated_cart.message is not None:
1233
                emival = updated_cart.message
1234
        except PromotionException as ex:
1235
            remove_coupon(cart.id)
1236
            #retval = ex.message
1237
    session.commit()
1238
 
1239
    cart = Cart.get_by(id=cartId)
1240
    cart_lines = cart.lines
1241
    insurerFlag = False
1242
    for line in cart_lines:
1243
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
1244
            line.insurer = 0
1245
            line.insuranceAmount = 0 
1246
            line.dataProtectionInsurer = 0
1247
            line.dataProtectionAmount = 0
1248
            insurerFlag = True
17782 amit.gupta 1249
 
17812 amit.gupta 1250
    if insurerFlag:
1251
        cart.updated_on = datetime.datetime.now()
17782 amit.gupta 1252
        session.commit()
17812 amit.gupta 1253
    session.close()
1254
    responseMap['totalQty']= totalQty
1255
    responseMap['totalAmount']= totalAmount
22210 amit.gupta 1256
    if totalAmount < 1000:
23095 amit.gupta 1257
        shippingCharges = 100
22211 amit.gupta 1258
    responseMap['cartMessages']= cartMessages
1259
    responseMap['cartItems']= cartItems
1260
    responseMap['pincode']= customer_pincode
17812 amit.gupta 1261
    responseMap['shippingCharge']=shippingCharges
1262
    responseMap['cartMessageChanged'] = cartMessageChanged
1263
    responseMap['cartMessageOOS'] = cartMessageOOS
1264
    responseMap['cartMessageUndeliverable'] = cartMessageUndeliverable
21454 amit.gupta 1265
    responseMap['codAllowed'] = codAllowed
22749 amit.gupta 1266
    print "responseMap", responseMap
17812 amit.gupta 1267
    return json.dumps(responseMap)
1268
 
1269
 
1270
def validate_cart_plus(cart_id, source_id, couponCode):
1271
    try:
1272
        cart_messages = validate_cart(cart_id, source_id, couponCode)
1273
        found_cart = Cart.get_by(id=cart_id)
1274
        pincode = "110001"
1275
        default_address_id = User.get_by(active_cart_id = cart_id).default_address_id
11598 amit.gupta 1276
 
17812 amit.gupta 1277
        default_address = None
1278
        if found_cart.address_id is not None and found_cart.address_id > 0:
1279
            pincode = Address.get_by(id=found_cart.address_id).pin
1280
        elif default_address_id is not None:
1281
            default_address = Address.get_by(id = default_address_id) 
1282
            pincode = default_address.pin
11592 amit.gupta 1283
 
18418 kshitij.so 1284
        needInsuranceInfo = False
17812 amit.gupta 1285
        if default_address_id is not None:
1286
            for line in found_cart.lines:
1287
                if line.insurer > 0:
18418 kshitij.so 1288
                    needInsuranceInfo = not is_insurance_detail_present(default_address_id)
17812 amit.gupta 1289
                    break
1290
        cartPlus = CartPlus()
1291
        cartPlus.cart = to_t_cart(found_cart)
1292
        cartPlus.pinCode = pincode
1293
        cartPlus.validateCartMessages = cart_messages
18418 kshitij.so 1294
        cartPlus.needInsuranceInfo = needInsuranceInfo
17812 amit.gupta 1295
        return cartPlus
1296
    finally:
1297
        close_session()
1298
 
1299
def close_session():
1300
    if session.is_active:
1301
        print "session is active. closing it."
18844 amit.gupta 1302
        session.close()
1303
 
20873 kshitij.so 1304
 
1305
def set_wallet_amount_in_cart(cartId, wallet_amount):
1306
    cart = Cart.get_by(id = cartId)
1307
    if cart is None:
1308
        raise ShoppingCartException(102, "The specified cart couldn't be found")
1309
    if wallet_amount < 0:
1310
        raise ShoppingCartException(103, "Wallet amount is negative")
1311
    cart.wallet_amount = wallet_amount
1312
    session.commit()
22452 amit.gupta 1313
    return True
1314
 
1315
 
1316
def add_item_pricing_to_cart(cartId, itemQtyPriceList):
1317
    try: 
1318
        found_cart = Cart.get_by(id=cartId)
1319
 
1320
        #Get prices to validate should not be less than mop
1321
        current_time = datetime.datetime.now()
1322
 
1323
        if found_cart.lines:
1324
            for line in found_cart.lines:
1325
                Discount.query.filter(Discount.line==line).delete()
1326
                line.delete()
1327
        for itemQtyPrice in itemQtyPriceList:
1328
            #This condition will ensure that cart is only persisted with non-zero quantities.
1329
            if itemQtyPrice.qty==0:
1330
                continue
1331
            line = Line()
1332
            line.cart = found_cart
1333
            print "itemQtyPrice.itemId-------", itemQtyPrice.itemId
1334
            line.item_id = itemQtyPrice.itemId
1335
            line.quantity = itemQtyPrice.qty
1336
            line.created_on = current_time
1337
            line.updated_on = current_time
1338
            line.line_status = LineStatus.LINE_ACTIVE
1339
            line.insurer = 0
1340
            line.insuranceAmount = 0
1341
            line.actual_price = itemQtyPrice.price
1342
        found_cart.coupon_code = None
1343
        session.commit()
1344
        return True
1345
 
1346
    except:
1347
        traceback.print_exc()
1348
        return False