Subversion Repositories SmartDukaan

Rev

Rev 17811 | Rev 17813 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 17811 Rev 17812
Line 1... Line 1...
1
    '''
1
'''
2
    Created on 10-May-2010
2
Created on 10-May-2010
3
    
3
 
4
    @author: ashish
4
@author: ashish
5
    '''
5
'''
6
    from elixir import *
6
from elixir import *
7
    from shop2020.clients.CatalogClient import CatalogClient
7
from shop2020.clients.CatalogClient import CatalogClient
8
    from shop2020.clients.InventoryClient import InventoryClient
8
from shop2020.clients.InventoryClient import InventoryClient
9
    from shop2020.clients.LogisticsClient import LogisticsClient
9
from shop2020.clients.LogisticsClient import LogisticsClient
10
    from shop2020.clients.PromotionClient import PromotionClient
10
from shop2020.clients.PromotionClient import PromotionClient
11
    from shop2020.clients.TransactionClient import TransactionClient
11
from shop2020.clients.TransactionClient import TransactionClient
12
    from shop2020.model.v1 import user
12
from shop2020.model.v1 import user
13
    from shop2020.model.v1.user.impl.Converters import to_t_cart, to_t_line
13
from shop2020.model.v1.user.impl.Converters import to_t_cart, to_t_line
14
    from shop2020.model.v1.user.impl.Dataservice import Cart, Line, Address, User, \
14
from shop2020.model.v1.user.impl.Dataservice import Cart, Line, Address, User, \
15
        Discount, InsuranceDetails, PrivateDealUser
15
    Discount, InsuranceDetails, PrivateDealUser
16
    from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, \
16
from shop2020.thriftpy.logistics.ttypes import LogisticsServiceException, \
17
        DeliveryType
17
    DeliveryType
18
    from shop2020.thriftpy.model.v1.catalog.ttypes import Item, InsurerType
18
from shop2020.thriftpy.model.v1.catalog.ttypes import Item, InsurerType
19
    from shop2020.thriftpy.model.v1.order.ttypes import Transaction as TTransaction, \
19
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as TTransaction, \
20
        TransactionStatus as TTransactionStatus, Order as TOrder, LineItem as TLineItem, \
20
    TransactionStatus as TTransactionStatus, Order as TOrder, LineItem as TLineItem, \
21
        OrderStatus, OrderSource
21
    OrderStatus, OrderSource
22
    from shop2020.thriftpy.model.v1.user.ttypes import CartStatus, LineStatus, \
22
from shop2020.thriftpy.model.v1.user.ttypes import CartStatus, LineStatus, \
23
        ShoppingCartException, PromotionException, CartPlus
23
    ShoppingCartException, PromotionException, CartPlus
24
    from shop2020.utils.Utils import to_py_date, to_java_date
24
from shop2020.utils.Utils import to_py_date, to_java_date
25
    import datetime
25
import datetime
26
    import json
26
import json
27
    import math
27
import math
28
    import traceback
28
import traceback
29
    
29
 
30
    
30
 
31
    
31
 
32
    
32
 
33
    def get_cart(userId):
33
def get_cart(userId):
34
        user = User.get_by(id=userId)
34
    user = User.get_by(id=userId)
35
        return user.active_cart
35
    return user.active_cart
36
    
36
 
37
    def get_cart_by_id(id):
37
def get_cart_by_id(id):
38
        cart = Cart.get_by(id=id)
38
    cart = Cart.get_by(id=id)
39
        return cart
39
    return cart
40
    
40
 
41
    def create_cart():
41
def create_cart():
42
        cart = Cart()
42
    cart = Cart()
43
        cart.created_on = datetime.datetime.now()
43
    cart.created_on = datetime.datetime.now()
44
        cart.updated_on = datetime.datetime.now()
44
    cart.updated_on = datetime.datetime.now()
45
        cart.cart_status = CartStatus.ACTIVE
45
    cart.cart_status = CartStatus.ACTIVE
46
        return cart
46
    return cart
47
    
47
 
48
    def get_carts_between(start_time, end_time, status):
48
def get_carts_between(start_time, end_time, status):
49
        init_time = to_py_date(start_time)
49
    init_time = to_py_date(start_time)
50
        finish_time = to_py_date(end_time)
50
    finish_time = to_py_date(end_time)
51
        
51
    
52
        query = Cart.query
52
    query = Cart.query
53
        if status:
53
    if status:
54
            query = query.filter(Cart.cart_status==status)
54
        query = query.filter(Cart.cart_status==status)
55
        if init_time:
55
    if init_time:
56
            query = query.filter(Cart.created_on >= init_time)
56
        query = query.filter(Cart.created_on >= init_time)
57
        if finish_time:
57
    if finish_time:
58
            query = query.filter(Cart.created_on <= finish_time)
58
        query = query.filter(Cart.created_on <= finish_time)
59
        
59
    
60
        carts = query.all()
60
    carts = query.all()
61
        return carts
61
    return carts
62
    
62
 
63
    def get_line(item_id, cart_id, status, single):
63
def get_line(item_id, cart_id, status, single):
64
        #get cart first 
64
    #get cart first 
65
        try:
65
    try:
66
            found_cart = Cart.get_by(id=cart_id)
66
        found_cart = Cart.get_by(id=cart_id)
67
        except:
67
    except:
68
            raise ShoppingCartException(101, "cart not found ")
68
        raise ShoppingCartException(101, "cart not found ")
69
        query = Line.query.filter_by(cart = found_cart, item_id = item_id)
69
    query = Line.query.filter_by(cart = found_cart, item_id = item_id)
70
        
70
    
71
        if status:
71
    if status:
72
            query = query.filter_by(line_status = status)
72
        query = query.filter_by(line_status = status)
-
 
73
    else:
-
 
74
        query = query.filter_by(line_status = LineStatus.LINE_ACTIVE)
-
 
75
    try:
-
 
76
        if single:
-
 
77
            return query.one()
73
        else:
78
        else:
74
            query = query.filter_by(line_status = LineStatus.LINE_ACTIVE)
-
 
75
        try:
-
 
76
            if single:
-
 
77
                return query.one()
-
 
78
            else:
-
 
79
                return query.all()
79
            return query.all()
80
        except:
80
    except:
81
            return None
81
        return None
82
    
82
 
83
    def add_item_to_cart(cart_id, item_id, quantity, sourceId):
83
def add_item_to_cart(cart_id, item_id, quantity, sourceId):
84
        if not item_id:
84
    if not item_id:
85
            raise ShoppingCartException(101, "item_id cannot be null")
85
        raise ShoppingCartException(101, "item_id cannot be null")
86
        
86
    
87
        if not quantity:
87
    if not quantity:
88
            raise ShoppingCartException(101, "quantity cannot be null")    
88
        raise ShoppingCartException(101, "quantity cannot be null")    
89
    
89
 
90
        cart = Cart.get_by(id = cart_id)    
90
    cart = Cart.get_by(id = cart_id)    
91
        if not cart:
91
    if not cart:
92
            raise ShoppingCartException(101, "no cart attached to this id" + str(cart_id))
92
        raise ShoppingCartException(101, "no cart attached to this id" + str(cart_id))
93
        retval = ""
93
    retval = ""
94
        catalog_client = CatalogClient().get_client()
94
    catalog_client = CatalogClient().get_client()
95
        item = catalog_client.getItemForSource(item_id, sourceId)
95
    item = catalog_client.getItemForSource(item_id, sourceId)
96
        dataProtectionInsurer = catalog_client.getPrefferedInsurerForItem(item_id,InsurerType._NAMES_TO_VALUES.get("DATA"))
96
    dataProtectionInsurer = catalog_client.getPrefferedInsurerForItem(item_id,InsurerType._NAMES_TO_VALUES.get("DATA"))
97
        item_shipping_info = catalog_client.isActive(item_id)
97
    item_shipping_info = catalog_client.isActive(item_id)
98
        if not item_shipping_info.isActive:
98
    if not item_shipping_info.isActive:
99
            return catalog_client.getItemStatusDescription(item_id)
99
        return catalog_client.getItemStatusDescription(item_id)
100
        
100
    
101
        current_time = datetime.datetime.now()
101
    current_time = datetime.datetime.now()
102
        cart.updated_on = current_time
102
    cart.updated_on = current_time
103
        line = get_line(item_id, cart_id, None,True)
103
    line = get_line(item_id, cart_id, None,True)
104
        if line:
104
    if line:
105
            #change the quantity only
105
        #change the quantity only
106
            line.insuranceAmount = (line.insuranceAmount/line.quantity) * quantity
106
        line.insuranceAmount = (line.insuranceAmount/line.quantity) * quantity
107
            line.quantity = quantity
107
        line.quantity = quantity
108
            line.updated_on = current_time
108
        line.updated_on = current_time
109
            line.dataProtectionAmount = (line.dataProtectionAmount/line.quantity) * quantity
109
        line.dataProtectionAmount = (line.dataProtectionAmount/line.quantity) * quantity
-
 
110
    else:
-
 
111
        line = Line()
-
 
112
        line.cart = cart
-
 
113
        line.item_id = item_id
-
 
114
        line.quantity = quantity
-
 
115
        line.created_on = current_time
-
 
116
        line.updated_on = current_time
-
 
117
        line.actual_price = item.sellingPrice
-
 
118
        line.line_status = LineStatus.LINE_ACTIVE
-
 
119
        line.insurer = 0
-
 
120
        line.insuranceAmount = 0
-
 
121
        #DATA INSURER IS SET UPON ADD TO CART
-
 
122
        line.dataProtectionInsurer = dataProtectionInsurer
-
 
123
    session.commit()
-
 
124
    return retval
-
 
125
 
-
 
126
def delete_item_from_cart(cart_id, item_id):
-
 
127
    if not item_id:
-
 
128
        raise ShoppingCartException(101, "item_id cannot be null")
-
 
129
    cart = Cart.get_by(id = cart_id)
-
 
130
    if not cart:
-
 
131
        raise ShoppingCartException(101, "no cart attached to this id")
-
 
132
    item = get_line(item_id, cart_id, None, True)
-
 
133
    count_deleted_discounts = delete_discounts_for_line(item)
-
 
134
    item.delete()
-
 
135
    current_time = datetime.datetime.now()
-
 
136
    cart.updated_on = current_time
-
 
137
    session.commit()
-
 
138
 
-
 
139
def delete_discounts_for_line(item_line):
-
 
140
    count_deleted = Discount.query.filter_by(line = item_line).delete()
-
 
141
    session.commit()
-
 
142
    return count_deleted
-
 
143
 
-
 
144
def delete_discounts_from_cart(cart_id, cart = None):
-
 
145
    if cart is None:
-
 
146
        if cart_id is None:
-
 
147
            raise ShoppingCartException(101, 'cart_id and cart, both cannot be null')
110
        else:
148
        else:
111
            line = Line()
-
 
112
            line.cart = cart
-
 
113
            line.item_id = item_id
-
 
114
            line.quantity = quantity
-
 
115
            line.created_on = current_time
-
 
116
            line.updated_on = current_time
-
 
117
            line.actual_price = item.sellingPrice
-
 
118
            line.line_status = LineStatus.LINE_ACTIVE
-
 
119
            line.insurer = 0
-
 
120
            line.insuranceAmount = 0
-
 
121
            #DATA INSURER IS SET UPON ADD TO CART
-
 
122
            line.dataProtectionInsurer = dataProtectionInsurer
-
 
123
        session.commit()
-
 
124
        return retval
-
 
125
    
-
 
