Subversion Repositories SmartDukaan

Rev

Rev 8096 | Rev 8098 | 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
 
8097 manish.sha 271
		PdfPTable logoTable = addLogoTable(order); 
7318 rajveer 272
 
7014 rajveer 273
		PdfPCell titleCell = getTitleCell();
274
		PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false);
8039 manish.sha 275
		PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont);
2787 chandransh 276
 
7014 rajveer 277
		PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
278
		dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
279
		dispatchTable.addCell(customerTable);
280
		dispatchTable.addCell(new Phrase(" "));
281
		dispatchTable.addCell(providerInfoTable);
2787 chandransh 282
 
7014 rajveer 283
		PdfPTable invoiceTable = getTopInvoiceTable(order, shippingLocation.getTinNumber());
284
		PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
8015 rajveer 285
				"\nPIN " + shippingLocation.getPincode() + "\n\n");
2787 chandransh 286
 
7014 rajveer 287
		PdfPTable chargesTable = new PdfPTable(1);
288
		chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
289
		chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
290
		if(order.isLogisticsCod()){
7318 rajveer 291
			chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()), helveticaBold12));
7014 rajveer 292
			chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
7994 manish.sha 293
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
294
			if(order.getLogistics_provider_id()==7L){
295
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
296
				String fedexCodReturnBarcode = "";
8080 manish.sha 297
				String fedexCodReturnTrackingId = "";
7994 manish.sha 298
				try {
299
					fedexCodReturnBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_BarCode");
8080 manish.sha 300
					fedexCodReturnTrackingId = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_Tracking_No");
7994 manish.sha 301
				} catch (TException e1) {
302
					logger.error("Error while getting the provider information.", e1);
303
				}
8080 manish.sha 304
				PdfPCell formIdCell= new PdfPCell(new Paragraph("COD Return "+fedexCodReturnTrackingId+" Form id-0325", helvetica6));
7994 manish.sha 305
				formIdCell.setPaddingTop(5.0f);
306
				formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
307
				formIdCell.setBorder(Rectangle.NO_BORDER);
308
				chargesTable.addCell(new Phrase("PRIORITY OVERNIGHT ", helvetica8));
309
				chargesTable.addCell(formIdCell);
8035 manish.sha 310
 
8067 manish.sha 311
				generateBarcode(fedexCodReturnBarcode, "fedex_codr_"+order.getId());
8037 manish.sha 312
 
8067 manish.sha 313
				Image barcodeImage=null;
314
				try {
315
					barcodeImage = Image.getInstance("/tmp/"+"fedex_codr_"+order.getId()+".png");
316
				} catch (Exception e) {
317
					logger.error("Exception during getting Barcode Image for Fedex : ", e);
318
				}
8072 manish.sha 319
				PdfPTable codReturnTable = new PdfPTable(new float[]{0.6f,0.4f});
320
				codReturnTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
321
				codReturnTable.addCell(barcodeImage);
322
				codReturnTable.addCell(new Phrase(" "));
323
				chargesTable.addCell(codReturnTable);
8067 manish.sha 324
 
7994 manish.sha 325
			}
326
			//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 327
		} else {
328
			chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
329
		}
8080 manish.sha 330
 
331
		if(order.getLogistics_provider_id()==7L){
332
			chargesTable.addCell(new Phrase("Term and Condition:- Subject to the Conditions of Carriage which " +
333
					"limits the liability of FedEx for loss, delay or damage to the consignment." +
334
					" Visit http://www.fedex.com/in/domestic/services/terms to view the conitions of Carriage" ,
8082 manish.sha 335
					new Font(FontFamily.TIMES_ROMAN, 8f)));
8080 manish.sha 336
		}
2787 chandransh 337
 
7014 rajveer 338
		PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
339
		addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
340
		addressAndNoteTable.addCell(addressCell);
341
		addressAndNoteTable.addCell(chargesTable);
2787 chandransh 342
 
7014 rajveer 343
		table.addCell(logoTable);
344
		table.addCell(titleCell);
345
		table.addCell(dispatchTable);
346
		table.addCell(invoiceTable);
347
		table.addCell(new Phrase("If undelivered, return to:", helvetica10));
348
		table.addCell(addressAndNoteTable);
349
		return table;
350
	}
2787 chandransh 351
 
