Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
490 rajveer 1
package in.shop2020.support.services;
2
 
1517 ankur.sing 3
import in.shop2020.config.ConfigException;
670 chandransh 4
import in.shop2020.logistics.LogisticsServiceException;
5
import in.shop2020.logistics.Provider;
490 rajveer 6
import in.shop2020.model.v1.catalog.InventoryService.Client;
7
import in.shop2020.model.v1.catalog.InventoryServiceException;
8
import in.shop2020.model.v1.catalog.Warehouse;
505 rajveer 9
import in.shop2020.model.v1.order.LineItem;
490 rajveer 10
import in.shop2020.model.v1.order.Order;
11
import in.shop2020.model.v1.order.TransactionServiceException;
12
import in.shop2020.thrift.clients.CatalogServiceClient;
670 chandransh 13
import in.shop2020.thrift.clients.LogisticsServiceClient;
490 rajveer 14
import in.shop2020.thrift.clients.TransactionServiceClient;
1517 ankur.sing 15
import in.shop2020.thrift.clients.config.ConfigClient;
490 rajveer 16
 
17
import java.io.ByteArrayOutputStream;
18
import java.io.File;
19
import java.io.FileOutputStream;
505 rajveer 20
import java.io.IOException;
2784 chandransh 21
import java.io.InputStream;
670 chandransh 22
import java.text.DateFormat;
734 chandransh 23
import java.text.DecimalFormat;
490 rajveer 24
import java.util.Date;
505 rajveer 25
import java.util.List;
2784 chandransh 26
import java.util.Locale;
27
import java.util.Properties;
490 rajveer 28
 
2784 chandransh 29
import org.apache.commons.lang.WordUtils;
490 rajveer 30
import org.apache.thrift.TException;
2784 chandransh 31
import org.slf4j.Logger;
32
import org.slf4j.LoggerFactory;
490 rajveer 33
 
2784 chandransh 34
import com.ibm.icu.text.RuleBasedNumberFormat;
35
 
490 rajveer 36
import com.itextpdf.text.Document;
37
import com.itextpdf.text.Element;
38
import com.itextpdf.text.Font;
39
import com.itextpdf.text.Font.FontFamily;
40
import com.itextpdf.text.FontFactory;
41
import com.itextpdf.text.FontFactoryImp;
670 chandransh 42
import com.itextpdf.text.Image;
490 rajveer 43
import com.itextpdf.text.Paragraph;
505 rajveer 44
import com.itextpdf.text.Phrase;
670 chandransh 45
import com.itextpdf.text.Rectangle;
490 rajveer 46
import com.itextpdf.text.pdf.BaseFont;
47
import com.itextpdf.text.pdf.PdfPCell;
48
import com.itextpdf.text.pdf.PdfPTable;
49
import com.itextpdf.text.pdf.PdfWriter;
2784 chandransh 50
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
490 rajveer 51
 
52
public class InvoiceGenerationService {
2784 chandransh 53
 
54
	private static Logger logger = LoggerFactory.getLogger(InvoiceGenerationService.class);
55
 
734 chandransh 56
	private TransactionServiceClient tsc = null;
57
	private CatalogServiceClient csc = null;
58
	private LogisticsServiceClient lsc = null;
2784 chandransh 59
 
60
	private static Locale indianLocale = new Locale("en", "IN");
734 chandransh 61
	private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");
2784 chandransh 62
 
63
	private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
64
	private static final Font helvetica10 = FontFactory.getFont(FontFactory.HELVETICA, 10);
65
	private static final Font helvetica12 = FontFactory.getFont(FontFactory.HELVETICA, 12);
66
	private static final Font helvetica16 = FontFactory.getFont(FontFactory.HELVETICA, 16);
490 rajveer 67
 
2784 chandransh 68
	private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
69
	private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);
70
 
71
	private static final Properties properties = readProperties();
72
	private static final String ourAddress = properties.getProperty("sales_tax_address",
73
					"Spice Online Retail Pvt. Ltd.\nKhasra No. 819, Block-K\nMahipalpur, New Delhi-110037\n");
74
	private static final String tinNo = properties.getProperty("sales_tax_tin",	"07250399732");
75
 
76
	private static final String delhiPincodePrefix = "11";
77
 
78
	private static final double salesTaxLowRate = Double.parseDouble(properties.getProperty("sales_tax_low_rate", "5.0"));
79
	private static final double salesTaxHighRate = Double.parseDouble(properties.getProperty("sales_tax_high_rate", "12.5"));
