Subversion Repositories SmartDukaan

Rev

Rev 5594 | Rev 5928 | 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 = []
239
 
557 chandransh 240
    for line in cart_lines:
576 chandransh 241
        if line.line_status == LineStatus.LINE_ACTIVE:
3554 varun.gupt 242
            quantity_remaining_for_order = line.quantity
243
 
244
            for discount in line.discounts:
245
                i = 0
246
                while i < discount.quantity:
247
                    t_line_item = create_line_item(line.item_id, line.actual_price - discount.discount)
5555 rajveer 248
                    t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId)
3554 varun.gupt 249
                    orders.append(t_order)
250
                    i += 1
251
                quantity_remaining_for_order -= discount.quantity
252
 
576 chandransh 253
            i = 0
3554 varun.gupt 254
            while i < quantity_remaining_for_order:
255
                t_line_item = create_line_item(line.item_id, line.actual_price)
5594 anupam.sin 256
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId)
576 chandransh 257
                orders.append(t_order)
258
                i += 1
259
    return orders
260
 
5555 rajveer 261
def create_order(userId, address_id, t_line_item, pickupStoreId):
5326 rajveer 262
    user = User.get_by(id=userId)
576 chandransh 263
    address = Address.get_by(id=address_id)
264
    t_order = TOrder()
557 chandransh 265
 
576 chandransh 266
    t_order.customer_id = user.id
267
    t_order.customer_email = user.email
268
 
910 rajveer 269
    t_order.customer_name = address.name
576 chandransh 270
    t_order.customer_pincode = address.pin
738 chandransh 271
    t_order.customer_address1 = address.line_1
272
    t_order.customer_address2 = address.line_2
669 chandransh 273
    t_order.customer_city = address.city
274
    t_order.customer_state = address.state
576 chandransh 275
    t_order.customer_mobilenumber = address.phone
276
 
277
    t_order.total_amount = t_line_item.total_price
1976 varun.gupt 278
 
576 chandransh 279
    t_order.total_weight = t_line_item.total_weight
280
    t_order.lineitems = [t_line_item]
281
 
690 chandransh 282
    t_order.status = OrderStatus.PAYMENT_PENDING
970 chandransh 283
    t_order.statusDescription = "Payment Pending"
576 chandransh 284
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
285
 
5555 rajveer 286
    t_order.pickupStoreId = pickupStoreId 
576 chandransh 287
    return t_order
288
 
3768 vikas 289
def create_line_item(item_id, final_price, quantity=1):
3133 rajveer 290
    inventory_client = CatalogClient().get_client()
636 rajveer 291
    item = inventory_client.getItem(item_id)
576 chandransh 292
    t_line_item = TLineItem()
963 chandransh 293
    t_line_item.productGroup = item.productGroup
294
    t_line_item.brand = item.brand
636 rajveer 295
    t_line_item.model_number = item.modelNumber
669 chandransh 296
    if item.color is None or item.color == "NA":
297
        t_line_item.color = ""
298
    else:
917 chandransh 299
        t_line_item.color = item.color
963 chandransh 300
    t_line_item.model_name = item.modelName
636 rajveer 301
    t_line_item.extra_info = item.featureDescription
702 chandransh 302
    t_line_item.item_id = item.id
3768 vikas 303
    t_line_item.quantity = quantity
1983 varun.gupt 304
 
3554 varun.gupt 305
    t_line_item.unit_price = final_price
3768 vikas 306
    t_line_item.total_price = final_price * quantity
1983 varun.gupt 307
 
636 rajveer 308
    t_line_item.unit_weight = item.weight
4172 rajveer 309
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
310
    t_line_item.dealText = item.bestDealText
4295 varun.gupt 311
 
4312 rajveer 312
    if item.warrantyPeriod:
313
        #Computing Manufacturer Warranty expiry date
314
        today = datetime.date.today()
315
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
316
        expiry_month = (today.month + item.warrantyPeriod) % 12
317
 
