Subversion Repositories SmartDukaan

Rev

Rev 3107 | Blame | Last modification | View Log | RSS feed

package in.shop2020.support.services;

import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.thrift.clients.TransactionClient;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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 java.util.Map.Entry;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PendingOrdersGenerator {
    
    private static Logger logger = LoggerFactory.getLogger(PendingOrdersGenerator.class);
    
        private TransactionClient tsc = null;
        
        public PendingOrdersGenerator(){
                try {
                        tsc = new TransactionClient();
                } catch (Exception e) {
                        logger.error("Error establishing connection to transaction service", e);
                }
        }

        public ByteArrayOutputStream generatePendingOrdersDetails(long warehouseId){
                final int COL_SNO = 0,
                        COL_ORDER_ID = 1,
                        COL_CUSTOMER_NAME = 2,
                        COL_CUTOMER_PHONE = 3, 
                        COL_SHIPPING_LOCATION = 4, 
                        COL_PRODUCT_GROUP = 5,
                        COL_MODEL = 6, 
                        COL_COLOUR = 7,
                        COL_QTY = 8,
                        COL_PRICE = 9;
                final int COL_SUMMARY_SNO = 0, COL_SUMMARY_PRODUCT = 1, COL_SUMMARY_QTY = 2;

                ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
                in.shop2020.model.v1.order.TransactionService.Client txnClient = tsc.getClient();
                List<Order> orders = null;
                
                try {
                        orders = txnClient.batchOrders(warehouseId);
                        //getAllOrders(OrderStatus.SUBMITTED_FOR_PROCESSING, 0L, new Date().getTime(), warehouseId);
                } catch (TransactionServiceException e) {
                        logger.error("Error in transaction service while batching orders", e);
                        return baosXLS;
                } catch (TException e) {
                        logger.error("Error getting info from transaction service", e);
                        return baosXLS;
                }
                
                Workbook wb = new HSSFWorkbook();
                CreationHelper createHelper = wb.getCreationHelper();
            Sheet detailedSheet = wb.createSheet("Detailed sheet");
            detailedSheet.getPrintSetup().setLandscape(true); // Sets the print orientation as Landscape, by default its Portrait.
            detailedSheet.setMargin(Sheet.RightMargin, 0.5);
            detailedSheet.setPrintGridlines(true);
            Sheet summarySheet = wb.createSheet("Summary sheet");
            summarySheet.setPrintGridlines(true);
            Map<String, Double> summaryMap = new HashMap<String, Double>(); 
        
        CellStyle csRA = wb.createCellStyle();
        csRA.setAlignment(CellStyle.ALIGN_RIGHT);
        
        CellStyle csWT = wb.createCellStyle();
        csWT.setWrapText(true);
        
        CellStyle weightStyle = wb.createCellStyle();
            weightStyle.setDataFormat(createHelper.createDataFormat().getFormat("0.00"));

        Calendar date = new GregorianCalendar();
                int year = date.get(Calendar.YEAR);
                int month = date.get(Calendar.MONTH) +1;
                int day = date.get(Calendar.DAY_OF_MONTH);
                int hour = date.get(Calendar.HOUR_OF_DAY);
                int minute = date.get(Calendar.MINUTE);
            
            Row dateRow = detailedSheet.createRow(1);
            dateRow.createCell(2).setCellValue("Date");
            dateRow.createCell(3).setCellValue(String.format("%4d-%02d-%02d", year, month, day));
            
            Row timeRow = detailedSheet.createRow(2);
            timeRow.createCell(2).setCellValue("Time");
            timeRow.createCell(3).setCellValue(String.format("%02d:%02d", hour, minute));
            
            Row batchRow = detailedSheet.createRow(3);
            batchRow.createCell(2).setCellValue("Batch No.");
            batchRow.createCell(3).setCellValue(orders.get(0).getBatchNo() + "");
            
            Row detailsHeaderRow = detailedSheet.createRow(5);
            detailsHeaderRow.createCell(COL_SNO).setCellValue("SNo");
            detailsHeaderRow.createCell(COL_ORDER_ID).setCellValue("Order ID");

            detailsHeaderRow.createCell(COL_CUSTOMER_NAME).setCellValue("Customer Name");
            detailedSheet.setColumnWidth(COL_CUSTOMER_NAME, 5000);
            
            detailsHeaderRow.createCell(COL_CUTOMER_PHONE).setCellValue("Customer Phone");
            
            detailsHeaderRow.createCell(COL_SHIPPING_LOCATION).setCellValue("Shipping Location");
            detailedSheet.setColumnWidth(COL_SHIPPING_LOCATION, 5000);
            
            detailsHeaderRow.createCell(COL_PRODUCT_GROUP).setCellValue("Product Group");
            
            detailsHeaderRow.createCell(COL_MODEL).setCellValue("Brand / Model");
            detailedSheet.setColumnWidth(COL_MODEL, 5000);
            
            detailsHeaderRow.createCell(COL_COLOUR).setCellValue("Colour");
            detailsHeaderRow.createCell(COL_QTY).setCellValue("QTY.");
            detailsHeaderRow.getCell(COL_QTY).setCellStyle(csRA);
            detailsHeaderRow.createCell(COL_PRICE).setCellValue("Price");
            detailsHeaderRow.getCell(COL_PRICE).setCellStyle(csRA);
            
            
            Row summaryHeaderRow = summarySheet.createRow((short)0);
            summaryHeaderRow.createCell(COL_SUMMARY_SNO).setCellValue("Sl No.");
            summaryHeaderRow.createCell(COL_SUMMARY_PRODUCT).setCellValue("Product");
            summaryHeaderRow.createCell(COL_SUMMARY_QTY).setCellValue("Quantity");
            
            short rowNum = 5;
            String customerName, shippingLocation, brandModel;
            float rowHeight = detailedSheet.getDefaultRowHeightInPoints();
            for(int i = 0; i<orders.size(); i++){
                Order order = orders.get(i);
                        rowNum++;
                Row contentRow = detailedSheet.createRow(rowNum);
                    contentRow.createCell(COL_SNO).setCellValue(order.getSerialNo() + "");                  
                    contentRow.createCell(COL_ORDER_ID).setCellValue(order.getId() + "");
                    
                    customerName = getValueForEmptyString(order.getCustomer_name());
                    contentRow.createCell(COL_CUSTOMER_NAME).setCellValue(customerName);
                    contentRow.getCell(COL_CUSTOMER_NAME).setCellStyle(csWT);
                    
                    contentRow.createCell(COL_CUTOMER_PHONE).setCellValue(getValueForEmptyString(order.getCustomer_mobilenumber()));
                    
                    shippingLocation = getValueForEmptyString(order.getCustomer_city()) + " (" + 
                                getValueForEmptyString(order.getCustomer_state()) + ")";
                    contentRow.createCell(COL_SHIPPING_LOCATION).setCellValue(shippingLocation);
                    contentRow.getCell(COL_SHIPPING_LOCATION).setCellStyle(csWT);

                    List<LineItem> lineItems = order.getLineitems();
                    LineItem lineItem = lineItems.get(0);
                    contentRow.createCell(COL_PRODUCT_GROUP).setCellValue(getValueForEmptyString(lineItem.getProductGroup()));
                    
                    brandModel = getValueForEmptyString(lineItem.getBrand()) + " / " + 
                        lineItem.getModel_number() + " " + getValueForEmptyString(lineItem.getModel_name());
                    contentRow.createCell(COL_MODEL).setCellValue(brandModel);
                    contentRow.getCell(COL_MODEL).setCellStyle(csWT);
                    
                    contentRow.createCell(COL_COLOUR).setCellValue(lineItem.getColor());
                    contentRow.createCell(COL_QTY).setCellValue(lineItem.getQuantity());
                    contentRow.createCell(COL_PRICE).setCellValue(lineItem.getTotal_price());
                    contentRow.getCell(COL_PRICE).setCellStyle(weightStyle);
                    
                    int maxLength = Math.max(brandModel.length(), Math.max(customerName.length(), shippingLocation.length()));
                    contentRow.setHeightInPoints((maxLength / (5000/256) + 1) * rowHeight);  // Set Row Height
                    
                    //Add this item to the summary map to print the summary sheet
                    String itemKey = lineItem.getProductGroup() + " " + 
                                                lineItem.getBrand() + " " +
                                                lineItem.getModel_number() + " " +
                                                getValueForEmptyString(lineItem.getModel_name()) + " " +
                                                getValueForEmptyString(lineItem.getColor());
                    Double quantity = summaryMap.get(itemKey);
                    if(quantity != null){
                        quantity = quantity + lineItem.getQuantity();
                    }else{
                        quantity = lineItem.getQuantity();
                    }
                    summaryMap.put(itemKey, quantity);
            }
            
            detailedSheet.autoSizeColumn(COL_SNO);
            detailedSheet.autoSizeColumn(COL_ORDER_ID);
            detailedSheet.autoSizeColumn(COL_CUTOMER_PHONE);
            detailedSheet.autoSizeColumn(COL_PRODUCT_GROUP);
            detailedSheet.autoSizeColumn(COL_COLOUR);
            detailedSheet.autoSizeColumn(COL_QTY);
            detailedSheet.autoSizeColumn(COL_PRICE);
            
            
            rowNum = 1;
            for(Entry<String, Double> entry : summaryMap.entrySet()){
                Row summaryRow = summarySheet.createRow(rowNum);
                summaryRow.createCell(COL_SUMMARY_SNO).setCellValue(rowNum);
                summaryRow.createCell(COL_SUMMARY_PRODUCT).setCellValue(entry.getKey());
                summaryRow.createCell(COL_SUMMARY_QTY).setCellValue(entry.getValue());
                rowNum++;
            }
            
            summarySheet.autoSizeColumn(COL_SUMMARY_PRODUCT);
            // Write the workbook to the output stream
                try {
                        wb.write(baosXLS);
                        baosXLS.close();
                } catch (IOException e) {
                        logger.error("Error streaming pending orders report", e);
                }
                return baosXLS;
        }
        
        private String getValueForEmptyString(String s){
                if(s==null || s.equals(""))
                        return " ";
                else
                        return s; 
        }
        
        public static void main(String[] args) {
                PendingOrdersGenerator pendingOrdersGenerator = new PendingOrdersGenerator();
                try {
                        String userHome = System.getProperty("user.home");
                        FileOutputStream f = new FileOutputStream(userHome + "/pending-orders.xls");
                        ByteArrayOutputStream baosXLS = pendingOrdersGenerator.generatePendingOrdersDetails(1);
                        baosXLS.writeTo(f);
                        f.close();
                } catch (FileNotFoundException e) {
                        logger.error("Error while creating the pending orders report", e);
                } catch (IOException e) {
                        logger.error("IO error while writing the pending orders report", e);
                }
                System.out.println("Successfully generated the pending orders report");
        }
}