Subversion Repositories SmartDukaan

Rev

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