Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
9576 anupam.sin 1
package in.shop2020.mobileapi.serving.controllers;
9570 anupam.sin 2
 
3
import in.shop2020.datalogger.EventType;
9577 anupam.sin 4
import in.shop2020.mobileapi.serving.services.ContentServingService;
5
import in.shop2020.mobileapi.serving.utils.SnippetType;
9570 anupam.sin 6
import in.shop2020.model.v1.catalog.CatalogService.Client;
7
import in.shop2020.model.v1.catalog.Item;
8
import in.shop2020.model.v1.user.Cart;
9
import in.shop2020.model.v1.user.ShoppingCartException;
10
import in.shop2020.model.v1.user.UserContextService;
11
import in.shop2020.thrift.clients.CatalogClient;
12
import in.shop2020.thrift.clients.UserClient;
13
import in.shop2020.utils.DataLogger;
14
 
15
import java.util.List;
16
import java.util.Map;
17
import java.util.StringTokenizer;
18
 
19
import org.apache.commons.lang.StringUtils;
20
import org.apache.log4j.Logger;
21
import org.apache.struts2.convention.annotation.Action;
22
import org.apache.struts2.convention.annotation.Actions;
23
import org.apache.struts2.convention.annotation.InterceptorRef;
24
import org.apache.struts2.convention.annotation.Result;
25
import org.apache.struts2.convention.annotation.Results;
26
import org.apache.struts2.interceptor.ParameterAware;
27
import org.apache.thrift.TException;
28
 
29
 
30
@Results({
31
    @Result(name = "index", location = "cart-index.vm"),
32
    @Result(name="redirect", type="redirectAction", params = {"actionName" , "cart"}),
33
    @Result(name="failure", location="cart-failure.vm"),
34
    @Result(name="success", location="cart-success.vm")
35
})
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;
59
    private long productId;
60
 
61
    private long cartId;
62
 
63
    public CartController(){
64
        super();
65
    }
66
 
9594 anupam.sin 67
 
9570 anupam.sin 68
    public String index()  {
69
        this.setVariationId(request.getRequestURI());
70
        log.info(this.getVariationId());
71
 
72
        if(cartId != -1){
73
            try {
74
                UserContextService.Client userClient = (new UserClient()).getClient();
75
                Cart cart = userClient.getCurrentCart(userinfo.getUserId());
76
                cartId = cart.getId();
77
                List<String> cartResponse  = userClient.validateCart(cartId, sourceId);
78
                errorMsg = cartResponse.get(0);
79
                if(StringUtils.isNotEmpty(cartResponse.get(1))) {
80
                    addActionMessage(cartResponse.get(1));
81
                }
82
                log.info("Cart Change/EMI Message rcvd from the service is:" + errorMsg);
83
            } catch (Exception e) {
84
                // This exception can be ignored for showing the cart. Not so
85
                // innocent when this occurs at the time of checkout or when the
86
                // user is proceeding to pay.
87
                log.warn("Unable to validate the cart: ", e);
88
            }
89
        }
90
        return "index";
91
    }
92
 
93
    // POST /entity
94
 
9594 anupam.sin 95
 
9570 anupam.sin 96
    public String create() {
97
        log.info("CartController.create");
98
 
99
        printParams();
100
 
101
        long userId = userinfo.getUserId();
102
 
103
        log.info("user id is " + userId);
104
        log.info("cart id is " + cartId);
105
 
106
        log.info("item id is " + this.reqparams.get("productid"));
107
 
108
        String itemIds = "";
109
        if (this.reqparams.get("productid") != null) {
110
            itemIds = this.reqparams.get("productid")[0];
111
        }else{
112
            return "failure";
113
        }
114
 
115
        StringTokenizer tokenizer = new StringTokenizer(itemIds, "_");
116
        while (tokenizer.hasMoreTokens()) {
117
            itemId = Long.parseLong(tokenizer.nextToken());
118
 
119
            try {
120
                UserClient userServiceClient = new UserClient();
121
                UserContextService.Client userClient = userServiceClient.getClient();
122
                if (cartId == 0){
123
                    cartId = userClient.getUserById(userId).getActiveCartId();
124
                }
125
                // If we add multiple items to cart and get some message from service, 
126
                // first message to be preserved and presented to the user.
127
                if(cartMsg.equals("")){
128
                    cartMsg = userClient.addItemToCart(cartId, itemId, 1, sourceId);
129
                }else{
130
                    userClient.addItemToCart(cartId, itemId, 1, sourceId);
131
                }
132
                int totalItems = userClient.getCart(cartId).getLinesSize();
133
            } catch (TException e) {
134
                log.error("Unable to create or add to cart because of: ", e);
135
            } catch (Exception e) {
136
                log.error("Unable to create or add to cart because of: ", e);
137
            }
138
 
139
        }
140
        DataLogger.logData(EventType.ADD_TO_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
141
                Long.toString(cartId), itemIds);
142
        return "success";
143
    }       
