Subversion Repositories SmartDukaan

Rev

Rev 13524 | 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.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.services.IPaymentService;
import in.shop2020.serving.utils.FormattingUtils;
import in.shop2020.serving.utils.PaymentUtils;
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.HashMap;
import java.util.List;
import java.util.Map;
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 static String emiSchemesInJSON;
        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;
        private boolean amountZero = false;

        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).get(0);

                        Cart cart = userClient.getCart(cartId);
                        String couponCode = cart.getCouponCode();
                        logger.info("Coupon: " + couponCode);

                        setTotalAmount(cart);
                        itemIdString = Utils.getItemIdStringInCart(cart);

                        PromotionService.Client pc = new PromotionClient().getClient();
                        /*
                         * If a gift voucher is used such that all of the amount is paid by
                         * the gift voucher then we do not need set the hasGiftVoucher flag.
                         */
                        if (StringUtils.isNotEmpty(couponCode) && pc.isGiftVoucher(couponCode) && getTotalAmountL() > 0) {
                                hasGiftVoucher = true;
                        }

                        if (!hasGiftVoucher && deliveryLocation.equals("HotSpot")) {
                                userClient.addStoreToCart(cartId, hotSpotAddressId);
                                showStorePickUpOption = true;
                        }

                        // 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 += str + "<BR/>";
                        }
                }

                return "index";
        }

        public static 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);
                if (totalAmountD == 0) {
                        amountZero = true;
                }
        }

        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, userinfo.isPrivateDealUser());
        }

        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 String getJSONEmiDiscountSchemes() {
                try {
                        PromotionService.Client pc = new PromotionClient().getClient();
                        Gson gson = new Gson();
                        return gson.toJson(pc.getEmiDiscount(userinfo.getCartId()));
                } catch (Exception e) {
                        logger.warn("Could not retrive emi based promotions for cart: " + userinfo.getCartId() + ".\n" + e);
                        return "{}";
                }
        }

        public static List<EmiScheme> getEmiSchemes() {
                if (emiSchemes != null) {
                        return emiSchemes;
                } else {
                        populateEmiSchemes();
                        return emiSchemes;
                }
        }

        public static long getGatewayId(String paymentOptions) {
                String payCode = "";
                // checking for emis
                if (paymentOptions.startsWith(PaymentUtils.PAYMENT_TYPE.EMI.toString())) {
                        payCode = paymentOptions.replace(PaymentUtils.PAYMENT_TYPE.EMI.toString(), "");
                        for (EmiScheme scheme : emiSchemes) {
                                if (scheme.getId() == Long.parseLong(payCode)) {
                                        return scheme.getGatewayId();
                                }
                        }
                }

                // As of on august 2 2016 all the debit,credit and netbanking payments
                // have to be redirected to payu.
                // so returning 13 as payment gateway
                // this can be re-written for other business logic
                if (paymentOptions.startsWith(PaymentUtils.PAYMENT_TYPE.CC.toString())) {
                        // payCode =
                        // paymentOptions.replace(PaymentUtils.PAYMENT_TYPE.CC.toString(),
                        // "");
                        return 5;

                }
                if (paymentOptions.startsWith(PaymentUtils.PAYMENT_TYPE.DC.toString())) {
                        // payCode =
                        // paymentOptions.replace(PaymentUtils.PAYMENT_TYPE.CC.toString(),
                        // "");
                        return 5;
                }
                if (paymentOptions.startsWith(PaymentUtils.PAYMENT_TYPE.NB.toString())) {
                        // payCode =
                        // paymentOptions.replace(PaymentUtils.PAYMENT_TYPE.CC.toString(),
                        // "");
                        return 5;
                }
                if (paymentOptions.startsWith(PaymentUtils.PAYMENT_TYPE.WAL.toString())) {
                        payCode = paymentOptions.replace(PaymentUtils.PAYMENT_TYPE.WAL.toString(), "");
                        if (PaymentUtils.PAYU_CC.equals(payCode))
                                return 5;
                        return 5;
                }
                if (paymentOptions.startsWith(PaymentUtils.PAYMENT_TYPE.CAS.toString())) {
                        return 18;
                }
                if (paymentOptions.startsWith(PaymentUtils.PAYMENT_TYPE.COD.toString())) {
                        payCode = paymentOptions.replace(PaymentUtils.PAYMENT_TYPE.COD.toString(), "");
                        if (payCode.equals(IPaymentService.COD)) {
                                return 4;
                        }
                        if (payCode.equals(IPaymentService.COUPON)) {
                                return 17;
                        }
                }

                return 0;
        }

        public static double getInterestRate(long emiSchemeId) {
                for (EmiScheme scheme : emiSchemes) {
                        if (scheme.getId() == emiSchemeId) {
                                return scheme.getInterestRate();
                        }
                }
                return 0;
        }

        public void setAmountZero(boolean amountZero) {
                this.amountZero = amountZero;
        }

        public boolean isAmountZero() {
                return amountZero;
        }

        public static String getEmiSchemesInJSON() {
                if (emiSchemesInJSON == null) {
                        List<Map<String, Object>> schemeList = new ArrayList<Map<String, Object>>();
                        for (EmiScheme scheme : getEmiSchemes()) {
                                Map<String, Object> arrayMap = new HashMap<String, Object>();
                                arrayMap.put("bankId", scheme.getBankId());
                                arrayMap.put("bankName", scheme.getBankName());
                                arrayMap.put("chargeType", scheme.getChargeType());
                                arrayMap.put("chargeValue", scheme.getChargeValue());
                                arrayMap.put("gatewayId", scheme.getGatewayId());
                                arrayMap.put("minAmount", scheme.getMinAmount());
                                arrayMap.put("tenure", scheme.getTenure());
                                arrayMap.put("tenureDescription", scheme.getTenureDescription());
                                arrayMap.put("id", scheme.getId());
                                arrayMap.put("interestRate", scheme.getInterestRate());
                                schemeList.add(arrayMap);
                        }
                        return new Gson().toJson(schemeList);
                } else {
                        return emiSchemesInJSON;
                }
        }

        public boolean isPrivateDealUser() {
                return userinfo.isPrivateDealUser();
        }
}