8097 manish.sha 352
	private PdfPTable addLogoTable(Order order) {
353
		PdfPTable logoTable = new PdfPTable(2);
7318 rajveer 354
		logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
355
		logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
356
		logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
8096 manish.sha 357
 
7318 rajveer 358
		PdfPCell logoCell;
359
		String logoPath;
8092 manish.sha 360
		logger.info("Order Source Value........."+order.getSource());
7556 rajveer 361
		if(order.getSource() == OrderSource.STORE.getValue()){
362
			logoCell = new PdfPCell(new Phrase(""));
363
 
364
		}else{
7318 rajveer 365
			logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
8092 manish.sha 366
			logger.info("Logo Path........."+logoPath);
8094 manish.sha 367
 
7318 rajveer 368
			try {
369
				logoCell = new PdfPCell(Image.getInstance(logoPath), false);
370
			} catch (Exception e) {
371
				//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
372
				logger.warn("Couldn't load the Saholic logo: ", e);
373
				logoCell = new PdfPCell(new Phrase("Saholic Logo"));
374
			}
375
 
376
		}
8090 manish.sha 377
		logoCell.setBorder(Rectangle.NO_BORDER);
378
		logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
379
 
380
		logoTable.addCell(logoCell);
8097 manish.sha 381
		return logoTable;
7318 rajveer 382
	}
383
 
7014 rajveer 384
	private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
385
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
386
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
387
		ttfFontFactory.register(fontPath, "barcode");
388
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
389
		return barCodeFont;
390
	}
2787 chandransh 391
 
7014 rajveer 392
	private PdfPCell getTitleCell() {
393
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
394
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
395
		titleCell.setBorder(Rectangle.NO_BORDER);
396
		return titleCell;
397
	}
2787 chandransh 398
 
8039 manish.sha 399
	private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
7014 rajveer 400
		PdfPTable providerInfoTable = new PdfPTable(1);
401
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7318 rajveer 402
		if(order.isLogisticsCod()){
403
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica28));
404
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
405
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
406
			providerInfoTable.addCell(deliveryTypeCell);
407
		}
408
 
8035 manish.sha 409
 
7014 rajveer 410
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
411
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
412
		providerNameCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 413
		PdfPCell formIdCell= null;
414
		if(order.getLogistics_provider_id()==7L){
415
			if(order.isCod()){
8034 manish.sha 416
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
7994 manish.sha 417
			}
418
			else{
8034 manish.sha 419
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
7994 manish.sha 420
			}
8015 rajveer 421
			formIdCell.setPaddingTop(20.0f);
422
			formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
423
			formIdCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 424
		}
8015 rajveer 425
 
7994 manish.sha 426
 
427
		PdfPCell awbNumberCell= null;
8034 manish.sha 428
		String fedexPackageBarcode = "";
7994 manish.sha 429
		if(order.getLogistics_provider_id()!=7L){
430
			awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
8017 manish.sha 431
			awbNumberCell.setPaddingTop(20.0f);
7994 manish.sha 432
		}
433
		else{
8013 rajveer 434
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
435
			try {
436
				fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
437
			} catch (TException e1) {
438
				logger.error("Error while getting the provider information.", e1);
439
			}
8067 manish.sha 440
			awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
8017 manish.sha 441
			awbNumberCell.setPaddingBottom(5.0f);
7994 manish.sha 442
		}
7014 rajveer 443
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
444
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
445
 
446
		providerInfoTable.addCell(providerNameCell);
8015 rajveer 447
		if(formIdCell != null){
448
			providerInfoTable.addCell(formIdCell);
449
		}
7994 manish.sha 450
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
8067 manish.sha 451
		if(order.getLogistics_provider_id()==7L){
452
			generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
453
 
454
			Image barcodeImage=null;
455
			try {
456
				barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
457
			} catch (Exception e) {
458
				logger.error("Exception during getting Barcode Image for Fedex : ", e);
459
			}
460
			providerInfoTable.addCell(barcodeImage);
461
		}
7014 rajveer 462
		providerInfoTable.addCell(awbNumberCell);
7792 anupam.sin 463
		Warehouse warehouse = null;
464
		try{
465
    		InventoryClient isc = new InventoryClient();
7804 amar.kumar 466
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
7803 amar.kumar 467
		} catch(Exception e) {
7792 anupam.sin 468
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
7805 amar.kumar 469
		    //TODO throw e;
7792 anupam.sin 470
		}
