Subversion Repositories SmartDukaan

Rev

Rev 3039 | Rev 3386 | 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 *
576 chandransh 7
from shop2020.model.v1.user.impl.Dataservice import Cart, Line, Address, User
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
 
576 chandransh 16
from shop2020.thriftpy.model.v1.catalog.ttypes import Item as TItem
844 chandransh 17
from shop2020.thriftpy.logistics.ttypes import LogisticsInfo as TLogisticsInfo,\
18
    LogisticsServiceException
576 chandransh 19
 
20
from shop2020.clients.TransactionClient import TransactionClient
3133 rajveer 21
from shop2020.clients.CatalogClient import CatalogClient
576 chandransh 22
from shop2020.clients.LogisticsClient import LogisticsClient
23
from shop2020.model.v1 import user
1976 varun.gupt 24
from shop2020.clients.PromotionClient import PromotionClient
2026 varun.gupt 25
from shop2020.model.v1.user.impl import UserDataAccessors
576 chandransh 26
 
557 chandransh 27
def get_cart(user_id):
28
    query = Cart.query.filter_by(user_id=user_id)      
29
    query = query.filter_by(cart_status = CartStatus.ACTIVE)
30
    try:
31
        cart = query.one()
32
        session.commit()
33
    except:
34
        return None
35
#        raise ShoppingCartException(101, "Cart does not exist")
36
    return cart
37
 
38
def get_cart_by_id(id):
39
    cart = Cart.get_by(id=id)
40
    return cart
41
 
42
def create_cart(user_id):
43
    cart = get_cart(user_id)
44
    if not cart: 
45
        cart = Cart()
46
        cart.user_id = user_id
47
        cart.created_on = datetime.datetime.now()
48
        cart.updated_on = datetime.datetime.now()
49
        cart.cart_status = CartStatus.ACTIVE
50
        session.commit()
51
    return cart
52
 
53
def get_cart_by_user_id_and_status(user_id, status):
54
    query = Cart.query.filter_by(user_id=user_id)
55
    if status:
56
        query = query.filter_by(cart_status=status)
57
    carts = query.all()
58
    return carts
59
 
60
def get_carts_by_status(status):
61
    return Cart.query.filter_by(cart_status=status).all()
62
 
63
def get_carts_between(start_time, end_time, status):
64
    init_time = to_py_date(start_time)
65
    finish_time = to_py_date(end_time)
66
 
67
    query = Cart.query
68
    if status:
69
        query = query.filter(Cart.cart_status==status)
70
    if init_time:
71
        query = query.filter(Cart.created_on >= init_time)
72
    if finish_time:
73
        query = query.filter(Cart.created_on <= finish_time)
74
 
75
    carts = query.all()
76
    return carts
77
 
643 chandransh 78
def get_line(item_id, cart_id, status, single):
557 chandransh 79
    #get cart first 
80
    try:
81
        found_cart = Cart.get_by(id=cart_id)
82
    except:
83
        raise ShoppingCartException(101, "cart not found ")
643 chandransh 84
    query = Line.query.filter_by(cart = found_cart, item_id = item_id)
557 chandransh 85
 
86
    if status:
87
        query = query.filter_by(line_status = status)
88
    else:
89
        query = query.filter_by(line_status = LineStatus.LINE_ACTIVE)
90
    try:
91
        if single:
92
            return query.one()
93
        else:
94
            return query.all()
95
    except:
96
        return None
97
 
98
def change_cart_status(cart_id, status):
99
    cart = get_cart_by_id(id)
100
    if not cart:
101
        raise ShoppingCartException(101, "no cart attached to this id")
102
    if not status:
103
        raise ShoppingCartException(101, "invalid status")
690 chandransh 104
    cart.cart_status = status
557 chandransh 105
    session.commit()
106
 
107
def add_item_to_cart(cart_id, item_id, quantity):
108
    if not item_id:
109
        raise ShoppingCartException(101, "item_id cannot be null")
110
 
111
    if not quantity:
112
        raise ShoppingCartException(101, "quantity cannot be null")    
643 chandransh 113
 
2983 chandransh 114
    cart = Cart.get_by(id = cart_id)    
557 chandransh 115
    if not cart:
116
        raise ShoppingCartException(101, "no cart attached to this id")
2983 chandransh 117
    retval = ""
3133 rajveer 118
    inventory_client = CatalogClient().get_client()
2983 chandransh 119
    item = inventory_client.getItem(item_id)
120
    item_shipping_info = inventory_client.isActive(item_id)
121
    if not item_shipping_info.isActive:
2035 rajveer 122
        return inventory_client.getItemStatusDescription(item_id)
