Subversion Repositories SmartDukaan

Rev

Rev 8034 | Rev 8036 | 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);
8035 manish.sha 307
 
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 ){
8035 manish.sha 438
			doc.open();
8034 manish.sha 439
			Barcode128 code128 = new Barcode128();
440
			code128.setGenerateChecksum(true);
441
			code128.setCode("*"+fedexPackageBarcode+"*"); 
8035 manish.sha 442
			try {
443
				baos = new ByteArrayOutputStream();
444
				providerInfoTable.addCell(code128.createImageWithBarcode(PdfWriter.getInstance(doc, baos).getDirectContent(), null, null));
445
			} catch (Exception e) {
446
				logger.error("Error while adding barcode for FedEx: ", e);
447
			}
8034 manish.sha 448
		}
7792 anupam.sin 449
 
450
		Warehouse warehouse = null;
451
		try{
452
    		InventoryClient isc = new InventoryClient();
7804 amar.kumar 453
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
7803 amar.kumar 454
		} catch(Exception e) {
7792 anupam.sin 455
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
7805 amar.kumar 456
		    //TODO throw e;
7792 anupam.sin 457
		}
458
		DeliveryType dt =  DeliveryType.PREPAID;
459
        if (order.isLogisticsCod()) {
460
            dt = DeliveryType.COD;
461
        }
7994 manish.sha 462
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
463
        if(order.getLogistics_provider_id()!=7L){
464
	        for (ProviderDetails detail : provider.getDetails()) {
465
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
466
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
467
	            }
468
	        }
7792 anupam.sin 469
        }
7994 manish.sha 470
        else{
471
        	providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
472
        }
473
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 474
		Date awbDate;
475
		if(order.getBilling_timestamp() == 0){
476
			awbDate = new Date();
477
		}else{
478
			awbDate = new Date(order.getBilling_timestamp());
479
		}
480
		providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
481
		providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
7994 manish.sha 482
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
483
		if(order.getLogistics_provider_id()==7L){
484
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
485
		}
486
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 487
		return providerInfoTable;
488
	}
489
 
490
	private PdfPTable getTopInvoiceTable(Order order, String tinNo){
491
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
492
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
493
 
494
		invoiceTable.addCell(getInvoiceTableHeader(6));
495
 
496
		invoiceTable.addCell(new Phrase("Order No", helvetica8));
497
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
498
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
499
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
500
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
501
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
502
		populateTopInvoiceTable(order, invoiceTable);
503
 
504
 
505
		if(order.getInsurer() > 0) {
506
			invoiceTable.addCell(getInsuranceCell(4));
507
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
508
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
509
		}
510
 
7318 rajveer 511
		if(order.getSource() == OrderSource.STORE.getValue()) {
512
			invoiceTable.addCell(getAdvanceAmountCell(4));
513
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
514
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
515
		}
516
 
7014 rajveer 517
		invoiceTable.addCell(getTotalCell(4));      
518
		invoiceTable.addCell(getRupeesCell());
7318 rajveer 519
		invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
7014 rajveer 520
 
521
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
522
		tinCell.setColspan(6);
523
		tinCell.setPadding(2);
524
		invoiceTable.addCell(tinCell);
525
 
526
		return invoiceTable;
527
	}
528
 
529
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
530
		List<LineItem> lineitems = order.getLineitems();
531
		for (LineItem lineitem : lineitems) {
532
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
533
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
534
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
535
			else if (order.isCod())
536
				invoiceTable.addCell(new Phrase("COD", helvetica8));
537
			else
538
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 539
 
7190 amar.kumar 540
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 541
 
7014 rajveer 542
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 543
 
7014 rajveer 544
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
545
 
546
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
547
		}
548
	}
549
 
550
	private PdfPCell getAddressCell(String address) {
551
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
552
		PdfPCell addressCell = new PdfPCell();
553
		addressCell.addElement(addressParagraph);
554
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
555
		addressCell.setBorder(Rectangle.NO_BORDER);
556
		return addressCell;
557
	}
558
 
