Subversion Repositories SmartDukaan

Rev

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