Subversion Repositories SmartDukaan

Rev

Rev 9602 | Rev 9667 | 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();
9602 amit.gupta 77
                List<String> cartResponse  = userClient.validateCart(cartId, -1);
9570 anupam.sin 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("")){
9602 amit.gupta 128
                    cartMsg = userClient.addItemToCart(cartId, itemId, 1, -1);
9570 anupam.sin 129
                }else{
9602 amit.gupta 130
                    userClient.addItemToCart(cartId, itemId, 1, -1);
9570 anupam.sin 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
        return "success";
141
    }       
142
 
143
 
144
    // DELETE /entity
145
    public String destroy() {
9576 anupam.sin 146
//        log.info("CartController.destroy");
147
//        printParams();
148
//        log.info("item id is " + this.request.getParameter("productid"));
149
//        
150
//        String itemIdString = this.request.getParameter("productid");
151
//        itemId = Long.parseLong(itemIdString);
152
//
153
//        if(userinfo.getCartId() == -1)  {
154
//            log.info("Cart does not exist. Nothing to delete.");
155
//        } else  {
156
//            if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))  {
157
//                updateUserSessionInfo(userinfo.getCartId());
158
//                DataLogger.logData(EventType.DELETE_FROM_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
159
//                        Long.toString(userinfo.getCartId()), itemIdString);
160
//                return "redirect";
161
//            }
162
//        }
9570 anupam.sin 163
        return "redirect";
164
    }
165
 
166
    // DELETE /entity
167
    public String update() {
9576 anupam.sin 168
//        log.info("CartController.update");
169
//        printParams();
170
//        log.info("item id is " + this.request.getParameter("productid"));
171
//        log.info("item quantity is " + this.request.getParameter("quantity"));
172
//        String itemIdString = this.request.getParameter("productid");
173
//        String quantityString = this.request.getParameter("quantity");
174
//        long itemId = Long.parseLong(itemIdString);
175
//        long quantity = Long.parseLong(quantityString);
176
//
177
//        if(quantity <= 0)   {
178
//            log.info("Not valid item quantity. Unable to change item quantity.");
179
//        } else  {
180
//            if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity))    {
181
//                DataLogger.logData(EventType.UPDATE_CART_QUANTITY, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
182
//                        Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
183
//                return "redirect";
184
//            }
185
//        }
186
//        DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
187
//                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
188
//        addActionError("Unable to update the quantity");
9570 anupam.sin 189
        return "redirect";
190
    }
191
 
192
    public void printParams(){
193
        for(String param : reqparams.keySet()) {
194
            log.info("param name is " + param);
195
            log.info("param first is " + reqparams.get(param)[0]);
196
        }
197
        log.info(this.reqparams);
198
    }
199
 
200
    private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
201
        try {
202
            UserClient userContextServiceClient = new UserClient();
203
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
204
 
9602 amit.gupta 205
            userClient.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);
209
        } catch (TException e) {
210
            log.error("Unable to update the item quantity in the cart: ", e);
211
        } catch (Exception e) {
212
            log.error("Unable to update the item quantity in the cart: ", e);
213
        }
214
        return false;
215
    }
216
 
217
    private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
218
        try {
219
            UserClient userContextServiceClient = new UserClient();
220
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
221
 
222
            userClient.deleteItemFromCart(cartId, catalogItemId);
223
            return true;
224
        } catch (ShoppingCartException e) {
225
            log.error("Unable to delete item from cart: ", e);
226
        } catch (TException e) {
227
            log.error("Unable to delete item from cart: ", e);
228
        } catch (Exception e) {
229
            log.error("Unable to delete item from cart: ", e);
230
        }
231
 
232
        return false;
233
    }
234
 
235
    private void updateUserSessionInfo(long cartId) {
9576 anupam.sin 236
//        UserClient userContextServiceClient = null;
237
//        try {
238
//            userContextServiceClient = new UserClient();
239
//            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
240
//            Cart cart = userClient.getCart(cartId);
241
//            userinfo.setTotalItems(cart.getLinesSize());
242
//            userinfo.setTotalAmount(cart.getTotalPrice());
243
//        } catch (ShoppingCartException e) {
244
//            log.error("Unable to get the cart from service: ", e);
245
//        } catch (TException e) {
246
//            log.error("Unable to get the cart from service: ", e);
247
//        } catch (Exception e) {
248
//            log.error("Unable to get the cart from service: ", e);
249
//        }
9570 anupam.sin 250
    }
251
 
