Subversion Repositories SmartDukaan

Rev

Rev 3132 | Rev 4313 | 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;
3132 rajveer 13
import in.shop2020.thrift.clients.CatalogClient;
14
import in.shop2020.thrift.clients.LogisticsClient;
15
import in.shop2020.thrift.clients.TransactionClient;
2787 chandransh 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
 
3132 rajveer 97
    private TransactionClient tsc = null;
98
    private CatalogClient csc = null;
99
    private LogisticsClient lsc = null;
2787 chandransh 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 {
3132 rajveer 138
            tsc = new TransactionClient();
139
            csc = new CatalogClient();
140
            lsc = new LogisticsClient();
2787 chandransh 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);
4262 rajveer 201
            }else{
202
            	PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16);
203
            	extraInfoTable.setSpacingBefore(5.0f);
204
            	extraInfoTable.setWidthPercentage(90.0f);
205
                document.add(new DottedLineSeparator());
206
                document.add(extraInfoTable);
2843 chandransh 207
            }
2787 chandransh 208
            document.close();
209
            baosPDF.close();
210
        } catch (Exception e) {
211
            logger.error("Error while generating Invoice: ", e);
212
        }
213
        return baosPDF;
214
    }
215
 
2915 chandransh 216
    private PdfPTable getDispatchAdviceTable(Order order, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode, boolean withBill){
2787 chandransh 217
        Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
218
 
219
        PdfPTable table = new PdfPTable(1);
220
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
221
 
3065 chandransh 222
        PdfPTable logoTable = new PdfPTable(2);
223
        logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
224
        logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
225
        logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
226
        logoTable.addCell(getLogoCell());
227
        if(order.isCod())
228
            logoTable.addCell(new Phrase("COD   ", helvetica28));
229
 
2787 chandransh 230
        PdfPCell titleCell = getTitleCell();
231
        PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12);
232
        PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont);
233
 
234
        PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
235
        dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
236
        dispatchTable.addCell(customerTable);
237
        dispatchTable.addCell(new Phrase(" "));
238
        dispatchTable.addCell(providerInfoTable);
239
 
2915 chandransh 240
 
241
        PdfPTable invoiceTable = null;
242
        if(withBill)
243
            invoiceTable = getTopInvoiceTable(order, tinNo);
244
        else
245
            invoiceTable = getTopInvoiceTable(order, warehouse.getTinNumber());
3065 chandransh 246
 
2915 chandransh 247
        PdfPCell addressCell = null;
248
        if(withBill)
249
            addressCell = getAddressCell(ourAddress);
250
        else
251
            addressCell = getAddressCell(warehouse.getLocation() + "\nPIN " + warehouse.getPincode() + "\n\n");
2787 chandransh 252
 
3065 chandransh 253
        PdfPTable chargesTable = new PdfPTable(1);
254
        chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
255
        chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
256
        if(order.isCod()){
257
            chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + order.getTotal_amount(), helveticaBold12));
258
            chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HSE-111118"));
259
        } else {
260
            chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
261
        }
262
 
263
        PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
264
        addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
265
        addressAndNoteTable.addCell(addressCell);
266
        addressAndNoteTable.addCell(chargesTable);
267
 
268
        table.addCell(logoTable);
2787 chandransh 269
        table.addCell(titleCell);
270
        table.addCell(dispatchTable);
271
        table.addCell(invoiceTable);
272
        table.addCell(new Phrase("If undelivered, return to:", helvetica10));
3065 chandransh 273
        table.addCell(addressAndNoteTable);
2787 chandransh 274
        return table;
275
    }
276
 
277
    private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
278
        String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
279
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
280
        ttfFontFactory.register(fontPath, "barcode");
281
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
282
        return barCodeFont;
283
    }
284
 
285
    private PdfPCell getLogoCell() {
286
        String logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
287
        PdfPCell logoCell;
288
        try {
289
            logoCell = new PdfPCell(Image.getInstance(logoPath), false);
290
        } catch (Exception e) {
291
            //Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
292
            logger.warn("Couldn't load the Saholic logo: ", e);
293
            logoCell = new PdfPCell(new Phrase("Saholic Logo"));
294
        }
295
        logoCell.setBorder(Rectangle.NO_BORDER);
296
        return logoCell;
297
    }
298
 
