Subversion Repositories SmartDukaan

Rev

Rev 13066 | Rev 17784 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
11592 amit.gupta 1
package in.shop2020.mobileapi.serving.controllers;
9570 anupam.sin 2
 
17782 amit.gupta 3
import in.shop2020.logistics.DeliveryType;
4
import in.shop2020.metamodel.util.ProductPojo;
11516 amit.gupta 5
import in.shop2020.mobileapi.serving.pojos.CartPojo;
10724 amit.gupta 6
import in.shop2020.mobileapi.serving.pojos.RedirectPojo;
9577 anupam.sin 7
import in.shop2020.mobileapi.serving.services.ContentServingService;
17782 amit.gupta 8
import in.shop2020.mobileapi.serving.services.LogisticsService;
9667 anupam.sin 9
import in.shop2020.mobileapi.serving.utils.PojoPopulator;
9577 anupam.sin 10
import in.shop2020.mobileapi.serving.utils.SnippetType;
9570 anupam.sin 11
import in.shop2020.model.v1.catalog.CatalogService.Client;
12
import in.shop2020.model.v1.catalog.Item;
13
import in.shop2020.model.v1.user.Cart;
11592 amit.gupta 14
import in.shop2020.model.v1.user.CartPlus;
17782 amit.gupta 15
import in.shop2020.model.v1.user.ItemQuantity;
9713 anupam.sin 16
import in.shop2020.model.v1.user.PromotionException;
17
import in.shop2020.model.v1.user.PromotionService;
9570 anupam.sin 18
import in.shop2020.model.v1.user.ShoppingCartException;
19
import in.shop2020.model.v1.user.UserContextService;
20
import in.shop2020.thrift.clients.CatalogClient;
9713 anupam.sin 21
import in.shop2020.thrift.clients.PromotionClient;
9570 anupam.sin 22
import in.shop2020.thrift.clients.UserClient;
23
 
17782 amit.gupta 24
import java.util.ArrayList;
9570 anupam.sin 25
import java.util.List;
26
import java.util.Map;
27
 
17782 amit.gupta 28
import org.apache.commons.lang.StringUtils;
9570 anupam.sin 29
import org.apache.log4j.Logger;
30
import org.apache.struts2.interceptor.ParameterAware;
31
import org.apache.thrift.TException;
17782 amit.gupta 32
import org.json.JSONArray;
33
import org.json.JSONObject;
9570 anupam.sin 34
 
9667 anupam.sin 35
import com.google.gson.Gson;
9570 anupam.sin 36
 
