Subversion Repositories SmartDukaan

Rev

Rev 6821 | Rev 6921 | 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 *
6903 anupam.sin 7
from shop2020.model.v1.user.impl.Dataservice import Cart, Line, Address, User, Discount, InsuranceDetails
2026 varun.gupt 8
from shop2020.thriftpy.model.v1.user.ttypes import CartStatus, LineStatus, ShoppingCartException,\
9
    PromotionException
557 chandransh 10
import datetime
576 chandransh 11
from shop2020.utils.Utils import to_py_date, to_java_date
557 chandransh 12
 
576 chandransh 13
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as TTransaction,\
685 chandransh 14
    TransactionStatus as TTransactionStatus, Order as TOrder, LineItem as TLineItem, OrderStatus 
557 chandransh 15
 
5326 rajveer 16
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, DeliveryType
576 chandransh 17
 
18
from shop2020.clients.TransactionClient import TransactionClient
3133 rajveer 19
from shop2020.clients.CatalogClient import CatalogClient
576 chandransh 20
from shop2020.clients.LogisticsClient import LogisticsClient
21
from shop2020.model.v1 import user
1976 varun.gupt 22
from shop2020.clients.PromotionClient import PromotionClient
576 chandransh 23
 
5326 rajveer 24
def get_cart(userId):
25
    user = User.get_by(id=userId)
26
    return user.active_cart
557 chandransh 27
 
28
def get_cart_by_id(id):
29
    cart = Cart.get_by(id=id)
30
    return cart
31
 
5326 rajveer 32
def create_cart():
33
    cart = Cart()
34
    cart.created_on = datetime.datetime.now()
35
    cart.updated_on = datetime.datetime.now()
36
    cart.cart_status = CartStatus.ACTIVE
557 chandransh 37
    return cart
38
 
39
def get_carts_between(start_time, end_time, status):
40
    init_time = to_py_date(start_time)
41
    finish_time = to_py_date(end_time)
42
 
43
    query = Cart.query
44
    if status:
45
        query = query.filter(Cart.cart_status==status)
46
    if init_time:
47
        query = query.filter(Cart.created_on >= init_time)
48
    if finish_time:
49
        query = query.filter(Cart.created_on <= finish_time)
50
 
51
    carts = query.all()
52
    return carts
53
 
643 chandransh 54
def get_line(item_id, cart_id, status, single):
557 chandransh 55
    #get cart first 
56
    try:
57
        found_cart = Cart.get_by(id=cart_id)
58
    except:
59
        raise ShoppingCartException(101, "cart not found ")
643 chandransh 60
    query = Line.query.filter_by(cart = found_cart, item_id = item_id)
557 chandransh 61
 
62
    if status:
63
        query = query.filter_by(line_status = status)
64
    else:
65
        query = query.filter_by(line_status = LineStatus.LINE_ACTIVE)
66
    try:
67
        if single:
68
            return query.one()
69
        else:
70
            return query.all()
71
    except:
72
        return None
73
 
3557 rajveer 74
def add_item_to_cart(cart_id, item_id, quantity, sourceId):
557 chandransh 75
    if not item_id:
76
        raise ShoppingCartException(101, "item_id cannot be null")
77
 
78
    if not quantity:
79
        raise ShoppingCartException(101, "quantity cannot be null")    
643 chandransh 80
 
2983 chandransh 81
    cart = Cart.get_by(id = cart_id)    
557 chandransh 82
    if not cart:
6502 rajveer 83
        raise ShoppingCartException(101, "no cart attached to this id" + str(cart_id))
2983 chandransh 84
    retval = ""
6550 rajveer 85
    catalog_client = CatalogClient().get_client()
86
    item = catalog_client.getItemForSource(item_id, sourceId)
87
    item_shipping_info = catalog_client.isActive(item_id)
2983 chandransh 88
    if not item_shipping_info.isActive:
6550 rajveer 89
        return catalog_client.getItemStatusDescription(item_id)
557 chandransh 90
 
643 chandransh 91
    current_time = datetime.datetime.now()
92
    cart.updated_on = current_time
93
    line = get_line(item_id, cart_id, None,True)
94
    if line:
95
        #change the quantity only
6903 anupam.sin 96
        line.insuranceAmount = (line.insuranceAmount/line.quantity) * quantity
643 chandransh 97
        line.quantity = quantity
685 chandransh 98
        line.updated_on = current_time
643 chandransh 99
    else:
100
        line = Line()
101
        line.cart = cart
102
        line.item_id = item_id
