Subversion Repositories SmartDukaan

Rev

Rev 7422 | Rev 7556 | 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;
7528 rajveer 14
import in.shop2020.model.v1.order.AmazonOrder;
5527 anupam.sin 15
import in.shop2020.model.v1.order.Attribute;
2787 chandransh 16
import in.shop2020.model.v1.order.LineItem;
17
import in.shop2020.model.v1.order.Order;
7318 rajveer 18
import in.shop2020.model.v1.order.OrderSource;
4361 rajveer 19
import in.shop2020.model.v1.order.OrderStatus;
5527 anupam.sin 20
import in.shop2020.model.v1.order.OrderType;
7190 amar.kumar 21
import in.shop2020.thrift.clients.CatalogClient;
3132 rajveer 22
import in.shop2020.thrift.clients.LogisticsClient;
23
import in.shop2020.thrift.clients.TransactionClient;
2787 chandransh 24
import in.shop2020.thrift.clients.config.ConfigClient;
5948 mandeep.dh 25
import in.shop2020.thrift.clients.InventoryClient;
2787 chandransh 26
 
27
import java.io.ByteArrayOutputStream;
28
import java.io.File;
29
import java.io.FileOutputStream;
30
import java.io.IOException;
31
import java.text.DateFormat;
32
import java.text.DecimalFormat;
4361 rajveer 33
import java.util.ArrayList;
2787 chandransh 34
import java.util.Date;
35
import java.util.Enumeration;
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);
7318 rajveer 279
		addLogoTable(logoTable, order);
280
 
7014 rajveer 281
		PdfPCell titleCell = getTitleCell();
282
		PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false);
283
		PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont);
2787 chandransh 284
 
7014 rajveer 285
		PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
286
		dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
287
		dispatchTable.addCell(customerTable);
288
		dispatchTable.addCell(new Phrase(" "));
289
		dispatchTable.addCell(providerInfoTable);
2787 chandransh 290
 
7014 rajveer 291
		Warehouse shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId());
292
		PdfPTable invoiceTable = getTopInvoiceTable(order, shippingLocation.getTinNumber());
293
		PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
294
				"\nPIN " + warehouse.getPincode() + "\n\n");
2787 chandransh 295
 
7014 rajveer 296
		PdfPTable chargesTable = new PdfPTable(1);
297
		chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
298
		chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
299
		if(order.isLogisticsCod()){
7318 rajveer 300
			chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()), helveticaBold12));
7014 rajveer 301
			chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
302
		} else {
303
			chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
304
		}
2787 chandransh 305
 
7014 rajveer 306
		PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
307
		addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
308
		addressAndNoteTable.addCell(addressCell);
309
		addressAndNoteTable.addCell(chargesTable);
2787 chandransh 310
 
7014 rajveer 311
		table.addCell(logoTable);
312
		table.addCell(titleCell);
313
		table.addCell(dispatchTable);
314
		table.addCell(invoiceTable);
315
		table.addCell(new Phrase("If undelivered, return to:", helvetica10));
316
		table.addCell(addressAndNoteTable);
317
		return table;
318
	}
2787 chandransh 319
 
7318 rajveer 320
	private void addLogoTable(PdfPTable logoTable, Order order) {
321
		logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
322
		logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
323
		logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
324
 
325
		PdfPCell logoCell;
326
		String logoPath;
327
 
328
		if(order.getSource() == OrderSource.WEBSITE.getValue()){
329
			logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
330
 
331
			try {
332
				logoCell = new PdfPCell(Image.getInstance(logoPath), false);
333
			} catch (Exception e) {
334
				//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
335
				logger.warn("Couldn't load the Saholic logo: ", e);
336
				logoCell = new PdfPCell(new Phrase("Saholic Logo"));
337
			}
338
			logoCell.setBorder(Rectangle.NO_BORDER);
339
			logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
340
 
341
			logoTable.addCell(logoCell);
342
 
343
		}
344
 
345
		if(order.getSource() == OrderSource.STORE.getValue()){
7422 rajveer 346
			logoCell = new PdfPCell(new Phrase(""));
7318 rajveer 347
 
348
			logoCell.setBorder(Rectangle.NO_BORDER);
349
			logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
350
 
351
			logoTable.addCell(logoCell);
352
		}
353
	}
