Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.controllers;

import in.shop2020.config.ConfigException;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.Transaction;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.model.v1.order.TransactionStatus;
import in.shop2020.model.v1.user.ShoppingCartException;
import in.shop2020.payments.Attribute;
import in.shop2020.payments.Payment;
import in.shop2020.payments.PaymentException;
import in.shop2020.payments.PaymentService.Client;
import in.shop2020.payments.PaymentStatus;
import in.shop2020.thrift.clients.PaymentServiceClient;
import in.shop2020.thrift.clients.TransactionServiceClient;
import in.shop2020.thrift.clients.UserContextServiceClient;
import in.shop2020.thrift.clients.config.ConfigClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.thrift.TException;
import org.apache.log4j.Logger;

public class HdfcPayResponseController implements ServletResponseAware, ServletRequestAware{
        private static final long serialVersionUID = 1L;
        
        private enum PaymentReturnStatus{
                CAPTURED("CAPTURED"),
                NOT_CAPTURED ("NOT CAPTURED"),
                CANCELLED ("CANCELLED"),
                DENIED_BY_RISK("DENIED BY RISK"),
                HOST_TIMEOUT("HOST TIMEOUT");
                private String value;
                PaymentReturnStatus(String value) {
                        this.value = value;
                }
                public String value(){
                        return this.value;
                }
        }
        
        HttpServletRequest request;
        HttpServletResponse response;

        //private static Logger log = LoggerFactory.getLogger(HdfcPayResponseController.class);
        private static Logger log = Logger.getLogger(Class.class);

        public static String successUrl;
        public static String errorUrl;
        
        public static String AMOUNT = "amt";
        public static String TRACKID = "trackid";
        public static String RESULT = "result";
        public static String AUTH = "auth";
        public static String TRANID = "tranid";
        public static String PAYMENTID = "paymentid";
        public static String REF = "ref";
        public static String POSTDATE = "postdate";
        public static String ERROR = "Error";
        public static String ERRORTEXT = "ErrorText";
        public static String UDF5 = "udf5";
        String redirectUrl;
        String amount;
        String trackId;
        String result;
        String postdate;
        String auth;
        String ref;
        String tranId;
        String paymentId;
        String sessionId;
        String errorText;
        String errorNo;
        long txnId;
        long merchantPaymentId;
        Transaction transaction = null;
        

        static{
                try {
                        successUrl = ConfigClient.getClient().get("payment_success_url");
                        errorUrl = ConfigClient.getClient().get("payment_error_url");
                } catch (ConfigException e) {
                        log.error("Unable to get success and error usr info from config server.");
                }
        }
        
        
        public HdfcPayResponseController() {
                
        }
        