80
	private static final double salesTaxCutOff = (Double.parseDouble(properties.getProperty("sales_tax_cutoff", "10000")) * (100 + salesTaxLowRate))/100;
81
 
82
	private static Properties readProperties(){
83
		Properties props = new Properties();
84
		try {
85
			InputStream is = InvoiceGenerationService.class.getResourceAsStream("/in/shop2020/support/services/InvoiceGenerationService.properties");
86
			props.load(is);
87
		} catch (IOException e) {
88
			logger.error("Error while reading properties file.", e);
89
		}
90
		return props;
91
	}
92
 
734 chandransh 93
	public InvoiceGenerationService() {
94
		try {
490 rajveer 95
			tsc = new TransactionServiceClient();
96
			csc = new CatalogServiceClient();
670 chandransh 97
			lsc = new LogisticsServiceClient();
490 rajveer 98
		} catch (Exception e) {
2784 chandransh 99
			logger.error("Error while instantiating thrift clients.", e);
490 rajveer 100
		}
101
	}
734 chandransh 102
 
103
	public ByteArrayOutputStream generateInvoice(long orderId) {
670 chandransh 104
		ByteArrayOutputStream baosPDF = null;
105
		in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
106
		Client iclient = csc.getClient();
107
		in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
734 chandransh 108
 
670 chandransh 109
		Order order = null;
110
		Warehouse warehouse = null;
111
		Provider provider = null;
734 chandransh 112
		String destCode = null;
1517 ankur.sing 113
		int barcodeFontSize = 0;
670 chandransh 114
		try {
490 rajveer 115
			order = tclient.getOrder(orderId);
116
			warehouse = iclient.getWarehouse(order.getWarehouse_id());
734 chandransh 117
			long providerId = order.getLogistics_provider_id();
118
			provider = logisticsClient.getProvider(providerId);
119
			destCode = logisticsClient.getDestinationCode(providerId, order.getCustomer_pincode());
1517 ankur.sing 120
			barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
2784 chandransh 121
		} catch (TransactionServiceException tse) {
122
			logger.error("Error while getting order information", tse);
670 chandransh 123
			return baosPDF;
2784 chandransh 124
		} catch (InventoryServiceException ise) {
125
			logger.error("Error while getting the warehouse information.", ise);
670 chandransh 126
			return baosPDF;
2784 chandransh 127
		} catch (LogisticsServiceException lse) {
128
			logger.error("Error while getting the provider information.", lse);
670 chandransh 129
			return baosPDF;
2784 chandransh 130
		} catch (ConfigException ce) {
131
			logger.error("Error while getting the fontsize for the given provider", ce);
670 chandransh 132
			return baosPDF;
2784 chandransh 133
		} catch (TException te) {
134
			logger.error("Error while getting some essential information from the services", te);
1517 ankur.sing 135
			return baosPDF;
490 rajveer 136
		}
734 chandransh 137
 
138
		try {
139
			baosPDF = new ByteArrayOutputStream();
140
 
141
			Document document = new Document();
142
			PdfWriter.getInstance(document, baosPDF);
143
			document.addAuthor("shop2020");
144
			document.addTitle("Invoice No: " + order.getInvoice_number());
145
			document.open();
2784 chandransh 146
 
147
			PdfPTable dispatchAdviceTable = getDispatchAdviceTable(order, warehouse, provider, barcodeFontSize, destCode);
148
			dispatchAdviceTable.setSpacingAfter(10.0f);
149
			dispatchAdviceTable.setWidthPercentage(90.0f);
150
 
151
			PdfPTable taxTable = getTaxCumRetailInvoiceTable(order, provider);
152
			taxTable.setSpacingBefore(5.0f);
153
			taxTable.setWidthPercentage(90.0f);
734 chandransh 154
 
2784 chandransh 155
			document.add(dispatchAdviceTable);
156
			document.add(new DottedLineSeparator());
157
			document.add(taxTable);
158
			document.close();
159
			baosPDF.close();
160
		} catch (Exception e) {
161
			logger.error("Error while generating Invoice: ", e);
162
		}
163
		return baosPDF;
164
	}
165
 
166
	private PdfPTable getDispatchAdviceTable(Order order, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode){
167
		Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
168
 
169
		PdfPTable table = new PdfPTable(1);
170
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
734 chandransh 171
 
2784 chandransh 172
		PdfPCell logoCell = getLogoCell();
173
		PdfPCell titleCell = getTitleCell();
174
		PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12);
