Subversion Repositories SmartDukaan

Rev

Rev 7492 | Rev 9299 | 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, \
7504 rajveer 19
    OrderStatus, OrderSource
6921 anupam.sin 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
 
6922 anupam.sin 197
def apply_coupon_to_cart(t_cart, coupon_code):
198
    cart = get_cart_by_id(t_cart.id)
1976 varun.gupt 199
    if not cart:
200
        raise ShoppingCartException(101, "no cart attached to this id")
6922 anupam.sin 201
    pc = PromotionClient().get_client()
202
    if not pc.isGiftVoucher(coupon_code):
203
        for t_line in t_cart.lines:
204
            line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
205
        #Update its discounted price.
206
            line.discounted_price = t_line.discountedPrice
207
 
208
    cart.total_price = t_cart.totalPrice
209
    cart.discounted_price = t_cart.discountedPrice
1976 varun.gupt 210
    cart.coupon_code = coupon_code
211
    session.commit()
212
 
213
def remove_coupon(cart_id):
214
    cart = get_cart_by_id(cart_id)
215
    if not cart:
216
        raise ShoppingCartException(101, "no cart attached to this id")
2261 varun.gupt 217
 
218
    #Resetting discounted price of each line in cart to Null
219
    for line in cart.lines:
220
        line.discounted_price = None
221
 
3619 chandransh 222
    delete_discounts_from_cart(cart.id, cart=cart)
1976 varun.gupt 223
    cart.discounted_price = None
224
    cart.coupon_code = None
225
    session.commit()
226
 
6389 rajveer 227
def commit_cart(cart_id, sessionSource, sessionTime, firstSource, firstSourceTime, userId, schemeId):   
690 chandransh 228
    cart = get_cart_by_id(cart_id)   
557 chandransh 229
    #now we have a cart. Need to create a transaction with it
576 chandransh 230
    txn = TTransaction()
231
    txn.shoppingCartid = cart_id
5326 rajveer 232
    txn.customer_id = userId
576 chandransh 233
    txn.createdOn = to_java_date(datetime.datetime.now())
234
    txn.transactionStatus = TTransactionStatus.INIT
235
    txn.statusDescription = "New Order"
2219 varun.gupt 236
    txn.coupon_code = cart.coupon_code
2815 vikas 237
    txn.sessionSource = sessionSource
238
    txn.sessionStartTime = sessionTime
3858 vikas 239
    txn.firstSource = firstSource
240
    txn.firstSourceTime = firstSourceTime
6389 rajveer 241
    txn.emiSchemeId = schemeId
5326 rajveer 242
    txn.orders = create_orders(cart, userId)
576 chandransh 243
 
244
    transaction_client = TransactionClient().get_client()
245
    txn_id = transaction_client.createTransaction(txn)
246
    session.commit()
247
 
248
    return txn_id
249
 
5326 rajveer 250
def create_orders(cart, userId):
557 chandransh 251
    cart_lines = cart.lines
576 chandransh 252
    orders = []
6318 rajveer 253
    isGv = False
254
    if cart.coupon_code:
255
        try:
256
            pc = PromotionClient().get_client()
257
            isGv = pc.isGiftVoucher(cart.coupon_code)
258
        except:
259
            isGv = False
260
 
6903 anupam.sin 261
    insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
262
 
557 chandransh 263
    for line in cart_lines:
576 chandransh 264
        if line.line_status == LineStatus.LINE_ACTIVE:
3554 varun.gupt 265
            quantity_remaining_for_order = line.quantity
266
 
267
            for discount in line.discounts:
268
                i = 0
269
                while i < discount.quantity:
6330 rajveer 270
                    t_line_item = create_line_item(line.item_id, line.actual_price if isGv else (line.actual_price - discount.discount))
6903 anupam.sin 271
                    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 272
                    orders.append(t_order)
273
                    i += 1
274
                quantity_remaining_for_order -= discount.quantity
275
 
576 chandransh 276
            i = 0
3554 varun.gupt 277
            while i < quantity_remaining_for_order:
278
                t_line_item = create_line_item(line.item_id, line.actual_price)
6903 anupam.sin 279
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails)
576 chandransh 280
                orders.append(t_order)
281
                i += 1
282
    return orders
283
 
6903 anupam.sin 284
def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails):
5326 rajveer 285
    user = User.get_by(id=userId)
576 chandransh 286
    address = Address.get_by(id=address_id)
287
    t_order = TOrder()
557 chandransh 288
 
576 chandransh 289
    t_order.customer_id = user.id
290
    t_order.customer_email = user.email
291
 
910 rajveer 292
    t_order.customer_name = address.name
576 chandransh 293
    t_order.customer_pincode = address.pin
738 chandransh 294
    t_order.customer_address1 = address.line_1
295
    t_order.customer_address2 = address.line_2
669 chandransh 296
    t_order.customer_city = address.city
297
    t_order.customer_state = address.state
576 chandransh 298
    t_order.customer_mobilenumber = address.phone
299
 
6903 anupam.sin 300
    t_order.total_amount = t_line_item.total_price + insuranceAmount
6318 rajveer 301
    t_order.gvAmount = gvAmount
1976 varun.gupt 302
 
576 chandransh 303
    t_order.total_weight = t_line_item.total_weight
304
    t_order.lineitems = [t_line_item]
305
 
690 chandransh 306
    t_order.status = OrderStatus.PAYMENT_PENDING
970 chandransh 307
    t_order.statusDescription = "Payment Pending"
576 chandransh 308
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
309
 
5555 rajveer 310
    t_order.pickupStoreId = pickupStoreId 
6903 anupam.sin 311
    t_order.insuranceAmount = insuranceAmount 
312
    t_order.insurer = insurer
6935 anupam.sin 313
    if insuranceDetails:
314
        t_order.dob = insuranceDetails.dob
315
        t_order.guardianName = insuranceDetails.guardianName
7190 amar.kumar 316
 
317
    catalog_client = CatalogClient().get_client()
318
    freebie_item_id = catalog_client.getFreebieForItem(t_line_item.item_id)
319
    if freebie_item_id:
320
        t_order.freebieItemId = freebie_item_id
7504 rajveer 321
    t_order.source = OrderSource.WEBSITE
576 chandransh 322
    return t_order
323
 
3768 vikas 324
def create_line_item(item_id, final_price, quantity=1):
3133 rajveer 325
    inventory_client = CatalogClient().get_client()
636 rajveer 326
    item = inventory_client.getItem(item_id)
576 chandransh 327
    t_line_item = TLineItem()
963 chandransh 328
    t_line_item.productGroup = item.productGroup
329
    t_line_item.brand = item.brand
636 rajveer 330
    t_line_item.model_number = item.modelNumber
669 chandransh 331
    if item.color is None or item.color == "NA":
332
        t_line_item.color = ""
333
    else:
917 chandransh 334
        t_line_item.color = item.color
963 chandransh 335
    t_line_item.model_name = item.modelName
636 rajveer 336
    t_line_item.extra_info = item.featureDescription
702 chandransh 337
    t_line_item.item_id = item.id
3768 vikas 338
    t_line_item.quantity = quantity
1983 varun.gupt 339
 
3554 varun.gupt 340
    t_line_item.unit_price = final_price
3768 vikas 341
    t_line_item.total_price = final_price * quantity
1983 varun.gupt 342
 
636 rajveer 343
    t_line_item.unit_weight = item.weight
4172 rajveer 344
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
345
    t_line_item.dealText = item.bestDealText
4295 varun.gupt 346
 
4312 rajveer 347
    if item.warrantyPeriod:
348
        #Computing Manufacturer Warranty expiry date
349
        today = datetime.date.today()
350
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
351
        expiry_month = (today.month + item.warrantyPeriod) % 12
352
 
4295 varun.gupt 353
        try:
4312 rajveer 354
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
4295 varun.gupt 355
        except ValueError:
356
            try:
4312 rajveer 357
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
4295 varun.gupt 358
            except ValueError:
4312 rajveer 359
                try:
360
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
361
                except ValueError:
362
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
363
 
364
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
365
 
576 chandransh 366
    return t_line_item
367
 
3557 rajveer 368
def validate_cart(cartId, sourceId):
3133 rajveer 369
    inventory_client = CatalogClient().get_client()
576 chandransh 370
    logistics_client = LogisticsClient().get_client()
1976 varun.gupt 371
    promotion_client = PromotionClient().get_client()
1466 ankur.sing 372
    retval = ""
6736 amit.gupta 373
    emival = ""
557 chandransh 374
    # No need to validate duplicate items since there are only two ways
375
    # to add items to a cart and both of them check whether the item being
376
    # added is a duplicate of an already existing item.
563 chandransh 377
    cart = Cart.get_by(id=cartId)
378
    cart_lines = cart.lines
776 rajveer 379
    customer_pincode = None
690 chandransh 380
    current_time = datetime.datetime.now()
5929 anupam.sin 381
    if cart.pickupStoreId :
5782 rajveer 382
        store = logistics_client.getPickupStore(cart.pickupStoreId)
383
        customer_pincode = store.pin
5572 anupam.sin 384
    if cart.address_id != None and customer_pincode == None:
576 chandransh 385
        address = Address.get_by(id=cart.address_id)
386
        customer_pincode = address.pin
776 rajveer 387
    if not customer_pincode:
785 rajveer 388
        user = User.get_by(active_cart_id = cartId)
389
        default_address_id = user.default_address_id
776 rajveer 390
        if default_address_id:
391
            address = Address.get_by(id = default_address_id)
392
            customer_pincode = address.pin
393
    if not customer_pincode:
394
        #FIXME should not be hard coded. May be we can pick from config server.
395
        customer_pincode = "110001"
1976 varun.gupt 396
    cart.total_price = 0
563 chandransh 397
    for line in cart_lines:
612 chandransh 398
        old_estimate = line.estimate
636 rajveer 399
        item_id = line.item_id
3557 rajveer 400
        item = inventory_client.getItemForSource(item_id, sourceId)
2983 chandransh 401
        item_shipping_info = inventory_client.isActive(item_id) 
402
        if item_shipping_info.isActive:
403
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
404
                line.quantity = 1
405
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
406
 
2139 chandransh 407
            line.actual_price = item.sellingPrice 
6921 anupam.sin 408
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
776 rajveer 409
            try:
4642 mandeep.dh 410
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
844 chandransh 411
            except LogisticsServiceException:
412
                item_delivery_estimate = -1
413
                #TODO Use the exception clause to set the retval appropriately
414
            except :
415
                item_delivery_estimate = -1
776 rajveer 416
            if old_estimate != item_delivery_estimate:
417
                line.estimate = item_delivery_estimate
418
                cart.updated_on = current_time
576 chandransh 419
        else:
563 chandransh 420
            line.delete()
716 rajveer 421
    if cart.checked_out_on is not None:
422
        if cart.updated_on > cart.checked_out_on:
844 chandransh 423
            cart.checked_out_on = None
612 chandransh 424
    session.commit()
1976 varun.gupt 425
 
6921 anupam.sin 426
    cart = Cart.get_by(id=cartId)
427
    cart_lines = cart.lines
428
    for line in cart_lines :
429
        if line.insurer > 0 :
430
            insure_item(line.item_id, cartId, True)
431
 
1976 varun.gupt 432
    if cart.coupon_code is not None:
2026 varun.gupt 433
        try:
434
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
6922 anupam.sin 435
#            totalInsuranceAmt = 0
436
#            for t_line in updated_cart.lines:
437
#            #Find the line in the database which corresponds to this line
438
#                line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
439
#            #Update its discounted price.
440
#                line.discounted_price = t_line.discountedPrice
441
#            #If discounted price of line is set and this coupon is not a gift voucher that means
442
#            # we will need to correct the insurance price accordingly.
443
##                if line.insurer > 0 and line.discounted_price and not promotion_client.isGiftVoucher(cart.coupon_code) :
444
##                    cc = CatalogClient().get_client()
445
##                    insuranceAmt = cc.getInsuranceAmount(line.item_id, line.discounted_price, line.insurer, line.quantity)
446
##                    line.insuranceAmount = insuranceAmt
447
##                    totalInsuranceAmt += insuranceAmt
448
#            cart.total_price = updated_cart.totalPrice
449
#            cart.discounted_price = updated_cart.discountedPrice
450
#            session.commit()
6740 amit.gupta 451
            if updated_cart.message is not None:
6739 amit.gupta 452
                emival = updated_cart.message
2026 varun.gupt 453
        except PromotionException as ex:
454
            remove_coupon(cart.id)
455
            retval = ex.message
6740 amit.gupta 456
 
6736 amit.gupta 457
    return [retval, emival]
576 chandransh 458
 
557 chandransh 459
def merge_cart(fromCartId, toCartId):
460
    fromCart = Cart.get_by(id=fromCartId)
461
    toCart = Cart.get_by(id=toCartId)
462
 
463
    old_lines = fromCart.lines
464
    new_lines = toCart.lines
465
 
466
    for line in old_lines:
5345 rajveer 467
        for discount in line.discounts:
468
            discount.delete()
469
    session.commit()
470
 
471
    for line in old_lines:
557 chandransh 472
        flag = True
473
        for new_line in new_lines:
474
            if line.item_id == new_line.item_id:
475
                flag = False
5345 rajveer 476
 
576 chandransh 477
        if flag:
5345 rajveer 478
            line.cart_id = toCartId
479
        else:
480
            line.delete()
481
 
2019 varun.gupt 482
    if toCart.coupon_code is None:
483
        toCart.coupon_code = fromCart.coupon_code
484
 
485
    toCart.updated_on = datetime.datetime.now()
557 chandransh 486
    fromCart.expired_on = datetime.datetime.now()
487
    fromCart.cart_status = CartStatus.INACTIVE
643 chandransh 488
    session.commit()
691 chandransh 489
 
490
def check_out(cartId):
491
    if cartId is None:
492
        raise ShoppingCartException(101, "Cart id not specified")
716 rajveer 493
    cart = Cart.get_by(id = cartId)
691 chandransh 494
    if cart is None:
495
        raise ShoppingCartException(102, "The specified cart couldn't be found")
496
    cart.checked_out_on = datetime.datetime.now()
497
    session.commit()
498
    return True
499
 
500
def reset_cart(cartId, items):
501
    if cartId is None:
502
        raise ShoppingCartException(101, "Cart id not specified")
503
    for item_id, quantity in items.iteritems():
504
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
505
        if line is not None:
3566 rajveer 506
            delete_discounts_for_line(line)
2261 varun.gupt 507
            line.discounted_price = None
691 chandransh 508
            line.quantity = line.quantity - quantity
509
            if line.quantity == 0:
510
                line.delete()
717 rajveer 511
    cart = Cart.get_by(id=cartId)
691 chandransh 512
    cart.updated_on = datetime.datetime.now()
1894 vikas 513
    cart.checked_out_on = None
1976 varun.gupt 514
 
515
    # Removing Coupon
516
    cart.total_price = None
517
    cart.discounted_price = None
518
    cart.coupon_code = None
519
 
691 chandransh 520
    session.commit()
766 rajveer 521
    return True
522
 
3386 varun.gupt 523
def get_carts_with_coupon_count(coupon_code):
524
    return Cart.query.filter_by(coupon_code = coupon_code).count()
4668 varun.gupt 525
 
526
def show_cod_option(cartId, sourceId, pincode):
527
    cart = Cart.get_by(id = cartId)
528
    cod_option = True
529
    logistics_client = LogisticsClient().get_client()
530
    if cart:
6355 amit.gupta 531
        if cart.coupon_code:
532
            promotion_client = PromotionClient().get_client()
533
            cod_option = promotion_client.isCodApplicable(cart.coupon_code)
5351 varun.gupt 534
 
6355 amit.gupta 535
        if cod_option and cart.lines:
4668 varun.gupt 536
            for line in cart.lines:
4866 rajveer 537
                logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
4871 rajveer 538
                if not logistics_info.codAllowed:
4668 varun.gupt 539
                    cod_option = False
540
                    break
7492 rajveer 541
            if cart.total_price > 60000 or cart.total_price <= 250:
5430 rajveer 542
                cod_option = False
4668 varun.gupt 543
    return cod_option
6821 amar.kumar 544
 
545
def is_product_added_to_cart(itemId, startDate, endDate):
546
    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()
547
    '''line = Line.query.filter_by(item_id = itemId, created_on > to_py_date(startDate), created_on < to_py_date(endDate)).first()'''
548
    if line is not None:
549
        return True
550
    else:
551
        return False
6903 anupam.sin 552
 
553
def insure_item(itemId, cartId, toInsure):
554
    cart = Cart.get_by(id = cartId)
555
    line = None
556
    for cartLine in cart.lines:
557
        if(cartLine.item_id == itemId):
558
            line = cartLine
559
            break
560
 
561
    if not line:
562
        print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
563
        return False
4668 varun.gupt 564
 
6903 anupam.sin 565
    try:
566
        if toInsure:
6921 anupam.sin 567
            csc = CatalogClient().get_client()
568
            item = csc.getItem(itemId)
569
            insuranceAmount = csc.getInsuranceAmount(itemId, line.discounted_price if line.discounted_price else line.actual_price, item.preferredInsurer, line.quantity)
6903 anupam.sin 570
            line.insurer = item.preferredInsurer
571
            line.insuranceAmount = insuranceAmount
572
            cart.total_price = cart.total_price + insuranceAmount
573
            if cart.discounted_price:
6921 anupam.sin 574
                cart.discounted_price = cart.discounted_price - line.insuranceAmount + insuranceAmount
6903 anupam.sin 575
        else:
6921 anupam.sin 576
            cart.total_price = cart.total_price - line.insuranceAmount
6903 anupam.sin 577
            if cart.discounted_price:
6921 anupam.sin 578
                cart.discounted_price = cart.discounted_price - line.insuranceAmount
6903 anupam.sin 579
            line.insurer = 0
580
            line.insuranceAmount = 0
581
        line.updated_on = datetime.datetime.now()
582
        cart.updated_on = datetime.datetime.now()
583
        session.commit()
584
    except:
585
        print("Error : Unable to insure")
586
        print("insurerId : " + str(item.preferredInsurer) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
587
        return False
588
 
589
    return True
590
 
591
def cancel_insurance(cartId):
592
    try:
593
        cart = Cart.get_by(id = cartId)
594
        for cartLine in cart.lines:
595
            cart.total_price = cart.total_price - cartLine.insuranceAmount
596
            if cart.discounted_price:
597
                cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
598
            cartLine.insurer = 0
599
            cartLine.insuranceAmount = 0
600
            cartLine.updated_on = datetime.datetime.now()
601
        cart.updated_on = datetime.datetime.now()
602
        session.commit()
603
    except:
604
        print("Error : Unable to cancel insurance for cartId :" + str(cartId))
605
        return False
606
 
607
    return True
608
 
609
def store_insurance_specific_details(addressId, dob, guardianName):
610
    try:
611
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
612
        if insuranceDetails is None :
613
            insuranceDetails = InsuranceDetails()
614
        insuranceDetails.addressId = addressId
615
        insuranceDetails.dob = dob
616
        insuranceDetails.guardianName = guardianName
617
        session.commit()
618
    except:
619
        print("Error : Unable to store insurance details for addressId : " + str(addressId))
620
        return False
621
    return True
622
 
623
def is_insurance_detail_present(addressId):
624
    try:
625
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
626
        if insuranceDetails is None :
627
            return False
628
    except:
629
        print("Error : Unable to get insurance details for addressId : " + str(addressId))
630
        return False
631
    return True
632
 
766 rajveer 633
def close_session():
634
    if session.is_active:
635
        print "session is active. closing it."
6903 anupam.sin 636
        session.close()