299
    private PdfPCell getTitleCell() {
300
        PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
301
        titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
302
        titleCell.setBorder(Rectangle.NO_BORDER);
303
        return titleCell;
304
    }
305
 
306
    private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
307
        PdfPTable providerInfoTable = new PdfPTable(1);
308
        providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
309
        PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
310
        providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
311
        providerNameCell.setBorder(Rectangle.NO_BORDER);
312
 
313
        PdfPCell awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
314
        awbNumberCell.setPaddingTop(20.0f);
315
        awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
316
        awbNumberCell.setBorder(Rectangle.NO_BORDER);
317
 
318
        providerInfoTable.addCell(providerNameCell);
319
        providerInfoTable.addCell(awbNumberCell);
3065 chandransh 320
        if(order.isCod())
321
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.COD).getAccountNo(), helvetica8));
322
        else
323
            providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.PREPAID).getAccountNo(), helvetica8));
2787 chandransh 324
        providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
325
        providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
326
        return providerInfoTable;
327
    }
328
 
2915 chandransh 329
    private PdfPTable getTopInvoiceTable(Order order, String tinNo){
2787 chandransh 330
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
331
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
332
 
333
        invoiceTable.addCell(getInvoiceTableHeader(6));
334
 
335
        invoiceTable.addCell(new Phrase("Order No", helvetica8));
336
        invoiceTable.addCell(new Phrase("Paymode", helvetica8));
337
        invoiceTable.addCell(new Phrase("Product Name", helvetica8));
338
        invoiceTable.addCell(new Phrase("Quantity", helvetica8));
339
        invoiceTable.addCell(new Phrase("Rate", helvetica8));
340
        invoiceTable.addCell(new Phrase("Amount", helvetica8));
341
        populateTopInvoiceTable(order, invoiceTable);
342
 
343
        invoiceTable.addCell(getTotalCell(4));      
344
        invoiceTable.addCell(getRupeesCell());
345
        invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()));
346
 
347
        PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
348
        tinCell.setColspan(6);
349
        tinCell.setPadding(2);
350
        invoiceTable.addCell(tinCell);
351
 
352
        return invoiceTable;
353
    }
354
 
355
    private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
356
        List<LineItem> lineitems = order.getLineitems();
357
        for (LineItem lineitem : lineitems) {
358
            invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
3065 chandransh 359
            if(order.isCod())
360
                invoiceTable.addCell(new Phrase("COD", helvetica8));
361
            else
362
                invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
2787 chandransh 363
 
364
            invoiceTable.addCell(getProductNameCell(lineitem, false));
365
 
366
            invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
367
 
368
            invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()));
369
 
370
            invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
371
        }
372
    }
373
 
2915 chandransh 374
    private PdfPCell getAddressCell(String address) {
375
        Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
2787 chandransh 376
        PdfPCell addressCell = new PdfPCell();
377
        addressCell.addElement(addressParagraph);
378
        addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
379
        addressCell.setBorder(Rectangle.NO_BORDER);
380
        return addressCell;
381
    }
382
 
383
    private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider){
384
        PdfPTable taxTable = new PdfPTable(1);
385
        taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
386
        taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
387
 
388
        PdfPCell retailInvoiceTitleCell = new PdfPCell(new Phrase("TAX CUM RETAIL INVOICE", helveticaBold12));
389
        retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
390
        retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
391
 
392
        Paragraph sorlAddress = new Paragraph(ourAddress + "TIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
393
        PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
394
        sorlAddressCell.addElement(sorlAddress);
395
        sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
396
 
397
        PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8);
398
        PdfPTable orderDetails = getOrderDetails(order, provider);
399
 
400
        PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
401
        addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
402
        addrAndOrderDetailsTable.addCell(customerAddress);
403
        addrAndOrderDetailsTable.addCell(new Phrase(" "));
404
        addrAndOrderDetailsTable.addCell(orderDetails);
405
 
406
        boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
407
        PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
408
 
409
        PdfPCell disclaimerCell = new PdfPCell(new Phrase("Goods once sold will not be taken back.\nAll disputes subject to Delhi Jurisdiction.", helvetica8));
410
        disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
411
        disclaimerCell.setBorder(Rectangle.NO_BORDER);
412
 
413
        taxTable.addCell(retailInvoiceTitleCell);
414
        taxTable.addCell(sorlAddress);
415
        taxTable.addCell(addrAndOrderDetailsTable);
416
        taxTable.addCell(invoiceTable);
417
        taxTable.addCell(disclaimerCell);
418
 
419
        return taxTable;
420
    }
