Subversion Repositories SmartDukaan

Rev

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