8011 rajveer 559
	private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider, String ourAddress, String tinNo){
7014 rajveer 560
		PdfPTable taxTable = new PdfPTable(1);
561
		Phrase phrase = null;
562
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
563
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
564
 
7318 rajveer 565
//		PdfPTable logoTable = new PdfPTable(2);
566
//		addLogoTable(logoTable, order);
567
 
7014 rajveer 568
		if (order.getOrderType().equals(OrderType.B2B)) {
569
			phrase = new Phrase("TAX INVOICE", helveticaBold12);
570
		} else {
571
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
572
		}
573
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
574
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
575
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
576
 
8016 rajveer 577
		Paragraph sorlAddress = new Paragraph(ourAddress + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
7014 rajveer 578
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
579
		sorlAddressCell.addElement(sorlAddress);
580
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
581
 
582
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
583
		PdfPTable orderDetails = getOrderDetails(order, provider);
584
 
585
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
586
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
587
		addrAndOrderDetailsTable.addCell(customerAddress);
588
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
589
		addrAndOrderDetailsTable.addCell(orderDetails);
590
 
591
		boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
592
		PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
593
 
594
		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));
595
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
596
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
7318 rajveer 597
 
598
		//taxTable.addCell(logoTable);
7014 rajveer 599
		taxTable.addCell(retailInvoiceTitleCell);
600
		taxTable.addCell(sorlAddress);
601
		taxTable.addCell(addrAndOrderDetailsTable);
602
		taxTable.addCell(invoiceTable);
603
		taxTable.addCell(disclaimerCell);
604
 
605
		return taxTable;
606
	}
607
 
608
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
609
		PdfPTable customerTable = new PdfPTable(1);
610
		customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
611
		if(forInvoce || order.getPickupStoreId() == 0){
612
			customerTable.addCell(new Phrase(order.getCustomer_name(), font));
613
			customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
614
			customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
615
			customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
7994 manish.sha 616
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
617
			if(order.getLogistics_provider_id()!=7L){
618
				if(destCode != null)
619
					customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
620
				else
621
					customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
622
				}
623
			else{
624
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
625
				String fedexLocationcode = "";
626
				try {
627
					fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
628
				} catch (TException e1) {
629
					logger.error("Error while getting the provider information.", e1);
630
				}
631
				customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
632
			}
633
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 634
			customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
635
		}else{
636
			try {
5556 rajveer 637
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 638
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
639
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
640
				customerTable.addCell(new Phrase(store.getLine1(), font));
641
				customerTable.addCell(new Phrase(store.getLine2(), font));
642
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
643
				if(destCode != null)
644
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
645
				else
646
					customerTable.addCell(new Phrase(store.getPin(), font));
647
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 648
			} catch (TException e) {
649
				// TODO Auto-generated catch block
650
				e.printStackTrace();
651
			}
5527 anupam.sin 652
 
7014 rajveer 653
		}
654
 
655
		if(order.getOrderType().equals(OrderType.B2B)) {
656
			String tin = null;
657
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
658
			List<Attribute> attributes;
659
			try {
660
				attributes = tclient.getAllAttributesForOrderId(order.getId());
661
 
662
				for(Attribute attribute : attributes) {
663
					if(attribute.getName().equals("tinNumber")) {
664
						tin = attribute.getValue();
665
					}
666
				}
667
				if (tin != null) {
668
					customerTable.addCell(new Phrase("TIN :" + tin, font));
669
				}
670
 
671
			} catch (Exception e) {
672
				logger.error("Error while getting order attributes", e);
673
			}
674
		}
675
		/*
2787 chandransh 676
        if(showPaymentMode){
677
            customerTable.addCell(new Phrase(" ", font));
678
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 679
        }*/
7014 rajveer 680
		return customerTable;
681
	}
2787 chandransh 682
 
