Subversion Repositories SmartDukaan

Rev

Rev 3970 | Rev 4217 | 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;
1981 varun.gupt 4
import in.shop2020.model.v1.catalog.Item;
5
import in.shop2020.model.v1.user.Cart;
6
import in.shop2020.model.v1.user.Line;
555 chandransh 7
import in.shop2020.model.v1.user.ShoppingCartException;
572 chandransh 8
import in.shop2020.model.v1.user.UserContextService;
3599 rajveer 9
import in.shop2020.serving.services.ContentServingService;
2137 chandransh 10
import in.shop2020.serving.utils.FormattingUtils;
3599 rajveer 11
import in.shop2020.serving.utils.SnippetType;
3126 rajveer 12
import in.shop2020.thrift.clients.CatalogClient;
13
import in.shop2020.thrift.clients.UserClient;
2511 vikas 14
import in.shop2020.utils.DataLogger;
410 rajveer 15
 
2419 vikas 16
import java.util.ArrayList;
17
import java.util.HashMap;
18
import java.util.List;
19
import java.util.Map;
20
import java.util.StringTokenizer;
21
 
832 rajveer 22
import org.apache.log4j.Logger;
1614 rajveer 23
import org.apache.struts2.convention.annotation.Action;
4046 varun.gupt 24
import org.apache.struts2.convention.annotation.Actions;
1614 rajveer 25
import org.apache.struts2.convention.annotation.InterceptorRef;
801 rajveer 26
import org.apache.struts2.convention.annotation.Result;
1614 rajveer 27
import org.apache.struts2.convention.annotation.Results;
410 rajveer 28
import org.apache.struts2.interceptor.ParameterAware;
29
import org.apache.thrift.TException;
30
 
1614 rajveer 31
 
32
@Results({
4046 varun.gupt 33
    @Result(name = "index", location = "cart-index.vm"),
34
	@Result(name="redirect", type="redirectAction", params = {"actionName" , "cart"}),
1614 rajveer 35
	@Result(name="failure", location="cart-failure.vm"),
36
	@Result(name="success", location="cart-success.vm")
37
})
38
 
