Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.controllers;

import in.shop2020.model.v1.catalog.Warehouse;
import in.shop2020.support.utils.FileUtils;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.HelperClient;
import in.shop2020.utils.LogisticsUser;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Allows executives of courier companies to login and download courier details
 * report which they then use to upload into their database.
 * 
 * @author Chandranshu
 * 
 */
public class CourierDetailsController implements ServletResponseAware,
                ServletRequestAware, ServletContextAware {
    
    private static Logger logger = LoggerFactory.getLogger(CourierDetailsController.class);
    
        private String id;
        private int daysToSubtract;
        
        //FIXME: Read this configuration from the config client
        private String courierDetailsPath = "/CourierDetailReports";
        
        private ServletContext context;
        private HttpServletRequest request;
        private HttpServletResponse response;
        private HttpSession session;

        public String index(){
                if(getSessionUserName()==null)
                        return "authfail";
                else
                        return "authsuccess";
        }
        
        // Handler for POST /courier-details
        public String create(){
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                try{
                        HelperClient helperServiceClient = new HelperClient();
                        in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
                        LogisticsUser user = client.authenticateLogisticsUser(username, password);
                        session.setAttribute("username", user.getUsername());
                        session.setAttribute("providerId", Long.valueOf(user.getProviderId()));
                }catch(Exception e){
                        logger.error("Error authenticating the user " + username, e);
                        return "authfail";
                }
                return "authsuccess";
        }
        
        // Handler for GET /courier-details/<warehouseId>
        public String show(){
                try {
                        long warehouseId = Long.parseLong(getId());
                        long providerId = ((Long)session.getAttribute("providerId")).longValue();
                        boolean isCod;
                        try {
                    isCod = Boolean.parseBoolean(request.getParameter("isCod"));
                } catch (Exception e) {
                    isCod = false;
                }
                        logger.info("Download request for " + (isCod ? "COD" : "Prepaid") + " Courier Details report of warehouse Id: " + warehouseId + " and provider Id:" + providerId);
                        
                        String deliveryType = "prepaid";
                        if(isCod)
                            deliveryType = "cod";
                        
                        response.setContentType("application/vnd.ms-excel");
                        
                        Calendar date = new GregorianCalendar();
                        date.add(Calendar.DAY_OF_MONTH, daysToSubtract);
                        int year = date.get(Calendar.YEAR);
                        int month = date.get(Calendar.MONTH) +1;
                        int day = date.get(Calendar.DAY_OF_MONTH);
                        String fileName = courierDetailsPath + "/courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-" + month + "-" + day +".xls";
                        response.setHeader("Content-disposition", "inline; filename=courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-"+ month + "-" + day +".xls" );
                        
                        ServletOutputStream sos;
                        try {
                                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                                baos.write(FileUtils.getBytesFromFile(new File(fileName)));
                                sos = response.getOutputStream();
                                baos.writeTo(sos);
                                sos.flush();
                        } catch (IOException e) {
                                logger.error("Unable to stream the courier details report", e);
                        }       
                        return "authsuccess";
                }catch(NumberFormatException nfe){
                        logger.error("Unable to parse the warehouse id", nfe);
                }
                return "authfail";
        }

    /**
     * Sets the daysToSubtract to -2 and then invokes the standard show() handler.
     * Should be used to view day before yesterday's courier details report.
     * 
     * @return the same string tokens as show
     */
        public String dayBefore(){
                daysToSubtract = -2;
                return show();
        }

    /**
     * Sets the daysToSubtract to -1 and then invokes the standard show()
     * handler. Should be used to view yesterday's courier details report.
     * 
     * @return the same string tokens as show
     */
        public String yesterday(){
                daysToSubtract = -1;
                return show();
        }

    /**
     * Sets the daysToSubtract to 0 and then invokes the standard show()
     * handler. Should be used to view today's courier details report.
     * 
     * @return the same string tokens as show
     */
        public String today(){
                daysToSubtract = 0;
                return show();
        }
                
        @Override
        public void setServletContext(ServletContext context) {
                this.context = context;
        }
        
        @Override
        public void setServletResponse(HttpServletResponse response) {
                this.response  = response;
        }

        @Override
        public void setServletRequest(HttpServletRequest request) {
                this.request = request;
                this.session = request.getSession();
        }

        public String getId(){
                return id;
        }
        
        public void setId(String id){
                this.id = id;
        }
        
        public String getSessionUserName(){
                return (String) session.getAttribute("username");
        }

    /**
     * Gets the list of all warehouses and maps the warehouse ids to their
     * display name.
     * 
     * @return the mapping of warehouse if to its display namee
     */
        public Map<Long, String> getWarehouses(){
                Map<Long, String> warehouseMap = new HashMap<Long, String>();
                try{
                        CatalogClient csc = new CatalogClient();
                        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient= csc.getClient();
                        List<Warehouse> warehouses = catalogClient.getAllWarehouses(true);
                        for(Warehouse warehouse : warehouses){
                                warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
                        }
                }catch(Exception e){
                        logger.error("Error getting the list of warehouses", e);
                }
                return warehouseMap;
        }

        public String getServletContextPath(){
                return context.getContextPath();
        }
}