Subversion Repositories SmartDukaan

Rev

Rev 2139 | Rev 2261 | 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
21
from shop2020.clients.InventoryClient import InventoryClient
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
 
114
    cart = Cart.get_by(id = cart_id)
557 chandransh 115
    if not cart:
116
        raise ShoppingCartException(101, "no cart attached to this id")
2035 rajveer 117
    inventory_client = InventoryClient().get_client()
118
    if not inventory_client.isActive(item_id):
119
        return inventory_client.getItemStatusDescription(item_id)
557 chandransh 120
 
643 chandransh 121
    current_time = datetime.datetime.now()
122
    cart.updated_on = current_time
123
    line = get_line(item_id, cart_id, None,True)
124
    if line:
125
        #change the quantity only
126
        line.quantity = quantity
685 chandransh 127
        line.updated_on = current_time
643 chandransh 128
    else:
129
        line = Line()
130
        line.cart = cart
131
        line.item_id = item_id
132
        line.quantity = quantity
133
        line.created_on = current_time
134
        line.updated_on = current_time
135
        line.line_status = LineStatus.LINE_ACTIVE
557 chandransh 136
    session.commit()
2100 rajveer 137
    return ""
1621 rajveer 138
    #validate_cart(cart_id)
557 chandransh 139
 
140
def delete_item_from_cart(cart_id, item_id):
141
    if not item_id:
142
        raise ShoppingCartException(101, "item_id cannot be null")
685 chandransh 143
    cart = Cart.get_by(id = cart_id)
144
    if not cart:
145
        raise ShoppingCartException(101, "no cart attached to this id")
643 chandransh 146
    item = get_line(item_id, cart_id, None, True)
557 chandransh 147
    item.delete()
685 chandransh 148
    current_time = datetime.datetime.now()
149
    cart.updated_on = current_time
557 chandransh 150
    session.commit()
151
 
152
def change_item_status(cart_id, item_id, status):
153
    if not status:
154
        raise ShoppingCartException(101, "Status cannot be made null")
685 chandransh 155
    line = get_line(item_id, cart_id, None, True)
156
    if line:
157
        line.line_status = status
158
        current_time = datetime.datetime.now()
159
        line.updated_on = current_time
160
        line.cart.updated_on = current_time
557 chandransh 161
        session.commit()
162
    else:
685 chandransh 163
        raise ShoppingCartException(101, "Unable to probe the line you desired")
557 chandransh 164
 
165
def add_address_to_cart(cart_id, address_id):
166
    if not cart_id:
167
        raise ShoppingCartException(101, "cart id cannot be made null")
168
 
169
    if not address_id:
170
        raise ShoppingCartException(101, "address id cannot be made null")
171
 
172
    cart = get_cart_by_id(cart_id)
173
    if not cart:
174
        raise ShoppingCartException(101, "no cart for this id")
576 chandransh 175
 
176
    address = Address.get_by(id=address_id)
177
    if not address:
178
        raise ShoppingCartException(101, "No address for this id")
179
 
557 chandransh 180
    cart.address_id = address_id
685 chandransh 181
    current_time = datetime.datetime.now()
716 rajveer 182
    #cart.updated_on = current_time
557 chandransh 183
    session.commit()
184
 
1976 varun.gupt 185
def apply_coupon_to_cart(cart_id, coupon_code, total_price, discounted_price):
186
    cart = get_cart_by_id(cart_id)
187
    if not cart:
188
        raise ShoppingCartException(101, "no cart attached to this id")
189
    cart.total_price = total_price
190
    cart.discounted_price = discounted_price
191
    cart.coupon_code = coupon_code
192
    session.commit()
193
 
194
def remove_coupon(cart_id):
195
    cart = get_cart_by_id(cart_id)
196
    if not cart:
197
        raise ShoppingCartException(101, "no cart attached to this id")
198
    cart.discounted_price = None
199
    cart.coupon_code = None
200
    session.commit()
201
 
576 chandransh 202
def commit_cart(cart_id):   
690 chandransh 203
    cart = get_cart_by_id(cart_id)   
557 chandransh 204
    #now we have a cart. Need to create a transaction with it
576 chandransh 205
    txn = TTransaction()
206
    txn.shoppingCartid = cart_id
207
    txn.customer_id = cart.user_id
208
    txn.createdOn = to_java_date(datetime.datetime.now())
209
    txn.transactionStatus = TTransactionStatus.INIT
210
    txn.statusDescription = "New Order"
2219 varun.gupt 211
    txn.coupon_code = cart.coupon_code
557 chandransh 212
 
576 chandransh 213
    txn.orders = create_orders(cart)
214
 
215
    transaction_client = TransactionClient().get_client()
216
    txn_id = transaction_client.createTransaction(txn)
217
    session.commit()
218
 
685 chandransh 219
    #new_cart = create_cart(cart.user_id)
220
    #user = User.get_by(id=cart.user_id)
