Subversion Repositories SmartDukaan

Rev

Rev 8173 | Rev 8182 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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