Subversion Repositories SmartDukaan

Rev

Rev 6152 | Rev 6903 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
410 rajveer 1
package in.shop2020.serving.controllers;
2
 
2263 vikas 3
import in.shop2020.datalogger.EventType;
5945 mandeep.dh 4
import in.shop2020.model.v1.catalog.CatalogService.Client;
1981 varun.gupt 5
import in.shop2020.model.v1.catalog.Item;
6
import in.shop2020.model.v1.user.Cart;
7
import in.shop2020.model.v1.user.Line;
555 chandransh 8
import in.shop2020.model.v1.user.ShoppingCartException;
572 chandransh 9
import in.shop2020.model.v1.user.UserContextService;
3599 rajveer 10
import in.shop2020.serving.services.ContentServingService;
2137 chandransh 11
import in.shop2020.serving.utils.FormattingUtils;
3599 rajveer 12
import in.shop2020.serving.utils.SnippetType;
3126 rajveer 13
import in.shop2020.thrift.clients.CatalogClient;
14
import in.shop2020.thrift.clients.UserClient;
2511 vikas 15
import in.shop2020.utils.DataLogger;
410 rajveer 16
 
2419 vikas 17
import java.util.ArrayList;
18
import java.util.HashMap;
19
import java.util.List;
20
import java.util.Map;
21
import java.util.StringTokenizer;
22
 
6736 amit.gupta 23
import org.apache.commons.lang.StringUtils;
832 rajveer 24
import org.apache.log4j.Logger;
1614 rajveer 25
import org.apache.struts2.convention.annotation.Action;
4046 varun.gupt 26
import org.apache.struts2.convention.annotation.Actions;
1614 rajveer 27
import org.apache.struts2.convention.annotation.InterceptorRef;
801 rajveer 28
import org.apache.struts2.convention.annotation.Result;
1614 rajveer 29
import org.apache.struts2.convention.annotation.Results;
410 rajveer 30
import org.apache.struts2.interceptor.ParameterAware;
31
import org.apache.thrift.TException;
32
 
1614 rajveer 33
 
34
@Results({
4046 varun.gupt 35
    @Result(name = "index", location = "cart-index.vm"),
36
	@Result(name="redirect", type="redirectAction", params = {"actionName" , "cart"}),
1614 rajveer 37
	@Result(name="failure", location="cart-failure.vm"),
38
	@Result(name="success", location="cart-success.vm")
39
})
40
 
