Subversion Repositories SmartDukaan

Rev

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