Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
557 chandransh 1
'''
2
Created on 10-May-2010
3
 
4
@author: ashish
5
'''
6
from elixir import *
6921 anupam.sin 7
from shop2020.clients.CatalogClient import CatalogClient
13136 amit.gupta 8
from shop2020.clients.InventoryClient import InventoryClient
6921 anupam.sin 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
13136 amit.gupta 13
from shop2020.model.v1.user.impl.Converters import to_t_cart, to_t_line
6921 anupam.sin 14
from shop2020.model.v1.user.impl.Dataservice import Cart, Line, Address, User, \
11980 amit.gupta 15
    Discount, InsuranceDetails, PrivateDealUser
6921 anupam.sin 16
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, \
17
    DeliveryType
9299 kshitij.so 18
from shop2020.thriftpy.model.v1.catalog.ttypes import Item, InsurerType
6921 anupam.sin 19
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as TTransaction, \
20
    TransactionStatus as TTransactionStatus, Order as TOrder, LineItem as TLineItem, \
7504 rajveer 21
    OrderStatus, OrderSource
6921 anupam.sin 22
from shop2020.thriftpy.model.v1.user.ttypes import CartStatus, LineStatus, \
11592 amit.gupta 23
    ShoppingCartException, PromotionException, CartPlus
6921 anupam.sin 24
from shop2020.utils.Utils import to_py_date, to_java_date
557 chandransh 25
import datetime
17470 manish.sha 26
import math
557 chandransh 27
 
28
 
576 chandransh 29
 
30
 
5326 rajveer 31
def get_cart(userId):
32
    user = User.get_by(id=userId)
33
    return user.active_cart
557 chandransh 34
 
35
def get_cart_by_id(id):
36
    cart = Cart.get_by(id=id)
37
    return cart
38
 
5326 rajveer 39
def create_cart():
40
    cart = Cart()
41
    cart.created_on = datetime.datetime.now()
42
    cart.updated_on = datetime.datetime.now()
43
    cart.cart_status = CartStatus.ACTIVE
557 chandransh 44
    return cart
45
 
46
def get_carts_between(start_time, end_time, status):
47
    init_time = to_py_date(start_time)
48
    finish_time = to_py_date(end_time)
49
 
50
    query = Cart.query
51
    if status:
52
        query = query.filter(Cart.cart_status==status)
53
    if init_time:
54
        query = query.filter(Cart.created_on >= init_time)
55
    if finish_time:
56
        query = query.filter(Cart.created_on <= finish_time)
57
 
58
    carts = query.all()
59
    return carts
60
 
643 chandransh 61
def get_line(item_id, cart_id, status, single):
557 chandransh 62
    #get cart first 
63
    try:
64
        found_cart = Cart.get_by(id=cart_id)
65
    except:
66
        raise ShoppingCartException(101, "cart not found ")
643 chandransh 67
    query = Line.query.filter_by(cart = found_cart, item_id = item_id)
557 chandransh 68
 
69
    if status:
70
        query = query.filter_by(line_status = status)
71
    else:
72
        query = query.filter_by(line_status = LineStatus.LINE_ACTIVE)
73
    try:
74
        if single:
75
            return query.one()
76
        else:
77
            return query.all()
78
    except:
79
        return None
80
 
3557 rajveer 81
def add_item_to_cart(cart_id, item_id, quantity, sourceId):
557 chandransh 82
    if not item_id:
83
        raise ShoppingCartException(101, "item_id cannot be null")
84
 
85
    if not quantity:
86
        raise ShoppingCartException(101, "quantity cannot be null")    
643 chandransh 87
 
2983 chandransh 88
    cart = Cart.get_by(id = cart_id)    
557 chandransh 89
    if not cart:
6502 rajveer 90
        raise ShoppingCartException(101, "no cart attached to this id" + str(cart_id))
2983 chandransh 91
    retval = ""
6550 rajveer 92
    catalog_client = CatalogClient().get_client()
93
    item = catalog_client.getItemForSource(item_id, sourceId)
9299 kshitij.so 94
    dataProtectionInsurer = catalog_client.getPrefferedInsurerForItem(item_id,InsurerType._NAMES_TO_VALUES.get("DATA"))
6550 rajveer 95
    item_shipping_info = catalog_client.isActive(item_id)
2983 chandransh 96
    if not item_shipping_info.isActive:
6550 rajveer 97
        return catalog_client.getItemStatusDescription(item_id)
557 chandransh 98
 
643 chandransh 99
    current_time = datetime.datetime.now()
100
    cart.updated_on = current_time