103
        line.quantity = quantity
104
        line.created_on = current_time
105
        line.updated_on = current_time
3557 rajveer 106
        line.actual_price = item.sellingPrice
643 chandransh 107
        line.line_status = LineStatus.LINE_ACTIVE
6903 anupam.sin 108
        line.insurer = 0
109
        line.insuranceAmount = 0
557 chandransh 110
    session.commit()
2983 chandransh 111
    return retval
557 chandransh 112
 
113
def delete_item_from_cart(cart_id, item_id):
114
    if not item_id:
115
        raise ShoppingCartException(101, "item_id cannot be null")
685 chandransh 116
    cart = Cart.get_by(id = cart_id)
117
    if not cart:
118
        raise ShoppingCartException(101, "no cart attached to this id")
643 chandransh 119
    item = get_line(item_id, cart_id, None, True)
3554 varun.gupt 120
    count_deleted_discounts = delete_discounts_for_line(item)
557 chandransh 121
    item.delete()
685 chandransh 122
    current_time = datetime.datetime.now()
123
    cart.updated_on = current_time
557 chandransh 124
    session.commit()
125
 
3554 varun.gupt 126
def delete_discounts_for_line(item_line):
127
    count_deleted = Discount.query.filter_by(line = item_line).delete()
128
    session.commit()
129
    return count_deleted
130
 
131
def delete_discounts_from_cart(cart_id, cart = None):
132
    if cart is None:
133
        if cart_id is None:
134
            raise ShoppingCartException(101, 'cart_id and cart, both cannot be null')
135
        else:
136
            cart = Cart.get_by(id = cart_id)
137
 
138
    if cart.lines:
139
        for line in cart.lines:
140
            delete_discounts_for_line(line)
141
 
142
def save_discounts(discounts):
143
    if not discounts:
144
        raise ShoppingCartException(101, 'discounts be null')
145
 
146
    if len(discounts) > 0:
147
        cart = Cart.get_by(id = discounts[0].cart_id)
148
 
149
        for t_discount in discounts:
150
            line = Line.query.filter_by(cart = cart, item_id = t_discount.item_id).first()
151
            if line is not None:
152
                discount = Discount()
153
                discount.line = line
154
                discount.discount = t_discount.discount
155
                discount.quantity = t_discount.quantity
156
                session.commit()
157
 
557 chandransh 158
def add_address_to_cart(cart_id, address_id):
159
    if not cart_id:
160
        raise ShoppingCartException(101, "cart id cannot be made null")
161
 
162
    if not address_id:
163
        raise ShoppingCartException(101, "address id cannot be made null")
164
 
165
    cart = get_cart_by_id(cart_id)
166
    if not cart:
167
        raise ShoppingCartException(101, "no cart for this id")
576 chandransh 168
 
169
    address = Address.get_by(id=address_id)
170
    if not address:
171
        raise ShoppingCartException(101, "No address for this id")
172
 
557 chandransh 173
    cart.address_id = address_id
685 chandransh 174
    current_time = datetime.datetime.now()
716 rajveer 175
    #cart.updated_on = current_time
557 chandransh 176
    session.commit()
5555 rajveer 177
 
178
def add_store_to_cart(cartId, storeId):
179
    if not cartId:
180
        raise ShoppingCartException(101, "cart id cannot be made null")
557 chandransh 181
 
5555 rajveer 182
    cart = get_cart_by_id(cartId)
183
    if not cart:
184
        raise ShoppingCartException(101, "no cart for this id")
185
 
186
    if storeId:
187
        cart.pickupStoreId = storeId
188
    else:
189
        cart.pickupStoreId = None
190
 
191
    session.commit()
192
 
1976 varun.gupt 193
def apply_coupon_to_cart(cart_id, coupon_code, total_price, discounted_price):
194
    cart = get_cart_by_id(cart_id)
195
    if not cart:
196
        raise ShoppingCartException(101, "no cart attached to this id")
197
    cart.total_price = total_price
198
    cart.discounted_price = discounted_price
199
    cart.coupon_code = coupon_code
200
    session.commit()
201
 
202
def remove_coupon(cart_id):
203
    cart = get_cart_by_id(cart_id)
204
    if not cart:
205
        raise ShoppingCartException(101, "no cart attached to this id")
2261 varun.gupt 206
 
207
    #Resetting discounted price of each line in cart to Null
208
    for line in cart.lines:
209
        line.discounted_price = None
210
 
3619 chandransh 211
    delete_discounts_from_cart(cart.id, cart=cart)