221
    #user.active_cart_id = new_cart.id
222
    #session.commit()
576 chandransh 223
    return txn_id
224
 
225
def create_orders(cart):
557 chandransh 226
    cart_lines = cart.lines
576 chandransh 227
    orders = []
228
 
557 chandransh 229
    for line in cart_lines:
576 chandransh 230
        if line.line_status == LineStatus.LINE_ACTIVE:
231
            i = 0
232
            while i< line.quantity:
1976 varun.gupt 233
                t_line_item = create_line_item(line.item_id, line.discounted_price)
576 chandransh 234
                t_order = create_order(cart.user_id, cart.address_id, t_line_item)
235
                orders.append(t_order)
236
                i += 1
237
    return orders
238
 
239
def create_order(user_id, address_id, t_line_item):
240
    user = User.get_by(id=user_id)
241
    address = Address.get_by(id=address_id)
242
    t_order = TOrder()
557 chandransh 243
 
576 chandransh 244
    t_order.customer_id = user.id
245
    t_order.customer_email = user.email
246
 
910 rajveer 247
    t_order.customer_name = address.name
576 chandransh 248
    t_order.customer_pincode = address.pin
738 chandransh 249
    t_order.customer_address1 = address.line_1
250
    t_order.customer_address2 = address.line_2
669 chandransh 251
    t_order.customer_city = address.city
252
    t_order.customer_state = address.state
576 chandransh 253
    t_order.customer_mobilenumber = address.phone
254
 
255
    t_order.total_amount = t_line_item.total_price
1976 varun.gupt 256
 
576 chandransh 257
    t_order.total_weight = t_line_item.total_weight
258
    t_order.lineitems = [t_line_item]
259
 
690 chandransh 260
    t_order.status = OrderStatus.PAYMENT_PENDING
970 chandransh 261
    t_order.statusDescription = "Payment Pending"
576 chandransh 262
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
263
 
743 rajveer 264
    # this code is moved somewhere else, as now order will be created but we dont want to add awb number etc
265
    '''
576 chandransh 266
    logistics_client = LogisticsClient().get_client()
716 rajveer 267
    logistics_info = logistics_client.getLogisticsInfo(t_order.customer_pincode, t_line_item.item_id)
576 chandransh 268
 
716 rajveer 269
    t_order.logistics_provider_id = logistics_info.providerId
576 chandransh 270
    t_order.airwaybill_no = logistics_info.airway_billno
271
    t_order.tracking_id = t_order.airwaybill_no
716 rajveer 272
    t_order.expected_delivery_time = to_java_date(datetime.datetime.now()) + 60*60*1000*logistics_info.deliveryTime
273
    t_order.warehouse_id = logistics_info.warehouseId
743 rajveer 274
    '''
275
 
576 chandransh 276
    return t_order
277
 
1976 varun.gupt 278
def create_line_item(item_id, discounted_price):
576 chandransh 279
    inventory_client = InventoryClient().get_client()
636 rajveer 280
    item = inventory_client.getItem(item_id)
576 chandransh 281
    t_line_item = TLineItem()
963 chandransh 282
    t_line_item.productGroup = item.productGroup
283
    t_line_item.brand = item.brand
636 rajveer 284
    t_line_item.model_number = item.modelNumber
669 chandransh 285
    if item.color is None or item.color == "NA":
286
        t_line_item.color = ""
287
    else:
917 chandransh 288
        t_line_item.color = item.color
963 chandransh 289
    t_line_item.model_name = item.modelName
636 rajveer 290
    t_line_item.extra_info = item.featureDescription
702 chandransh 291
    t_line_item.item_id = item.id
576 chandransh 292
    t_line_item.quantity = 1
1983 varun.gupt 293
 
294
    if discounted_price is None or discounted_price == 0:
295
        t_line_item.unit_price = item.sellingPrice
296
        t_line_item.total_price = item.sellingPrice
297
    else:
298
        t_line_item.unit_price = discounted_price
299
        t_line_item.total_price = discounted_price
300
 
636 rajveer 301
    t_line_item.unit_weight = item.weight
302
    t_line_item.total_weight = item.weight
576 chandransh 303
    return t_line_item
304
 
305
def validate_cart(cartId):
306
    inventory_client = InventoryClient().get_client()
307
    logistics_client = LogisticsClient().get_client()
1976 varun.gupt 308
    promotion_client = PromotionClient().get_client()
1466 ankur.sing 309
    retval = ""
557 chandransh 310
    # No need to validate duplicate items since there are only two ways
311
    # to add items to a cart and both of them check whether the item being
312
    # added is a duplicate of an already existing item.
563 chandransh 313
    cart = Cart.get_by(id=cartId)
314
    cart_lines = cart.lines
776 rajveer 315
    customer_pincode = None
690 chandransh 316
    current_time = datetime.datetime.now()
576 chandransh 317
    if cart.address_id:
318
        address = Address.get_by(id=cart.address_id)
