Subversion Repositories SmartDukaan

Rev

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