Subversion Repositories SmartDukaan

Rev

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