507 rajveer 41
public class CartController extends BaseController implements ParameterAware{
410 rajveer 42
 
43
	private static final long serialVersionUID = 1L;
1957 vikas 44
	private static Logger log = Logger.getLogger(Class.class);
507 rajveer 45
	Map<String, String[]> reqparams = null;
4217 varun.gupt 46
 
4046 varun.gupt 47
	private int variationId = 0;
2137 chandransh 48
    private String totalamount;
410 rajveer 49
 
572 chandransh 50
	private String errorMsg = "";
3970 varun.gupt 51
	private String cartMsg = "";
410 rajveer 52
 
1981 varun.gupt 53
	private String pincode = "110001";
54
 
55
	private String couponCode = null;
56
 
2137 chandransh 57
	private String discountedAmount;
1981 varun.gupt 58
 
2810 rajveer 59
	private long itemId;
60
 
410 rajveer 61
	public CartController(){
507 rajveer 62
		super();
63
	}
64
 
65
	 // GET /cart
4046 varun.gupt 66
	@Actions({
67
		@Action(value="cart", interceptorRefs={@InterceptorRef("myDefault")}),
4453 varun.gupt 68
		@Action(value="cart1", interceptorRefs={@InterceptorRef("myDefault")})
4046 varun.gupt 69
	})
4344 anupam.sin 70
	public String index()  {
4046 varun.gupt 71
		this.setVariationId(request.getRequestURI());
72
		log.info(this.getVariationId());
1614 rajveer 73
 
4046 varun.gupt 74
		long cartId = userinfo.getCartId();
75
 
76
	    if(cartId != -1){
77
        	try {
78
    			UserContextService.Client userClient = (new UserClient()).getClient();
6736 amit.gupta 79
    			List<String> cartResponse  = userClient.validateCart(cartId, sourceId);
80
    			errorMsg = cartResponse.get(0);
81
    			if(StringUtils.isNotEmpty(cartResponse.get(1))) {
82
    				addActionMessage(cartResponse.get(1));
83
    			}
84
    			log.info("Cart Change/EMI Message rcvd from the service is:" + errorMsg);
4046 varun.gupt 85
 
86
    			// As per ticket #119 in trac
87
    			Cart cart = userClient.getCart(cartId);
88
    			int totalItems = cart.getLinesSize();
89
    			double totalAmount = cart.getTotalPrice();
90
				userinfo.setTotalItems(totalItems);
91
				userinfo.setTotalAmount(totalAmount);
92
    		} catch (Exception e) {
93
    			// This exception can be ignored for showing the cart. Not so
94
    			// innocent when this occurs at the time of checkout or when the
95
    			// user is proceeding to pay.
96
    		    log.warn("Unable to validate the cart: ", e);
97
    		}
98
	    }
3970 varun.gupt 99
		return "index";
100
	}
4046 varun.gupt 101
 
572 chandransh 102
	// POST /entity
1614 rajveer 103
 
104
	@Action(value="addtocart",interceptorRefs={@InterceptorRef("createuser"),@InterceptorRef("myDefault")})
572 chandransh 105
	public String create() {
106
		log.info("CartController.create");
555 chandransh 107
 
572 chandransh 108
		printParams();
109
 
110
		long userId = userinfo.getUserId();
111
		long cartId = userinfo.getCartId();
112
 
1614 rajveer 113
		log.info("user id is " + userId);
114
		log.info("cart id is " + cartId);
115
 
572 chandransh 116
		log.info("item id is " + this.reqparams.get("productid"));
1614 rajveer 117
 
637 rajveer 118
		String itemIds = "";
572 chandransh 119
		if (this.reqparams.get("productid") != null) {
120
			itemIds = this.reqparams.get("productid")[0];
637 rajveer 121
		}else{
122
			return "failure";
572 chandransh 123
		}
637 rajveer 124
 
572 chandransh 125
		StringTokenizer tokenizer = new StringTokenizer(itemIds, "_");
126
		while (tokenizer.hasMoreTokens()) {
2810 rajveer 127
			itemId = Long.parseLong(tokenizer.nextToken());
572 chandransh 128
 
129
			try {
3126 rajveer 130
				UserClient userServiceClient = new UserClient();
572 chandransh 131
				UserContextService.Client userClient = userServiceClient.getClient();
762 rajveer 132
				if (cartId == 0){
5342 rajveer 133
					cartId = userClient.getUserById(userId).getActiveCartId();
762 rajveer 134
				}
3561 rajveer 135
				// If we add multiple items to cart and get some message from service, 
136
				// first message to be preserved and presented to the user.
2099 rajveer 137
				if(cartMsg.equals("")){
3561 rajveer 138
				    cartMsg = userClient.addItemToCart(cartId, itemId, 1, sourceId);
2036 rajveer 139
			    }else{
3561 rajveer 140
			        userClient.addItemToCart(cartId, itemId, 1, sourceId);
2036 rajveer 141
			    }
762 rajveer 142
				userinfo.setCartId(cartId);
143
				int totalItems = userClient.getCart(cartId).getLinesSize();
144
				userinfo.setTotalItems(totalItems);
572 chandransh 145
			} catch (TException e) {
2944 chandransh 146
			    log.error("Unable to create or add to cart because of: ", e);
572 chandransh 147
			} catch (Exception e) {
2944 chandransh 148
			    log.error("Unable to create or add to cart because of: ", e);
507 rajveer 149
			}
150
 
572 chandransh 151
		}
3185 vikas 152
        DataLogger.logData(EventType.ADD_TO_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 153
                Long.toString(cartId), itemIds);
572 chandransh 154
		return "success";
155
	}		
156
 
1614 rajveer 157
 
4217 varun.gupt 158
	// DELETE /entity
159
	public String destroy()	{
160
		log.info("CartController.destroy");
161
		printParams();
162
		log.info("item id is " + this.request.getParameter("productid"));
163
 
164
		String itemIdString = this.request.getParameter("productid");
165
		itemId = Long.parseLong(itemIdString);
166
 
167
		if(userinfo.getCartId() == -1)	{
168
			log.info("Cart does not exist. Nothing to delete.");
169
		} else	{
170
			if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))	{
171
				updateUserSessionInfo(userinfo.getCartId());
172
				DataLogger.logData(EventType.DELETE_FROM_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 173
                        Long.toString(userinfo.getCartId()), itemIdString);
4217 varun.gupt 174
				return "redirect";
507 rajveer 175
			}
176
		}
4217 varun.gupt 177
		return "redirect";
178
	}
179
 
180
	// DELETE /entity