1976 varun.gupt 212
    cart.discounted_price = None
213
    cart.coupon_code = None
214
    session.commit()
215
 
6389 rajveer 216
def commit_cart(cart_id, sessionSource, sessionTime, firstSource, firstSourceTime, userId, schemeId):   
690 chandransh 217
    cart = get_cart_by_id(cart_id)   
557 chandransh 218
    #now we have a cart. Need to create a transaction with it
576 chandransh 219
    txn = TTransaction()
220
    txn.shoppingCartid = cart_id
5326 rajveer 221
    txn.customer_id = userId
576 chandransh 222
    txn.createdOn = to_java_date(datetime.datetime.now())
223
    txn.transactionStatus = TTransactionStatus.INIT
224
    txn.statusDescription = "New Order"
2219 varun.gupt 225
    txn.coupon_code = cart.coupon_code
2815 vikas 226
    txn.sessionSource = sessionSource
227
    txn.sessionStartTime = sessionTime
3858 vikas 228
    txn.firstSource = firstSource
229
    txn.firstSourceTime = firstSourceTime
6389 rajveer 230
    txn.emiSchemeId = schemeId
5326 rajveer 231
    txn.orders = create_orders(cart, userId)
576 chandransh 232
 
233
    transaction_client = TransactionClient().get_client()
234
    txn_id = transaction_client.createTransaction(txn)
235
    session.commit()
236
 
237
    return txn_id
238
 
5326 rajveer 239
def create_orders(cart, userId):
557 chandransh 240
    cart_lines = cart.lines
576 chandransh 241
    orders = []
6318 rajveer 242
    isGv = False
243
    if cart.coupon_code:
244
        try:
245
            pc = PromotionClient().get_client()
246
            isGv = pc.isGiftVoucher(cart.coupon_code)
247
        except:
248
            isGv = False
249
 
6903 anupam.sin 250
    insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
251
 
557 chandransh 252
    for line in cart_lines:
576 chandransh 253
        if line.line_status == LineStatus.LINE_ACTIVE:
3554 varun.gupt 254
            quantity_remaining_for_order = line.quantity
255
 
256
            for discount in line.discounts:
257
                i = 0
258
                while i < discount.quantity:
6330 rajveer 259
                    t_line_item = create_line_item(line.item_id, line.actual_price if isGv else (line.actual_price - discount.discount))
6903 anupam.sin 260
                    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)
3554 varun.gupt 261
                    orders.append(t_order)
262
                    i += 1
263
                quantity_remaining_for_order -= discount.quantity
264
 
576 chandransh 265
            i = 0
3554 varun.gupt 266
            while i < quantity_remaining_for_order:
267
                t_line_item = create_line_item(line.item_id, line.actual_price)
6903 anupam.sin 268
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails)
576 chandransh 269
                orders.append(t_order)
270
                i += 1
271
    return orders
272
 
6903 anupam.sin 273
def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails):
5326 rajveer 274
    user = User.get_by(id=userId)
576 chandransh 275
    address = Address.get_by(id=address_id)
276
    t_order = TOrder()
557 chandransh 277
 
576 chandransh 278
    t_order.customer_id = user.id
279
    t_order.customer_email = user.email
280
 
910 rajveer 281
    t_order.customer_name = address.name
576 chandransh 282
    t_order.customer_pincode = address.pin
738 chandransh 283
    t_order.customer_address1 = address.line_1
284
    t_order.customer_address2 = address.line_2
669 chandransh 285
    t_order.customer_city = address.city
286
    t_order.customer_state = address.state
576 chandransh 287
    t_order.customer_mobilenumber = address.phone
288
 
6903 anupam.sin 289
    t_order.total_amount = t_line_item.total_price + insuranceAmount
6318 rajveer 290
    t_order.gvAmount = gvAmount
1976 varun.gupt 291
 
576 chandransh 292
    t_order.total_weight = t_line_item.total_weight
293
    t_order.lineitems = [t_line_item]
294
 
690 chandransh 295
    t_order.status = OrderStatus.PAYMENT_PENDING
970 chandransh 296
    t_order.statusDescription = "Payment Pending"
576 chandransh 297
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
298
 
5555 rajveer 299
    t_order.pickupStoreId = pickupStoreId 
6903 anupam.sin 300
    t_order.insuranceAmount = insuranceAmount 
301
    t_order.insurer = insurer
302
    t_order.dob = insuranceDetails.dob
303
    t_order.guardianName = insuranceDetails.guardianName
