Subversion Repositories SmartDukaan

Rev

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