Subversion Repositories SmartDukaan

Rev

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