Subversion Repositories SmartDukaan

Rev

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