Subversion Repositories SmartDukaan

Rev

Rev 4801 | Rev 5387 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2787 chandransh 1
package in.shop2020.hotspot.dashbaord.server;
2
 
3
import in.shop2020.config.ConfigException;
3044 chandransh 4
import in.shop2020.logistics.DeliveryType;
2787 chandransh 5
import in.shop2020.logistics.LogisticsServiceException;
6
import in.shop2020.logistics.Provider;
7
import in.shop2020.model.v1.catalog.InventoryServiceException;
8
import in.shop2020.model.v1.catalog.Warehouse;
9
import in.shop2020.model.v1.catalog.InventoryService.Client;
10
import in.shop2020.model.v1.order.LineItem;
11
import in.shop2020.model.v1.order.Order;
4361 rajveer 12
import in.shop2020.model.v1.order.OrderStatus;
3132 rajveer 13
import in.shop2020.thrift.clients.CatalogClient;
14
import in.shop2020.thrift.clients.LogisticsClient;
15
import in.shop2020.thrift.clients.TransactionClient;
2787 chandransh 16
import in.shop2020.thrift.clients.config.ConfigClient;
17
 
18
import java.io.ByteArrayOutputStream;
19
import java.io.File;
20
import java.io.FileOutputStream;
21
import java.io.IOException;
22
import java.text.DateFormat;
23
import java.text.DecimalFormat;
4361 rajveer 24
import java.util.ArrayList;
4746 rajveer 25
import java.util.Calendar;
2787 chandransh 26
import java.util.Date;
27
import java.util.Enumeration;
4746 rajveer 28
import java.util.GregorianCalendar;
2787 chandransh 29
import java.util.List;
30
import java.util.Locale;
31
import java.util.Properties;
32
import java.util.ResourceBundle;
33
 
34
import javax.servlet.ServletException;
35
import javax.servlet.ServletOutputStream;
36
import javax.servlet.http.HttpServlet;
37
import javax.servlet.http.HttpServletRequest;
38
import javax.servlet.http.HttpServletResponse;
39
 
40
import org.apache.commons.lang.WordUtils;
41
import org.apache.thrift.TException;
42
import org.slf4j.Logger;
43
import org.slf4j.LoggerFactory;
44
 
45
import com.ibm.icu.text.RuleBasedNumberFormat;
46
 
47
import com.itextpdf.text.Document;
48
import com.itextpdf.text.Element;
49
import com.itextpdf.text.Font;
50
import com.itextpdf.text.FontFactory;
51
import com.itextpdf.text.FontFactoryImp;
52
import com.itextpdf.text.Image;
53
import com.itextpdf.text.Paragraph;
54
import com.itextpdf.text.Phrase;
55
import com.itextpdf.text.Rectangle;
56
import com.itextpdf.text.Font.FontFamily;
57
import com.itextpdf.text.pdf.BaseFont;
58
import com.itextpdf.text.pdf.PdfPCell;
59
import com.itextpdf.text.pdf.PdfPTable;
60
import com.itextpdf.text.pdf.PdfWriter;
61
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
62
 
63
@SuppressWarnings("serial")
64
public class InvoiceServlet extends HttpServlet {
65
 
66
    private static Logger logger = LoggerFactory.getLogger(InvoiceServlet.class);
67
 
68
    @Override
69
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
70
        long orderId = Long.parseLong(request.getParameter("id"));
4361 rajveer 71
        long warehouseId = Long.parseLong(request.getParameter("warehouse"));
2843 chandransh 72
        boolean withBill = false;
4361 rajveer 73
        boolean printAll = false;
2843 chandransh 74
        try {
75
            withBill = Boolean.parseBoolean(request.getParameter("withBill"));
76
        } catch(Exception e){
77
            logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
78
        }
4361 rajveer 79
        try {
80
        	printAll = Boolean.parseBoolean(request.getParameter("printAll"));
81
        } catch(Exception e){
82
            logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
83
        }
84
 
2787 chandransh 85
        logger.info("Printing invoice for order id: " + orderId);
86
 
87
        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
4361 rajveer 88
        ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, withBill, printAll, warehouseId);
