Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import in.shop2020.model.v1.order.TransactionService.Client;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.support.utils.ReportsUtils;
import in.shop2020.thrift.clients.TransactionClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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.struts2.interceptor.ServletRequestAware;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
@InterceptorRefs({
    @InterceptorRef("defaultStack"),
    @InterceptorRef("login")
})
@Results({
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
})
public class CodReconciliationController extends ActionSupport implements ServletRequestAware {

    private static Logger logger = LoggerFactory.getLogger(CodReconciliationController.class);
    
    private HttpServletRequest request;
    private HttpSession session;
    
    private File codReport;
    private String codReportContentType;
    private String codReportFileName;
    
    private String errorMsg = "";

    public String index() {
        if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath()))
            return "authfail";
        checkForErrors();
        return "authsuccess";
    }
    
    public String create() {
        File fileToCreate = null;
        try {
            fileToCreate = new File("/tmp/", this.codReportFileName);
            FileUtils.copyFile(this.codReport, fileToCreate);
        } catch (Exception e) {
           logger.error("Error while writing COD report to the local file system", e);
           addActionError("Error while writing COD report to the local file system");
        }
        
        String xferBy = this.request.getParameter("xferBy");
        String xferTxnId = this.request.getParameter("xferTxnId");
        String xferDateStr = this.request.getParameter("xferTxnDate"); 
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        Date xferDate = null;
        try {
            xferDate = df.parse(xferDateStr);
        } catch (ParseException e1) {
            logger.error("Invalid date: " + xferDateStr);
            addActionError("Invalid date supplied");
        }
        
        if(checkForErrors())
            return "authsuccess";
        
        //Parse the file and submit the data for update to the transaction service
        Workbook wb = null;
        try {
            wb = new HSSFWorkbook(new FileInputStream(fileToCreate));
        } catch (FileNotFoundException e) {
            logger.error("Unable to open the COD report", e);
            addActionError("Unable to open the COD report. Please check the report format.");
        } catch (IOException e) {
            logger.error("Unable to open the COD report", e);
            addActionError("Unable to open the COD report. Please check the report format.");
        }
        if(checkForErrors())
            return "authsuccess";
        
        HashMap<String, Double> collectedAmountMap = new HashMap<String, Double>(); 
        
        Sheet sheet = wb.getSheetAt(0);
        Row firstRow = sheet.getRow(0);
        logger.info("Last row number is:" + sheet.getLastRowNum());
        for (Row row : sheet) {
            if(row.equals(firstRow))
                continue;
            logger.info("Row no. " + row.getRowNum());
            String awb = row.getCell(0).getStringCellValue();
            double collectedAmount = row.getCell(1).getNumericCellValue();
            collectedAmountMap.put(awb, collectedAmount);
        }
        
        TransactionClient tsc = null;
        try {
            tsc = new TransactionClient();
        } catch (TTransportException e) {
            logger.error("Unable to establish connection to the transaction service", e);
            addActionError("Unable to establish connection to the transaction service");
        }
        if(checkForErrors())
            return "authsuccess";
        
        Client txnClient = tsc.getClient();
        try {
            Map<String, String> unprocessedAwbs = txnClient.reconcileCodCollection(collectedAmountMap, xferBy, xferTxnId, xferDate.getTime());
            if(!unprocessedAwbs.isEmpty()){
                for(Entry<String, String> entry: unprocessedAwbs.entrySet())
                    addActionError("Unable to process AWB no. " + entry.getKey() + " since " + entry.getValue());
            }
        } catch (TransactionServiceException e) {
            logger.error("Unable to reconcile COD collection", e);
            addActionError(e.getMessage());
        } catch (TException e) {
            logger.error("Unable to reconcile COD collection", e);
            addActionError(e.getMessage());
        }
        
        checkForErrors();
        return "authsuccess";
    }
    
    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
        this.session = request.getSession();
    }

    public File getCodReport() {
        return codReport;
    }

    public void setCodReport(File codReport) {
        this.codReport = codReport;
    }

    public String getCodReportContentType() {
        return codReportContentType;
    }

    public void setCodReportContentType(String codReportContentType) {
        this.codReportContentType = codReportContentType;
    }

    public String getCodReportFileName() {
        return codReportFileName;
    }

    public void setCodReportFileName(String codReportFileName) {
        this.codReportFileName = codReportFileName;
    }
    
    public String getErrorMsg(){
        return this.errorMsg;
    }

    private boolean checkForErrors(){
        Collection<String> actionErrors = getActionErrors();
        if(actionErrors != null && !actionErrors.isEmpty()){
            for (String str : actionErrors) {
                errorMsg += "<BR/>" + str;
            }
            return true;
        }
        return false;
    }
}