471
		DeliveryType dt =  DeliveryType.PREPAID;
472
        if (order.isLogisticsCod()) {
473
            dt = DeliveryType.COD;
474
        }
7994 manish.sha 475
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
476
        if(order.getLogistics_provider_id()!=7L){
477
	        for (ProviderDetails detail : provider.getDetails()) {
478
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
479
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
480
	            }
481
	        }
7792 anupam.sin 482
        }
7994 manish.sha 483
        else{
484
        	providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
485
        }
486
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 487
		Date awbDate;
488
		if(order.getBilling_timestamp() == 0){
489
			awbDate = new Date();
490
		}else{
491
			awbDate = new Date(order.getBilling_timestamp());
492
		}
493
		providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
494
		providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
7994 manish.sha 495
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
496
		if(order.getLogistics_provider_id()==7L){
497
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
498
		}
499
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 500
		return providerInfoTable;
501
	}
502
 
503
	private PdfPTable getTopInvoiceTable(Order order, String tinNo){
504
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
505
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
506
 
507
		invoiceTable.addCell(getInvoiceTableHeader(6));
508
 
509
		invoiceTable.addCell(new Phrase("Order No", helvetica8));
510
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
511
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
512
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
513
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
514
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
515
		populateTopInvoiceTable(order, invoiceTable);
516
 
517
 
518
		if(order.getInsurer() > 0) {
519
			invoiceTable.addCell(getInsuranceCell(4));
520
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
521
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
522
		}
523
 
7318 rajveer 524
		if(order.getSource() == OrderSource.STORE.getValue()) {
525
			invoiceTable.addCell(getAdvanceAmountCell(4));
526
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
527
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
528
		}
529
 
7014 rajveer 530
		invoiceTable.addCell(getTotalCell(4));      
531
		invoiceTable.addCell(getRupeesCell());
7318 rajveer 532
		invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
7014 rajveer 533
 
534
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
535
		tinCell.setColspan(6);
536
		tinCell.setPadding(2);
537
		invoiceTable.addCell(tinCell);
538
 
539
		return invoiceTable;
540
	}
541
 
542
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
543
		List<LineItem> lineitems = order.getLineitems();
544
		for (LineItem lineitem : lineitems) {
545
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
546
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
547
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
548
			else if (order.isCod())
549
				invoiceTable.addCell(new Phrase("COD", helvetica8));
550
			else
551
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 552
 
7190 amar.kumar 553
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 554
 
7014 rajveer 555
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 556
 
7014 rajveer 557
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
558
 
559
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
560
		}
561
	}
562
 
563
	private PdfPCell getAddressCell(String address) {
564
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
565
		PdfPCell addressCell = new PdfPCell();
566
		addressCell.addElement(addressParagraph);
567
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
568
		addressCell.setBorder(Rectangle.NO_BORDER);
569
		return addressCell;
570
	}
571
 
8011 rajveer 572
	private PdfPTable getTaxCumRetailInvoiceTable(Order order, Provider provider, String ourAddress, String tinNo){
7014 rajveer 573
		PdfPTable taxTable = new PdfPTable(1);
574
		Phrase phrase = null;
575
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
576
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
577
 
8097 manish.sha 578
		PdfPTable logoTable = addLogoTable(order);
7318 rajveer 579
 
7014 rajveer 580
		if (order.getOrderType().equals(OrderType.B2B)) {
581
			phrase = new Phrase("TAX INVOICE", helveticaBold12);
582
		} else {
583
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
584
		}
585
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
586
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
587
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
588
 
8016 rajveer 589
		Paragraph sorlAddress = new Paragraph(ourAddress + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
7014 rajveer 590
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
591
		sorlAddressCell.addElement(sorlAddress);
592
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_CENTER);
593
 
594
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
595
		PdfPTable orderDetails = getOrderDetails(order, provider);
596
 
597
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
598
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
599
		addrAndOrderDetailsTable.addCell(customerAddress);
600
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
601
		addrAndOrderDetailsTable.addCell(orderDetails);
602
 
603
		boolean isVAT = order.getCustomer_pincode().startsWith(delhiPincodePrefix);
604
		PdfPTable invoiceTable = getBottomInvoiceTable(order, isVAT);
605
 
606
		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));
607
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
608
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
7318 rajveer 609
 
