Subversion Repositories SmartDukaan

Rev

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