Subversion Repositories SmartDukaan

Rev

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