557 chandransh 123
 
643 chandransh 124
    current_time = datetime.datetime.now()
125
    cart.updated_on = current_time
126
    line = get_line(item_id, cart_id, None,True)
127
    if line:
128
        #change the quantity only
129
        line.quantity = quantity
685 chandransh 130
        line.updated_on = current_time
643 chandransh 131
    else:
132
        line = Line()
133
        line.cart = cart
134
        line.item_id = item_id
135
        line.quantity = quantity
136
        line.created_on = current_time
137
        line.updated_on = current_time
138
        line.line_status = LineStatus.LINE_ACTIVE
557 chandransh 139
    session.commit()
2983 chandransh 140
    return retval
557 chandransh 141
 
142
def delete_item_from_cart(cart_id, item_id):
143
    if not item_id:
144
        raise ShoppingCartException(101, "item_id cannot be null")
685 chandransh 145
    cart = Cart.get_by(id = cart_id)
146
    if not cart:
147
        raise ShoppingCartException(101, "no cart attached to this id")
643 chandransh 148
    item = get_line(item_id, cart_id, None, True)
557 chandransh 149
    item.delete()
685 chandransh 150
    current_time = datetime.datetime.now()
151
    cart.updated_on = current_time
557 chandransh 152
    session.commit()
153
 
154
def change_item_status(cart_id, item_id, status):
155
    if not status:
156
        raise ShoppingCartException(101, "Status cannot be made null")
685 chandransh 157
    line = get_line(item_id, cart_id, None, True)
158
    if line:
159
        line.line_status = status
160
        current_time = datetime.datetime.now()
161
        line.updated_on = current_time
162
        line.cart.updated_on = current_time
557 chandransh 163
        session.commit()
164
    else:
685 chandransh 165
        raise ShoppingCartException(101, "Unable to probe the line you desired")
557 chandransh 166
 
167
def add_address_to_cart(cart_id, address_id):
168
    if not cart_id:
169
        raise ShoppingCartException(101, "cart id cannot be made null")
170
 
171
    if not address_id:
172
        raise ShoppingCartException(101, "address id cannot be made null")
173
 
174
    cart = get_cart_by_id(cart_id)
175
    if not cart:
176
        raise ShoppingCartException(101, "no cart for this id")
576 chandransh 177
 
178
    address = Address.get_by(id=address_id)
179
    if not address:
180
        raise ShoppingCartException(101, "No address for this id")
181
 
557 chandransh 182
    cart.address_id = address_id
685 chandransh 183
    current_time = datetime.datetime.now()
716 rajveer 184
    #cart.updated_on = current_time
557 chandransh 185
    session.commit()
186
 
1976 varun.gupt 187
def apply_coupon_to_cart(cart_id, coupon_code, total_price, discounted_price):
188
    cart = get_cart_by_id(cart_id)
189
    if not cart:
190
        raise ShoppingCartException(101, "no cart attached to this id")
191
    cart.total_price = total_price
192
    cart.discounted_price = discounted_price
193
    cart.coupon_code = coupon_code
194
    session.commit()
195
 
196
def remove_coupon(cart_id):
197
    cart = get_cart_by_id(cart_id)
198
    if not cart:
199
        raise ShoppingCartException(101, "no cart attached to this id")
2261 varun.gupt 200
 
201
    #Resetting discounted price of each line in cart to Null
202
    for line in cart.lines:
203
        line.discounted_price = None
204
 
1976 varun.gupt 205
    cart.discounted_price = None
206
    cart.coupon_code = None
207
    session.commit()
208
 
2815 vikas 209
def commit_cart(cart_id, sessionSource, sessionTime):   
690 chandransh 210
    cart = get_cart_by_id(cart_id)   
557 chandransh 211
    #now we have a cart. Need to create a transaction with it
576 chandransh 212
    txn = TTransaction()
213
    txn.shoppingCartid = cart_id
214
    txn.customer_id = cart.user_id
215
    txn.createdOn = to_java_date(datetime.datetime.now())
216
    txn.transactionStatus = TTransactionStatus.INIT
217
    txn.statusDescription = "New Order"
2219 varun.gupt 218
    txn.coupon_code = cart.coupon_code
2815 vikas 219
    txn.sessionSource = sessionSource
220
    txn.sessionStartTime = sessionTime
557 chandransh 221
 
576 chandransh 222
    txn.orders = create_orders(cart)
223
 
224
    transaction_client = TransactionClient().get_client()
225
    txn_id = transaction_client.createTransaction(txn)
226
    session.commit()
227
 
685 chandransh 228
    #new_cart = create_cart(cart.user_id)
