Subversion Repositories SmartDukaan

Rev

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