Subversion Repositories SmartDukaan

Rev

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