175
		PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont);
176
 
177
		PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
178
		dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
179
		dispatchTable.addCell(customerTable);
180
		dispatchTable.addCell(new Phrase(" "));
181
		dispatchTable.addCell(providerInfoTable);
182
 
183
		PdfPTable invoiceTable = getTopInvoiceTable(order);
734 chandransh 184
 
2784 chandransh 185
		PdfPCell addressCell = getAddressCell();
186
 
187
		table.addCell(logoCell);
188
		table.addCell(titleCell);
189
		table.addCell(dispatchTable);
190
		table.addCell(invoiceTable);
191
		table.addCell(new Phrase("If undelivered, return to:", helvetica10));
192
		table.addCell(addressCell);
193
		table.addCell(new Phrase("Do not pay any extra charges to the Courier."));
194
		return table;
195
	}
734 chandransh 196
 
2784 chandransh 197
	private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
198
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
199
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
200
		ttfFontFactory.register(fontPath, "barcode");
201
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
202
		return barCodeFont;
203
	}
734 chandransh 204
 
2784 chandransh 205
	private PdfPCell getLogoCell() {
206
		String logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
207
		PdfPCell logoCell;
208
		try {
209
			logoCell = new PdfPCell(Image.getInstance(logoPath), false);
210
		} catch (Exception e) {
211
			//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
212
			logger.warn("Couldn't load the Saholic logo: ", e);
213
			logoCell = new PdfPCell(new Phrase("Saholic Logo"));
214
		}
215
		logoCell.setBorder(Rectangle.NO_BORDER);
216
		return logoCell;
217
	}
734 chandransh 218
 
2784 chandransh 219
	private PdfPCell getTitleCell() {
220
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice",	helveticaBold12));
221
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
222
		titleCell.setBorder(Rectangle.NO_BORDER);
223
		return titleCell;
224
	}
225
 
226
	private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
227
		PdfPTable providerInfoTable = new PdfPTable(1);
228
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
229
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
230
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
231
		providerNameCell.setBorder(Rectangle.NO_BORDER);
232
 
233
		PdfPCell awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
234
		awbNumberCell.setPaddingTop(20.0f);
235
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
236
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
237
 
238
		providerInfoTable.addCell(providerNameCell);
239
		providerInfoTable.addCell(awbNumberCell);
240
		providerInfoTable.addCell(new Phrase("Account No : " + provider.getAccountNo(), helvetica8));
241
		providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
242
		providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
243
		return providerInfoTable;
244
	}
245
 
246
	private PdfPTable getTopInvoiceTable(Order order){
247
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
248
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
249
 
250
		invoiceTable.addCell(getInvoiceTableHeader(6));
251
 
252
		invoiceTable.addCell(new Phrase("Order No", helvetica8));
253
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
254
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
255
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
256
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
257
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
258
		populateTopInvoiceTable(order, invoiceTable);
259
 
260
		invoiceTable.addCell(getTotalCell(4));		
261
		invoiceTable.addCell(getRupeesCell());
262
		invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()));
263
 
264
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
265
		tinCell.setColspan(6);
266
		tinCell.setPadding(2);
267
		invoiceTable.addCell(tinCell);
268
 
269
		return invoiceTable;
270
	}
271
 
272
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
273
		List<LineItem> lineitems = order.getLineitems();
274
		for (LineItem lineitem : lineitems) {
275
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
276
			invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
734 chandransh 277
 
2784 chandransh 278
			invoiceTable.addCell(getProductNameCell(lineitem, false));
279
 
280
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
281
 
282
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()));
283
 
284
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
285
		}
286
	}
287
 
288
	private PdfPCell getAddressCell() {
289
		Paragraph addressParagraph = new Paragraph(ourAddress, new Font(FontFamily.TIMES_ROMAN, 8f));
290
		PdfPCell addressCell = new PdfPCell();
291
		addressCell.addElement(addressParagraph);
292
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
293
		addressCell.setBorder(Rectangle.NO_BORDER);
294
		return addressCell;
295
	}
296
 
