Subversion Repositories SmartDukaan

Rev

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