Subversion Repositories SmartDukaan

Rev

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

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