297
	private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider){
298
		PdfPTable taxTable = new PdfPTable(1);
299
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
300
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
301
 
302
		PdfPCell retailInvoiceTitleCell = new PdfPCell(new Phrase("TAX CUM RETAIL INVOICE", helveticaBold12));
303
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
304
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
305
 
306
		Paragraph sorlAddress = new Paragraph(ourAddress + "TIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
307
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
308
		sorlAddressCell.addElement(sorlAddress);
309
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
310
 
311
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8);
312
		PdfPTable orderDetails = getOrderDetails(order, provider);
313
 
314
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
315
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
316
		addrAndOrderDetailsTable.addCell(customerAddress);
317
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
318
		addrAndOrderDetailsTable.addCell(orderDetails);
319
 
320
		boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
321
		PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
322
 
323
		PdfPCell disclaimerCell = new PdfPCell(new Phrase("Goods once sold will not be taken back.\nAll disputes subject to Delhi Jurisdiction.", helvetica8));
324
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
325
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
326
 
327
		taxTable.addCell(retailInvoiceTitleCell);
328
		taxTable.addCell(sorlAddress);
329
		taxTable.addCell(addrAndOrderDetailsTable);
330
		taxTable.addCell(invoiceTable);
331
		taxTable.addCell(disclaimerCell);
332
 
333
		return taxTable;
334
	}
335
 
336
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font){
337
		PdfPTable customerTable = new PdfPTable(1);
338
		customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
339
		customerTable.addCell(new Phrase(order.getCustomer_name(), font));
340
		customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
341
		customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
342
		customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
343
		if(destCode != null)
734 chandransh 344
			customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
2784 chandransh 345
		else
346
			customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
347
		customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
348
		if(showPaymentMode){
349
			customerTable.addCell(new Phrase(" ", font));
350
			customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
351
		}
352
		return customerTable;
353
	}
354
 
355
	private PdfPTable getOrderDetails(Order order, Provider provider){
356
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
357
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
358
 
359
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
360
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
361
 
362
		orderTable.addCell(new Phrase("Date:", helvetica8));
363
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
364
 
365
		orderTable.addCell(new Phrase(" "));
366
		orderTable.addCell(new Phrase(" "));
367
 
368
		orderTable.addCell(new Phrase("Order ID:", helvetica8));
369
		orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
370
 
371
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
372
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
373
 
374
		orderTable.addCell(new Phrase("Courier:", helvetica8));
375
		orderTable.addCell(new Phrase(provider.getName(), helvetica8));
376
 
377
		orderTable.addCell(new Phrase("AWB No:", helvetica8));
378
		orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
379
 
380
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
381
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()), helvetica8));
382
 
383
		return orderTable;
384
	}
385
 
386
	private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
387
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
388
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
734 chandransh 389
 
2784 chandransh 390
		invoiceTable.addCell(getInvoiceTableHeader(5));
734 chandransh 391
 
2784 chandransh 392
		invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
393
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
394
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
395
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
396
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
397
 
398
		double orderAmount = order.getTotal_amount();
399
		double rate = getTaxRate(orderAmount);
400
		double salesTax = (rate * orderAmount)/(100 + rate);
401
 
402
		populateBottomInvoiceTable(order, invoiceTable, rate);
403
 
404
		PdfPCell salesTaxCell = getPriceCell(salesTax);
405
 
406
		invoiceTable.addCell(getVATLabelCell(isVAT));
407
		invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
408
		invoiceTable.addCell(salesTaxCell);
409
 
410
		invoiceTable.addCell(getEmptyCell(5));
411
 
412
		invoiceTable.addCell(getTotalCell(3));
413
		invoiceTable.addCell(getRupeesCell());
414
		invoiceTable.addCell(getTotalAmountCell(orderAmount));
415
 
416
		invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
417
		invoiceTable.addCell(getAmountInWordsCell(orderAmount));
418
 
419
		invoiceTable.addCell(getEOECell(5));
420
 
421
		return invoiceTable;
422
	}
734 chandransh 423
 
2784 chandransh 424
	private PdfPCell getInvoiceTableHeader(int colspan) {
425
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
426
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
427
		invoiceTableHeader.setColspan(colspan);
428
		invoiceTableHeader.setPaddingTop(10);
429
		return invoiceTableHeader;
430
	}
431
 
432
	private double getTaxRate(double orderAmount) {
433
		double rate;
434
		if(orderAmount <= salesTaxCutOff){
435
			rate = salesTaxLowRate;
436
		} else {
437
			rate = salesTaxHighRate;
438
		}
439
		return rate;
440
	}
441
 
442
	private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
