Subversion Repositories SmartDukaan

Rev

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