7014 rajveer 683
	private PdfPTable getOrderDetails(Order order, Provider provider){
684
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
685
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 686
 
7014 rajveer 687
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
688
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 689
 
7014 rajveer 690
		orderTable.addCell(new Phrase("Date:", helvetica8));
691
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 692
 
7014 rajveer 693
		orderTable.addCell(new Phrase("Order ID:", helvetica8));
694
		orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
2787 chandransh 695
 
7528 rajveer 696
		if(order.getSource() == OrderSource.AMAZON.getValue()){
697
			AmazonOrder aorder = null;
698
			try {
699
				aorder = tsc.getClient().getAmazonOrder(order.getId());
700
			} catch (TException e) {
701
				logger.error("Error while getting amazon order", e);
702
			}
703
			orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
704
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
705
		}
706
 
7014 rajveer 707
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
708
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
2787 chandransh 709
 
7014 rajveer 710
		orderTable.addCell(new Phrase("Courier:", helvetica8));
711
		orderTable.addCell(new Phrase(provider.getName(), helvetica8));
2787 chandransh 712
 
7014 rajveer 713
		orderTable.addCell(new Phrase("AWB No:", helvetica8));
714
		orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
2787 chandransh 715
 
7014 rajveer 716
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
717
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 718
 
7014 rajveer 719
		return orderTable;
720
	}
2787 chandransh 721
 
7014 rajveer 722
	private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
723
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
724
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 725
 
7014 rajveer 726
		invoiceTable.addCell(getInvoiceTableHeader(5));
4262 rajveer 727
 
7014 rajveer 728
		invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
729
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
730
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
731
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
732
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
733
		LineItem lineItem = order.getLineitems().get(0);
734
		double orderAmount = order.getTotal_amount();
735
		double rate = lineItem.getVatRate();
7057 amar.kumar 736
		double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
6750 rajveer 737
 
7014 rajveer 738
		populateBottomInvoiceTable(order, invoiceTable, rate);
6750 rajveer 739
 
7014 rajveer 740
		PdfPCell salesTaxCell = getPriceCell(salesTax);
741
 
742
		invoiceTable.addCell(getVATLabelCell(isVAT));
743
		invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
744
		invoiceTable.addCell(salesTaxCell);
745
 
746
		if(order.getInsurer() > 0) {
747
			invoiceTable.addCell(getInsuranceCell(3));
748
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
749
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
750
		}
751
 
752
		invoiceTable.addCell(getEmptyCell(5));
753
 
754
		invoiceTable.addCell(getTotalCell(3));
755
		invoiceTable.addCell(getRupeesCell());
756
		invoiceTable.addCell(getTotalAmountCell(orderAmount));
757
 
758
		invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
759
		invoiceTable.addCell(getAmountInWordsCell(orderAmount));
760
 
761
		invoiceTable.addCell(getEOECell(5));
762
 
763
		return invoiceTable;
764
	}
765
 
766
	private PdfPCell getInvoiceTableHeader(int colspan) {
767
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
768
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
769
		invoiceTableHeader.setColspan(colspan);
770
		invoiceTableHeader.setPaddingTop(10);
771
		return invoiceTableHeader;
772
	}
773
 
774
	private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
775
		for (LineItem lineitem : order.getLineitems()) {
776
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
777
 
7190 amar.kumar 778
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 779
 
780
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
781
 
782
			double itemPrice = lineitem.getUnit_price();
783
			double showPrice = (100 * itemPrice)/(100 + rate);
784
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
785
 
786
			double totalPrice = lineitem.getTotal_price();
787
			showPrice = (100 * totalPrice)/(100 + rate);
788
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
789
		}
790
	}
791
 
7190 amar.kumar 792
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 793
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 794
		if(freebieItemId!=null && freebieItemId!=0){
795
			try {
796
				CatalogService.Client catalogClient = ctsc.getClient();
797
				Item item = catalogClient.getItem(freebieItemId);
798
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
799
			} catch(Exception tex) {
800
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
801
			}
802
		}
7014 rajveer 803
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
804
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
805
		return productNameCell;
806
	}
807
 
808
	private PdfPCell getPriceCell(double price) {
809
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
810
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
811
		return totalPriceCell;
812
	}
813
 
814
	private PdfPCell getVATLabelCell(boolean isVAT) {
815
		PdfPCell vatCell = null;
816
		if(isVAT){
817
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
818
		} else {
819
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
820
		}
821
		vatCell.setColspan(3);
822
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
823
		return vatCell;
824
	}
825
 
7318 rajveer 826
	private PdfPCell getAdvanceAmountCell(int colspan) {
827
		PdfPCell insuranceCell = null;
828
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
829
		insuranceCell.setColspan(colspan);
830
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
831
		return insuranceCell;
832
	}
833
 