181
	public String update() {
182
		log.info("CartController.update");
183
		printParams();
184
		log.info("item id is " + this.request.getParameter("productid"));
185
		log.info("item quantity is " + this.request.getParameter("quantity"));
186
		String itemIdString = this.request.getParameter("productid");
187
		String quantityString = this.request.getParameter("quantity");
188
		long itemId = Long.parseLong(itemIdString);
189
		long quantity = Long.parseLong(quantityString);
190
 
191
		if(quantity <= 0)	{
192
			log.info("Not valid item quantity. Unable to change item quantity.");
193
		} else	{
194
			if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity))	{
195
				DataLogger.logData(EventType.UPDATE_CART_QUANTITY, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
196
                        Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
197
				return "redirect";
507 rajveer 198
			}
4217 varun.gupt 199
		}
200
		DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 201
                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
4217 varun.gupt 202
		addActionError("Unable to update the quantity");
203
		return "redirect";
204
	}
3970 varun.gupt 205
 
507 rajveer 206
    public void printParams(){
207
    	for(String param : reqparams.keySet()) {
208
    		log.info("param name is " + param);
209
    		log.info("param first is " + reqparams.get(param)[0]);
210
    	}
211
    	log.info(this.reqparams);
212
    }
213
 
762 rajveer 214
	private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
215
		try {
3126 rajveer 216
			UserClient userContextServiceClient = new UserClient();
762 rajveer 217
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
218
 
3562 rajveer 219
			userClient.addItemToCart(cartId, itemId, quantity, sourceId);
762 rajveer 220
			return true;
221
		} catch (ShoppingCartException e) {
2944 chandransh 222
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 223
		} catch (TException e) {
2944 chandransh 224
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 225
		} catch (Exception e) {
2944 chandransh 226
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 227
		}
228
		return false;
229
	}
230
 
231
	private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
232
		try {
3126 rajveer 233
			UserClient userContextServiceClient = new UserClient();
762 rajveer 234
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
4217 varun.gupt 235
 
762 rajveer 236
			userClient.deleteItemFromCart(cartId, catalogItemId);
4217 varun.gupt 237
			return true;
762 rajveer 238
		} catch (ShoppingCartException e) {
2944 chandransh 239
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 240
		} catch (TException e) {
2944 chandransh 241
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 242
		} catch (Exception e) {
2944 chandransh 243
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 244
		}
245
 
246
		return false;
247
	}
248
 
3830 chandransh 249
	private void updateUserSessionInfo(long cartId) {
3126 rajveer 250
		UserClient userContextServiceClient = null;
762 rajveer 251
		try {
3126 rajveer 252
			userContextServiceClient = new UserClient();
762 rajveer 253
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
3830 chandransh 254
			Cart cart = userClient.getCart(cartId);
255
			userinfo.setTotalItems(cart.getLinesSize());
256
			userinfo.setTotalAmount(cart.getTotalPrice());
762 rajveer 257
		} catch (ShoppingCartException e) {
2944 chandransh 258
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 259
		} catch (TException e) {
2944 chandransh 260
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 261
		} catch (Exception e) {
2944 chandransh 262
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 263
		}
264
	}
1981 varun.gupt 265
 
266
	public List<Map<String,String>> getCartItems() {
267
	    List<Map<String,String>> items = null;
762 rajveer 268
 
3126 rajveer 269
        UserClient userServiceClient = null;
1981 varun.gupt 270
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
3126 rajveer 271
        CatalogClient catalogServiceClient  = null;
5945 mandeep.dh 272
        in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = null;
762 rajveer 273
 
2137 chandransh 274
        FormattingUtils formattingUtils = new FormattingUtils();
275
 
1981 varun.gupt 276
        try    {
3126 rajveer 277
            catalogServiceClient = new CatalogClient();
1981 varun.gupt 278
            catalogClient = catalogServiceClient.getClient();
3126 rajveer 279
            userServiceClient = new UserClient();
1981 varun.gupt 280
            userClient = userServiceClient.getClient();
281
 
282
            pincode = userClient.getDefaultPincode(userinfo.getUserId());
283
            Cart cart = userClient.getCart(userinfo.getCartId());
284
            List<Line> lineItems = cart.getLines();
285
 
286
            if(lineItems.size() != 0)  {
287
                items = new ArrayList<Map<String,String>>();
288
 
289
                for (Line line : lineItems)    {
290
                    Map<String, String> itemdetail = new HashMap<String, String>();
3561 rajveer 291
 
292
                    Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
293
 
1981 varun.gupt 294
                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
295
                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
3830 chandransh 296
                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" );
1981 varun.gupt 297
 
3830 chandransh 298
                    String itemColor = "";
299
                    if(item.getColor() != null && !item.getColor().trim().equals("NA"))
300
                        itemColor = "Color - " + item.getColor();
301
 
1981 varun.gupt 302
                    itemdetail.put("ITEM_NAME", itemName);
3830 chandransh 303
                    itemdetail.put("ITEM_COLOR", itemColor);
1981 varun.gupt 304
                    itemdetail.put("ITEM_ID", line.getItemId() + "");
305
                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
306
                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
2137 chandransh 307
                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
308
                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
309
                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
1981 varun.gupt 310
                    itemdetail.put("SHIPPING_TIME", line.getEstimate() + "");
4217 varun.gupt 311
					itemdetail.put("BEST_DEAL_TEXT", item.getBestDealText());
1981 varun.gupt 312
 
313
                    items.add(itemdetail);
314
                }
315
            }
2137 chandransh 316
 
317
            totalamount = formattingUtils.formatPrice(cart.getTotalPrice());
1981 varun.gupt 318
            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
2137 chandransh 319
            discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
1981 varun.gupt 320
        } catch (Exception e)  {
2944 chandransh 321
            log.error("Unable to get the cart details becasue of: ", e);
1981 varun.gupt 322
        }
323
        return items;
507 rajveer 324
	}