126
    def delete_item_from_cart(cart_id, item_id):
-
 
127
        if not item_id:
-
 
128
            raise ShoppingCartException(101, "item_id cannot be null")
-
 
129
        cart = Cart.get_by(id = cart_id)
149
            cart = Cart.get_by(id = cart_id)
130
        if not cart:
-
 
131
            raise ShoppingCartException(101, "no cart attached to this id")
-
 
132
        item = get_line(item_id, cart_id, None, True)
-
 
133
        count_deleted_discounts = delete_discounts_for_line(item)
-
 
134
        item.delete()
-
 
135
        current_time = datetime.datetime.now()
-
 
136
        cart.updated_on = current_time
-
 
137
        session.commit()
-
 
138
    
150
    
139
    def delete_discounts_for_line(item_line):
-
 
140
        count_deleted = Discount.query.filter_by(line = item_line).delete()
-
 
141
        session.commit()
-
 
142
        return count_deleted
-
 
143
    
-
 
144
    def delete_discounts_from_cart(cart_id, cart = None):
-
 
145
        if cart is None:
-
 
146
            if cart_id is None:
-
 
147
                raise ShoppingCartException(101, 'cart_id and cart, both cannot be null')
-
 
148
            else:
-
 
149
                cart = Cart.get_by(id = cart_id)
-
 
150
        
-
 
151
        if cart.lines:
151
    if cart.lines:
152
            for line in cart.lines:
152
        for line in cart.lines:
153
                delete_discounts_for_line(line)
153
            delete_discounts_for_line(line)
154
    
154
 
155
    def save_discounts(discounts):
155
def save_discounts(discounts):
156
        if not discounts:
156
    if not discounts:
157
            raise ShoppingCartException(101, 'discounts be null')
157
        raise ShoppingCartException(101, 'discounts be null')
158
        
-
 
159
        if len(discounts) > 0:
-
 
160
            cart = Cart.get_by(id = discounts[0].cart_id)
-
 
161
            
-
 
162
            for t_discount in discounts:
-
 
163
                line = Line.query.filter_by(cart = cart, item_id = t_discount.item_id).first()
-
 
164
                if line is not None:
-
 
165
                    discount = Discount()
-
 
166
                    discount.line = line
-
 
167
                    discount.discount = t_discount.discount
-
 
168
                    discount.quantity = t_discount.quantity
-
 
169
                    session.commit()
-
 
170
                
-
 
171
    def add_address_to_cart(cart_id, address_id):
-
 
172
        if not cart_id:
-
 
173
            raise ShoppingCartException(101, "cart id cannot be made null")
-
 
174
        
-
 
175
        if not address_id:
-
 
176
            raise ShoppingCartException(101, "address id cannot be made null")
-
 
177
        
-
 
178
        cart = get_cart_by_id(cart_id)
-
 
179
        if not cart:
-
 
180
            raise ShoppingCartException(101, "no cart for this id")
-
 
181
        
-
 
182
        address = Address.get_by(id=address_id)
-
 
183
        if not address:
-
 
184
            raise ShoppingCartException(101, "No address for this id")
-
 
185
        
-
 
186
        cart.address_id = address_id
-
 
187
        current_time = datetime.datetime.now()
-
 
188
        #cart.updated_on = current_time
-
 
189
        session.commit()
-
 
190
    
158
    
191
    def add_store_to_cart(cartId, storeId):
-
 
192
        if not cartId:
159
    if len(discounts) > 0:
193
            raise ShoppingCartException(101, "cart id cannot be made null")
-
 
194
        
-
 
195
        cart = get_cart_by_id(cartId)
160
        cart = Cart.get_by(id = discounts[0].cart_id)
196
        if not cart:
-
 
197
            raise ShoppingCartException(101, "no cart for this id")
-
 
198
        
161
        
-
 
162
        for t_discount in discounts:
-
 
163
            line = Line.query.filter_by(cart = cart, item_id = t_discount.item_id).first()
-
 
164
            if line is not None:
-
 
165
                discount = Discount()
-
 
166
                discount.line = line
-
 
167
                discount.discount = t_discount.discount
-
 
168
                discount.quantity = t_discount.quantity
-
 
169
                session.commit()
-
 
170
            
-
 
171
def add_address_to_cart(cart_id, address_id):
-
 
172
    if not cart_id:
-
 
173
        raise ShoppingCartException(101, "cart id cannot be made null")
-
 
174
    
-
 
175
    if not address_id:
-
 
176
        raise ShoppingCartException(101, "address id cannot be made null")
-
 
177
    
-
 
178
    cart = get_cart_by_id(cart_id)
-
 
179
    if not cart:
-
 
180
        raise ShoppingCartException(101, "no cart for this id")
-
 
181
    
-
 
182
    address = Address.get_by(id=address_id)
-
 
183
    if not address:
-
 
184
        raise ShoppingCartException(101, "No address for this id")
-
 
185
    
-
 
186
    cart.address_id = address_id
-
 
187
    current_time = datetime.datetime.now()
-
 
188
    #cart.updated_on = current_time
-
 
189
    session.commit()
-
 
190
 
-
 
191
def add_store_to_cart(cartId, storeId):
-
 
192
    if not cartId:
-
 
193
        raise ShoppingCartException(101, "cart id cannot be made null")
-
 
194
    
-
 
195
    cart = get_cart_by_id(cartId)
-
 
196
    if not cart:
-
 
197
        raise ShoppingCartException(101, "no cart for this id")
-
 
198
    
199
        if storeId:
199
    if storeId:
200
            cart.pickupStoreId = storeId
200
        cart.pickupStoreId = storeId
201
        else:
201
    else:
202
            cart.pickupStoreId = None
202
        cart.pickupStoreId = None
203
            
203
        
-
 
204
    session.commit()
-
 
205
    
-
 
206
def apply_coupon_to_cart(t_cart, coupon_code):
-
 
207
    cart = get_cart_by_id(t_cart.id)
-
 
208
    if not cart:
-
 
209
        raise ShoppingCartException(101, "no cart attached to this id")
-
 
210
    pc = PromotionClient().get_client()
-
 
211
    for t_line in t_cart.lines:
-
 
212
        line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
-
 
213
        line.discounted_price = None
-
 
214
        if not pc.isGiftVoucher(coupon_code):
-
 
215
            line.discounted_price = t_line.discountedPrice
-
 
216
        #line.dealText = t_line.dealText
-
 
217
        #line.freebieId = t_line.freebieId
-
 
218
    
-
 
219
    cart.total_price = t_cart.totalPrice
-
 
220
    cart.discounted_price = t_cart.discountedPrice
-
 
221
    cart.coupon_code = coupon_code
-
 
222
    session.commit()
-
 
223
 
-
 
224
def remove_coupon(cart_id):
-
 
225
    cart = get_cart_by_id(cart_id)
-
 
226
    if not cart:
-
 
227
        raise ShoppingCartException(101, "no cart attached to this id")
-
 
228
    
-
 
229
    #Resetting discounted price of each line in cart to Null
-
 
230
    for line in cart.lines:
-
 
231
        line.discounted_price = None
-
 
232
        line.dealText = None
-
 
233
        line.freebieId = None
-
 
234
    
-
 
235
    delete_discounts_from_cart(cart.id, cart=cart)
-
 
236
    cart.discounted_price = None
-
 
237
    cart.coupon_code = None
204
        session.commit()
238
    session.commit()
-
 
239
    
-
 
240
def commit_cart(cart_id, sessionSource, sessionTime, firstSource, firstSourceTime, userId, schemeId, orderSource):   
-
 
241
    cart = get_cart_by_id(cart_id)   
-
 
242
    #now we have a cart. Need to create a transaction with it
-
 
243
    totalCartVal = 0
-
 
244
    totalshippingCost = 0
-
 
245
    for lineObj in cart.lines:
-
 
246
        totalCartVal += lineObj.actual_price * lineObj.quantity
-
 
247
    txn = TTransaction()
-
 
248
    txn.shoppingCartid = cart_id
-
 
249
    txn.customer_id = userId
-
 
250
    txn.createdOn = to_java_date(datetime.datetime.now())
-
 
251
    txn.transactionStatus = TTransactionStatus.INIT
-
 
252
    txn.statusDescription = "New Order"
-
 
253
    txn.coupon_code = cart.coupon_code
-
 
254
    txn.sessionSource = sessionSource
-
 
255
    txn.sessionStartTime = sessionTime
-
 
256
    txn.firstSource = firstSource
-
 
257
    txn.firstSourceTime = firstSourceTime
-
 
258
    txn.emiSchemeId = schemeId
-
 
259
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
-
 
260
    if privateDealUser is not None:
-
 
261
        if totalCartVal < 500:
-
 
262
            totalshippingCost = 100
-
 
263
        elif totalCartVal >=500 and totalCartVal<1000:
-
 
264
            totalshippingCost = 50
-
 
265
    txn.totalShippingCost = totalshippingCost
-
 
266
        
-
 
267
    txnOrders = create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal)
-
 
268
    shippingCostInOrders = 0
-
 
269
    for order in txnOrders:
-
 
270
        shippingCostInOrders = shippingCostInOrders + order.shippingCost
-
 
271
    
-
 
272
    diff = totalshippingCost - shippingCostInOrders
-
 
273
    if diff > 0:
-
 
274
        txnOrders[0].shippingCost = txnOrders[0].shippingCost + diff
-
 
275
    
-
 
276
    
-
 
277
    txn.orders = txnOrders
-
 
278
    
-
 
279
    transaction_client = TransactionClient().get_client()
-
 
280
    txn_id = transaction_client.createTransaction(txn)
-
 
281
    
-
 
282
    privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
-
 
283
    if privateDealUser is not None and privateDealUser.counter is not None:
-
 
284
        privateDealUser.counter.lastPurchasedOn = datetime.datetime.now()
-
 
285
    session.commit()
-
 
286
    
-
 
287
    return txn_id
-
 
288
 
-
 
289
def create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal):
-
 
290
    cart_lines = cart.lines
-
 
291
    orders = []
-
 
292
    isGv = False
-
 
293
    if cart.coupon_code:
-
 
294
        try:
-
 
295
            pc = PromotionClient().get_client()
-
 
296
            isGv = pc.isGiftVoucher(cart.coupon_code)
-
 
297
        except:
-
 
298
            isGv = False
205
        
299
        
206
    def apply_coupon_to_cart(t_cart, coupon_code):
-
 
207
        cart = get_cart_by_id(t_cart.id)
-
 
208
        if not cart:
-
 
209
            raise ShoppingCartException(101, "no cart attached to this id")
300
    insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
210
        pc = PromotionClient().get_client()
-
 
211
        for t_line in t_cart.lines:
-
 
212
            line = Line.query.filter_by(cart = cart).filter_by(item_id = t_line.itemId).one()
-
 
213
            line.discounted_price = None
-
 
214
            if not pc.isGiftVoucher(coupon_code):
-
 
215
                line.discounted_price = t_line.discountedPrice
-
 
216
            #line.dealText = t_line.dealText
-
 
217
            #line.freebieId = t_line.freebieId
-
 
218
        
-
 
219
        cart.total_price = t_cart.totalPrice
-
 
220
        cart.discounted_price = t_cart.discountedPrice
-
 
221
        cart.coupon_code = coupon_code
-
 
222
        session.commit()
-
 
223
    
301
    
224
    def remove_coupon(cart_id):
-
 
225
        cart = get_cart_by_id(cart_id)
-
 
226
        if not cart:
-
 
227
            raise ShoppingCartException(101, "no cart attached to this id")
-
 
