Subversion Repositories SmartDukaan

Rev

Rev 4344 | Rev 5228 | 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;
4217 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")}),
4453 varun.gupt 66
		@Action(value="cart1", interceptorRefs={@InterceptorRef("myDefault")})
4046 varun.gupt 67
	})
4344 anupam.sin 68
	public String index()  {
4046 varun.gupt 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
 
4217 varun.gupt 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
 
158
		String itemIdString = this.request.getParameter("productid");
159
		itemId = Long.parseLong(itemIdString);
160
 
161
		if(userinfo.getCartId() == -1)	{
162
			log.info("Cart does not exist. Nothing to delete.");
163
		} else	{
164
			if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))	{
165
				updateUserSessionInfo(userinfo.getCartId());
166
				DataLogger.logData(EventType.DELETE_FROM_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 167
                        Long.toString(userinfo.getCartId()), itemIdString);
4217 varun.gupt 168
				return "redirect";
507 rajveer 169
			}
170
		}
4217 varun.gupt 171
		return "redirect";
172
	}
173
 
174
	// DELETE /entity
175
	public String update() {
176
		log.info("CartController.update");
177
		printParams();
178
		log.info("item id is " + this.request.getParameter("productid"));
179
		log.info("item quantity is " + this.request.getParameter("quantity"));
180
		String itemIdString = this.request.getParameter("productid");
181
		String quantityString = this.request.getParameter("quantity");
182
		long itemId = Long.parseLong(itemIdString);
183
		long quantity = Long.parseLong(quantityString);
184
 
185
		if(quantity <= 0)	{
186
			log.info("Not valid item quantity. Unable to change item quantity.");
187
		} else	{
188
			if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity))	{
189
				DataLogger.logData(EventType.UPDATE_CART_QUANTITY, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
190
                        Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
191
				return "redirect";
507 rajveer 192
			}
4217 varun.gupt 193
		}
194
		DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 195
                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
4217 varun.gupt 196
		addActionError("Unable to update the quantity");
197
		return "redirect";
198
	}
3970 varun.gupt 199
 
507 rajveer 200
    public void printParams(){
201
    	for(String param : reqparams.keySet()) {
202
    		log.info("param name is " + param);
203
    		log.info("param first is " + reqparams.get(param)[0]);
204
    	}
205
    	log.info(this.reqparams);
206
    }
207
 
762 rajveer 208
	private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
209
		try {
3126 rajveer 210
			UserClient userContextServiceClient = new UserClient();
762 rajveer 211
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
212
 
3562 rajveer 213
			userClient.addItemToCart(cartId, itemId, quantity, sourceId);
762 rajveer 214
			return true;
215
		} catch (ShoppingCartException e) {
2944 chandransh 216
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 217
		} catch (TException e) {
2944 chandransh 218
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 219
		} catch (Exception e) {
2944 chandransh 220
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 221
		}
222
		return false;
223
	}
224
 
225
	private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
226
		try {
3126 rajveer 227
			UserClient userContextServiceClient = new UserClient();
762 rajveer 228
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
4217 varun.gupt 229
 
762 rajveer 230
			userClient.deleteItemFromCart(cartId, catalogItemId);
4217 varun.gupt 231
			return true;
762 rajveer 232
		} catch (ShoppingCartException e) {
2944 chandransh 233
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 234
		} catch (TException e) {
2944 chandransh 235
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 236
		} catch (Exception e) {
2944 chandransh 237
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 238
		}
239
 
240
		return false;
241
	}
242
 
3830 chandransh 243
	private void updateUserSessionInfo(long cartId) {
3126 rajveer 244
		UserClient userContextServiceClient = null;
762 rajveer 245
		try {
3126 rajveer 246
			userContextServiceClient = new UserClient();
762 rajveer 247
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
3830 chandransh 248
			Cart cart = userClient.getCart(cartId);
249
			userinfo.setTotalItems(cart.getLinesSize());
250
			userinfo.setTotalAmount(cart.getTotalPrice());
762 rajveer 251
		} catch (ShoppingCartException e) {
2944 chandransh 252
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 253
		} catch (TException e) {
2944 chandransh 254
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 255
		} catch (Exception e) {
2944 chandransh 256
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 257
		}
258
	}
1981 varun.gupt 259
 
