Subversion Repositories SmartDukaan

Rev

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