101
    line = get_line(item_id, cart_id, None,True)
102
    if line:
103
        #change the quantity only
6903 anupam.sin 104
        line.insuranceAmount = (line.insuranceAmount/line.quantity) * quantity
643 chandransh 105
        line.quantity = quantity
685 chandransh 106
        line.updated_on = current_time
9299 kshitij.so 107
        line.dataProtectionAmount = (line.dataProtectionAmount/line.quantity) * quantity
643 chandransh 108
    else:
109
        line = Line()
110
        line.cart = cart
111
        line.item_id = item_id
112
        line.quantity = quantity
113
        line.created_on = current_time
114
        line.updated_on = current_time
3557 rajveer 115
        line.actual_price = item.sellingPrice
643 chandransh 116
        line.line_status = LineStatus.LINE_ACTIVE
6903 anupam.sin 117
        line.insurer = 0
118
        line.insuranceAmount = 0
9299 kshitij.so 119
        #DATA INSURER IS SET UPON ADD TO CART
120
        line.dataProtectionInsurer = dataProtectionInsurer
557 chandransh 121
    session.commit()
2983 chandransh 122
    return retval
557 chandransh 123
 
124
def delete_item_from_cart(cart_id, item_id):
125
    if not item_id:
126
        raise ShoppingCartException(101, "item_id cannot be null")
685 chandransh 127
    cart = Cart.get_by(id = cart_id)
128
    if not cart:
129
        raise ShoppingCartException(101, "no cart attached to this id")
643 chandransh 130
    item = get_line(item_id, cart_id, None, True)
3554 varun.gupt 131
    count_deleted_discounts = delete_discounts_for_line(item)
557 chandransh 132
    item.delete()
685 chandransh 133
    current_time = datetime.datetime.now()
134
    cart.updated_on = current_time
557 chandransh 135
    session.commit()
136
 
3554 varun.gupt 137
def delete_discounts_for_line(item_line):
138
    count_deleted = Discount.query.filter_by(line = item_line).delete()
139
    session.commit()
140
    return count_deleted
141
 
142
def delete_discounts_from_cart(cart_id, cart = None):
143
    if cart is None:
144
        if cart_id is None:
145
            raise ShoppingCartException(101, 'cart_id and cart, both cannot be null')
146
        else:
147
            cart = Cart.get_by(id = cart_id)
148
 
149
    if cart.lines:
150
        for line in cart.lines:
151
            delete_discounts_for_line(line)
152
 
153
def save_discounts(discounts):
154
    if not discounts:
155
        raise ShoppingCartException(101, 'discounts be null')
156
 
157
    if len(discounts) > 0:
158
        cart = Cart.get_by(id = discounts[0].cart_id)
159
 
160
        for t_discount in discounts:
161
            line = Line.query.filter_by(cart = cart, item_id = t_discount.item_id).first()
162
            if line is not None:
163
                discount = Discount()
164
                discount.line = line
165
                discount.discount = t_discount.discount
166
                discount.quantity = t_discount.quantity
167
                session.commit()
168
 
557 chandransh 169
def add_address_to_cart(cart_id, address_id):
170
    if not cart_id:
171
        raise ShoppingCartException(101, "cart id cannot be made null")
172
 
173
    if not address_id:
174
        raise ShoppingCartException(101, "address id cannot be made null")
175
 
176
    cart = get_cart_by_id(cart_id)
177
    if not cart:
178
        raise ShoppingCartException(101, "no cart for this id")
576 chandransh 179
 
180
    address = Address.get_by(id=address_id)
181
    if not address:
182
        raise ShoppingCartException(101, "No address for this id")
183
 
557 chandransh 184
    cart.address_id = address_id
685 chandransh 185
    current_time = datetime.datetime.now()
716 rajveer 186
    #cart.updated_on = current_time
557 chandransh 187
    session.commit()
5555 rajveer 188
 
189
def add_store_to_cart(cartId, storeId):
190
    if not cartId:
191
        raise ShoppingCartException(101, "cart id cannot be made null")
557 chandransh 192
 
5555 rajveer 193
    cart = get_cart_by_id(cartId)
194
    if not cart:
195
        raise ShoppingCartException(101, "no cart for this id")
196
 
197
    if storeId:
198
        cart.pickupStoreId = storeId
199
    else:
200
        cart.pickupStoreId = None
201
 
202
    session.commit()
203
 
6922 anupam.sin 204
def apply_coupon_to_cart(t_cart, coupon_code):
205
    cart = get_cart_by_id(t_cart.id)
1976 varun.gupt 206
    if not cart:
207
        raise ShoppingCartException(101, "no cart attached to this id")
6922 anupam.sin 208
    pc = PromotionClient().get_client()
11853 amit.gupta 209
    for t_line in t_cart.lines:
210
        line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
13136 amit.gupta 211
        line.discounted_price = None
11853 amit.gupta 212
        if not pc.isGiftVoucher(coupon_code):
6922 anupam.sin 213
            line.discounted_price = t_line.discountedPrice
13136 amit.gupta 214
        #line.dealText = t_line.dealText
215
        #line.freebieId = t_line.freebieId
6922 anupam.sin 216
 
217
    cart.total_price = t_cart.totalPrice
218
    cart.discounted_price = t_cart.discountedPrice
12055 amit.gupta 219
    cart.coupon_code = coupon_code
1976 varun.gupt 220
    session.commit()
221
 
222
def remove_coupon(cart_id):
223
    cart = get_cart_by_id(cart_id)
224
    if not cart:
225
        raise ShoppingCartException(101, "no cart attached to this id")
2261 varun.gupt 226
 
227
    #Resetting discounted price of each line in cart to Null
228
    for line in cart.lines:
229
        line.discounted_price = None
11653 amit.gupta 230
        line.dealText = None
231
        line.freebieId = None
2261 varun.gupt 232
 
3619 chandransh 233
    delete_discounts_from_cart(cart.id, cart=cart)
1976 varun.gupt 234
    cart.discounted_price = None
235
    cart.coupon_code = None
236
    session.commit()
237
 
11526 amit.gupta 238
def commit_cart(cart_id, sessionSource, sessionTime, firstSource, firstSourceTime, userId, schemeId, orderSource):   
690 chandransh 239
    cart = get_cart_by_id(cart_id)   
557 chandransh 240
    #now we have a cart. Need to create a transaction with it
17470 manish.sha 241
    totalCartVal = 0
242
    totalshippingCost = 0
243
    for lineObj in cart.lines:
244
        totalCartVal += lineObj.actual_price * lineObj.quantity
576 chandransh 245
    txn = TTransaction()
246
    txn.shoppingCartid = cart_id
5326 rajveer 247
    txn.customer_id = userId
576 chandransh 248
    txn.createdOn = to_java_date(datetime.datetime.now())
249
    txn.transactionStatus = TTransactionStatus.INIT
250
    txn.statusDescription = "New Order"
2219 varun.gupt 251
    txn.coupon_code = cart.coupon_code
2815 vikas 252
    txn.sessionSource = sessionSource
253
    txn.sessionStartTime = sessionTime
3858 vikas 254
    txn.firstSource = firstSource
255
    txn.firstSourceTime = firstSourceTime
6389 rajveer 256
    txn.emiSchemeId = schemeId
17470 manish.sha 257
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
258
    if privateDealUser is not None:
259
        if totalCartVal < 500:
260
            totalshippingCost = 100
261
        elif totalCartVal >=500 and totalCartVal<1000:
262
            totalshippingCost = 50
263
    txn.totalShippingCost = totalshippingCost
264
 
265
    txnOrders = create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal)
266
    shippingCostInOrders = 0
267
    for order in txnOrders:
268
        shippingCostInOrders = shippingCostInOrders + order.shippingCost
576 chandransh 269
 
17470 manish.sha 270
    diff = totalshippingCost - shippingCostInOrders
271
    if diff > 0:
272
        txnOrders[0].shippingCost = txnOrders[0].shippingCost + diff
273
 
274
 
275
    txn.orders = txnOrders
276
 
576 chandransh 277
    transaction_client = TransactionClient().get_client()
278
    txn_id = transaction_client.createTransaction(txn)
12743 amit.gupta 279
 
280
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
281
    if privateDealUser is not None and privateDealUser.counter is not None:
282
        privateDealUser.counter.lastPurchasedOn = datetime.datetime.now()
576 chandransh 283
    session.commit()
284
 
285
    return txn_id
286
 
17470 manish.sha 287
def create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal):
557 chandransh 288
    cart_lines = cart.lines
576 chandransh 289
    orders = []
6318 rajveer 290
    isGv = False
291
    if cart.coupon_code:
292
        try:
293
            pc = PromotionClient().get_client()
294
            isGv = pc.isGiftVoucher(cart.coupon_code)
295
        except:
296
            isGv = False
297
 
6903 anupam.sin 298
    insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
299
 
557 chandransh 300
    for line in cart_lines:
576 chandransh 301
        if line.line_status == LineStatus.LINE_ACTIVE:
3554 varun.gupt 302
            quantity_remaining_for_order = line.quantity
303
 
304
            for discount in line.discounts:
17470 manish.sha 305
                #i = 0
306
                #while i < discount.quantity:
307
                t_line_item = create_line_item(line, line.actual_price if isGv else (line.actual_price - discount.discount), line.quantity)
308
                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)
309
                orders.append(t_order)
310
                    #i += 1
3554 varun.gupt 311
                quantity_remaining_for_order -= discount.quantity
312
 
17470 manish.sha 313
            if quantity_remaining_for_order > 0:
314
                t_line_item = create_line_item(line, line.actual_price, quantity_remaining_for_order)
17484 manish.sha 315
                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)
17470 manish.sha 316
                orders.append(t_order)
317
            '''
576 chandransh 318
            i = 0
3554 varun.gupt 319
            while i < quantity_remaining_for_order:
11915 amit.gupta 320
                t_line_item = create_line_item(line, line.actual_price)
11669 amit.gupta 321
                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)
576 chandransh 322
                orders.append(t_order)
323
                i += 1
17470 manish.sha 324
            '''
576 chandransh 325
    return orders
326
 
17470 manish.sha 327
def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails, dataProtectionInsurer, dataProtectionAmount, orderSource, freebieId, totalshippingCost, totalCartVal):
5326 rajveer 328
    user = User.get_by(id=userId)
576 chandransh 329
    address = Address.get_by(id=address_id)
330
    t_order = TOrder()
557 chandransh 331
 
576 chandransh 332
    t_order.customer_id = user.id
333
    t_order.customer_email = user.email
334
 
910 rajveer 335
    t_order.customer_name = address.name
576 chandransh 336
    t_order.customer_pincode = address.pin
738 chandransh 337
    t_order.customer_address1 = address.line_1
338
    t_order.customer_address2 = address.line_2
669 chandransh 339
    t_order.customer_city = address.city
340
    t_order.customer_state = address.state
576 chandransh 341
    t_order.customer_mobilenumber = address.phone
342
 
9299 kshitij.so 343
    t_order.total_amount = t_line_item.total_price + insuranceAmount + dataProtectionAmount
6318 rajveer 344
    t_order.gvAmount = gvAmount
1976 varun.gupt 345
 
576 chandransh 346
    t_order.total_weight = t_line_item.total_weight
347
    t_order.lineitems = [t_line_item]
348
 
690 chandransh 349
    t_order.status = OrderStatus.PAYMENT_PENDING
970 chandransh 350
    t_order.statusDescription = "Payment Pending"
576 chandransh 351
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
352
 
5555 rajveer 353
    t_order.pickupStoreId = pickupStoreId 
6903 anupam.sin 354
    t_order.insuranceAmount = insuranceAmount 
355
    t_order.insurer = insurer
6935 anupam.sin 356
    if insuranceDetails:
357
        t_order.dob = insuranceDetails.dob
358
        t_order.guardianName = insuranceDetails.guardianName
7190 amar.kumar 359
 
360
    catalog_client = CatalogClient().get_client()
11669 amit.gupta 361
 
362
    if freebieId is None:
363
        freebie_item_id = catalog_client.getFreebieForItem(t_line_item.item_id)
364
        if freebie_item_id:
365
            t_order.freebieItemId = freebie_item_id
366
    else:
367
        freebie_item_id = None if freebieId == 0 else freebieId  
11526 amit.gupta 368
    t_order.source = orderSource
9299 kshitij.so 369
    t_order.dataProtectionInsurer = dataProtectionInsurer
370
    t_order.dataProtectionAmount = dataProtectionAmount
17486 manish.sha 371
    t_order.shippingCost = round((t_line_item.total_price*totalshippingCost)/totalCartVal, 0)
576 chandransh 372
    return t_order
373
 
11915 amit.gupta 374
def create_line_item(line, final_price, quantity=1):
3133 rajveer 375
    inventory_client = CatalogClient().get_client()
11915 amit.gupta 376
    item = inventory_client.getItem(line.item_id)
576 chandransh 377
    t_line_item = TLineItem()
963 chandransh 378
    t_line_item.productGroup = item.productGroup
379
    t_line_item.brand = item.brand
636 rajveer 380
    t_line_item.model_number = item.modelNumber
669 chandransh 381
    if item.color is None or item.color == "NA":
382
        t_line_item.color = ""
383
    else:
917 chandransh 384
        t_line_item.color = item.color
963 chandransh 385
    t_line_item.model_name = item.modelName
636 rajveer 386
    t_line_item.extra_info = item.featureDescription