37
public class CartController extends BaseController implements ParameterAware{
38
 
39
    private static final long serialVersionUID = 1L;
40
    private static Logger log = Logger.getLogger(Class.class);
41
    Map<String, String[]> reqparams = null;
42
 
43
    private int variationId = 0;
44
    private String totalamount;
45
 
46
    private String errorMsg = "";
47
    private String cartMsg = "";
48
 
49
    private String pincode = "110001";
50
 
51
    private String couponCode = null;
52
 
53
    private String discountedAmount;
54
 
55
    private long itemId;
56
    private String insuranceResult;
57
 
58
    private boolean toInsure;
12021 amit.gupta 59
    private boolean privateDealUser = false;
12022 amit.gupta 60
    private boolean autoApplicationOff = true;
9570 anupam.sin 61
 
11516 amit.gupta 62
    private long id =-1; //CartId
9667 anupam.sin 63
    private String cartPojoJson;
9676 anupam.sin 64
    private long quantity;
9697 anupam.sin 65
    private int insuranceType;
11386 amit.gupta 66
    UserContextService.Client userClient;
9570 anupam.sin 67
 
11386 amit.gupta 68
    public CartController() throws Exception{
9570 anupam.sin 69
        super();
70
    }
71
 
11535 amit.gupta 72
    public UserContextService.Client getClient() throws Exception{
11602 amit.gupta 73
    	userClient = new UserClient().getClient();
11535 amit.gupta 74
    	return userClient;
11593 amit.gupta 75
    }	
9808 anupam.sin 76
    public String index() {
9709 anupam.sin 77
        if(id != -1){
9570 anupam.sin 78
            try {
11983 amit.gupta 79
            	String cc = null;
12022 amit.gupta 80
            	log.info(privateDealUser + "  "  + autoApplicationOff);
81
            	if(privateDealUser && !autoApplicationOff) {
11983 amit.gupta 82
            		cc = "saholicdeals";
83
            	}
13066 amit.gupta 84
            	log.info("Before cart response--------");
11983 amit.gupta 85
            	CartPlus cartResponse  = getClient().validateCartPlus(id, -1, cc);
11511 amit.gupta 86
                log.info("After cart response--------");
11823 amit.gupta 87
                if (errorMsg == null || errorMsg.equals("")) {
11917 amit.gupta 88
                	if(cartResponse.getValidateCartMessages().get(1)!=null && !cartResponse.getValidateCartMessages().get(1).equals("")){
89
                		errorMsg = cartResponse.getValidateCartMessages().get(1);
90
                	}else {
91
                		errorMsg = cartResponse.getValidateCartMessages().get(0);
92
                	}
11823 amit.gupta 93
                }
94
                cartPojoJson = new Gson().toJson(PojoPopulator.getCartPojo(cartResponse.getCart(), errorMsg, 
11592 amit.gupta 95
                		cartResponse.getPinCode(), cartResponse.isNeedInsuranceInfo()));
10551 amit.gupta 96
                log.info(cartPojoJson);
9570 anupam.sin 97
            } catch (Exception e) {
11593 amit.gupta 98
                /*TTransportException te = (TTransportException)e;
99
                log.warn(e.getLocalizedMessage() + " " + te.getType());*/
9570 anupam.sin 100
                log.warn("Unable to validate the cart: ", e);
101
            }
11516 amit.gupta 102
        } else {
103
        	cartPojoJson = new Gson().toJson(new CartPojo());
9570 anupam.sin 104
        }
105
        return "index";
106
    }
107
 
108
    public String create() {
10724 amit.gupta 109
    	RedirectPojo rp = new RedirectPojo();
110
    	rp.setRedirectUrl("");
9676 anupam.sin 111
        try {
11526 amit.gupta 112
        	//Try adding to cart
11535 amit.gupta 113
            cartMsg = getClient().addItemToCart(id, itemId, 1, -1);
114
            log.info("Cart message while adding item to cart - " + cartMsg);
11526 amit.gupta 115
            //If could not add to cart try to add notification reminder if email exists.
9680 amit.gupta 116
            if (!("".equals(cartMsg))) {
10767 amit.gupta 117
            	String emailId = this.request.getParameter("email");
10766 amit.gupta 118
            	log.info("QuesyString" + this.request.getParameterMap().toString());
10724 amit.gupta 119
    			if(emailId==null || emailId.equals("")){
11526 amit.gupta 120
    				//User tries to add to cart but product is actually out of stock
10724 amit.gupta 121
    				rp.setMessage("Item is currently out of stock");
122
    			} else {	
123
        			try {
124
	        	        CatalogClient catalogClientService;
125
	        			catalogClientService = new CatalogClient();
126
	        			in.shop2020.model.v1.catalog.CatalogService.Client client = catalogClientService.getClient();
127
	        			client.addProductNotification(itemId, emailId);
128
	        			log.debug("Got product notification for product: " + itemId + "  from user: " + emailId );
129
	        			rp.setMessage("You will be notified when product is avaliable");
130
        			} catch (Exception e) {
131
        				rp.setMessage("Error occurred while adding to notificiation");
132
        				log.error("Exception while adding product notification for item: " + itemId + " and email: " + emailId, e);
10261 amit.gupta 133
        			}
10724 amit.gupta 134
 
10261 amit.gupta 135
        		}
10724 amit.gupta 136
            } else {
137
            	rp.setRedirectUrl("cart");
9676 anupam.sin 138
            }
139
        } catch (TException e) {
140
            log.error("Unable to create or add to cart because of: ", e);
9713 anupam.sin 141
            errorMsg = "Unable to add to cart. Please try again.";
9676 anupam.sin 142
        } catch (Exception e) {
143
            log.error("Unable to create or add to cart because of: ", e);
9713 anupam.sin 144
            errorMsg = "Unable to add to cart. Please try again.";
9570 anupam.sin 145
        }
10724 amit.gupta 146
        cartPojoJson = new Gson().toJson(rp);
147
        return "index";
9676 anupam.sin 148
    }       
9570 anupam.sin 149
 
9676 anupam.sin 150
 
151
    // DELETE /entity
152
    public String destroy() {
9709 anupam.sin 153
        if(id > 0)  {
9570 anupam.sin 154
            try {
11535 amit.gupta 155
                getClient().deleteItemFromCart(id, itemId);
9676 anupam.sin 156
                return index();
157
            } catch (ShoppingCartException e) {
158
                log.error("Unable to delete item from cart: ", e);
9713 anupam.sin 159
                errorMsg = "Unable to delete item. Please try again.";
9570 anupam.sin 160
            } catch (TException e) {
9676 anupam.sin 161
                log.error("Unable to delete item from cart: ", e);
9713 anupam.sin 162
                errorMsg = "Unable to delete item. Please try again.";
9570 anupam.sin 163
            } catch (Exception e) {
9676 anupam.sin 164
                log.error("Unable to delete item from cart: ", e);
9713 anupam.sin 165
                errorMsg = "Unable to delete item. Please try again.";
9570 anupam.sin 166
            }
167
        }
9676 anupam.sin 168
        return index();
9570 anupam.sin 169
    }
9676 anupam.sin 170
 
171
    //PUT
9570 anupam.sin 172
    public String update() {
9676 anupam.sin 173
        if(quantity <= 0)   {
174
            log.info("Not valid item quantity. Unable to change item quantity.");
9713 anupam.sin 175
            errorMsg = "Invalid item quantity";
9676 anupam.sin 176
        } else  {
9709 anupam.sin 177
            if(updateItemQuantityInCart(id, itemId, quantity))    {
9676 anupam.sin 178
                return index();
179
            }
180
        }
181
        return index();
9570 anupam.sin 182
    }
183
 
184
    private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
185
        try {
11535 amit.gupta 186
            getClient().addItemToCart(cartId, itemId, quantity, -1);
9570 anupam.sin 187
            return true;
188
        } catch (ShoppingCartException e) {
189
            log.error("Unable to update the item quantity in the cart: ", e);
9713 anupam.sin 190
            errorMsg = "Unable to change quantity. Please try again.";
9570 anupam.sin 191
        } catch (TException e) {
192
            log.error("Unable to update the item quantity in the cart: ", e);
9713 anupam.sin 193
            errorMsg = "Unable to change quantity. Please try again.";
9570 anupam.sin 194
        } catch (Exception e) {
195
            log.error("Unable to update the item quantity in the cart: ", e);
9713 anupam.sin 196
            errorMsg = "Unable to change quantity. Please try again.";
9570 anupam.sin 197
        }
198
        return false;
199
    }