2787 chandransh 89
        response.setContentType("application/pdf");
90
        response.setHeader("Content-disposition", "inline; filename=invoice-"+orderId+".pdf" );
91
 
92
        ServletOutputStream sos;
93
        try {
94
            sos = response.getOutputStream();
95
            baos.writeTo(sos);
96
            sos.flush();
97
        } catch (IOException e) {
98
            logger.error("Encountered error while sending invoice response: ", e);
99
        }
100
    }
101
}
102
 
103
class InvoiceGenerationService {
104
 
105
    private static Logger logger = LoggerFactory.getLogger(InvoiceGenerationService.class);
106
 
3132 rajveer 107
    private TransactionClient tsc = null;
108
    private CatalogClient csc = null;
109
    private LogisticsClient lsc = null;
2787 chandransh 110
 
111
    private static Locale indianLocale = new Locale("en", "IN");
112
    private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");
113
 
114
    private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
115
    private static final Font helvetica10 = FontFactory.getFont(FontFactory.HELVETICA, 10);
116
    private static final Font helvetica12 = FontFactory.getFont(FontFactory.HELVETICA, 12);
117
    private static final Font helvetica16 = FontFactory.getFont(FontFactory.HELVETICA, 16);
3065 chandransh 118
    private static final Font helvetica28 = FontFactory.getFont(FontFactory.HELVETICA, 28);
2787 chandransh 119
 
120
    private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
121
    private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);
122
 
123
    private static final Properties properties = readProperties();
124
    private static final String ourAddress = properties.getProperty("sales_tax_address",
125
                    "Spice Online Retail Pvt. Ltd.\nKhasra No. 819, Block-K\nMahipalpur, New Delhi-110037\n");
126
    private static final String tinNo = properties.getProperty("sales_tax_tin", "07250399732");
127
 
128
    private static final String delhiPincodePrefix = "11";
129
 
130
    private static final double salesTaxLowRate = Double.parseDouble(properties.getProperty("sales_tax_low_rate", "5.0"));
131
    private static final double salesTaxHighRate = Double.parseDouble(properties.getProperty("sales_tax_high_rate", "12.5"));
132
    private static final double salesTaxCutOff = (Double.parseDouble(properties.getProperty("sales_tax_cutoff", "10000")) * (100 + salesTaxLowRate))/100;
133
 
134
    private static Properties readProperties(){
135
        ResourceBundle resource = ResourceBundle.getBundle(InvoiceGenerationService.class.getName());
136
        Properties props = new Properties();
137
 
138
        Enumeration<String> keys = resource.getKeys();
139
        while (keys.hasMoreElements()) {
140
            String key = keys.nextElement();
141
            props.put(key, resource.getString(key));
142
        }
143
        return props;
144
    }
145
 
146
    public InvoiceGenerationService() {
147
        try {
3132 rajveer 148
            tsc = new TransactionClient();
149
            csc = new CatalogClient();
150
            lsc = new LogisticsClient();
2787 chandransh 151
        } catch (Exception e) {
152
            logger.error("Error while instantiating thrift clients.", e);
153
        }
154
    }
155
 