702 chandransh 387
    t_line_item.item_id = item.id
3768 vikas 388
    t_line_item.quantity = quantity
1983 varun.gupt 389
 
3554 varun.gupt 390
    t_line_item.unit_price = final_price
3768 vikas 391
    t_line_item.total_price = final_price * quantity
1983 varun.gupt 392
 
636 rajveer 393
    t_line_item.unit_weight = item.weight
4172 rajveer 394
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
11915 amit.gupta 395
    if line.dealText is None:
396
        t_line_item.dealText = item.bestDealText
397
    elif line.dealText == '':
398
        t_line_item.dealText = None
399
    else:
400
        t_line_item.dealText = line.dealText
401
 
4312 rajveer 402
    if item.warrantyPeriod:
403
        #Computing Manufacturer Warranty expiry date
404
        today = datetime.date.today()
405
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
406
        expiry_month = (today.month + item.warrantyPeriod) % 12
407
 
4295 varun.gupt 408
        try:
4312 rajveer 409
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
4295 varun.gupt 410
        except ValueError:
411
            try:
4312 rajveer 412
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
4295 varun.gupt 413
            except ValueError:
4312 rajveer 414
                try:
415
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
416
                except ValueError:
417
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
418
 
419
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
420
 
576 chandransh 421
    return t_line_item
422
 
11980 amit.gupta 423
def validate_cart(cartId, sourceId, couponCode):
3133 rajveer 424
    inventory_client = CatalogClient().get_client()
576 chandransh 425
    logistics_client = LogisticsClient().get_client()
1976 varun.gupt 426
    promotion_client = PromotionClient().get_client()
1466 ankur.sing 427
    retval = ""
6736 amit.gupta 428
    emival = ""
557 chandransh 429
    # No need to validate duplicate items since there are only two ways
430
    # to add items to a cart and both of them check whether the item being
431
    # added is a duplicate of an already existing item.
563 chandransh 432
    cart = Cart.get_by(id=cartId)
433
    cart_lines = cart.lines
776 rajveer 434
    customer_pincode = None
690 chandransh 435
    current_time = datetime.datetime.now()
5929 anupam.sin 436
    if cart.pickupStoreId :
5782 rajveer 437
        store = logistics_client.getPickupStore(cart.pickupStoreId)
438
        customer_pincode = store.pin
5572 anupam.sin 439
    if cart.address_id != None and customer_pincode == None:
576 chandransh 440
        address = Address.get_by(id=cart.address_id)
441
        customer_pincode = address.pin
13136 amit.gupta 442
 
443
    user = User.get_by(active_cart_id = cartId)
444
 
445
    dealItems = []
13141 amit.gupta 446
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
13136 amit.gupta 447
    if privateDealUser is not None and privateDealUser.isActive:
13142 amit.gupta 448
        itemIds = [cartLine.item_id for cartLine in cart.lines]
13136 amit.gupta 449
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
450
        dealItems = deals.keys()
451
 
776 rajveer 452
    if not customer_pincode:
785 rajveer 453
        default_address_id = user.default_address_id
776 rajveer 454
        if default_address_id:
455
            address = Address.get_by(id = default_address_id)
456
            customer_pincode = address.pin
457
    if not customer_pincode:
458
        #FIXME should not be hard coded. May be we can pick from config server.
459
        customer_pincode = "110001"
1976 varun.gupt 460
    cart.total_price = 0
563 chandransh 461
    for line in cart_lines:
612 chandransh 462
        old_estimate = line.estimate
636 rajveer 463
        item_id = line.item_id
3557 rajveer 464
        item = inventory_client.getItemForSource(item_id, sourceId)
13136 amit.gupta 465
 
2983 chandransh 466
        item_shipping_info = inventory_client.isActive(item_id) 
467
        if item_shipping_info.isActive:
468
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
469
                line.quantity = 1
470
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
13136 amit.gupta 471
 
472
            if item_id in dealItems:
473
                line.actual_price = deals[item_id].dealPrice
474
                if deals[item_id].dealTextOption==0:
475
                    line.dealText = ''
476
                if deals[item_id].dealTextOption==2:
477
                    line.dealText =  deals[item_id].dealText
478
 
479
                if deals[item_id].dealFreebieOption==0:
480
                    line.freebieId = 0
481
                if deals[item_id].dealFreebieOption==2:
482
                    line.freebieId =  deals[item_id].dealFreebieItemId
483
 
484
            else:
485
                line.actual_price = item.sellingPrice 
486
                line.dealText = None
487
                line.freebieId = None