252
    public List<Map<String,String>> getCartItems() {
253
        List<Map<String,String>> items = null;
9576 anupam.sin 254
//
255
//        UserClient userServiceClient = null;
256
//        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
257
//        CatalogClient catalogServiceClient  = null;
258
//        in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = null;
259
//
260
//        FormattingUtils formattingUtils = new FormattingUtils();
261
//        
262
//        try    {
263
//            catalogServiceClient = new CatalogClient();
264
//            catalogClient = catalogServiceClient.getClient();
265
//            userServiceClient = new UserClient();
266
//            userClient = userServiceClient.getClient();
267
//            
268
//            pincode = userClient.getDefaultPincode(userinfo.getUserId());
269
//            Cart cart = userClient.getCart(userinfo.getCartId());
270
//            List<Line> lineItems = cart.getLines();
271
//            double totalInsuranceAmount = 0.0;
272
//            boolean isAnyItemInsured = false;
273
//            if(lineItems.size() != 0)  {
274
//                items = new ArrayList<Map<String,String>>();
275
//
276
//                for (Line line : lineItems)    {
277
//                    Map<String, String> itemdetail = new HashMap<String, String>();
278
//                    
279
//                    double insuranceAmount = 0;
9602 amit.gupta 280
//                    Item item = catalogClient.getItemForSource(line.getItemId(), -1);
9576 anupam.sin 281
//                    Insurer insurer = null;
282
//                    
283
//                    if(line.getInsurer() != 0) {
284
//                        insuranceAmount = catalogClient.getInsuranceAmount(item.getId(), 
285
//                                (line.getDiscountedPrice() == 0 ? line.getActualPrice() : line.getDiscountedPrice()),
286
//                                item.getPreferredInsurer(), 
287
//                                (long)line.getQuantity());
288
//                        isAnyItemInsured = true;
289
//                    } else if (item.getPreferredInsurer() != 0) {
290
//                        insuranceAmount = catalogClient.getInsuranceAmount(item.getId(), 
291
//                                (line.getDiscountedPrice() == 0 ? line.getActualPrice() : line.getDiscountedPrice()),
292
//                                item.getPreferredInsurer(), 
293
//                                (long)line.getQuantity());
294
//                        //Insurer insurer = catalogClient.getInsurer(item.getPreferredInsurer());
295
//                    } else {
296
//                        insuranceAmount = 0;
297
//                    }
298
//                    
299
//                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
300
//                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
301
//                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" );
302
//                    
303
//                    String itemColor = "";
304
//                    if(item.getColor() != null && !item.getColor().trim().equals("NA"))
305
//                        itemColor = "Color - " + item.getColor();
306
//                    
307
//                    itemdetail.put("ITEM_NAME", itemName);
308
//                    itemdetail.put("ITEM_COLOR", itemColor);
309
//                    itemdetail.put("ITEM_ID", line.getItemId() + "");
310
//                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
311
//                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
312
//                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
313
//                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
314
//                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
315
//                    itemdetail.put("SHIPPING_TIME", EstimateController.getDeliveryDateString(line.getEstimate(), DeliveryType.PREPAID));
316
//                    itemdetail.put("COD_SHIPPING_TIME", EstimateController.getDeliveryDateString(line.getEstimate(), DeliveryType.COD));
317
//                    itemdetail.put("BEST_DEAL_TEXT", item.getBestDealText());
318
//                    itemdetail.put("IS_INSURABLE", item.getPreferredInsurer() + "");
319
//                    itemdetail.put("IS_INSURED", (line.getInsurer() == 0 ? false : true) + "");
320
//                    itemdetail.put("INSURANCE_AMOUNT", insuranceAmount + "");
321
//
322
//                    totalInsuranceAmount += insuranceAmount;
323
//                    items.add(itemdetail);
324
//                }
9570 anupam.sin 325
//            }
9576 anupam.sin 326
//            
327
////            if(isAnyItemInsured == false) {
328
////                totalamount = formattingUtils.formatPrice(cart.getTotalPrice() + totalInsuranceAmount);
329
////                discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice() + totalInsuranceAmount);
330
////            } else {
331
//                totalamount = formattingUtils.formatPrice(cart.getTotalPrice());
332
//                discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
333
////            }
334
//            
335
//            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
336
//        } catch (Exception e){
337
//            log.error("Unable to get the cart details becasue of: ", e);
338
//        }
9570 anupam.sin 339
        return items;
340
    }
341
 