421
 
422
    private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font){
423
        PdfPTable customerTable = new PdfPTable(1);
424
        customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
425
        customerTable.addCell(new Phrase(order.getCustomer_name(), font));
426
        customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
427
        customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
428
        customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
429
        if(destCode != null)
430
            customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
431
        else
432
            customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
433
        customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
434
        if(showPaymentMode){
435
            customerTable.addCell(new Phrase(" ", font));
436
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
437
        }
438
        return customerTable;
439
    }
440
 
441
    private PdfPTable getOrderDetails(Order order, Provider provider){
442
        PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
443
        orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
444
 
445
        orderTable.addCell(new Phrase("Invoice No:", helvetica8));
446
        orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
447
 
448
        orderTable.addCell(new Phrase("Date:", helvetica8));
449
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
450
 
451
        orderTable.addCell(new Phrase(" "));
452
        orderTable.addCell(new Phrase(" "));
453
 
454
        orderTable.addCell(new Phrase("Order ID:", helvetica8));
455
        orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
456
 
457
        orderTable.addCell(new Phrase("Order Date:", helvetica8));
458
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
459
 
460
        orderTable.addCell(new Phrase("Courier:", helvetica8));
461
        orderTable.addCell(new Phrase(provider.getName(), helvetica8));
462
 
463
        orderTable.addCell(new Phrase("AWB No:", helvetica8));
464
        orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
465
 
466
        orderTable.addCell(new Phrase("AWB Date:", helvetica8));
467
        orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
468
 
469
        return orderTable;
470
    }
471
 
472
    private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
473
        PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
474
        invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
475
 
476
        invoiceTable.addCell(getInvoiceTableHeader(5));
477
 
478
        invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
479
        invoiceTable.addCell(new Phrase("Description", helveticaBold8));
480
        invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
481
        invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
482
        invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
483
 
484
        double orderAmount = order.getTotal_amount();
485
        double rate = getTaxRate(orderAmount);
486
        double salesTax = (rate * orderAmount)/(100 + rate);
487
 
488
        populateBottomInvoiceTable(order, invoiceTable, rate);
489
 
490
        PdfPCell salesTaxCell = getPriceCell(salesTax);
491
 
492
        invoiceTable.addCell(getVATLabelCell(isVAT));
493
        invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
494
        invoiceTable.addCell(salesTaxCell);
495
 
496
        invoiceTable.addCell(getEmptyCell(5));
497
 
498
        invoiceTable.addCell(getTotalCell(3));
499
        invoiceTable.addCell(getRupeesCell());
500
        invoiceTable.addCell(getTotalAmountCell(orderAmount));
501
 
502
        invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
503
        invoiceTable.addCell(getAmountInWordsCell(orderAmount));
504
 
505
        invoiceTable.addCell(getEOECell(5));
506
 
507
        return invoiceTable;
508
    }
509
 
510
    private PdfPCell getInvoiceTableHeader(int colspan) {
511
        PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
512
        invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
513
        invoiceTableHeader.setColspan(colspan);
514
        invoiceTableHeader.setPaddingTop(10);
515
        return invoiceTableHeader;
516
    }
517
 
518
    private double getTaxRate(double orderAmount) {
519
        double rate;
520
        if(orderAmount <= salesTaxCutOff){
521
            rate = salesTaxLowRate;
522
        } else {
523
            rate = salesTaxHighRate;
524
        }
525
        return rate;
526
    }
527
 
528
    private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
529
        for (LineItem lineitem : order.getLineitems()) {
530
            invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
531
 
532
            invoiceTable.addCell(getProductNameCell(lineitem, true));
533
 
534
            invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
535
 
536
            double itemPrice = lineitem.getUnit_price();
537
            double showPrice = (100 * itemPrice)/(100 + rate);
538
            invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
539
 
540
            double totalPrice = lineitem.getTotal_price();
541
            showPrice = (100 * totalPrice)/(100 + rate);
542
            invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
543
        }
544
    }
545
 
546
    private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI) {
547
        String itemName = getItemDisplayName(lineitem, appendIMEI);
548
        PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
549
        productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
550
        return productNameCell;
551
    }
