Subversion Repositories SmartDukaan

Rev

Rev 20986 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.mobileapi.serving.controllers;

import in.shop2020.config.ConfigException;
import in.shop2020.logistics.DeliveryType;
import in.shop2020.metamodel.util.ProductPojo;
import in.shop2020.mobileapi.serving.pojos.CartPojo;
import in.shop2020.mobileapi.serving.pojos.RedirectPojo;
import in.shop2020.mobileapi.serving.services.ContentServingService;
import in.shop2020.mobileapi.serving.services.LogisticsService;
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.CartPlus;
import in.shop2020.model.v1.user.ItemQuantity;
import in.shop2020.model.v1.user.PromotionException;
import in.shop2020.model.v1.user.PromotionService;
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.PromotionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.thrift.clients.config.ConfigClient;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ParameterAware;
import org.apache.thrift.TException;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;

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 boolean privateDealUser = false;
    private boolean autoApplicationOff = true;
    
    private long id =-1; //CartId
    private String cartPojoJson;
    private String cartMap = null;
    private long quantity;
    private int insuranceType;
    UserContextService.Client userClient;
    
    public CartController() throws Exception{
        super();
    }
    
    public UserContextService.Client getClient() throws Exception{
        userClient = new UserClient().getClient();
        return userClient;
    }   
    public String index() {
                try {
                        if(ConfigClient.getClient().get("SALES_FLAG").equals("0")){
                                cartPojoJson = new Gson().toJson(new CartPojo());
                                return "index";
                        }
                } catch (ConfigException e1) {
                        cartPojoJson = new Gson().toJson(new CartPojo());
                        return "index";
                }
        if(id != -1){
            try {
                String cc = null;
                log.info(privateDealUser + "  "  + autoApplicationOff);
                if(privateDealUser && !autoApplicationOff) {
                        cc = "saholicdeals";
                }
                log.info("Before cart response--------");
                CartPlus cartResponse  = getClient().validateCartPlus(id, -1, cc);
                log.info("After cart response--------");
                if (errorMsg == null || errorMsg.equals("")) {
                        if(cartResponse.getValidateCartMessages().get(1)!=null && !cartResponse.getValidateCartMessages().get(1).equals("")){
                                errorMsg = cartResponse.getValidateCartMessages().get(1);
                        }else {
                                errorMsg = cartResponse.getValidateCartMessages().get(0);
                        }
                }
                cartPojoJson = new Gson().toJson(PojoPopulator.getCartPojo(cartResponse.getCart(), errorMsg, 
                                cartResponse.getPinCode(), cartResponse.isNeedInsuranceInfo()));
                log.info(cartPojoJson);
            } catch (Exception e) {
                /*TTransportException te = (TTransportException)e;
                log.warn(e.getLocalizedMessage() + " " + te.getType());*/
                log.warn("Unable to validate the cart: ", e);
            }
        } else {
                cartPojoJson = new Gson().toJson(new CartPojo());
        }
        return "index";
    }

    public String create() {
        RedirectPojo rp = new RedirectPojo();
        rp.setRedirectUrl("");
        try {
                
                        if(ConfigClient.getClient().get("SALES_FLAG").equals("1")){
                                cartMsg = getClient().addItemToCart(id, itemId, 1, -1);
                        } else {
                                cartMsg = "Sale is off";
                        }
                //Try adding to cart
            log.info("Cart message while adding item to cart - " + cartMsg);
            //If could not add to cart try to add notification reminder if email exists.
            if (!("".equals(cartMsg))) {
                String emailId = this.request.getParameter("email");
                log.info("QuesyString" + this.request.getParameterMap().toString());
                        if(emailId==null || emailId.equals("")){
                                //User tries to add to cart but product is actually out of stock
                                rp.setMessage("Item is currently out of stock");
                        } else {        
                                try {
                                CatalogClient catalogClientService;
                                        catalogClientService = new CatalogClient();
                                        in.shop2020.model.v1.catalog.CatalogService.Client client = catalogClientService.getClient();
                                        client.addProductNotification(itemId, emailId);
                                        log.debug("Got product notification for product: " + itemId + "  from user: " + emailId );
                                        rp.setMessage("You will be notified when product is avaliable");
                                } catch (Exception e) {
                                        rp.setMessage("Error occurred while adding to notificiation");
                                        log.error("Exception while adding product notification for item: " + itemId + " and email: " + emailId, e);
                                }
                                
                        }
            } else {
                rp.setRedirectUrl("cart");
            }
        } catch (TException e) {
            log.error("Unable to create or add to cart because of: ", e);
            errorMsg = "Unable to add to cart. Please try again.";
        } catch (Exception e) {
            log.error("Unable to create or add to cart because of: ", e);
            errorMsg = "Unable to add to cart. Please try again.";
        }
        cartPojoJson = new Gson().toJson(rp);
        return "index";
    }       


    // DELETE /entity
    public String destroy() {
        if(id > 0)  {
            try {
                getClient().deleteItemFromCart(id, itemId);
                return index();
            } catch (ShoppingCartException e) {
                log.error("Unable to delete item from cart: ", e);
                errorMsg = "Unable to delete item. Please try again.";
            } catch (TException e) {
                log.error("Unable to delete item from cart: ", e);
                errorMsg = "Unable to delete item. Please try again.";
            } catch (Exception e) {
                log.error("Unable to delete item from cart: ", e);
                errorMsg = "Unable to delete item. Please try again.";
            }
        }
        return index();
    }
    
    //PUT
    public String update() {
        if(quantity <= 0)   {
            log.info("Not valid item quantity. Unable to change item quantity.");
            errorMsg = "Invalid item quantity";
        } else  {
            if(updateItemQuantityInCart(id, itemId, quantity))    {
                return index();
            }
        }
        return index();
    }
    
    private boolean updateItemQuantityInCart(long cartId, long itemId, long quantity){
        try {
            getClient().addItemToCart(cartId, itemId, quantity, -1);
            return true;
        } catch (ShoppingCartException e) {
            log.error("Unable to update the item quantity in the cart: ", e);
            errorMsg = "Unable to change quantity. Please try again.";
        } catch (TException e) {
            log.error("Unable to update the item quantity in the cart: ", e);
            errorMsg = "Unable to change quantity. Please try again.";
        } catch (Exception e) {
            log.error("Unable to update the item quantity in the cart: ", e);
            errorMsg = "Unable to change quantity. Please try again.";
        }
        return false;
    }
           
    public String insureItem() {
        insuranceResult = "";
        try {
            if(getClient().insureItem(itemId, id, toInsure, insuranceType)) {
                setInsuranceResult("SUCCESS");
            } else {
                setInsuranceResult("FAILURE");
            }
        } catch (Exception e) {
            log.error("Unable to insure item : " + itemId + " for cart : " + id, e);
            setInsuranceResult("FAILURE");
        }
        return "insurance-result";
    }
    
    public String edit()  {
        String action = request.getParameter("action");
        PromotionClient promotionServiceClient = null;
        try {
            if(action == null || action.isEmpty())  {
                errorMsg = "Invalid Request Action";
                return index();
            }
            String couponCode = request.getParameter("coupon_code");
            
            if (action.equalsIgnoreCase("applycoupon"))   {
                if (couponCode == null || couponCode.isEmpty()) {
                    errorMsg = "Coupon Code field cannot be left empty";
                    return index();
                }
                
                promotionServiceClient = new PromotionClient();
                PromotionService.Client promotionClient = promotionServiceClient.getClient();
                
                Cart cart = promotionClient.applyCoupon(couponCode, id);
                errorMsg = "Coupon successfully applied";
                if(cart.getMessage() != null && !cart.getMessage().equals("")){
                        errorMsg = errorMsg +  ", " + cart.getMessage();
                }
            }
            else if (action.equals("removecoupon"))    {
                getClient().removeCoupon(id);
            }
        } catch (PromotionException e) {
            log.info("Invalid coupon: " + e.getMessage());
            errorMsg = e.getMessage();
        } catch (Exception e) {
            log.error("Unable to apply or remove coupon", e);
            errorMsg = "Unable to apply or remove coupon";
        }
        return index();
    }
    
    public String changeAddress() {
        long addressId;
        if(request.getParameter("addressId") == null || request.getParameter("addressId").isEmpty()) {
            errorMsg = "Null or empty addressId";
            return index();
        } else {
            addressId = Long.parseLong(request.getParameter("addressId"));
        }
         
        try {
            if(request.getParameter("addressType").equalsIgnoreCase("store")) {
                getClient().addStoreToCart(id, addressId);
            } else if (request.getParameter("addressType").equalsIgnoreCase("home")){
                getClient().addAddressToCart(id, addressId);
            } else {
                errorMsg = "Invalid addressType. It can only be set to home or store.";
            }
        } catch(Exception e) {
            log.error("Unable to change address", e);
        }
        return index();
    }

    public long getItemId(){
        return this.itemId;
    }
    
    public void setItemId(long itemId){
        this.itemId = 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 getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }


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


    public String getCartPojoJson() {
        return cartPojoJson;
    }
    
    public void setCartMap(String cartMap) {
        log.info("I am in cartMap" + " " + cartMap);
        log.info(this.request.getParameterMap());
        this.cartMap = cartMap;
    }
    
    public String pinServiceable(){
        return "";
    }
    
    public String validateCart() {
        log.info(this.cartMap);
        JSONObject jsonObj  = null;
        if(!userinfo.isPrivateDealUser()){
                cartPojoJson = "{\"response\":\"error\", \"message\":\"Invalid request.\"}";
        } else {
                if(StringUtils.isEmpty(cartMap)){
                        jsonObj = new JSONObject("{\"cartItems\":[]}");
                }else {
                        jsonObj = new JSONObject(cartMap);
                }
                        try{
                                List<ItemQuantity> itemQuantities = new ArrayList<ItemQuantity>();
                                JSONArray cartItems = jsonObj.getJSONArray("cartItems");
                                List<Integer> itemsList = new ArrayList<Integer>();
                                for (int i=0; i< cartItems.length(); i++) {
                                        JSONObject obj = cartItems.getJSONObject(i);
                                        //Just to avoid garbage values
                                        int itemId = 0;
                                        try{
                                                itemId = obj.getInt("itemId");
                                        } catch(Exception e){
                                                continue;
                                        }
                                        Integer quantity = obj.getInt("quantity");
                                        ItemQuantity iq = new ItemQuantity(itemId, quantity);
                                        itemQuantities.add(iq);
                                        itemsList.add(itemId);
                                }
                                userClient = getClient();
                                if (itemsList.size()==0 || userClient.addItemsToCart(id, itemQuantities, jsonObj.has("couponCode")? jsonObj.getString("couponCode"):null)){
                                        log.info("Items added to cart Successfully");
                                        //Now validate cart and provide appropriate response.
                                        String cartString = userClient.validateCartNew(id, userinfo.getPincode(), -1);
                                        //System.out.println("cartString  "  + cartString);
                                        JSONObject cartObj = new JSONObject(cartString);
                                        JSONArray arr = cartObj.getJSONArray("cartItems");
                                        int maxEstimate=-2;
                                        boolean allSame=true;
                                        int removedCount = 0;
                                        cartObj.put("cartMessagesMerged", 0);
                                        for (int j=0; j<arr.length(); j++){
                                                JSONObject itemObj = arr.getJSONObject(j-removedCount);
                                                if(!itemsList.contains(itemObj.getInt("itemId"))){
                                                         if(itemObj.getInt("quantity")==0){
                                                                arr.remove(j-removedCount);
                                                                removedCount++;
                                                                if (itemObj.has("estimate") && itemObj.getInt("estimate")==-1){
                                                                        cartObj.put("cartMessageUndeliverable", cartObj.getInt("cartMessageUndeliverable") - 1);
                                                                } else {
                                                                        cartObj.put("cartMessageOOS", cartObj.getInt("cartMessageOOS") - 1);
                                                                }
                                                                continue;
                                                         } else {
                                                                JSONArray messagesArray = new JSONArray();
                                                                itemObj.put("cartItemMessages", messagesArray);
                                                                if(itemsList.size()>0){
                                                                        JSONObject message=new JSONObject();
                                                                        message.put("type","info");
                                                                        message.put("messageText","Added from earlier cart");
                                                                        messagesArray.put(message);
                                                                        cartObj.put("cartMessagesMerged", cartObj.getInt("cartMessagesMerged") + 1);
                                                                }
                                                         }
                                                }
                                                ProductPojo pp = PojoPopulator.getShortContent(itemObj.getLong("catalogItemId"));
                                                String productProperties = ContentServingService.getSnippet(SnippetType.PRODUCT_PROPERTIES_SNIPPET, pp.getId() +"", -1);
                                                JSONObject productPropertiesInJson = new JSONObject(productProperties);
                                                pp.setCategoryName(productPropertiesInJson.getString("categoryName"));
                                                
                                                if(itemObj.has("estimate")){
                                                        if(allSame){
                                                                allSame = maxEstimate==-2 || maxEstimate==itemObj.getInt("estimate");
                                                        }
                                                        if(itemObj.getInt("estimate") > maxEstimate){
                                                                maxEstimate = itemObj.getInt("estimate");
                                                        }
                                                }
                                                itemObj.put("imageUrl", pp.getImageUrl());
                                                itemObj.put("categoryName", pp.getCategoryName());
                                                itemObj.put("title", pp.getTitle());
                                        }
                                        
                                        ArrayList<JSONObject> listdata = new ArrayList<JSONObject>();     
                                        if (arr != null) { 
                                           for (int i=0;i<arr.length();i++){
                                                   JSONArray itemMessages = arr.getJSONObject(i).optJSONArray(("cartItemMessages"));
                                                   if(itemMessages!=null && itemMessages.length()>0){
                                                           listdata.add(0,arr.getJSONObject(i));
                                                   } else {
                                                           listdata.add(arr.getJSONObject(i));
                                                   }
                                           } 
                                        }
                                        arr = new JSONArray();
                                        for(int i=0;i<listdata.size();i++){
                                                arr.put(listdata.get(i));
                                        }
                                        cartObj.put("cartItems", arr);
                                        JSONArray cartMessagesArray = new JSONArray();
                                        for (String message :Arrays.asList("cartMessageOOS", "cartMessageUndeliverable", "cartMessageChanged","cartMessagesMerged")){
                                                int count = cartObj.getInt(message);
                                                if (count>0) {
                                                        String type="danger";
                                                        JSONObject cartMessage=new JSONObject();
                                                        if (message.equals("cartMessagesMerged")) {
                                                                type = "info";
                                                                if (count==1){
                                                                        cartMessage.put("messageText","1 item is added from earlier cart");
                                                                }else {
                                                                        cartMessage.put("messageText","Few items are added from earlier cart");
                                                                }
                                                        } else if (message.equals("cartMessageOOS")) {
                                                                if (count==1){
                                                                        cartMessage.put("messageText","One item is currently Out of Stock");
                                                                }else {
                                                                        cartMessage.put("messageText","Few items are currently Out of Stock");
                                                                }
                                                        } else if (message.equals("cartMessageUndeliverable")) {
                                                                if (count==1){
                                                                        cartMessage.put("messageText","One item is undeliverable");
                                                                }else {
                                                                        cartMessage.put("messageText","Few items are underiverable");
                                                                }
                                                        } else {
                                                                if (count==1){
                                                                        cartMessage.put("messageText","One item qty has changed");
                                                                }else {
                                                                        cartMessage.put("messageText","Few items qty have changed");
                                                                }
                                                        }
                                                        cartMessage.put("type",type);
                                                        cartMessagesArray.put(cartMessage);
                                                }
                                        }
                                        cartObj.put("cartMessages", cartMessagesArray);
                                                
                                        if (maxEstimate==-1){
                                                cartObj.put("estimateString", "Can't ship here");
                                        }
                                        else if(maxEstimate==-2){
                                                cartObj.put("estimateString", "Out of Stock");
                                        } else {
                                                cartObj.put("cod", getClient().showCODOption(id, 0, userinfo.getPincode()));
                                                cartObj.put("estimateString", LogisticsService.getDeliveryDateString(maxEstimate,DeliveryType.COD));
                                        }
                                        cartObj.put("maxEstimate", maxEstimate);
                                        cartPojoJson = cartObj.toString();
                                } else {
                                        cartPojoJson = "{\"response\":\"error\", \"message\":\"Problem occurred while updating cart\"}";
                                }
                        }catch(Exception e) {
                                cartPojoJson = "{\"response\":\"error\", \"message\":\"Something went wrong while validation\"}";
                                e.printStackTrace();
                        }
        }
        setResultJson(cartPojoJson);
        return "index";
    }

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

    public long getQuantity() {
        return quantity;
    }

    public int getInsuranceType() {
        return insuranceType;
    }

    public void setInsuranceType(int insuranceType) {
        this.insuranceType = insuranceType;
    }

        public void setPrivateDealUser(boolean privateDealUser) {
                this.privateDealUser = privateDealUser;
        }

        public boolean isPrivateDealUser() {
                return privateDealUser;
        }

        public void setAutoApplicationOff(boolean autoApplicationOff) {
                this.autoApplicationOff = autoApplicationOff;
        }

        public boolean isAutoApplicationOff() {
                return autoApplicationOff;
        }
}