Subversion Repositories SmartDukaan

Rev

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