Subversion Repositories SmartDukaan

Rev

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