Subversion Repositories SmartDukaan

Rev

Rev 3561 | Rev 3599 | 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();
3561 rajveer 73
    			errorMsg = userClient.validateCart(cartId, sourceId);
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
				}
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
				{
762 rajveer 156
					userinfo.setTotalItems(getNumberOfItemsInCart(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
 
238
	private int getNumberOfItemsInCart(long cartId) {
239
		int numberOfItems = 0;
3126 rajveer 240
		UserClient userContextServiceClient = null;
762 rajveer 241
		try {
3126 rajveer 242
			userContextServiceClient = new UserClient();
762 rajveer 243
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
244
 
245
			numberOfItems = userClient.getCart(cartId).getLinesSize();
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
		return numberOfItems;
254
	}
1981 varun.gupt 255
 
256
	public List<Map<String,String>> getCartItems() {
257
	    List<Map<String,String>> items = null;
762 rajveer 258
 
3126 rajveer 259
        UserClient userServiceClient = null;
1981 varun.gupt 260
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
3126 rajveer 261
        CatalogClient catalogServiceClient  = null;
1981 varun.gupt 262
        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = null;
762 rajveer 263
 
2137 chandransh 264
        FormattingUtils formattingUtils = new FormattingUtils();
265
 
1981 varun.gupt 266
        try    {
3126 rajveer 267
            catalogServiceClient = new CatalogClient();
1981 varun.gupt 268
            catalogClient = catalogServiceClient.getClient();
3126 rajveer 269
            userServiceClient = new UserClient();
1981 varun.gupt 270
            userClient = userServiceClient.getClient();
271
 
272
            pincode = userClient.getDefaultPincode(userinfo.getUserId());
273
            Cart cart = userClient.getCart(userinfo.getCartId());
274
            List<Line> lineItems = cart.getLines();
275
 
276
            if(lineItems.size() != 0)  {
277
                items = new ArrayList<Map<String,String>>();
278
 
279
                for (Line line : lineItems)    {
280
                    Map<String, String> itemdetail = new HashMap<String, String>();
3561 rajveer 281
 
282
                    Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
283
 
1981 varun.gupt 284
                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
285
                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
286
                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" )
287
                                            + (( (item.getColor() != null && !item.getColor().trim().equals("NA"))) ? "("+item.getColor()+")" : "" );
288
 
289
                    itemdetail.put("ITEM_NAME", itemName);
290
                    itemdetail.put("ITEM_ID", line.getItemId() + "");
291
                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
292
                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
2137 chandransh 293
                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
294
                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
295
                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
1981 varun.gupt 296
                    itemdetail.put("SHIPPING_TIME", line.getEstimate() + "");
297
 
298
                    items.add(itemdetail);
299
                }
300
            }
2137 chandransh 301
 
302
            totalamount = formattingUtils.formatPrice(cart.getTotalPrice());
1981 varun.gupt 303
            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
2137 chandransh 304
            discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
1981 varun.gupt 305
        } catch (Exception e)  {
2944 chandransh 306
            log.error("Unable to get the cart details becasue of: ", e);
1981 varun.gupt 307
        }
308
        return items;
507 rajveer 309
	}
1981 varun.gupt 310
 
3080 rajveer 311
	public long getItemId(){
312
		return this.itemId;
313
	}
314
 
2137 chandransh 315
	public String getTotalAmount() {
1981 varun.gupt 316
	    return totalamount;
317
	}
507 rajveer 318
 
1981 varun.gupt 319
	public String getPinCode() {
320
	    return pincode;
507 rajveer 321
	}
322
 
1981 varun.gupt 323
	public String getCouponCode()  {
324
	    return couponCode;
325
	}
326
 
327
	public String getDiscountedAmount()   {
2137 chandransh 328
	    return discountedAmount;
1981 varun.gupt 329
	}
330
 
331
	public String getErrorMsg()    {
332
	    return errorMsg;
333
	}
334
 
507 rajveer 335
	public long getNumberOfItems(){
336
		return userinfo.getTotalItems();
337
	}
650 rajveer 338
 
2036 rajveer 339
	public String getCartMsg(){
2099 rajveer 340
	    if(cartMsg.equals("")){
341
	        return null;
342
	    }
343
	    return cartMsg;
2036 rajveer 344
	}
345
 
2810 rajveer 346
 
347
	public String getSnippets(){
348
    	String snippets = "";
3126 rajveer 349
		CatalogClient csc;
2810 rajveer 350
		try {
3126 rajveer 351
			csc = new CatalogClient();
2810 rajveer 352
			List<Long> similarItems = csc.getClient().getSimilarItemsCatalogIds(0, 4, itemId);
353
			for(Long catalogId: similarItems){
354
				try {
355
					snippets += FileUtils.read( Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator + "WidgetSnippet.html");
356
		    	}
357
	            catch (FileNotFoundException e) {
358
	                log.error("File not found : " + Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator +"WidgetSnippet.html");
359
	            }
360
	            catch (IOException e) {
361
	                log.error("IO exception : " + Utils.EXPORT_ENTITIES_PATH + catalogId + File.separator +"WidgetSnippet.html");
362
	            }
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
	}
507 rajveer 374
}