Subversion Repositories SmartDukaan

Rev

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