Subversion Repositories SmartDukaan

Rev

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