Subversion Repositories SmartDukaan

Rev

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