354
 
7014 rajveer 355
	private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
356
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
357
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
358
		ttfFontFactory.register(fontPath, "barcode");
359
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
360
		return barCodeFont;
361
	}
2787 chandransh 362
 
7014 rajveer 363
	private PdfPCell getTitleCell() {
364
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
365
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
366
		titleCell.setBorder(Rectangle.NO_BORDER);
367
		return titleCell;
368
	}
2787 chandransh 369
 
7014 rajveer 370
	private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
371
		PdfPTable providerInfoTable = new PdfPTable(1);
372
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7318 rajveer 373
		if(order.isLogisticsCod()){
374
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica28));
375
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
376
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
377
			providerInfoTable.addCell(deliveryTypeCell);
378
		}
379
 
380
 
381
 
382
 
7014 rajveer 383
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
384
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
385
		providerNameCell.setBorder(Rectangle.NO_BORDER);
386
 
387
		PdfPCell awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
388
		awbNumberCell.setPaddingTop(20.0f);
389
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
390
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
391
 
392
		providerInfoTable.addCell(providerNameCell);
393
		providerInfoTable.addCell(awbNumberCell);
394
		if(order.isLogisticsCod())
395
			providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.COD).getAccountNo(), helvetica8));
396
		else
397
			providerInfoTable.addCell(new Phrase("Account No : " + provider.getDetails().get(DeliveryType.PREPAID).getAccountNo(), helvetica8));
398
		Date awbDate;
399
		if(order.getBilling_timestamp() == 0){
400
			awbDate = new Date();
401
		}else{
402
			awbDate = new Date(order.getBilling_timestamp());
403
		}
404
		providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
405
		providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
406
		return providerInfoTable;
407
	}
408
 
409
	private PdfPTable getTopInvoiceTable(Order order, String tinNo){
410
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
411
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
412
 
413
		invoiceTable.addCell(getInvoiceTableHeader(6));
414
 
415
		invoiceTable.addCell(new Phrase("Order No", helvetica8));
416
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
417
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
418
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
419
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
420
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
421
		populateTopInvoiceTable(order, invoiceTable);
422
 
423
 
424
		if(order.getInsurer() > 0) {
425
			invoiceTable.addCell(getInsuranceCell(4));
426
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
427
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
428
		}
429
 
7318 rajveer 430
		if(order.getSource() == OrderSource.STORE.getValue()) {
431
			invoiceTable.addCell(getAdvanceAmountCell(4));
432
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
433
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
434
		}
435
 
7014 rajveer 436
		invoiceTable.addCell(getTotalCell(4));      
437
		invoiceTable.addCell(getRupeesCell());
7318 rajveer 438
		invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
7014 rajveer 439
 
440
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
441
		tinCell.setColspan(6);
442
		tinCell.setPadding(2);
443
		invoiceTable.addCell(tinCell);
444
 
445
		return invoiceTable;
446
	}
447
 
448
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
449
		List<LineItem> lineitems = order.getLineitems();
450
		for (LineItem lineitem : lineitems) {
451
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
452
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
453
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
454
			else if (order.isCod())
455
				invoiceTable.addCell(new Phrase("COD", helvetica8));
456
			else
457
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 458
 
7190 amar.kumar 459
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 460
 
7014 rajveer 461
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 462
 
7014 rajveer 463
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
464
 
465
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
466
		}
467
	}
468
 
469
	private PdfPCell getAddressCell(String address) {
470
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
471
		PdfPCell addressCell = new PdfPCell();
472
		addressCell.addElement(addressParagraph);
473
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
474
		addressCell.setBorder(Rectangle.NO_BORDER);
475
		return addressCell;
476
	}
477
 