4361 rajveer 156
    public ByteArrayOutputStream generateInvoice(long orderId, boolean withBill, boolean printAll, long warehouseId) {
2787 chandransh 157
        ByteArrayOutputStream baosPDF = null;
158
        in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
159
        Client iclient = csc.getClient();
160
        in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
161
 
4361 rajveer 162
 
2787 chandransh 163
        try {
164
            baosPDF = new ByteArrayOutputStream();
165
 
166
            Document document = new Document();
167
            PdfWriter.getInstance(document, baosPDF);
168
            document.addAuthor("shop2020");
4361 rajveer 169
            //document.addTitle("Invoice No: " + order.getInvoice_number());
2787 chandransh 170
            document.open();
4361 rajveer 171
 
172
            List<Order> orders = new ArrayList<Order>();
173
            if(printAll){
174
	            try {
4801 anupam.sin 175
	                List<OrderStatus> statuses = new ArrayList<OrderStatus>();
176
	                statuses.add(OrderStatus.ACCEPTED);
177
	                orders = tclient.getAllOrders(statuses, 0, 0, warehouseId);
4361 rajveer 178
	            } catch (Exception e) {
179
	            	logger.error("Error while getting order information", e);
180
	                return baosPDF; 
181
				}
182
            }else{
183
            	orders.add(tclient.getOrder(orderId));	
184
            }
2787 chandransh 185
 
4361 rajveer 186
            for(Order order: orders){
187
            	Warehouse warehouse = null;
188
            	Provider provider = null;
189
            	String destCode = null;
190
            	int barcodeFontSize = 0;
191
            	try {
192
            		warehouse = iclient.getWarehouse(order.getWarehouse_id());
193
            		long providerId = order.getLogistics_provider_id();
194
            		provider = logisticsClient.getProvider(providerId);
195
            		destCode = logisticsClient.getDestinationCode(providerId, order.getCustomer_pincode());
196
            		barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
197
            	} catch (InventoryServiceException ise) {
198
            		logger.error("Error while getting the warehouse information.", ise);
199
            		return baosPDF;
200
            	} catch (LogisticsServiceException lse) {
201
            		logger.error("Error while getting the provider information.", lse);
202
            		return baosPDF;
203
            	} catch (ConfigException ce) {
204
            		logger.error("Error while getting the fontsize for the given provider", ce);
205
            		return baosPDF;
206
            	} catch (TException te) {
207
            		logger.error("Error while getting some essential information from the services", te);
208
            		return baosPDF;
209
            	}
2787 chandransh 210
 
4361 rajveer 211
	            PdfPTable dispatchAdviceTable = getDispatchAdviceTable(order, warehouse, provider, barcodeFontSize, destCode, withBill);
212
	            dispatchAdviceTable.setSpacingAfter(10.0f);
213
	            dispatchAdviceTable.setWidthPercentage(90.0f);
214
 
215
	            document.add(dispatchAdviceTable);
216
	            if(withBill){
217
	                PdfPTable taxTable = getTaxCumRetailInvoiceTable(order, provider);
218
	                taxTable.setSpacingBefore(5.0f);
219
	                taxTable.setWidthPercentage(90.0f);
220
	                document.add(new DottedLineSeparator());
221
	                document.add(taxTable);
222
	            }else{
223
	            	PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16);
224
	            	extraInfoTable.setSpacingBefore(5.0f);
225
	            	extraInfoTable.setWidthPercentage(90.0f);
226
	                document.add(new DottedLineSeparator());
227
	                document.add(extraInfoTable);
228
	            }
229
	            document.newPage();
2843 chandransh 230
            }
2787 chandransh 231
            document.close();
232
            baosPDF.close();
4747 rajveer 233
         // Adding facility to store the bill on the local directory. This will happen for only for Mahipalpur warehouse.
234
            if(withBill && !printAll){
235
            	Calendar cal = new GregorianCalendar();
236
            	cal.setTimeInMillis(orders.get(0).getBilling_timestamp());
237
            	int year = cal.get(Calendar.YEAR);
238
      		  	int month = cal.get(Calendar.MONTH);
239
      		  	int day = cal.get(Calendar.DAY_OF_MONTH);
240
      		  	String dirPath = "/SaholicInvoices" + File.separator + year + File.separator  + month + File.separator + day;
241
      		  	File dirFile = new File(dirPath);
242
      		  	if(!dirFile.exists()){
243
      		  		dirFile.mkdirs();	
244
      		  	}
245
      		  	File f = new File( dirPath + File.separator + orderId + ".pdf");
246
                FileOutputStream fos = new FileOutputStream(f);
247
                baosPDF.writeTo(fos);
248
            }
2787 chandransh 249
        } catch (Exception e) {
250
            logger.error("Error while generating Invoice: ", e);
251
        }
252
        return baosPDF;
253
    }
254
 
