Subversion Repositories SmartDukaan

Rev

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

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