Subversion Repositories SmartDukaan

Rev

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