Subversion Repositories SmartDukaan

Rev

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