Subversion Repositories SmartDukaan

Rev

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