Subversion Repositories SmartDukaan

Rev

Rev 6740 | Rev 6903 | 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:
6502 rajveer 83
        raise ShoppingCartException(101, "no cart attached to this id" + str(cart_id))
2983 chandransh 84
    retval = ""
6550 rajveer 85
    catalog_client = CatalogClient().get_client()
86
    item = catalog_client.getItemForSource(item_id, sourceId)
87
    item_shipping_info = catalog_client.isActive(item_id)
2983 chandransh 88
    if not item_shipping_info.isActive:
6550 rajveer 89
        return catalog_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
 
6389 rajveer 213
def commit_cart(cart_id, sessionSource, sessionTime, firstSource, firstSourceTime, userId, schemeId):   
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
6389 rajveer 227
    txn.emiSchemeId = schemeId
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 = ""
6736 amit.gupta 346
    emival = ""
557 chandransh 347
    # No need to validate duplicate items since there are only two ways
348
    # to add items to a cart and both of them check whether the item being
349
    # added is a duplicate of an already existing item.
563 chandransh 350
    cart = Cart.get_by(id=cartId)
351
    cart_lines = cart.lines
776 rajveer 352
    customer_pincode = None
690 chandransh 353
    current_time = datetime.datetime.now()
5929 anupam.sin 354
    if cart.pickupStoreId :
5782 rajveer 355
        store = logistics_client.getPickupStore(cart.pickupStoreId)
356
        customer_pincode = store.pin
5572 anupam.sin 357
    if cart.address_id != None and customer_pincode == None:
576 chandransh 358
        address = Address.get_by(id=cart.address_id)
359
        customer_pincode = address.pin
776 rajveer 360
    if not customer_pincode:
785 rajveer 361
        user = User.get_by(active_cart_id = cartId)
362
        default_address_id = user.default_address_id
776 rajveer 363
        if default_address_id:
364
            address = Address.get_by(id = default_address_id)
365
            customer_pincode = address.pin
366
    if not customer_pincode:
367
        #FIXME should not be hard coded. May be we can pick from config server.
368
        customer_pincode = "110001"
1976 varun.gupt 369
    cart.total_price = 0
563 chandransh 370
    for line in cart_lines:
612 chandransh 371
        old_estimate = line.estimate
636 rajveer 372
        item_id = line.item_id
3557 rajveer 373
        item = inventory_client.getItemForSource(item_id, sourceId)
2983 chandransh 374
        item_shipping_info = inventory_client.isActive(item_id) 
375
        if item_shipping_info.isActive:
376
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
377
                line.quantity = 1
378
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
379
 
2139 chandransh 380
            line.actual_price = item.sellingPrice 
381
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
776 rajveer 382
            try:
4642 mandeep.dh 383
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
844 chandransh 384
            except LogisticsServiceException:
385
                item_delivery_estimate = -1
386
                #TODO Use the exception clause to set the retval appropriately
387
            except :
388
                item_delivery_estimate = -1
776 rajveer 389
            if old_estimate != item_delivery_estimate:
390
                line.estimate = item_delivery_estimate
391
                cart.updated_on = current_time
576 chandransh 392
        else:
563 chandransh 393
            line.delete()
716 rajveer 394
    if cart.checked_out_on is not None:
395
        if cart.updated_on > cart.checked_out_on:
844 chandransh 396
            cart.checked_out_on = None
612 chandransh 397
    session.commit()
1976 varun.gupt 398
 
399
    if cart.coupon_code is not None:
2026 varun.gupt 400
        try:
401
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
402
            for t_line in updated_cart.lines:
1976 varun.gupt 403
            #Find the line in the database which corresponds to this line
2026 varun.gupt 404
                line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
1976 varun.gupt 405
            #Update its discounted price.
2026 varun.gupt 406
                line.discounted_price = t_line.discountedPrice
407
            cart.discounted_price = updated_cart.discountedPrice
408
            session.commit()
6740 amit.gupta 409
            if updated_cart.message is not None:
6739 amit.gupta 410
                emival = updated_cart.message
2026 varun.gupt 411
        except PromotionException as ex:
412
            remove_coupon(cart.id)
