Subversion Repositories SmartDukaan

Rev

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