Subversion Repositories SmartDukaan

Rev

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