Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.mobileapi.serving.controllers;

import in.shop2020.datalogger.EventType;
import in.shop2020.mobileapi.serving.services.ContentServingService;
import in.shop2020.mobileapi.serving.utils.PojoPopulator;
import in.shop2020.mobileapi.serving.utils.SnippetType;
import in.shop2020.model.v1.catalog.CatalogService.Client;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.ShoppingCartException;
import in.shop2020.model.v1.user.UserContextService;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.DataLogger;

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;

import com.google.gson.Gson;


@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 cartId;
    private String cartPojoJson;
    private long quantity;
    
    public CartController(){
        super();
    }
    
    public String index()  {
        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, -1);
                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);
                
                cartPojoJson = new Gson().toJson(PojoPopulator.getCartPojo(cart, 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";
    }

    public String create() {
        try {
            UserClient userServiceClient = new UserClient();
            UserContextService.Client userClient = userServiceClient.getClient();
            cartMsg = userClient.addItemToCart(cartId, itemId, 1, -1);
            if (!("".equals(cartMsg))) {
                return "outofstock";
            }
        } 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);
        }
        
    return index();
    }       


    // DELETE /entity
    public String destroy() {
        if(cartId > 0)  {
            try {
                UserClient userContextServiceClient = new UserClient();
                in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();

                userClient.deleteItemFromCart(cartId, itemId);
                return index();
            } 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 index();
    }
    
    //PUT
    public String update() {
        if(quantity <= 0)   {
            log.info("Not valid item quantity. Unable to change item quantity.");
        } else  {
            if(updateItemQuantityInCart(cartId, itemId, quantity))    {
                return index();
            }
        }
        return index();
    }
    
    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, -1);
            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;
    }
           
    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+"", -1);
            }
        } 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 getCartId() {
        return cartId;
    }

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


    public void setCartPojoJson(String cartPojoJson) {
        this.cartPojoJson = cartPojoJson;
    }


    public String getCartPojoJson() {
        return cartPojoJson;
    }

    public void setQuantity(long quantity) {
        this.quantity = quantity;
    }

    public long getQuantity() {
        return quantity;
    }
}