Subversion Repositories SmartDukaan

Rev

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