478
	private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider){
479
		PdfPTable taxTable = new PdfPTable(1);
480
		Phrase phrase = null;
481
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
482
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
483
 
7318 rajveer 484
//		PdfPTable logoTable = new PdfPTable(2);
485
//		addLogoTable(logoTable, order);
486
 
7014 rajveer 487
		if (order.getOrderType().equals(OrderType.B2B)) {
488
			phrase = new Phrase("TAX INVOICE", helveticaBold12);
489
		} else {
490
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
491
		}
492
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
493
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
494
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
495
 
496
		Paragraph sorlAddress = new Paragraph(ourAddress + "TIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
497
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
498
		sorlAddressCell.addElement(sorlAddress);
499
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
500
 
501
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
502
		PdfPTable orderDetails = getOrderDetails(order, provider);
503
 
504
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
505
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
506
		addrAndOrderDetailsTable.addCell(customerAddress);
507
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
508
		addrAndOrderDetailsTable.addCell(orderDetails);
509
 
510
		boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
511
		PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
512
 
513
		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));
514
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
515
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
7318 rajveer 516
 
517
		//taxTable.addCell(logoTable);
7014 rajveer 518
		taxTable.addCell(retailInvoiceTitleCell);
519
		taxTable.addCell(sorlAddress);
520
		taxTable.addCell(addrAndOrderDetailsTable);
521
		taxTable.addCell(invoiceTable);
522
		taxTable.addCell(disclaimerCell);
523
 
524
		return taxTable;
525
	}
526
 
527
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
528
		PdfPTable customerTable = new PdfPTable(1);
529
		customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
530
		if(forInvoce || order.getPickupStoreId() == 0){
531
			customerTable.addCell(new Phrase(order.getCustomer_name(), font));
532
			customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
533
			customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
534
			customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
535
			if(destCode != null)
536
				customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
537
			else
538
				customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
539
			customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
540
		}else{
541
			try {
5556 rajveer 542
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 543
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
544
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
545
				customerTable.addCell(new Phrase(store.getLine1(), font));
546
				customerTable.addCell(new Phrase(store.getLine2(), font));
547
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
548
				if(destCode != null)
549
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
550
				else
551
					customerTable.addCell(new Phrase(store.getPin(), font));
552
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 553
			} catch (TException e) {
554
				// TODO Auto-generated catch block
555
				e.printStackTrace();
556
			}
5527 anupam.sin 557
 
7014 rajveer 558
		}
559
 
560
		if(order.getOrderType().equals(OrderType.B2B)) {
561
			String tin = null;
562
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
563
			List<Attribute> attributes;
564
			try {
565
				attributes = tclient.getAllAttributesForOrderId(order.getId());
566
 
567
				for(Attribute attribute : attributes) {
568
					if(attribute.getName().equals("tinNumber")) {
569
						tin = attribute.getValue();
570
					}
571
				}
572
				if (tin != null) {
573
					customerTable.addCell(new Phrase("TIN :" + tin, font));
574
				}
575
 
576
			} catch (Exception e) {
577
				logger.error("Error while getting order attributes", e);
578
			}
579
		}
580
		/*
2787 chandransh 581
        if(showPaymentMode){
582
            customerTable.addCell(new Phrase(" ", font));
583
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 584
        }*/
7014 rajveer 585
		return customerTable;
586
	}
2787 chandransh 587
 
7014 rajveer 588
	private PdfPTable getOrderDetails(Order order, Provider provider){
589
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
590
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 591
 
7014 rajveer 592
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
593
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 594
 
7014 rajveer 595
		orderTable.addCell(new Phrase("Date:", helvetica8));
596
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 597
 
7014 rajveer 598
		orderTable.addCell(new Phrase("Order ID:", helvetica8));
599
		orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
2787 chandransh 600
 
7528 rajveer 601
		if(order.getSource() == OrderSource.AMAZON.getValue()){
602
			AmazonOrder aorder = null;
603
			try {
604
				aorder = tsc.getClient().getAmazonOrder(order.getId());
605
			} catch (TException e) {
606
				logger.error("Error while getting amazon order", e);
607
			}
608
			orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
609
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
610
		}
611
 
7014 rajveer 612
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
613
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
2787 chandransh 614
 
7014 rajveer 615
		orderTable.addCell(new Phrase("Courier:", helvetica8));
616
		orderTable.addCell(new Phrase(provider.getName(), helvetica8));
2787 chandransh 617
 
7014 rajveer 618
		orderTable.addCell(new Phrase("AWB No:", helvetica8));
619
		orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
2787 chandransh 620
 
7014 rajveer 621
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
622
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 623
 
7014 rajveer 624
		return orderTable;
625
	}
