Subversion Repositories SmartDukaan

Rev

Rev 9576 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;

import in.shop2020.datalogger.EventType;
import in.shop2020.logistics.DeliveryType;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.Insurer;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.Line;
import in.shop2020.model.v1.user.ShoppingCartException;
import in.shop2020.model.v1.user.UserContextService;
import in.shop2020.serving.services.ContentServingService;
import in.shop2020.serving.utils.FormattingUtils;
import in.shop2020.serving.utils.SnippetType;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.DataLogger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.thrift.TException;


@Results({
    @Result(name = "index", location = "cart-index.vm"),
    @Result(name="redirect", type="redirectAction", params = {"actionName" , "cart"}),
    @Result(name="failure", location="cart-failure.vm"),
    @Result(name="success", location="cart-success.vm")
})

public class CartController extends BaseController implements ParameterAware{
    
    private static final long serialVersionUID = 1L;
    private static Logger log = Logger.getLogger(Class.class);
    Map<String, String[]> reqparams = null;
    
    private int variationId = 0;
    private String totalamount;
    
    private String errorMsg = "";
    private String cartMsg = "";
    
    private String pincode = "110001";
    
    private String couponCode = null;
    
    private String discountedAmount;
    
    private long itemId;
    private String insuranceResult;
    
    private boolean toInsure;
    private long productId;
    
    private long cartId;
    
    public CartController(){
        super();
    }
    
     // GET /cart
    @Actions({
        @Action(value="cart", interceptorRefs={@InterceptorRef("myDefault")}),
        @Action(value="cart1", interceptorRefs={@InterceptorRef("myDefault")})
    })
    public String index()  {
        this.setVariationId(request.getRequestURI());
        log.info(this.getVariationId());
        
        if(cartId != -1){
            try {
                UserContextService.Client userClient = (new UserClient()).getClient();
                Cart cart = userClient.getCurrentCart(userinfo.getUserId());
                cartId = cart.getId();
                List<String> cartResponse  = userClient.validateCart(cartId, sourceId);
                errorMsg = cartResponse.get(0);
                if(StringUtils.isNotEmpty(cartResponse.get(1))) {
                    addActionMessage(cartResponse.get(1));
                }
                log.info("Cart Change/EMI Message rcvd from the service is:" + errorMsg);
            } catch (Exception e) {
                // This exception can be ignored for showing the cart. Not so
                // innocent when this occurs at the time of checkout or when the
                // user is proceeding to pay.
                log.warn("Unable to validate the cart: ", e);
            }
        }
        return "index";
    }

    // POST /entity

    @Action(value="addtocart",interceptorRefs={@InterceptorRef("createuser"),@InterceptorRef("myDefault")})
    public String create() {
        log.info("CartController.create");

        printParams();

        long userId = userinfo.getUserId();

        log.info("user id is " + userId);
        log.info("cart id is " + cartId);
        
        log.info("item id is " + this.reqparams.get("productid"));
        
        String itemIds = "";
        if (this.reqparams.get("productid") != null) {
            itemIds = this.reqparams.get("productid")[0];
        }else{
            return "failure";
        }
        
        StringTokenizer tokenizer = new StringTokenizer(itemIds, "_");
        while (tokenizer.hasMoreTokens()) {
            itemId = Long.parseLong(tokenizer.nextToken());

            try {
                UserClient userServiceClient = new UserClient();
                UserContextService.Client userClient = userServiceClient.getClient();
                if (cartId == 0){
                    cartId = userClient.getUserById(userId).getActiveCartId();
                }
                // If we add multiple items to cart and get some message from service, 
                // first message to be preserved and presented to the user.
                if(cartMsg.equals("")){
                    cartMsg = userClient.addItemToCart(cartId, itemId, 1, sourceId);
                }else{
                    userClient.addItemToCart(cartId, itemId, 1, sourceId);
                }
                int totalItems = userClient.getCart(cartId).getLinesSize();
            } catch (TException e) {
                log.error("Unable to create or add to cart because of: ", e);
            } catch (Exception e) {
                log.error("Unable to create or add to cart because of: ", e);
            }

        }
        DataLogger.logData(EventType.ADD_TO_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
                Long.toString(cartId), itemIds);
        return "success";
    }       


    // DELETE /entity
    public String destroy() {
        log.info("CartController.destroy");
        printParams();
        log.info("item id is " + this.request.getParameter("productid"));
        
        String itemIdString = this.request.getParameter("productid");
        itemId = Long.parseLong(itemIdString);

        if(userinfo.getCartId() == -1)  {
            log.info("Cart does not exist. Nothing to delete.");
        } else  {
            if(deleteItemFromCart(userinfo.getCartId(), itemId, userinfo.getUserId(), userinfo.isSessionId()))  {
                updateUserSessionInfo(userinfo.getCartId());
                DataLogger.logData(EventType.DELETE_FROM_CART, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
                        Long.toString(userinfo.getCartId()), itemIdString);
                return "redirect";
            }
        }
        return "redirect";
    }

