Subversion Repositories SmartDukaan

Rev

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