Subversion Repositories SmartDukaan

Rev

Rev 9576 | Go to most recent revision | Details | Last modification | View Log | RSS feed

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