1981 varun.gupt 325
 
3080 rajveer 326
	public long getItemId(){
327
		return this.itemId;
328
	}
329
 
2137 chandransh 330
	public String getTotalAmount() {
1981 varun.gupt 331
	    return totalamount;
332
	}
507 rajveer 333
 
1981 varun.gupt 334
	public String getPinCode() {
335
	    return pincode;
507 rajveer 336
	}
337
 
1981 varun.gupt 338
	public String getCouponCode()  {
339
	    return couponCode;
340
	}
341
 
342
	public String getDiscountedAmount()   {
2137 chandransh 343
	    return discountedAmount;
1981 varun.gupt 344
	}
345
 
346
	public String getErrorMsg()    {
347
	    return errorMsg;
348
	}
349
 
507 rajveer 350
	public long getNumberOfItems(){
351
		return userinfo.getTotalItems();
352
	}
650 rajveer 353
 
2036 rajveer 354
	public String getCartMsg(){
2099 rajveer 355
	    if(cartMsg.equals("")){
356
	        return null;
357
	    }
358
	    return cartMsg;
2036 rajveer 359
	}
360
 
2810 rajveer 361
	public String getSnippets(){
362
    	String snippets = "";
3126 rajveer 363
		CatalogClient csc;
2810 rajveer 364
		try {
3126 rajveer 365
			csc = new CatalogClient();
2810 rajveer 366
			List<Long> similarItems = csc.getClient().getSimilarItemsCatalogIds(0, 4, itemId);
367
			for(Long catalogId: similarItems){
3599 rajveer 368
				snippets = snippets + ContentServingService.getSnippet(SnippetType.WIDGET_SNIPPET, catalogId+"", sourceId);
2810 rajveer 369
			}
370
		} catch (Exception e) {
371
			log.error("Unable to initialise Catalogservice Client");
372
		}	    
373
	    return snippets;
374
    }
375
 
650 rajveer 376
	@Override
377
	public void setParameters(Map<String, String[]> parameters) {
378
		this.reqparams = parameters;	
379
	}
3903 varun.gupt 380
 
381
	@Override
382
	public String getHeaderSnippet() {
383
		String url = request.getQueryString();
384
		if (url == null) {
385
			url = "";
386
		} else {
387
			url = "?" + url;
388
		}
389
		url = request.getRequestURI() + url;
6152 amit.gupta 390
		return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , 0, false);
3903 varun.gupt 391
	}
3970 varun.gupt 392
 
4222 varun.gupt 393
	public boolean isUserLoggedIn()	{
394
		return userinfo.isLoggedIn();
395
	}
396
 
4046 varun.gupt 397
	public void setVariationId(String uri)	{
398
		if (uri.equals("/cart1"))	{
399
			this.variationId = 1;
400
		}
3970 varun.gupt 401
	}
402
 
4046 varun.gupt 403
	public int getVariationId()	{
404
		return this.variationId;
3970 varun.gupt 405
	}
5228 amit.gupta 406
 
407
	public String getActionMessage(){
408
		if(cartMsg.contains("out of stock")){
409
			return "Notify me when this product is in stock.";
410
		}else {
411
			return "Notify me when this product is available.";
412
		}
413
	}
414
 
415
	public String getOfferNote(){
416
		String note = null;
417
		if(cartMsg.contains("out of stock")){
418
			return note;
419
		}
420
		else {
421
			try {
422
	            CatalogClient catalogServiceClient = new CatalogClient();
423
	            Client catalogClient = catalogServiceClient.getClient();
424
	            Item it = catalogClient.getItem(itemId);
425
	            note = it.getBestDealText();
426
			} catch (Exception e)  {
427
				log.error("Unable to get the offertext because of: ", e);
428
			}
429
		}
430
		return note;
431
	}
432
}