507 rajveer 39
public class CartController extends BaseController implements ParameterAware{
410 rajveer 40
 
41
	private static final long serialVersionUID = 1L;
1957 vikas 42
	private static Logger log = Logger.getLogger(Class.class);
507 rajveer 43
	Map<String, String[]> reqparams = null;
1981 varun.gupt 44
 
4046 varun.gupt 45
	private int variationId = 0;
2137 chandransh 46
    private String totalamount;
410 rajveer 47
 
572 chandransh 48
	private String errorMsg = "";
3970 varun.gupt 49
	private String cartMsg = "";
410 rajveer 50
 
1981 varun.gupt 51
	private String pincode = "110001";
52
 
53
	private String couponCode = null;
54
 
2137 chandransh 55
	private String discountedAmount;
1981 varun.gupt 56
 
2810 rajveer 57
	private long itemId;
58
 
410 rajveer 59
	public CartController(){
507 rajveer 60
		super();
61
	}
62
 
63
	 // GET /cart
4046 varun.gupt 64
	@Actions({
65
		@Action(value="cart", interceptorRefs={@InterceptorRef("myDefault")}),
66
		@Action(value="cart1", interceptorRefs={@InterceptorRef("myDefault")})
67
	})
68
	public String index()	{
69
		this.setVariationId(request.getRequestURI());
70
		log.info(this.getVariationId());
1614 rajveer 71
 
4046 varun.gupt 72
		long cartId = userinfo.getCartId();
73
 
74
	    if(cartId != -1){
75
        	try {
76
    			UserContextService.Client userClient = (new UserClient()).getClient();
77
    			errorMsg = userClient.validateCart(cartId, sourceId);
78
    			log.info("Error Message rcvd from the service is:" + errorMsg);
79
 
80
    			// As per ticket #119 in trac
81
    			Cart cart = userClient.getCart(cartId);
82
    			int totalItems = cart.getLinesSize();
83
    			double totalAmount = cart.getTotalPrice();
84
				userinfo.setTotalItems(totalItems);
85
				userinfo.setTotalAmount(totalAmount);
86
    		} catch (Exception e) {
87
    			// This exception can be ignored for showing the cart. Not so
88
    			// innocent when this occurs at the time of checkout or when the
89
    			// user is proceeding to pay.
90
    		    log.warn("Unable to validate the cart: ", e);
91
    		}
92
	    }
3970 varun.gupt 93
		return "index";
94
	}
4046 varun.gupt 95
 
572 chandransh 96
	// POST /entity
1614 rajveer 97
 
98
	@Action(value="addtocart",interceptorRefs={@InterceptorRef("createuser"),@InterceptorRef("myDefault")})
572 chandransh 99
	public String create() {
100
		log.info("CartController.create");
555 chandransh 101
 
572 chandransh 102
		printParams();
103
 
104
		long userId = userinfo.getUserId();
105
		long cartId = userinfo.getCartId();
106
 
1614 rajveer 107
		log.info("user id is " + userId);
108
		log.info("cart id is " + cartId);
109
 
572 chandransh 110
		log.info("item id is " + this.reqparams.get("productid"));
1614 rajveer 111
 
637 rajveer 112
		String itemIds = "";
572 chandransh 113
		if (this.reqparams.get("productid") != null) {
114
			itemIds = this.reqparams.get("productid")[0];
637 rajveer 115
		}else{
116
			return "failure";
572 chandransh 117
		}
637 rajveer 118
 
572 chandransh 119
		StringTokenizer tokenizer = new StringTokenizer(itemIds, "_");
120
		while (tokenizer.hasMoreTokens()) {
2810 rajveer 121
			itemId = Long.parseLong(tokenizer.nextToken());
572 chandransh 122
 
123
			try {
3126 rajveer 124
				UserClient userServiceClient = new UserClient();
572 chandransh 125
				UserContextService.Client userClient = userServiceClient.getClient();
762 rajveer 126
				if (cartId == 0){
555 chandransh 127
					cartId = userClient.createCart(userId);
762 rajveer 128
				}
3561 rajveer 129
				// If we add multiple items to cart and get some message from service, 
130
				// first message to be preserved and presented to the user.
2099 rajveer 131
				if(cartMsg.equals("")){
3561 rajveer 132
				    cartMsg = userClient.addItemToCart(cartId, itemId, 1, sourceId);
2036 rajveer 133
			    }else{
3561 rajveer 134
			        userClient.addItemToCart(cartId, itemId, 1, sourceId);
2036 rajveer 135
			    }
762 rajveer 136
				userinfo.setCartId(cartId);
137
				int totalItems = userClient.getCart(cartId).getLinesSize();
138
				userinfo.setTotalItems(totalItems);
572 chandransh 139
			} catch (TException e) {
2944 chandransh 140
			    log.error("Unable to create or add to cart because of: ", e);
572 chandransh 141
			} catch (Exception e) {
2944 chandransh 142
			    log.error("Unable to create or add to cart because of: ", e);
507 rajveer 143
			}
144
 
572 chandransh 145
		}
3185 vikas 146
        DataLogger.logData(EventType.ADD_TO_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 147
                Long.toString(cartId), itemIds);
572 chandransh 148
		return "success";
149
	}		
150
 
1614 rajveer 151
 
507 rajveer 152
		// DELETE /entity
153
		public String destroy() {
154
	    	log.info("CartController.destroy");
155
	    	printParams();
156
	    	log.info("item id is " + this.request.getParameter("productid"));
157
			String itemIdString = this.request.getParameter("productid");
2810 rajveer 158
			itemId = Long.parseLong(itemIdString);
517 rajveer 159
			if(userinfo.getCartId() == -1){
160
				log.info("Cart does not exist. Nothing to delete.");
161
			}else{
1957 vikas 162
				if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))
163
				{
3830 chandransh 164
					updateUserSessionInfo(userinfo.getCartId());
3185 vikas 165
                DataLogger.logData(EventType.DELETE_FROM_CART, getSessionId(),
2419 vikas 166
                        userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 167
                        Long.toString(userinfo.getCartId()), itemIdString);
801 rajveer 168
					return "redirect";	
517 rajveer 169
				}
507 rajveer 170
			}
801 rajveer 171
			return "redirect";
507 rajveer 172
		}
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 id 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);
517 rajveer 185
			if(quantity <= 0){
186
				log.info("Not valid item quantity. Unable to change item quantity.");
187
			}else{
762 rajveer 188
				if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity)){
3185 vikas 189
                DataLogger.logData(EventType.UPDATE_CART_QUANTITY, getSessionId(),
2419 vikas 190
                        userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 191
                        Long.toString(userinfo.getCartId()),
192
                        Long.toString(itemId), Long.toString(quantity));
801 rajveer 193
					return "redirect";	
517 rajveer 194
				}
507 rajveer 195
			}
3224 vikas 196
			DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 197
                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
801 rajveer 198
			addActionError("Unable to update the quantity");
199
			return "redirect";
507 rajveer 200
		}
3970 varun.gupt 201
 
