Subversion Repositories SmartDukaan

Rev

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