8096 manish.sha 610
		taxTable.addCell(logoTable);
7014 rajveer 611
		taxTable.addCell(retailInvoiceTitleCell);
612
		taxTable.addCell(sorlAddress);
613
		taxTable.addCell(addrAndOrderDetailsTable);
614
		taxTable.addCell(invoiceTable);
615
		taxTable.addCell(disclaimerCell);
616
 
617
		return taxTable;
618
	}
619
 
620
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
621
		PdfPTable customerTable = new PdfPTable(1);
622
		customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
623
		if(forInvoce || order.getPickupStoreId() == 0){
624
			customerTable.addCell(new Phrase(order.getCustomer_name(), font));
625
			customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
626
			customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
627
			customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
7994 manish.sha 628
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
629
			if(order.getLogistics_provider_id()!=7L){
630
				if(destCode != null)
631
					customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
632
				else
633
					customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
634
				}
635
			else{
636
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
637
				String fedexLocationcode = "";
638
				try {
639
					fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
640
				} catch (TException e1) {
641
					logger.error("Error while getting the provider information.", e1);
642
				}
643
				customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
644
			}
645
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 646
			customerTable.addCell(new Phrase("Phone :" + order.getCustomer_mobilenumber(), font));
647
		}else{
648
			try {
5556 rajveer 649
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 650
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
651
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
652
				customerTable.addCell(new Phrase(store.getLine1(), font));
653
				customerTable.addCell(new Phrase(store.getLine2(), font));
654
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
655
				if(destCode != null)
656
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
657
				else
658
					customerTable.addCell(new Phrase(store.getPin(), font));
659
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 660
			} catch (TException e) {
661
				// TODO Auto-generated catch block
662
				e.printStackTrace();
663
			}
5527 anupam.sin 664
 
7014 rajveer 665
		}
666
 
667
		if(order.getOrderType().equals(OrderType.B2B)) {
668
			String tin = null;
669
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
670
			List<Attribute> attributes;
671
			try {
672
				attributes = tclient.getAllAttributesForOrderId(order.getId());
673
 
674
				for(Attribute attribute : attributes) {
675
					if(attribute.getName().equals("tinNumber")) {
676
						tin = attribute.getValue();
677
					}
678
				}
679
				if (tin != null) {
680
					customerTable.addCell(new Phrase("TIN :" + tin, font));
681
				}
682
 
683
			} catch (Exception e) {
684
				logger.error("Error while getting order attributes", e);
685
			}
686
		}
687
		/*
2787 chandransh 688
        if(showPaymentMode){
689
            customerTable.addCell(new Phrase(" ", font));
690
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 691
        }*/
7014 rajveer 692
		return customerTable;
693
	}
2787 chandransh 694
 
7014 rajveer 695
	private PdfPTable getOrderDetails(Order order, Provider provider){
696
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
697
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 698
 
7014 rajveer 699
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
700
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 701
 
7014 rajveer 702
		orderTable.addCell(new Phrase("Date:", helvetica8));
703
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 704
 
7014 rajveer 705
		orderTable.addCell(new Phrase("Order ID:", helvetica8));
706
		orderTable.addCell(new Phrase("" + order.getId(), helvetica8));
2787 chandransh 707
 
7528 rajveer 708
		if(order.getSource() == OrderSource.AMAZON.getValue()){
709
			AmazonOrder aorder = null;
710
			try {
711
				aorder = tsc.getClient().getAmazonOrder(order.getId());
712
			} catch (TException e) {
713
				logger.error("Error while getting amazon order", e);
714
			}
715
			orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
716
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
717
		}
718
 
7014 rajveer 719
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
720
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
2787 chandransh 721
 
7014 rajveer 722
		orderTable.addCell(new Phrase("Courier:", helvetica8));
723
		orderTable.addCell(new Phrase(provider.getName(), helvetica8));
2787 chandransh 724
 
7014 rajveer 725
		orderTable.addCell(new Phrase("AWB No:", helvetica8));
726
		orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
2787 chandransh 727
 
7014 rajveer 728
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
729
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 730
 
7014 rajveer 731
		return orderTable;
732
	}
2787 chandransh 733
 
7014 rajveer 734
	private PdfPTable getBottomInvoiceTable(Order order, boolean isVAT){
735
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.5f, 0.1f, 0.1f, 0.1f});
736
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 737
 
