Subversion Repositories SmartDukaan

Rev

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