Subversion Repositories SmartDukaan

Rev

Rev 5446 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
5432 amar.kumar 1
package in.shop2020.user.handler;
2
 
3
import java.util.ArrayList;
4
import java.util.Date;
5
import java.util.HashSet;
6
import java.util.List;
7
import java.util.Map;
8
import java.util.Set;
9
 
10
import org.apache.commons.logging.Log;
11
import org.apache.commons.logging.LogFactory;
12
import org.apache.thrift.TException;
13
import org.apache.thrift.transport.TTransportException;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.stereotype.Service;
16
import org.springframework.transaction.annotation.Transactional;
17
 
18
import in.shop2020.logistics.DeliveryType;
19
import in.shop2020.logistics.LogisticsInfo;
20
import in.shop2020.logistics.LogisticsService;
21
import in.shop2020.logistics.LogisticsServiceException;
22
import in.shop2020.model.v1.catalog.InventoryService;
23
import in.shop2020.model.v1.catalog.InventoryServiceException;
24
import in.shop2020.model.v1.catalog.Item;
25
import in.shop2020.model.v1.catalog.ItemShippingInfo;
26
import in.shop2020.model.v1.order.LineItem;
27
import in.shop2020.model.v1.order.Order;
28
import in.shop2020.model.v1.order.OrderStatus;
29
import in.shop2020.model.v1.order.Transaction;
30
import in.shop2020.model.v1.order.TransactionService;
31
import in.shop2020.model.v1.order.TransactionServiceException;
32
import in.shop2020.model.v1.order.TransactionStatus;
33
import in.shop2020.model.v1.user.CartStatus;
34
import in.shop2020.model.v1.user.Discount;
35
import in.shop2020.model.v1.user.LineStatus;
36
import in.shop2020.model.v1.user.PromotionException;
37
import in.shop2020.model.v1.user.PromotionService;
38
import in.shop2020.model.v1.user.ShoppingCartException;
39
import in.shop2020.thrift.clients.CatalogClient;
40
import in.shop2020.thrift.clients.LogisticsClient;
41
import in.shop2020.thrift.clients.PromotionClient;
42
import in.shop2020.thrift.clients.TransactionClient;
43
import in.shop2020.user.domain.Address;
44
import in.shop2020.user.domain.Cart;
45
import in.shop2020.user.domain.Line;
46
import in.shop2020.user.persistence.CartMapper;
47
import in.shop2020.user.util.Converter;
48
 