229
    #user = User.get_by(id=cart.user_id)
230
    #user.active_cart_id = new_cart.id
231
    #session.commit()
576 chandransh 232
    return txn_id
233
 
234
def create_orders(cart):
557 chandransh 235
    cart_lines = cart.lines
576 chandransh 236
    orders = []
237
 
557 chandransh 238
    for line in cart_lines:
576 chandransh 239
        if line.line_status == LineStatus.LINE_ACTIVE:
240
            i = 0
241
            while i< line.quantity:
1976 varun.gupt 242
                t_line_item = create_line_item(line.item_id, line.discounted_price)
576 chandransh 243
                t_order = create_order(cart.user_id, cart.address_id, t_line_item)
244
                orders.append(t_order)
245
                i += 1
246
    return orders
247
 
248
def create_order(user_id, address_id, t_line_item):
249
    user = User.get_by(id=user_id)
250
    address = Address.get_by(id=address_id)
251
    t_order = TOrder()
557 chandransh 252
 
576 chandransh 253
    t_order.customer_id = user.id
254
    t_order.customer_email = user.email
255
 
910 rajveer 256
    t_order.customer_name = address.name
576 chandransh 257
    t_order.customer_pincode = address.pin
738 chandransh 258
    t_order.customer_address1 = address.line_1
259
    t_order.customer_address2 = address.line_2
669 chandransh 260
    t_order.customer_city = address.city
261
    t_order.customer_state = address.state
576 chandransh 262
    t_order.customer_mobilenumber = address.phone
263
 
264
    t_order.total_amount = t_line_item.total_price
1976 varun.gupt 265
 
576 chandransh 266
    t_order.total_weight = t_line_item.total_weight
267
    t_order.lineitems = [t_line_item]
268
 
690 chandransh 269
    t_order.status = OrderStatus.PAYMENT_PENDING
970 chandransh 270
    t_order.statusDescription = "Payment Pending"
576 chandransh 271
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
272
 
273
    return t_order
274
 
1976 varun.gupt 275
def create_line_item(item_id, discounted_price):
3133 rajveer 276
    inventory_client = CatalogClient().get_client()
636 rajveer 277
    item = inventory_client.getItem(item_id)
576 chandransh 278
    t_line_item = TLineItem()
963 chandransh 279
    t_line_item.productGroup = item.productGroup
280
    t_line_item.brand = item.brand
636 rajveer 281
    t_line_item.model_number = item.modelNumber
669 chandransh 282
    if item.color is None or item.color == "NA":
283
        t_line_item.color = ""
284
    else:
917 chandransh 285
        t_line_item.color = item.color
963 chandransh 286
    t_line_item.model_name = item.modelName
636 rajveer 287
    t_line_item.extra_info = item.featureDescription
702 chandransh 288
    t_line_item.item_id = item.id
576 chandransh 289
    t_line_item.quantity = 1
1983 varun.gupt 290
 
291
    if discounted_price is None or discounted_price == 0:
292
        t_line_item.unit_price = item.sellingPrice
293
        t_line_item.total_price = item.sellingPrice
294
    else:
295
        t_line_item.unit_price = discounted_price
296
        t_line_item.total_price = discounted_price
297
 
636 rajveer 298
    t_line_item.unit_weight = item.weight
299
    t_line_item.total_weight = item.weight
576 chandransh 300
    return t_line_item
301
 
302
def validate_cart(cartId):
3133 rajveer 303
    inventory_client = CatalogClient().get_client()
576 chandransh 304
    logistics_client = LogisticsClient().get_client()
1976 varun.gupt 305
    promotion_client = PromotionClient().get_client()
1466 ankur.sing 306
    retval = ""
557 chandransh 307
    # No need to validate duplicate items since there are only two ways
308
    # to add items to a cart and both of them check whether the item being
309
    # added is a duplicate of an already existing item.
563 chandransh 310
    cart = Cart.get_by(id=cartId)
311
    cart_lines = cart.lines
776 rajveer 312
    customer_pincode = None
690 chandransh 313
    current_time = datetime.datetime.now()
576 chandransh 314
    if cart.address_id:
315
        address = Address.get_by(id=cart.address_id)
316
        customer_pincode = address.pin
776 rajveer 317
    if not customer_pincode:
785 rajveer 318
        user = User.get_by(active_cart_id = cartId)
319
        default_address_id = user.default_address_id
776 rajveer 320
        if default_address_id:
321
            address = Address.get_by(id = default_address_id)
322
            customer_pincode = address.pin
323
    if not customer_pincode:
324
        #FIXME should not be hard coded. May be we can pick from config server.
325
        customer_pincode = "110001"