9676 anupam.sin 200
 
9570 anupam.sin 201
    public String insureItem() {
9697 anupam.sin 202
        insuranceResult = "";
203
        try {
11535 amit.gupta 204
            if(getClient().insureItem(itemId, id, toInsure, insuranceType)) {
9697 anupam.sin 205
                setInsuranceResult("SUCCESS");
206
            } else {
207
                setInsuranceResult("FAILURE");
208
            }
209
        } catch (Exception e) {
9709 anupam.sin 210
            log.error("Unable to insure item : " + itemId + " for cart : " + id, e);
9697 anupam.sin 211
            setInsuranceResult("FAILURE");
212
        }
9570 anupam.sin 213
        return "insurance-result";
214
    }
9713 anupam.sin 215
 
216
    public String edit()  {
217
        String action = request.getParameter("action");
218
        PromotionClient promotionServiceClient = null;
219
        try {
220
            if(action == null || action.isEmpty())  {
221
                errorMsg = "Invalid Request Action";
222
                return index();
223
            }
224
            String couponCode = request.getParameter("coupon_code");
225
 
226
            if (action.equalsIgnoreCase("applycoupon"))   {
227
                if (couponCode == null || couponCode.isEmpty()) {
228
                    errorMsg = "Coupon Code field cannot be left empty";
229
                    return index();
230
                }
231
 
232
                promotionServiceClient = new PromotionClient();
233
                PromotionService.Client promotionClient = promotionServiceClient.getClient();
234
 
11768 amit.gupta 235
                Cart cart = promotionClient.applyCoupon(couponCode, id);
11823 amit.gupta 236
            	errorMsg = "Coupon successfully applied";
11861 amit.gupta 237
            	if(cart.getMessage() != null && !cart.getMessage().equals("")){
11823 amit.gupta 238
                	errorMsg = errorMsg +  ", " + cart.getMessage();
11768 amit.gupta 239
                }
9713 anupam.sin 240
            }
241
            else if (action.equals("removecoupon"))    {
11535 amit.gupta 242
                getClient().removeCoupon(id);
9713 anupam.sin 243
            }
244
        } catch (PromotionException e) {
245
            log.info("Invalid coupon: " + e.getMessage());
11823 amit.gupta 246
            errorMsg = e.getMessage();
9713 anupam.sin 247
        } catch (Exception e) {
248
            log.error("Unable to apply or remove coupon", e);
249
            errorMsg = "Unable to apply or remove coupon";
250
        }
251
        return index();
252
    }