413
            retval = ex.message
6740 amit.gupta 414
 
6736 amit.gupta 415
    return [retval, emival]
576 chandransh 416
 
557 chandransh 417
def merge_cart(fromCartId, toCartId):
418
    fromCart = Cart.get_by(id=fromCartId)
419
    toCart = Cart.get_by(id=toCartId)
420
 
421
    old_lines = fromCart.lines
422
    new_lines = toCart.lines
423
 
424
    for line in old_lines:
5345 rajveer 425
        for discount in line.discounts:
426
            discount.delete()
427
    session.commit()
428
 
429
    for line in old_lines:
557 chandransh 430
        flag = True
431
        for new_line in new_lines:
432
            if line.item_id == new_line.item_id:
433
                flag = False
5345 rajveer 434
 
576 chandransh 435
        if flag:
5345 rajveer 436
            line.cart_id = toCartId
437
        else:
438
            line.delete()
439
 
2019 varun.gupt 440
    if toCart.coupon_code is None:
441
        toCart.coupon_code = fromCart.coupon_code
442
 
443
    toCart.updated_on = datetime.datetime.now()
557 chandransh 444
    fromCart.expired_on = datetime.datetime.now()
445
    fromCart.cart_status = CartStatus.INACTIVE
643 chandransh 446
    session.commit()
691 chandransh 447
 
448
def check_out(cartId):
449
    if cartId is None:
450
        raise ShoppingCartException(101, "Cart id not specified")
716 rajveer 451
    cart = Cart.get_by(id = cartId)
691 chandransh 452
    if cart is None:
453
        raise ShoppingCartException(102, "The specified cart couldn't be found")
454
    cart.checked_out_on = datetime.datetime.now()
455
    session.commit()
456
    return True
457
 
458
def reset_cart(cartId, items):
459
    if cartId is None:
460
        raise ShoppingCartException(101, "Cart id not specified")
461
    for item_id, quantity in items.iteritems():
462
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
463
        if line is not None:
3566 rajveer 464
            delete_discounts_for_line(line)
2261 varun.gupt 465
            line.discounted_price = None
691 chandransh 466
            line.quantity = line.quantity - quantity
467
            if line.quantity == 0:
468
                line.delete()
717 rajveer 469
    cart = Cart.get_by(id=cartId)
691 chandransh 470
    cart.updated_on = datetime.datetime.now()
1894 vikas 471
    cart.checked_out_on = None
1976 varun.gupt 472
 
473
    # Removing Coupon
474
    cart.total_price = None
475
    cart.discounted_price = None
476
    cart.coupon_code = None
477
 
691 chandransh 478
    session.commit()
766 rajveer 479
    return True
480
 
3386 varun.gupt 481
def get_carts_with_coupon_count(coupon_code):
482
    return Cart.query.filter_by(coupon_code = coupon_code).count()
4668 varun.gupt 483
 
484
def show_cod_option(cartId, sourceId, pincode):
485
    cart = Cart.get_by(id = cartId)
486
    cod_option = True
487
    logistics_client = LogisticsClient().get_client()
488
    if cart:
6355 amit.gupta 489
        if cart.coupon_code:
490
            promotion_client = PromotionClient().get_client()
491
            cod_option = promotion_client.isCodApplicable(cart.coupon_code)
5351 varun.gupt 492
 
6355 amit.gupta 493
        if cod_option and cart.lines:
4668 varun.gupt 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
6528 rajveer 499
            if cart.total_price > 25000 or cart.total_price <= 250:
5430 rajveer 500
                cod_option = False
4668 varun.gupt 501
    return cod_option
6821 amar.kumar 502
 
503
def is_product_added_to_cart(itemId, startDate, endDate):
504
    line = Line.query.filter_by(item_id = itemId).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).first()
505
    '''line = Line.query.filter_by(item_id = itemId, created_on > to_py_date(startDate), created_on < to_py_date(endDate)).first()'''
506
    if line is not None:
507
        return True
508
    else:
509
        return False
4668 varun.gupt 510
 
766 rajveer 511
def close_session():
512
    if session.is_active:
513
        print "session is active. closing it."
1621 rajveer 514
        session.close()