576 chandransh 304
    return t_order
305
 
3768 vikas 306
def create_line_item(item_id, final_price, quantity=1):
3133 rajveer 307
    inventory_client = CatalogClient().get_client()
636 rajveer 308
    item = inventory_client.getItem(item_id)
576 chandransh 309
    t_line_item = TLineItem()
963 chandransh 310
    t_line_item.productGroup = item.productGroup
311
    t_line_item.brand = item.brand
636 rajveer 312
    t_line_item.model_number = item.modelNumber
669 chandransh 313
    if item.color is None or item.color == "NA":
314
        t_line_item.color = ""
315
    else:
917 chandransh 316
        t_line_item.color = item.color
963 chandransh 317
    t_line_item.model_name = item.modelName
636 rajveer 318
    t_line_item.extra_info = item.featureDescription
702 chandransh 319
    t_line_item.item_id = item.id
3768 vikas 320
    t_line_item.quantity = quantity
1983 varun.gupt 321
 
3554 varun.gupt 322
    t_line_item.unit_price = final_price
3768 vikas 323
    t_line_item.total_price = final_price * quantity
1983 varun.gupt 324
 
636 rajveer 325
    t_line_item.unit_weight = item.weight
4172 rajveer 326
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
327
    t_line_item.dealText = item.bestDealText
4295 varun.gupt 328
 
4312 rajveer 329
    if item.warrantyPeriod:
330
        #Computing Manufacturer Warranty expiry date
331
        today = datetime.date.today()
332
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
333
        expiry_month = (today.month + item.warrantyPeriod) % 12
334
 
4295 varun.gupt 335
        try:
4312 rajveer 336
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
4295 varun.gupt 337
        except ValueError:
338
            try:
4312 rajveer 339
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
4295 varun.gupt 340
            except ValueError:
4312 rajveer 341
                try:
342
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
343
                except ValueError:
344
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
345
 
346
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
347
 
576 chandransh 348
    return t_line_item
349
 
3557 rajveer 350
def validate_cart(cartId, sourceId):
3133 rajveer 351
    inventory_client = CatalogClient().get_client()
576 chandransh 352
    logistics_client = LogisticsClient().get_client()
1976 varun.gupt 353
    promotion_client = PromotionClient().get_client()
1466 ankur.sing 354
    retval = ""
6736 amit.gupta 355
    emival = ""
557 chandransh 356
    # No need to validate duplicate items since there are only two ways
357
    # to add items to a cart and both of them check whether the item being
358
    # added is a duplicate of an already existing item.
563 chandransh 359
    cart = Cart.get_by(id=cartId)
360
    cart_lines = cart.lines
776 rajveer 361
    customer_pincode = None
690 chandransh 362
    current_time = datetime.datetime.now()
5929 anupam.sin 363
    if cart.pickupStoreId :
5782 rajveer 364
        store = logistics_client.getPickupStore(cart.pickupStoreId)
365
        customer_pincode = store.pin
5572 anupam.sin 366
    if cart.address_id != None and customer_pincode == None:
576 chandransh 367
        address = Address.get_by(id=cart.address_id)
368
        customer_pincode = address.pin
776 rajveer 369
    if not customer_pincode:
785 rajveer 370
        user = User.get_by(active_cart_id = cartId)
371
        default_address_id = user.default_address_id
776 rajveer 372
        if default_address_id:
373
            address = Address.get_by(id = default_address_id)
374
            customer_pincode = address.pin
375
    if not customer_pincode:
376
        #FIXME should not be hard coded. May be we can pick from config server.
377
        customer_pincode = "110001"
1976 varun.gupt 378
    cart.total_price = 0
563 chandransh 379
    for line in cart_lines:
612 chandransh 380
        old_estimate = line.estimate
636 rajveer 381
        item_id = line.item_id
3557 rajveer 382
        item = inventory_client.getItemForSource(item_id, sourceId)
2983 chandransh 383
        item_shipping_info = inventory_client.isActive(item_id) 
384
        if item_shipping_info.isActive:
385
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
386
                line.quantity = 1
387
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
388
 
2139 chandransh 389
            line.actual_price = item.sellingPrice 
6903 anupam.sin 390
            cart.total_price = cart.total_price + (line.actual_price * line.quantity) + line.insuranceAmount
776 rajveer 391
            try:
4642 mandeep.dh 392
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
844 chandransh 393
            except LogisticsServiceException:
394
                item_delivery_estimate = -1
395
                #TODO Use the exception clause to set the retval appropriately
396
            except :
