Subversion Repositories SmartDukaan

Rev

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