228
        
-
 
229
        #Resetting discounted price of each line in cart to Null
-
 
230
        for line in cart.lines:
302
    for line in cart_lines:
231
            line.discounted_price = None
-
 
232
            line.dealText = None
-
 
233
            line.freebieId = None
-
 
234
        
-
 
235
        delete_discounts_from_cart(cart.id, cart=cart)
303
        if line.line_status == LineStatus.LINE_ACTIVE:
236
        cart.discounted_price = None
-
 
237
        cart.coupon_code = None
-
 
238
        session.commit()
-
 
239
        
-
 
240
    def commit_cart(cart_id, sessionSource, sessionTime, firstSource, firstSourceTime, userId, schemeId, orderSource):   
-
 
241
        cart = get_cart_by_id(cart_id)   
-
 
242
        #now we have a cart. Need to create a transaction with it
-
 
243
        totalCartVal = 0
-
 
244
        totalshippingCost = 0
-
 
245
        for lineObj in cart.lines:
-
 
246
            totalCartVal += lineObj.actual_price * lineObj.quantity
304
            quantity_remaining_for_order = line.quantity
247
        txn = TTransaction()
-
 
248
        txn.shoppingCartid = cart_id
-
 
249
        txn.customer_id = userId
-
 
250
        txn.createdOn = to_java_date(datetime.datetime.now())
-
 
251
        txn.transactionStatus = TTransactionStatus.INIT
-
 
252
        txn.statusDescription = "New Order"
-
 
253
        txn.coupon_code = cart.coupon_code
-
 
254
        txn.sessionSource = sessionSource
-
 
255
        txn.sessionStartTime = sessionTime
-
 
256
        txn.firstSource = firstSource
-
 
257
        txn.firstSourceTime = firstSourceTime
-
 
258
        txn.emiSchemeId = schemeId
-
 
259
        privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
-
 
260
        if privateDealUser is not None:
-
 
261
            if totalCartVal < 500:
-
 
262
                totalshippingCost = 100
-
 
263
            elif totalCartVal >=500 and totalCartVal<1000:
-
 
264
                totalshippingCost = 50
-
 
265
        txn.totalShippingCost = totalshippingCost
-
 
266
            
-
 
267
        txnOrders = create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal)
-
 
268
        shippingCostInOrders = 0
-
 
269
        for order in txnOrders:
-
 
270
            shippingCostInOrders = shippingCostInOrders + order.shippingCost
-
 
271
        
-
 
272
        diff = totalshippingCost - shippingCostInOrders
-
 
273
        if diff > 0:
-
 
274
            txnOrders[0].shippingCost = txnOrders[0].shippingCost + diff
-
 
275
        
305
        
-
 
306
            for discount in line.discounts:
-
 
307
                #i = 0
-
 
308
                #while i < discount.quantity:
-
 
309
                t_line_item = create_line_item(line, line.actual_price if isGv else (line.actual_price - discount.discount), line.quantity)
-
 
310
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, discount.discount if isGv else 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails,line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, totalshippingCost, totalCartVal)
-
 
311
                orders.append(t_order)
-
 
312
                    #i += 1
-
 
313
                quantity_remaining_for_order -= discount.quantity
-
 
314
            
-
 
315
            if quantity_remaining_for_order > 0:
-
 
316
                t_line_item = create_line_item(line, line.actual_price, quantity_remaining_for_order)
-
 
317
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails, line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, totalshippingCost, totalCartVal)
-
 
318
                orders.append(t_order)
-
 
319
            '''
-
 
320
            i = 0
-
 
321
            while i < quantity_remaining_for_order:
-
 
322
                t_line_item = create_line_item(line, line.actual_price)
-
 
323
                t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails, line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId)
-
 
324
                orders.append(t_order)
-
 
325
                i += 1
-
 
326
            '''
-
 
327
    return orders
-
 
328
 
-
 
329
def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails, dataProtectionInsurer, dataProtectionAmount, orderSource, freebieId, totalshippingCost, totalCartVal):
-
 
330
    user = User.get_by(id=userId)
-
 
331
    address = Address.get_by(id=address_id)
-
 
332
    t_order = TOrder()
-
 
333
    
-
 
334
    t_order.customer_id = user.id
-
 
335
    t_order.customer_email = user.email
-
 
336
    
-
 
337
    t_order.customer_name = address.name
-
 
338
    t_order.customer_pincode = address.pin
-
 
339
    t_order.customer_address1 = address.line_1
-
 
340
    t_order.customer_address2 = address.line_2
-
 
341
    t_order.customer_city = address.city
-
 
342
    t_order.customer_state = address.state
-
 
343
    t_order.customer_mobilenumber = address.phone
-
 
344
    
-
 
345
    t_order.total_amount = t_line_item.total_price + insuranceAmount + dataProtectionAmount
-
 
346
    t_order.gvAmount = gvAmount
-
 
347
    
-
 
348
    t_order.total_weight = t_line_item.total_weight
-
 
349
    t_order.lineitems = [t_line_item]
-
 
350
    
-
 
351
    t_order.status = OrderStatus.PAYMENT_PENDING
-
 
352
    t_order.statusDescription = "Payment Pending"
-
 
353
    t_order.created_timestamp = to_java_date(datetime.datetime.now())
-
 
354
    
-
 
355
    t_order.pickupStoreId = pickupStoreId 
-
 
356
    t_order.insuranceAmount = insuranceAmount 
-
 
357
    t_order.insurer = insurer
-
 
358
    if insuranceDetails:
-
 
359
        t_order.dob = insuranceDetails.dob
-
 
360
        t_order.guardianName = insuranceDetails.guardianName
-
 
361
    
-
 
362
    catalog_client = CatalogClient().get_client()
-
 
363
    
-
 
364
    if freebieId is None:
-
 
365
        freebie_item_id = catalog_client.getFreebieForItem(t_line_item.item_id)
-
 
366
        if freebie_item_id:
-
 
367
            t_order.freebieItemId = freebie_item_id
-
 
368
    else:
-
 
369
        freebie_item_id = None if freebieId == 0 else freebieId  
-
 
370
    t_order.source = orderSource
-
 
371
    t_order.dataProtectionInsurer = dataProtectionInsurer
-
 
372
    t_order.dataProtectionAmount = dataProtectionAmount
-
 
373
    t_order.shippingCost = round((t_line_item.total_price*totalshippingCost)/totalCartVal, 0)
-
 
374
    return t_order
-
 
375
        
-
 
376
def create_line_item(line, final_price, quantity=1):
-
 
377
    inventory_client = CatalogClient().get_client()
-
 
378
    item = inventory_client.getItem(line.item_id)
-
 
379
    t_line_item = TLineItem()
-
 
380
    t_line_item.productGroup = item.productGroup
-
 
381
    t_line_item.brand = item.brand
-
 
382
    t_line_item.model_number = item.modelNumber
-
 
383
    if item.color is None or item.color == "NA":
-
 
384
        t_line_item.color = ""
-
 
385
    else:
-
 
386
        t_line_item.color = item.color
-
 
387
    t_line_item.model_name = item.modelName
-
 
388
    t_line_item.extra_info = item.featureDescription
-
 
389
    t_line_item.item_id = item.id
-
 
390
    t_line_item.quantity = quantity
-
 
391
    
-
 
392
    t_line_item.unit_price = final_price
-
 
393
    t_line_item.total_price = final_price * quantity
-
 
394
    
-
 
395
    t_line_item.unit_weight = item.weight
-
 
396
    t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
-
 
397
    if line.dealText is None:
-
 
398
        t_line_item.dealText = item.bestDealText
-
 
399
    elif line.dealText == '':
-
 
400
        t_line_item.dealText = None
-
 
401
    else:
-
 
402
        t_line_item.dealText = line.dealText
-
 
403
        
-
 
404
    if item.warrantyPeriod:
-
 
405
        #Computing Manufacturer Warranty expiry date
-
 
406
        today = datetime.date.today()
-
 
407
        expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
-
 
408
        expiry_month = (today.month + item.warrantyPeriod) % 12
276
        
409
        
277
        txn.orders = txnOrders
-
 
278
        
-
 
279
        transaction_client = TransactionClient().get_client()
-
 
280
        txn_id = transaction_client.createTransaction(txn)
-
 
281
        
-
 
282
        privateDealUser = PrivateDealUser.query.filter(PrivateDealUser.id == userId).filter(PrivateDealUser.isActive==True).first()
-
 
283
        if privateDealUser is not None and privateDealUser.counter is not None:
-
 
284
            privateDealUser.counter.lastPurchasedOn = datetime.datetime.now()
-
 
285
        session.commit()
-
 
286
        
-
 
287
        return txn_id
-
 
288
    
-
 
289
    def create_orders(cart, userId, orderSource, totalshippingCost, totalCartVal):
-
 
290
        cart_lines = cart.lines
-
 
291
        orders = []
-
 
292
        isGv = False
-
 
293
        if cart.coupon_code:
-
 
294
            try:
-
 
295
                pc = PromotionClient().get_client()
-
 
296
                isGv = pc.isGiftVoucher(cart.coupon_code)
-
 
297
            except:
-
 
298
                isGv = False
-
 
299
            
-
 
300
        insuranceDetails = InsuranceDetails.get_by(addressId = cart.address_id)
-
 
301
        
-
 
302
        for line in cart_lines:
-
 
303
            if line.line_status == LineStatus.LINE_ACTIVE:
-
 
304
                quantity_remaining_for_order = line.quantity
-
 
305
            
-
 
306
                for discount in line.discounts:
-
 
307
                    #i = 0
-
 
308
                    #while i < discount.quantity:
-
 
309
                    t_line_item = create_line_item(line, line.actual_price if isGv else (line.actual_price - discount.discount), line.quantity)
-
 
310
                    t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, discount.discount if isGv else 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails,line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, totalshippingCost, totalCartVal)
410
        try:
311
                    orders.append(t_order)
-
 
312
                        #i += 1
-
 
313
                    quantity_remaining_for_order -= discount.quantity
-
 
314
                
-
 
315
                if quantity_remaining_for_order > 0:
-
 
316
                    t_line_item = create_line_item(line, line.actual_price, quantity_remaining_for_order)
-
 
317
                    t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails, line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId, totalshippingCost, totalCartVal)
411
            expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
318
                    orders.append(t_order)
-
 
319
                '''
-
 
320
                i = 0
-
 
321
                while i < quantity_remaining_for_order:
-
 
322
                    t_line_item = create_line_item(line, line.actual_price)
-
 
323
                    t_order = create_order(userId, cart.address_id, t_line_item, cart.pickupStoreId, 0, line.insurer, (line.insuranceAmount/line.quantity), insuranceDetails, line.dataProtectionInsurer,(line.dataProtectionAmount)/line.quantity, orderSource, line.freebieId)
412
        except ValueError:
324
                    orders.append(t_order)
-
 
325
                    i += 1
-
 
326
                '''
-
 
327
        return orders
-
 
328
    
-
 
329
    def create_order(userId, address_id, t_line_item, pickupStoreId, gvAmount, insurer, insuranceAmount, insuranceDetails, dataProtectionInsurer, dataProtectionAmount, orderSource, freebieId, totalshippingCost, totalCartVal):
-
 
330
        user = User.get_by(id=userId)
-
 
331
        address = Address.get_by(id=address_id)
-
 
332
        t_order = TOrder()
-
 
333
        
-
 
334
        t_order.customer_id = user.id
-
 
335
        t_order.customer_email = user.email
-
 
336
        
-
 
