Subversion Repositories SmartDukaan

Rev

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