        public String create() throws IOException, SecurityException{
                log.info("Inside hdfc pay response Create");
                
                PaymentServiceClient paymentServiceClient = null;
                TransactionServiceClient transactionServiceClient = null;
                UserContextServiceClient userServiceClient = null;
                try{
                        paymentServiceClient = new PaymentServiceClient();
                        transactionServiceClient = new TransactionServiceClient();
                        userServiceClient = new UserContextServiceClient();
                }catch(Exception e){
                        //Nothing to worry. lets move forward
                        log.error("Unable to initialize one of the clients");
                        e.printStackTrace();
                }
                
                result = this.request.getParameter(RESULT);
                postdate = this.request.getParameter(POSTDATE);
                tranId = this.request.getParameter(TRANID);
                auth = this.request.getParameter(AUTH);
                ref = this.request.getParameter(REF);
                amount = this.request.getParameter(AMOUNT);
                paymentId = this.request.getParameter(PAYMENTID);
                trackId = this.request.getParameter(TRACKID);

                merchantPaymentId = Long.parseLong(trackId);
                sessionId = this.request.getSession().getId();
                errorNo = request.getParameter(ERROR);
                errorText = request.getParameter(ERRORTEXT);
                //FIXME dump them somewhere
                String udf1=request.getParameter("udf1");
                String udf2=request.getParameter("udf2");
                String udf3=request.getParameter("udf3");
                String udf4=request.getParameter("udf4");
                String udf5=request.getParameter(UDF5);
                //FIXME hdfc is sending comma separated amount, which is very disappointing. May be we get more surprises moving forward.
                amount= amount.replace(",", "");
                
                Client paymentClient = paymentServiceClient.getClient();
                in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();
                try {
                        Payment payment = paymentClient.getPayment(merchantPaymentId);
                        String dbUdf5="";
                        double dbAmount = payment.getAmount();
                        for(Attribute attribute: payment.getAttributes()){
                                if(attribute.getName().trim().equalsIgnoreCase(UDF5)){
                                        dbUdf5 = attribute.getValue();
                                }
                        }
                        // verify 3 things:  udf5, amount and paymentid
                        //FIXME should we first dump the data and than verify these things. ?? 
                        log.info(paymentId+ ":"+ payment.getGatewayPaymentId() + "\n" + Double.parseDouble(amount) + ":" + dbAmount + "\n" + dbUdf5 + ":" + udf5 );
                        if(!(paymentId.equalsIgnoreCase(payment.getGatewayPaymentId()) && dbAmount == Double.parseDouble(amount) && udf5.equalsIgnoreCase(dbUdf5))){
                                log.error("Checks and balance failed on returned date");
                                this.redirectUrl =  errorUrl + "?paymentId="+merchantPaymentId;
                                return "index";
                        }
                } catch (PaymentException e1) {
                        log.error("Payment exception. It is serious, check merchant payment id + " + merchantPaymentId);
                        e1.printStackTrace();
                } catch (TException e1) {
                        log.error("Thrift exception. Check payment id "+ merchantPaymentId);
                        e1.printStackTrace();
                }
                
                if(result != null && result.trim().equals(PaymentReturnStatus.CAPTURED.value())){
                        String message = "Payment successful";
                        
                        try {
                                paymentClient.updatePaymentDetails(merchantPaymentId, paymentId, sessionId, result, message, tranId, auth, ref, errorNo, PaymentStatus.SUCCESS, postdate, null);
                        } catch (PaymentException e1) {
                                log.error("Unable to update payment details in our database." + e1.getError_code() + e1.getMessage());
                                e1.printStackTrace();
                        } catch (TException e1) {
                                log.error("Unable to update payment details in our database. Thrift exception.");
                                e1.printStackTrace();
                        }
                        
                        Map<Long,Double> items = new HashMap<Long, Double>();
                        try {
                                txnId = paymentServiceClient.getClient().getPayment(merchantPaymentId).getMerchantTxnId();
                                transactionClient.changeTransactionStatus(txnId, TransactionStatus.IN_PROCESS, "Payment received for the order");
                                transaction = transactionClient.getTransaction(txnId);
                                for(Order order: transaction.getOrders()){
                                        for(LineItem lineitem: order.getLineitems()){
                                                Long itemId = lineitem.getItem_id();
                                                Double quantity = items.get(itemId);
                                                if(quantity==null){
                                                        quantity = lineitem.getQuantity();
                                                }
                                                else{
                                                        quantity= quantity + lineitem.getQuantity();
                                                }
                                                items.put(itemId, quantity);
                                        }
                                }       
                        } catch (PaymentException e1) {
                                log.error("Unable to get transaction id from payment service." + e1.getError_code() + e1.getMessage());
                                e1.printStackTrace();
                        } catch (TException e1) {
                                log.error("Unable to get transaction id from payment service. Thrift Exception" + e1.getMessage());
                                e1.printStackTrace();
                        } catch (TransactionServiceException e) {
                                log.error("Unable to get transaction id from payment service. Thrift Exception" + e.getErrorCode() + e.getMessage());
                                e.printStackTrace();
                        }
                        
                        
                        
                        try {
                                //TODO Optimize the function to send less number of data over network
                                System.out.println("Transaction shopping cart id is: " + transaction.getShoppingCartid());
                                System.out.println("Items to restr in cart are: " + items );
                                log.info("Transaction shopping cart id is: " + transaction.getShoppingCartid());
                                log.info("Items to restr in cart are: " + items );
                                userServiceClient.getClient().resetCart(transaction.getShoppingCartid(), items);        
                        }catch (TException e) {
                                log.error("Error while updating information in payment database.");
                                e.printStackTrace();
                                //FIXME Even we get exception we should sent url back to payment gateway. And some thing back channel should be done
                                
                        } catch (ShoppingCartException e) {
                                log.error("Error while reseting the cart in cart database.");
                                e.printStackTrace();
                        }
                        
                        // Enqueue the email, containing transaction info, to be sent later by batch job  
                        try {
                                transactionClient.enqueueTransactionInfoEmail(txnId);
                        } catch (Exception e) {
                                log.error("Error while adding email to depatch queue.");
                                e.printStackTrace();
                        }
                        
                        this.redirectUrl = successUrl + "?paymentId="+merchantPaymentId;
                }
                else    {
                        try {
                                paymentClient.updatePaymentDetails(merchantPaymentId, paymentId, sessionId, result, errorText, tranId, auth, ref, errorNo, PaymentStatus.FAILED, postdate, null);
                        } catch (PaymentException e1) {
                                log.error("Unable to update payment details in our database." + e1.getError_code() + e1.getMessage());
                                e1.printStackTrace();
                        } catch (TException e1) {
                                log.error("Unable to update payment details in our database. Thrift exception.");
                                e1.printStackTrace();
                        }
                        
                        try{
                                txnId = paymentClient.getPayment(merchantPaymentId).getMerchantTxnId();
                                transactionClient.changeTransactionStatus(txnId, TransactionStatus.FAILED, "Payment failed for the transaction.");
                        }catch(TException e){
                                log.error("Thrift exception while getting information from transaction service.");
                                e.printStackTrace();
                        } catch (PaymentException e) {
                                log.error("Error while getting information from merchant.");
                                e.printStackTrace();
                        } catch (TransactionServiceException e) {
                                log.error("Error while updating status information in transaction database.");
                                e.printStackTrace();
                        }
                        
                        this.redirectUrl = errorUrl + "?paymentId="+merchantPaymentId;
                }
                
                return "index";
        }
        
        
        public String getRedirectUrl(){
                return this.redirectUrl;
        }

        @Override
        public void setServletRequest(HttpServletRequest request) {
                this.request = request;
                for(Object param: request.getParameterMap().keySet()){
                        System.out.println("PARAMS: " + param + " = "+ request.getParameter((String)param));
                }
        }

        @Override
        public void setServletResponse(HttpServletResponse response) {
                this.response = response;
        }
}