2787 chandransh 626
 
7014 rajveer 627
	private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
628
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
629
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 630
 
7014 rajveer 631
		invoiceTable.addCell(getInvoiceTableHeader(5));
4262 rajveer 632
 
7014 rajveer 633
		invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
634
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
635
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
636
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
637
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
638
		LineItem lineItem = order.getLineitems().get(0);
639
		double orderAmount = order.getTotal_amount();
640
		double rate = lineItem.getVatRate();
7057 amar.kumar 641
		double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
6750 rajveer 642
 
7014 rajveer 643
		populateBottomInvoiceTable(order, invoiceTable, rate);
6750 rajveer 644
 
7014 rajveer 645
		PdfPCell salesTaxCell = getPriceCell(salesTax);
646
 
647
		invoiceTable.addCell(getVATLabelCell(isVAT));
648
		invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
649
		invoiceTable.addCell(salesTaxCell);
650
 
651
		if(order.getInsurer() > 0) {
652
			invoiceTable.addCell(getInsuranceCell(3));
653
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
654
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
655
		}
656
 
657
		invoiceTable.addCell(getEmptyCell(5));
658
 
659
		invoiceTable.addCell(getTotalCell(3));
660
		invoiceTable.addCell(getRupeesCell());
661
		invoiceTable.addCell(getTotalAmountCell(orderAmount));
662
 
663
		invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
664
		invoiceTable.addCell(getAmountInWordsCell(orderAmount));
665
 
666
		invoiceTable.addCell(getEOECell(5));
667
 
668
		return invoiceTable;
669
	}
670
 
671
	private PdfPCell getInvoiceTableHeader(int colspan) {
672
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
673
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
674
		invoiceTableHeader.setColspan(colspan);
675
		invoiceTableHeader.setPaddingTop(10);
676
		return invoiceTableHeader;
677
	}
678
 
679
	private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
680
		for (LineItem lineitem : order.getLineitems()) {
681
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
682
 
7190 amar.kumar 683
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 684
 
685
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
686
 
687
			double itemPrice = lineitem.getUnit_price();
688
			double showPrice = (100 * itemPrice)/(100 + rate);
689
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
690
 
691
			double totalPrice = lineitem.getTotal_price();
692
			showPrice = (100 * totalPrice)/(100 + rate);
693
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
694
		}
695
	}
696
 
7190 amar.kumar 697
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 698
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 699
		if(freebieItemId!=null && freebieItemId!=0){
700
			try {
701
				CatalogService.Client catalogClient = ctsc.getClient();
702
				Item item = catalogClient.getItem(freebieItemId);
703
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
704
			} catch(Exception tex) {
705
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
706
			}
707
		}
7014 rajveer 708
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
709
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
710
		return productNameCell;
711
	}
712
 
713
	private PdfPCell getPriceCell(double price) {
714
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
715
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
716
		return totalPriceCell;
717
	}
718
 
719
	private PdfPCell getVATLabelCell(boolean isVAT) {
720
		PdfPCell vatCell = null;
721
		if(isVAT){
722
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
723
		} else {
724
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
725
		}
726
		vatCell.setColspan(3);
727
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
728
		return vatCell;
729
	}
730
 
7318 rajveer 731
	private PdfPCell getAdvanceAmountCell(int colspan) {
732
		PdfPCell insuranceCell = null;
733
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
734
		insuranceCell.setColspan(colspan);
735
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
736
		return insuranceCell;
737
	}
738
 
7014 rajveer 739
	private PdfPCell getInsuranceCell(int colspan) {
740
		PdfPCell insuranceCell = null;
741
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance", helvetica8));
742
		insuranceCell.setColspan(colspan);
743
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
744
		return insuranceCell;
745
	}