144
 
145
 
146
    // DELETE /entity
147
    public String destroy() {
9576 anupam.sin 148
//        log.info("CartController.destroy");
149
//        printParams();
150
//        log.info("item id is " + this.request.getParameter("productid"));
151
//        
152
//        String itemIdString = this.request.getParameter("productid");
153
//        itemId = Long.parseLong(itemIdString);
154
//
155
//        if(userinfo.getCartId() == -1)  {
156
//            log.info("Cart does not exist. Nothing to delete.");
157
//        } else  {
158
//            if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))  {
159
//                updateUserSessionInfo(userinfo.getCartId());
160
//                DataLogger.logData(EventType.DELETE_FROM_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
161
//                        Long.toString(userinfo.getCartId()), itemIdString);
162
//                return "redirect";
163
//            }
164
//        }
9570 anupam.sin 165
        return "redirect";
166
    }
167
 
168
    // DELETE /entity
169
    public String update() {
9576 anupam.sin 170
//        log.info("CartController.update");
171
//        printParams();
172
//        log.info("item id is " + this.request.getParameter("productid"));
173
//        log.info("item quantity is " + this.request.getParameter("quantity"));
174
//        String itemIdString = this.request.getParameter("productid");
175
//        String quantityString = this.request.getParameter("quantity");
176
//        long itemId = Long.parseLong(itemIdString);
177
//        long quantity = Long.parseLong(quantityString);
178
//
179
//        if(quantity <= 0)   {
180
//            log.info("Not valid item quantity. Unable to change item quantity.");
181
//        } else  {
182
//            if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity))    {
183
//                DataLogger.logData(EventType.UPDATE_CART_QUANTITY, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
184
//                        Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
185
//                return "redirect";
186
//            }
187
//        }
188
//        DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
189
//                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
190
//        addActionError("Unable to update the quantity");
9570 anupam.sin 191
        return "redirect";
192
    }
193
 
194
    public void printParams(){
195
        for(String param : reqparams.keySet()) {
196
            log.info("param name is " + param);
197
            log.info("param first is " + reqparams.get(param)[0]);
198
        }
199
        log.info(this.reqparams);
200
    }
201
 
202
    private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
203
        try {
204
            UserClient userContextServiceClient = new UserClient();
205
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
206
 
207
            userClient.addItemToCart(cartId, itemId, quantity, sourceId);
208
            return true;
209
        } catch (ShoppingCartException e) {
210
            log.error("Unable to update the item quantity in the cart: ", e);
211
        } catch (TException e) {
212
            log.error("Unable to update the item quantity in the cart: ", e);
213
        } catch (Exception e) {
214
            log.error("Unable to update the item quantity in the cart: ", e);
215
        }
216
        return false;
217
    }
218
 
219
    private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
220
        try {
221
            UserClient userContextServiceClient = new UserClient();
222
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
223
 
224
            userClient.deleteItemFromCart(cartId, catalogItemId);
225
            return true;
226
        } catch (ShoppingCartException e) {
227
            log.error("Unable to delete item from cart: ", e);
228
        } catch (TException e) {
229
            log.error("Unable to delete item from cart: ", e);
230
        } catch (Exception e) {
231
            log.error("Unable to delete item from cart: ", e);
232
        }
233
 
234
        return false;
235
    }
236
 
237
    private void updateUserSessionInfo(long cartId) {
9576 anupam.sin 238
//        UserClient userContextServiceClient = null;
239
//        try {
240
//            userContextServiceClient = new UserClient();
241
//            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
242
//            Cart cart = userClient.getCart(cartId);
243
//            userinfo.setTotalItems(cart.getLinesSize());
244
//            userinfo.setTotalAmount(cart.getTotalPrice());
245
//        } catch (ShoppingCartException e) {
246
//            log.error("Unable to get the cart from service: ", e);
247
//        } catch (TException e) {
248
//            log.error("Unable to get the cart from service: ", e);
249
//        } catch (Exception e) {
250
//            log.error("Unable to get the cart from service: ", e);
251
//        }
9570 anupam.sin 252
    }
253
 