443
		for (LineItem lineitem : order.getLineitems()) {
444
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
734 chandransh 445
 
2784 chandransh 446
			invoiceTable.addCell(getProductNameCell(lineitem, true));
734 chandransh 447
 
2784 chandransh 448
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
449
 
450
			double itemPrice = lineitem.getUnit_price();
451
			double showPrice = (100 * itemPrice)/(100 + rate);
452
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
453
 
454
			double totalPrice = lineitem.getTotal_price();
455
			showPrice = (100 * totalPrice)/(100 + rate);
456
			invoiceTable.addCell(getPriceCell(showPrice));	//Total Price Cell
457
		}
458
	}
734 chandransh 459
 
2784 chandransh 460
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI) {
461
		String itemName = getItemDisplayName(lineitem, appendIMEI);
462
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
463
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
464
		return productNameCell;
465
	}
734 chandransh 466
 
2784 chandransh 467
	private PdfPCell getPriceCell(double price) {
468
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
469
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
470
		return totalPriceCell;
471
	}
734 chandransh 472
 
2784 chandransh 473
	private PdfPCell getVATLabelCell(boolean isVAT) {
474
		PdfPCell vatCell = null;
475
		if(isVAT){
476
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
477
		} else {
478
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
479
		}
480
		vatCell.setColspan(3);
481
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
482
		return vatCell;
483
	}
484
 
485
	private PdfPCell getEmptyCell(int colspan) {
486
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
487
		emptyCell.setColspan(colspan);
488
		return emptyCell;
489
	}
734 chandransh 490
 
2784 chandransh 491
	private PdfPCell getTotalCell(int colspan) {
492
		PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
493
		totalCell.setColspan(colspan);
494
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
495
		return totalCell;
496
	}
497
 
498
	private PdfPCell getRupeesCell() {
499
		PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
500
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
501
		return rupeesCell;
502
	}
734 chandransh 503
 
2784 chandransh 504
	private PdfPCell getTotalAmountCell(double orderAmount) {
505
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
506
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
507
		return totalAmountCell;
508
	}
509
 
510
	/**
511
	 * This method uses ICU4J libraries to convert the given amount into words
512
	 * of Indian locale.
513
	 * 
514
	 * @param orderAmount
515
	 *            The amount to convert.
516
	 * @return the string representation of the given amount.
517
	 */
518
	private PdfPCell getAmountInWordsCell(double orderAmount) {
519
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
520
		StringBuilder amountInWords = new StringBuilder("Rs. ");
521
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
522
		amountInWords.append(" and ");
523
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
524
		amountInWords.append(" paise");
525
 
526
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
527
		amountInWordsCell.setColspan(4);
528
		return amountInWordsCell;
529
	}
530
 
531
	/**
532
	 * Returns the item name to be displayed in the invoice table.
533
	 * 
534
	 * @param lineitem
535
	 *            The line item whose name has to be displayed
536
	 * @param appendIMEI
537
	 *            Whether to attach the IMEI No. to the item name
538
	 * @return The name to be displayed for the given line item.
539
	 */
540
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
541
		StringBuffer itemName = new StringBuffer();
542
		if(lineitem.getBrand()!= null)
543
			itemName.append(lineitem.getBrand() + " ");
544
		if(lineitem.getModel_name() != null)
545
			itemName.append(lineitem.getModel_name() + " ");
546
		if(lineitem.getModel_number() != null )
547
			itemName.append(lineitem.getModel_number() + " ");
548
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
549
			itemName.append("("+lineitem.getColor()+")");
550
		if(appendIMEI && lineitem.isSetImei_number()){
551
			itemName.append("\nIMEI No. " + lineitem.getImei_number());
734 chandransh 552
		}
2784 chandransh 553
 
554
		return itemName.toString();
734 chandransh 555
	}
556
 
2784 chandransh 557
	/**
558
	 * 
559
	 * @param colspan
560
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
561
	 *         no. of columns
562
	 */
563
	private PdfPCell getEOECell(int colspan) {
564
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
565
		eoeCell.setColspan(colspan);
566
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
567
		return eoeCell;
568
	}
569
 
505 rajveer 570
	public static void main(String[] args) throws IOException {
734 chandransh 571
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
2784 chandransh 572
		long orderId = 434;
1476 ankur.sing 573
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId);
574
		String userHome = System.getProperty("user.home");
575
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
505 rajveer 576
		FileOutputStream fos = new FileOutputStream(f);
577
		baos.writeTo(fos);
1476 ankur.sing 578
		System.out.println("Invoice generated.");
490 rajveer 579
	}
580
}