Subversion Repositories SmartDukaan

Rev

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