Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.support.services;

import in.shop2020.logistics.LogisticsServiceException;
import in.shop2020.logistics.PickUpType;
import in.shop2020.logistics.PickupStore;
import in.shop2020.logistics.Provider;
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.OrderStatus;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.thrift.clients.InventoryClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.TransactionClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class ManifestGenerator {
    
    private static Logger logger = LoggerFactory.getLogger(ManifestGenerator.class);
    
        private TransactionClient tsc = null;
        private InventoryClient csc = null;
        private LogisticsClient lsc = null;
        private DecimalFormat weightFormat = new DecimalFormat("0.000");
        public ManifestGenerator() {
                try {
                        tsc = new TransactionClient();
                        csc = new InventoryClient();
                        lsc = new LogisticsClient();
                } catch (Exception e) {
                    logger.error("Error while initializing one of the thrift clients", e);
                }
        }

        public ByteArrayOutputStream generateManifestFile(long warehouseId,     long providerId, boolean isCod, List<Long> orderIds, String runner) {
                ByteArrayOutputStream baosPDF = null;
                in.shop2020.model.v1.order.TransactionService.Client txnClient = tsc.getClient();
                in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = csc.getClient();
                in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
                
                List<OrderStatus> statuses = new ArrayList<OrderStatus>();
                statuses.add(OrderStatus.BILLED);
                
                List<Order> orders = null;
                Warehouse warehouse = null;
                Provider provider = null;
                List<PickupStore> stores = null;
                try {
                        orders = txnClient.getOrdersInBatch(statuses, 0, 0, warehouseId);
                        warehouse = inventoryClient.getWarehouse(warehouseId);
                        provider = logisticsClient.getProvider(providerId);
                        stores = logisticsClient.getAllPickupStores();
                } catch (TException e) {
                    logger.error("Error getting information from one of the Thrift Services: ", e);
                        return baosPDF;
                } catch (InventoryServiceException e) {
                    logger.error("Error getting warehouse info from the catalog service: ", e);
                        return baosPDF;
                } catch (LogisticsServiceException e) {
                    logger.error("Error getting provider info from the logistics service: ", e);
                        return baosPDF;
                } catch (TransactionServiceException e) {
                    logger.error("Error getting orders from the transaction service: ", e);
                        return baosPDF;
                }
                
                try {
                        baosPDF = new ByteArrayOutputStream();
                        Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
                        Document document = new Document();
                        PdfWriter.getInstance(document, baosPDF);
                        document.addAuthor("shop2020");
                        document.addTitle("Manifest for warehouse " + warehouseId + " provider " + providerId);
                        document.open();
                        PdfPTable table = new PdfPTable(1);
                        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        table.getDefaultCell().setPaddingBottom(10.0f);
                        
                        String logoPath = ManifestGenerator.class.getResource("/logo.jpg").getPath();
                        PdfPCell logoCell = new PdfPCell(Image.getInstance(logoPath), false);
                        logoCell.setBorder(Rectangle.NO_BORDER);
                         
                        String addressString =  warehouse.getLocation() + "\nPIN " + warehouse.getPincode()+ "\n\n";
                        Paragraph addressParagraph = new Paragraph(addressString, new Font(FontFamily.TIMES_ROMAN,8f));
                        PdfPCell addressCell = new PdfPCell();
                        addressCell.addElement(addressParagraph);
                        addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                        addressCell.setBorder(Rectangle.NO_BORDER);
                        
                        PdfPTable ordersTable = new PdfPTable(8);
                        ordersTable.addCell(new Phrase("Sl No", helvetica8));
                        ordersTable.addCell(new Phrase("Order No", helvetica8));
                        ordersTable.addCell(new Phrase("AWB No", helvetica8));
                        ordersTable.addCell(new Phrase("Packet Wt.", helvetica8));
                        if(runner == null){
                                ordersTable.addCell(new Phrase("Name", helvetica8));
                                ordersTable.addCell(new Phrase("Destination City", helvetica8));
                                ordersTable.addCell(new Phrase("Pincode", helvetica8));
                                ordersTable.addCell(new Phrase("State", helvetica8));
                        }else{
                                ordersTable.addCell(new Phrase("Store Code", helvetica8));
                                ordersTable.addCell(new Phrase("Store Address", helvetica8));
                                ordersTable.addCell(new Phrase("Store City", helvetica8));
                                ordersTable.addCell(new Phrase("Phone", helvetica8));
                        }
                        
                        int serialNo = 0;
                        for(int i=0; i < orders.size();i++){
                                Order order = orders.get(i);
                                if(!orderIds.contains(order.getId()))
                                        continue;
                                if(order.getLogistics_provider_id()!=providerId)
                                        continue;
                                if(order.isLogisticsCod() != isCod)
                        continue;
                                //TODO: These are exactly the orders which will be shipped now. Shouldn't we change their status to be SHIPPED?
                                serialNo++;
                                List<LineItem> lineItems = order.getLineitems();
                                double weight = 0;
                                for(LineItem lineItem: lineItems)
                                        weight += lineItem.getTotal_weight();
                                
                                ordersTable.addCell(new Phrase(serialNo + "", helvetica8));
                                ordersTable.addCell(new Phrase(order.getId() + "", helvetica8));
                                ordersTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
                                ordersTable.addCell(new Phrase(weightFormat.format(weight), helvetica8));
                                if(runner == null){
                                        ordersTable.addCell(new Phrase(order.getCustomer_name(), helvetica8));
                                        ordersTable.addCell(new Phrase(order.getCustomer_city(), helvetica8));
                                        ordersTable.addCell(new Phrase(order.getCustomer_pincode(), helvetica8));
                                        ordersTable.addCell(new Phrase(order.getCustomer_state(), helvetica8));
                                }else{
                                        PickupStore store = getStoreFromId(stores, order.getPickupStoreId());
                                        ordersTable.addCell(new Phrase(store.getHotspotId(), helvetica8));
                                        ordersTable.addCell(new Phrase(store.getLine1() + ((store.getLine2() == null)? "": "\n" + store.getLine2()), helvetica8));
                                        ordersTable.addCell(new Phrase(store.getCity(), helvetica8));
                                        ordersTable.addCell(new Phrase(store.getPhone(), helvetica8));
                                }
                        }
                        
                        table.addCell(logoCell);
                        table.addCell(addressCell);
                        if(isCod)
                            table.addCell(new Phrase("PAYMODE: COD", helvetica8));
                        else
                            table.addCell(new Phrase("PAYMODE: Prepaid", helvetica8));
                        if(provider.getPickup() == PickUpType.RUNNER){
                                table.addCell(new Phrase("Runner Name: " + runner, helvetica8));
                        }else{
                                table.addCell(new Phrase("Courier Name: " + provider.getName(), helvetica8));
                        }
                        
                        table.addCell(new Phrase("Pick up Date: " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
                        table.addCell(ordersTable);
                        table.setWidthPercentage(90.0f);
                        
                        document.add(table);  
                        document.close();
                        baosPDF.close();
                } catch (DocumentException e) {
                    logger.error("Error while creating the manifest file", e);
                } catch (MalformedURLException e) {
                    logger.error("Error while creating the manifest file", e);
                } catch (IOException e) {
                        logger.error("Error while creating the manifest file", e);
                }

                return baosPDF;
        }

        private static PickupStore getStoreFromId(List<PickupStore> stores, long storeId){
                for(PickupStore store: stores){
                        if(store.getId() == storeId)
                                return store;
                }
                return null;
        }
        
        
        public ByteArrayOutputStream generateManifestFile(long providerId, long storeId, List<Long> orderIds, List<String> awbs) {
                ByteArrayOutputStream baosPDF = null;
                in.shop2020.model.v1.order.TransactionService.Client txnClient = tsc.getClient();
                in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
                
                List<OrderStatus> statuses = new ArrayList<OrderStatus>();
                statuses.add(OrderStatus.RET_PICKUP_REQUEST_RAISED);
                
                List<Order> orders = null;
                PickupStore store = null;
                Provider provider = null;
                try {
                        orders = txnClient.getOrdersInBatch(statuses, 0, 0, 0);
                        store = logisticsClient.getPickupStore(storeId);
                        provider = logisticsClient.getProvider(providerId);
                } catch (TException e) {
                    logger.error("Error getting information from one of the Thrift Services: ", e);
                        return baosPDF;
                } catch (LogisticsServiceException e) {
                    logger.error("Error getting provider info from the logistics service: ", e);
                        return baosPDF;
                } catch (TransactionServiceException e) {
                    logger.error("Error getting orders from the transaction service: ", e);
                        return baosPDF;
                }
                
                try {
                        baosPDF = new ByteArrayOutputStream();
                        Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
                        Document document = new Document();
                        PdfWriter.getInstance(document, baosPDF);
                        document.addAuthor("shop2020");
                        document.addTitle("Manifest for store " + storeId + " provider " + providerId);
                        document.open();
                        PdfPTable table = new PdfPTable(1);
                        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                        table.getDefaultCell().setPaddingBottom(10.0f);
                        
                        String addressString =  store.getName() +  "\n" + store.getLine1() + ((store.getLine2() == null)? "": "\n" + store.getLine2()) 
                                                                        + "\n" + store.getCity()  + "\n" + store.getState() + "\nPIN " + store.getPin()+ "\n\n";
                        Paragraph addressParagraph = new Paragraph(addressString, new Font(FontFamily.TIMES_ROMAN,8f));
                        PdfPCell addressCell = new PdfPCell();
                        addressCell.addElement(addressParagraph);
                        addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                        addressCell.setBorder(Rectangle.NO_BORDER);
                        
                        PdfPTable ordersTable = new PdfPTable(4);
                        ordersTable.addCell(new Phrase("Sl No", helvetica8));
                        ordersTable.addCell(new Phrase("Order No", helvetica8));
                        ordersTable.addCell(new Phrase("AWB No", helvetica8));
                        ordersTable.addCell(new Phrase("Packet Wt.", helvetica8));
                        
                        int serialNo = 0;
                        for(int i=0; i < orders.size();i++){
                                Order order = orders.get(i);
                                if(!orderIds.contains(order.getId()))
                                        continue;
                                if(order.getLogistics_provider_id()!=providerId)
                                        continue;
                                if(order.getPickupStoreId()!=storeId)
                                        continue;
                                //TODO: These are exactly the orders which will be shipped now. Shouldn't we change their status to be SHIPPED?
                                serialNo++;
                                List<LineItem> lineItems = order.getLineitems();
                                double weight = 0;
                                for(LineItem lineItem: lineItems)
                                        weight += lineItem.getTotal_weight();
                                
                                ordersTable.addCell(new Phrase(serialNo + "", helvetica8));
                                ordersTable.addCell(new Phrase(order.getId() + "", helvetica8));
                                ordersTable.addCell(new Phrase(awbs.get(orderIds.indexOf(order.getId())), helvetica8));
                                ordersTable.addCell(new Phrase(weightFormat.format(weight), helvetica8));
                        }
                        
                        table.addCell(addressCell);
                        table.addCell(new Phrase("Courier Name: " + provider.getName(), helvetica8));
                        table.addCell(new Phrase("Pick up Date: " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
                        table.addCell(ordersTable);
                        table.setWidthPercentage(90.0f);
                        
                        document.add(table);  
                        document.close();
                        baosPDF.close();
                } catch (DocumentException e) {
                    logger.error("Error while creating the manifest file", e);
                } catch (MalformedURLException e) {
                    logger.error("Error while creating the manifest file", e);
                } catch (IOException e) {
                        logger.error("Error while creating the manifest file", e);
                }

                return baosPDF;
        }

        public static void main(String[] args) throws IOException {
                ManifestGenerator manifestGenerator = new ManifestGenerator();
                ByteArrayOutputStream baos = manifestGenerator.generateManifestFile(1, 1, true, null, null);
                File f = new File("/home/ashish/Downloads/manifest-1-2.pdf");
                FileOutputStream fos = new FileOutputStream(f);
                baos.writeTo(fos);
        }
}