9808 anupam.sin 253
 
254
    public String changeAddress() {
255
        long addressId;
256
        if(request.getParameter("addressId") == null || request.getParameter("addressId").isEmpty()) {
257
            errorMsg = "Null or empty addressId";
258
            return index();
259
        } else {
9815 anupam.sin 260
            addressId = Long.parseLong(request.getParameter("addressId"));
9808 anupam.sin 261
        }
262
 
263
        try {
9815 anupam.sin 264
            if(request.getParameter("addressType").equalsIgnoreCase("store")) {
11535 amit.gupta 265
                getClient().addStoreToCart(id, addressId);
9815 anupam.sin 266
            } else if (request.getParameter("addressType").equalsIgnoreCase("home")){
11535 amit.gupta 267
                getClient().addAddressToCart(id, addressId);
9808 anupam.sin 268
            } else {
269
                errorMsg = "Invalid addressType. It can only be set to home or store.";
270
            }
271
        } catch(Exception e) {
272
            log.error("Unable to change address", e);
273
        }
274
        return index();
275
    }
9570 anupam.sin 276
 
277
    public long getItemId(){
278
        return this.itemId;
279
    }
280
 
9684 amit.gupta 281
    public void setItemId(long itemId){
282
    	this.itemId = itemId;
283
    }
284
 
9570 anupam.sin 285
    public String getTotalAmount() {
286
        return totalamount;
287
    }
288
 
289
    public String getPinCode() {
290
        return pincode;
291
    }
292
 
293
    public String getCouponCode()  {
294
        return couponCode;
295
    }
296
 
297
    public String getDiscountedAmount()   {
298
        return discountedAmount;
299
    }
300
 
301
    public String getErrorMsg()    {
302
        return errorMsg;
303
    }
304
 
9576 anupam.sin 305
//    public long getNumberOfItems(){
306
//        return userinfo.getTotalItems();
307
//    }
9570 anupam.sin 308
 
