Subversion Repositories SmartDukaan

Rev

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