397
                item_delivery_estimate = -1
776 rajveer 398
            if old_estimate != item_delivery_estimate:
399
                line.estimate = item_delivery_estimate
400
                cart.updated_on = current_time
576 chandransh 401
        else:
563 chandransh 402
            line.delete()
716 rajveer 403
    if cart.checked_out_on is not None:
404
        if cart.updated_on > cart.checked_out_on:
844 chandransh 405
            cart.checked_out_on = None
612 chandransh 406
    session.commit()
1976 varun.gupt 407
 
408
    if cart.coupon_code is not None:
2026 varun.gupt 409
        try:
410
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
6903 anupam.sin 411
            totalPrice = 0
2026 varun.gupt 412
            for t_line in updated_cart.lines:
1976 varun.gupt 413
            #Find the line in the database which corresponds to this line
2026 varun.gupt 414
                line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
1976 varun.gupt 415
            #Update its discounted price.
2026 varun.gupt 416
                line.discounted_price = t_line.discountedPrice
6903 anupam.sin 417
            #If discounted price of line is set and this coupon is not a gift voucher that means
418
            # we will need to correct the insurance price accordingly.
419
                if line.discounted_price and not promotion_client.isGiftVoucher(cart.coupon_code) :
420
                    line.insuranceAmount = round((line.insuranceAmount/line.actual_price) * line.discounted_price)
421
                    totalPrice = totalPrice + line.actual_price * line.quantity + line.insuranceAmount
422
                    cart.total_price = totalPrice
2026 varun.gupt 423
            cart.discounted_price = updated_cart.discountedPrice
424
            session.commit()
6740 amit.gupta 425
            if updated_cart.message is not None:
6739 amit.gupta 426
                emival = updated_cart.message
2026 varun.gupt 427
        except PromotionException as ex:
428
            remove_coupon(cart.id)
429
            retval = ex.message
6740 amit.gupta 430
 
6736 amit.gupta 431
    return [retval, emival]
576 chandransh 432
 
557 chandransh 433
def merge_cart(fromCartId, toCartId):
434
    fromCart = Cart.get_by(id=fromCartId)
435
    toCart = Cart.get_by(id=toCartId)
436
 
437
    old_lines = fromCart.lines
438
    new_lines = toCart.lines
439
 
440
    for line in old_lines:
5345 rajveer 441
        for discount in line.discounts:
442
            discount.delete()
443
    session.commit()
444
 
445
    for line in old_lines:
557 chandransh 446
        flag = True
447
        for new_line in new_lines:
448
            if line.item_id == new_line.item_id:
449
                flag = False
5345 rajveer 450
 
576 chandransh 451
        if flag:
5345 rajveer 452
            line.cart_id = toCartId
453
        else:
454
            line.delete()
455
 
2019 varun.gupt 456
    if toCart.coupon_code is None:
457
        toCart.coupon_code = fromCart.coupon_code
458
 
459
    toCart.updated_on = datetime.datetime.now()
557 chandransh 460
    fromCart.expired_on = datetime.datetime.now()
461
    fromCart.cart_status = CartStatus.INACTIVE
643 chandransh 462
    session.commit()
691 chandransh 463
 
464
def check_out(cartId):
465
    if cartId is None:
466
        raise ShoppingCartException(101, "Cart id not specified")
716 rajveer 467
    cart = Cart.get_by(id = cartId)
691 chandransh 468
    if cart is None:
469
        raise ShoppingCartException(102, "The specified cart couldn't be found")
470
    cart.checked_out_on = datetime.datetime.now()
471
    session.commit()
472
    return True
473
 
474
def reset_cart(cartId, items):
475
    if cartId is None:
476
        raise ShoppingCartException(101, "Cart id not specified")
477
    for item_id, quantity in items.iteritems():
478
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
479
        if line is not None:
3566 rajveer 480
            delete_discounts_for_line(line)
2261 varun.gupt 481
            line.discounted_price = None
691 chandransh 482
            line.quantity = line.quantity - quantity
483
            if line.quantity == 0:
484
                line.delete()
717 rajveer 485
    cart = Cart.get_by(id=cartId)
691 chandransh 486
    cart.updated_on = datetime.datetime.now()
1894 vikas 487
    cart.checked_out_on = None
1976 varun.gupt 488
 
489
    # Removing Coupon
490
    cart.total_price = None
491
    cart.discounted_price = None
492
    cart.coupon_code = None
493
 
691 chandransh 494
    session.commit()
766 rajveer 495
    return True
496
 