254
    public List<Map<String,String>> getCartItems() {
255
        List<Map<String,String>> items = null;
9576 anupam.sin 256
//
257
//        UserClient userServiceClient = null;
258
//        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
259
//        CatalogClient catalogServiceClient  = null;
260
//        in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = null;
261
//
262
//        FormattingUtils formattingUtils = new FormattingUtils();
263
//        
264
//        try    {
265
//            catalogServiceClient = new CatalogClient();
266
//            catalogClient = catalogServiceClient.getClient();
267
//            userServiceClient = new UserClient();
268
//            userClient = userServiceClient.getClient();
269
//            
270
//            pincode = userClient.getDefaultPincode(userinfo.getUserId());
271
//            Cart cart = userClient.getCart(userinfo.getCartId());
272
//            List<Line> lineItems = cart.getLines();
273
//            double totalInsuranceAmount = 0.0;
274
//            boolean isAnyItemInsured = false;
275
//            if(lineItems.size() != 0)  {
276
//                items = new ArrayList<Map<String,String>>();
277
//
278
//                for (Line line : lineItems)    {
279
//                    Map<String, String> itemdetail = new HashMap<String, String>();
280
//                    
281
//                    double insuranceAmount = 0;
282
//                    Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
283
//                    Insurer insurer = null;
284
//                    
285
//                    if(line.getInsurer() != 0) {
286
//                        insuranceAmount = catalogClient.getInsuranceAmount(item.getId(), 
287
//                                (line.getDiscountedPrice() == 0 ? line.getActualPrice() : line.getDiscountedPrice()),
288
//                                item.getPreferredInsurer(), 
289
//                                (long)line.getQuantity());
290
//                        isAnyItemInsured = true;
291
//                    } else if (item.getPreferredInsurer() != 0) {
292
//                        insuranceAmount = catalogClient.getInsuranceAmount(item.getId(), 
293
//                                (line.getDiscountedPrice() == 0 ? line.getActualPrice() : line.getDiscountedPrice()),
294
//                                item.getPreferredInsurer(), 
295
//                                (long)line.getQuantity());
296
//                        //Insurer insurer = catalogClient.getInsurer(item.getPreferredInsurer());
297
//                    } else {
298
//                        insuranceAmount = 0;
299
//                    }
300
//                    
301
//                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
302
//                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
303
//                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" );
304
//                    
305
//                    String itemColor = "";
306
//                    if(item.getColor() != null && !item.getColor().trim().equals("NA"))
307
//                        itemColor = "Color - " + item.getColor();
308
//                    
309
//                    itemdetail.put("ITEM_NAME", itemName);
310
//                    itemdetail.put("ITEM_COLOR", itemColor);
311
//                    itemdetail.put("ITEM_ID", line.getItemId() + "");
312
//                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
313
//                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
314
//                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
315
//                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
316
//                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
317
//                    itemdetail.put("SHIPPING_TIME", EstimateController.getDeliveryDateString(line.getEstimate(), DeliveryType.PREPAID));
318
//                    itemdetail.put("COD_SHIPPING_TIME", EstimateController.getDeliveryDateString(line.getEstimate(), DeliveryType.COD));
319
//                    itemdetail.put("BEST_DEAL_TEXT", item.getBestDealText());
320
//                    itemdetail.put("IS_INSURABLE", item.getPreferredInsurer() + "");
321
//                    itemdetail.put("IS_INSURED", (line.getInsurer() == 0 ? false : true) + "");
322
//                    itemdetail.put("INSURANCE_AMOUNT", insuranceAmount + "");
323
//
324
//                    totalInsuranceAmount += insuranceAmount;
325
//                    items.add(itemdetail);
326
//                }
9570 anupam.sin 327
//            }
9576 anupam.sin 328
//            
329
////            if(isAnyItemInsured == false) {
330
////                totalamount = formattingUtils.formatPrice(cart.getTotalPrice() + totalInsuranceAmount);
331
////                discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice() + totalInsuranceAmount);
332
////            } else {
333
//                totalamount = formattingUtils.formatPrice(cart.getTotalPrice());
334
//                discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
335
////            }
336
//            
337
//            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
338
//        } catch (Exception e){
339
//            log.error("Unable to get the cart details becasue of: ", e);
340
//        }
9570 anupam.sin 341
        return items;
342
    }
343
 
