Rev 24012 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.inventory.service;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.text.DateFormat;import java.text.MessageFormat;import java.util.Calendar;import java.util.Date;import java.util.List;import java.util.Map;import org.apache.commons.lang.StringUtils;import org.apache.thrift.TException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.itextpdf.text.Document;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.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;import in.shop2020.model.v1.catalog.CatalogServiceException;import in.shop2020.model.v1.inventory.InventoryService;import in.shop2020.model.v1.inventory.StateInfo;import in.shop2020.model.v1.inventory.VendorItemMapping;import in.shop2020.model.v1.order.BuyerInfo;import in.shop2020.model.v1.order.WarehouseAddress;import in.shop2020.purchase.PurchaseOrder;import in.shop2020.purchase.Supplier;import in.shop2020.purchase.TaxType;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.thrift.clients.InventoryClient;import in.shop2020.thrift.clients.TransactionClient;public class PdfPoSheetGenerator {private static Logger logger = LoggerFactory.getLogger(PdfPoSheetGenerator.class);private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);public static Map<Long, StateInfo> stateIdMap = null;public static InventoryService.Client inventoryClient = null;static String CONTACT_FORMAT = "Mr. {0}, Contact No. +91 {1}";static {try {inventoryClient = new InventoryClient().getClient();stateIdMap = inventoryClient.getStateMaster();} catch (Exception e) {logger.error("Unable to get State Info Map", e);}}public static String generatePdfSheet(PurchaseOrder purchaseOrder, Supplier supplier) throws IOException {ByteArrayOutputStream baosPDF = null;try {in.shop2020.model.v1.order.TransactionService.Client tClient = new TransactionClient().getClient();BuyerInfo binfo = tClient.getBuyerByWarehouse(purchaseOrder.getWarehouseId());baosPDF = new ByteArrayOutputStream();Document document = new Document();PdfWriter.getInstance(document, baosPDF);document.addAuthor("shop2020");document.addTitle("Purchase Order No: " + purchaseOrder.getPoNumber());document.open();PdfPTable poTable = getPoTable(purchaseOrder, supplier, binfo);poTable.setSpacingAfter(10.0f);poTable.setWidthPercentage(100.0f);document.add(poTable);document.close();baosPDF.close();} catch (Exception e) {logger.error("Error while generating Invoice: ", e);e.printStackTrace();}String tmpDir = System.getProperty("java.io.tmpdir");String filename = tmpDir + "/NSSPL-" + purchaseOrder.getId() + ".pdf";File f = new File(filename);FileOutputStream fos = new FileOutputStream(f);baosPDF.writeTo(fos);return filename;}private static PdfPTable getPoTable(PurchaseOrder purchaseOrder, Supplier supplier, BuyerInfo binfo) throws Exception {PdfPTable poTable = new PdfPTable(1);poTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);poTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);PdfPCell poTitleCell = new PdfPCell(new Phrase("Purchase Order", helveticaBold12));poTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);poTitleCell.setBorder(Rectangle.NO_BORDER);long poValidityLimit = supplier.getPoValidityLimit();Calendar cal1 = Calendar.getInstance();cal1.setTimeInMillis(purchaseOrder.getCreatedAt());cal1.add(Calendar.DAY_OF_MONTH, (int) poValidityLimit);Date poDate = new Date(purchaseOrder.getCreatedAt());Date poExpiryDate = new Date(cal1.getTimeInMillis());PdfPTable poSummaryTable = new PdfPTable(new float[] { 0.3f, 0.3f, 0.4f });poSummaryTable.addCell(new PdfPCell(new Phrase("PO No: " + purchaseOrder.getPoNumber())));poSummaryTable.addCell(new PdfPCell(new Phrase("Date: " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(poDate))));poSummaryTable.addCell(new PdfPCell(new Phrase("PO Valid for delivery by: "+ DateFormat.getDateInstance(DateFormat.MEDIUM).format(poExpiryDate))));poSummaryTable.setSpacingBefore(10.0f);poTable.addCell(poTitleCell);poTable.addCell(getAddressCell(purchaseOrder, binfo));poTable.addCell(poSummaryTable);poTable.addCell(getSalutationTable(supplier));poTable.addCell(getPoDetailsTable(purchaseOrder, supplier, binfo));poTable.addCell(getBillToTable(purchaseOrder));// poTable.addCell(getCFormCell(purchaseOrder.getTaxType()));if(supplier.isSetTnc()) {poTable.addCell(getTncTable(supplier.getTnc()));}return poTable;}/** private static PdfPCell getCFormCell(TaxType taxType) { PdfPCell* cFormCell = null; if(taxType == TaxType.CFORM) { cFormCell = new* PdfPCell(new Paragraph("*To be billed on CST Against C-Form ", new* Font(FontFamily.TIMES_ROMAN, 8f))); } else { cFormCell = new PdfPCell();* } cFormCell.setBorder(Rectangle.NO_BORDER);* cFormCell.setHorizontalAlignment(Element.ALIGN_LEFT); return cFormCell; }*/private static PdfPTable getAddressCell(PurchaseOrder purchaseOrder, BuyerInfo binfo) {// TODO Write this code in a proper configurable wayString address = "";String tinNo = "";String shippingAddress = "";try {in.shop2020.model.v1.order.TransactionService.Client tClient = new TransactionClient().getClient();WarehouseAddress addr = tClient.getWarehouseAddress(purchaseOrder.getWarehouseAddressId());tinNo = binfo.getTin();address = binfo.getOrganisationName() + "\n" + addr.getAddress() + "\n" + "-" + addr.getPin();} catch (Exception e) {logger.error("This should not happen", e);}PdfPTable billToShipToTable = new PdfPTable(2);Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));PdfPCell addressCell = new PdfPCell();if (purchaseOrder.getWarehouseId() != purchaseOrder.getShippingWarehouseId()) {addressParagraph = new Paragraph("Bill To :\n" + address + "\n\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f));}addressCell.addElement(addressParagraph);// addressCell.setHorizontalAlignment(Element.ALIGN_CENTER);addressCell.setBorder(Rectangle.NO_BORDER);if (purchaseOrder.getWarehouseId() != purchaseOrder.getShippingWarehouseId()) {try {in.shop2020.model.v1.order.TransactionService.Client tClient = new TransactionClient().getClient();WarehouseAddress addr = tClient.getWarehouseAddress(purchaseOrder.getShippingWarehouseAddressId());address = binfo.getOrganisationName() + "\n" + addr.getAddress() + "\n" + "-" + addr.getPin();} catch (Exception e) {logger.error("This should not happen", e);}PdfPCell billToShipToCell = new PdfPCell();billToShipToCell.setHorizontalAlignment(Element.ALIGN_LEFT);billToShipToCell.setBorder(Rectangle.NO_BORDER);PdfPCell shippingAddressCell = new PdfPCell();shippingAddressCell.addElement(new Paragraph("Ship To :\n" + shippingAddress + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f)));shippingAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);shippingAddressCell.setBorder(Rectangle.LEFT);billToShipToTable.addCell(addressCell);billToShipToTable.addCell(shippingAddressCell);billToShipToCell.addElement(billToShipToTable);return billToShipToTable;}billToShipToTable.addCell(addressCell);PdfPCell placeHolderCell = new PdfPCell();placeHolderCell.setBorder(Rectangle.NO_BORDER);billToShipToTable.addCell(placeHolderCell);return billToShipToTable;}private static PdfPTable getSalutationTable(Supplier supplier) throws Exception {PdfPTable salutationTable = new PdfPTable(1);salutationTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);salutationTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);salutationTable.addCell(new Phrase("To", helvetica8));if (supplier.getName().equals("Smobility Ltd.")) {salutationTable.addCell(new Phrase("Spice Retail Ltd.", helvetica8));} else if (supplier.getName().equals("Smobility Ltd. - Mumbai")) {salutationTable.addCell(new Phrase("Spice Retail Ltd. Mumbai", helvetica8));} else {salutationTable.addCell(new Phrase(supplier.getName(), helvetica8));}salutationTable.addCell(new Paragraph(supplier.getCommunicationAddress(), helvetica8));salutationTable.addCell(new Phrase("Dear Sir/Madam", helveticaBold8));salutationTable.addCell(new Phrase("Please supply the following stocks as per the details given below:", helvetica8));salutationTable.addCell(new Phrase(" "));return salutationTable;}private static PdfPTable getPoDetailsTable(PurchaseOrder purchaseOrder, Supplier supplier, BuyerInfo binfo)throws CatalogServiceException, TException {float[] widths;TaxType taxType = purchaseOrder.getTaxType();if(taxType.equals(TaxType.SGST)){widths = new float[] { 0.05f, 0.25f, 0.09f, 0.1f, 0.09f, 0.09f, 0.09f, 0.07f, 0.1f, 0.07f, 0.1f };} else {widths = new float[] { 0.1f, 0.27f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.08f, 0.1f };}PdfPTable detailsTable = new PdfPTable(widths);PdfPCell slNoCell = getHeaderCell("Sl. No");detailsTable.addCell(slNoCell);PdfPCell description = getHeaderCell("Description");detailsTable.addCell(description);PdfPCell hsnCodeCell = getHeaderCell("HSN Code");detailsTable.addCell(hsnCodeCell);PdfPCell qtyCell = getHeaderCell("Qty");detailsTable.addCell(qtyCell);PdfPCell rateCell = getHeaderCell("Rate");detailsTable.addCell(rateCell);PdfPCell totalCell = getHeaderCell("Total Value");detailsTable.addCell(totalCell);PdfPCell taxableAmontCell = getHeaderCell("Taxable Value");taxableAmontCell.setRowspan(2);detailsTable.addCell(taxableAmontCell);if(taxType.equals(TaxType.SGST)) {PdfPCell cell1 = new PdfPCell(new Phrase("CGST", helveticaBold8));cell1.setColspan(2);cell1.setHorizontalAlignment(Element.ALIGN_CENTER);detailsTable.addCell(cell1);PdfPCell cell2 = new PdfPCell(new Phrase("SGST", helveticaBold8));cell2.setHorizontalAlignment(Element.ALIGN_CENTER);cell2.setColspan(2);detailsTable.addCell(cell2);} else {PdfPCell cell3 = new PdfPCell(new Phrase("IGST", helveticaBold8));cell3.setHorizontalAlignment(Element.ALIGN_CENTER);cell3.setRowspan(2);detailsTable.addCell(cell3);}if(taxType.equals(TaxType.SGST)) {detailsTable.addCell(new Phrase("Rate(%)", helveticaBold8));detailsTable.addCell(new Phrase("Amount", helveticaBold8));detailsTable.addCell(new Phrase("Rate(%)", helveticaBold8));detailsTable.addCell(new Phrase("Amount", helveticaBold8));}else {detailsTable.addCell(new Phrase("Rate(%)", helveticaBold8));detailsTable.addCell(new Phrase("Amount", helveticaBold8));}int slNo = 0;double total = 0;double vatFactor = 0;double totalUnits = 0;String stateCode = null;CatalogClient cClient = new CatalogClient();in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = cClient.getClient();for (in.shop2020.purchase.LineItem lineitem : purchaseOrder.getLineitems()) {slNo++;detailsTable.addCell(new Phrase(slNo + "", helvetica8));detailsTable.addCell(getProductNameCell(lineitem, purchaseOrder.getSupplierId()));detailsTable.addCell(new Phrase(lineitem.getHsnCode(), helvetica8));detailsTable.addCell(new Phrase(String.format("%d Units", (int)lineitem.getQuantity()), helvetica8));detailsTable.addCell(new Phrase(String.format("%.2f", lineitem.getUnitPrice()), helvetica8));double totalAmount = lineitem.getUnitPrice()*lineitem.getQuantity();detailsTable.addCell(new Phrase(String.format("%.2f", totalAmount), helvetica8));double totalTaxRate = lineitem.getIgstRate() + lineitem.getSgstRate() + lineitem.getCgstRate();double taxableAmount = totalAmount / (1 + (totalTaxRate / 100));detailsTable.addCell(new Phrase(String.format("%.2f", taxableAmount), helvetica8));if(purchaseOrder.getTaxType().equals(TaxType.SGST)) {double cgstAmount = taxableAmount * (lineitem.getCgstRate() / 100);detailsTable.addCell(new Phrase(String.format("%.2f", lineitem.getCgstRate()), helvetica8));detailsTable.addCell(new Phrase(String.format("%.2f", cgstAmount), helvetica8));double sgstAmount = taxableAmount * (lineitem.getSgstRate() / 100);detailsTable.addCell(new Phrase(String.format("%.2f", lineitem.getSgstRate()), helvetica8));detailsTable.addCell(new Phrase(String.format("%.2f", sgstAmount), helvetica8));} else {double igstAmount = taxableAmount * (lineitem.getIgstRate() / 100);detailsTable.addCell(new Phrase(String.format("%.2f", lineitem.getIgstRate()), helvetica8));detailsTable.addCell(new Phrase(String.format("%.2f", igstAmount), helvetica8));}totalUnits += lineitem.getQuantity();total += totalAmount;}if(purchaseOrder.getTaxType().equals(TaxType.SGST)) {detailsTable.addCell(getTotalCell(3));detailsTable.addCell(new Phrase(String.format("%.0f", totalUnits), helvetica8));detailsTable.addCell(getTotalAmountCell(7, total));} else {detailsTable.addCell(getTotalCell(2));detailsTable.addCell(new Phrase(String.format("%.0f", totalUnits), helvetica8));detailsTable.addCell(getTotalAmountCell(6, total));}return detailsTable;}private static PdfPCell getHeaderCell(String headerName) {PdfPCell cell = new PdfPCell(new Phrase(headerName, helveticaBold8));cell.setRowspan(2);cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setVerticalAlignment(Element.ALIGN_MIDDLE);return cell;}private static PdfPTable getTncTable(String tnc) {PdfPTable tncTable = new PdfPTable(new float[] { 1f });tncTable.addCell(new Phrase("Terms & Conditions", helveticaBold8));tncTable.addCell(new Phrase(tnc, helvetica8));return tncTable;}private static PdfPTable getBillToTable(PurchaseOrder po) {// TODO Write this code in a proper configurable wayString address = "";String gstin = "";String contactPerson = "Neeraj Gupta";String contactNumber = "9873802000";BuyerInfo binfo = new BuyerInfo();try {in.shop2020.model.v1.order.TransactionService.Client tClient = new TransactionClient().getClient();binfo = tClient.getBuyerByWarehouse(po.getWarehouseId());gstin = binfo.getGstin();WarehouseAddress addr = tClient.getWarehouseAddress(po.getWarehouseAddressId());address = binfo.getOrganisationName() + "\n" + addr.getAddress() + "\n" + "-" + addr.getPin();if (StringUtils.isNotBlank(addr.getContact_person())) {contactPerson = addr.getContact_person();}if (StringUtils.isNotBlank(addr.getContact_number())) {contactNumber = addr.getContact_number();}} catch (Exception e) {logger.error("This should not happen", e);}contactPerson = MessageFormat.format(CONTACT_FORMAT, contactPerson, contactNumber);PdfPTable billToTable = new PdfPTable(new float[] { 0.2f, 0.8f });billToTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);billToTable.addCell(new Phrase("Bill To :", helvetica8));billToTable.addCell(new PdfPCell(new Paragraph(address+ "\n\nPlace of Supply - "+ MessageFormat.format("{0}({1})", stateIdMap.get(binfo.getStateId()).getStateName(),stateIdMap.get(binfo.getStateId()).getStateCode())+ "\nGST NO. " + gstin, helvetica8)));billToTable.addCell(new Phrase("Contact Person:", helvetica8));billToTable.addCell(new Phrase(contactPerson, helvetica8));billToTable.addCell(new Phrase("Taxes:", helvetica8));if (po.getTaxType() == TaxType.CFORM) {billToTable.addCell(new Phrase("Prices inclusive of all taxes (To be billed on CST Against C-Form)", helvetica8));} else {billToTable.addCell(new Phrase("Prices inclusive of all taxes", helvetica8));}return billToTable;}private static PdfPCell getProductNameCell(in.shop2020.purchase.LineItem lineitem, long supplierId) {String itemName = getItemDisplayName(lineitem, supplierId);PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);return productNameCell;}private static String getItemDisplayName(in.shop2020.purchase.LineItem lineitem, long supplierId) {StringBuffer itemName = new StringBuffer();if (lineitem.getBrand() != null)itemName.append(lineitem.getBrand() + " ");if (lineitem.getModelName() != null)itemName.append(lineitem.getModelName() + " ");if (lineitem.getModelNumber() != null)itemName.append(lineitem.getModelNumber() + " ");if (lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))itemName.append("-" + lineitem.getColor());if(lineitem.getBrand()=="Samsung") {List<VendorItemMapping> vims = getVendorItemMapping(lineitem.getItemId());if(vims != null && vims.size() > 0) {for(VendorItemMapping vim : vims) {if(vim.getVendorId() == supplierId) {itemName.append("(" + vim.getItemKey() + ")");}}}}return itemName.toString();}private static List<VendorItemMapping> getVendorItemMapping(long itemId) {try {return inventoryClient.getVendorItemMappings(itemId);}catch (Exception e) {try {inventoryClient = new InventoryClient().getClient();return inventoryClient.getVendorItemMappings(itemId);} catch(Exception e1) {e1.printStackTrace();}}return null;}private static PdfPCell getTotalCell(int colspan) {PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));totalCell.setColspan(colspan);totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);return totalCell;}private static PdfPCell getTotalAmountCell(int colspan, double totalAmount) {PdfPCell totalCell = new PdfPCell(new Phrase(String.format("%.2f", totalAmount), helvetica8));totalCell.setColspan(colspan);totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);return totalCell;}}