Subversion Repositories SmartDukaan

Rev

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