552
 
553
    private PdfPCell getPriceCell(double price) {
554
        PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
555
        totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
556
        return totalPriceCell;
557
    }
558
 
559
    private PdfPCell getVATLabelCell(boolean isVAT) {
560
        PdfPCell vatCell = null;
561
        if(isVAT){
562
            vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
563
        } else {
564
            vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
565
        }
566
        vatCell.setColspan(3);
567
        vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
568
        return vatCell;
569
    }
570
 
571
    private PdfPCell getEmptyCell(int colspan) {
572
        PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
573
        emptyCell.setColspan(colspan);
574
        return emptyCell;
575
    }
576
 
577
    private PdfPCell getTotalCell(int colspan) {
578
        PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
579
        totalCell.setColspan(colspan);
580
        totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
581
        return totalCell;
582
    }
583
 
584
    private PdfPCell getRupeesCell() {
585
        PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
586
        rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
587
        return rupeesCell;
588
    }
589
 
590
    private PdfPCell getTotalAmountCell(double orderAmount) {
591
        PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
592
        totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
593
        return totalAmountCell;
594
    }
595
 
596
    /**
597
     * This method uses ICU4J libraries to convert the given amount into words
598
     * of Indian locale.
599
     * 
600
     * @param orderAmount
601
     *            The amount to convert.
602
     * @return the string representation of the given amount.
603
     */
604
    private PdfPCell getAmountInWordsCell(double orderAmount) {
605
        RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
606
        StringBuilder amountInWords = new StringBuilder("Rs. ");
607
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
608
        amountInWords.append(" and ");
609
        amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
610
        amountInWords.append(" paise");
611
 
612
        PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
613
        amountInWordsCell.setColspan(4);
614
        return amountInWordsCell;
615
    }
616
 
617
    /**
618
     * Returns the item name to be displayed in the invoice table.
619
     * 
620
     * @param lineitem
621
     *            The line item whose name has to be displayed
622
     * @param appendIMEI
623
     *            Whether to attach the IMEI No. to the item name
624
     * @return The name to be displayed for the given line item.
625
     */
626
    private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
627
        StringBuffer itemName = new StringBuffer();
628
        if(lineitem.getBrand()!= null)
629
            itemName.append(lineitem.getBrand() + " ");
630
        if(lineitem.getModel_name() != null)
631
            itemName.append(lineitem.getModel_name() + " ");
632
        if(lineitem.getModel_number() != null )
633
            itemName.append(lineitem.getModel_number() + " ");
634
        if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
635
            itemName.append("("+lineitem.getColor()+")");
636
        if(appendIMEI && lineitem.isSetImei_number()){
637
            itemName.append("\nIMEI No. " + lineitem.getImei_number());
638
        }
639
 
640
        return itemName.toString();
641
    }
642
 
643
    /**
644
     * 
645
     * @param colspan
646
     * @return a PdfPCell containing the E&amp;OE text and spanning the given
647
     *         no. of columns
648
     */
649
    private PdfPCell getEOECell(int colspan) {
650
        PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
651
        eoeCell.setColspan(colspan);
652
        eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
653
        return eoeCell;
654
    }
655
 
4262 rajveer 656
    private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize){
657
        PdfPTable extraInfoTable = new PdfPTable(1);
658
        extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
659
        extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
660
 
661
        String fontPath = InvoiceGenerationService.class.getResource("/saholic.TTF").getPath();
662
        FontFactoryImp ttfFontFactory = new FontFactoryImp();
663
        ttfFontFactory.register(fontPath, "barcode");
664
        Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
665
 
666
        PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
667
        extraInfoCell.setPaddingTop(20.0f);
668
        extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
669
        extraInfoCell.setBorder(Rectangle.NO_BORDER);
670
 
671
        extraInfoTable.addCell(extraInfoCell);
672
 
673
 
674
        return extraInfoTable;
675
    }
2787 chandransh 676
    public static void main(String[] args) throws IOException {
677
        InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
3065 chandransh 678
        long orderId = 542;
679
        ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, false);
2787 chandransh 680
        String userHome = System.getProperty("user.home");
681
        File f = new File(userHome + "/invoice-" + orderId + ".pdf");
682
        FileOutputStream fos = new FileOutputStream(f);
683
        baos.writeTo(fos);
684
        System.out.println("Invoice generated.");
685
    }
686
}