Subversion Repositories SmartDukaan

Rev

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