2915 chandransh 255
    private PdfPTable getDispatchAdviceTable(Order order, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode, boolean withBill){
2787 chandransh 256
        Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
257
 
258
        PdfPTable table = new PdfPTable(1);
259
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
260
 
3065 chandransh 261
        PdfPTable logoTable = new PdfPTable(2);
262
        logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
263
        logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
264
        logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
265
        logoTable.addCell(getLogoCell());
266
        if(order.isCod())
267
            logoTable.addCell(new Phrase("COD   ", helvetica28));
4550 rajveer 268
        else
269
        	logoTable.addCell(new Phrase("   ", helvetica28));
2787 chandransh 270
        PdfPCell titleCell = getTitleCell();
271
        PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12);
272
        PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont);
273
 
274
        PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
275
        dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
276
        dispatchTable.addCell(customerTable);
277
        dispatchTable.addCell(new Phrase(" "));
278
        dispatchTable.addCell(providerInfoTable);
279
 
2915 chandransh 280
 
281
        PdfPTable invoiceTable = null;
282
        if(withBill)
283
            invoiceTable = getTopInvoiceTable(order, tinNo);
284
        else
285
            invoiceTable = getTopInvoiceTable(order, warehouse.getTinNumber());
3065 chandransh 286
 
2915 chandransh 287
        PdfPCell addressCell = null;
288
        if(withBill)
289
            addressCell = getAddressCell(ourAddress);
290
        else
291
            addressCell = getAddressCell(warehouse.getLocation() + "\nPIN " + warehouse.getPincode() + "\n\n");
2787 chandransh 292
 
3065 chandransh 293
        PdfPTable chargesTable = new PdfPTable(1);
294
        chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
295
        chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
296
        if(order.isCod()){
297
            chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + order.getTotal_amount(), helveticaBold12));
4313 rajveer 298
            chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/ITG-111117"));
3065 chandransh 299
        } else {
300
            chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
301
        }
302
 
303
        PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
304
        addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
305
        addressAndNoteTable.addCell(addressCell);
306
        addressAndNoteTable.addCell(chargesTable);
307
 
308
        table.addCell(logoTable);
2787 chandransh 309
        table.addCell(titleCell);
310
        table.addCell(dispatchTable);
311
        table.addCell(invoiceTable);
312
        table.addCell(new Phrase("If undelivered, return to:", helvetica10));
3065 chandransh 313
        table.addCell(addressAndNoteTable);
2787 chandransh 314
        return table;
315
    }
316
 
317
    private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
318
        String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
319
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
320
        ttfFontFactory.register(fontPath, "barcode");
321
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
322
        return barCodeFont;
323
    }
324
 
325
    private PdfPCell getLogoCell() {
326
        String logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
327
        PdfPCell logoCell;
328
        try {
329
            logoCell = new PdfPCell(Image.getInstance(logoPath), false);
330
        } catch (Exception e) {
331
            //Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
332
            logger.warn("Couldn't load the Saholic logo: ", e);
333
            logoCell = new PdfPCell(new Phrase("Saholic Logo"));
334
        }
335
        logoCell.setBorder(Rectangle.NO_BORDER);
336
        return logoCell;
337
    }
338
 
339
    private PdfPCell getTitleCell() {
340
        PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
341
        titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
342
        titleCell.setBorder(Rectangle.NO_BORDER);
343
        return titleCell;
344
    }
345
 
346
    private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
347
        PdfPTable providerInfoTable = new PdfPTable(1);
348
        providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
349
        PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
350
        providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
351
        providerNameCell.setBorder(Rectangle.NO_BORDER);
352
 
353
        PdfPCell awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
354
        awbNumberCell.setPaddingTop(20.0f);
355
        awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
356
        awbNumberCell.setBorder(Rectangle.NO_BORDER);
357
 
358
        providerInfoTable.addCell(providerNameCell);
359
        providerInfoTable.addCell(awbNumberCell);
3065 chandransh 360
        if(order.isCod())
361
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.COD).getAccountNo(), helvetica8));
362
        else
363
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.PREPAID).getAccountNo(), helvetica8));
2787 chandransh 364
        providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
365
        providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
366
        return providerInfoTable;
