Subversion Repositories SmartDukaan

Rev

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