3386 varun.gupt 497
def get_carts_with_coupon_count(coupon_code):
498
    return Cart.query.filter_by(coupon_code = coupon_code).count()
4668 varun.gupt 499
 
500
def show_cod_option(cartId, sourceId, pincode):
501
    cart = Cart.get_by(id = cartId)
502
    cod_option = True
503
    logistics_client = LogisticsClient().get_client()
504
    if cart:
6355 amit.gupta 505
        if cart.coupon_code:
506
            promotion_client = PromotionClient().get_client()
507
            cod_option = promotion_client.isCodApplicable(cart.coupon_code)
5351 varun.gupt 508
 
6355 amit.gupta 509
        if cod_option and cart.lines:
4668 varun.gupt 510
            for line in cart.lines:
4866 rajveer 511
                logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
4871 rajveer 512
                if not logistics_info.codAllowed:
4668 varun.gupt 513
                    cod_option = False
514
                    break
6528 rajveer 515
            if cart.total_price > 25000 or cart.total_price <= 250:
5430 rajveer 516
                cod_option = False
4668 varun.gupt 517
    return cod_option
6821 amar.kumar 518
 
519
def is_product_added_to_cart(itemId, startDate, endDate):
520
    line = Line.query.filter_by(item_id = itemId).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).first()
521
    '''line = Line.query.filter_by(item_id = itemId, created_on > to_py_date(startDate), created_on < to_py_date(endDate)).first()'''
522
    if line is not None:
523
        return True
524
    else:
525
        return False
6903 anupam.sin 526
 
527
def insure_item(itemId, cartId, toInsure):
528
    cart = Cart.get_by(id = cartId)
529
    line = None
530
    for cartLine in cart.lines:
531
        if(cartLine.item_id == itemId):
532
            line = cartLine
533
            break
534
 
535
    if not line:
536
        print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
537
        return False
4668 varun.gupt 538
 
6903 anupam.sin 539
    try:
540
        csc = CatalogClient().get_client()
541
        item = csc.getItem(itemId)
542
        insuranceAmount = csc.getInsuranceAmount(itemId, item.preferredInsurer, line.quantity)
543
        if toInsure:
544
            line.insurer = item.preferredInsurer
545
            line.insuranceAmount = insuranceAmount
546
            cart.total_price = cart.total_price + insuranceAmount
547
            if cart.discounted_price:
548
                cart.discounted_price = cart.discounted_price + insuranceAmount
549
        else:
550
            cart.total_price = cart.total_price - insuranceAmount
551
            if cart.discounted_price:
552
                cart.discounted_price = cart.discounted_price - insuranceAmount
553
            line.insurer = 0
554
            line.insuranceAmount = 0
555
        line.updated_on = datetime.datetime.now()
556
        cart.updated_on = datetime.datetime.now()
557
        session.commit()
558
    except:
559
        print("Error : Unable to insure")
560
        print("insurerId : " + str(item.preferredInsurer) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
561
        return False
562
 
563
    return True
564
 
565
def cancel_insurance(cartId):
566
    try:
567
        cart = Cart.get_by(id = cartId)
568
        for cartLine in cart.lines:
569
            cart.total_price = cart.total_price - cartLine.insuranceAmount
570
            if cart.discounted_price:
571
                cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
572
            cartLine.insurer = 0
573
            cartLine.insuranceAmount = 0
574
            cartLine.updated_on = datetime.datetime.now()
575
        cart.updated_on = datetime.datetime.now()
576
        session.commit()
577
    except:
578
        print("Error : Unable to cancel insurance for cartId :" + str(cartId))
579
        return False
580
 
581
    return True
582
 
583
def store_insurance_specific_details(addressId, dob, guardianName):
584
    try:
585
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
586
        if insuranceDetails is None :
587
            insuranceDetails = InsuranceDetails()
588
        insuranceDetails.addressId = addressId
589
        insuranceDetails.dob = dob
590
        insuranceDetails.guardianName = guardianName
591
        session.commit()
592
    except:
593
        print("Error : Unable to store insurance details for addressId : " + str(addressId))
594
        return False
595
    return True
596
 
597
def is_insurance_detail_present(addressId):
598
    try:
599
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
600
        if insuranceDetails is None :
601
            return False
602
    except:
603
        print("Error : Unable to get insurance details for addressId : " + str(addressId))
604
        return False
605
    return True
606
 
766 rajveer 607
def close_session():
608
    if session.is_active:
609
        print "session is active. closing it."
6903 anupam.sin 610
        session.close()