Subversion Repositories SmartDukaan

Rev

Rev 3224 | Rev 3561 | 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;
2810 rajveer 9
import in.shop2020.serving.utils.FileUtils;
2137 chandransh 10
import in.shop2020.serving.utils.FormattingUtils;
2810 rajveer 11
import in.shop2020.serving.utils.Utils;
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
 
2810 rajveer 16
import java.io.File;
17
import java.io.FileNotFoundException;
18
import java.io.IOException;
2419 vikas 19
import java.util.ArrayList;
20
import java.util.HashMap;
21
import java.util.List;
22
import java.util.Map;
23
import java.util.StringTokenizer;
24
 
832 rajveer 25
import org.apache.log4j.Logger;
1614 rajveer 26
import org.apache.struts2.convention.annotation.Action;
27
import org.apache.struts2.convention.annotation.InterceptorRef;
801 rajveer 28
import org.apache.struts2.convention.annotation.Result;
1614 rajveer 29
import org.apache.struts2.convention.annotation.Results;
410 rajveer 30
import org.apache.struts2.interceptor.ParameterAware;
31
import org.apache.thrift.TException;
32
 
1614 rajveer 33
 
34
@Results({
35
	@Result(name="redirect", type="redirectAction", 
36
	   		params = {"actionName" , "cart"}),
37
	@Result(name="failure", location="cart-failure.vm"),
38
	@Result(name="success", location="cart-success.vm")
39
})
40
 
41
 
507 rajveer 42
public class CartController extends BaseController implements ParameterAware{
410 rajveer 43
 
44
	private static final long serialVersionUID = 1L;
1957 vikas 45
	private static Logger log = Logger.getLogger(Class.class);
507 rajveer 46
	Map<String, String[]> reqparams = null;
1981 varun.gupt 47
 
2137 chandransh 48
    private String totalamount;
410 rajveer 49
 
572 chandransh 50
	private String errorMsg = "";
2099 rajveer 51
	private String cartMsg = ""; 
410 rajveer 52
 
1981 varun.gupt 53
	private String pincode = "110001";
54
 
55
	private String couponCode = null;
56
 
2137 chandransh 57
	private String discountedAmount;
1981 varun.gupt 58
 
2810 rajveer 59
	private long itemId;
60
 
410 rajveer 61
	public CartController(){
507 rajveer 62
		super();
63
	}
64
 
65
	 // GET /cart
1614 rajveer 66
 
67
	@Action(value="cart",interceptorRefs={@InterceptorRef("myDefault")})
650 rajveer 68
	 public String index() {
2974 chandransh 69
	    long cartId = userinfo.getCartId();
70
	    if(cartId != -1){
71
        	try {
3126 rajveer 72
    			UserContextService.Client userClient = (new UserClient()).getClient();
2974 chandransh 73
    			errorMsg = userClient.validateCart(cartId);
2983 chandransh 74
    			log.info("Error Message rcvd from the service is:" + errorMsg);
3507 rajveer 75
 
76
    			// As per ticket #119 in trac
77
    			int totalItems = userClient.getCart(cartId).getLinesSize();
78
				userinfo.setTotalItems(totalItems);
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
				}
2099 rajveer 121
				if(cartMsg.equals("")){
2036 rajveer 122
				    cartMsg = userClient.addItemToCart(cartId, itemId, 1);
123
			    }else{
124
			        userClient.addItemToCart(cartId, itemId, 1);
125
			    }
762 rajveer 126
				userinfo.setCartId(cartId);
127
				int totalItems = userClient.getCart(cartId).getLinesSize();
128
				userinfo.setTotalItems(totalItems);
572 chandransh 129
			} catch (TException e) {
2944 chandransh 130
			    log.error("Unable to create or add to cart because of: ", e);
572 chandransh 131
			} catch (Exception e) {
2944 chandransh 132
			    log.error("Unable to create or add to cart because of: ", e);
507 rajveer 133
			}
134
 
572 chandransh 135
		}
3185 vikas 136
        DataLogger.logData(EventType.ADD_TO_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 137
                Long.toString(cartId), itemIds);
572 chandransh 138
		return "success";
139
	}		
140
 
1614 rajveer 141
 
507 rajveer 142
		// DELETE /entity
143
		public String destroy() {
144
	    	log.info("CartController.destroy");
145
	    	printParams();
146
	    	log.info("item id is " + this.request.getParameter("productid"));
147
			String itemIdString = this.request.getParameter("productid");
2810 rajveer 148
			itemId = Long.parseLong(itemIdString);
517 rajveer 149
			if(userinfo.getCartId() == -1){
150
				log.info("Cart does not exist. Nothing to delete.");
151
			}else{
1957 vikas 152
				if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))
153
				{
762 rajveer 154
					userinfo.setTotalItems(getNumberOfItemsInCart(userinfo.getCartId()));
3185 vikas 155
                DataLogger.logData(EventType.DELETE_FROM_CART, getSessionId(),
2419 vikas 156
                        userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 157
                        Long.toString(userinfo.getCartId()), itemIdString);
801 rajveer 158
					return "redirect";	
517 rajveer 159
				}
507 rajveer 160
			}
801 rajveer 161
			return "redirect";
507 rajveer 162
		}
163
 
164
 
165
		// DELETE /entity
