Subversion Repositories SmartDukaan

Rev

Rev 3616 | Rev 4453 | 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.model.v1.catalog.Item;
import in.shop2020.model.v1.user.Address;
import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.Line;
import in.shop2020.serving.utils.FormattingUtils;
import in.shop2020.serving.utils.Utils;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.DataLogger;

import java.util.Collection;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

@SuppressWarnings("serial")
@InterceptorRefs({
    @InterceptorRef("myDefault"),
    @InterceptorRef("login")
})

@Results({
    @Result(name="shipping-redirect", type="redirectAction", params = {"actionName" , "shipping"})
})

public class ProceedToPayController extends BaseController {
    
    private static Logger logger = Logger.getLogger(ProceedToPayController.class);
    
    private static final ResourceBundle resource = ResourceBundle.getBundle(ProceedToPayController.class.getName());
    private static final double COD_CUTOFF_AMOUNT = Double.parseDouble(resource.getString("cod_cutoff_amount")); 
    private static final String RECAPTCHA_PUBLIC_KEY = resource.getString("recaptcha_public_key");
    private static final boolean SHOW_EBS_TEST_GATEWAY = Boolean.parseBoolean(resource.getString("show_ebs_test_gateway"));
    
    private long addressId = -1;
    private String totalAmount = "";
    private boolean showCodOption = true;
    private boolean showEmiOption = false;
    private String errorMsg = "";
    
    public String index(){
        return processPaymentOptions();
    }
    
    public String create(){
        String addressIdString = this.request.getParameter("addressid");
        if(addressIdString == null){
            addActionError("Please specify shipping address to continue.");
            return "shipping-redirect";
        }

        try {
            addressId = Long.parseLong(addressIdString);
        } catch(NumberFormatException nfe) {
            logger.error("Unable to parse address id", nfe);
            addActionError("Please specify shipping address to continue.");
            return "shipping-redirect";
        }
        return processPaymentOptions();
    }

    private String processPaymentOptions() {
        String showEmiOptionStr = this.request.getParameter("showEmiOption");
        if(showEmiOptionStr!=null){
            try{
                showEmiOption = Boolean.parseBoolean(showEmiOptionStr);
            }catch(Exception e){
                logger.info("A non-boolean value passed for showing EMI option");
            }
        }
        
        UserClient userContextServiceClient = null;
        in.shop2020.model.v1.user.UserContextService.Client userClient = null;
        
        Address address;
        List<Line> lineItems;
        String itemIdString = "";
        try {
            userContextServiceClient = new UserClient();
            userClient = userContextServiceClient.getClient();
            
            long cartId = userinfo.getCartId();
                  
            // Validate the cart to ensure that we are not accepting payment for
            // an invalid order.
            errorMsg = userClient.validateCart(cartId, sourceId);
            

            Cart cart = userClient.getCart(cartId);
            setTotalAmount(cart);
            itemIdString = Utils.getItemIdStringInCart(cart);
            
            //Get the line items to check if COD option should be shown.
            lineItems = cart.getLines();
            
            // Get the address to check if COD option is available for this
            // address.
            if(addressId == -1){
                addressId = cart.getAddressId();
            }
            address = userClient.getAddressById(addressId);
            DataLogger.logData(EventType.PROCEED_TO_PAY, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
                    Long.toString(cartId), itemIdString);
        } catch(Exception e) {
            logger.error("Error while either validating the cart or getting the address", e);
            addActionError("We are experiencing some problem. Please try again.");
            return "shipping-redirect";
        }
        
        try {
            CatalogClient catalogServiceClient  = new CatalogClient();
            in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = catalogServiceClient.getClient();
            for (Line line : lineItems) {
                Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
                if(item.getSellingPrice() > COD_CUTOFF_AMOUNT)
                    showCodOption = false;    
            }
        } catch(Exception e) {
            logger.error("Error while getting item info from the catalog service", e);
            addActionError("We are experiencing some problem. Please try again.");
            return "shipping-redirect";
        }
        
        try {
            LogisticsClient lClient = new LogisticsClient();
            showCodOption = showCodOption && lClient.getClient().isCodAllowed(address.getPin());
        } catch(Exception e) {
            logger.error("Error while checking if COD is available for: " + showCodOption, e);
            showCodOption = false; //Not a critical error, proceeding with defensive behaviour.
        }
        
        Collection<String> actionErrors = getActionErrors();
        if(actionErrors != null && !actionErrors.isEmpty()){
            for (String str : actionErrors) {
                errorMsg += "<BR/>" + str;
            }
        }
        
        return "index";
    }

    private void setTotalAmount(Cart cart) {
        FormattingUtils formattingUtils = new FormattingUtils();
        String couponCode = cart.getCouponCode();
        if(couponCode == null || "".equals(couponCode))
            totalAmount = formattingUtils.formatPrice(cart.getTotalPrice());
        else
            totalAmount = formattingUtils.formatPrice(cart.getDiscountedPrice());
    }

    public long getAddressId(){
        return this.addressId;
    }
    
    public String getErrorMsg(){
        return this.errorMsg;
    }
    
    public boolean shouldShowCodOption() {
        return showCodOption;
    }

    public boolean shouldShowEmiOption() {
        return showEmiOption;
    }

    public String getTotalAmount(){
        return totalAmount;
    }
    
    public boolean shouldShowEbsTestGateway() {
        return SHOW_EBS_TEST_GATEWAY;
    }
    
    public String getPublicKey(){
        return RECAPTCHA_PUBLIC_KEY;
    }

        @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.getNameOfUser(), url , 0, false);
        }
}