260
	public List<Map<String,String>> getCartItems() {
261
	    List<Map<String,String>> items = null;
762 rajveer 262
 
3126 rajveer 263
        UserClient userServiceClient = null;
1981 varun.gupt 264
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
3126 rajveer 265
        CatalogClient catalogServiceClient  = null;
1981 varun.gupt 266
        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = null;
762 rajveer 267
 
2137 chandransh 268
        FormattingUtils formattingUtils = new FormattingUtils();
269
 
1981 varun.gupt 270
        try    {
3126 rajveer 271
            catalogServiceClient = new CatalogClient();
1981 varun.gupt 272
            catalogClient = catalogServiceClient.getClient();
3126 rajveer 273
            userServiceClient = new UserClient();
1981 varun.gupt 274
            userClient = userServiceClient.getClient();
275
 
276
            pincode = userClient.getDefaultPincode(userinfo.getUserId());
277
            Cart cart = userClient.getCart(userinfo.getCartId());
278
            List<Line> lineItems = cart.getLines();
279
 
280
            if(lineItems.size() != 0)  {
281
                items = new ArrayList<Map<String,String>>();
282
 
283
                for (Line line : lineItems)    {
284
                    Map<String, String> itemdetail = new HashMap<String, String>();
3561 rajveer 285
 
286
                    Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
287
 
1981 varun.gupt 288
                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
289
                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
3830 chandransh 290
                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" );
1981 varun.gupt 291
 
3830 chandransh 292
                    String itemColor = "";
293
                    if(item.getColor() != null && !item.getColor().trim().equals("NA"))
294
                        itemColor = "Color - " + item.getColor();
295
 
1981 varun.gupt 296
                    itemdetail.put("ITEM_NAME", itemName);
3830 chandransh 297
                    itemdetail.put("ITEM_COLOR", itemColor);
1981 varun.gupt 298
                    itemdetail.put("ITEM_ID", line.getItemId() + "");
299
                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
300
                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
2137 chandransh 301
                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
302
                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
303
                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
1981 varun.gupt 304
                    itemdetail.put("SHIPPING_TIME", line.getEstimate() + "");
4217 varun.gupt 305
					itemdetail.put("BEST_DEAL_TEXT", item.getBestDealText());
1981 varun.gupt 306
 
307
                    items.add(itemdetail);
308
                }
309
            }
2137 chandransh 310
 
311
            totalamount = formattingUtils.formatPrice(cart.getTotalPrice());
1981 varun.gupt 312
            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
2137 chandransh 313
            discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
1981 varun.gupt 314
        } catch (Exception e)  {
2944 chandransh 315
            log.error("Unable to get the cart details becasue of: ", e);
1981 varun.gupt 316
        }
317
        return items;
507 rajveer 318
	}
1981 varun.gupt 319
 
3080 rajveer 320
	public long getItemId(){
321
		return this.itemId;
322
	}
323
 
2137 chandransh 324
	public String getTotalAmount() {
1981 varun.gupt 325
	    return totalamount;
326
	}
507 rajveer 327
 
1981 varun.gupt 328
	public String getPinCode() {
329
	    return pincode;
507 rajveer 330
	}
331
 
1981 varun.gupt 332
	public String getCouponCode()  {
333
	    return couponCode;
334
	}
335
 
336
	public String getDiscountedAmount()   {
2137 chandransh 337
	    return discountedAmount;
1981 varun.gupt 338
	}
339
 
340
	public String getErrorMsg()    {
341
	    return errorMsg;
342
	}
343
 
507 rajveer 344
	public long getNumberOfItems(){
345
		return userinfo.getTotalItems();
346
	}
650 rajveer 347
 
2036 rajveer 348
	public String getCartMsg(){
2099 rajveer 349
	    if(cartMsg.equals("")){
350
	        return null;
351
	    }
352
	    return cartMsg;
2036 rajveer 353
	}
354
 
2810 rajveer 355
	public String getSnippets(){
356
    	String snippets = "";
3126 rajveer 357
		CatalogClient csc;
2810 rajveer 358
		try {
3126 rajveer 359
			csc = new CatalogClient();
2810 rajveer 360
			List<Long> similarItems = csc.getClient().getSimilarItemsCatalogIds(0, 4, itemId);
361
			for(Long catalogId: similarItems){
3599 rajveer 362
				snippets = snippets + ContentServingService.getSnippet(SnippetType.WIDGET_SNIPPET, catalogId+"", sourceId);
2810 rajveer 363
			}
364
		} catch (Exception e) {
365
			log.error("Unable to initialise Catalogservice Client");
366
		}	    
367
	    return snippets;
368
    }
369
 
650 rajveer 370
	@Override
371
	public void setParameters(Map<String, String[]> parameters) {
372
		this.reqparams = parameters;	
373
	}
3903 varun.gupt 374
 
375
	@Override
376
	public String getHeaderSnippet() {
377
		String url = request.getQueryString();
378
		if (url == null) {
379
			url = "";
380
		} else {
381
			url = "?" + url;
382
		}
383
		url = request.getRequestURI() + url;
4453 varun.gupt 384
		return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), url , 0, false);
3903 varun.gupt 385
	}
3970 varun.gupt 386
 
4222 varun.gupt 387
	public boolean isUserLoggedIn()	{
388
		return userinfo.isLoggedIn();
389
	}
390
 
4046 varun.gupt 391
	public void setVariationId(String uri)	{
392
		if (uri.equals("/cart1"))	{
393
			this.variationId = 1;
394
		}
3970 varun.gupt 395
	}
396
 
4046 varun.gupt 397
	public int getVariationId()	{
398
		return this.variationId;
3970 varun.gupt 399
	}
3903 varun.gupt 400
}