166
		public String update() {
167
	    	log.info("CartController.update");
168
	    	printParams();
169
	    	log.info("item id is " + this.request.getParameter("productid"));
170
	    	log.info("item id is " + this.request.getParameter("quantity"));
171
			String itemIdString = this.request.getParameter("productid");
172
			String quantityString = this.request.getParameter("quantity");
173
			long itemId = Long.parseLong(itemIdString);
174
			long quantity = Long.parseLong(quantityString);
517 rajveer 175
			if(quantity <= 0){
176
				log.info("Not valid item quantity. Unable to change item quantity.");
177
			}else{
762 rajveer 178
				if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity)){
3185 vikas 179
                DataLogger.logData(EventType.UPDATE_CART_QUANTITY, getSessionId(),
2419 vikas 180
                        userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 181
                        Long.toString(userinfo.getCartId()),
182
                        Long.toString(itemId), Long.toString(quantity));
801 rajveer 183
					return "redirect";	
517 rajveer 184
				}
507 rajveer 185
			}
3224 vikas 186
			DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
2157 vikas 187
                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
801 rajveer 188
			addActionError("Unable to update the quantity");
189
			return "redirect";
507 rajveer 190
		}
191
 
192
 
193
    public void printParams(){
194
    	for(String param : reqparams.keySet()) {
195
    		log.info("param name is " + param);
196
    		log.info("param first is " + reqparams.get(param)[0]);
197
    	}
198
    	log.info(this.reqparams);
199
    }
200
 
762 rajveer 201
	private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
202
		try {
3126 rajveer 203
			UserClient userContextServiceClient = new UserClient();
762 rajveer 204
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
205
 
206
			userClient.changeQuantity(cartId, itemId, quantity);
207
			return true;
208
		} catch (ShoppingCartException e) {
2944 chandransh 209
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 210
		} catch (TException e) {
2944 chandransh 211
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 212
		} catch (Exception e) {
2944 chandransh 213
		    log.error("Unable to update the item quantity in the cart: ", e);
762 rajveer 214
		}
215
		return false;
216
	}
217
 
218
	private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
219
		try {
3126 rajveer 220
			UserClient userContextServiceClient = new UserClient();
762 rajveer 221
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
222
 
223
			userClient.deleteItemFromCart(cartId, catalogItemId);
224
			return true;	
225
		} catch (ShoppingCartException e) {
2944 chandransh 226
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 227
		} catch (TException e) {
2944 chandransh 228
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 229
		} catch (Exception e) {
2944 chandransh 230
		    log.error("Unable to delete item from cart: ", e);
762 rajveer 231
		}
232
 
233
		return false;
234
	}
235
 
236
	private int getNumberOfItemsInCart(long cartId) {
237
		int numberOfItems = 0;
3126 rajveer 238
		UserClient userContextServiceClient = null;
762 rajveer 239
		try {
3126 rajveer 240
			userContextServiceClient = new UserClient();
762 rajveer 241
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
242
 
243
			numberOfItems = userClient.getCart(cartId).getLinesSize();
244
		} catch (ShoppingCartException e) {
2944 chandransh 245
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 246
		} catch (TException e) {
2944 chandransh 247
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 248
		} catch (Exception e) {
2944 chandransh 249
		    log.error("Unable to get the cart from service: ", e);
762 rajveer 250
		}
251
		return numberOfItems;
252
	}
1981 varun.gupt 253
 
254
	public List<Map<String,String>> getCartItems() {
255
	    List<Map<String,String>> items = null;
762 rajveer 256
 
3126 rajveer 257
        UserClient userServiceClient = null;
1981 varun.gupt 258
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
3126 rajveer 259
        CatalogClient catalogServiceClient  = null;
1981 varun.gupt 260
        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = null;
762 rajveer 261
 
2137 chandransh 262
        FormattingUtils formattingUtils = new FormattingUtils();
263
 
1981 varun.gupt 264
        try    {
3126 rajveer 265
            catalogServiceClient = new CatalogClient();
1981 varun.gupt 266
            catalogClient = catalogServiceClient.getClient();
3126 rajveer 267
            userServiceClient = new UserClient();
1981 varun.gupt 268
            userClient = userServiceClient.getClient();
269
 
270
            pincode = userClient.getDefaultPincode(userinfo.getUserId());
271
            Cart cart = userClient.getCart(userinfo.getCartId());
272
            List<Line> lineItems = cart.getLines();
273
 
274
            if(lineItems.size() != 0)  {
275
                items = new ArrayList<Map<String,String>>();
276
 
277
                for (Line line : lineItems)    {
278
                    Map<String, String> itemdetail = new HashMap<String, String>();
279
                    Item item = catalogClient.getItem(line.getItemId());
280
 
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){
351
				try {
352
					snippets += FileUtils.read( Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "WidgetSnippet.html");
353
		    	}
354
	            catch (FileNotFoundException e) {
355
	                log.error("File not found : " + Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator +"WidgetSnippet.html");
356
	            }
357
	            catch (IOException e) {
358
	                log.error("IO exception : " + Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator +"WidgetSnippet.html");
359
	            }
360
			}
361
		} catch (Exception e) {
362
			log.error("Unable to initialise Catalogservice Client");
363
		}	    
364
	    return snippets;
365
    }
366
 
650 rajveer 367
	@Override
368
	public void setParameters(Map<String, String[]> parameters) {
369
		this.reqparams = parameters;	
370
	}
507 rajveer 371
}