Subversion Repositories SmartDukaan

Rev

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