Subversion Repositories SmartDukaan

Rev

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