Subversion Repositories SmartDukaan

Rev

Rev 8017 | Rev 8035 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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