7014 rajveer 738
		invoiceTable.addCell(getInvoiceTableHeader(5));
4262 rajveer 739
 
7014 rajveer 740
		invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
741
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
742
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
743
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
744
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
745
		LineItem lineItem = order.getLineitems().get(0);
746
		double orderAmount = order.getTotal_amount();
747
		double rate = lineItem.getVatRate();
7057 amar.kumar 748
		double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
6750 rajveer 749
 
7014 rajveer 750
		populateBottomInvoiceTable(order, invoiceTable, rate);
6750 rajveer 751
 
7014 rajveer 752
		PdfPCell salesTaxCell = getPriceCell(salesTax);
753
 
754
		invoiceTable.addCell(getVATLabelCell(isVAT));
755
		invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
756
		invoiceTable.addCell(salesTaxCell);
757
 
758
		if(order.getInsurer() > 0) {
759
			invoiceTable.addCell(getInsuranceCell(3));
760
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
761
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
762
		}
763
 
764
		invoiceTable.addCell(getEmptyCell(5));
765
 
766
		invoiceTable.addCell(getTotalCell(3));
767
		invoiceTable.addCell(getRupeesCell());
768
		invoiceTable.addCell(getTotalAmountCell(orderAmount));
769
 
770
		invoiceTable.addCell(new Phrase("Amount in Words:", helvetica8));
771
		invoiceTable.addCell(getAmountInWordsCell(orderAmount));
772
 
773
		invoiceTable.addCell(getEOECell(5));
774
 
775
		return invoiceTable;
776
	}
777
 
778
	private PdfPCell getInvoiceTableHeader(int colspan) {
779
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
780
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
781
		invoiceTableHeader.setColspan(colspan);
782
		invoiceTableHeader.setPaddingTop(10);
783
		return invoiceTableHeader;
784
	}
785
 
786
	private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
787
		for (LineItem lineitem : order.getLineitems()) {
788
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
789
 
7190 amar.kumar 790
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 791
 
792
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
793
 
794
			double itemPrice = lineitem.getUnit_price();
795
			double showPrice = (100 * itemPrice)/(100 + rate);
796
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
797
 
798
			double totalPrice = lineitem.getTotal_price();
799
			showPrice = (100 * totalPrice)/(100 + rate);
800
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
801
		}
802
	}
803
 
7190 amar.kumar 804
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 805
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 806
		if(freebieItemId!=null && freebieItemId!=0){
807
			try {
808
				CatalogService.Client catalogClient = ctsc.getClient();
809
				Item item = catalogClient.getItem(freebieItemId);
810
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
811
			} catch(Exception tex) {
812
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
813
			}
814
		}
7014 rajveer 815
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
816
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
817
		return productNameCell;
818
	}
819
 
820
	private PdfPCell getPriceCell(double price) {
821
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
822
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
823
		return totalPriceCell;
824
	}
825
 
826
	private PdfPCell getVATLabelCell(boolean isVAT) {
827
		PdfPCell vatCell = null;
828
		if(isVAT){
829
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
830
		} else {
831
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
832
		}
833
		vatCell.setColspan(3);
834
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
835
		return vatCell;
836
	}
837
 
7318 rajveer 838
	private PdfPCell getAdvanceAmountCell(int colspan) {
839
		PdfPCell insuranceCell = null;
840
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
841
		insuranceCell.setColspan(colspan);
842
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
843
		return insuranceCell;
844
	}
845
 
7014 rajveer 846
	private PdfPCell getInsuranceCell(int colspan) {
847
		PdfPCell insuranceCell = null;
848
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance", helvetica8));
849
		insuranceCell.setColspan(colspan);
850
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
851
		return insuranceCell;
852
	}
853
 
854
	private PdfPCell getEmptyCell(int colspan) {
855
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
856
		emptyCell.setColspan(colspan);
857
		return emptyCell;
858
	}
859
 
860
	private PdfPCell getTotalCell(int colspan) {
861
		PdfPCell totalCell = new PdfPCell(new Phrase("Total", helveticaBold8));
862
		totalCell.setColspan(colspan);
863
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
864
		return totalCell;
865
	}
866
 
867
	private PdfPCell getRupeesCell() {
868
		PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
869
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
870
		return rupeesCell;
871
	}
872
 