367
    }
368
 
2915 chandransh 369
    private PdfPTable getTopInvoiceTable(Order order, String tinNo){
2787 chandransh 370
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
371
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
372
 
373
        invoiceTable.addCell(getInvoiceTableHeader(6));
374
 
375
        invoiceTable.addCell(new Phrase("Order No", helvetica8));
376
        invoiceTable.addCell(new Phrase("Paymode", helvetica8));
377
        invoiceTable.addCell(new Phrase("Product Name", helvetica8));
378
        invoiceTable.addCell(new Phrase("Quantity", helvetica8));
379
        invoiceTable.addCell(new Phrase("Rate", helvetica8));
380
        invoiceTable.addCell(new Phrase("Amount", helvetica8));
381
        populateTopInvoiceTable(order, invoiceTable);
382
 
383
        invoiceTable.addCell(getTotalCell(4));      
384
        invoiceTable.addCell(getRupeesCell());
385
        invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()));
386
 
387
        PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
388
        tinCell.setColspan(6);
389
        tinCell.setPadding(2);
390
        invoiceTable.addCell(tinCell);
391
 
392
        return invoiceTable;
393
    }
394
 
395
    private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
396
        List<LineItem> lineitems = order.getLineitems();
397
        for (LineItem lineitem : lineitems) {
398
            invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
3065 chandransh 399
            if(order.isCod())
400
                invoiceTable.addCell(new Phrase("COD", helvetica8));
401
            else
402
                invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
2787 chandransh 403
 
404
            invoiceTable.addCell(getProductNameCell(lineitem, false));
405
 
406
            invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
407
 
408
            invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()));
409
 
410
            invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
411
        }
412
    }
413
 
2915 chandransh 414
    private PdfPCell getAddressCell(String address) {
415
        Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
2787 chandransh 416
        PdfPCell addressCell = new PdfPCell();
417
        addressCell.addElement(addressParagraph);
418
        addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
419
        addressCell.setBorder(Rectangle.NO_BORDER);
420
        return addressCell;
421
    }
422
 
423
    private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider){
424
        PdfPTable taxTable = new PdfPTable(1);
425
        taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
426
        taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
427
 
428
        PdfPCell retailInvoiceTitleCell = new PdfPCell(new Phrase("TAX CUM RETAIL INVOICE", helveticaBold12));
429
        retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
430
        retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
431
 
432
        Paragraph sorlAddress = new Paragraph(ourAddress + "TIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
433
        PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
434
        sorlAddressCell.addElement(sorlAddress);
435
        sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
436
 
437
        PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8);
438
        PdfPTable orderDetails = getOrderDetails(order, provider);
439
 
440
        PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
441
        addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
442
        addrAndOrderDetailsTable.addCell(customerAddress);
443
        addrAndOrderDetailsTable.addCell(new Phrase(" "));
444
        addrAndOrderDetailsTable.addCell(orderDetails);
445
 
446
        boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
447
        PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
448
 
449
        PdfPCell disclaimerCell = new PdfPCell(new Phrase("Goods once sold will not be taken back.\nAll disputes subject to Delhi Jurisdiction.", helvetica8));
450
        disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
451
        disclaimerCell.setBorder(Rectangle.NO_BORDER);
452
 
453
        taxTable.addCell(retailInvoiceTitleCell);
454
        taxTable.addCell(sorlAddress);
455
        taxTable.addCell(addrAndOrderDetailsTable);
456
        taxTable.addCell(invoiceTable);
457
        taxTable.addCell(disclaimerCell);
458
 
459
        return taxTable;
460
    }
461
 
462
    private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font){
463
        PdfPTable customerTable = new PdfPTable(1);
464
        customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
465
        customerTable.addCell(new Phrase(order.getCustomer_name(), font));
466
        customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
467
        customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
468
        customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
469
        if(destCode != null)
470
            customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
471
        else
472
            customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
473
        customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
474
        if(showPaymentMode){
475
            customerTable.addCell(new Phrase(" ", font));
476
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
477
        }
478
        return customerTable;
479
    }