4295 varun.gupt 318
        try:
4312 rajveer 319
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
4295 varun.gupt 320
        except ValueError:
321
            try:
4312 rajveer 322
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
4295 varun.gupt 323
            except ValueError:
4312 rajveer 324
                try:
325
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
326
                except ValueError:
327
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
328
 
329
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
330
 
576 chandransh 331
    return t_line_item
332
 
3557 rajveer 333
def validate_cart(cartId, sourceId):
3133 rajveer 334
    inventory_client = CatalogClient().get_client()
576 chandransh 335
    logistics_client = LogisticsClient().get_client()
1976 varun.gupt 336
    promotion_client = PromotionClient().get_client()
1466 ankur.sing 337
    retval = ""
557 chandransh 338
    # No need to validate duplicate items since there are only two ways
339
    # to add items to a cart and both of them check whether the item being
340
    # added is a duplicate of an already existing item.
563 chandransh 341
    cart = Cart.get_by(id=cartId)
342
    cart_lines = cart.lines
776 rajveer 343
    customer_pincode = None
690 chandransh 344
    current_time = datetime.datetime.now()
5572 anupam.sin 345
    if cart.pickupStoreId:
5782 rajveer 346
        store = logistics_client.getPickupStore(cart.pickupStoreId)
347
        customer_pincode = store.pin
5572 anupam.sin 348
    if cart.address_id != None and customer_pincode == None:
576 chandransh 349
        address = Address.get_by(id=cart.address_id)
350
        customer_pincode = address.pin
776 rajveer 351
    if not customer_pincode:
785 rajveer 352
        user = User.get_by(active_cart_id = cartId)
353
        default_address_id = user.default_address_id
776 rajveer 354
        if default_address_id:
355
            address = Address.get_by(id = default_address_id)
356
            customer_pincode = address.pin
357
    if not customer_pincode:
358
        #FIXME should not be hard coded. May be we can pick from config server.
359
        customer_pincode = "110001"
1976 varun.gupt 360
    cart.total_price = 0
563 chandransh 361
    for line in cart_lines:
612 chandransh 362
        old_estimate = line.estimate
636 rajveer 363
        item_id = line.item_id
3557 rajveer 364
        item = inventory_client.getItemForSource(item_id, sourceId)
2983 chandransh 365
        item_shipping_info = inventory_client.isActive(item_id) 
366
        if item_shipping_info.isActive:
367
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
368
                line.quantity = 1
369
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
370
 
2139 chandransh 371
            line.actual_price = item.sellingPrice 
372
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
776 rajveer 373
            try:
4642 mandeep.dh 374
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
844 chandransh 375
            except LogisticsServiceException:
376
                item_delivery_estimate = -1
377
                #TODO Use the exception clause to set the retval appropriately
378
            except :
379
                item_delivery_estimate = -1
776 rajveer 380
            if old_estimate != item_delivery_estimate:
381
                line.estimate = item_delivery_estimate
382
                cart.updated_on = current_time
1466 ankur.sing 383
                if old_estimate != None:
384
                    retval = "Delivery Estimates updated."
576 chandransh 385
        else:
563 chandransh 386
            line.delete()
1466 ankur.sing 387
            retval = "Some items have been removed from the cart."
716 rajveer 388
    if cart.checked_out_on is not None:
389
        if cart.updated_on > cart.checked_out_on:
844 chandransh 390
            cart.checked_out_on = None
1466 ankur.sing 391
            if retval == "":
392
                retval = "Your cart has been updated after the last checkout."
612 chandransh 393
    session.commit()
1976 varun.gupt 394
 
395
    if cart.coupon_code is not None:
2026 varun.gupt 396
        try:
397
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
398
            for t_line in updated_cart.lines:
1976 varun.gupt 399
            #Find the line in the database which corresponds to this line
2026 varun.gupt 400
                line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
1976 varun.gupt 401
            #Update its discounted price.
2026 varun.gupt 402
                line.discounted_price = t_line.discountedPrice