6921 anupam.sin 488
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
776 rajveer 489
            try:
4642 mandeep.dh 490
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
844 chandransh 491
            except LogisticsServiceException:
492
                item_delivery_estimate = -1
493
                #TODO Use the exception clause to set the retval appropriately
494
            except :
495
                item_delivery_estimate = -1
12893 manish.sha 496
 
497
            if item_delivery_estimate !=-1:
498
                inv_client = InventoryClient().get_client()
499
                itemAvailability = None
500
                try:
12898 manish.sha 501
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
12893 manish.sha 502
                except:
503
                    pass
12904 manish.sha 504
 
505
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
12893 manish.sha 506
                if itemAvailability is not None:
507
                    billingWarehouse = None
508
                    try:
12904 manish.sha 509
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
12893 manish.sha 510
                    except:
511
                        pass
12904 manish.sha 512
 
513
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
12893 manish.sha 514
                    if billingWarehouse is not None:
12904 manish.sha 515
                        estimateVal = None
12893 manish.sha 516
                        if not logistics_client.isAlive() :
517
                            logistics_client = LogisticsClient().get_client()
518
                        try:
12904 manish.sha 519
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
12893 manish.sha 520
                            if estimateVal ==-1:
521
                                item_delivery_estimate =-1
522
                        except:
523
                            pass
12904 manish.sha 524
                        print 'estimateVal Value ', estimateVal
776 rajveer 525
            if old_estimate != item_delivery_estimate:
526
                line.estimate = item_delivery_estimate
527
                cart.updated_on = current_time
576 chandransh 528
        else:
11877 amit.gupta 529
            Discount.query.filter(Discount.line==line).delete()
563 chandransh 530
            line.delete()
716 rajveer 531
    if cart.checked_out_on is not None:
532
        if cart.updated_on > cart.checked_out_on:
844 chandransh 533
            cart.checked_out_on = None
612 chandransh 534
    session.commit()
1976 varun.gupt 535
 
536
    if cart.coupon_code is not None:
2026 varun.gupt 537
        try:
538
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
6740 amit.gupta 539
            if updated_cart.message is not None:
6739 amit.gupta 540
                emival = updated_cart.message
2026 varun.gupt 541
        except PromotionException as ex:
542
            remove_coupon(cart.id)
12020 amit.gupta 543
            #retval = ex.message
13155 amit.gupta 544
    session.commit()
13136 amit.gupta 545
 
546
    cart = Cart.get_by(id=cartId)
547
    cart_lines = cart.lines
548
    map_lines = {}
549
 
550
    insurerFlag = False
551
    for line in cart_lines:
552
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
553
            line_map = {}
554
            line_map['insurer'] = line.insurer
555
            line_map['dpinsurer'] = line.dataProtectionInsurer
556
            line_map['amount'] = line.discounted_price if line.discounted_price else line.actual_price
557
            line_map['quantity'] = line.quantity
558
            insurerFlag = True
559
            map_lines[line.item_id] = line_map
560
 
561
    if insurerFlag:
13142 amit.gupta 562
        map_lines = inventory_client.checkServices(map_lines)
13136 amit.gupta 563
        for line in cart_lines :
13142 amit.gupta 564
            if map_lines.has_key(line.item_id):
565
                line_map = map_lines[line.item_id]
566
                if line_map['insurer'] > 0:
13136 amit.gupta 567
                    if cart.discounted_price:
13142 amit.gupta 568
                        cart.discounted_price = cart.discounted_price + line_map['insureramount']
569
                    line.insurer = line_map['insurer']
570
                    line.insuranceAmount = line_map['insureramount']
571
                    cart.total_price = cart.total_price + line_map['insureramount']
572
                if line_map['dpinsurer'] > 0:
13136 amit.gupta 573
                    if cart.discounted_price:
13142 amit.gupta 574
                        cart.discounted_price = cart.discounted_price + line_map['dpinsureramount']
575
                    line.dataProtectionInsurer = line_map['dpinsurer']
576
                    line.dataProtectionAmount = line_map['dpinsureramount']
577
                    cart.total_price = cart.total_price + line_map['dpinsureramount']
13136 amit.gupta 578
                line.updated_on = datetime.datetime.now()
579
        cart.updated_on = datetime.datetime.now()
13142 amit.gupta 580
        session.commit()
11860 amit.gupta 581
    session.close()
6736 amit.gupta 582
    return [retval, emival]
576 chandransh 583
 
557 chandransh 584
def merge_cart(fromCartId, toCartId):
585
    fromCart = Cart.get_by(id=fromCartId)