    // DELETE /entity
    public String update() {
        log.info("CartController.update");
        printParams();
        log.info("item id is " + this.request.getParameter("productid"));
        log.info("item quantity is " + this.request.getParameter("quantity"));
        String itemIdString = this.request.getParameter("productid");
        String quantityString = this.request.getParameter("quantity");
        long itemId = Long.parseLong(itemIdString);
        long quantity = Long.parseLong(quantityString);

        if(quantity <= 0)   {
            log.info("Not valid item quantity. Unable to change item quantity.");
        } else  {
            if(updateItemQuantityInCart(userinfo.getCartId(), itemId, quantity))    {
                DataLogger.logData(EventType.UPDATE_CART_QUANTITY, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
                        Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
                return "redirect";
            }
        }
        DataLogger.logData(EventType.UPDATE_CART_QUANTITY_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
                    Long.toString(userinfo.getCartId()), Long.toString(itemId), Long.toString(quantity));
        addActionError("Unable to update the quantity");
        return "redirect";
    }
    
    public void printParams(){
        for(String param : reqparams.keySet()) {
            log.info("param name is " + param);
            log.info("param first is " + reqparams.get(param)[0]);
        }
        log.info(this.reqparams);
    }

    private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
        try {
            UserClient userContextServiceClient = new UserClient();
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();

            userClient.addItemToCart(cartId, itemId, quantity, sourceId);
            return true;
        } catch (ShoppingCartException e) {
            log.error("Unable to update the item quantity in the cart: ", e);
        } catch (TException e) {
            log.error("Unable to update the item quantity in the cart: ", e);
        } catch (Exception e) {
            log.error("Unable to update the item quantity in the cart: ", e);
        }
        return false;
    }
    
    private boolean deleteItemFromCart(long cartId, long catalogItemId, long userId, boolean isSessionId){
        try {
            UserClient userContextServiceClient = new UserClient();
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
            
            userClient.deleteItemFromCart(cartId, catalogItemId);
            return true;
        } catch (ShoppingCartException e) {
            log.error("Unable to delete item from cart: ", e);
        } catch (TException e) {
            log.error("Unable to delete item from cart: ", e);
        } catch (Exception e) {
            log.error("Unable to delete item from cart: ", e);
        }
        
        return false;
    }

    private void updateUserSessionInfo(long cartId) {
        UserClient userContextServiceClient = null;
        try {
            userContextServiceClient = new UserClient();
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
            Cart cart = userClient.getCart(cartId);
            userinfo.setTotalItems(cart.getLinesSize());
            userinfo.setTotalAmount(cart.getTotalPrice());
        } catch (ShoppingCartException e) {
            log.error("Unable to get the cart from service: ", e);
        } catch (TException e) {
            log.error("Unable to get the cart from service: ", e);
        } catch (Exception e) {
            log.error("Unable to get the cart from service: ", e);
        }
    }
    
    public List<Map<String,String>> getCartItems() {
        List<Map<String,String>> items = null;

        UserClient userServiceClient = null;
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
        CatalogClient catalogServiceClient  = null;
        in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = null;

        FormattingUtils formattingUtils = new FormattingUtils();
        
        try    {
            catalogServiceClient = new CatalogClient();
            catalogClient = catalogServiceClient.getClient();
            userServiceClient = new UserClient();
            userClient = userServiceClient.getClient();
            
            pincode = userClient.getDefaultPincode(userinfo.getUserId());
            Cart cart = userClient.getCart(userinfo.getCartId());
            List<Line> lineItems = cart.getLines();
            double totalInsuranceAmount = 0.0;
            boolean isAnyItemInsured = false;
            if(lineItems.size() != 0)  {
                items = new ArrayList<Map<String,String>>();

                for (Line line : lineItems)    {
                    Map<String, String> itemdetail = new HashMap<String, String>();
                    
                    double insuranceAmount = 0;
                    Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
                    Insurer insurer = null;
                    
                    if(line.getInsurer() != 0) {
                        insuranceAmount = catalogClient.getInsuranceAmount(item.getId(), 
                                (line.getDiscountedPrice() == 0 ? line.getActualPrice() : line.getDiscountedPrice()),
                                item.getPreferredInsurer(), 
                                (long)line.getQuantity());
                        isAnyItemInsured = true;
                    } else if (item.getPreferredInsurer() != 0) {
                        insuranceAmount = catalogClient.getInsuranceAmount(item.getId(), 
                                (line.getDiscountedPrice() == 0 ? line.getActualPrice() : line.getDiscountedPrice()),
                                item.getPreferredInsurer(), 
                                (long)line.getQuantity());
                        //Insurer insurer = catalogClient.getInsurer(item.getPreferredInsurer());
                    } else {
                        insuranceAmount = 0;
                    }
                    
                    String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
                                            + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
                                            + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" );
                    
                    String itemColor = "";
                    if(item.getColor() != null && !item.getColor().trim().equals("NA"))
                        itemColor = "Color - " + item.getColor();
                    
                    itemdetail.put("ITEM_NAME", itemName);
                    itemdetail.put("ITEM_COLOR", itemColor);
                    itemdetail.put("ITEM_ID", line.getItemId() + "");
                    itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
                    itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity()) + "");
                    itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
                    itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
                    itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice(((item.getSellingPrice() * line.getQuantity()))));
                    itemdetail.put("SHIPPING_TIME", EstimateController.getDeliveryDateString(line.getEstimate(), DeliveryType.PREPAID));
                    itemdetail.put("COD_SHIPPING_TIME", EstimateController.getDeliveryDateString(line.getEstimate(), DeliveryType.COD));
                    itemdetail.put("BEST_DEAL_TEXT", item.getBestDealText());
                    itemdetail.put("IS_INSURABLE", item.getPreferredInsurer() + "");
                    itemdetail.put("IS_INSURED", (line.getInsurer() == 0 ? false : true) + "");
                    itemdetail.put("INSURANCE_AMOUNT", insuranceAmount + "");

                    totalInsuranceAmount += insuranceAmount;
                    items.add(itemdetail);
                }
            }
            
