Subversion Repositories SmartDukaan

Rev

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