Subversion Repositories SmartDukaan

Rev

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