//            if(isAnyItemInsured == false) {
//                totalamount = formattingUtils.formatPrice(cart.getTotalPrice() + totalInsuranceAmount);
//                discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice() + totalInsuranceAmount);
//            } else {
                totalamount = formattingUtils.formatPrice(cart.getTotalPrice());
                discountedAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
//            }
            
            couponCode = cart.getCouponCode() == null ? "" : cart.getCouponCode();
        } catch (Exception e){
            log.error("Unable to get the cart details becasue of: ", e);
        }
        return items;
    }
    
    public String insureItem() {
        //TODO : Call a method in userservice that insures the item.
        insuranceResult = "";
        try {
            UserContextService.Client usc = new UserClient().getClient();
            if(usc.insureItem(productId, userinfo.getCartId(), toInsure)) {
                setInsuranceResult("SUCCESS");
            } else {
                setInsuranceResult("FAILURE");
            }
        } catch (Exception e) {
            log.error("Unable to insure item : " + productId + " for cart : " + userinfo.getCartId(), e);
            setInsuranceResult("FAILURE");
        }
        return "insurance-result";
    }

    public long getItemId(){
        return this.itemId;
    }
    
    public String getTotalAmount() {
        return totalamount;
    }
    
    public String getPinCode() {
        return pincode;
    }
    
    public String getCouponCode()  {
        return couponCode;
    }
    
    public String getDiscountedAmount()   {
        return discountedAmount;
    }
    
    public String getErrorMsg()    {
        return errorMsg;
    }
    
    public long getNumberOfItems(){
        return userinfo.getTotalItems();
    }

    public String getCartMsg(){
        if(cartMsg.equals("")){
            return null;
        }
        return cartMsg;
    }
    
    public String getSnippets(){
        String snippets = "";
        CatalogClient csc;
        try {
            csc = new CatalogClient();
            List<Long> similarItems = csc.getClient().getSimilarItemsCatalogIds(0, 4, itemId);
            for(Long catalogId: similarItems){
                snippets = snippets + ContentServingService.getSnippet(SnippetType.WIDGET_SNIPPET, catalogId+"", sourceId);
            }
        } catch (Exception e) {
            log.error("Unable to initialise Catalogservice Client");
        }       
        return snippets;
    }
    
    @Override
    public void setParameters(Map<String, String[]> parameters) {
        this.reqparams = parameters;    
    }
    
    @Override
    public String getHeaderSnippet() {
        String url = request.getQueryString();
        if (url == null) {
            url = "";
        } else {
            url = "?" + url;
        }
        url = request.getRequestURI() + url;
        return pageLoader.getHeaderHtml(userinfo.isLoggedIn(), userinfo.getEmail(), userinfo.getTotalItems(), url , 0, false);
    }
    
    public boolean isUserLoggedIn() {
        return userinfo.isLoggedIn();
    }
    
    public void setVariationId(String uri)  {
        if (uri.equals("/cart1"))   {
            this.variationId = 1;
        }
    }
    
    public int getVariationId() {
        return this.variationId;
    }
    
    public String getActionMessage(){
        if(cartMsg.contains("out of stock")){
            return "Notify me when this product is in stock.";
        }else {
            return "Notify me when this product is available.";
        }
    }
    
    public String getOfferNote(){
        String note = null;
        if(cartMsg.contains("out of stock")){
            return note;
        }
        else {
            try {
                CatalogClient catalogServiceClient = new CatalogClient();
                Client catalogClient = catalogServiceClient.getClient();
                Item it = catalogClient.getItem(itemId);
                note = it.getBestDealText();
            } catch (Exception e)  {
                log.error("Unable to get the offertext because of: ", e);
            }
        }
        return note;
    }

    public String getInsuranceResult() {
        return insuranceResult;
    }

    public void setInsuranceResult(String insuranceResult) {
        this.insuranceResult = insuranceResult;
    }

    public void setToInsure(boolean toInsure) {
        this.toInsure = toInsure;
    }

    public boolean getToInsure() {
        return toInsure;
    }

    public long getProductId() {
        return productId;
    }

    public void setProductId(long productId) {
        this.productId = productId;
    }

    public long getCartId() {
        return cartId;
    }

    public void setCartId(long cartId) {
        this.cartId = cartId;
    }
}