Subversion Repositories SmartDukaan

Rev

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