Subversion Repositories SmartDukaan

Rev

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