49
@Service
50
public class CartHandler {
51
 
52
	@Autowired
53
	private CartMapper cartMapper;
54
	@Autowired
55
	private AddressHandler addressHandler;
56
	@Autowired
57
	private UserHandler userHandler;
58
 
59
	private static final Log log = LogFactory.getLog(CartHandler.class);
60
 
61
	public Cart createCart() throws TException{
62
		log.info("Creating new cart");
63
		Cart cart = new Cart();
64
		cart.setCart_status(CartStatus.ACTIVE.getValue());
65
		cart.setCreated_on(new Date());
66
		cart.setUpdated_on(new Date());
67
		cartMapper.createCart(cart);
68
		return cart;
69
	}
70
 
71
	public in.shop2020.model.v1.user.Cart getCart(long id) throws TException{
72
		return Converter.toThriftCart(cartMapper.getCart(id));
73
	}
74
 
75
	public in.shop2020.model.v1.user.Cart getCartsForUser(long userId,
76
		CartStatus status) throws ShoppingCartException, TException{
77
		if(userId == 0 || userId == -1) {
78
			log.error("UserId : "+userId+"incorrect to get cart");
79
			throw new ShoppingCartException(101, "user_id is not provided");
80
		}
81
		in.shop2020.model.v1.user.User user = userHandler.getUserById(userId);
82
		return Converter.toThriftCart(cartMapper.getCart(user.getActiveCartId()));
83
	}
84
 
85
	public void changeCartStatus(long cartId, CartStatus status) throws TException{
86
		cartMapper.changeCartStatus(cartId, status.getValue());
87
	}
88
 
89
	public List<in.shop2020.model.v1.user.Cart> getCartsByStatus(
90
		CartStatus status) throws TException{
91
		List<Cart> carts = cartMapper.getCartsByStatus(status.getValue());
92
		if(carts!=null) {
93
			List<in.shop2020.model.v1.user.Cart> tCarts = new ArrayList<in.shop2020.model.v1.user.Cart>();
94
			for(Cart cart : carts) {
95
				tCarts.add(Converter.toThriftCart(cart));
96
			}
97
			return tCarts;
98
		}
99
		log.warn("No carts found for cartStatus : "+status);
100
		return null;
101
	}
102
 
103
	public List<in.shop2020.model.v1.user.Cart> getCartsByTime(long from_time,
104
		long to_time, CartStatus status) throws TException{
105
		List<Cart> carts = cartMapper.getCartsByTime(from_time, to_time, status.getValue());
106
		if(carts!=null) {
107
			List<in.shop2020.model.v1.user.Cart> tCarts = new ArrayList<in.shop2020.model.v1.user.Cart>();
108
			for(Cart cart : carts) {
109
				tCarts.add(Converter.toThriftCart(cart));
110
			}
111
			return tCarts;
112
		}
113
		log.warn("Couldn't get carts in specified time ");
114
		return null;
115
	}
116
 
117
	public void deleteItemFromCart(long cartId, long itemId) 
118
	throws ShoppingCartException, TException{
119
		try {
120
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
121
			if(cart == null) {
122
				log.error("No cart found with Id : "+cartId);
123
				throw new ShoppingCartException(101, "no cart attached to this id");
124
			} else {
125
				Line lineItem = cartMapper.getLine(itemId, cartId, -1);
126
				if(lineItem!=null) {
127
					cartMapper.deleteDiscountForLine(cartId, itemId);
128
					cartMapper.deleteLine(cartId, itemId);
129
					cartMapper.updateCartUpdatedTime(new Date(), cartId);
130
				}
131
			}
132
		} catch(Exception e) {
133
			log.error(e);
134
			throw new TException(e.getMessage(), e);
135
		}
136
	}
137
 
138
	public long getCartsWithCouponCount(String couponCode) throws TException{
139
			return cartMapper.getCartsWithCouponCount(couponCode);
140
	}
141
 
142
	public void changeItemStatus(long cartId, long itemId, LineStatus status) 
143
		throws ShoppingCartException, TException{
144
		try {
145
		 	if(status == null) {
146
				log.error("LineStatus cannot be null for Item : " + itemId + 
147
						"cart : "+cartId);
148
				throw new ShoppingCartException(101, "Status cannot be made null");
149
			}
150
			Line line = cartMapper.getLine(itemId, cartId, -1);
151
			if(line!=null) {
152
				line.setLine_status(status.getValue());
153
				line.setUpdated_on(new Date());
154
				cartMapper.updateLine(line);
155
				cartMapper.updateCartUpdatedTime(new Date(), cartId);
156
			} else {
157
				log.error("Unable to probe the line you desired");
158
				throw new ShoppingCartException(101, "Unable to probe the line you desired");
159
			}
160
		} catch(Exception e) {
161
			log.error(e);
162
			throw new TException(e.getMessage(), e);
163
		}
164
	}
165
 
166
	public void addAddressToCart(long cartId, long addressId) 
167
		throws ShoppingCartException, TException{
168
		try {
169
			if(cartId == 0 ) {
170
				log.error("CartId cannot be 0");
171
				throw new ShoppingCartException(101, "cart id cannot be empty");
172
			}
173
			if(addressId == 0) {
174
				log.error("AddressId cannot be 0");
175
				throw new ShoppingCartException(101, "Address id cannot be empty");
176
			}
177
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
178
			if(cart == null) {
179
				log.error("No cart found for Id : " + cartId);
180
				throw new ShoppingCartException(101, "no cart for this id");
181
			}
182
			in.shop2020.user.domain.Address address = addressHandler.getAddress(addressId);
183
			if(address == null) {
184
				log.error("No address found for Id : " + addressId);
185
				throw new ShoppingCartException(101, "No address for this id");
186
			}
187
			cartMapper.addAddressToCart(cartId, addressId);
188
		} catch(Exception e) {
189
			log.error(e);
190
			throw new TException(e.getMessage(), e);
191
		}
192
	}
193
 
194
	public boolean checkOut(long cartId) throws ShoppingCartException, TException{
195
		try {
196
			if(cartId == 0){
197
			log.error("CartId cannot be 0");
198
			throw new ShoppingCartException(101, "Cart id not specified");
199
			}
200
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
201
			if(cart == null) {
202
				log.error("No cart found for Id : " + cartId);
203
				throw new ShoppingCartException(102, "The specified cart couldn't be found");
204
			}
205
			cartMapper.updateCartUpdatedTime(new Date(), cartId);
206
			return true;
207
		} catch(Exception e) {
208
			log.error(e);
209
			throw new TException(e.getMessage(), e);
210
		}
211
	}
212
 
213
	public void saveDiscounts(List<Discount> discounts) 
214
		throws ShoppingCartException, TException{
215
		try {
216
			if(discounts == null||discounts.size()!=0) {
217
			 	log.error("Discounts cannot be empty");
218
				throw new ShoppingCartException(101, "discounts cannot be null");
219
			}
220
			if(discounts.size()>0) {
221
				in.shop2020.user.domain.Cart cart = cartMapper.getCart(discounts.get(0).getCart_id());
222
				for(Discount tDiscount : discounts) {
223
					in.shop2020.user.domain.Line line = cartMapper.getLine(tDiscount.getItem_id(), cart.getId(), -1);
224
					if(line!=null) {
225
						in.shop2020.user.domain.Discount discount = new in.shop2020.user.domain.Discount();
226
						discount.setLine_cart_id(line.getCart_id());
227
						discount.setLine_item_id(tDiscount.getItem_id());
228
						discount.setDiscount(tDiscount.getDiscount());
229
						discount.setQuantity(tDiscount.getQuantity());
230
						cartMapper.insertDiscount(discount);
231
					}
232
				}
233
			}
234
		} catch(Exception e) {
235
			log.error(e);
236
			throw new TException(e.getMessage(), e);
237
		}
238
	}
239
 
240
	public void applyCouponToCart(long cartId, String couponCode,
241
		double totalPrice, double discountedPrice) throws ShoppingCartException, TException{
242
		try {
243
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
244
			if(cart == null) {
245
				log.error("No cart found for Id : " + cartId);
246
				throw new ShoppingCartException(101, "no cart attached to this id");
247
			}
248
			cart.setTotal_price(totalPrice);
249
			cart.setDiscounted_price(discountedPrice);
250
			cart.setCoupon_code(couponCode);
251
			cartMapper.updateCart(cart);
252
		} catch(Exception e) {
253
			log.error(e);
254
			throw new TException(e.getMessage(), e);
255
		}
256
	}
257
 
258
	public void removeCoupon(long cartId) throws ShoppingCartException, TException{
259
		try {
260
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
261
			if(cart == null) {
262
				log.error("No cart found for Id : " + cartId);
263
				throw new ShoppingCartException(101, "no cart attached to this id");
264
			}
265
			for(in.shop2020.user.domain.Line line : cart.getLines()) {
266
				cartMapper.removeLineDiscount(line.getCart_id(), line.getItem_id());
267
			}
268
 
269
			deleteDiscountsFromCart(cart.getId());
270
		    cart.setDiscounted_price(0);
271
		    cart.setCoupon_code(null);
272
		    cartMapper.updateCart(cart);
273
		} catch(Exception e) {
274
			log.error(e);
275
			throw new TException(e.getMessage(), e);
276
		}
277
 	}
278
 
279
	public String addItemToCart(long cartId, long itemId, long quantity,
280
		long sourceId) throws ShoppingCartException, TException {
281
		try {
282
			if(itemId == 0) {
283
				log.error("ItemId cannot be 0");
284
				throw new ShoppingCartException(101, "item_id cannot be 0");
285
			}
286
			if(quantity == 0) {
287
				log.error("quantity cannot be 0");
288
				throw new ShoppingCartException(101, "quantity cannot be null");
289
			}
290
 
291
			Cart cart = cartMapper.getCart(cartId);
292
			if(cart == null) {
293
				log.error("No cart found for Id : " + cartId);
294
				throw new ShoppingCartException(101, "no cart attached to this id");
295
			}
296
			Item item;
297
			try {
298
				InventoryService.Client catalogClient = new CatalogClient().getClient();
299
				item = catalogClient.getItemForSource(itemId, sourceId);
300
				ItemShippingInfo itemShippingInfo = catalogClient.isActive(itemId);
301
				if(!itemShippingInfo.isIsActive()) {
302
					return catalogClient.getItemStatusDescription(itemId);
303
				}
304
			} catch(InventoryServiceException ex) {
305
				log.error("InventoryServiceException while getting item ");
306
				try {
307
					InventoryService.Client catalogClient = new CatalogClient().getClient();
308
					item = catalogClient.getItemForSource(itemId, sourceId);
309
					ItemShippingInfo itemShippingInfo = catalogClient.isActive(itemId);
310
					if(!itemShippingInfo.isIsActive()) {
311
						return catalogClient.getItemStatusDescription(itemId);
312
					} 
313
				} catch(InventoryServiceException e) {
314
					log.error("InventoryServiceException while getting item ");
315
					throw new TException("InventoryServiceException caught in adding Item to Cart"+e);
316
				}
317
			}
318
 
319
				cartMapper.updateCartUpdatedTime(new Date(), cartId);
320
				Line line = cartMapper.getLine(itemId, cartId, -1);
321
				if(line==null) {
322
					line = new Line();
323
					line.setCart_id(cartId);
324
					line.setItem_id(itemId);
325
					line.setQuantity(quantity);
326
					line.setCreated_on(new Date());
327
					line.setUpdated_on(new Date());
328
					line.setActual_price(item.getSellingPrice());
329
					line.setLine_status(LineStatus.LINE_ACTIVE.getValue());
330
					cartMapper.insertLine(line);
331
				} else {
332
					cartMapper.updateLineQuantity(quantity, cartId, itemId, new Date());
333
				}
334
 
335
			return "";
336
		} catch(Exception e) {
337
			log.error(e);
338
			throw new TException(e.getMessage(), e);
339
		}
340
	}
341
 
342
	public boolean showCODOption(long cartId, long sourceId, String pincode) throws TException {
343
		try {
344
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
345
			boolean codOption = true;
346
			try{
347
				if(cart!=null) {
348
					if(cart.getCoupon_code() != null && cart.getCoupon_code().toLowerCase().equals("saccessory")) {
349
						codOption = false;
350
					} else if(cart.getLines()!=null){
351
						for(Line line : cart.getLines()) {
352
							LogisticsService.Client logisticsClient = new LogisticsClient().getClient();
353
							LogisticsInfo logisticsInfo = logisticsClient.
354
								getLogisticsEstimation(line.getItem_id(), pincode, DeliveryType.PREPAID);
355
							if(!logisticsInfo.isCodAllowed()){
356
								codOption = false;
357
								break;
358
							}
359
						}
360
					}
361
				}
362
			}catch(LogisticsServiceException ex) {
363
				log.error("Error in getting COD option");
364
				codOption = false;
365
			}
366
			return codOption;
367
		} catch(Exception e) {
368
			log.error(e);
369
			throw new TException(e.getMessage(), e);
370
		}
371
	}
372
 
373
	public void deleteDiscountsFromCart(long cartId) throws ShoppingCartException, TException{
374
		try {
375
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
376
			if(cart == null) {
377
				log.error("No cart found for Id : "+cartId);
378
				throw new ShoppingCartException(101, "No cart found for Id : "+cartId);
379
			}
380
			if(cart.getLines()!=null && !cart.getLines().isEmpty()) {
381
				for(in.shop2020.user.domain.Line line : cart.getLines()) {
382
					deleteDiscountsForLine(line.getCart_id(), line.getItem_id());
383
				}
384
			} else {
385
				log.info("No lines found for cart : " + cartId);
386
			}
387
		} catch(Exception e) {
388
			log.error(e);
389
			throw new TException(e.getMessage(), e);
390
		}
391
	}
392
 
393
	private void deleteDiscountsForLine(long cartId, long itemId) throws TException{
394
			cartMapper.deleteDiscountForLine(cartId, itemId);
395
	}
396
 
397
	@Transactional
398
	public boolean resetCart(long cartId, Map<Long, Double> items) throws TException{
399
		try {
400
			Set<Long> itemIds = new HashSet<Long>();
401
			itemIds = items.keySet(); 
402
			for(Long itemId : itemIds) {
403
				in.shop2020.user.domain.Line line = cartMapper.getLine(itemId, cartId, 0);
404
				if(line!=null) {
405
					deleteDiscountsForLine(cartId, itemId);
406
					if((line.getQuantity() - items.get(itemId)) == 0) {
407
						cartMapper.deleteDiscountForLine(line.getCart_id(), line.getItem_id());
408
						cartMapper.deleteLine(line.getCart_id(), line.getItem_id());
409
					} else {
410
						line.setQuantity(line.getQuantity() - items.get(itemId));
411
						line.setDiscounted_price(0);
412
						cartMapper.updateLine(line);
413
					}
414
				}
415
			}
416
 
417
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
418
			cart.setUpdated_on(new Date());
419
			cart.setChecked_out_on(null);
420
			cart.setTotal_price(0);
421
			cart.setDiscounted_price(0);
422
			cart.setCoupon_code(null);
423
			cartMapper.updateCart(cart);
424
			return true;
425
		} catch(Exception e) {
426
			log.error(e);
427
			throw new TException(e.getMessage(), e);
428
		}
429
	}
430
 
431
	@Transactional
432
	public void mergeCart(long fromCartId, long toCartId) throws TException{
433
		try {
434
			in.shop2020.user.domain.Cart fromCart = cartMapper.getCart(fromCartId);
435
			in.shop2020.user.domain.Cart toCart = cartMapper.getCart(toCartId);
436
 
437
			List<in.shop2020.user.domain.Line> fromLines = new ArrayList<in.shop2020.user.domain.Line>();
438
			List<in.shop2020.user.domain.Line> toLines = new ArrayList<in.shop2020.user.domain.Line>();
439
			fromLines = fromCart.getLines();
440
			toLines = toCart.getLines();
441
 
442
			for (Line line : fromLines) {
443
				for(in.shop2020.user.domain.Discount discount : line.getDiscounts()) {
444
					cartMapper.deleteDiscountForLine(discount.getLine_cart_id(), discount.getLine_item_id());
445
				}
446
			}
447
 
448
			for(Line line : fromLines) {
449
				boolean flag = true;
450
				for(Line toLine : toLines) {
451
					if(line.getItem_id() == toLine.getItem_id()) {
452
						flag = false;
453
					}
454
				}
455
				if(flag) {
456
					line.setCart_id(toCartId);
457
					cartMapper.changeCartIdForLine(fromCartId, line.getItem_id(), toCartId);
458
				} else {
459
					cartMapper.deleteDiscountForLine(fromCartId, line.getItem_id());
460
					cartMapper.deleteLine(fromCartId,line.getItem_id());
461
				}
462
			}
463
 
464
			if(toCart.getCoupon_code()==null) {
465
				toCart.setCoupon_code(fromCart.getCoupon_code());
466
			}
467
			toCart.setUpdated_on(new Date());
468
			cartMapper.updateCart(toCart);
469
			cartMapper.deActivateCart(fromCart.getId());
470
		} catch(Exception e) {
471
			log.error(e);
472
			throw new TException(e.getMessage(), e);
473
		}
474
	}
475
 
476
	public String validateCart(long cartId, long sourceId) throws TException, ShoppingCartException {
477
		try {
478
			String retval = "";
479
 
480
		    /* No need to validate duplicate items since there are only two ways
481
		     to add items to a cart and both of them check whether the item being
482
		     added is a duplicate of an already existing item.*/
483
 
484
			Cart cart = cartMapper.getCart(cartId);
485
			List<Line> lines = cart.getLines();
486
			String pincode = null;
487
			Date currentTime = new Date();
488
			if(cart.getAddress_id()!=0) {
489
				Address address = addressHandler.getAddress(cart.getAddress_id());
490
				pincode = address.getPin();
491
			}
492
			if(null == pincode) {
493
				in.shop2020.model.v1.user.User user = userHandler.getUserByCartId(cartId);
494
				long addressId = user.getDefaultAddressId();
495
				pincode = addressHandler.getPincodeForAddress(addressId);
496
			}
497
			if(pincode == null) {
498
				pincode = "110001";
499
			}
500
			cart.setTotal_price(0);
501
			for(Line line : lines) {
502
				int oldEstimate = line.getEstimate();
503
				long itemId = line.getItem_id();
504
				line.setCart_id(cartId);
505
				Item item;
506
				ItemShippingInfo itemShippingInfo;
507
				try {
508
					InventoryService.Client inventoryClient = new CatalogClient().getClient();
509
					item = inventoryClient.getItemForSource(itemId, sourceId);
510
					itemShippingInfo = inventoryClient.isActive(itemId);
511
				} catch(InventoryServiceException invEx) {
512
					log.error("Exception in getting item and itemShippingInfo" +
513
							"inventory Service");
514
					throw new ShoppingCartException(101, invEx.getMessage());
515
				}
516
				if(itemShippingInfo.isIsActive()) {
517
					long itemDeliveryEstimate;
518
					if(itemShippingInfo.isIsRisky() && itemShippingInfo.getQuantity()<line.getQuantity()) {
519
						line.setQuantity(1);
520
						retval = "Try adding a smaller quantity of " + item.getBrand() +
521
								" " + item.getModelNumber() + " (" + item.getColor() + ")";
522
					}
523
					line.setActual_price(item.getSellingPrice());
524
					cart.setTotal_price(cart.getTotal_price() + (line.getActual_price()*line.getQuantity()));
525
					try {
526
						LogisticsService.Client logisticsClient = new LogisticsClient().getClient();
527
						itemDeliveryEstimate = logisticsClient.getLogisticsEstimation(itemId, pincode, DeliveryType.PREPAID).getDeliveryTime();
528
					} catch(LogisticsServiceException ex) {
529
						log.error("Exception while delivery estimates for item:" +
530
								""+itemId+" & pincode:"+pincode +"\n"+ex);
531
						itemDeliveryEstimate = -1;
532
					} catch(Exception e) {
533
						log.error("Exception while delivery estimates for item:" +
534
								""+itemId+" & pincode:"+pincode +"\n"+e);
535
		                itemDeliveryEstimate = -1;
536
					}
537
					if(oldEstimate!=itemDeliveryEstimate) {
538
						line.setEstimate((int)itemDeliveryEstimate);
539
						cart.setUpdated_on(new Date());
540
						if(oldEstimate!=-1||oldEstimate!=0) {
541
							retval = "Delivery Estimates updated.";
542
						}
543
					}
544
				} else {
545
					cartMapper.deleteDiscountForLine(line.getCart_id(), line.getItem_id());
546
					cartMapper.deleteLine(line.getCart_id(), line.getItem_id());
547
					retval = "Some items have been removed from the cart.";
548
				}
549
			}
550
 
551
			if(cart.getChecked_out_on()!=null && cart.getUpdated_on()!=null) {
552
				if(cart.getUpdated_on().getTime()>cart.getChecked_out_on().getTime()) {
553
					cart.setChecked_out_on(null);
554
					if(retval.equals("")) {
555
						retval = "Your cart has been updated after the last checkout.";
556
					}
557
				}
558
			}
559
			cartMapper.updateCart(cart);
560
			for(Line line : lines) {
561
				line.setCart_id(cartId);
562
				cartMapper.updateLine(line);
563
			}
564
			if(cart.getCoupon_code()!=null) {
565
				try {
566
					PromotionService.Client promotionClient = new PromotionClient().getClient();
567
					in.shop2020.model.v1.user.Cart tCart = promotionClient.applyCoupon(cart.getCoupon_code(), cart.getId());
568
					for(in.shop2020.model.v1.user.Line tLine : tCart.getLines()) {
569
						Line line  = cartMapper.getLine(tLine.getItemId(), tCart.getId(), -1);
570
						line.setDiscounted_price(tLine.getDiscountedPrice());
571
					}
572
					cart.setDiscounted_price(tCart.getDiscountedPrice());
573
 
574
					cartMapper.updateCart(cart);
575
					for(Line line : lines) {
576
						cartMapper.updateLine(line);
577
					}
578
				} catch (PromotionException ex) {
579
					log.error("PromotionException while applying coupon "+cart.getCoupon_code()+ex);
580
					removeCoupon(cart.getId());
581
					retval = ex.getMessage();
582
				}
583
			}
584
			return retval;
585
		} catch(Exception e) {
586
			log.error(e);
587
			throw new TException(e.getMessage(), e);
588
		}
589
	}
590
 
591
	public long commitCart(long cartId, String sessionSource,
592
			long sessionStartTime, String firstSource, long firstSourceTime,
593
			long userId) throws  TException, ShoppingCartException {
594
		try {
595
			in.shop2020.user.domain.Cart cart = cartMapper.getCart(cartId);
596
 
597
			Transaction transaction = new Transaction();
598
			transaction.setShoppingCartid(cartId);
599
			transaction.setCustomer_id(userId);
600
			transaction.setCreatedOn(new Date().getTime());
601
			transaction.setTransactionStatus(TransactionStatus.INIT);
602
			transaction.setStatusDescription("New Order");
603
			transaction.setCoupon_code(cart.getCoupon_code());
604
			transaction.setSessionSource(sessionSource);
605
			transaction.setSessionStartTime(sessionStartTime);
606
			transaction.setFirstSource(firstSource);
607
			transaction.setFirstSourceTime(firstSourceTime);
608
			transaction.setOrders(createOrders(cart,userId));
609
			try{
610
				TransactionService.Client transactionClient = new TransactionClient().getClient();
611
				return transactionClient.createTransaction(transaction);
612
			} catch(TransactionServiceException txnEx) {
613
				log.error("TransactionServiceException while creating Transa caction ");
614
				try {
615
					TransactionService.Client transactionClient = new TransactionClient().getClient();
616
					return transactionClient.createTransaction(transaction);
617
				} catch(TransactionServiceException txnE) {
618
					log.error("TransactionServiceException while creating Transa caction ");
619
					throw new ShoppingCartException(101, txnE.getMessage());
620
				}
621
			}
622
		} catch(Exception e) {
623
			log.error(e);
624
			throw new TException(e.getMessage(), e);
625
		}
626
	}
627
 
628
	private List<Order> createOrders(Cart cart, long userId) throws TException {
629
		try {
630
			List<Line> cartLine = cart.getLines();
631
			List<Order> orders = new ArrayList<Order>();
632
			double quantityRemainingForOrder;
633
 
634
			for(Line line : cartLine) {
635
				if(line.getLine_status() == LineStatus.LINE_ACTIVE.getValue()) {
636
					quantityRemainingForOrder = line.getQuantity();
637
					List<in.shop2020.user.domain.Discount> discounts = line.getDiscounts();
638
					if(discounts!=null) {
639
						log.info("Discount not null");
640
						for(in.shop2020.user.domain.Discount discount : discounts) {
641
							log.info(discount.getLine_item_id());
642
							int i = 0;
643
							while(i<discount.getQuantity()) {
644
								LineItem tLineItem = createLineItem(line.getItem_id(), line.getActual_price()-discount.getDiscount());
645
								Order order = createOrder(userId, cart.getAddress_id(), tLineItem);
646
								orders.add(order);
647
								i++;
648
							}
649
							quantityRemainingForOrder = quantityRemainingForOrder - discount.getQuantity();
650
						}
651
					}
652
					int i=0;
653
					while(i<quantityRemainingForOrder) {
654
						LineItem tLineItem = createLineItem(line.getItem_id(), line.getActual_price());
655
		                Order order = createOrder(userId, cart.getAddress_id(), tLineItem);
656
		                orders.add(order);
657
		                i += 1;
658
					}
659
				}
660
			}
661
			return orders;
662
		} catch(Exception e) {
663
			log.error(e);
664
			throw new TException(e.getMessage(), e);
665
		}
666
	}
667
 
668
	private Order createOrder(long userId, long addressId, LineItem tLine) throws TException{
669
		try {
670
			in.shop2020.model.v1.user.User user = userHandler.getUserById(userId);
671
			Address address = addressHandler.getAddress(addressId);
672
			Order order = new Order();
673
			order.setCustomer_id(user.getUserId());
674
			order.setCustomer_email(user.getEmail());
675
			order.setCustomer_name(address.getName());
676
			order.setCustomer_pincode(address.getPin());
677
			order.setCustomer_address1(address.getLine_1());
678
			order.setCustomer_address2(address.getLine_2());
679
			order.setCustomer_city(address.getCity());
680
			order.setCustomer_state(address.getState());
681
			order.setCustomer_mobilenumber(address.getPhone());
682
			order.setTotal_amount(tLine.getTotal_price());
683
			order.setTotal_weight(tLine.getTotal_weight());
684
			List<LineItem> lineItems = new ArrayList<LineItem>();
685
			lineItems.add(tLine);
686
			order.setLineitems(lineItems);
687
			order.setStatus(OrderStatus.PAYMENT_PENDING);
688
			order.setStatusDescription("Payment Pending");
689
			order.setCreated_timestamp(new Date().getTime());
690
		    return order;
691
		} catch(Exception e) {
692
			log.error(e);
693
			throw new TException(e.getMessage(), e);
694
		}
695
	}
696
 
697
	private LineItem createLineItem(long item_id, double finalPrice) throws TException {
698
		double quantity=1;
699
		try {
700
			InventoryService.Client inventoryClient;
701
			Item item = null;
702
			try {
703
				inventoryClient = new CatalogClient().getClient();
704
				item = inventoryClient.getItem(item_id);
705
			} catch (TTransportException e) {
706
				log.warn("Retrying to create Line Item, Failed first time"+e);
707
				try {
708
					inventoryClient = new CatalogClient().getClient();
709
					item = inventoryClient.getItem(item_id);
710
				} catch(TTransportException ex) {
711
					log.error("Error while getting item from inventory");
712
					throw new TException("Exception while creating line item"+ex);
713
				} catch (InventoryServiceException exx) {
714
					log.error("Error while getting item from inventory"+exx);
715
					throw new TException("Exception while creating line item"+exx);
716
				}
717
			} catch(InventoryServiceException invEx) {
718
				log.error("Error while creating line item "+invEx);
719
				throw new TException("Exception while creating line item"+invEx);
720
			}
721
			LineItem tLineItem = new LineItem();
722
			tLineItem.setProductGroup(item.getProductGroup());
723
			tLineItem.setBrand(item.getBrand());
724
			tLineItem.setModel_number(item.getModelNumber());
725
			if(item.getColor()==null || item.getColor().equals("N/A")) {
726
				tLineItem.setColor("");
727
			} else {
728
				tLineItem.setColor(item.getColor());
729
			}
730
			tLineItem.setModel_name(item.getModelName());
731
			tLineItem.setExtra_info(item.getFeatureDescription());
732
			tLineItem.setItem_id(item.getId());
733
			tLineItem.setQuantity(quantity);//TODO Quantity always 1
734
			tLineItem.setUnit_price(finalPrice);
735
			tLineItem.setTotal_price(finalPrice*quantity);
736
			tLineItem.setUnit_weight(item.getWeight());
737
			tLineItem.setTotal_weight(item.getWeight()*quantity);
738
			tLineItem.setDealText(item.getBestDealText());
739
 
740
			if(item.getWarrantyPeriod()!=0) {
741
				Date today = new Date();
742
				Date expiryDate;
743
				int expiryYear = today.getYear() + (int)((today.getMonth() + item.getWarrantyPeriod())/12);
744
				int expiryMonth = (today.getMonth() + item.getWarrantyPeriod()) % 12;
745
				try  {
746
					expiryDate = new Date(expiryYear, expiryMonth, today.getDate(), 23, 59, 59); //Milliseconds
747
				} catch (Exception e) {
748
					try {
749
		                expiryDate = new Date(expiryYear, expiryMonth, (today.getDate() - 1), 23, 59, 59);
750
					} catch (Exception ex) {
751
		                try {
752
		                    expiryDate = new Date(expiryYear, expiryMonth, (today.getDate() - 2), 23, 59, 59);
753
		                } catch (Exception exc) {
754
		                    expiryDate = new Date(expiryYear, expiryMonth, (today.getDate() - 3), 23, 59, 59);
755
		                }
756
					}
757
				}
758
				tLineItem.setWarrantry_expiry_timestamp(expiryDate.getTime());
759
	 		}
760
 
761
		    return tLineItem;
762
		} catch(Exception e) {
763
			log.error(e);
764
			throw new TException(e.getMessage(), e);
765
		}
766
	}
767
}