337
        t_order.customer_name = address.name
-
 
338
        t_order.customer_pincode = address.pin
-
 
339
        t_order.customer_address1 = address.line_1
-
 
340
        t_order.customer_address2 = address.line_2
-
 
341
        t_order.customer_city = address.city
-
 
342
        t_order.customer_state = address.state
-
 
343
        t_order.customer_mobilenumber = address.phone
-
 
344
        
-
 
345
        t_order.total_amount = t_line_item.total_price + insuranceAmount + dataProtectionAmount
-
 
346
        t_order.gvAmount = gvAmount
-
 
347
        
-
 
348
        t_order.total_weight = t_line_item.total_weight
-
 
349
        t_order.lineitems = [t_line_item]
-
 
350
        
-
 
351
        t_order.status = OrderStatus.PAYMENT_PENDING
-
 
352
        t_order.statusDescription = "Payment Pending"
-
 
353
        t_order.created_timestamp = to_java_date(datetime.datetime.now())
-
 
354
        
-
 
355
        t_order.pickupStoreId = pickupStoreId 
-
 
356
        t_order.insuranceAmount = insuranceAmount 
-
 
357
        t_order.insurer = insurer
-
 
358
        if insuranceDetails:
-
 
359
            t_order.dob = insuranceDetails.dob
-
 
360
            t_order.guardianName = insuranceDetails.guardianName
-
 
361
        
-
 
362
        catalog_client = CatalogClient().get_client()
-
 
363
        
-
 
364
        if freebieId is None:
-
 
365
            freebie_item_id = catalog_client.getFreebieForItem(t_line_item.item_id)
-
 
366
            if freebie_item_id:
-
 
367
                t_order.freebieItemId = freebie_item_id
-
 
368
        else:
-
 
369
            freebie_item_id = None if freebieId == 0 else freebieId  
-
 
370
        t_order.source = orderSource
-
 
371
        t_order.dataProtectionInsurer = dataProtectionInsurer
-
 
372
        t_order.dataProtectionAmount = dataProtectionAmount
-
 
373
        t_order.shippingCost = round((t_line_item.total_price*totalshippingCost)/totalCartVal, 0)
-
 
374
        return t_order
-
 
375
            
-
 
376
    def create_line_item(line, final_price, quantity=1):
-
 
377
        inventory_client = CatalogClient().get_client()
-
 
378
        item = inventory_client.getItem(line.item_id)
-
 
379
        t_line_item = TLineItem()
-
 
380
        t_line_item.productGroup = item.productGroup
-
 
381
        t_line_item.brand = item.brand
-
 
382
        t_line_item.model_number = item.modelNumber
-
 
383
        if item.color is None or item.color == "NA":
-
 
384
            t_line_item.color = ""
-
 
385
        else:
-
 
386
            t_line_item.color = item.color
-
 
387
        t_line_item.model_name = item.modelName
-
 
388
        t_line_item.extra_info = item.featureDescription
-
 
389
        t_line_item.item_id = item.id
-
 
390
        t_line_item.quantity = quantity
-
 
391
        
-
 
392
        t_line_item.unit_price = final_price
-
 
393
        t_line_item.total_price = final_price * quantity
-
 
394
        
-
 
395
        t_line_item.unit_weight = item.weight
-
 
396
        t_line_item.total_weight = item.weight if item.weight is None else item.weight * quantity
-
 
397
        if line.dealText is None:
-
 
398
            t_line_item.dealText = item.bestDealText
-
 
399
        elif line.dealText == '':
-
 
400
            t_line_item.dealText = None
-
 
401
        else:
-
 
402
            t_line_item.dealText = line.dealText
-
 
403
            
-
 
404
        if item.warrantyPeriod:
-
 
405
            #Computing Manufacturer Warranty expiry date
-
 
406
            today = datetime.date.today()
-
 
407
            expiry_year = today.year + int((today.month + item.warrantyPeriod) / 12)
-
 
408
            expiry_month = (today.month + item.warrantyPeriod) % 12
-
 
409
            
-
 
410
            try:
413
            try:
411
                expiry_date = datetime.datetime(expiry_year, expiry_month, today.day, 23, 59, 59, 999999)
414
                expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
412
            except ValueError:
415
            except ValueError:
413
                try:
416
                try:
414
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 1), 23, 59, 59, 999999)
417
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
415
                except ValueError:
418
                except ValueError:
416
                    try:
-
 
417
                        expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 2), 23, 59, 59, 999999)
-
 
418
                    except ValueError:
-
 
419
                        expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
419
                    expiry_date = datetime.date(expiry_year, expiry_month, (today.day - 3), 23, 59, 59, 999999)
420
            
-
 
421
            t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
-
 
422
            
-
 
423
        return t_line_item
-
 
424
        
420
        
425
    def validate_cart(cartId, sourceId, couponCode):
-
 
426
        inventory_client = CatalogClient().get_client()
-
 
427
        logistics_client = LogisticsClient().get_client()
-
 
428
        promotion_client = PromotionClient().get_client()
-
 
429
        retval = ""
-
 
430
        emival = ""
-
 
431
        # No need to validate duplicate items since there are only two ways
421
        t_line_item.warrantry_expiry_timestamp = to_java_date(expiry_date)
432
        # to add items to a cart and both of them check whether the item being
-
 
433
        # added is a duplicate of an already existing item.
-
 
434
        cart = Cart.get_by(id=cartId)
-
 
435
        cart_lines = cart.lines
-
 
436
        customer_pincode = None
-
 
437
        current_time = datetime.datetime.now()
-
 
438
        if cart.pickupStoreId :
-
 
439
            store = logistics_client.getPickupStore(cart.pickupStoreId)
-
 
440
            customer_pincode = store.pin
-
 
441
        if cart.address_id != None and customer_pincode == None:
-
 
442
            address = Address.get_by(id=cart.address_id)
-
 
443
            customer_pincode = address.pin
-
 
444
    
-
 
445
        user = User.get_by(active_cart_id = cartId)
-
 
446
        
422
        
-
 
423
    return t_line_item
-
 
424
    
-
 
425
def validate_cart(cartId, sourceId, couponCode):
-
 
426
    inventory_client = CatalogClient().get_client()
-
 
427
    logistics_client = LogisticsClient().get_client()
-
 
428
    promotion_client = PromotionClient().get_client()
-
 
429
    retval = ""
-
 
430
    emival = ""
-
 
431
    # No need to validate duplicate items since there are only two ways
-
 
432
    # to add items to a cart and both of them check whether the item being
-
 
433
    # added is a duplicate of an already existing item.
-
 
434
    cart = Cart.get_by(id=cartId)
-
 
435
    cart_lines = cart.lines
-
 
436
    customer_pincode = None
-
 
437
    current_time = datetime.datetime.now()
-
 
438
    if cart.pickupStoreId :
-
 
439
        store = logistics_client.getPickupStore(cart.pickupStoreId)
-
 
440
        customer_pincode = store.pin
-
 
441
    if cart.address_id != None and customer_pincode == None:
-
 
442
        address = Address.get_by(id=cart.address_id)
-
 
443
        customer_pincode = address.pin
-
 
444
 
-
 
445
    user = User.get_by(active_cart_id = cartId)
-
 
446
    
447
        dealItems = []
447
    dealItems = []
448
        privateDealUser = PrivateDealUser.get_by(id=user.id)    
448
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
449
        if privateDealUser is not None and privateDealUser.isActive:
449
    if privateDealUser is not None and privateDealUser.isActive:
450
            itemIds = [cartLine.item_id for cartLine in cart.lines]
450
        itemIds = [cartLine.item_id for cartLine in cart.lines]
451
            deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
451
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
452
            dealItems = deals.keys()
452
        dealItems = deals.keys()
453
    
453
 
454
        if not customer_pincode:
454
    if not customer_pincode:
455
            default_address_id = user.default_address_id
455
        default_address_id = user.default_address_id
456
            if default_address_id:
456
        if default_address_id:
457
                address = Address.get_by(id = default_address_id)
457
            address = Address.get_by(id = default_address_id)
458
                customer_pincode = address.pin
458
            customer_pincode = address.pin
459
        if not customer_pincode:
459
    if not customer_pincode:
460
            #FIXME should not be hard coded. May be we can pick from config server.
460
        #FIXME should not be hard coded. May be we can pick from config server.
461
            customer_pincode = "110001"
461
        customer_pincode = "110001"
462
        cart.total_price = 0
462
    cart.total_price = 0
463
        for line in cart_lines:
463
    for line in cart_lines:
464
            old_estimate = line.estimate
464
        old_estimate = line.estimate
465
            item_id = line.item_id
465
        item_id = line.item_id
466
            item = inventory_client.getItemForSource(item_id, sourceId)
466
        item = inventory_client.getItemForSource(item_id, sourceId)
467
            
467
        
468
            item_shipping_info = inventory_client.isActive(item_id) 
468
        item_shipping_info = inventory_client.isActive(item_id) 
469
            if item_shipping_info.isActive:
469
        if item_shipping_info.isActive:
470
                if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
470
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
471
                    line.quantity = 1
471
                line.quantity = 1
472
                    retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
472
                retval = "Try adding a smaller quantity of " + item.brand + " " + item.modelNumber + " (" + item.color + ")"
473
                     
473
                 
474
                if item_id in dealItems:
474
            if item_id in dealItems:
475
                    line.actual_price = deals[item_id].dealPrice
475
                line.actual_price = deals[item_id].dealPrice
476
                    if deals[item_id].dealTextOption==0:
476
                if deals[item_id].dealTextOption==0:
477
                        line.dealText = ''
477
                    line.dealText = ''
478
                    if deals[item_id].dealTextOption==2:
478
                if deals[item_id].dealTextOption==2:
479
                        line.dealText =  deals[item_id].dealText
479
                    line.dealText =  deals[item_id].dealText
480
                        
-
 
481
                    if deals[item_id].dealFreebieOption==0:
-
 
482
                        line.freebieId = 0
-
 
483
                    if deals[item_id].dealFreebieOption==2:
-
 
484
                        line.freebieId =  deals[item_id].dealFreebieItemId
-
 
485
    
-
 
486
                else:
-
 
487
                    line.actual_price = item.sellingPrice 
-
 
488
                    line.dealText = None
-
 
489
                    line.freebieId = None
-
 
490
                cart.total_price = cart.total_price + (line.actual_price * line.quantity)
-
 
491
                try:
-
 
492
                    item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
-
 
493
                except LogisticsServiceException:
-
 
494
                    item_delivery_estimate = -1
-
 
495
                    #TODO Use the exception clause to set the retval appropriately
-
 
496
                except :
-
 
497
                    item_delivery_estimate = -1
-
 
498
                    
480
                    
-
 
481
                if deals[item_id].dealFreebieOption==0:
-
 
482
                    line.freebieId = 0
-
 
483
                if deals[item_id].dealFreebieOption==2:
-
 
484
                    line.freebieId =  deals[item_id].dealFreebieItemId
-
 
485
 
-
 
486
            else:
-
 
487
                line.actual_price = item.sellingPrice 
-
 
488
                line.dealText = None
-
 
489
                line.freebieId = None
-
 
490
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
-
 
491
            try:
-
 
492
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
-
 
493
            except LogisticsServiceException:
-
 
494
                item_delivery_estimate = -1
-
 
495
                #TODO Use the exception clause to set the retval appropriately
-
 
496
            except :
-
 
497
                item_delivery_estimate = -1
-
 
498
                
499
                if item_delivery_estimate !=-1:
499
            if item_delivery_estimate !=-1:
500
                    inv_client = InventoryClient().get_client()
500
                inv_client = InventoryClient().get_client()
501
                    itemAvailability = None
501
                itemAvailability = None
-
 
502
                try:
-
 
503
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
-
 
504
                except:
-
 
505
                    pass
-
 
506
                
-
 
507
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
-
 
508
                if itemAvailability is not None:
-
 
509
                    billingWarehouse = None
502
                    try:
510
                    try:
503
                        itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
511
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
504
                    except:
512
                    except:
505
                        pass
513
                        pass
506
                    
514
                    
507
                    print 'itemAvailability billling Warehouse ', itemAvailability[2]
515
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
508
                    if itemAvailability is not None:
516
                    if billingWarehouse is not None:
509
                        billingWarehouse = None
517
                        estimateVal = None
-
 
518
                        if not logistics_client.isAlive() :
-
 
519
                            logistics_client = LogisticsClient().get_client()
510
                        try:
520
                        try:
-
 
521
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
-
 
522
                            if estimateVal ==-1:
511
                            billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
523
                                item_delivery_estimate =-1
512
                        except:
524
                        except:
513
                            pass
525
                            pass
514
                        
-
 
515
                        print 'billingWarehouse Id Location ', billingWarehouse.stateId
-
 
516
                        if billingWarehouse is not None:
-
 
517
                            estimateVal = None
-
 
518
                            if not logistics_client.isAlive() :
-
 
519
                                logistics_client = LogisticsClient().get_client()
-
 
520
                            try:
-
 
521
                                estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
-
 
522
                                if estimateVal ==-1:
-
 
523
                                    item_delivery_estimate =-1
-
 
524
                            except:
-
 
525
                                pass
-
 
526
                            print 'estimateVal Value ', estimateVal
526
                        print 'estimateVal Value ', estimateVal
527
                if old_estimate != item_delivery_estimate:
527
            if old_estimate != item_delivery_estimate:
528
                    line.estimate = item_delivery_estimate
528
                line.estimate = item_delivery_estimate
529
                    cart.updated_on = current_time
529
                cart.updated_on = current_time
530
            else:
530
        else:
531
                Discount.query.filter(Discount.line==line).delete()
531
            Discount.query.filter(Discount.line==line).delete()
532
                line.delete()
532
            line.delete()
533
        if cart.checked_out_on is not None:
533
    if cart.checked_out_on is not None:
534
            if cart.updated_on > cart.checked_out_on:
534
        if cart.updated_on > cart.checked_out_on:
535
                cart.checked_out_on = None
535
            cart.checked_out_on = None
536
        session.commit()
-
 
537
        
-
 
538
        if cart.coupon_code is not None:
-
 
539
            try:
-
 
540
                updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
-
 
541
                if updated_cart.message is not None:
-
 
542
                    emival = updated_cart.message
-
 
543
            except PromotionException as ex:
-
 
544
                remove_coupon(cart.id)
-
 
545
                #retval = ex.message
-
 
546
        session.commit()
536
    session.commit()
547
        
-
 
548
        cart = Cart.get_by(id=cartId)
-
 
549
        cart_lines = cart.lines
-
 
550
        map_lines = {}
-
 
551
        
-
 
552
        insurerFlag = False
-
 
553
        for line in cart_lines:
-
 
554
            if line.insurer > 0 or line.dataProtectionInsurer > 0:
-
 
555
                line_map = {}
-
 
556
                line_map['insurer'] = line.insurer
-
 
557
                line_map['dpinsurer'] = line.dataProtectionInsurer
-
 
558
                line_map['amount'] = line.discounted_price if line.discounted_price else line.actual_price
-
 
559
                line_map['quantity'] = line.quantity
-
 
560
                insurerFlag = True
-
 
561
                map_lines[line.item_id] = line_map
-
 
562
            
-
 
563
        if insurerFlag:
-
 
564
            map_lines = inventory_client.checkServices(map_lines)
-
 
565
            for line in cart_lines :
-
 
566
                if map_lines.has_key(line.item_id):
-
 
567
                    line_map = map_lines[line.item_id]
-
 
568
                    if line_map['insurer'] > 0:
-
 
569
                        if cart.discounted_price:
-
 
570
                            cart.discounted_price = cart.discounted_price + line_map['insureramount']
-
 
571
                        line.insurer = line_map['insurer']
-
 
572
                        line.insuranceAmount = line_map['insureramount']
-
 
573
                        cart.total_price = cart.total_price + line_map['insureramount']
-
 
574
                    if line_map['dpinsurer'] > 0:
-
 
575
                        if cart.discounted_price:
-
 
576
                            cart.discounted_price = cart.discounted_price + line_map['dpinsureramount']
-
 
577
                        line.dataProtectionInsurer = line_map['dpinsurer']
-
 
578
                        line.dataProtectionAmount = line_map['dpinsureramount']
-
 
579
                        cart.total_price = cart.total_price + line_map['dpinsureramount']
-
 
580
                    line.updated_on = datetime.datetime.now()
-
 
581
            cart.updated_on = datetime.datetime.now()
-
 
582
            session.commit()
-
 
583
        session.close()
-
 
584
        return [retval, emival]
-
 
585
    
-
 
586
    def merge_cart(fromCartId, toCartId):
-
 
587
        fromCart = Cart.get_by(id=fromCartId)
-
 
588
        toCart = Cart.get_by(id=toCartId)
-
 
589
        
-
 
590
        old_lines = fromCart.lines
-
 
591
        new_lines = toCart.lines
-
 
592
        
-
 
593
        for line in old_lines:
-
 
594
            for discount in line.discounts:
-
 
595
                discount.delete()
-
 
596
        session.commit()
-
 
597
        
-
 
598
        for line in old_lines:
-
 
599
            flag = True
-
 
600
            for new_line in new_lines:
-
 
601
                if line.item_id == new_line.item_id:
-
 
602
                    flag = False
-
 
603
            
-
 
604
            if flag:
-
 
605
                line.cart_id = toCartId
-
 
606
            else:
-
 
607
                line.delete()
-
 
608
                
-
 
609
        if toCart.coupon_code is None:
-
 
610
            toCart.coupon_code = fromCart.coupon_code
-
 
611
        
-
 
612
        toCart.updated_on = datetime.datetime.now()
-
 
613
        fromCart.expired_on = datetime.datetime.now()
-
 
614
        fromCart.cart_status = CartStatus.INACTIVE
-
 
615
        session.commit()
-
 
616
    
-
 
617
    def check_out(cartId):
-
 
618
        if cartId is None:
-
 
619
            raise ShoppingCartException(101, "Cart id not specified")
-
 
620
        cart = Cart.get_by(id = cartId)
-
 
621
        if cart is None:
-
 
622
            raise ShoppingCartException(102, "The specified cart couldn't be found")
-
 
623
        cart.checked_out_on = datetime.datetime.now()
-
 
624
        session.commit()
-
 
625
        return True
-
 
626
    
-
 
627
    def reset_cart(cartId, items):
-
 
628
        if cartId is None:
-
 
629
            raise ShoppingCartException(101, "Cart id not specified")
-
 
630
        for item_id, quantity in items.iteritems():
-
 
631
            line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
-
 
632
            if line is not None:
-
 
633
                delete_discounts_for_line(line)
-
 
634
                line.discounted_price = None
-
 
635
                line.quantity = line.quantity - quantity
-
 
636
                if line.quantity == 0:
-
 
637
                    line.delete()
-
 
638
        cart = Cart.get_by(id=cartId)
-
 
639
        cart.updated_on = datetime.datetime.now()
-
 
640
        cart.checked_out_on = None
-
 
641
        
-
 
642
        # Removing Coupon
-
 
643
        cart.total_price = None
-
 
644
        cart.discounted_price = None
-
 
645
        cart.coupon_code = None
-
 
646
        
-
 
647
        session.commit()
-
 
648
        return True
-
 
649
    
-
 
650
    def get_carts_with_coupon_count(coupon_code):
-
 
651
        return Cart.query.filter_by(coupon_code = coupon_code).count()
-
 
652
    
-
 
653
    def show_cod_option(cartId, sourceId, pincode):
-
 
654
        cart = Cart.get_by(id = cartId)
-
 
655
        cod_option = True
-
 
656
        logistics_client = LogisticsClient().get_client()
-
 
657
        if cart:
-
 
658
            if cart.coupon_code:
-
 
659
                promotion_client = PromotionClient().get_client()
-
 
660
                cod_option = promotion_client.isCodApplicable(to_t_cart(cart))
-
 
661
            
-
 
662
            if cod_option and cart.lines:
-
 
663
                for line in cart.lines:
-
 
664
                    logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
-
 
665
                    if not logistics_info.codAllowed:
-
 
666
                        cod_option = False
-
 
667
                        break
-
 
668
                if cart.total_price > 60000:# or cart.total_price <= 250:
-
 
669
                    cod_option = False
-
 
670
        return cod_option
-
 
671
    
-
 
672
    def get_products_added_to_cart(startDate, endDate):
-
 
673
        lines = session.query(Line.item_id).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).all()
-
 
674
        datas = []
-
 
675
        for line in lines:
-
 
676
            datas.append(line[0])
-
 
677
        return datas
-
 
678
    
537
    
679
    def insure_item(itemId, cartId, toInsure, insurerType):
-
 
680
        cart = Cart.get_by(id = cartId)
-
 
681
        line = None
-
 
682
        for cartLine in cart.lines:
538
    if cart.coupon_code is not None:
683
            if(cartLine.item_id == itemId):
-
 
684
                line = cartLine
-
 
685
                break
-
 
686
            
-
 
687
        if not line:
-
 
688
            print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
-
 
689
            return False
-
 
690
        
-
 
691
        try:
539
        try:
-
 
540
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
692
            if toInsure:
541
            if updated_cart.message is not None:
693
                csc = CatalogClient().get_client()
542
                emival = updated_cart.message
-
 
543
        except PromotionException as ex:
694
                item = csc.getItem(itemId)
544
            remove_coupon(cart.id)
-
 
545
            #retval = ex.message
-
 
546
    session.commit()
-
 
547
    
-
 
548
    cart = Cart.get_by(id=cartId)
-
 
549
    cart_lines = cart.lines
-
 
550
    map_lines = {}
-
 
551
    
-
 
552
    insurerFlag = False
-
 
553
    for line in cart_lines:
695
                insurerId = csc.getPrefferedInsurerForItem(itemId,insurerType)
554
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
-
 
555
            line_map = {}
-
 
556
            line_map['insurer'] = line.insurer
-
 
557
            line_map['dpinsurer'] = line.dataProtectionInsurer
696
                insuranceAmount = csc.getInsuranceAmount(itemId, line.discounted_price if line.discounted_price else line.actual_price, insurerId, line.quantity)
558
            line_map['amount'] = line.discounted_price if line.discounted_price else line.actual_price
-
 
559
            line_map['quantity'] = line.quantity
-
 
560
            insurerFlag = True
-
 
561
            map_lines[line.item_id] = line_map
-
 
562
        
-
 
563
    if insurerFlag:
-
 
564
        map_lines = inventory_client.checkServices(map_lines)
-
 
565
        for line in cart_lines :
-
 
566
            if map_lines.has_key(line.item_id):
-
 
567
                line_map = map_lines[line.item_id]
697
                if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
568
                if line_map['insurer'] > 0:
698
                    if cart.discounted_price:
569
                    if cart.discounted_price:
699
                        cart.discounted_price = cart.discounted_price - line.insuranceAmount + insuranceAmount