873
	private PdfPCell getTotalAmountCell(double orderAmount) {
874
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
875
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
876
		return totalAmountCell;
877
	}
878
 
879
	/**
880
	 * This method uses ICU4J libraries to convert the given amount into words
881
	 * of Indian locale.
882
	 * 
883
	 * @param orderAmount
884
	 *            The amount to convert.
885
	 * @return the string representation of the given amount.
886
	 */
887
	private PdfPCell getAmountInWordsCell(double orderAmount) {
888
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
889
		StringBuilder amountInWords = new StringBuilder("Rs. ");
890
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
891
		amountInWords.append(" and ");
892
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
893
		amountInWords.append(" paise");
894
 
895
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
896
		amountInWordsCell.setColspan(4);
897
		return amountInWordsCell;
898
	}
899
 
900
	/**
901
	 * Returns the item name to be displayed in the invoice table.
902
	 * 
903
	 * @param lineitem
904
	 *            The line item whose name has to be displayed
905
	 * @param appendIMEI
906
	 *            Whether to attach the IMEI No. to the item name
907
	 * @return The name to be displayed for the given line item.
908
	 */
909
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
910
		StringBuffer itemName = new StringBuffer();
911
		if(lineitem.getBrand()!= null)
912
			itemName.append(lineitem.getBrand() + " ");
913
		if(lineitem.getModel_name() != null)
914
			itemName.append(lineitem.getModel_name() + " ");
915
		if(lineitem.getModel_number() != null )
916
			itemName.append(lineitem.getModel_number() + " ");
917
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
918
			itemName.append("("+lineitem.getColor()+")");
919
		if(appendIMEI && lineitem.isSetSerial_number()){
920
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
921
		}
922
 
923
		return itemName.toString();
924
	}
925
 
926
	/**
927
	 * 
928
	 * @param colspan
929
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
930
	 *         no. of columns
931
	 */
932
	private PdfPCell getEOECell(int colspan) {
933
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
934
		eoeCell.setColspan(colspan);
935
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
936
		return eoeCell;
937
	}
938
 
939
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
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;
950
		if(billingType == BillingType.EXTERNAL){
951
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
952
		}else{
953
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
954
		}
955
 
956
		extraInfoCell.setPaddingTop(20.0f);
957
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
958
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
959
 
960
		extraInfoTable.addCell(extraInfoCell);
961
 
962
 
963
		return extraInfoTable;
964
	}
965
 
966
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
967
		PdfPTable extraInfoTable = new PdfPTable(1);
968
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
969
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
970
 
971
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
972
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
973
		ttfFontFactory.register(fontPath, "barcode");
974
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
975
 
976
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
977
 
978
		extraInfoCell.setPaddingTop(20.0f);
979
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
980
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
981
 
982
		extraInfoTable.addCell(extraInfoCell);
983
 
984
		return extraInfoTable;
985
	}
8067 manish.sha 986
 
987
	private void generateBarcode(String barcodeString, String fileName){
988
		Code128Bean bean = new Code128Bean();
7014 rajveer 989
 
8067 manish.sha 990
		final int dpi = 60;
991
 
992
		//Configure the barcode generator
993
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
994
		                                                 //width exactly one pixel
995
		bean.setFontSize(bean.getFontSize()+1.0f);
996
		bean.doQuietZone(false);
997
 
998
		try {
999
			File outputFile = new File("/tmp/"+fileName+".png");
1000
			OutputStream out = new FileOutputStream(outputFile);
1001
 
1002
		    //Set up the canvas provider for monochrome PNG output 
1003
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
1004
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
1005
 
1006
		    //Generate the barcode
1007
		    bean.generateBarcode(canvas, barcodeString);
1008
 
1009
		    //Signal end of generation
1010
		    canvas.finish();
1011
		    out.close();
1012
 
1013
		} 
1014
		catch(Exception e){
1015
			logger.error("Exception during generating Barcode : ", e);
1016
		}
1017
	}
1018
 
7014 rajveer 1019
	public static void main(String[] args) throws IOException {
1020
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 1021
		long orderId = 356324;
1022
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 1023
		String userHome = System.getProperty("user.home");
1024
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
1025
		FileOutputStream fos = new FileOutputStream(f);
1026
		baos.writeTo(fos);
1027
		System.out.println("Invoice generated.");
1028
	}
2787 chandransh 1029
}