480
 
481
    private PdfPTable getOrderDetails(Order order, Provider provider){
482
        PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
483
        orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
484
 
485
        orderTable.addCell(new Phrase("Invoice No:", helvetica8));
486
        orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
487
 
488
        orderTable.addCell(new Phrase("Date:", helvetica8));
489
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
490
 
491
        orderTable.addCell(new Phrase(" "));
492
        orderTable.addCell(new Phrase(" "));
493
 
494
        orderTable.addCell(new Phrase("Order ID:", helvetica8));
495
        orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
496
 
497
        orderTable.addCell(new Phrase("Order Date:", helvetica8));
498
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
499
 
500
        orderTable.addCell(new Phrase("Courier:", helvetica8));
501
        orderTable.addCell(new Phrase(provider.getName(), helvetica8));
502
 
503
        orderTable.addCell(new Phrase("AWB No:", helvetica8));
504
        orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
505
 
506
        orderTable.addCell(new Phrase("AWB Date:", helvetica8));
507
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
508
 
509
        return orderTable;
510
    }
511
 
512
    private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
513
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
514
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
515
 
516
        invoiceTable.addCell(getInvoiceTableHeader(5));
517
 
518
        invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
519
        invoiceTable.addCell(new Phrase("Description", helveticaBold8));
520
        invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
521
        invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
522
        invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
523
 
524
        double orderAmount = order.getTotal_amount();
4951 mandeep.dh 525
        double rate = getTaxRate(order.getLineitems().get(0).getUnit_price());
2787 chandransh 526
        double salesTax = (rate * orderAmount)/(100 + rate);
527
 
528
        populateBottomInvoiceTable(order, invoiceTable, rate);
529
 
530
        PdfPCell salesTaxCell = getPriceCell(salesTax);
531
 
532
        invoiceTable.addCell(getVATLabelCell(isVAT));
533
        invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
534
        invoiceTable.addCell(salesTaxCell);
535
 
536
        invoiceTable.addCell(getEmptyCell(5));
537
 
538
        invoiceTable.addCell(getTotalCell(3));
539
        invoiceTable.addCell(getRupeesCell());
540
        invoiceTable.addCell(getTotalAmountCell(orderAmount));
541
 
542
        invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
543
        invoiceTable.addCell(getAmountInWordsCell(orderAmount));
544
 
545
        invoiceTable.addCell(getEOECell(5));
546
 
547
        return invoiceTable;
548
    }
549
 
550
    private PdfPCell getInvoiceTableHeader(int colspan) {
551
        PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
552
        invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
553
        invoiceTableHeader.setColspan(colspan);
554
        invoiceTableHeader.setPaddingTop(10);
555
        return invoiceTableHeader;
556
    }
557
 
558
    private double getTaxRate(double orderAmount) {
559
        double rate;
560
        if(orderAmount <= salesTaxCutOff){
561
            rate = salesTaxLowRate;
562
        } else {
563
            rate = salesTaxHighRate;
564
        }
565
        return rate;
566
    }
567
 
568
    private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
569
        for (LineItem lineitem : order.getLineitems()) {
570
            invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
571
 
572
            invoiceTable.addCell(getProductNameCell(lineitem, true));
573
 
574
            invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
575
 
576
            double itemPrice = lineitem.getUnit_price();
577
            double showPrice = (100 * itemPrice)/(100 + rate);
578
            invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
579
 
580
            double totalPrice = lineitem.getTotal_price();
581
            showPrice = (100 * totalPrice)/(100 + rate);
582
            invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
583
        }
584
    }
585
 
586
    private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI) {
587
        String itemName = getItemDisplayName(lineitem, appendIMEI);
588
        PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
589
        productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
590
        return productNameCell;
591
    }
592
 
593
    private PdfPCell getPriceCell(double price) {
594
        PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
595
        totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
596
        return totalPriceCell;
597
    }
598
 
