Subversion Repositories SmartDukaan

Rev

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