Subversion Repositories SmartDukaan

Rev

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