586
    toCart = Cart.get_by(id=toCartId)
587
 
588
    old_lines = fromCart.lines
589
    new_lines = toCart.lines
590
 
591
    for line in old_lines:
5345 rajveer 592
        for discount in line.discounts:
593
            discount.delete()
594
    session.commit()
595
 
596
    for line in old_lines:
557 chandransh 597
        flag = True
598
        for new_line in new_lines:
599
            if line.item_id == new_line.item_id:
600
                flag = False
5345 rajveer 601
 
576 chandransh 602
        if flag:
5345 rajveer 603
            line.cart_id = toCartId
604
        else:
605
            line.delete()
606
 
2019 varun.gupt 607
    if toCart.coupon_code is None:
608
        toCart.coupon_code = fromCart.coupon_code
609
 
610
    toCart.updated_on = datetime.datetime.now()
557 chandransh 611
    fromCart.expired_on = datetime.datetime.now()
612
    fromCart.cart_status = CartStatus.INACTIVE
643 chandransh 613
    session.commit()
691 chandransh 614
 
615
def check_out(cartId):
616
    if cartId is None:
617
        raise ShoppingCartException(101, "Cart id not specified")
716 rajveer 618
    cart = Cart.get_by(id = cartId)
691 chandransh 619
    if cart is None:
620
        raise ShoppingCartException(102, "The specified cart couldn't be found")
621
    cart.checked_out_on = datetime.datetime.now()
622
    session.commit()
623
    return True
624
 
625
def reset_cart(cartId, items):
626
    if cartId is None:
627
        raise ShoppingCartException(101, "Cart id not specified")
628
    for item_id, quantity in items.iteritems():
629
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
630
        if line is not None:
3566 rajveer 631
            delete_discounts_for_line(line)
2261 varun.gupt 632
            line.discounted_price = None
691 chandransh 633
            line.quantity = line.quantity - quantity
634
            if line.quantity == 0:
635
                line.delete()
717 rajveer 636
    cart = Cart.get_by(id=cartId)
691 chandransh 637
    cart.updated_on = datetime.datetime.now()
1894 vikas 638
    cart.checked_out_on = None
1976 varun.gupt 639
 
640
    # Removing Coupon
641
    cart.total_price = None
642
    cart.discounted_price = None
643
    cart.coupon_code = None
644
 
691 chandransh 645
    session.commit()
766 rajveer 646
    return True
647
 
3386 varun.gupt 648
def get_carts_with_coupon_count(coupon_code):
649
    return Cart.query.filter_by(coupon_code = coupon_code).count()
4668 varun.gupt 650
 
651
def show_cod_option(cartId, sourceId, pincode):
652
    cart = Cart.get_by(id = cartId)
653
    cod_option = True
654
    logistics_client = LogisticsClient().get_client()
655
    if cart:
6355 amit.gupta 656
        if cart.coupon_code:
657
            promotion_client = PromotionClient().get_client()
11819 amit.gupta 658
            cod_option = promotion_client.isCodApplicable(to_t_cart(cart))
5351 varun.gupt 659
 
6355 amit.gupta 660
        if cod_option and cart.lines:
4668 varun.gupt 661
            for line in cart.lines:
4866 rajveer 662
                logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
4871 rajveer 663
                if not logistics_info.codAllowed:
4668 varun.gupt 664
                    cod_option = False
665
                    break
17648 manish.sha 666
            if cart.total_price > 60000:# or cart.total_price <= 250:
5430 rajveer 667
                cod_option = False
4668 varun.gupt 668
    return cod_option
6821 amar.kumar 669
 
9791 rajveer 670
def get_products_added_to_cart(startDate, endDate):
671
    lines = session.query(Line.item_id).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).all()
9804 rajveer 672
    datas = []
673
    for line in lines:
674
        datas.append(line[0])
675
    return datas
6903 anupam.sin 676
 
11655 amit.gupta 677
def insure_item(itemId, cartId, toInsure, insurerType):
678
    cart = Cart.get_by(id = cartId)
679
    line = None
680
    for cartLine in cart.lines:
681
        if(cartLine.item_id == itemId):
682
            line = cartLine
683
            break
684
 
685
    if not line:
686
        print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
687
        return False
688
 
6903 anupam.sin 689
    try:
690
        if toInsure:
6921 anupam.sin 691
            csc = CatalogClient().get_client()
692
            item = csc.getItem(itemId)
9299 kshitij.so 693
            insurerId = csc.getPrefferedInsurerForItem(itemId,insurerType)