309
    public String getCartMsg(){
310
        if(cartMsg.equals("")){
311
            return null;
312
        }
313
        return cartMsg;
314
    }
315
 
316
    public String getSnippets(){
317
        String snippets = "";
318
        CatalogClient csc;
319
        try {
320
            csc = new CatalogClient();
321
            List<Long> similarItems = csc.getClient().getSimilarItemsCatalogIds(0, 4, itemId);
322
            for(Long catalogId: similarItems){
9602 amit.gupta 323
                snippets = snippets + ContentServingService.getSnippet(SnippetType.WIDGET_SNIPPET, catalogId+"", -1);
9570 anupam.sin 324
            }
325
        } catch (Exception e) {
326
            log.error("Unable to initialise Catalogservice Client");
327
        }       
328
        return snippets;
329
    }
330
 
331
    @Override
332
    public void setParameters(Map<String, String[]> parameters) {
333
        this.reqparams = parameters;    
334
    }
335
 
9576 anupam.sin 336
//    @Override
337
//    public String getHeaderSnippet() {
338
//        String url = request.getQueryString();
339
//        if (url == null) {
340
//            url = "";
341
//        } else {
342
//            url = "?" + url;
343
//        }
344
//        url = request.getRequestURI() + url;
345
//        return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , 0, false);
346
//    }
9570 anupam.sin 347
 
9576 anupam.sin 348
//    public boolean isUserLoggedIn() {
349
//        return userinfo.isLoggedIn();
350
//    }
9570 anupam.sin 351
 
352
    public void setVariationId(String uri)  {
353
        if (uri.equals("/cart1"))   {
354
            this.variationId = 1;
355
        }
356
    }
357
 
358
    public int getVariationId() {
359
        return this.variationId;
360
    }
361
 
362
    public String getActionMessage(){
363
        if(cartMsg.contains("out of stock")){
364
            return "Notify me when this product is in stock.";
365
        }else {
366
            return "Notify me when this product is available.";
367
        }
368
    }
369
 
370
    public String getOfferNote(){
371
        String note = null;
372
        if(cartMsg.contains("out of stock")){
373
            return note;
374
        }
375
        else {
376
            try {
377
                CatalogClient catalogServiceClient = new CatalogClient();
378
                Client catalogClient = catalogServiceClient.getClient();
379
                Item it = catalogClient.getItem(itemId);
380
                note = it.getBestDealText();
381
            } catch (Exception e)  {
382
                log.error("Unable to get the offertext because of: ", e);
383
            }
384
        }
385
        return note;
386
    }
387
 
388
    public String getInsuranceResult() {
389
        return insuranceResult;
390
    }
391
 
392
    public void setInsuranceResult(String insuranceResult) {
393
        this.insuranceResult = insuranceResult;
394
    }
395
 
396
    public void setToInsure(boolean toInsure) {
397
        this.toInsure = toInsure;
398
    }
399
 
400
    public boolean getToInsure() {
401
        return toInsure;
402
    }
403
 
9709 anupam.sin 404
    public long getId() {
405
        return id;
9570 anupam.sin 406
    }
407
 
9709 anupam.sin 408
    public void setId(long id) {
409
        this.id = id;
9570 anupam.sin 410
    }
9667 anupam.sin 411
 
412
 
413
    public void setCartPojoJson(String cartPojoJson) {
414
        this.cartPojoJson = cartPojoJson;
415
    }
416
 
417
 
418
    public String getCartPojoJson() {
419
        return cartPojoJson;
420
    }
17782 amit.gupta 421
 
422
 