319
        customer_pincode = address.pin
776 rajveer 320
    if not customer_pincode:
785 rajveer 321
        user = User.get_by(active_cart_id = cartId)
322
        default_address_id = user.default_address_id
776 rajveer 323
        if default_address_id:
324
            address = Address.get_by(id = default_address_id)
325
            customer_pincode = address.pin
326
    if not customer_pincode:
327
        #FIXME should not be hard coded. May be we can pick from config server.
328
        customer_pincode = "110001"
1976 varun.gupt 329
    cart.total_price = 0
563 chandransh 330
    for line in cart_lines:
612 chandransh 331
        old_estimate = line.estimate
636 rajveer 332
        item_id = line.item_id
1976 varun.gupt 333
        item = inventory_client.getItem(item_id)
636 rajveer 334
        if inventory_client.isActive(item_id):
2139 chandransh 335
            line.actual_price = item.sellingPrice 
336
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
776 rajveer 337
            try:
338
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode).deliveryTime
844 chandransh 339
            except LogisticsServiceException:
340
                item_delivery_estimate = -1
341
                #TODO Use the exception clause to set the retval appropriately
342
            except :
343
                item_delivery_estimate = -1
776 rajveer 344
            if old_estimate != item_delivery_estimate:
345
                line.estimate = item_delivery_estimate
346
                cart.updated_on = current_time
1466 ankur.sing 347
                if old_estimate != None:
348
                    retval = "Delivery Estimates updated."
576 chandransh 349
        else:
563 chandransh 350
            line.delete()
1466 ankur.sing 351
            retval = "Some items have been removed from the cart."
716 rajveer 352
    if cart.checked_out_on is not None:
353
        if cart.updated_on > cart.checked_out_on:
844 chandransh 354
            cart.checked_out_on = None
1466 ankur.sing 355
            if retval == "":
356
                retval = "Your cart has been updated after the last checkout."
612 chandransh 357
    session.commit()
1976 varun.gupt 358
 
359
    if cart.coupon_code is not None:
2026 varun.gupt 360
        try:
361
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
362
            for t_line in updated_cart.lines:
1976 varun.gupt 363
            #Find the line in the database which corresponds to this line
2026 varun.gupt 364
                line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
1976 varun.gupt 365
            #Update its discounted price.
2026 varun.gupt 366
                line.discounted_price = t_line.discountedPrice
367
            cart.discounted_price = updated_cart.discountedPrice
368
            session.commit()
369
        except PromotionException as ex:
370
            remove_coupon(cart.id)
371
            retval = ex.message
563 chandransh 372
    return retval
576 chandransh 373
 
557 chandransh 374
def merge_cart(fromCartId, toCartId):
375
    fromCart = Cart.get_by(id=fromCartId)
376
    toCart = Cart.get_by(id=toCartId)
377
 
378
    old_lines = fromCart.lines
379
    new_lines = toCart.lines
380
 
381
    for line in old_lines:
382
        flag = True
383
        for new_line in new_lines:
384
            if line.item_id == new_line.item_id:
385
                flag = False
576 chandransh 386
        if flag:
557 chandransh 387
            toCart.lines.append(line)
388
 
2019 varun.gupt 389
    if toCart.coupon_code is None:
390
        toCart.coupon_code = fromCart.coupon_code
391
 
392
    toCart.updated_on = datetime.datetime.now()
557 chandransh 393
    fromCart.expired_on = datetime.datetime.now()
394
    fromCart.cart_status = CartStatus.INACTIVE
643 chandransh 395
    session.commit()
691 chandransh 396
 
397
def check_out(cartId):
398
    if cartId is None:
399
        raise ShoppingCartException(101, "Cart id not specified")
716 rajveer 400
    cart = Cart.get_by(id = cartId)
691 chandransh 401
    if cart is None:
402
        raise ShoppingCartException(102, "The specified cart couldn't be found")
403
    cart.checked_out_on = datetime.datetime.now()
404
    session.commit()
405
    return True
406
 
407
def reset_cart(cartId, items):
408
    if cartId is None:
409
        raise ShoppingCartException(101, "Cart id not specified")
410
    for item_id, quantity in items.iteritems():
411
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
412
        if line is not None:
413
            line.quantity = line.quantity - quantity
414
            if line.quantity == 0:
415
                line.delete()
717 rajveer 416
    cart = Cart.get_by(id=cartId)
691 chandransh 417
    cart.updated_on = datetime.datetime.now()
1894 vikas 418
    cart.checked_out_on = None
1976 varun.gupt 419
 
420
    # Removing Coupon
421
    cart.total_price = None
422
    cart.discounted_price = None
423
    cart.coupon_code = None
424
 
691 chandransh 425
    session.commit()
766 rajveer 426
    return True
427
 
428
def close_session():
429
    if session.is_active:
430
        print "session is active. closing it."
1621 rajveer 431
        session.close()