Subversion Repositories SmartDukaan

Rev

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