423
    public String validateCart() {
424
    	if(!userinfo.isPrivateDealUser()){
425
    		cartPojoJson = "{\"response\":\"error\", \"message\":\"Invalid request.\"}";
426
    	} else {
427
    		String cartMap = request.getParameter("cartMap");
428
    		if(StringUtils.isEmpty(cartMap))
429
    			cartPojoJson = "{\"response\":\"error\", \"message\":\"Empty Cart.\"}";
430
    		else {
431
    			try{
432
    				List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
433
    				JSONObject jsonObj = new JSONObject(cartMap);
434
    				JSONArray cartItems = jsonObj.getJSONArray("cartItems");
435
    				if (cartItems==null || cartItems.length()==0){
436
    					cartPojoJson = "{\"response\":\"error\", \"message\":\"Empty Cart.\"}";
437
    				} else {
438
    					for (int i=0; i< cartItems.length(); i++) {
439
    						JSONObject obj = cartItems.getJSONObject(i);
440
    						int itemId = obj.getInt("itemId");
441
    						Integer quantity = obj.getInt("quantity");
442
    						ItemQuantity iq = new ItemQuantity(itemId, quantity);
443
    						itemQuantities.add(iq);
444
    					}
445
    					userClient = getClient();
446
    					if (userClient.addItemsToCart(jsonObj.getLong("cartId"), itemQuantities, jsonObj.getString("couponCode"))){
447
    						log.info("Items added to cart Successfully");
448
    						//Now validate cart and provide appropriate response.
449
    						String cartString = userClient.validateCartNew(id, userinfo.getPincode(), -1);
450
    						JSONObject cartObj = new JSONObject(cartString);
451
    						JSONArray arr = cartObj.getJSONArray("cartItems");
452
    						int maxEstimate=0;
453
    						boolean allSame=true;
454
    						for (int j=0; j<arr.length(); j++){
455
    							JSONObject itemObj = arr.getJSONObject(j);
456
    							ProductPojo pp = PojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
457
    							if(allSame){
458
    								allSame = maxEstimate==0 || maxEstimate==itemObj.getInt("estimate");
459
    							}
460
    							if(itemObj.getInt("estimate")>maxEstimate){
461
    								maxEstimate = itemObj.getInt("estimate");
462
    							}
463
    							cartObj.put("imageUrl", pp.getImageUrl());
464
    							cartObj.put("title", pp.getTitle());
465
    						}
466
    						cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate,DeliveryType.COD));
467
    						cartObj.put("sameEstimate", allSame);
468
    						cartPojoJson = new Gson().toJson(cartObj);
469
    					} else {
470
    						cartPojoJson = "{\"response\":\"error\", \"message\":\"Problem occurred while updating cart\"}";
471
    					}
472
    				}
473
    			}catch(Exception e) {
474
    				cartPojoJson = "{\"response\":\"error\", \"message\":\"Something went wrong while validation\"}";
475
    				e.printStackTrace();
476
    			}
477
    		}
478
 
479
    	}
480
    	setResultJson(cartPojoJson);
481
    	return "index";
482
    }
9676 anupam.sin 483
 
484
    public void setQuantity(long quantity) {
485
        this.quantity = quantity;
486
    }
487
 
488
    public long getQuantity() {
489
        return quantity;
490
    }
9697 anupam.sin 491
 
492
    public int getInsuranceType() {
493
        return insuranceType;
494
    }
495
 
496
    public void setInsuranceType(int insuranceType) {
497
        this.insuranceType = insuranceType;
498
    }
11983 amit.gupta 499
 
12021 amit.gupta 500
	public void setPrivateDealUser(boolean privateDealUser) {
501
		this.privateDealUser = privateDealUser;
11983 amit.gupta 502
	}
503
 
504
	public boolean isPrivateDealUser() {
12021 amit.gupta 505
		return privateDealUser;
11983 amit.gupta 506
	}
507
 
12022 amit.gupta 508
	public void setAutoApplicationOff(boolean autoApplicationOff) {
509
		this.autoApplicationOff = autoApplicationOff;
11983 amit.gupta 510
	}
511
 
12022 amit.gupta 512
	public boolean isAutoApplicationOff() {
513
		return autoApplicationOff;
11983 amit.gupta 514
	}
9570 anupam.sin 515
}