570
                        cart.discounted_price = cart.discounted_price + line_map['insureramount']
700
                    line.insurer = insurerId
571
                    line.insurer = line_map['insurer']
701
                    line.insuranceAmount = insuranceAmount
572
                    line.insuranceAmount = line_map['insureramount']
-
 
573
                    cart.total_price = cart.total_price + line_map['insureramount']
702
                if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
574
                if line_map['dpinsurer'] > 0:
703
                    if cart.discounted_price:
575
                    if cart.discounted_price:
704
                        cart.discounted_price = cart.discounted_price - line.dataProtectionAmount + insuranceAmount
576
                        cart.discounted_price = cart.discounted_price + line_map['dpinsureramount']
705
                    line.dataProtectionInsurer = insurerId
577
                    line.dataProtectionInsurer = line_map['dpinsurer']
706
                    line.dataProtectionAmount = insuranceAmount
578
                    line.dataProtectionAmount = line_map['dpinsureramount']
707
                cart.total_price = cart.total_price + insuranceAmount
579
                    cart.total_price = cart.total_price + line_map['dpinsureramount']
708
            else:
-
 
709
                if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
580
                line.updated_on = datetime.datetime.now()
710
                    cart.total_price = cart.total_price - line.insuranceAmount
581
        cart.updated_on = datetime.datetime.now()
711
                    if cart.discounted_price:
582
        session.commit()
712
                        cart.discounted_price = cart.discounted_price - line.insuranceAmount
583
    session.close()
713
                    line.insurer = 0
584
    return [retval, emival]
-
 
585
 
714
                    line.insuranceAmount = 0
586
def merge_cart(fromCartId, toCartId):
715
                if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
587
    fromCart = Cart.get_by(id=fromCartId)
716
                    cart.total_price = cart.total_price - line.dataProtectionAmount
588
    toCart = Cart.get_by(id=toCartId)
-
 
589
    
717
                    if cart.discounted_price:
590
    old_lines = fromCart.lines
718
                        cart.discounted_price = cart.discounted_price - line.dataProtectionAmount
-
 
719
                    line.dataProtectionInsurer = 0
591
    new_lines = toCart.lines
-
 
592
    
720
                    line.dataProtectionAmount = 0
593
    for line in old_lines:
721
            line.updated_on = datetime.datetime.now()
594
        for discount in line.discounts:
722
            cart.updated_on = datetime.datetime.now()
595
            discount.delete()
723
            session.commit()
596
    session.commit()
-
 
597
    
-
 
598
    for line in old_lines:
724
        except:
599
        flag = True
725
            print("Error : Unable to insure")
600
        for new_line in new_lines:
726
            print("insurerId : " + str(insurerId) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
601
            if line.item_id == new_line.item_id:
727
            return False
602
                flag = False
728
        
603
        
-
 
604
        if flag:
-
 
605
            line.cart_id = toCartId
729
        return True
606
        else:
-
 
607
            line.delete()
-
 
608
            
-
 
609
    if toCart.coupon_code is None:
-
 
610
        toCart.coupon_code = fromCart.coupon_code
730
    
611
    
-
 
612
    toCart.updated_on = datetime.datetime.now()
-
 
613
    fromCart.expired_on = datetime.datetime.now()
-
 
614
    fromCart.cart_status = CartStatus.INACTIVE
-
 
615
    session.commit()
-
 
616
 
731
    def cancel_insurance(cartId):
617
def check_out(cartId):
732
        try:
618
    if cartId is None:
-
 
619
        raise ShoppingCartException(101, "Cart id not specified")
733
            cart = Cart.get_by(id = cartId)
620
    cart = Cart.get_by(id = cartId)
-
 
621
    if cart is None:
-
 
622
        raise ShoppingCartException(102, "The specified cart couldn't be found")
-
 
623
    cart.checked_out_on = datetime.datetime.now()
-
 
624
    session.commit()
-
 
625
    return True
-
 
626
 
-
 
627
def reset_cart(cartId, items):
-
 
628
    if cartId is None:
-
 
629
        raise ShoppingCartException(101, "Cart id not specified")
-
 
630
    for item_id, quantity in items.iteritems():
-
 
631
        line = Line.query.filter_by(cart_id=cartId, item_id=item_id).one()
734
            for cartLine in cart.lines:
632
        if line is not None:
735
                cart.total_price = cart.total_price - cartLine.insuranceAmount
633
            delete_discounts_for_line(line)
736
                if cart.discounted_price:
634
            line.discounted_price = None
737
                    cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
635
            line.quantity = line.quantity - quantity
738
                cartLine.insurer = 0
636
            if line.quantity == 0:
739
                cartLine.insuranceAmount = 0
637
                line.delete()
740
                cartLine.updated_on = datetime.datetime.now()
638
    cart = Cart.get_by(id=cartId)
741
            cart.updated_on = datetime.datetime.now()
639
    cart.updated_on = datetime.datetime.now()
-
 
640
    cart.checked_out_on = None
-
 
641
    
-
 
642
    # Removing Coupon
-
 
643
    cart.total_price = None
-
 
644
    cart.discounted_price = None
-
 
645
    cart.coupon_code = None
-
 
646
    
742
            session.commit()
647
    session.commit()
743
        except:
648
    return True
-
 
649
 
-
 
650
def get_carts_with_coupon_count(coupon_code):
744
            print("Error : Unable to cancel insurance for cartId :" + str(cartId))
651
    return Cart.query.filter_by(coupon_code = coupon_code).count()
-
 
652
 
-
 
653
def show_cod_option(cartId, sourceId, pincode):
-
 
654
    cart = Cart.get_by(id = cartId)
-
 
655
    cod_option = True
-
 
656
    logistics_client = LogisticsClient().get_client()
-
 
657
    if cart:
745
            return False
658
        if cart.coupon_code:
-
 
659
            promotion_client = PromotionClient().get_client()
-
 
660
            cod_option = promotion_client.isCodApplicable(to_t_cart(cart))
746
        
661
        
747
        return True
662
        if cod_option and cart.lines:
748
    
-
 
749
    def store_insurance_specific_details(addressId, dob, guardianName):
-
 
750
        try:
663
            for line in cart.lines:
751
            insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
664
                logistics_info = logistics_client.getLogisticsEstimation(line.item_id, pincode, DeliveryType.PREPAID)
752
            if insuranceDetails is None :
665
                if not logistics_info.codAllowed:
753
                insuranceDetails = InsuranceDetails()
666
                    cod_option = False
754
            insuranceDetails.addressId = addressId
667
                    break
755
            insuranceDetails.dob = dob
668
            if cart.total_price > 60000:# or cart.total_price <= 250:
756
            insuranceDetails.guardianName = guardianName
669
                cod_option = False
757
            session.commit()
670
    return cod_option
-
 
671
 
-
 
672
def get_products_added_to_cart(startDate, endDate):
-
 
673
    lines = session.query(Line.item_id).filter(Line.created_on > to_py_date(startDate)).filter(Line.created_on < to_py_date(endDate)).all()
758
        except:
674
    datas = []
759
            print("Error : Unable to store insurance details for addressId : " + str(addressId))
675
    for line in lines:
760
            return False
676
        datas.append(line[0])
761
        return True
677
    return datas
762
    
678
 
763
    def is_insurance_detail_present(addressId):
679
def insure_item(itemId, cartId, toInsure, insurerType):
-
 
680
    cart = Cart.get_by(id = cartId)
764
        try:
681
    line = None
-
 
682
    for cartLine in cart.lines:
765
            insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
683
        if(cartLine.item_id == itemId):
766
            if insuranceDetails is None :
684
            line = cartLine
767
                return False
685
            break
768
        except:
686
        
-
 
687
    if not line:
769
            print("Error : Unable to get insurance details for addressId : " + str(addressId))
688
        print("Error : No line found for cartId : " + cartId + " and itemId : " + itemId)
770
            return False
689
        return False
771
        return True
-
 
772
    
690
    
773
    
691
    try:
774
    def add_items_to_cart(cartId, itemQty, couponCode=None):
-
 
775
        try: 
692
        if toInsure:
776
            found_cart = Cart.get_by(id=cartId)
693
            csc = CatalogClient().get_client()
777
            itemQtyMap = {}
694
            item = csc.getItem(itemId)
778
            current_time = datetime.datetime.now()
695
            insurerId = csc.getPrefferedInsurerForItem(itemId,insurerType)
779
            for itemqty in itemQty:
-
 
780
                itemQtyMap[itemqty.itemId] = itemqty.qty 
696
            insuranceAmount = csc.getInsuranceAmount(itemId, line.discounted_price if line.discounted_price else line.actual_price, insurerId, line.quantity)
781
            if found_cart.lines:    
697
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
782
                for line in found_cart.lines:
698
                if cart.discounted_price:
783
                    if itemQtyMap.has_key(line.item_id):
699
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount + insuranceAmount
784
                        line.delete()
700
                line.insurer = insurerId
785
            for itemId,qty in itemQtyMap.iteritems():
701
                line.insuranceAmount = insuranceAmount
786
                #This condition will ensure that cart is only persisted with non-zero quantities.
702
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
787
                if qty==0:
703
                if cart.discounted_price:
788
                    continue
704
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount + insuranceAmount
789
                line = Line()
705
                line.dataProtectionInsurer = insurerId
790
                line.cart = found_cart
706
                line.dataProtectionAmount = insuranceAmount
791
                line.item_id = itemId
707
            cart.total_price = cart.total_price + insuranceAmount
-
 
708
        else:
792
                line.quantity = qty
709
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DEVICE':
793
                line.created_on = current_time
710
                cart.total_price = cart.total_price - line.insuranceAmount
794
                line.updated_on = current_time
711
                if cart.discounted_price:
795
                line.line_status = LineStatus.LINE_ACTIVE
712
                    cart.discounted_price = cart.discounted_price - line.insuranceAmount
796
                line.insurer = 0
713
                line.insurer = 0
797
                line.insuranceAmount = 0
714
                line.insuranceAmount = 0
-
 
715
            if InsurerType._VALUES_TO_NAMES.get(insurerType)=='DATA':
-
 
716
                cart.total_price = cart.total_price - line.dataProtectionAmount
798
            if couponCode:
717
                if cart.discounted_price:
-
 
718
                    cart.discounted_price = cart.discounted_price - line.dataProtectionAmount
-
 
719
                line.dataProtectionInsurer = 0
799
                found_cart.coupon_code = couponCode
720
                line.dataProtectionAmount = 0
-
 
721
        line.updated_on = datetime.datetime.now()
-
 
722
        cart.updated_on = datetime.datetime.now()
-
 
723
        session.commit()
-
 
724
    except:
-
 
725
        print("Error : Unable to insure")
-
 
726
        print("insurerId : " + str(insurerId) + " ItemId : " + str(itemId) + " CartId : " + str(cartId))
800
            else:
727
        return False
-
 
728
    
-
 
729
    return True
-
 
730
 
-
 
731
def cancel_insurance(cartId):
-
 
732
    try:
-
 
733
        cart = Cart.get_by(id = cartId)
-
 
734
        for cartLine in cart.lines:
-
 
735
            cart.total_price = cart.total_price - cartLine.insuranceAmount
801
                found_cart.coupon_code = None
736
            if cart.discounted_price:
-
 
737
                cart.discounted_price = cart.discounted_price - cartLine.insuranceAmount
-
 
738
            cartLine.insurer = 0
-
 
739
            cartLine.insuranceAmount = 0
-
 
740
            cartLine.updated_on = datetime.datetime.now()
-
 
741
        cart.updated_on = datetime.datetime.now()
802
            session.commit()
742
        session.commit()
-
 
743
    except:
-
 
744
        print("Error : Unable to cancel insurance for cartId :" + str(cartId))
803
            return True
745
        return False
-
 
746
    
-
 
747
    return True
-
 
748
 
-
 
749
def store_insurance_specific_details(addressId, dob, guardianName):
-
 
750
    try:
-
 
751
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
-
 
752
        if insuranceDetails is None :
-
 
753
            insuranceDetails = InsuranceDetails()
-
 
754
        insuranceDetails.addressId = addressId
-
 
755
        insuranceDetails.dob = dob
-
 
756
        insuranceDetails.guardianName = guardianName
-
 
757
        session.commit()
804
        except:
758
    except:
-
 
759
        print("Error : Unable to store insurance details for addressId : " + str(addressId))
-
 
760
        return False
-
 
761
    return True
-
 
762
 
-
 
763
def is_insurance_detail_present(addressId):
-
 
764
    try:
-
 
765
        insuranceDetails = InsuranceDetails.get_by(addressId = addressId);
805
            traceback.print_exc()
766
        if insuranceDetails is None :
806
            return False
767
            return False
-
 
768
    except:
-
 
769
        print("Error : Unable to get insurance details for addressId : " + str(addressId))
807
                 
770
        return False
808
        
771
    return True
-
 
772
 
-
 
773
 
809
    def valiate_cart_new(cartId, customer_pincode, sourceId):
774
def add_items_to_cart(cartId, itemQty, couponCode=None):
810
        
775
    try: 
811
        inventory_client = CatalogClient().get_client()
-
 
812
        logistics_client = LogisticsClient().get_client()
-
 
813
        promotion_client = PromotionClient().get_client()
-
 
814
        # No need to validate duplicate items since there are only two ways
-
 
815
        # to add items to a cart and both of them check whether the item being
-
 
816
        # added is a duplicate of an already existing item.
-
 
817
        cart = Cart.get_by(id=cartId)
776
        found_cart = Cart.get_by(id=cartId)
818
        cart_lines = cart.lines
777
        itemQtyMap = {}
819
        current_time = datetime.datetime.now()
778
        current_time = datetime.datetime.now()
820
    
-
 
821
        user = User.get_by(active_cart_id = cartId)
-
 
822
        responseMap = {}
-
 
823
        totalQty = 0
-
 
824
        totalAmount = 0 
-
 
825
        shippingCharges=0
-
 
826
        cartMessages=[]
-
 
827
        cartItems = []
-
 
828
        dealItems = []
-
 
829
        
-
 
830
        responseMap['shippingCharges']= shippingCharges
-
 
831
        responseMap['cartMessages']= cartMessages
-
 
832
        responseMap['cartItems']= cartItems
-
 
833
        responseMap['pincode']= customer_pincode
-
 
834
    
-
 
835
        privateDealUser = PrivateDealUser.get_by(id=user.id)    
-
 
836
        itemIds = [cartLine.item_id for cartLine in cart.lines]
-
 
837
        if privateDealUser is not None and privateDealUser.isActive:
-
 
838
            deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
-
 
839
            dealItems = deals.keys()
-
 
840
    
-
 
841
        cart.total_price = 0
779
        for itemqty in itemQty:
842
        itemsMap = inventory_client.getItems(itemIds)
780
            itemQtyMap[itemqty.itemId] = itemqty.qty 
843
        
-
 
844
        cartMessageChanged = 0
-
 
845
        cartMessageOOS = 0
-
 
846
        cartMessageUndeliverable = 0
-
 
847
        
-
 
848
        for line in cart_lines:
-
 
849
            cartItem={}
-
 
850
            
781
            
-
 
782
        if found_cart.lines:
-
 
783
            for line in found_cart.lines:
-
 
784
                if itemQtyMap.has_key(line.item_id):
-
 
785
                    line.delete()
-
 
786
        for itemId,qty in itemQtyMap.iteritems():
-
 
787
            #This condition will ensure that cart is only persisted with non-zero quantities.
-
 
788
            if qty==0:
-
 
789
                continue
-
 
790
            line = Line()
-
 
791
            line.cart = found_cart
-
 
792
            line.item_id = itemId
-
 
793
            line.quantity = qty
-
 
794
            line.created_on = current_time
-
 
795
            line.updated_on = current_time
-
 
796
            line.line_status = LineStatus.LINE_ACTIVE
-
 
797
            line.insurer = 0
-
 
798
            line.insuranceAmount = 0
-
 
799
        if couponCode:
-
 
800
            found_cart.coupon_code = couponCode
-
 
801
        else:
-
 
802
            found_cart.coupon_code = None
-
 
803
        session.commit()
-
 
804
        return True
-
 
805
    except:
-
 
806
        traceback.print_exc()
-
 
807
        return False
-
 
808
             
-
 
809
    
-
 
810
def valiate_cart_new(cartId, customer_pincode, sourceId):
-
 
811
    
-
 
812
    inventory_client = CatalogClient().get_client()
-
 
813
    logistics_client = LogisticsClient().get_client()
-
 
814
    promotion_client = PromotionClient().get_client()
-
 
815
    # No need to validate duplicate items since there are only two ways
-
 
816
    # to add items to a cart and both of them check whether the item being
-
 
817
    # added is a duplicate of an already existing item.
-
 
818
    cart = Cart.get_by(id=cartId)
-
 
819
    cart_lines = cart.lines
-
 
820
    current_time = datetime.datetime.now()
-
 
821
 
-
 
822
    user = User.get_by(active_cart_id = cartId)
-
 
823
    responseMap = {}
-
 
824
    totalQty = 0
-
 
825
    totalAmount = 0 
-
 
826
    shippingCharges=0
-
 
827
    cartMessages=[]
-
 
828
    cartItems = []
-
 
829
    dealItems = []
-
 
830
    
-
 
831
    responseMap['shippingCharges']= shippingCharges
-
 
832
    responseMap['cartMessages']= cartMessages
-
 
833
    responseMap['cartItems']= cartItems
-
 
834
    responseMap['pincode']= customer_pincode
-
 
835
 
-
 
836
    privateDealUser = PrivateDealUser.get_by(id=user.id)    
-
 
837
    itemIds = [cartLine.item_id for cartLine in cart.lines]
-
 
838
    if privateDealUser is not None and privateDealUser.isActive:
-
 
839
        deals = inventory_client.getAllActivePrivateDeals(itemIds, 0)
-
 
840
        dealItems = deals.keys()
-
 
841
 
-
 
842
    cart.total_price = 0
-
 
843
    itemsMap = inventory_client.getItems(itemIds)
-
 
844
    
-
 
845
    cartMessageChanged = 0
-
 
846
    cartMessageOOS = 0
-
 
847
    cartMessageUndeliverable = 0
-
 
848
    
-
 
849
    for line in cart_lines:
-
 
850
        cartItem={}
-
 
851
        
851
            old_estimate = line.estimate
852
        old_estimate = line.estimate
852
            item_id = line.item_id
853
        item_id = line.item_id
853
            item = itemsMap.get(item_id)
854
        item = itemsMap.get(item_id)
854
            cartItem['itemId']=line.item_id
855
        cartItem['itemId']=line.item_id
855
            cartItem['quantity']=0
856
        cartItem['quantity']=0
856
            cartItem['color'] = item.color
857
        cartItem['color'] = item.color
857
            cartItem['catalogItemId'] = item.catalogItemId
858
        cartItem['catalogItemId'] = item.catalogItemId
858
            
859
        
859
            item_shipping_info = inventory_client.isActive(item_id) 
860
        item_shipping_info = inventory_client.isActive(item_id) 
860
            if item_shipping_info.isActive:
861
        if item_shipping_info.isActive:
861
                if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
862
            if item_shipping_info.isRisky and item_shipping_info.quantity < line.quantity:
862
                    line.quantity = item_shipping_info.quantity
863
                line.quantity = item_shipping_info.quantity
863
                    cartMessageChanged += 1
864
                cartMessageChanged += 1
864
                    cartItemMessages.append({"type":"danger", "messageText":"Only " + str(item_shipping_info.quantity) + " available"})
865
                cartItemMessages.append({"type":"danger", "messageText":"Only " + str(item_shipping_info.quantity) + " available"})
865
                
866
            
866
                cartItem['maxQuantity'] = min(item_shipping_info.quantity, 20)
867
            cartItem['maxQuantity'] = min(item_shipping_info.quantity, 20)
-
 
868
            
-
 
869
            if item_id in dealItems:
-
 
870
                line.actual_price = deals[item_id].dealPrice
-
 
871
                if deals[item_id].dealTextOption==0:
-
 
872
                    line.dealText = ''
-
 
873
                if deals[item_id].dealTextOption==2:
-
 
874
                    line.dealText = deals[item_id].dealText
-
 
875
                    
-
 
876
                if deals[item_id].dealFreebieOption==0:
-
 
877
                    line.freebieId = 0
-
 
878
                if deals[item_id].dealFreebieOption==2:
-
 
879
                    line.freebieId =  deals[item_id].dealFreebieItemId
-
 
880
                cartItem['dealText'] = line.dealText
-
 
881
            else:
-
 
882
                line.actual_price = item.sellingPrice
-
 
883
                if item.bestDealText:
-
 
884
                    cartItem['dealText'] = item.bestDealText
-
 
885
                line.dealText = None
-
 
886
                line.freebieId = None
-
 
887
            cartItem['sellingPrice'] = line.actual_price
-
 
888
            cartItem['quantity'] = line.quantity
-
 
889
            cart.total_price = cart.total_price + (line.actual_price * line.quantity)
-
 
890
            try:
-
 
891
                item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
-
 
892
            except LogisticsServiceException:
-
 
893
                item_delivery_estimate = -1
-
 
894
                #TODO Use the exception clause to set the retval appropriately
-
 
895
            except :
-
 
896
                item_delivery_estimate = -1
867
                
897
                
868
                if item_id in dealItems:
898
            if item_delivery_estimate !=-1:
869
                    line.actual_price = deals[item_id].dealPrice
-
 
870
                    if deals[item_id].dealTextOption==0:
-
 
871
                        line.dealText = ''
-
 
872
                    if deals[item_id].dealTextOption==2:
-
 
873
                        line.dealText = deals[item_id].dealText
-
 
874
                        
-
 
875
                    if deals[item_id].dealFreebieOption==0:
-
 
876
                        line.freebieId = 0
-
 
877
                    if deals[item_id].dealFreebieOption==2:
-
 
878
                        line.freebieId =  deals[item_id].dealFreebieItemId
-
 
879
                    cartItem['dealText'] = line.dealText
899
                inv_client = InventoryClient().get_client()
880
                else:
-
 
881
                    line.actual_price = item.sellingPrice
-
 
882
                    if item.bestDealText:
-
 
883
                        cartItem['dealText'] = item.bestDealText
-
 
884
                    line.dealText = None
900
                itemAvailability = None
885
                    line.freebieId = None
-
 
886
                cartItem['sellingPrice'] = line.actual_price
-
 
887
                cartItem['quantity'] = line.quantity
-
 
888
                cart.total_price = cart.total_price + (line.actual_price * line.quantity)
-
 
889
                try:
901
                try:
890
                    item_delivery_estimate = logistics_client.getLogisticsEstimation(item_id, customer_pincode, DeliveryType.PREPAID).deliveryTime
-
 
891
                except LogisticsServiceException:
-
 
892
                    item_delivery_estimate = -1
-
 
893
                    #TODO Use the exception clause to set the retval appropriately
902
                    itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
894
                except :
903
                except:
895
                    item_delivery_estimate = -1
904
                    pass
896
                    
905
                
897
                if item_delivery_estimate !=-1:
906
                print 'itemAvailability billling Warehouse ', itemAvailability[2]
898
                    inv_client = InventoryClient().get_client()
907
                if itemAvailability is not None:
899
                    itemAvailability = None
908
                    billingWarehouse = None
900
                    try:
909
                    try:
901
                        itemAvailability = inv_client.getItemAvailabilityAtLocation(item_id, 1)
910
                        billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
902
                    except:
911
                    except:
903
                        pass
912
                        pass
904
                    
913
                    
905
                    print 'itemAvailability billling Warehouse ', itemAvailability[2]
914
                    print 'billingWarehouse Id Location ', billingWarehouse.stateId
906
                    if itemAvailability is not None:
915
                    if billingWarehouse is not None:
907
                        billingWarehouse = None
916
                        estimateVal = None
-
 
917
                        if not logistics_client.isAlive() :
-
 
918
                            logistics_client = LogisticsClient().get_client()
908
                        try:
919
                        try:
-
 
920
                            estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
-
 
921
                            if estimateVal ==-1:
909
                            billingWarehouse = inv_client.getWarehouse(itemAvailability[2])
922
                                item_delivery_estimate =-1
910
                        except:
923
                        except:
911
                            pass
924
                            pass
912
                        
-
 
913
                        print 'billingWarehouse Id Location ', billingWarehouse.stateId
-
 
914
                        if billingWarehouse is not None:
-
 
915
                            estimateVal = None
-
 
916
                            if not logistics_client.isAlive() :
-
 
917
                                logistics_client = LogisticsClient().get_client()
-
 
918
                            try:
-
 
919
                                estimateVal = logistics_client.getFirstDeliveryEstimateForWhLocation(customer_pincode, billingWarehouse.stateId)
-
 
920
                                if estimateVal ==-1:
-
 
921
                                    item_delivery_estimate =-1
-
 
922
                            except:
-
 
923
                                pass
-
 
924
                            print 'estimateVal Value ', estimateVal
925
                        print 'estimateVal Value ', estimateVal
925
                cartItem['estimate'] = item_delivery_estimate
926
            cartItem['estimate'] = item_delivery_estimate
926
                if item_delivery_estimate == -1:
927
            if item_delivery_estimate == -1:
927
                    cartItem['quantity'] = 0
-
 
928
                    cartMessageUndeliverable += 1
-
 
929
                    cartItemMessages.append({"type":"danget", "messageText":"Undeliverable"})
-
 
930
                if old_estimate != item_delivery_estimate:
-
 
931
                    line.estimate = item_delivery_estimate
-
 
932
                    cart.updated_on = current_time
-
 
933
            else:
-
 
934
                cartItem['quantity'] = 0
928
                cartItem['quantity'] = 0
-
 
929
                cartMessageUndeliverable += 1
-
 
930
                cartItemMessages.append({"type":"danget", "messageText":"Undeliverable"})
-
 
931
            if old_estimate != item_delivery_estimate:
-
 
932
                line.estimate = item_delivery_estimate
-
 
933
                cart.updated_on = current_time
-
 
934
        else:
-
 
935
            cartItem['quantity'] = 0
935
                cartMessageOOS += 1
936
            cartMessageOOS += 1
936
                cartItemMessages.append({"type":"danger", "messageText":"Out of Stock"})
937
            cartItemMessages.append({"type":"danger", "messageText":"Out of Stock"})
937
                Discount.query.filter(Discount.line==line).delete()
938
            Discount.query.filter(Discount.line==line).delete()
938
                line.delete()
939
            line.delete()
939
            totalQty += cartItem['quantity']
940
        totalQty += cartItem['quantity']
940
            totalAmount += line.actual_price * cartItem['quantity']
941
        totalAmount += line.actual_price * cartItem['quantity']
941
            if cartItemMessages:
942
        if cartItemMessages:
942
                cartItems.insert(0, cartItem)
943
            cartItems.insert(0, cartItem)
943
            else:
944
        else:
944
                cartItems.append(cartItem)
945
            cartItems.append(cartItem)
945
        if cart.checked_out_on is not None:
946
    if cart.checked_out_on is not None:
946
            if cart.updated_on > cart.checked_out_on:
947
        if cart.updated_on > cart.checked_out_on:
947
                cart.checked_out_on = None
948
            cart.checked_out_on = None
-
 
949
    session.commit()
-
 
950
    
-
 
951
    if cart.coupon_code is not None:
-
 
952
        try:
-
 
953
            updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
-
 
954
            if updated_cart.message is not None:
-
 
955
                emival = updated_cart.message
-
 
956
        except PromotionException as ex:
-
 
957
            remove_coupon(cart.id)
-
 
958
            #retval = ex.message
948
        session.commit()
959
    session.commit()
-
 
960
    
-
 
961
    cart = Cart.get_by(id=cartId)
-
 
962
    cart_lines = cart.lines
-
 
963
    insurerFlag = False
-
 
964
    for line in cart_lines:
-
 
965
        if line.insurer > 0 or line.dataProtectionInsurer > 0:
-
 
966
            line.insurer = 0
-
 
967
            line.insuranceAmount = 0 
-
 
968
            line.dataProtectionInsurer = 0
-
 
969
            line.dataProtectionAmount = 0
-
 
970
            insurerFlag = True
949
        
971
        
950
        if cart.coupon_code is not None:
-
 
951
            try:
972
    if insurerFlag:
952
                updated_cart = promotion_client.applyCoupon(cart.coupon_code, cart.id)
-
 
953
                if updated_cart.message is not None:
973
        cart.updated_on = datetime.datetime.now()
954
                    emival = updated_cart.message
-
 
955
            except PromotionException as ex:
-
 
956
                remove_coupon(cart.id)
-
 
957
                #retval = ex.message
-
 
958
        session.commit()
974
        session.commit()
959
        
-
 
960
        cart = Cart.get_by(id=cartId)
-
 
961
        cart_lines = cart.lines
-
 
962
        insurerFlag = False
-
 
963
        for line in cart_lines:
-
 
964
            if line.insurer > 0 or line.dataProtectionInsurer > 0:
-
 
965
                line.insurer = 0
-
 
966
                line.insuranceAmount = 0 
-
 
967
                line.dataProtectionInsurer = 0
-
 
968
                line.dataProtectionAmount = 0
-
 
969
                insurerFlag = True
-
 
970
            
-
 
971
        if insurerFlag:
-
 
972
            cart.updated_on = datetime.datetime.now()
-
 
973
            session.commit()
-
 
974
        session.close()
-
 
975
        responseMap['totalQty']= totalQty
-
 
976
        responseMap['totalAmount']= totalAmount
-
 
977
        if totalAmount < 500:
-
 
978
            shippingCharges = 100
-
 
979
        elif totalAmount < 1000:
-
 
980
            shippingCharges = 50
-
 
981
        responseMap['shippingCharge']=shippingCharges
-
 
982
        responseMap['cartMessageChanged'] = cartMessageChanged
-
 
983
        responseMap['cartMessageOOS'] = cartMessageOOS
-
 
984
        responseMap['cartMessageUndeliverable'] = cartMessageUndeliverable
-
 
985
        return json.dumps(responseMap)
-
 
986
        
-
 
987
        
-
 
988
    def validate_cart_plus(cart_id, source_id, couponCode):
-
 
989
        try:
-
 
990
            cart_messages = validate_cart(cart_id, source_id, couponCode)
-
 
991
            found_cart = Cart.get_by(id=cart_id)
-
 
992
            pincode = "110001"
-
 
993
            default_address_id = User.get_by(active_cart_id = cart_id).default_address_id
-
 
994
            
-
 
995
            default_address = None
-
 
996
            if found_cart.address_id is not None and found_cart.address_id > 0:
-
 
997
                pincode = Address.get_by(id=found_cart.address_id).pin
-
 
998
            elif default_address_id is not None:
-
 
999
                default_address = Address.get_by(id = default_address_id) 
-
 
1000
                pincode = default_address.pin
-
 
1001
            
-
 
1002
            needInuranceInfo = False
-
 
1003
            if default_address_id is not None:
-
 
1004
                for line in found_cart.lines:
-
 
1005
                    if line.insurer > 0:
-
 
1006
                        needInuranceInfo = not is_insurance_detail_present(default_address_id)
-
 
1007
                        break
-
 
1008
            cartPlus = CartPlus()
-
 
1009
            cartPlus.cart = to_t_cart(found_cart)
-
 
1010
            cartPlus.pinCode = pincode
-
 
1011
            cartPlus.validateCartMessages = cart_messages
-
 
1012
            cartPlus.needInsuranceInfo = needInuranceInfo
-
 
1013
            return cartPlus
-
 
1014
        finally:
-
 
1015
            close_session()
-
 
1016
    
-
 
1017
    def close_session():
-
 
1018
        if session.is_active:
-
 
1019
            print "session is active. closing it."
-
 
1020
            session.close()        
-
 
1021
975
    session.close()
-
 
976
    responseMap['totalQty']= totalQty
-
 
977
    responseMap['totalAmount']= totalAmount
-
 
978
    if totalAmount < 500:
-
 
979
        shippingCharges = 100
-
 
980
    elif totalAmount < 1000:
-
 
981
        shippingCharges = 50
-
 
982
    responseMap['shippingCharge']=shippingCharges
-
 
983
    responseMap['cartMessageChanged'] = cartMessageChanged
-
 
984
    responseMap['cartMessageOOS'] = cartMessageOOS
-
 
985
    responseMap['cartMessageUndeliverable'] = cartMessageUndeliverable
-
 
986
    return json.dumps(responseMap)
-
 
987
    
-
 
988
    
-
 
989
def validate_cart_plus(cart_id, source_id, couponCode):
-
 
990
    try:
-
 
991
        cart_messages = validate_cart(cart_id, source_id, couponCode)
-
 
992
        found_cart = Cart.get_by(id=cart_id)
-
 
993
        pincode = "110001"
-
 
994
        default_address_id = User.get_by(active_cart_id = cart_id).default_address_id
-
 
995
        
-
 
996
        default_address = None
-
 
997
        if found_cart.address_id is not None and found_cart.address_id > 0:
-
 
998
            pincode = Address.get_by(id=found_cart.address_id).pin
-
 
999
        elif default_address_id is not None:
-
 
1000
            default_address = Address.get_by(id = default_address_id) 
-
 
1001
            pincode = default_address.pin
-
 
1002
        
-
 
1003
        needInuranceInfo = False
-
 
1004
        if default_address_id is not None:
-
 
1005
            for line in found_cart.lines:
-
 
1006
                if line.insurer > 0:
-
 
1007
                    needInuranceInfo = not is_insurance_detail_present(default_address_id)
-
 
1008
                    break
-
 
1009
        cartPlus = CartPlus()
-
 
1010
        cartPlus.cart = to_t_cart(found_cart)
-
 
1011
        cartPlus.pinCode = pincode
-
 
1012
        cartPlus.validateCartMessages = cart_messages
-
 
1013
        cartPlus.needInsuranceInfo = needInuranceInfo
-
 
1014
        return cartPlus
-
 
1015
    finally:
-
 
1016
        close_session()
-
 
1017
 
-
 
1018
def close_session():
-
 
1019
    if session.is_active:
-
 
1020
        print "session is active. closing it."
-
 
1021
        session.close()        
-
 
1022
1022
1023