694
            insuranceAmount = csc.getInsuranceAmount(itemId, line.discounted_price if line.discounted_price else line.actual_price, insurerId, line.quantity)
695
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
696
                if cart.discounted_price:
697
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount + insuranceAmount
698
                line.insurer = insurerId
699
                line.insuranceAmount = insuranceAmount
700
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
701
                if cart.discounted_price:
702
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount + insuranceAmount
703
                line.dataProtectionInsurer = insurerId
704
                line.dataProtectionAmount = insuranceAmount
6903 anupam.sin 705
            cart.total_price = cart.total_price + insuranceAmount
706
        else:
9299 kshitij.so 707
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
708
                cart.total_price = cart.total_price - line.insuranceAmount
709
                if cart.discounted_price:
710
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount
711
                line.insurer = 0
712
                line.insuranceAmount = 0
713
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
714
                cart.total_price = cart.total_price - line.dataProtectionAmount
715
                if cart.discounted_price:
716
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount
717
                line.dataProtectionInsurer = 0
718
                line.dataProtectionAmount = 0
6903 anupam.sin 719
        line.updated_on = datetime.datetime.now()
720
        cart.updated_on = datetime.datetime.now()
721
        session.commit()
722
    except:
723
        print("Error : Unable to insure")
9299 kshitij.so 724
        print("insurerId : " + str(insurerId) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
6903 anupam.sin 725
        return False
726
 
727
    return True
728
 
729
def cancel_insurance(cartId):
730
    try:
731
        cart = Cart.get_by(id = cartId)
732
        for cartLine in cart.lines:
733
            cart.total_price = cart.total_price - cartLine.insuranceAmount
734
            if cart.discounted_price:
735
                cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
736
            cartLine.insurer = 0
737
            cartLine.insuranceAmount = 0
738
            cartLine.updated_on = datetime.datetime.now()
739
        cart.updated_on = datetime.datetime.now()
740
        session.commit()
741
    except:
742
        print("Error : Unable to cancel insurance for cartId :" + str(cartId))
743
        return False
744
 
745
    return True
746
 
747
def store_insurance_specific_details(addressId, dob, guardianName):
748
    try:
749
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
750
        if insuranceDetails is None :
751
            insuranceDetails = InsuranceDetails()
752
        insuranceDetails.addressId = addressId
753
        insuranceDetails.dob = dob
754
        insuranceDetails.guardianName = guardianName
755
        session.commit()
756
    except:
757
        print("Error : Unable to store insurance details for addressId : " + str(addressId))
758
        return False
759
    return True
760
 
761
def is_insurance_detail_present(addressId):
762
    try:
763
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
764
        if insuranceDetails is None :
765
            return False
766
    except:
767
        print("Error : Unable to get insurance details for addressId : " + str(addressId))
768
        return False
769
    return True
770
 
11980 amit.gupta 771
def validate_cart_plus(cart_id, source_id, couponCode):
11655 amit.gupta 772
    try:
11980 amit.gupta 773
        cart_messages = validate_cart(cart_id, source_id, couponCode)
11655 amit.gupta 774
        found_cart = Cart.get_by(id=cart_id)
11592 amit.gupta 775
        pincode = "110001"
11599 amit.gupta 776
        default_address_id = User.get_by(active_cart_id = cart_id).default_address_id
11598 amit.gupta 777
 
11592 amit.gupta 778
        default_address = None
779
        if found_cart.address_id is not None and found_cart.address_id > 0:
780
            pincode = Address.get_by(id=found_cart.address_id).pin
11600 amit.gupta 781
        elif default_address_id is not None:
11592 amit.gupta 782
            default_address = Address.get_by(id = default_address_id) 
783
            pincode = default_address.pin
784
 
11612 amit.gupta 785
        needInuranceInfo = False
11600 amit.gupta 786
        if default_address_id is not None:
787
            for line in found_cart.lines:
788
                if line.insurer > 0:
11611 amit.gupta 789
                    needInuranceInfo = not is_insurance_detail_present(default_address_id)
11600 amit.gupta 790
                    break
11592 amit.gupta 791
        cartPlus = CartPlus()
792
        cartPlus.cart = to_t_cart(found_cart)
793
        cartPlus.pinCode = pincode
794
        cartPlus.validateCartMessages = cart_messages
795
        cartPlus.needInsuranceInfo = needInuranceInfo
796
        return cartPlus
797
    finally:
798
        close_session()
799
 
766 rajveer 800
def close_session():
801
    if session.is_active:
802
        print "session is active. closing it."
6903 anupam.sin 803
        session.close()