Subversion Repositories SmartDukaan

Rev

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

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