Subversion Repositories SmartDukaan

Rev

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