403
            cart.discounted_price = updated_cart.discountedPrice
404
            session.commit()
405
        except PromotionException as ex:
406
            remove_coupon(cart.id)
407
            retval = ex.message
563 chandransh 408
    return retval
576 chandransh 409
 
557 chandransh 410
def merge_cart(fromCartId, toCartId):
411
    fromCart = Cart.get_by(id=fromCartId)
412
    toCart = Cart.get_by(id=toCartId)
413
 
414
    old_lines = fromCart.lines
415
    new_lines = toCart.lines
416
 
417
    for line in old_lines:
5345 rajveer 418
        for discount in line.discounts:
419
            discount.delete()
420
    session.commit()
421
 
422
    for line in old_lines:
557 chandransh 423
        flag = True
424
        for new_line in new_lines:
425
            if line.item_id == new_line.item_id:
426
                flag = False
5345 rajveer 427
 
576 chandransh 428
        if flag:
5345 rajveer 429
            line.cart_id = toCartId
430
        else:
431
            line.delete()
432
 
2019 varun.gupt 433
    if toCart.coupon_code is None:
434
        toCart.coupon_code = fromCart.coupon_code
435
 
436
    toCart.updated_on = datetime.datetime.now()
557 chandransh 437
    fromCart.expired_on = datetime.datetime.now()
438
    fromCart.cart_status = CartStatus.INACTIVE
643 chandransh 439
    session.commit()
691 chandransh 440
 
441
def check_out(cartId):
442
    if cartId is None:
443
        raise ShoppingCartException(101, "Cart id not specified")
716 rajveer 444
    cart = Cart.get_by(id = cartId)
691 chandransh 445
    if cart is None:
446
        raise ShoppingCartException(102, "The specified cart couldn't be found")
447
    cart.checked_out_on = datetime.datetime.now()
448
    session.commit()
449
    return True
450
 
451
def reset_cart(cartId, items):
452
    if cartId is None:
453
        raise ShoppingCartException(101, "Cart id not specified")
454
    for item_id, quantity in items.iteritems():
455
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
456
        if line is not None:
3566 rajveer 457
            delete_discounts_for_line(line)
2261 varun.gupt 458
            line.discounted_price = None
691 chandransh 459
            line.quantity = line.quantity - quantity
460
            if line.quantity == 0:
461
                line.delete()
717 rajveer 462
    cart = Cart.get_by(id=cartId)
691 chandransh 463
    cart.updated_on = datetime.datetime.now()
1894 vikas 464
    cart.checked_out_on = None
1976 varun.gupt 465
 
466
    # Removing Coupon
467
    cart.total_price = None
468
    cart.discounted_price = None
469
    cart.coupon_code = None
470
 
691 chandransh 471
    session.commit()
766 rajveer 472
    return True
473
 
3386 varun.gupt 474
def get_carts_with_coupon_count(coupon_code):
475
    return Cart.query.filter_by(coupon_code = coupon_code).count()
4668 varun.gupt 476
 
477
def show_cod_option(cartId, sourceId, pincode):
478
    cart = Cart.get_by(id = cartId)
479
    cod_option = True
480
    logistics_client = LogisticsClient().get_client()
481
    if cart:
5351 varun.gupt 482
        if cart.coupon_code and cart.coupon_code.lower() == 'searlybird':
483
            cod_option = False
484
 
4668 varun.gupt 485
        elif cart.lines:
486
            for line in cart.lines:
4866 rajveer 487
                logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
4871 rajveer 488
                if not logistics_info.codAllowed:
4668 varun.gupt 489
                    cod_option = False
490
                    break
5434 rajveer 491
            if cart.total_price > 20000 or cart.total_price <= 250:
5430 rajveer 492
                cod_option = False
4668 varun.gupt 493
    return cod_option
494
 
766 rajveer 495
def close_session():
496
    if session.is_active:
497
        print "session is active. closing it."
1621 rajveer 498
        session.close()