599
    private PdfPCell getVATLabelCell(boolean isVAT) {
600
        PdfPCell vatCell = null;
601
        if(isVAT){
602
            vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
603
        } else {
604
            vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
605
        }
606
        vatCell.setColspan(3);
607
        vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
608
        return vatCell;
609
    }
610
 
611
    private PdfPCell getEmptyCell(int colspan) {
612
        PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
613
        emptyCell.setColspan(colspan);
614
        return emptyCell;
615
    }
616
 
617
    private PdfPCell getTotalCell(int colspan) {
618
        PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
619
        totalCell.setColspan(colspan);
620
        totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
621
        return totalCell;
622
    }
623
 
624
    private PdfPCell getRupeesCell() {
625
        PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
626
        rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
627
        return rupeesCell;
628
    }
629
 
630
    private PdfPCell getTotalAmountCell(double orderAmount) {
631
        PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
632
        totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
633
        return totalAmountCell;
634
    }
635
 
636
    /**
637
     * This method uses ICU4J libraries to convert the given amount into words
638
     * of Indian locale.
639
     * 
640
     * @param orderAmount
641
     *            The amount to convert.
642
     * @return the string representation of the given amount.
643
     */
644
    private PdfPCell getAmountInWordsCell(double orderAmount) {
645
        RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
646
        StringBuilder amountInWords = new StringBuilder("Rs. ");
647
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
648
        amountInWords.append(" and ");
649
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
650
        amountInWords.append(" paise");
651
 
652
        PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
653
        amountInWordsCell.setColspan(4);
654
        return amountInWordsCell;
655
    }
656
 
657
    /**
658
     * Returns the item name to be displayed in the invoice table.
659
     * 
660
     * @param lineitem
661
     *            The line item whose name has to be displayed
662
     * @param appendIMEI
663
     *            Whether to attach the IMEI No. to the item name
664
     * @return The name to be displayed for the given line item.
665
     */
666
    private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
667
        StringBuffer itemName = new StringBuffer();
668
        if(lineitem.getBrand()!= null)
669
            itemName.append(lineitem.getBrand() + " ");
670
        if(lineitem.getModel_name() != null)
671
            itemName.append(lineitem.getModel_name() + " ");
672
        if(lineitem.getModel_number() != null )
673
            itemName.append(lineitem.getModel_number() + " ");
674
        if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
675
            itemName.append("("+lineitem.getColor()+")");
4659 mandeep.dh 676
        if(appendIMEI && lineitem.isSetSerial_number()){
677
            itemName.append("\nIMEI No. " + lineitem.getSerial_number());
2787 chandransh 678
        }
679
 
680
        return itemName.toString();
681
    }
682
 
683
    /**
684
     * 
685
     * @param colspan
686
     * @return a PdfPCell containing the E&amp;OE text and spanning the given
687
     *         no. of columns
688
     */
689
    private PdfPCell getEOECell(int colspan) {
690
        PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
691
        eoeCell.setColspan(colspan);
692
        eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
693
        return eoeCell;
694
    }
695
 
4262 rajveer 696
    private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize){
697
        PdfPTable extraInfoTable = new PdfPTable(1);
698
        extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
699
        extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
700
 
701
        String fontPath = InvoiceGenerationService.class.getResource("/saholic.TTF").getPath();
702
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
703
        ttfFontFactory.register(fontPath, "barcode");
704
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
705
 
706
        PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
707
        extraInfoCell.setPaddingTop(20.0f);
708
        extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
709
        extraInfoCell.setBorder(Rectangle.NO_BORDER);
710
 
711
        extraInfoTable.addCell(extraInfoCell);
712
 
713
 
714
        return extraInfoTable;
715
    }
2787 chandransh 716
    public static void main(String[] args) throws IOException {
717
        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
3065 chandransh 718
        long orderId = 542;
4361 rajveer 719
        ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, false, false, 1);
2787 chandransh 720
        String userHome = System.getProperty("user.home");
721
        File f = new File(userHome + "/invoice-" + orderId + ".pdf");
722
        FileOutputStream fos = new FileOutputStream(f);
723
        baos.writeTo(fos);
724
        System.out.println("Invoice generated.");
725
    }
726
}