344
    public String insureItem() {
9576 anupam.sin 345
//        //TODO : Call a method in userservice that insures the item.
346
//        insuranceResult = "";
347
//        try {
348
//            UserContextService.Client usc = new UserClient().getClient();
349
//            if(usc.insureItem(productId, userinfo.getCartId(), toInsure)) {
350
//                setInsuranceResult("SUCCESS");
351
//            } else {
352
//                setInsuranceResult("FAILURE");
353
//            }
354
//        } catch (Exception e) {
355
//            log.error("Unable to insure item : " + productId + " for cart : " + userinfo.getCartId(), e);
356
//            setInsuranceResult("FAILURE");
357
//        }
9570 anupam.sin 358
        return "insurance-result";
359
    }
360
 
361
    public long getItemId(){
362
        return this.itemId;
363
    }
364
 
365
    public String getTotalAmount() {
366
        return totalamount;
367
    }
368
 
369
    public String getPinCode() {
370
        return pincode;
371
    }
372
 
373
    public String getCouponCode()  {
374
        return couponCode;
375
    }
376
 
377
    public String getDiscountedAmount()   {
378
        return discountedAmount;
379
    }
380
 
381
    public String getErrorMsg()    {
382
        return errorMsg;
383
    }
384
 
9576 anupam.sin 385
//    public long getNumberOfItems(){
386
//        return userinfo.getTotalItems();
387
//    }
9570 anupam.sin 388
 
389
    public String getCartMsg(){
390
        if(cartMsg.equals("")){
391
            return null;
392
        }
393
        return cartMsg;
394
    }
395
 
396
    public String getSnippets(){
397
        String snippets = "";
398
        CatalogClient csc;
399
        try {
400
            csc = new CatalogClient();
401
            List<Long> similarItems = csc.getClient().getSimilarItemsCatalogIds(0, 4, itemId);
402
            for(Long catalogId: similarItems){
403
                snippets = snippets + ContentServingService.getSnippet(SnippetType.WIDGET_SNIPPET, catalogId+"", sourceId);
404
            }
405
        } catch (Exception e) {
406
            log.error("Unable to initialise Catalogservice Client");
407
        }       
408
        return snippets;
409
    }
410
 
411
    @Override
412
    public void setParameters(Map<String, String[]> parameters) {
413
        this.reqparams = parameters;    
414
    }
415
 
9576 anupam.sin 416
//    @Override
417
//    public String getHeaderSnippet() {
418
//        String url = request.getQueryString();
419
//        if (url == null) {
420
//            url = "";
421
//        } else {
422
//            url = "?" + url;
423
//        }
424
//        url = request.getRequestURI() + url;
425
//        return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , 0, false);
426
//    }
9570 anupam.sin 427
 
9576 anupam.sin 428
//    public boolean isUserLoggedIn() {
429
//        return userinfo.isLoggedIn();
430
//    }
9570 anupam.sin 431
 
432
    public void setVariationId(String uri)  {
433
        if (uri.equals("/cart1"))   {
434
            this.variationId = 1;
435
        }
436
    }
437
 
438
    public int getVariationId() {
439
        return this.variationId;
440
    }
441
 
442
    public String getActionMessage(){
443
        if(cartMsg.contains("out of stock")){
444
            return "Notify me when this product is in stock.";
445
        }else {
446
            return "Notify me when this product is available.";
447
        }
448
    }
449
 
450
    public String getOfferNote(){
451
        String note = null;
452
        if(cartMsg.contains("out of stock")){
453
            return note;
454
        }
455
        else {
456
            try {
457
                CatalogClient catalogServiceClient = new CatalogClient();
458
                Client catalogClient = catalogServiceClient.getClient();
459
                Item it = catalogClient.getItem(itemId);
460
                note = it.getBestDealText();
461
            } catch (Exception e)  {
462
                log.error("Unable to get the offertext because of: ", e);
463
            }
464
        }
465
        return note;
466
    }
467
 
468
    public String getInsuranceResult() {
469
        return insuranceResult;
470
    }
471
 
472
    public void setInsuranceResult(String insuranceResult) {
473
        this.insuranceResult = insuranceResult;
474
    }
475
 
476
    public void setToInsure(boolean toInsure) {
477
        this.toInsure = toInsure;
478
    }
479
 
480
    public boolean getToInsure() {
481
        return toInsure;
482
    }
483
 
484
    public long getProductId() {
485
        return productId;
486
    }
487
 
488
    public void setProductId(long productId) {
489
        this.productId = productId;
490
    }
491
 
492
    public long getCartId() {
493
        return cartId;
494
    }
495
 
496
    public void setCartId(long cartId) {
497
        this.cartId = cartId;
498
    }
499
}