Subversion Repositories SmartDukaan

Rev

Rev 6390 | Rev 6736 | 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.order.EmiChargeType;
import in.shop2020.model.v1.order.EmiScheme;
import in.shop2020.model.v1.order.TransactionService.Client;
import in.shop2020.model.v1.user.Address;
import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.PromotionService;
import in.shop2020.serving.utils.FormattingUtils;
import in.shop2020.serving.utils.Utils;
import in.shop2020.thrift.clients.PromotionClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.DataLogger;

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

import org.apache.commons.lang.StringUtils;
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;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

import com.google.gson.Gson;

@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 boolean SHOW_EBS_TEST_GATEWAY = Boolean.parseBoolean(resource.getString("show_ebs_test_gateway"));
    
    private static List<EmiScheme> emiSchemes;
    private boolean hasGiftVoucher = false;
    private long addressId = -1;
    private String totalAmount = "";
    private double totalAmountD = 0l;
    private boolean showCodOption = true;
    private boolean showEmiOption = false;
    private String errorMsg = "";
    private String deliveryLocation = ""; //This could be set as myLocation or HotSpot
    private boolean showStorePickUpOption = false;
    private long hotSpotAddressId = 1;
    
    
    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() {
        if(emiSchemes == null){
                populateEmiSchemes();
        }
        
        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;
        String itemIdString = "";
        try {
            userContextServiceClient = new UserClient();
            userClient = userContextServiceClient.getClient();
            
            long cartId = userinfo.getCartId();
            if(deliveryLocation.equals("myLocation")) {
                userClient.addStoreToCart(cartId, 0);
            }
            // 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);
            String couponCode = cart.getCouponCode();
            logger.info("Coupon: " + couponCode);
            
            PromotionService.Client pc = new PromotionClient().getClient();
            if(StringUtils.isNotEmpty(couponCode) && pc.isGiftVoucher(couponCode)){
                hasGiftVoucher = true;
            }
            
            if (!hasGiftVoucher && deliveryLocation.equals("HotSpot")) {
                userClient.addStoreToCart(cartId, hotSpotAddressId);
                showStorePickUpOption = true;
            }
            setTotalAmount(cart);
            itemIdString = Utils.getItemIdStringInCart(cart);
            
            
            // Get the address to check if COD option is available for this
            // address.
            if(addressId == -1){
                addressId = cart.getAddressId();
            }
            address = userClient.getAddressById(addressId);
            
            try {
                showCodOption = userClient.showCODOption(cartId, sourceId, 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.
            }
            
            showStorePickUpOption = showStorePickUpOption && showCodOption;
            
            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";
        }
        
        Collection<String> actionErrors = getActionErrors();
        if(actionErrors != null && !actionErrors.isEmpty()){
            for (String str : actionErrors) {
                errorMsg += "<BR/>" + str;
            }
        }
        
        return "index";
    }

    private void populateEmiSchemes(){
        try {
                        Client tClient = new TransactionClient().getClient();
                        emiSchemes = tClient.getAvailableEmiSchemes();
                } catch (TTransportException e) {
                        logger.error("Error while getting EMI schemes: ", e);
                } catch (TException e) {
                        logger.error("Error while getting EMI schemes: ", e);
                }
    }
    
    private void setTotalAmount(Cart cart) {
        String couponCode = cart.getCouponCode();
        if(couponCode == null || "".equals(couponCode))
                totalAmountD = cart.getTotalPrice();
        else
            totalAmountD = cart.getDiscountedPrice();
        
        FormattingUtils formattingUtils = new FormattingUtils();
        totalAmount = formattingUtils.formatPrice(totalAmountD);
    }

    public long getAddressId(){
        return this.addressId;
    }
    
    public String getErrorMsg(){
        logger.info("added error msg:" + this.errorMsg);
        return this.errorMsg;
    }
    
    public boolean shouldShowCodOption() {
        return showCodOption;
    }

    public boolean shouldShowEmiOption() {
        return showEmiOption;
    }

    public String getTotalAmount(){
        return totalAmount;
    }
    
    public double getTotalAmountL(){
        return totalAmountD;
    }
    
    public boolean shouldShowEbsTestGateway() {
        return SHOW_EBS_TEST_GATEWAY;
    }
    
        @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 String getDeliveryLocation() {
        return deliveryLocation;
    }

    public void setDeliveryLocation(String deliveryLocation) {
        this.deliveryLocation = deliveryLocation;
    }

    public long getHotSpotAddressId() {
        return hotSpotAddressId;
    }

    public void setHotSpotAddressId(long hotSpotAddressId) {
        this.hotSpotAddressId = hotSpotAddressId;
    }

    public boolean shouldShowStorePickUpOption() {
        return showStorePickUpOption;
    }
    
    public String getJSONEmiSchemes(){
        getEmiSchemes();
        Double totalAmount = getTotalAmountL();
        List<EmiScheme> schemes = new ArrayList<EmiScheme>();
        for(EmiScheme emiScheme : emiSchemes) {
                if(emiScheme.getMinAmount() <= totalAmount ) {
                        schemes.add(emiScheme);
                }
        }
        Gson gson  = new Gson();
        return gson.toJson(schemes);
    }
    
    public List<EmiScheme> getEmiSchemes(){
        /*List<EmiScheme> schemes = new ArrayList<EmiScheme>();
        schemes.add(new EmiScheme(1,1,1,3,"HDFC Bank", 2000, "3 Months", EmiChargeType.FIXED, 500));
        schemes.add(new EmiScheme(2,1,1,6,"HDFC Bank", 4000, "6 Months", EmiChargeType.FIXED, 1000));
        schemes.add(new EmiScheme(3,1,1,9,"HDFC Bank", 6000, "9 Months", EmiChargeType.FIXED, 1500));
        schemes.add(new EmiScheme(4,1,1,12,"HDFC Bank", 6000, "12 Months", EmiChargeType.FIXED, 2000));
        schemes.add(new EmiScheme(5,1,2,6,"ICICI Bank", 7000, "6 Months", EmiChargeType.FIXED, 1000));
        schemes.add(new EmiScheme(6,1,2,9,"ICICI Bank", 7000,"9 Months", EmiChargeType.FIXED, 1500));
        schemes.add(new EmiScheme(7,1,2,12,"ICICI Bank", 7000, "12 Months", EmiChargeType.FIXED, 2000));
        schemes.add(new EmiScheme(8,1,2,12,"ICICI Bank", 7000, "12 Months", EmiChargeType.PERCENTAGE, 3));
        emiSchemes = schemes;*/ 
        return emiSchemes;
    }
    
    public static long getGatewayId(long emiSchemeId){
        for(EmiScheme scheme: emiSchemes){
                if(scheme.getId() == emiSchemeId){
                        return scheme.getGatewayId();
                }
        }
        return 0;
    }
}