746
 
747
	private PdfPCell getEmptyCell(int colspan) {
748
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
749
		emptyCell.setColspan(colspan);
750
		return emptyCell;
751
	}
752
 
753
	private PdfPCell getTotalCell(int colspan) {
754
		PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
755
		totalCell.setColspan(colspan);
756
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
757
		return totalCell;
758
	}
759
 
760
	private PdfPCell getRupeesCell() {
761
		PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
762
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
763
		return rupeesCell;
764
	}
765
 
766
	private PdfPCell getTotalAmountCell(double orderAmount) {
767
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
768
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
769
		return totalAmountCell;
770
	}
771
 
772
	/**
773
	 * This method uses ICU4J libraries to convert the given amount into words
774
	 * of Indian locale.
775
	 * 
776
	 * @param orderAmount
777
	 *            The amount to convert.
778
	 * @return the string representation of the given amount.
779
	 */
780
	private PdfPCell getAmountInWordsCell(double orderAmount) {
781
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
782
		StringBuilder amountInWords = new StringBuilder("Rs. ");
783
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
784
		amountInWords.append(" and ");
785
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
786
		amountInWords.append(" paise");
787
 
788
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
789
		amountInWordsCell.setColspan(4);
790
		return amountInWordsCell;
791
	}
792
 
793
	/**
794
	 * Returns the item name to be displayed in the invoice table.
795
	 * 
796
	 * @param lineitem
797
	 *            The line item whose name has to be displayed
798
	 * @param appendIMEI
799
	 *            Whether to attach the IMEI No. to the item name
800
	 * @return The name to be displayed for the given line item.
801
	 */
802
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
803
		StringBuffer itemName = new StringBuffer();
804
		if(lineitem.getBrand()!= null)
805
			itemName.append(lineitem.getBrand() + " ");
806
		if(lineitem.getModel_name() != null)
807
			itemName.append(lineitem.getModel_name() + " ");
808
		if(lineitem.getModel_number() != null )
809
			itemName.append(lineitem.getModel_number() + " ");
810
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
811
			itemName.append("("+lineitem.getColor()+")");
812
		if(appendIMEI && lineitem.isSetSerial_number()){
813
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
814
		}
815
 
816
		return itemName.toString();
817
	}
818
 
819
	/**
820
	 * 
821
	 * @param colspan
822
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
823
	 *         no. of columns
824
	 */
825
	private PdfPCell getEOECell(int colspan) {
826
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
827
		eoeCell.setColspan(colspan);
828
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
829
		return eoeCell;
830
	}
831
 
832
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
833
		PdfPTable extraInfoTable = new PdfPTable(1);
834
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
835
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
836
 
837
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
838
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
839
		ttfFontFactory.register(fontPath, "barcode");
840
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
841
 
842
		PdfPCell extraInfoCell;
843
		if(billingType == BillingType.EXTERNAL){
844
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
845
		}else{
846
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
847
		}
848
 
849
		extraInfoCell.setPaddingTop(20.0f);
850
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
851
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
852
 
853
		extraInfoTable.addCell(extraInfoCell);
854
 
855
 
856
		return extraInfoTable;
857
	}
858
 
859
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
860
		PdfPTable extraInfoTable = new PdfPTable(1);
861
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
862
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
863
 
864
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
865
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
866
		ttfFontFactory.register(fontPath, "barcode");
867
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
868
 
869
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
870
 
871
		extraInfoCell.setPaddingTop(20.0f);
872
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
873
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
874
 
875
		extraInfoTable.addCell(extraInfoCell);
876
 
877
		return extraInfoTable;
878
	}
879
 
880
	public static void main(String[] args) throws IOException {
881
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 882
		long orderId = 356324;
883
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 884
		String userHome = System.getProperty("user.home");
885
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
886
		FileOutputStream fos = new FileOutputStream(f);
887
		baos.writeTo(fos);
888
		System.out.println("Invoice generated.");
889
	}
2787 chandransh 890
}