342
    public String insureItem() {
9576 anupam.sin 343
//        //TODO : Call a method in userservice that insures the item.
344
//        insuranceResult = "";
345
//        try {
346
//            UserContextService.Client usc = new UserClient().getClient();
347
//            if(usc.insureItem(productId, userinfo.getCartId(), toInsure)) {
348
//                setInsuranceResult("SUCCESS");
349
//            } else {
350
//                setInsuranceResult("FAILURE");
351
//            }
352
//        } catch (Exception e) {
353
//            log.error("Unable to insure item : " + productId + " for cart : " + userinfo.getCartId(), e);
354
//            setInsuranceResult("FAILURE");
355
//        }
9570 anupam.sin 356
        return "insurance-result";
357
    }
358
 
359
    public long getItemId(){
360
        return this.itemId;
361
    }
362
 
363
    public String getTotalAmount() {
364
        return totalamount;
365
    }
366
 
367
    public String getPinCode() {
368
        return pincode;
369
    }
370
 
371
    public String getCouponCode()  {
372
        return couponCode;
373
    }
374
 
375
    public String getDiscountedAmount()   {
376
        return discountedAmount;
377
    }
378
 
379
    public String getErrorMsg()    {
380
        return errorMsg;
381
    }
382
 
9576 anupam.sin 383
//    public long getNumberOfItems(){
384
//        return userinfo.getTotalItems();
385
//    }
9570 anupam.sin 386
 
387
    public String getCartMsg(){
388
        if(cartMsg.equals("")){
389
            return null;
390
        }
391
        return cartMsg;
392
    }
393
 
394
    public String getSnippets(){
395
        String snippets = "";
396
        CatalogClient csc;
397
        try {
398
            csc = new CatalogClient();
399
            List<Long> similarItems = csc.getClient().getSimilarItemsCatalogIds(0, 4, itemId);
400
            for(Long catalogId: similarItems){
9602 amit.gupta 401
                snippets = snippets + ContentServingService.getSnippet(SnippetType.WIDGET_SNIPPET, catalogId+"", -1);
9570 anupam.sin 402
            }
403
        } catch (Exception e) {
404
            log.error("Unable to initialise Catalogservice Client");
405
        }       
406
        return snippets;
407
    }
408
 
409
    @Override
410
    public void setParameters(Map<String, String[]> parameters) {
411
        this.reqparams = parameters;    
412
    }
413
 
9576 anupam.sin 414
//    @Override
415
//    public String getHeaderSnippet() {
416
//        String url = request.getQueryString();
417
//        if (url == null) {
418
//            url = "";
419
//        } else {
420
//            url = "?" + url;
421
//        }
422
//        url = request.getRequestURI() + url;
423
//        return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , 0, false);
424
//    }
9570 anupam.sin 425
 
9576 anupam.sin 426
//    public boolean isUserLoggedIn() {
427
//        return userinfo.isLoggedIn();
428
//    }
9570 anupam.sin 429
 
430
    public void setVariationId(String uri)  {
431
        if (uri.equals("/cart1"))   {
432
            this.variationId = 1;
433
        }
434
    }
435
 
436
    public int getVariationId() {
437
        return this.variationId;
438
    }
439
 
440
    public String getActionMessage(){
441
        if(cartMsg.contains("out of stock")){
442
            return "Notify me when this product is in stock.";
443
        }else {
444
            return "Notify me when this product is available.";
445
        }
446
    }
447
 
448
    public String getOfferNote(){
449
        String note = null;
450
        if(cartMsg.contains("out of stock")){
451
            return note;
452
        }
453
        else {
454
            try {
455
                CatalogClient catalogServiceClient = new CatalogClient();
456
                Client catalogClient = catalogServiceClient.getClient();
457
                Item it = catalogClient.getItem(itemId);
458
                note = it.getBestDealText();
459
            } catch (Exception e)  {
460
                log.error("Unable to get the offertext because of: ", e);
461
            }
462
        }
463
        return note;
464
    }
465
 
466
    public String getInsuranceResult() {
467
        return insuranceResult;
468
    }
469
 
470
    public void setInsuranceResult(String insuranceResult) {
471
        this.insuranceResult = insuranceResult;
472
    }
473
 
474
    public void setToInsure(boolean toInsure) {
475
        this.toInsure = toInsure;
476
    }
477
 
478
    public boolean getToInsure() {
479
        return toInsure;
480
    }
481
 
482
    public long getProductId() {
483
        return productId;
484
    }
485
 
486
    public void setProductId(long productId) {
487
        this.productId = productId;
488
    }
489
 
490
    public long getCartId() {
491
        return cartId;
492
    }
493
 
494
    public void setCartId(long cartId) {
495
        this.cartId = cartId;
496
    }
497
}