Subversion Repositories SmartDukaan

Rev

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

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