1976 varun.gupt 326
    cart.total_price = 0
563 chandransh 327
    for line in cart_lines:
612 chandransh 328
        old_estimate = line.estimate
636 rajveer 329
        item_id = line.item_id
1976 varun.gupt 330
        item = inventory_client.getItem(item_id)
2983 chandransh 331
        item_shipping_info = inventory_client.isActive(item_id) 
332
        if item_shipping_info.isActive:
333
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
334
                line.quantity = 1
335
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
336
 
2139 chandransh 337
            line.actual_price = item.sellingPrice 
338
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
776 rajveer 339
            try:
340
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode).deliveryTime
844 chandransh 341
            except LogisticsServiceException:
342
                item_delivery_estimate = -1
343
                #TODO Use the exception clause to set the retval appropriately
344
            except :
345
                item_delivery_estimate = -1
776 rajveer 346
            if old_estimate != item_delivery_estimate:
347
                line.estimate = item_delivery_estimate
348
                cart.updated_on = current_time
1466 ankur.sing 349
                if old_estimate != None:
350
                    retval = "Delivery Estimates updated."
576 chandransh 351
        else:
563 chandransh 352
            line.delete()
1466 ankur.sing 353
            retval = "Some items have been removed from the cart."
716 rajveer 354
    if cart.checked_out_on is not None:
355
        if cart.updated_on > cart.checked_out_on:
844 chandransh 356
            cart.checked_out_on = None
1466 ankur.sing 357
            if retval == "":
358
                retval = "Your cart has been updated after the last checkout."
612 chandransh 359
    session.commit()
1976 varun.gupt 360
 
361
    if cart.coupon_code is not None:
2026 varun.gupt 362
        try:
363
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
364
            for t_line in updated_cart.lines:
1976 varun.gupt 365
            #Find the line in the database which corresponds to this line
2026 varun.gupt 366
                line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
1976 varun.gupt 367
            #Update its discounted price.
2026 varun.gupt 368
                line.discounted_price = t_line.discountedPrice
369
            cart.discounted_price = updated_cart.discountedPrice
370
            session.commit()
371
        except PromotionException as ex:
372
            remove_coupon(cart.id)
373
            retval = ex.message
563 chandransh 374
    return retval
576 chandransh 375
 
557 chandransh 376
def merge_cart(fromCartId, toCartId):
377
    fromCart = Cart.get_by(id=fromCartId)
378
    toCart = Cart.get_by(id=toCartId)
379
 
380
    old_lines = fromCart.lines
381
    new_lines = toCart.lines
382
 
383
    for line in old_lines:
384
        flag = True
385
        for new_line in new_lines:
386
            if line.item_id == new_line.item_id:
387
                flag = False
576 chandransh 388
        if flag:
557 chandransh 389
            toCart.lines.append(line)
390
 
2019 varun.gupt 391
    if toCart.coupon_code is None:
392
        toCart.coupon_code = fromCart.coupon_code
393
 
394
    toCart.updated_on = datetime.datetime.now()
557 chandransh 395
    fromCart.expired_on = datetime.datetime.now()
396
    fromCart.cart_status = CartStatus.INACTIVE
643 chandransh 397
    session.commit()
691 chandransh 398
 
399
def check_out(cartId):
400
    if cartId is None:
401
        raise ShoppingCartException(101, "Cart id not specified")
716 rajveer 402
    cart = Cart.get_by(id = cartId)
691 chandransh 403
    if cart is None:
404
        raise ShoppingCartException(102, "The specified cart couldn't be found")
405
    cart.checked_out_on = datetime.datetime.now()
406
    session.commit()
407
    return True
408
 
409
def reset_cart(cartId, items):
410
    if cartId is None:
411
        raise ShoppingCartException(101, "Cart id not specified")
412
    for item_id, quantity in items.iteritems():
413
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
414
        if line is not None:
2261 varun.gupt 415
            line.discounted_price = None
691 chandransh 416
            line.quantity = line.quantity - quantity
417
            if line.quantity == 0:
418
                line.delete()
717 rajveer 419
    cart = Cart.get_by(id=cartId)
691 chandransh 420
    cart.updated_on = datetime.datetime.now()
1894 vikas 421
    cart.checked_out_on = None
1976 varun.gupt 422
 
423
    # Removing Coupon
424
    cart.total_price = None
425
    cart.discounted_price = None
426
    cart.coupon_code = None
427
 
691 chandransh 428
    session.commit()
766 rajveer 429
    return True
430
 
431
def close_session():
432
    if session.is_active:
433
        print "session is active. closing it."
1621 rajveer 434
        session.close()