7014 rajveer 834
	private PdfPCell getInsuranceCell(int colspan) {
835
		PdfPCell insuranceCell = null;
836
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance", helvetica8));
837
		insuranceCell.setColspan(colspan);
838
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
839
		return insuranceCell;
840
	}
841
 
842
	private PdfPCell getEmptyCell(int colspan) {
843
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
844
		emptyCell.setColspan(colspan);
845
		return emptyCell;
846
	}
847
 
848
	private PdfPCell getTotalCell(int colspan) {
849
		PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
850
		totalCell.setColspan(colspan);
851
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
852
		return totalCell;
853
	}
854
 
855
	private PdfPCell getRupeesCell() {
856
		PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
857
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
858
		return rupeesCell;
859
	}
860
 
861
	private PdfPCell getTotalAmountCell(double orderAmount) {
862
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
863
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
864
		return totalAmountCell;
865
	}
866
 
867
	/**
868
	 * This method uses ICU4J libraries to convert the given amount into words
869
	 * of Indian locale.
870
	 * 
871
	 * @param orderAmount
872
	 *            The amount to convert.
873
	 * @return the string representation of the given amount.
874
	 */
875
	private PdfPCell getAmountInWordsCell(double orderAmount) {
876
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
877
		StringBuilder amountInWords = new StringBuilder("Rs. ");
878
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
879
		amountInWords.append(" and ");
880
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
881
		amountInWords.append(" paise");
882
 
883
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
884
		amountInWordsCell.setColspan(4);
885
		return amountInWordsCell;
886
	}
887
 
888
	/**
889
	 * Returns the item name to be displayed in the invoice table.
890
	 * 
891
	 * @param lineitem
892
	 *            The line item whose name has to be displayed
893
	 * @param appendIMEI
894
	 *            Whether to attach the IMEI No. to the item name
895
	 * @return The name to be displayed for the given line item.
896
	 */
897
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
898
		StringBuffer itemName = new StringBuffer();
899
		if(lineitem.getBrand()!= null)
900
			itemName.append(lineitem.getBrand() + " ");
901
		if(lineitem.getModel_name() != null)
902
			itemName.append(lineitem.getModel_name() + " ");
903
		if(lineitem.getModel_number() != null )
904
			itemName.append(lineitem.getModel_number() + " ");
905
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
906
			itemName.append("("+lineitem.getColor()+")");
907
		if(appendIMEI && lineitem.isSetSerial_number()){
908
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
909
		}
910
 
911
		return itemName.toString();
912
	}
913
 
914
	/**
915
	 * 
916
	 * @param colspan
917
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
918
	 *         no. of columns
919
	 */
920
	private PdfPCell getEOECell(int colspan) {
921
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
922
		eoeCell.setColspan(colspan);
923
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
924
		return eoeCell;
925
	}
926
 
927
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
928
		PdfPTable extraInfoTable = new PdfPTable(1);
929
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
930
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
931
 
932
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
933
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
934
		ttfFontFactory.register(fontPath, "barcode");
935
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
936
 
937
		PdfPCell extraInfoCell;
938
		if(billingType == BillingType.EXTERNAL){
939
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
940
		}else{
941
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
942
		}
943
 
944
		extraInfoCell.setPaddingTop(20.0f);
945
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
946
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
947
 
948
		extraInfoTable.addCell(extraInfoCell);
949
 
950
 
951
		return extraInfoTable;
952
	}
953
 
954
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
955
		PdfPTable extraInfoTable = new PdfPTable(1);
956
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
957
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
958
 
959
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
960
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
961
		ttfFontFactory.register(fontPath, "barcode");
962
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
963
 
964
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
965
 
966
		extraInfoCell.setPaddingTop(20.0f);
967
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
968
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
969
 
970
		extraInfoTable.addCell(extraInfoCell);
971
 
972
		return extraInfoTable;
973
	}
974
 
975
	public static void main(String[] args) throws IOException {
976
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 977
		long orderId = 356324;
978
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 979
		String userHome = System.getProperty("user.home");
980
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
981
		FileOutputStream fos = new FileOutputStream(f);
982
		baos.writeTo(fos);
983
		System.out.println("Invoice generated.");
984
	}
2787 chandransh 985
}