507 rajveer 202
    public void printParams(){
203
    	for(String param : reqparams.keySet()) {
204
    		log.info("param name is " + param);
205
    		log.info("param first is " + reqparams.get(param)[0]);
206
    	}
207
    	log.info(this.reqparams);
208
    }
209
 
762 rajveer 210
	private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
211
		try {
3126 rajveer 212
			UserClient userContextServiceClient = new UserClient();
762 rajveer 213
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
214
 
3562 rajveer 215
			userClient.addItemToCart(cartId, itemId, quantity, sourceId);
762 rajveer 216
			return true;
217
		} catch (ShoppingCartException e) {
2944 chandransh 218
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 219
		} catch (TException e) {
2944 chandransh 220
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 221
		} catch (Exception e) {
2944 chandransh 222
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 223
		}
224
		return false;
225
	}
226
 
227
	private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
228
		try {
3126 rajveer 229
			UserClient userContextServiceClient = new UserClient();
762 rajveer 230
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
231
 
232
			userClient.deleteItemFromCart(cartId, catalogItemId);
233
			return true;	
234
		} catch (ShoppingCartException e) {
2944 chandransh 235
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 236
		} catch (TException e) {
2944 chandransh 237
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 238
		} catch (Exception e) {
2944 chandransh 239
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 240
		}
241
 
242
		return false;
243
	}
244
 
3830 chandransh 245
	private void updateUserSessionInfo(long cartId) {
3126 rajveer 246
		UserClient userContextServiceClient = null;
762 rajveer 247
		try {
3126 rajveer 248
			userContextServiceClient = new UserClient();
762 rajveer 249
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
3830 chandransh 250
			Cart cart = userClient.getCart(cartId);
251
			userinfo.setTotalItems(cart.getLinesSize());
252
			userinfo.setTotalAmount(cart.getTotalPrice());
762 rajveer 253
		} catch (ShoppingCartException e) {
2944 chandransh 254
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 255
		} catch (TException e) {
2944 chandransh 256
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 257
		} catch (Exception e) {
2944 chandransh 258
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 259
		}
260
	}
1981 varun.gupt 261
 
262
	public List<Map<String,String>> getCartItems() {
263
	    List<Map<String,String>> items = null;
762 rajveer 264
 
3126 rajveer 265
        UserClient userServiceClient = null;
1981 varun.gupt 266
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
3126 rajveer 267
        CatalogClient catalogServiceClient  = null;
1981 varun.gupt 268
        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = null;
762 rajveer 269
 
2137 chandransh 270
        FormattingUtils formattingUtils = new FormattingUtils();
271
 
1981 varun.gupt 272
        try    {
3126 rajveer 273
            catalogServiceClient = new CatalogClient();
1981 varun.gupt 274
            catalogClient = catalogServiceClient.getClient();
3126 rajveer 275
            userServiceClient = new UserClient();
1981 varun.gupt 276
            userClient = userServiceClient.getClient();
277
 
278
            pincode = userClient.getDefaultPincode(userinfo.getUserId());
279
            Cart cart = userClient.getCart(userinfo.getCartId());
280
            List<Line> lineItems = cart.getLines();
281
 
282
            if(lineItems.size() != 0)  {
283
                items = new ArrayList<Map<String,String>>();
284
 
285
                for (Line line : lineItems)    {
286
                    Map<String, String> itemdetail = new HashMap<String, String>();
3561 rajveer 287
 
288
                    Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
289
 
1981 varun.gupt 290
                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
291
                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
3830 chandransh 292
                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" );
1981 varun.gupt 293
 
3830 chandransh 294
                    String itemColor = "";
295
                    if(item.getColor() != null && !item.getColor().trim().equals("NA"))
296
                        itemColor = "Color - " + item.getColor();
297
 
1981 varun.gupt 298
                    itemdetail.put("ITEM_NAME", itemName);
3830 chandransh 299
                    itemdetail.put("ITEM_COLOR", itemColor);
1981 varun.gupt 300
                    itemdetail.put("ITEM_ID", line.getItemId() + "");
301
                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
302
                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
2137 chandransh 303
                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
304
                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
305
                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
1981 varun.gupt 306
                    itemdetail.put("SHIPPING_TIME", line.getEstimate() + "");
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;
385
		return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getNameOfUser(), url , 0, false);
386
	}
3970 varun.gupt 387
 
4046 varun.gupt 388
	public void setVariationId(String uri)	{
389
		if (uri.equals("/cart1"))	{
390
			this.variationId = 1;
391
		}
3970 varun.gupt 392
	}
393
 
4046 varun.gupt 394
	public int getVariationId()	{
395
		return this.variationId;
3970 varun.gupt 396
	}
3903 varun.gupt 397
}