Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.controllers;

import in.shop2020.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsServiceException;
import in.shop2020.logistics.PickupStore;
import in.shop2020.logistics.Provider;
import in.shop2020.logistics.ProviderDetails;
import in.shop2020.model.v1.inventory.InventoryServiceException;
import in.shop2020.model.v1.inventory.Warehouse;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.support.models.AwbDetails;
import in.shop2020.support.utils.FileUtils;
import in.shop2020.thrift.clients.HelperClient;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.utils.LogisticsUser;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
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.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
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.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
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 static final String EMPTY_STRING = "-";
    
        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;

    private String awbNumbers;
    private List<AwbDetails> detailedAWBs;

    private String errorMsg = "";
    
    private File awbFile;
    private String awbFileContentType;
    private String awbFileFileName;

        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());
                        if(warehouseId == 1){
                                warehouseId = 0;
                        }
                        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";
        }
        
        /**
         * Use this method to view details of a given awb number
         */
        public String viewAwbDetails() {
                if(awbNumbers.isEmpty()) {
                        setErrorMsg("Field cannot be empty");
                        return "info";
                }
                String [] awbArray = awbNumbers.split(",");
                createAwbDetailList(awbArray);
                return "info";
        }

        /**
         * Use this method to download details of given comma separated list of awb numbers
         */

        public String getAwbDetails() {
                if(awbNumbers.isEmpty()) {
                        setErrorMsg("Field cannot be empty");
                        return "info";
                }
                String [] awbArray = awbNumbers.split(",");
                createAwbDetailList(awbArray);
                ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");
                ServletOutputStream sos;
                try {
                        sos = response.getOutputStream();
                        baos.writeTo(sos);
                        sos.flush();
                } catch (IOException e) {
                        logger.error("Encountered error while sending invoice response: ", e);
                }
                return "info";
        }

        /**
         * Use this method to download details of given list of awb numbers uploaded in a text file
         */

        public String getAwbDetailsByFile() {
                if(awbFile == null) {
                        return null;
                }

                List<String> awbList = new ArrayList<String>();

                try {
                        BufferedReader in = new BufferedReader(new FileReader(awbFile));
                        String line;
                        while((line = in.readLine()) != null) {
                                awbList.add(line.trim());
                        }
                } catch (FileNotFoundException e1) {
                        logger.error("File not found", e1);
                        return null;
                } catch (IOException e) {
                        logger.error("Unable to read file", e);
                        return null;
                }

                String[] awbArray  = awbList.toArray(new String [awbList.size()]);
                createAwbDetailList(awbArray);

                ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");
                ServletOutputStream sos;
                try {
                        sos = response.getOutputStream();
                        baos.writeTo(sos);
                        sos.flush();
                } catch (IOException e) {
                        logger.error("Encountered error while sending invoice response: ", e);
                }
                return "info";
        }
        
        private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
                StringBuffer itemName = new StringBuffer();
                if(lineitem.getBrand()!= null)
                        itemName.append(lineitem.getBrand() + " ");
                if(lineitem.getModel_name() != null)
                        itemName.append(lineitem.getModel_name() + " ");
                if(lineitem.getModel_number() != null )
                        itemName.append(lineitem.getModel_number() + " ");
                if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
                        itemName.append("("+lineitem.getColor()+")");
                if(appendIMEI && lineitem.isSetSerial_number()){
                        itemName.append("\nIMEI No. " + lineitem.getSerial_number());
                }

                return itemName.toString();
        }

        private void createAwbDetailList(String[] awbArray) {
                List<Order> orderList;
                List<AwbDetails> tempList = new ArrayList<AwbDetails>() ;
                for(String awbNumber : awbArray) {
                        try {
                                LogisticsClient lsc = new LogisticsClient();
                                TransactionClient tsc = new TransactionClient();
                                InventoryClient isc = new InventoryClient();
                                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = isc.getClient();
                                in.shop2020.model.v1.order.TransactionService.Client txnClient = tsc.getClient();
                                in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();

                                /*
                                 * Get required stuff
                                 * FIXME: Reduce service calls 
                                 */
                                logger.info("Session : " + session);
                                logger.info("provider Id : " + ((Long)session.getAttribute("providerId")).longValue());
                                Provider provider = logisticsClient.getProvider(((Long)session.getAttribute("providerId")).longValue());
                                orderList = txnClient.getOrderForAwb(awbNumber);
                                
                                Map<String, List<Order>> logisticsTxnIdOrdersMap = new HashMap<String, List<Order>>(); 
                            Map<Long, String> itemNamesMap = new HashMap<Long, String>();
                            Map<String, Map<Long, Double>> logisticsTxnIdOrderQuantityMap = new HashMap<String, Map<Long, Double>>();
                            
                            for(Order order:orderList){
                                        if(order.getLogistics_provider_id()!=provider.getId())
                                                continue;
                                        LineItem lineItem = order.getLineitems().get(0);
                                        if(order.isSetLogisticsTransactionId()){
                                                if(logisticsTxnIdOrdersMap.containsKey(order.getLogisticsTransactionId())){
                                                        List<Order> ordersList = logisticsTxnIdOrdersMap.get(order.getLogisticsTransactionId());
                                                        ordersList.add(order);
                                                        logisticsTxnIdOrdersMap.put(order.getLogisticsTransactionId(), ordersList);
                                                } else{
                                                        List<Order> ordersList = new ArrayList<Order>();
                                                        ordersList.add(order);
                                                        logisticsTxnIdOrdersMap.put(order.getLogisticsTransactionId(), ordersList);
                                                }
                                                if(logisticsTxnIdOrderQuantityMap.containsKey(order.getLogisticsTransactionId())){
                                                        Map<Long, Double> orderItemQuantityMap = logisticsTxnIdOrderQuantityMap.get(order.getLogisticsTransactionId());
                                                        if(orderItemQuantityMap.containsKey(lineItem.getItem_id())){
                                                                double orderQuantity = orderItemQuantityMap.get(lineItem.getItem_id())+ lineItem.getQuantity();
                                                                orderItemQuantityMap.put(lineItem.getItem_id(),orderQuantity);
                                                                logisticsTxnIdOrderQuantityMap.put(order.getLogisticsTransactionId(), orderItemQuantityMap);
                                                        }else{
                                                                double orderQuantity = lineItem.getQuantity();
                                                                orderItemQuantityMap.put(lineItem.getItem_id(),orderQuantity);
                                                                logisticsTxnIdOrderQuantityMap.put(order.getLogisticsTransactionId(), orderItemQuantityMap);
                                                        }
                                                }else{
                                                        Map<Long, Double> orderItemQuantityMap = new HashMap<Long, Double>();
                                                        orderItemQuantityMap.put(lineItem.getItem_id(), lineItem.getQuantity());
                                                        logisticsTxnIdOrderQuantityMap.put(order.getLogisticsTransactionId(), orderItemQuantityMap);
                                                }
                                        }else{
                                                List<Order> ordersList = new ArrayList<Order>();
                                                ordersList.add(order);
                                                logisticsTxnIdOrdersMap.put(order.getId()+"", ordersList);
                                                Map<Long, Double> orderItemQuantityMap = new HashMap<Long, Double>();
                                                orderItemQuantityMap.put(lineItem.getItem_id(), lineItem.getQuantity());
                                                logisticsTxnIdOrderQuantityMap.put(order.getId()+"", orderItemQuantityMap);
                                        }
                                        if(!itemNamesMap.containsKey(lineItem.getItem_id())){
                                                itemNamesMap.put(lineItem.getItem_id(), getItemDisplayName(lineItem, false));
                                        }
                            }
                            
                            for(String logisticsTxnId : logisticsTxnIdOrdersMap.keySet()){
                                List<Order> ordersList = logisticsTxnIdOrdersMap.get(logisticsTxnId);
                                Warehouse warehouse = inventoryClient.getWarehouse(ordersList.get(0).getWarehouse_id());
                                String accountNo = "";

                                        DeliveryType dt =  DeliveryType.PREPAID;
                                        if (ordersList.get(0).isLogisticsCod()) {
                                                dt = DeliveryType.COD;
                                        }

                                        for (ProviderDetails detail : provider.getDetails()) {
                                                if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
                                                        accountNo = detail.getAccountNo();
                                                }
                                        }
                                        
                                        double totalAmount = 0.0;
                                double totalWeight = 0.0;
                                for(Order o:ordersList){
                                        totalAmount = totalAmount + (o.getTotal_amount()+o.getShippingCost()+o.getCodCharges()-o.getGvAmount());
                                        totalWeight = totalWeight + o.getTotal_weight();
                                }
                                        
                                        AwbDetails detailedAwb = new AwbDetails();

                                        String[] addresses = warehouse.getLocation().split(",+");

                                        detailedAwb.setReturnAddress1((addresses[0].trim() + ", " + addresses[1].trim()).replace("\n", ", "));
                                        detailedAwb.setReturnAddress2((addresses[2].trim() + (addresses.length > 3 ? ", " + addresses[3].trim() : "")).replace("\n", ", "));

                                        String line3 = "";
                                        if(addresses.length > 4) {
                                                for(int i = 4; i<addresses.length; i++) {
                                                        line3 += addresses[i] + ", ";
                                                }
                                        }

                                        if(StringUtils.isNotEmpty(line3)) {
                                                detailedAwb.setReturnAddress3(line3.trim().replace("\n", ", "));
                                        } else {
                                                detailedAwb.setReturnAddress3(EMPTY_STRING);
                                        }
                                        detailedAwb.setReturnPin(warehouse.getPincode());
                                        detailedAwb.setAwbNumber(awbNumber);
                                        detailedAwb.setAccountCode(accountNo);
                                        detailedAwb.setVendorCode((int) ordersList.get(0).getWarehouse_id());
                                        if(ordersList.get(0).isLogisticsCod()){
                                                detailedAwb.setAmountToCollect("" + totalAmount);
                                        } else {
                                                detailedAwb.setAmountToCollect("" + 0 );
                                        }
                                        
                                        if(ordersList.get(0).getShipping_timestamp() > 0) {
                                                Date date = new Date(ordersList.get(0).getShipping_timestamp());
                                                detailedAwb.setAwbDate(date.toString());
                                        } else {
                                                detailedAwb.setAwbDate("N/A");
                                        }

                                        if(ordersList.get(0).getPickupStoreId() > 0) {
                                                PickupStore store = lsc.getClient().getPickupStore(ordersList.get(0).getPickupStoreId());
                                                detailedAwb.setAddress1(store.getLine1());
                                                detailedAwb.setAddress2(store.getLine2());
                                                detailedAwb.setCity(store.getCity());
                                                detailedAwb.setCustomerName("Spice Hotspot");
                                                detailedAwb.setPhoneNumber("" + store.getPhone());
                                                detailedAwb.setPinCode(store.getPin());
                                                detailedAwb.setState(store.getState());
                                        } else {
                                                detailedAwb.setAddress1(ordersList.get(0).getCustomer_address1());
                                                detailedAwb.setAddress2(ordersList.get(0).getCustomer_address2());
                                                detailedAwb.setCity(ordersList.get(0).getCustomer_city());
                                                detailedAwb.setCustomerName(ordersList.get(0).getCustomer_name());
                                                detailedAwb.setPhoneNumber("" + ordersList.get(0).getCustomer_mobilenumber());
                                                detailedAwb.setPinCode(ordersList.get(0).getCustomer_pincode());
                                                detailedAwb.setState(ordersList.get(0).getCustomer_state());
                                        }

                                        detailedAwb.setItemId("" + ordersList.get(0).getLineitems().get(0).getItem_id());
                                        detailedAwb.setOrderId("" + ordersList.get(0).getId());
                                        detailedAwb.setPacketWeight("" + totalWeight);
                                        if(ordersList.get(0).isLogisticsCod()){
                                                detailedAwb.setPaymentMode("COD");
                                        } else {
                                                detailedAwb.setPaymentMode("Prepaid");
                                        }


                                        detailedAwb.setPickupLocation(warehouse.getLocation());
                                        
                                        StringBuffer productNameBuffer = new StringBuffer();
                                    int skuSizeTxn = logisticsTxnIdOrderQuantityMap.get(logisticsTxnId).keySet().size();
                                    int count = 1;
                                    for(Long itemId : logisticsTxnIdOrderQuantityMap.get(logisticsTxnId).keySet()){
                                        Map<Long, Double> quantityMap = logisticsTxnIdOrderQuantityMap.get(logisticsTxnId);
                                        double quantity = quantityMap.get(itemId);
                                        productNameBuffer.append(itemNamesMap.get(itemId)+"("+quantity+")");
                                        if(count<skuSizeTxn){
                                                productNameBuffer.append(",");
                                        }
                                        count++;
                                    }
                                    
                                    detailedAwb.setProductName(productNameBuffer.toString());
                                    LineItem lineitem = ordersList.get(0).getLineitems().get(0);
                                        if (ordersList.get(0).getFreebieItemId() > 0) {
                                                //If order has a freebie order attached with it
                                                detailedAwb.setShipmentValue("" + (ordersList.get(0).getTotal_amount()));
                                        } else {
                                                //else if the order is itself a split freebie order then we don't know how much was the selling price at the time of order
                                                //so we set the transfer price as shipment value
                                                if (lineitem.getExtra_info() != null && lineitem.getExtra_info().contains("Freebie Order for Order ID")) {
                                                        detailedAwb.setShipmentValue("" + (totalAmount));
                                                } else {
                                                        //Else set total amount
                                                        detailedAwb.setShipmentValue("" +totalAmount);
                                                }
                                        }
                                        
                                        if(ordersList.get(0).isSetLogisticsTransactionId()){
                                                detailedAwb.setMasterOrderId(ordersList.get(0).getLogisticsTransactionId());
                                        }else{
                                                detailedAwb.setMasterOrderId("-");
                                        }

                                        tempList.add(detailedAwb);
                            }
                                
                                /*for(Order order : orderList){
                                        Warehouse warehouse = inventoryClient.getWarehouse(order.getWarehouse_id());

                                        String accountNo = "";

                                        DeliveryType dt =  DeliveryType.PREPAID;
                                        if (order.isLogisticsCod()) {
                                                dt = DeliveryType.COD;
                                        }

                                        for (ProviderDetails detail : provider.getDetails()) {
                                                if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
                                                        accountNo = detail.getAccountNo();
                                                }
                                        }

                                        AwbDetails detailedAwb = new AwbDetails();

                                        String[] addresses = warehouse.getLocation().split(",+");

                                        detailedAwb.setReturnAddress1((addresses[0].trim() + ", " + addresses[1].trim()).replace("\n", ", "));
                                        detailedAwb.setReturnAddress2((addresses[2].trim() + (addresses.length > 3 ? ", " + addresses[3].trim() : "")).replace("\n", ", "));

                                        String line3 = "";
                                        if(addresses.length > 4) {
                                                for(int i = 4; i<addresses.length; i++) {
                                                        line3 += addresses[i] + ", ";
                                                }
                                        }

                                        if(StringUtils.isNotEmpty(line3)) {
                                                detailedAwb.setReturnAddress3(line3.trim().replace("\n", ", "));
                                        } else {
                                                detailedAwb.setReturnAddress3(EMPTY_STRING);
                                        }
                                        detailedAwb.setReturnPin(warehouse.getPincode());
                                        detailedAwb.setAwbNumber(awbNumber);
                                        detailedAwb.setAccountCode(accountNo);
                                        detailedAwb.setVendorCode((int) order.getWarehouse_id());
                                        if(order.isLogisticsCod()){
                                                detailedAwb.setAmountToCollect("" + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
                                        } else {
                                                detailedAwb.setAmountToCollect("" + 0 );
                                        }

                                        if(order.getShipping_timestamp() > 0) {
                                                Date date = new Date(order.getShipping_timestamp());
                                                detailedAwb.setAwbDate(date.toString());
                                        } else {
                                                detailedAwb.setAwbDate("N/A");
                                        }

                                        if(order.getPickupStoreId() > 0) {
                                                PickupStore store = lsc.getClient().getPickupStore(order.getPickupStoreId());
                                                detailedAwb.setAddress1(store.getLine1());
                                                detailedAwb.setAddress2(store.getLine2());
                                                detailedAwb.setCity(store.getCity());
                                                detailedAwb.setCustomerName("Spice Hotspot");
                                                detailedAwb.setPhoneNumber("" + store.getPhone());
                                                detailedAwb.setPinCode(store.getPin());
                                                detailedAwb.setState(store.getState());
                                        } else {
                                                detailedAwb.setAddress1(order.getCustomer_address1());
                                                detailedAwb.setAddress2(order.getCustomer_address2());
                                                detailedAwb.setCity(order.getCustomer_city());
                                                detailedAwb.setCustomerName(order.getCustomer_name());
                                                detailedAwb.setPhoneNumber("" + order.getCustomer_mobilenumber());
                                                detailedAwb.setPinCode(order.getCustomer_pincode());
                                                detailedAwb.setState(order.getCustomer_state());
                                        }

                                        detailedAwb.setItemId("" + order.getLineitems().get(0).getItem_id());
                                        detailedAwb.setOrderId("" + order.getId());
                                        detailedAwb.setPacketWeight("" + order.getTotal_weight());
                                        if(order.isLogisticsCod()){
                                                detailedAwb.setPaymentMode("COD");
                                        } else {
                                                detailedAwb.setPaymentMode("Prepaid");
                                        }


                                        detailedAwb.setPickupLocation(warehouse.getLocation());

                                        LineItem lineitem = order.getLineitems().get(0);
                                        detailedAwb.setProductName(lineitem.getBrand() + " " 
                                                        + (lineitem.getModel_name() == null ? "" : lineitem.getModel_name()) + " " 
                                                        + (lineitem.getModel_number() == null ? "" : lineitem.getModel_number()) + " " 
                                                        + (lineitem.getColor() == null ? "" : lineitem.getColor()));
                                        if (order.getFreebieItemId() > 0) {
                                                //If order has a freebie order attached with it
                                                detailedAwb.setShipmentValue("" + (order.getTotal_amount()));
                                        } else {
                                                //else if the order is itself a split freebie order then we don't know how much was the selling price at the time of order
                                                //so we set the transfer price as shipment value
                                                if (lineitem.getExtra_info() != null && lineitem.getExtra_info().contains("Freebie Order for Order ID")) {
                                                        detailedAwb.setShipmentValue("" + (lineitem.getTransfer_price()));
                                                } else {
                                                        //Else set total amount
                                                        detailedAwb.setShipmentValue("" + (order.getTotal_amount()));
                                                }
                                        }
                                        
                                        if(order.isSetLogisticsTransactionId()){
                                                detailedAwb.setMasterOrderId(order.getLogisticsTransactionId());
                                        }else{
                                                detailedAwb.setMasterOrderId("-");
                                        }

                                        tempList.add(detailedAwb);
                                }*/

                        } catch (TTransportException e) {
                                setErrorMsg("Your request cannot be processed due to technical error. Please try later.");
                        } catch (TException e) {
                                setErrorMsg(e.getMessage());
                        } catch (TransactionServiceException e) {
                                setErrorMsg(e.getMessage());
                        } catch (LogisticsServiceException e) {
                                setErrorMsg(e.getMessage());
                        } catch (InventoryServiceException e) {
                                setErrorMsg(e.getMessage());
                        }
                }
                setDetailedAWBs(tempList);
        }


        public ByteArrayOutputStream generateAwbDetailsSheet(List<AwbDetails> awbDetailList) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();;
                Workbook wb = new HSSFWorkbook();
                CreationHelper createHelper = wb.getCreationHelper();
                Sheet sheet = wb.createSheet("Saholic - Data");

                CellStyle dateCellStyle = wb.createCellStyle();
                dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yyyy"));

                CellStyle weightStyle = wb.createCellStyle();
                weightStyle.setDataFormat(createHelper.createDataFormat().getFormat("0.000"));
                
                

                Row headerRow = sheet.createRow((short)0);
                headerRow.createCell(0).setCellValue("Airwaybill");
                headerRow.createCell(1).setCellValue("Type"); //Values : "COD" / "NONCOD"
                headerRow.createCell(2).setCellValue("Master Order Id");
                headerRow.createCell(3).setCellValue("Reference Number"); //OrderId
                headerRow.createCell(4).setCellValue("Sender / Store name"); //"Spice Online retail pvt ltd"
                headerRow.createCell(5).setCellValue("attention"); //Customer name
                headerRow.createCell(6).setCellValue("address1"); //Line 1
                headerRow.createCell(7).setCellValue("address2"); //Line 2
                headerRow.createCell(8).setCellValue("address3"); //city + state
                headerRow.createCell(9).setCellValue("pincode");
                headerRow.createCell(10).setCellValue("tel number"); //Empty
                headerRow.createCell(11).setCellValue("mobile number"); //Empty
                headerRow.createCell(12).setCellValue("Prod/SKU code");  //ItemId
                headerRow.createCell(13).setCellValue("contents"); //Product name
                headerRow.createCell(14).setCellValue("weight");  //In Kgs
                headerRow.createCell(15).setCellValue("Declared Value");  
                headerRow.createCell(16).setCellValue("Collectable Value");
                headerRow.createCell(17).setCellValue("Vendor Code");
                headerRow.createCell(18).setCellValue("Shipper Name");  
                headerRow.createCell(19).setCellValue("Return Address1");
                headerRow.createCell(20).setCellValue("Return Address2");
                headerRow.createCell(21).setCellValue("Return Address3");
                headerRow.createCell(22).setCellValue("Return Pin");
                headerRow.createCell(23).setCellValue("Length ( Cms )");
                headerRow.createCell(24).setCellValue("Bredth ( Cms )");
                headerRow.createCell(25).setCellValue("Height ( Cms )");
                headerRow.createCell(26).setCellValue("Pieces");       
                headerRow.createCell(27).setCellValue("Area_customer_code");
                headerRow.createCell(28).setCellValue("Handover Date ( DD/MM/YYYY )");
                headerRow.createCell(29).setCellValue("Handover Time ( 24 hrs format )");

                int serialNo = 0;

                for(AwbDetails awbDetail : awbDetailList) {
                        //          0  Airwaybill   1 Type    2 Reference Number  3 Sender / Store name 4 attention   5 address1    6 address2    7 address3    
                        //          8 pincode    9 tel number     10 mobile number   11 Prod/SKU code    12 contents    13 weight  
                        //          14 Declared Value   15 Collectable Value   
                        //          16 Vendor Code    17 Shipper Name    18 Return Address1    19 Return Address2    20 Return Address3     21 Return Pin  
                        //          22 Length ( Cms )   23 Breadth ( Cms )      24 Height ( Cms )  
                        //          25 Pieces  26 Area_customer_code  27 Handover Date ( DD/MM/YYYY )   28 Handover Time ( 24 hrs format )  

                        serialNo++;
                        Row contentRow = sheet.createRow((short)serialNo);

                        contentRow.createCell(0).setCellValue(awbDetail.getAwbNumber());
                        contentRow.createCell(1).setCellValue(awbDetail.getPaymentMode().equals("COD") ? "COD" : "NONCOD");
                        contentRow.createCell(2).setCellValue(awbDetail.getMasterOrderId());
                        contentRow.createCell(3).setCellValue(awbDetail.getOrderId());
                        contentRow.createCell(4).setCellValue("Spice Online Retail Pvt Ltd");
                        contentRow.createCell(5).setCellValue(awbDetail.getCustomerName());
                        contentRow.createCell(6).setCellValue(awbDetail.getAddress1());
                        contentRow.createCell(7).setCellValue(awbDetail.getAddress2());
                        contentRow.createCell(8).setCellValue(awbDetail.getCity() + ", " + awbDetail.getState());
                        contentRow.createCell(9).setCellValue(awbDetail.getPinCode());
                        contentRow.createCell(10).setCellValue(awbDetail.getPhoneNumber());
                        contentRow.createCell(11).setCellValue(awbDetail.getPhoneNumber());
                        contentRow.createCell(12).setCellValue(awbDetail.getItemId());
                        contentRow.createCell(13).setCellValue(awbDetail.getProductName());
                        contentRow.createCell(14).setCellValue(awbDetail.getPacketWeight());
                        contentRow.createCell(15).setCellValue(awbDetail.getShipmentValue());
                        contentRow.createCell(16).setCellValue(awbDetail.getAmountToCollect());
                        contentRow.createCell(17).setCellValue(awbDetail.getVendorCode());
                        contentRow.createCell(18).setCellValue("Spice Online Retail Pvt Ltd");
                        contentRow.createCell(19).setCellValue(awbDetail.getReturnAddress1());
                        contentRow.createCell(20).setCellValue(awbDetail.getReturnAddress2());
                        contentRow.createCell(21).setCellValue(awbDetail.getReturnAddress3());
                        contentRow.createCell(22).setCellValue(awbDetail.getReturnPin());
                        contentRow.createCell(23).setCellValue(CourierDetailsController.EMPTY_STRING);
                        contentRow.createCell(24).setCellValue(CourierDetailsController.EMPTY_STRING);
                        contentRow.createCell(25).setCellValue(CourierDetailsController.EMPTY_STRING);
                        contentRow.createCell(26).setCellValue("1");
                        contentRow.createCell(27).setCellValue(awbDetail.getAccountCode());

                        Date date = null;
                        SimpleDateFormat sdf4Date = new SimpleDateFormat("dd/MM/yyyy");                
                        SimpleDateFormat sdf4Time = new SimpleDateFormat("HHmm");

                        if(!awbDetail.getAwbDate().equals("N/A")) {
                                try {
                                        date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(awbDetail.getAwbDate());
                                } catch (ParseException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                }
                                contentRow.createCell(28).setCellValue(sdf4Date.format(date));
                                contentRow.createCell(29).setCellValue(sdf4Time.format(date));
                        } else {
                                contentRow.createCell(28).setCellValue("N/A");
                                contentRow.createCell(29).setCellValue("N/A");
                        }



                        /**
                         * According to javadoc of Date, Date.toString() converts a Date object to a String of the form:
                         * 
                 dow mon dd hh:mm:ss zzz yyyy

            where:

                         * dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
                         * mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
                         * dd is the day of the month (01 through 31), as two decimal digits.
                         * hh is the hour of the day (00 through 23), as two decimal digits.
                         * mm is the minute within the hour (00 through 59), as two decimal digits.
                         * ss is the second within the minute (00 through 61, as two decimal digits.
                         * zzz is the time zone (and may reflect daylight saving time). Standard time zone abbreviations include those recognized by the method parse. If time zone information is not available, then zzz is empty - that is, it consists of no characters at all.
                         * yyyy is the year, as four decimal digits. 
                         * 
                         * And we need to send this in format DD/MM/YYYY and time in HHMM
                         */
                }

                try {
                        wb.write(baos);
                        baos.close();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                return baos;
        }


        /**
         * 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{
                        InventoryClient isc = new InventoryClient();
                        in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient= isc.getClient();
                        List<Warehouse> warehouses = inventoryClient.getShippingLocations();
                        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();
        }

        public String getAwbNumbers() {
                return awbNumbers;
        }

        public void setAwbNumbers(String awbNumbers) {
                this.awbNumbers = awbNumbers;
        }

        public List<AwbDetails> getDetailedAWBs() {
                return detailedAWBs;
        }

        public void setDetailedAWBs(List<AwbDetails> detailedAWBs) {
                this.detailedAWBs = detailedAWBs;
        }

        public String getErrorMsg() {
                return errorMsg;
        }

        public void setErrorMsg(String errorMsg) {
                this.errorMsg = errorMsg;
        }

        public File getAwbFile() {
                return awbFile;
        }

        public void setAwbFile(File awbFile) {
                this.awbFile = awbFile;
        }

        public String getAwbFileContentType() {
                return awbFileContentType;
        }

        public void setAwbFileContentType(String awbFileContentType) {
                this.awbFileContentType = awbFileContentType;
        }

        public String getAwbFileFileName() {
                return awbFileFileName;
        }

        public void setAwbFileFileName(String awbFileFileName) {
                this.awbFileFileName = awbFileFileName;
        }

        public static void main(String[] args) {
                //        CourierDetailsController cdc = new CourierDetailsController();
                //        cdc.setAwbNumbers("4340987735");
                //        String msg = cdc.getAwbDetails();
                //        System.out.println(msg);
                //        //58539182004
                //        //43726980393

                //        String string = "January 2, 2010";
                //        Date date = null;
                //        Calendar cal = Calendar.getInstance();
                //        //cal.set(2014, 0, 20);
                //        
                //        try {
                //            date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(cal.getTime().toString());
                //        } catch (ParseException e) {
                //            // TODO Auto-generated catch block
                //            e.printStackTrace();
                //        }
                //        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                //        System.out.println(sdf.format(date));

                String[] addresses = "fjdaks\n,24/1,hello".split(",+");
                System.out.println(addresses[0].trim());
                System.out.println(addresses[1]);
                System.out.println(addresses[2]);
        }
}