Subversion Repositories SmartDukaan

Rev

Rev 13276 | Rev 13283 | 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;
10310 amar.kumar 23
import in.shop2020.model.v1.order.ProductCondition;
8488 amar.kumar 24
import in.shop2020.model.v1.order.SnapdealOrder;
8996 amar.kumar 25
import in.shop2020.model.v1.order.FlipkartOrder;
9432 amar.kumar 26
import in.shop2020.model.v1.order.TaxType;
7190 amar.kumar 27
import in.shop2020.thrift.clients.CatalogClient;
3132 rajveer 28
import in.shop2020.thrift.clients.LogisticsClient;
29
import in.shop2020.thrift.clients.TransactionClient;
2787 chandransh 30
import in.shop2020.thrift.clients.config.ConfigClient;
5948 mandeep.dh 31
import in.shop2020.thrift.clients.InventoryClient;
2787 chandransh 32
 
8067 manish.sha 33
import java.awt.image.BufferedImage;
2787 chandransh 34
import java.io.ByteArrayOutputStream;
35
import java.io.File;
36
import java.io.FileOutputStream;
37
import java.io.IOException;
8067 manish.sha 38
import java.io.OutputStream;
2787 chandransh 39
import java.text.DateFormat;
40
import java.text.DecimalFormat;
4361 rajveer 41
import java.util.ArrayList;
2787 chandransh 42
import java.util.Date;
13276 manish.sha 43
import java.util.HashMap;
2787 chandransh 44
import java.util.List;
45
import java.util.Locale;
13276 manish.sha 46
import java.util.Map;
2787 chandransh 47
 
48
import javax.servlet.ServletException;
49
import javax.servlet.ServletOutputStream;
50
import javax.servlet.http.HttpServlet;
51
import javax.servlet.http.HttpServletRequest;
52
import javax.servlet.http.HttpServletResponse;
53
 
7014 rajveer 54
import org.apache.commons.lang.StringUtils;
2787 chandransh 55
import org.apache.commons.lang.WordUtils;
56
import org.apache.thrift.TException;
8067 manish.sha 57
import org.krysalis.barcode4j.impl.code128.Code128Bean;
58
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
59
import org.krysalis.barcode4j.tools.UnitConv;
2787 chandransh 60
import org.slf4j.Logger;
61
import org.slf4j.LoggerFactory;
62
 
63
import com.ibm.icu.text.RuleBasedNumberFormat;
64
 
65
import com.itextpdf.text.Document;
66
import com.itextpdf.text.Element;
67
import com.itextpdf.text.Font;
68
import com.itextpdf.text.FontFactory;
69
import com.itextpdf.text.FontFactoryImp;
70
import com.itextpdf.text.Image;
71
import com.itextpdf.text.Paragraph;
72
import com.itextpdf.text.Phrase;
73
import com.itextpdf.text.Rectangle;
74
import com.itextpdf.text.Font.FontFamily;
8034 manish.sha 75
import com.itextpdf.text.pdf.Barcode128;
2787 chandransh 76
import com.itextpdf.text.pdf.BaseFont;
8037 manish.sha 77
import com.itextpdf.text.pdf.PdfContentByte;
2787 chandransh 78
import com.itextpdf.text.pdf.PdfPCell;
79
import com.itextpdf.text.pdf.PdfPTable;
80
import com.itextpdf.text.pdf.PdfWriter;
81
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
82
 
83
@SuppressWarnings("serial")
84
public class InvoiceServlet extends HttpServlet {
7014 rajveer 85
 
86
	private static Logger logger = LoggerFactory.getLogger(InvoiceServlet.class);
87
 
88
	@Override
89
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
90
		long orderId = Long.parseLong(request.getParameter("id"));
13276 manish.sha 91
		String logisticsTxnId  = request.getParameter("logisticsTxnId");
7014 rajveer 92
		long warehouseId = Long.parseLong(request.getParameter("warehouse"));
93
		boolean withBill = false;
94
		boolean printAll = false;
95
		try {
96
			withBill = Boolean.parseBoolean(request.getParameter("withBill"));
97
		} catch(Exception e){
98
			logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
99
		}
100
		try {
101
			printAll = Boolean.parseBoolean(request.getParameter("printAll"));
102
		} catch(Exception e){
103
			logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
104
		}
105
 
13276 manish.sha 106
		if(logisticsTxnId!=null && !logisticsTxnId.isEmpty()){
107
			logger.info("Printing invoice for master order id: " + logisticsTxnId);
108
		}else{
109
			logger.info("Printing invoice for order id: " + orderId);
110
		}
8182 amar.kumar 111
 
8194 amar.kumar 112
		ByteArrayOutputStream baos = null;
8182 amar.kumar 113
 
114
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
115
		baos = invoiceGenerationService.generateInvoice(orderId, withBill, printAll, warehouseId);
7014 rajveer 116
 
117
		response.setContentType("application/pdf");
13276 manish.sha 118
		if(logisticsTxnId!=null && !logisticsTxnId.isEmpty()){
119
			response.setHeader("Content-disposition", "inline; filename=invoice-"+logisticsTxnId+".pdf" );
120
		} else {
121
			response.setHeader("Content-disposition", "inline; filename=invoice-"+orderId+".pdf" );
122
		}
7014 rajveer 123
 
124
		ServletOutputStream sos;
125
		try {
126
			sos = response.getOutputStream();
127
			baos.writeTo(sos);
128
			sos.flush();
129
		} catch (IOException e) {
130
			logger.error("Encountered error while sending invoice response: ", e);
131
		}
132
	}
2787 chandransh 133
}
134
 
135
class InvoiceGenerationService {
136
 
7014 rajveer 137
	private static Logger logger = LoggerFactory.getLogger(InvoiceGenerationService.class);
2787 chandransh 138
 
7014 rajveer 139
	private TransactionClient tsc = null;
140
	private InventoryClient csc = null;
141
	private LogisticsClient lsc = null;
7190 amar.kumar 142
	private CatalogClient ctsc = null;
2787 chandransh 143
 
7014 rajveer 144
	private static Locale indianLocale = new Locale("en", "IN");
145
	private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");
2787 chandransh 146
 
7994 manish.sha 147
	//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
148
	private static final Font helvetica6 = FontFactory.getFont(FontFactory.HELVETICA, 6);
7995 manish.sha 149
	//End:-Added By Manish Sharma for FedEx Integration  - Shipment Creation on 21-Aug-2013
7014 rajveer 150
	private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
151
	private static final Font helvetica10 = FontFactory.getFont(FontFactory.HELVETICA, 10);
152
	private static final Font helvetica12 = FontFactory.getFont(FontFactory.HELVETICA, 12);
153
	private static final Font helvetica16 = FontFactory.getFont(FontFactory.HELVETICA, 16);
8551 manish.sha 154
	private static final Font helvetica22 = FontFactory.getFont(FontFactory.HELVETICA, 22);
2787 chandransh 155
 
7014 rajveer 156
	private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
157
	private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);
158
 
159
	private static final String delhiPincodePrefix = "11";
9319 amar.kumar 160
	private static final String[] maharashtraPincodePrefix = {"40", "41", "42", "43", "44"};
12809 manish.sha 161
	private static final String[] telanganaPincodes = {"500001","500002","500003","500004","500005","500006","500007","500008","500009","500010","500011","500012","500013","500014","500015","500016","500017","500018","500019","500020","500021","500022","500023","500024","500025","500026","500027","500028","500029","500030","500031","500032","500033","500034","500035","500036","500037","500038","500039","500040","500041","500042","500043","500044","500045","500046","500047","500048","500049","500050","500051","500052","500053","500054","500055","500056","500057","500058","500059","500060","500061","500062","500063","500064","500065","500066","500067","500068","500069","500070","500071","500072","500073","500074","500075","500076","500077","500078","500079","500080","500081","500082","500083","500084","500085","500086","500087","500088","500089","500090","500091","500092","500093","500094","500095","500096","500097","500098","500178","500409","501218","501301","501401","501510","501511","501512","502307","502319","517501","517502","517503","517505","517507","520001","520002","520003","520004","520005","520006","520007","520008","520009","520010","520011","520012","520013","520014","520015","521108","521225","522001","522002","522003","522004","522005","522006","522007","522019","522509","530001","530002","530003","530004","530005","530007","530008","530009","530010","530010","530011","530012","530013","530014","530015","530016","530017","530018","530020","530021","530022","530023","530024","530026","530027","530028","530029","530032","530035","530040","530041","530043","530044","530045","530046","531001","533101","533103","533104","533105"};
7014 rajveer 162
 
163
	public InvoiceGenerationService() {
164
		try {
165
			tsc = new TransactionClient();
166
			csc = new InventoryClient();
167
			lsc = new LogisticsClient();
7190 amar.kumar 168
			ctsc = new CatalogClient();
7014 rajveer 169
		} catch (Exception e) {
170
			logger.error("Error while instantiating thrift clients.", e);
171
		}
172
	}
173
 
174
	public ByteArrayOutputStream generateInvoice(long orderId, boolean withBill, boolean printAll, long warehouseId) {
175
		ByteArrayOutputStream baosPDF = null;
176
		in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
177
		in.shop2020.model.v1.inventory.InventoryService.Client iclient = csc.getClient();
178
		in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
179
 
180
 
181
		try {
182
			baosPDF = new ByteArrayOutputStream();
183
 
184
			Document document = new Document();
8039 manish.sha 185
			PdfWriter.getInstance(document, baosPDF);
7014 rajveer 186
			document.addAuthor("shop2020");
187
			//document.addTitle("Invoice No: " + order.getInvoice_number());
188
			document.open();
13276 manish.sha 189
			//document.bo
7014 rajveer 190
 
191
			List<Order> orders = new ArrayList<Order>();
13276 manish.sha 192
			Map<String, List<Order>> logisticsTxnIdOrdersMap = new HashMap<String, List<Order>>();
7014 rajveer 193
			if(printAll){
194
				try {
195
					List<OrderStatus> statuses = new ArrayList<OrderStatus>();
196
					statuses.add(OrderStatus.ACCEPTED);
13276 manish.sha 197
					if(!tclient.isAlive()){
198
						tclient = tsc.getClient();
199
					}
7014 rajveer 200
					orders = tclient.getAllOrders(statuses, 0, 0, warehouseId);
13276 manish.sha 201
					for(Order o:orders){
202
						if(o.isSetLogisticsTransactionId()){
203
							if(logisticsTxnIdOrdersMap.containsKey(o.getLogisticsTransactionId())){
204
								List<Order> groupOrdersList = logisticsTxnIdOrdersMap.get(o.getLogisticsTransactionId());
205
								groupOrdersList.add(o);
206
								logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
207
							}else {
208
								List<Order> groupOrdersList = new ArrayList<Order>();
209
								groupOrdersList.add(o);
210
								logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
211
							}
212
						}
213
					}
7014 rajveer 214
				} catch (Exception e) {
215
					logger.error("Error while getting order information", e);
216
					return baosPDF; 
4361 rajveer 217
				}
7014 rajveer 218
			}else{
13276 manish.sha 219
				if(!tclient.isAlive()){
220
					tclient = tsc.getClient();
221
				}
222
				orders.add(tclient.getOrder(orderId));
223
				Order o = orders.get(0);
224
				if(o.isSetLogisticsTransactionId()){
225
					List<Order> groupOrdersList = tclient.getGroupOrdersByLogisticsTxnId(o.getLogisticsTransactionId());
226
					logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
227
				}
7014 rajveer 228
			}
229
			boolean isFirst = true;
13276 manish.sha 230
			if(logisticsTxnIdOrdersMap!=null && logisticsTxnIdOrdersMap.size()>0){
231
				for(String logisticsTxnId : logisticsTxnIdOrdersMap.keySet()){
232
					List<Order> ordersList = logisticsTxnIdOrdersMap.get(logisticsTxnId);
233
					Order singleOrder = ordersList.get(0);
234
					Warehouse warehouse = null;
235
					Provider provider = null;
236
					String destCode = null;
237
					Warehouse shippingLocation = null;
238
					int barcodeFontSize = 0;
239
					String invoiceFormat = null;
240
					try {
241
						warehouse = iclient.getWarehouse(singleOrder.getWarehouse_id());
242
						long providerId = singleOrder.getLogistics_provider_id();
243
						provider = logisticsClient.getProvider(providerId);
244
						if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
245
							destCode = provider.getPickup().toString();
246
						else
247
							destCode = logisticsClient.getDestinationCode(providerId, singleOrder.getCustomer_pincode());
5387 rajveer 248
 
13276 manish.sha 249
						barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
250
						shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId());
251
						invoiceFormat = tclient.getInvoiceFormatLogisticsTxnId(singleOrder.getTransactionId(), Long.parseLong(logisticsTxnId.split("-")[1])); 
252
					} catch (InventoryServiceException ise) {
253
						logger.error("Error while getting the warehouse information.", ise);
254
						return baosPDF;
255
					} catch (LogisticsServiceException lse) {
256
						logger.error("Error while getting the provider information.", lse);
257
						return baosPDF;
258
					} catch (ConfigException ce) {
259
						logger.error("Error while getting the fontsize for the given provider", ce);
260
						return baosPDF;
261
					} catch (TException te) {
262
						logger.error("Error while getting some essential information from the services", te);
263
						return baosPDF;
264
					}
265
 
266
					if(printAll && warehouse.getBillingType() == BillingType.OURS_EXTERNAL){
267
						for(Order order : ordersList){
268
							if(isFirst){
269
								document.add(getFixedTextTable(16, "Spice Online Retail Pvt Ltd"));
270
								isFirst = false;
271
							}
272
							document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
273
							continue;
274
						}
275
					}
276
					PdfPTable dispatchAdviceTable = null;
277
					Order order = ordersList.get(0);
278
					if(ordersList.size()==1){					
279
						if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
280
							dispatchAdviceTable = new PdfPTable(1);
281
						}  else if(new Long(order.getSource()).intValue() == OrderSource.FLIPKART.getValue()) {
282
							dispatchAdviceTable = new PdfPTable(1);
283
						}  else if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7)) {
284
							if(order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
285
								dispatchAdviceTable = new PdfPTable(1);
286
							} else { 
287
								if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty()) {
288
									dispatchAdviceTable = new PdfPTable(1);
289
								} else {
290
									EbayInvoiceGenerationService invoiceGenerationService = new EbayInvoiceGenerationService();
291
									dispatchAdviceTable = invoiceGenerationService.getDispatchAdviceTable(orderId, warehouseId);
292
								}
293
							}
294
						}
295
						else {
296
							dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
297
						}
298
					} else {
299
						dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
300
					}
301
 
302
					dispatchAdviceTable.setSpacingAfter(10.0f);
303
					dispatchAdviceTable.setWidthPercentage(90.0f);
304
					document.add(dispatchAdviceTable);
305
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
306
						document.newPage();
307
					}
308
 
309
					if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7) &&(ordersList.size()==1)) {
310
						if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty() 
311
								|| order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
312
							if(withBill){
313
								PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
314
								taxTable.setSpacingBefore(5.0f);
315
								taxTable.setWidthPercentage(90.0f);
316
								document.add(new DottedLineSeparator());
317
								document.add(taxTable);
318
							}else{
319
								PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
320
								extraInfoTable.setSpacingBefore(5.0f);
321
								extraInfoTable.setWidthPercentage(90.0f);
322
								document.add(new DottedLineSeparator());
323
								document.add(extraInfoTable);
324
							}
325
						} else {
326
							document.newPage();
327
						}
328
					} else if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue() &&(ordersList.size()==1)) {
329
						if(withBill){
330
							PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
331
							taxTable.setSpacingBefore(5.0f);
332
							taxTable.setWidthPercentage(90.0f);
333
							document.add(new DottedLineSeparator());
334
							document.add(taxTable);
335
						}else{
336
							PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
337
							extraInfoTable.setSpacingBefore(5.0f);
338
							extraInfoTable.setWidthPercentage(90.0f);
339
							document.add(new DottedLineSeparator());
340
							document.add(extraInfoTable);
341
						}
342
					}
343
					if(withBill){
344
						PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
345
						taxTable.setSpacingBefore(5.0f);
346
						taxTable.setWidthPercentage(90.0f);
347
						document.add(new DottedLineSeparator());
348
						document.add(taxTable);
349
						if(order.getSource() == OrderSource.FLIPKART.getValue()) {
350
							//document.add(new DottedLineSeparator());
351
							document.add(getFlipkartBarCodes(order));
352
						}
2787 chandransh 353
 
13276 manish.sha 354
					}else{
355
						PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
356
						extraInfoTable.setSpacingBefore(5.0f);
357
						extraInfoTable.setWidthPercentage(90.0f);
358
						document.add(new DottedLineSeparator());
359
						document.add(extraInfoTable);
360
					}
361
					document.newPage();
7014 rajveer 362
				}
13276 manish.sha 363
			} else {
364
				for(Order singleOrder : orders){
365
					List<Order> ordersList = new ArrayList<Order>();
366
					ordersList.add(singleOrder);
367
					Warehouse warehouse = null;
368
					Provider provider = null;
369
					String destCode = null;
370
					Warehouse shippingLocation = null;
371
					int barcodeFontSize = 0;
372
					String invoiceFormat = "Individual";
373
					try {
374
						warehouse = iclient.getWarehouse(singleOrder.getWarehouse_id());
375
						long providerId = singleOrder.getLogistics_provider_id();
376
						provider = logisticsClient.getProvider(providerId);
377
						if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
378
							destCode = provider.getPickup().toString();
379
						else
380
							destCode = logisticsClient.getDestinationCode(providerId, singleOrder.getCustomer_pincode());
4361 rajveer 381
 
13276 manish.sha 382
						barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
383
						shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId()); 
384
					} catch (InventoryServiceException ise) {
385
						logger.error("Error while getting the warehouse information.", ise);
386
						return baosPDF;
387
					} catch (LogisticsServiceException lse) {
388
						logger.error("Error while getting the provider information.", lse);
389
						return baosPDF;
390
					} catch (ConfigException ce) {
391
						logger.error("Error while getting the fontsize for the given provider", ce);
392
						return baosPDF;
393
					} catch (TException te) {
394
						logger.error("Error while getting some essential information from the services", te);
395
						return baosPDF;
7014 rajveer 396
					}
13276 manish.sha 397
 
398
					if(printAll && warehouse.getBillingType() == BillingType.OURS_EXTERNAL){
399
						for(Order order : ordersList){
400
							if(isFirst){
401
								document.add(getFixedTextTable(16, "Spice Online Retail Pvt Ltd"));
402
								isFirst = false;
403
							}
404
							document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
405
							continue;
406
						}
407
					}
408
					PdfPTable dispatchAdviceTable = null;
409
					Order order = ordersList.get(0);
410
					if(ordersList.size()==1){					
411
						if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
8303 amar.kumar 412
							dispatchAdviceTable = new PdfPTable(1);
13276 manish.sha 413
						}  else if(new Long(order.getSource()).intValue() == OrderSource.FLIPKART.getValue()) {
414
							dispatchAdviceTable = new PdfPTable(1);
415
						}  else if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7)) {
416
							if(order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
417
								dispatchAdviceTable = new PdfPTable(1);
418
							} else { 
419
								if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty()) {
420
									dispatchAdviceTable = new PdfPTable(1);
421
								} else {
422
									EbayInvoiceGenerationService invoiceGenerationService = new EbayInvoiceGenerationService();
423
									dispatchAdviceTable = invoiceGenerationService.getDispatchAdviceTable(orderId, warehouseId);
424
								}
425
							}
426
						}
427
						else {
428
							dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
429
						}
430
					} else {
431
						dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
432
					}
433
 
434
					dispatchAdviceTable.setSpacingAfter(10.0f);
435
					dispatchAdviceTable.setWidthPercentage(90.0f);
436
					document.add(dispatchAdviceTable);
437
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
438
						document.newPage();
439
					}
440
 
441
					if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7) &&(ordersList.size()==1)) {
442
						if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty() 
443
								|| order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
444
							if(withBill){
445
								PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
446
								taxTable.setSpacingBefore(5.0f);
447
								taxTable.setWidthPercentage(90.0f);
448
								document.add(new DottedLineSeparator());
449
								document.add(taxTable);
450
							}else{
451
								PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
452
								extraInfoTable.setSpacingBefore(5.0f);
453
								extraInfoTable.setWidthPercentage(90.0f);
454
								document.add(new DottedLineSeparator());
455
								document.add(extraInfoTable);
456
							}
8303 amar.kumar 457
						} else {
13276 manish.sha 458
							document.newPage();
8303 amar.kumar 459
						}
13276 manish.sha 460
					} else if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue() &&(ordersList.size()==1)) {
8303 amar.kumar 461
						if(withBill){
13276 manish.sha 462
							PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
8303 amar.kumar 463
							taxTable.setSpacingBefore(5.0f);
464
							taxTable.setWidthPercentage(90.0f);
465
							document.add(new DottedLineSeparator());
466
							document.add(taxTable);
467
						}else{
468
							PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
469
							extraInfoTable.setSpacingBefore(5.0f);
470
							extraInfoTable.setWidthPercentage(90.0f);
471
							document.add(new DottedLineSeparator());
472
							document.add(extraInfoTable);
473
						}
474
					}
8488 amar.kumar 475
					if(withBill){
13276 manish.sha 476
						PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
8488 amar.kumar 477
						taxTable.setSpacingBefore(5.0f);
478
						taxTable.setWidthPercentage(90.0f);
479
						document.add(new DottedLineSeparator());
480
						document.add(taxTable);
13276 manish.sha 481
						if(order.getSource() == OrderSource.FLIPKART.getValue()) {
482
							//document.add(new DottedLineSeparator());
483
							document.add(getFlipkartBarCodes(order));
484
						}
485
 
8488 amar.kumar 486
					}else{
487
						PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
488
						extraInfoTable.setSpacingBefore(5.0f);
489
						extraInfoTable.setWidthPercentage(90.0f);
490
						document.add(new DottedLineSeparator());
491
						document.add(extraInfoTable);
492
					}
13276 manish.sha 493
 
494
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
495
						PdfPTable orderItemsDetailTable = new PdfPTable(1);
496
						orderItemsDetailTable.setWidthPercentage(90.0f);
497
						orderItemsDetailTable.setSpacingBefore(5.0f);
498
						orderItemsDetailTable.addCell(new Phrase("Order Reference Ids :", helveticaBold8));
499
						StringBuffer sbOrders = new StringBuffer();
500
 
501
						for(Order o1 : orders){
502
							sbOrders.append(o1.getId()+",");
503
						}
504
 
505
 
506
						String orderIds = sbOrders.toString();
507
						orderIds = orderIds.substring(0, orderIds.length()-1);
508
 
509
						orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
510
						orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
511
 
512
						StringBuffer sbImeis = new StringBuffer();
513
 
514
						for(Order o1 : orders){
515
							if(o1.getLineitems().get(0).getSerial_number()!=null){
516
								sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
517
							}
518
						}
519
 
520
						String imeis = sbImeis.toString();
521
						imeis = imeis.substring(0, imeis.length()-1);
522
 
523
						orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
524
 
525
						document.add(new DottedLineSeparator());
526
						document.add(orderItemsDetailTable);
9009 amar.kumar 527
					}
13276 manish.sha 528
					document.newPage();
7014 rajveer 529
				}
530
			}
13276 manish.sha 531
 
532
 
533
 
7014 rajveer 534
			document.close();
535
			baosPDF.close();
536
			// Adding facility to store the bill on the local directory. This will happen for only for Mahipalpur warehouse.
537
			if(withBill && !printAll){
7079 rajveer 538
				String strOrderId = StringUtils.repeat("0", 10-String.valueOf(orderId).length()) + orderId;  
7014 rajveer 539
				String dirPath = "/SaholicInvoices" + File.separator + strOrderId.substring(0, 2) + File.separator + strOrderId.substring(2, 4) + File.separator + strOrderId.substring(4, 6);
540
				String filename = dirPath + File.separator + orderId + ".pdf";
541
				File dirFile = new File(dirPath);
542
				if(!dirFile.exists()){
543
					dirFile.mkdirs();
544
				}
545
				File f = new File(filename);
546
				FileOutputStream fos = new FileOutputStream(f);
547
				baosPDF.writeTo(fos);
548
			}
549
		} catch (Exception e) {
550
			logger.error("Error while generating Invoice: ", e);
551
		}
552
		return baosPDF;
553
	}
3065 chandransh 554
 
13276 manish.sha 555
	private PdfPTable getDispatchAdviceTable(List<Order> orderList, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode, boolean withBill, Warehouse shippingLocation, String invoiceFormat){
556
		Order order = orderList.get(0);
7014 rajveer 557
		Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
13276 manish.sha 558
 
559
		double totalAmount = 0.0;
560
		double totalWeight = 0.0;
561
 
562
		for (Order o: orderList){
563
			totalAmount = totalAmount + order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount();
564
			totalWeight = totalWeight + o.getTotal_weight();
565
		}
2787 chandransh 566
 
7014 rajveer 567
		PdfPTable table = new PdfPTable(1);
568
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 569
 
570
		PdfPTable titleBarTable = new PdfPTable(new float[]{0.4f, 0.4f, 0.2f});
8107 manish.sha 571
		titleBarTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 572
 
8103 manish.sha 573
		PdfPTable logoTable = new PdfPTable(2);
574
		addLogoTable(logoTable,order); 
7318 rajveer 575
 
7014 rajveer 576
		PdfPCell titleCell = getTitleCell();
577
		PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false);
13276 manish.sha 578
		PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont, totalWeight);
2787 chandransh 579
 
7014 rajveer 580
		PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
581
		dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
582
		dispatchTable.addCell(customerTable);
583
		dispatchTable.addCell(new Phrase(" "));
584
		dispatchTable.addCell(providerInfoTable);
2787 chandransh 585
 
13276 manish.sha 586
		PdfPTable invoiceTable = getTopInvoiceTable(orderList, shippingLocation.getTinNumber(), invoiceFormat);
8110 manish.sha 587
		PdfPTable addressTable = new PdfPTable(1);
588
		addressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
589
		addressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
590
 
7014 rajveer 591
		PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
8169 manish.sha 592
				" - " + shippingLocation.getPincode() + "\nContact No.- 0120-2479977" + "\n\n");
2787 chandransh 593
 
7014 rajveer 594
		PdfPTable chargesTable = new PdfPTable(1);
595
		chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
596
		chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
597
		if(order.isLogisticsCod()){
13276 manish.sha 598
			chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (totalAmount), helveticaBold12));
7014 rajveer 599
			chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
7994 manish.sha 600
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
601
			if(order.getLogistics_provider_id()==7L){
602
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
603
				String fedexCodReturnBarcode = "";
8080 manish.sha 604
				String fedexCodReturnTrackingId = "";
7994 manish.sha 605
				try {
606
					fedexCodReturnBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_BarCode");
8080 manish.sha 607
					fedexCodReturnTrackingId = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_Tracking_No");
7994 manish.sha 608
				} catch (TException e1) {
609
					logger.error("Error while getting the provider information.", e1);
610
				}
8080 manish.sha 611
				PdfPCell formIdCell= new PdfPCell(new Paragraph("COD Return "+fedexCodReturnTrackingId+" Form id-0325", helvetica6));
8104 manish.sha 612
				formIdCell.setPaddingTop(2.0f);
7994 manish.sha 613
				formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
614
				formIdCell.setBorder(Rectangle.NO_BORDER);
615
				chargesTable.addCell(new Phrase("PRIORITY OVERNIGHT ", helvetica8));
616
				chargesTable.addCell(formIdCell);
8035 manish.sha 617
 
8067 manish.sha 618
				generateBarcode(fedexCodReturnBarcode, "fedex_codr_"+order.getId());
8037 manish.sha 619
 
8067 manish.sha 620
				Image barcodeImage=null;
621
				try {
622
					barcodeImage = Image.getInstance("/tmp/"+"fedex_codr_"+order.getId()+".png");
623
				} catch (Exception e) {
624
					logger.error("Exception during getting Barcode Image for Fedex : ", e);
625
				}
626
 
8173 manish.sha 627
				PdfPTable codReturnTable = new PdfPTable(new float[]{0.6f,0.4f});
628
				codReturnTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
629
				codReturnTable.addCell(barcodeImage);
630
				codReturnTable.addCell(new Phrase(" "));
631
				chargesTable.addCell(codReturnTable);
632
 
7994 manish.sha 633
			}
634
			//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 635
		} else {
636
			chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
637
		}
8080 manish.sha 638
 
639
		if(order.getLogistics_provider_id()==7L){
640
			chargesTable.addCell(new Phrase("Term and Condition:- Subject to the Conditions of Carriage which " +
641
					"limits the liability of FedEx for loss, delay or damage to the consignment." +
642
					" Visit http://www.fedex.com/in/domestic/services/terms to view the conitions of Carriage" ,
8082 manish.sha 643
					new Font(FontFamily.TIMES_ROMAN, 8f)));
8080 manish.sha 644
		}
10310 amar.kumar 645
 
8110 manish.sha 646
		addressTable.addCell(new Phrase("If undelivered, return to:", helvetica10));
647
		addressTable.addCell(addressCell);
648
 
7014 rajveer 649
		PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
650
		addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8110 manish.sha 651
		addressAndNoteTable.addCell(addressTable);
7014 rajveer 652
		addressAndNoteTable.addCell(chargesTable);
2787 chandransh 653
 
8106 manish.sha 654
		titleBarTable.addCell(logoTable);
655
		titleBarTable.addCell(titleCell);
656
		titleBarTable.addCell(" ");
657
 
658
		table.addCell(titleBarTable);
7014 rajveer 659
		table.addCell(dispatchTable);
660
		table.addCell(invoiceTable);
661
		table.addCell(addressAndNoteTable);
662
		return table;
663
	}
2787 chandransh 664
 
8103 manish.sha 665
	private void addLogoTable(PdfPTable logoTable,Order order) {
7318 rajveer 666
		logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
667
		logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
668
		logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
8096 manish.sha 669
 
7318 rajveer 670
		PdfPCell logoCell;
671
		String logoPath;
8102 manish.sha 672
 
7556 rajveer 673
		if(order.getSource() == OrderSource.STORE.getValue()){
674
			logoCell = new PdfPCell(new Phrase(""));
675
 
676
		}else{
8102 manish.sha 677
			logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
8094 manish.sha 678
 
7318 rajveer 679
			try {
680
				logoCell = new PdfPCell(Image.getInstance(logoPath), false);
681
			} catch (Exception e) {
682
				//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
683
				logger.warn("Couldn't load the Saholic logo: ", e);
684
				logoCell = new PdfPCell(new Phrase("Saholic Logo"));
685
			}
686
 
687
		}
8090 manish.sha 688
		logoCell.setBorder(Rectangle.NO_BORDER);
689
		logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
8102 manish.sha 690
		logoTable.addCell(logoCell);
691
		logoTable.addCell(" ");
8103 manish.sha 692
 
7318 rajveer 693
	}
694
 
7014 rajveer 695
	private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
696
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
697
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
698
		ttfFontFactory.register(fontPath, "barcode");
699
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
700
		return barCodeFont;
701
	}
2787 chandransh 702
 
7014 rajveer 703
	private PdfPCell getTitleCell() {
704
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
705
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
706
		titleCell.setBorder(Rectangle.NO_BORDER);
707
		return titleCell;
708
	}
2787 chandransh 709
 
13276 manish.sha 710
	private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont, double totalWeight) {
7014 rajveer 711
		PdfPTable providerInfoTable = new PdfPTable(1);
712
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7318 rajveer 713
		if(order.isLogisticsCod()){
8551 manish.sha 714
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica22));
7318 rajveer 715
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
716
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
717
			providerInfoTable.addCell(deliveryTypeCell);
718
		}
719
 
8035 manish.sha 720
 
7014 rajveer 721
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
722
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
723
		providerNameCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 724
		PdfPCell formIdCell= null;
725
		if(order.getLogistics_provider_id()==7L){
726
			if(order.isCod()){
8034 manish.sha 727
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
7994 manish.sha 728
			}
729
			else{
8034 manish.sha 730
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
7994 manish.sha 731
			}
8551 manish.sha 732
			formIdCell.setPaddingTop(1.0f);
8015 rajveer 733
			formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
734
			formIdCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 735
		}
8015 rajveer 736
 
7994 manish.sha 737
 
738
		PdfPCell awbNumberCell= null;
8034 manish.sha 739
		String fedexPackageBarcode = "";
7994 manish.sha 740
		if(order.getLogistics_provider_id()!=7L){
741
			awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
8017 manish.sha 742
			awbNumberCell.setPaddingTop(20.0f);
7994 manish.sha 743
		}
744
		else{
8013 rajveer 745
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
746
			try {
747
				fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
748
			} catch (TException e1) {
749
				logger.error("Error while getting the provider information.", e1);
750
			}
8174 manish.sha 751
			awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
752
		}
753
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
754
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
755
 
756
		providerInfoTable.addCell(providerNameCell);
757
		if(formIdCell != null){
758
			providerInfoTable.addCell(formIdCell);
759
		}
760
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
761
		if(order.getLogistics_provider_id()==7L){
8169 manish.sha 762
			generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
763
 
764
			Image barcodeImage=null;
765
			try {
766
				barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
767
			} catch (Exception e) {
768
				logger.error("Exception during getting Barcode Image for Fedex : ", e);
769
			}
8174 manish.sha 770
			providerInfoTable.addCell(barcodeImage);
7994 manish.sha 771
		}
8174 manish.sha 772
		providerInfoTable.addCell(awbNumberCell);
7014 rajveer 773
 
7792 anupam.sin 774
		Warehouse warehouse = null;
775
		try{
776
    		InventoryClient isc = new InventoryClient();
7804 amar.kumar 777
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
7803 amar.kumar 778
		} catch(Exception e) {
7792 anupam.sin 779
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
7805 amar.kumar 780
		    //TODO throw e;
7792 anupam.sin 781
		}
782
		DeliveryType dt =  DeliveryType.PREPAID;
783
        if (order.isLogisticsCod()) {
784
            dt = DeliveryType.COD;
785
        }
7994 manish.sha 786
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
787
        if(order.getLogistics_provider_id()!=7L){
788
	        for (ProviderDetails detail : provider.getDetails()) {
789
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
790
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
791
	            }
792
	        }
7792 anupam.sin 793
        }
7994 manish.sha 794
        else{
795
        	providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
796
        }
797
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 798
		Date awbDate;
799
		if(order.getBilling_timestamp() == 0){
800
			awbDate = new Date();
801
		}else{
802
			awbDate = new Date(order.getBilling_timestamp());
803
		}
8106 manish.sha 804
		if(order.getLogistics_provider_id()!=7L){
805
			providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
806
		}
7014 rajveer 807
		providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
8182 amar.kumar 808
		if(order.getSource() == OrderSource.EBAY.getValue()){
809
			EbayOrder ebayOrder = null;
810
			try {
811
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
812
			} catch (TException e) {
813
				logger.error("Error while getting ebay order", e);
814
			}
815
			providerInfoTable.addCell(new Phrase("PaisaPayId            : " + ebayOrder.getPaisaPayId(), helvetica8));
816
			providerInfoTable.addCell(new Phrase("Sales Rec Number: " + ebayOrder.getSalesRecordNumber(), helvetica8));
817
		}
7994 manish.sha 818
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
819
		if(order.getLogistics_provider_id()==7L){
820
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
821
		}
822
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 823
		return providerInfoTable;
824
	}
825
 
13276 manish.sha 826
	private PdfPTable getTopInvoiceTable(List<Order> orderList, String tinNo, String invoiceFormat){
7014 rajveer 827
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
828
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
829
 
13276 manish.sha 830
		invoiceTable.addCell(getInvoiceTableHeader(6,orderList.get(0).getLogisticsTransactionId()));
831
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
832
			invoiceTable.addCell(new Phrase("Sr No", helvetica8));
833
		}else{
834
			invoiceTable.addCell(new Phrase("Order No", helvetica8));
835
		}
7014 rajveer 836
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
837
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
838
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
839
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
840
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
13276 manish.sha 841
		double totalAmount = 0.0;
842
		double insuranceAmount = 0.0;
843
		double advanceAmount = 0.0;
844
 
845
 
846
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
847
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
848
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
849
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
850
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
851
			String paymentMode = "";
852
			for(Order order : orderList){
853
				LineItem lineitem = order.getLineitems().get(0);
854
				totalAmount = totalAmount + order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount();
855
				if(order.getInsurer() > 0) {
856
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
857
				}
858
				if(order.getSource() == OrderSource.STORE.getValue()) {
859
					advanceAmount = advanceAmount + order.getAdvanceAmount();
860
				}
861
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
862
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
863
				}
864
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
865
					itemRateMap.put(lineitem.getItem_id(), lineitem.getUnit_price());
866
				}
867
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
868
					double currentQuantity = itemQuantityMap.get(lineitem.getItem_id()) +lineitem.getQuantity();
869
					itemQuantityMap.put(lineitem.getItem_id(), currentQuantity);
870
				}else{
871
					itemQuantityMap.put(lineitem.getItem_id(), lineitem.getQuantity());
872
				}
873
 
874
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
875
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount());
876
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
877
				}else{
878
					itemTotalAmtMap.put(lineitem.getItem_id(), (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
879
				}
880
				if(paymentMode==null || paymentMode.isEmpty()){
881
					if(order.getPickupStoreId() > 0 && order.isCod() == true)
882
						paymentMode = "In-Store";
883
					else if (order.isCod())
884
						paymentMode = "COD";
885
					else
886
						paymentMode = "Prepaid";
887
				}		
888
			}
889
 
890
			int serialNo = 0;
891
			for(Long itemId : itemNamesMap.keySet()){
892
				serialNo ++;
893
				invoiceTable.addCell(new Phrase(serialNo+ "", helvetica8));
894
				invoiceTable.addCell(new Phrase(paymentMode, helvetica8));
895
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId), helvetica8));
896
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"", helvetica8));
897
				invoiceTable.addCell(new Phrase(itemRateMap.get(itemId)+"", helvetica8));
898
				invoiceTable.addCell(new Phrase(itemTotalAmtMap.get(itemId)+"", helvetica8));
899
			}
900
 
901
			if(insuranceAmount>0){
902
				invoiceTable.addCell(getInsuranceCell(4));
903
				invoiceTable.addCell(getPriceCell(insuranceAmount));
904
				invoiceTable.addCell(getPriceCell(insuranceAmount));
905
			}
906
			if(advanceAmount>0){
907
				invoiceTable.addCell(getAdvanceAmountCell(4));
908
				invoiceTable.addCell(getPriceCell(advanceAmount));
909
				invoiceTable.addCell(getPriceCell(advanceAmount));
910
			}
911
		}else{
912
			for(Order order : orderList){
913
				populateTopInvoiceTable(order, invoiceTable);
914
				if(order.getInsurer() > 0) {
915
					invoiceTable.addCell(getInsuranceCell(4));
916
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
917
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
918
				}
7014 rajveer 919
 
13276 manish.sha 920
				if(order.getSource() == OrderSource.STORE.getValue()) {
921
					invoiceTable.addCell(getAdvanceAmountCell(4));
922
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
923
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
924
				}
925
				totalAmount = totalAmount + order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount();
926
			}
7014 rajveer 927
		}
7318 rajveer 928
 
7014 rajveer 929
		invoiceTable.addCell(getTotalCell(4));      
930
		invoiceTable.addCell(getRupeesCell());
13276 manish.sha 931
		invoiceTable.addCell(getTotalAmountCell(totalAmount));
932
 
7014 rajveer 933
 
934
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
935
		tinCell.setColspan(6);
936
		tinCell.setPadding(2);
937
		invoiceTable.addCell(tinCell);
938
 
939
		return invoiceTable;
940
	}
941
 
942
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
943
		List<LineItem> lineitems = order.getLineitems();
944
		for (LineItem lineitem : lineitems) {
945
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
946
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
947
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
948
			else if (order.isCod())
949
				invoiceTable.addCell(new Phrase("COD", helvetica8));
950
			else
951
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 952
 
7190 amar.kumar 953
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 954
 
7014 rajveer 955
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 956
 
7014 rajveer 957
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
958
 
959
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
960
		}
961
	}
962
 
963
	private PdfPCell getAddressCell(String address) {
964
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
965
		PdfPCell addressCell = new PdfPCell();
966
		addressCell.addElement(addressParagraph);
967
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
968
		addressCell.setBorder(Rectangle.NO_BORDER);
969
		return addressCell;
970
	}
971
 
13276 manish.sha 972
	private PdfPTable getTaxCumRetailInvoiceTable(List<Order> orderList, Provider provider, String ourAddress, String tinNo, String invoiceFormat){
973
		Order order = orderList.get(0);
7014 rajveer 974
		PdfPTable taxTable = new PdfPTable(1);
975
		Phrase phrase = null;
976
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
977
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
8104 manish.sha 978
 
8110 manish.sha 979
		PdfPTable logoTitleAndOurAddressTable = new PdfPTable(new float[]{0.4f, 0.3f, 0.3f});
8107 manish.sha 980
		logoTitleAndOurAddressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8112 manish.sha 981
		logoTitleAndOurAddressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
8107 manish.sha 982
 
8110 manish.sha 983
 
8103 manish.sha 984
		PdfPTable logoTable = new PdfPTable(2);
985
		addLogoTable(logoTable,order); 
7318 rajveer 986
 
7014 rajveer 987
		if (order.getOrderType().equals(OrderType.B2B)) {
988
			phrase = new Phrase("TAX INVOICE", helveticaBold12);
989
		} else {
990
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
991
		}
992
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
993
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
994
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
995
 
8169 manish.sha 996
		Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- 0120-2479977" + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
7014 rajveer 997
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
998
		sorlAddressCell.addElement(sorlAddress);
8110 manish.sha 999
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
7014 rajveer 1000
 
1001
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
1002
		PdfPTable orderDetails = getOrderDetails(order, provider);
1003
 
1004
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
1005
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1006
		addrAndOrderDetailsTable.addCell(customerAddress);
1007
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
1008
		addrAndOrderDetailsTable.addCell(orderDetails);
1009
 
9319 amar.kumar 1010
		boolean isVAT = isVatApplicable(order);
13276 manish.sha 1011
		PdfPTable invoiceTable = getBottomInvoiceTable(orderList, isVAT, invoiceFormat);
7014 rajveer 1012
 
10607 manish.sha 1013
		PdfPTable regAddAndDisCellTable = new PdfPTable(2);
1014
 
7014 rajveer 1015
		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));
1016
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1017
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
7318 rajveer 1018
 
10609 manish.sha 1019
		PdfPCell regAddressCell = new PdfPCell(new Phrase(" SPICE ONLINE RETAIL PRIVATE LIMITED\n Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062\n CIN: U74140DL2008PTC183856 Tel. No. 0120-2479977 E-mail. help@saholic.com Website. www.saholic.com", helvetica6));
10607 manish.sha 1020
		regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1021
		regAddressCell.setBorder(Rectangle.NO_BORDER);
1022
		/*SPICE ONLINE RETAIL PRIVATE LIMITED
1023
		Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
1024
		CIN: U74140DL2008PTC183856
1025
		Tel. No. 0120-2479977
1026
		E-mail. help@saholic.com
1027
		Website. www.saholic.com*/
9014 amar.kumar 1028
		PdfPCell powerTextCell = new PdfPCell(new Phrase("Powered By  Flipkart", helvetica8));
1029
		powerTextCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1030
		powerTextCell.setBorder(Rectangle.NO_BORDER);
1031
		powerTextCell.setPaddingBottom(30.0f);
8104 manish.sha 1032
 
1033
		logoTitleAndOurAddressTable.addCell(logoTable);
8110 manish.sha 1034
		logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
1035
		logoTitleAndOurAddressTable.addCell(sorlAddress);
8104 manish.sha 1036
 
10607 manish.sha 1037
		regAddAndDisCellTable.addCell(disclaimerCell);
1038
		regAddAndDisCellTable.addCell(regAddressCell);
1039
 
8104 manish.sha 1040
		taxTable.addCell(logoTitleAndOurAddressTable);
7014 rajveer 1041
		taxTable.addCell(addrAndOrderDetailsTable);
1042
		taxTable.addCell(invoiceTable);
10608 manish.sha 1043
		taxTable.addCell(regAddAndDisCellTable);
9014 amar.kumar 1044
		if(order.getSource() == OrderSource.FLIPKART.getValue()) {
1045
			taxTable.addCell(powerTextCell);
1046
 
1047
		}
10320 amar.kumar 1048
		if(order.getProductCondition().equals(ProductCondition.BAD)){
10328 amar.kumar 1049
			PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
10320 amar.kumar 1050
					"may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
1051
					"are not returnable, exchangeable or refundable under any circumstances. No " +
1052
					"warranty is assured on these items." ,
10329 amar.kumar 1053
					new Font(FontFamily.TIMES_ROMAN, 8f)));
10328 amar.kumar 1054
			badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1055
			badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
1056
			taxTable.addCell(badSaleDisclaimerCell);
10320 amar.kumar 1057
		}
7014 rajveer 1058
		return taxTable;
1059
	}
9009 amar.kumar 1060
 
9319 amar.kumar 1061
	private boolean isVatApplicable(Order order) {
1062
		if(order.getWarehouse_id() == 7) {
1063
			if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
1064
				return true;
1065
			} else {
1066
				return false;
1067
			}
12809 manish.sha 1068
		} else if(order.getWarehouse_id() == 3298){
1069
			for(int i=0; i< telanganaPincodes.length; i++) {
1070
				if(order.getCustomer_pincode().trim().equalsIgnoreCase(telanganaPincodes[i])) {
1071
					return true;
1072
				}
1073
			}
1074
			return false;
1075
		}
1076
		else {
9319 amar.kumar 1077
			for(int i=0; i< maharashtraPincodePrefix.length; i++) {
1078
				if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
1079
					return true;
1080
				}
1081
			}
1082
			return false;
1083
		}
1084
	}
1085
 
9037 amar.kumar 1086
	private PdfPTable getFlipkartBarCodes(Order order) {
1087
		PdfPTable flipkartTable = new PdfPTable(3);
1088
 
1089
		PdfPCell spacerCell = new PdfPCell();
9040 amar.kumar 1090
		spacerCell.setBorder(Rectangle.NO_BORDER);
9037 amar.kumar 1091
		spacerCell.setColspan(3);
9099 amar.kumar 1092
		spacerCell.setPaddingTop(330.0f);
9037 amar.kumar 1093
 
1094
		String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1095
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1096
		ttfFontFactory.register(flipkartCodeFontPath, "barcode");
1097
		Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
1098
 
9040 amar.kumar 1099
		String serialNumber = "0000000000";
9511 manish.sha 1100
		if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
9040 amar.kumar 1101
			serialNumber = order.getLineitems().get(0).getSerial_number();
9511 manish.sha 1102
		} else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
9040 amar.kumar 1103
			serialNumber = order.getLineitems().get(0).getItem_number();
1104
		}
1105
 
1106
		PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
9037 amar.kumar 1107
		serialNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1108
		serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1109
		serialNumberBarCodeCell.setPaddingTop(11.0f);
1110
 
1111
 
1112
		PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
1113
		invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1114
		invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1115
		invoiceNumberBarCodeCell.setPaddingTop(11.0f);
1116
 
1117
		double rate = order.getLineitems().get(0).getVatRate();
1118
		double salesTax = (rate * order.getTotal_amount())/(100 + rate);
9040 amar.kumar 1119
		PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
9037 amar.kumar 1120
		vatAmtBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1121
		vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1122
		vatAmtBarCodeCell.setPaddingTop(11.0f);
1123
 
1124
		flipkartTable.addCell(spacerCell);
1125
		flipkartTable.addCell(serialNumberBarCodeCell);
1126
		flipkartTable.addCell(invoiceNumberBarCodeCell);
1127
		flipkartTable.addCell(vatAmtBarCodeCell);
1128
 
1129
		return flipkartTable;
1130
 
9009 amar.kumar 1131
	}
1132
 
7014 rajveer 1133
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
1134
		PdfPTable customerTable = new PdfPTable(1);
1135
		customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1136
		if(forInvoce || order.getPickupStoreId() == 0){
1137
			customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1138
			customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1139
			customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1140
			customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
7994 manish.sha 1141
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1142
			if(order.getLogistics_provider_id()!=7L){
1143
				if(destCode != null)
1144
					customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1145
				else
1146
					customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1147
				}
1148
			else{
1149
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1150
				String fedexLocationcode = "";
1151
				try {
1152
					fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1153
				} catch (TException e1) {
1154
					logger.error("Error while getting the provider information.", e1);
1155
				}
1156
				customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1157
			}
1158
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
9100 amar.kumar 1159
			if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1160
				customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1161
			}
7014 rajveer 1162
		}else{
1163
			try {
5556 rajveer 1164
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 1165
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
1166
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
1167
				customerTable.addCell(new Phrase(store.getLine1(), font));
1168
				customerTable.addCell(new Phrase(store.getLine2(), font));
1169
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
1170
				if(destCode != null)
1171
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
1172
				else
1173
					customerTable.addCell(new Phrase(store.getPin(), font));
1174
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 1175
			} catch (TException e) {
1176
				// TODO Auto-generated catch block
1177
				e.printStackTrace();
1178
			}
5527 anupam.sin 1179
 
7014 rajveer 1180
		}
1181
 
1182
		if(order.getOrderType().equals(OrderType.B2B)) {
1183
			String tin = null;
1184
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1185
			List<Attribute> attributes;
1186
			try {
1187
				attributes = tclient.getAllAttributesForOrderId(order.getId());
1188
 
1189
				for(Attribute attribute : attributes) {
1190
					if(attribute.getName().equals("tinNumber")) {
1191
						tin = attribute.getValue();
1192
					}
1193
				}
1194
				if (tin != null) {
1195
					customerTable.addCell(new Phrase("TIN :" + tin, font));
1196
				}
1197
 
1198
			} catch (Exception e) {
1199
				logger.error("Error while getting order attributes", e);
1200
			}
1201
		}
1202
		/*
2787 chandransh 1203
        if(showPaymentMode){
1204
            customerTable.addCell(new Phrase(" ", font));
1205
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 1206
        }*/
7014 rajveer 1207
		return customerTable;
1208
	}
2787 chandransh 1209
 
7014 rajveer 1210
	private PdfPTable getOrderDetails(Order order, Provider provider){
1211
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
1212
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 1213
 
7014 rajveer 1214
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
1215
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 1216
 
7014 rajveer 1217
		orderTable.addCell(new Phrase("Date:", helvetica8));
1218
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1219
 
12590 amit.gupta 1220
		if(order.getSource() == OrderSource.AMAZON.getValue() || order.getSource() == OrderSource.JUNGLEE.getValue()){
7528 rajveer 1221
			AmazonOrder aorder = null;
1222
			try {
1223
				aorder = tsc.getClient().getAmazonOrder(order.getId());
1224
			} catch (TException e) {
1225
				logger.error("Error while getting amazon order", e);
1226
			}
12590 amit.gupta 1227
			if(order.getSource() == OrderSource.JUNGLEE.getValue()){
1228
				orderTable.addCell(new Phrase("Junglee Order ID:", helvetica8));
1229
			}else {
1230
				orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
1231
			}
7528 rajveer 1232
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
8182 amar.kumar 1233
		} else if(order.getSource() == OrderSource.EBAY.getValue()){
1234
			EbayOrder ebayOrder = null;
1235
			try {
1236
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1237
			} catch (TException e) {
1238
				logger.error("Error while getting ebay order", e);
1239
			}
1240
			orderTable.addCell(new Phrase("PaisaPayId:", helvetica8));
1241
			orderTable.addCell(new Phrase(ebayOrder.getPaisaPayId(), helvetica8));
1242
			orderTable.addCell(new Phrase("Sales Rec Number:", helvetica8));
1243
			orderTable.addCell(new Phrase(new Long(ebayOrder.getSalesRecordNumber()).toString(), helvetica8));
8488 amar.kumar 1244
		} else if(order.getSource() == OrderSource.SNAPDEAL.getValue()){
1245
			SnapdealOrder snapdealOrder = null;
1246
			try {
11424 kshitij.so 1247
				snapdealOrder = tsc.getClient().getSnapdealOrder(order.getId(), null, null).get(0);
8488 amar.kumar 1248
			} catch (TException e) {
1249
				logger.error("Error while getting snapdeal order", e);
1250
			}
1251
			orderTable.addCell(new Phrase("Snapdeal OrderId:", helvetica8));
1252
			orderTable.addCell(new Phrase(new Long(snapdealOrder.getSubOrderId()).toString(), helvetica8));
8828 amar.kumar 1253
 
1254
			String refernceCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1255
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1256
			ttfFontFactory.register(refernceCodeFontPath, "barcode");
8876 amar.kumar 1257
			Font referenceCodeBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
8828 amar.kumar 1258
 
8874 amar.kumar 1259
			PdfPCell snapdealReferenceBarCodeCell = new PdfPCell(new Paragraph("*" +  snapdealOrder.getReferenceCode() + "*", referenceCodeBarCodeFont));
8828 amar.kumar 1260
			snapdealReferenceBarCodeCell.setBorder(Rectangle.NO_BORDER);
8876 amar.kumar 1261
			snapdealReferenceBarCodeCell.setPaddingTop(9.0f);
1262
			snapdealReferenceBarCodeCell.setColspan(2);
9042 amar.kumar 1263
			snapdealReferenceBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
8876 amar.kumar 1264
			//orderTable.addCell(new Phrase("Snapdeal ReferenceCode:", helvetica8));
8828 amar.kumar 1265
			orderTable.addCell(snapdealReferenceBarCodeCell);
1266
			//orderTable.addCell(new Phrase(snapdealOrder.getReferenceCode(), helvetica8));
7528 rajveer 1267
		}
8989 vikram.rag 1268
		else if(order.getSource() == OrderSource.FLIPKART.getValue()){
1269
			FlipkartOrder flipkartOrder = null;
1270
			try {
1271
				flipkartOrder = tsc.getClient().getFlipkartOrder(order.getId());
1272
			} catch (TException e) {
8996 amar.kumar 1273
				logger.error("Error while getting flipkart order", e);
8989 vikram.rag 1274
			}
1275
			orderTable.addCell(new Phrase("Flipkart OrderId:", helvetica8));
1276
			orderTable.addCell(new Phrase(flipkartOrder.getFlipkartOrderId(), helvetica8));
9037 amar.kumar 1277
 
1278
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1279
			String flipkartBarCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1280
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1281
			ttfFontFactory.register(flipkartBarCodeFontPath, "barcode");
9043 amar.kumar 1282
			Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 18);
9037 amar.kumar 1283
 
9043 amar.kumar 1284
			orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
9037 amar.kumar 1285
			PdfPCell flipkartOrderItemIdBarCodeCell = new PdfPCell(new Paragraph("*" +  new Long(flipkartOrder.getFlipkartSubOrderId()).toString() + "*", flipkartBarCodeFont));
1286
			flipkartOrderItemIdBarCodeCell.setBorder(Rectangle.NO_BORDER);
1287
			flipkartOrderItemIdBarCodeCell.setPaddingTop(9.0f);
9043 amar.kumar 1288
			//flipkartOrderItemIdBarCodeCell.setColspan(2);
1289
			//flipkartOrderItemIdBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1290
			orderTable.addCell(flipkartOrderItemIdBarCodeCell);
1291
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1292
			//orderTable.addCell(new Phrase(new Long(flipkartOrder.getFlipkartSubOrderId()).toString(), helvetica8));
8989 vikram.rag 1293
		}
1294
 
1295
 
7014 rajveer 1296
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
1297
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
13276 manish.sha 1298
 
1299
		if(OrderType.B2B==order.getOrderType()){
1300
			try {
1301
				String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
1302
				if(poRefVal!=null && poRefVal.length()>0){
1303
					orderTable.addCell(new Phrase("PO Ref:", helvetica8));
1304
					orderTable.addCell(new Phrase(poRefVal, helvetica8));
1305
				}
1306
 
1307
			} catch (TException e) {
1308
				logger.error("Error while getting amazon order", e);
1309
			}
1310
		}
2787 chandransh 1311
 
7014 rajveer 1312
		orderTable.addCell(new Phrase("Courier:", helvetica8));
1313
		orderTable.addCell(new Phrase(provider.getName(), helvetica8));
2787 chandransh 1314
 
9038 amar.kumar 1315
		if(order.getAirwaybill_no()!=null && !order.getAirwaybill_no().isEmpty()) {
1316
			orderTable.addCell(new Phrase("AWB No:", helvetica8));
1317
			orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
1318
		}
2787 chandransh 1319
 
7014 rajveer 1320
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
1321
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1322
 
7014 rajveer 1323
		return orderTable;
1324
	}
2787 chandransh 1325
 
13276 manish.sha 1326
	private PdfPTable getBottomInvoiceTable(List<Order> orderList,boolean isVAT, String invoiceFormat){
1327
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
7014 rajveer 1328
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 1329
 
13276 manish.sha 1330
		invoiceTable.addCell(getInvoiceTableHeader(5,orderList.get(0).getLogisticsTransactionId()));
4262 rajveer 1331
 
13276 manish.sha 1332
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1333
			invoiceTable.addCell(new Phrase("Sr No", helveticaBold8));
1334
		}else{
1335
			invoiceTable.addCell(new Phrase("Order No", helveticaBold8));
1336
		}
7014 rajveer 1337
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
1338
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
1339
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
1340
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
13276 manish.sha 1341
		invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
1342
		invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
1343
		invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));;
1344
		double totalAmount = 0.0;
1345
		double insuranceAmount = 0.0;
1346
		int i=1;
1347
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1348
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1349
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1350
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1351
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1352
			Map<Long, Double> itemTaxPercentageMap = new HashMap<Long, Double>();
1353
			Map<Long, Double> itemTaxValueMap = new HashMap<Long, Double>();
1354
 
1355
			for(Order order : orderList){
1356
				LineItem lineitem = order.getLineitems().get(0);
1357
 
1358
				double orderAmount = order.getTotal_amount();
1359
				double rate = lineitem.getVatRate();
1360
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1361
				totalAmount = totalAmount + orderAmount;
1362
				double itemPrice = lineitem.getUnit_price();
1363
				double showPrice = (100 * itemPrice)/(100 + rate);
1364
				double totalPrice = lineitem.getTotal_price();
1365
				double showTotalPrice = (100 * totalPrice)/(100 + rate);
1366
 
1367
				if(order.getInsurer() > 0) {
1368
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1369
				}
1370
 
1371
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1372
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1373
				}
1374
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1375
					double quantity = itemQuantityMap.get(lineitem.getItem_id()) + lineitem.getQuantity();
1376
					itemQuantityMap.put(lineitem.getItem_id(), quantity);
1377
				} else {
1378
					itemQuantityMap.put(lineitem.getItem_id(),lineitem.getQuantity());
1379
				}
1380
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1381
					itemRateMap.put(lineitem.getItem_id(), showPrice);
1382
				}
1383
				if(!itemTaxPercentageMap.containsKey(lineitem.getItem_id())){
1384
					itemTaxPercentageMap.put(lineitem.getItem_id(), rate);
1385
				}
1386
				if(itemTaxValueMap.containsKey(lineitem.getItem_id())){
1387
					double taxValue = itemTaxValueMap.get(lineitem.getItem_id()) + salesTax;
1388
					itemTaxValueMap.put(lineitem.getItem_id(), taxValue);
1389
				}else{
1390
					itemTaxValueMap.put(lineitem.getItem_id(), salesTax);
1391
				}
1392
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
1393
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + showTotalPrice;
1394
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1395
				}else{
1396
					itemTotalAmtMap.put(lineitem.getItem_id(), showTotalPrice);
1397
				}
1398
			}
1399
 
1400
			for(Long itemId : itemNamesMap.keySet()){
1401
				invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
1402
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId),helvetica8));
1403
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"",helvetica8));
1404
				invoiceTable.addCell(new Phrase(itemRateMap.get(itemId)+"",helvetica8));
1405
				invoiceTable.addCell(new Phrase(itemTotalAmtMap.get(itemId)+"",helvetica8));
1406
				invoiceTable.addCell(new Phrase(itemTaxPercentageMap.get(itemId)+"",helvetica8));
1407
				invoiceTable.addCell(new Phrase(itemTaxValueMap.get(itemId)+"",helvetica8));
1408
				invoiceTable.addCell(new Phrase((itemTotalAmtMap.get(itemId)+itemTaxValueMap.get(itemId))+"",helvetica8));
1409
			}
1410
		}
1411
		else{
9432 amar.kumar 1412
 
13276 manish.sha 1413
			for(Order order :orderList){
1414
				LineItem lineItem = order.getLineitems().get(0);
1415
				double orderAmount = order.getTotal_amount();
1416
				double rate = lineItem.getVatRate();
1417
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1418
 
1419
				invoiceTable.addCell(new Phrase(order.getId()+"", helveticaBold8));
1420
				invoiceTable.addCell(getProductNameCell(lineItem, true, order.getFreebieItemId()));
1421
				invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
1422
 
1423
 
1424
				//populateBottomInvoiceTable(order, invoiceTable, rate);
1425
 
1426
				double itemPrice = lineItem.getUnit_price();
1427
				double showPrice = (100 * itemPrice)/(100 + rate);
1428
				invoiceTable.addCell(getPriceCell(showPrice));
1429
 
1430
				double totalPrice = lineItem.getTotal_price();
1431
				showPrice = (100 * totalPrice)/(100 + rate);
1432
				invoiceTable.addCell(getPriceCell(showPrice));
1433
 
1434
				PdfPCell salesTaxCell = getPriceCell(salesTax);
1435
 
1436
 
1437
				invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
1438
				invoiceTable.addCell(salesTaxCell);
1439
				invoiceTable.addCell(getTotalAmountCell(orderAmount));
1440
 
1441
				if(order.getInsurer() > 0) {
1442
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1443
				}
1444
				totalAmount = totalAmount+ orderAmount;
1445
				i++;
1446
			}
9432 amar.kumar 1447
		}
7014 rajveer 1448
 
13276 manish.sha 1449
		if(insuranceAmount>0){
1450
			invoiceTable.addCell(getInsuranceCell(7));
1451
			invoiceTable.addCell(getPriceCell(insuranceAmount));
7014 rajveer 1452
		}
1453
 
13276 manish.sha 1454
		invoiceTable.addCell(getTotalCell(6));
7014 rajveer 1455
		invoiceTable.addCell(getRupeesCell());
13276 manish.sha 1456
		invoiceTable.addCell(getTotalAmountCell(totalAmount));
7014 rajveer 1457
 
13276 manish.sha 1458
		invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
1459
		invoiceTable.addCell(getAmountInWordsCell(totalAmount));
7014 rajveer 1460
 
13276 manish.sha 1461
		invoiceTable.addCell(getEOECell(8));
7014 rajveer 1462
 
1463
		return invoiceTable;
1464
	}
1465
 
13276 manish.sha 1466
	private PdfPCell getInvoiceTableHeader(int colspan, String masterOrderId) {
1467
		PdfPTable invoiceHeaderTable = new PdfPTable(2);
1468
		PdfPCell masterOrderIdCell = new PdfPCell(new Phrase("Master Order Id- "+masterOrderId, helvetica10));
1469
		masterOrderIdCell.setBorder(Rectangle.NO_BORDER);
1470
		masterOrderIdCell.setColspan(colspan);
1471
		masterOrderIdCell.setPaddingTop(1);
13281 manish.sha 1472
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
7014 rajveer 1473
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
1474
		invoiceTableHeader.setColspan(colspan);
8551 manish.sha 1475
		invoiceTableHeader.setPaddingTop(1);
13276 manish.sha 1476
		invoiceHeaderTable.addCell(invoiceTableHeader);
1477
		invoiceHeaderTable.addCell(masterOrderIdCell);
1478
 
1479
		return new PdfPCell(invoiceHeaderTable);
7014 rajveer 1480
	}
1481
 
13276 manish.sha 1482
	/*private void populateBottomInvoiceTable(List<Order> orderList, PdfPTable invoiceTable) {
7014 rajveer 1483
		for (LineItem lineitem : order.getLineitems()) {
1484
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
1485
 
7190 amar.kumar 1486
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 1487
 
1488
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
1489
 
1490
			double itemPrice = lineitem.getUnit_price();
1491
			double showPrice = (100 * itemPrice)/(100 + rate);
1492
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
1493
 
1494
			double totalPrice = lineitem.getTotal_price();
1495
			showPrice = (100 * totalPrice)/(100 + rate);
1496
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
1497
		}
13276 manish.sha 1498
	}*/
7014 rajveer 1499
 
7190 amar.kumar 1500
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 1501
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 1502
		if(freebieItemId!=null && freebieItemId!=0){
1503
			try {
1504
				CatalogService.Client catalogClient = ctsc.getClient();
1505
				Item item = catalogClient.getItem(freebieItemId);
1506
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
1507
			} catch(Exception tex) {
1508
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
1509
			}
1510
		}
7014 rajveer 1511
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
1512
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1513
		return productNameCell;
1514
	}
1515
 
1516
	private PdfPCell getPriceCell(double price) {
1517
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
1518
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1519
		return totalPriceCell;
1520
	}
1521
 
1522
	private PdfPCell getVATLabelCell(boolean isVAT) {
1523
		PdfPCell vatCell = null;
1524
		if(isVAT){
1525
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
1526
		} else {
1527
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
1528
		}
1529
		vatCell.setColspan(3);
1530
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1531
		return vatCell;
1532
	}
1533
 
9432 amar.kumar 1534
	private PdfPCell getCFORMLabelCell() {
1535
		PdfPCell cFormCell = null;
1536
		cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
1537
		cFormCell.setColspan(3);
1538
		cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1539
		return cFormCell;
1540
	}
1541
 
7318 rajveer 1542
	private PdfPCell getAdvanceAmountCell(int colspan) {
1543
		PdfPCell insuranceCell = null;
1544
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
1545
		insuranceCell.setColspan(colspan);
1546
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1547
		return insuranceCell;
1548
	}
1549
 
7014 rajveer 1550
	private PdfPCell getInsuranceCell(int colspan) {
1551
		PdfPCell insuranceCell = null;
13276 manish.sha 1552
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance. T&C Apply", helvetica8));
7014 rajveer 1553
		insuranceCell.setColspan(colspan);
1554
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1555
		return insuranceCell;
1556
	}
1557
 
1558
	private PdfPCell getEmptyCell(int colspan) {
1559
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
1560
		emptyCell.setColspan(colspan);
1561
		return emptyCell;
1562
	}
1563
 
1564
	private PdfPCell getTotalCell(int colspan) {
13276 manish.sha 1565
		PdfPCell totalCell = new PdfPCell(new Phrase("Grand Total", helveticaBold8));
7014 rajveer 1566
		totalCell.setColspan(colspan);
1567
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1568
		return totalCell;
1569
	}
1570
 
1571
	private PdfPCell getRupeesCell() {
1572
		PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
1573
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1574
		return rupeesCell;
1575
	}
1576
 
1577
	private PdfPCell getTotalAmountCell(double orderAmount) {
1578
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
1579
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1580
		return totalAmountCell;
1581
	}
1582
 
1583
	/**
1584
	 * This method uses ICU4J libraries to convert the given amount into words
1585
	 * of Indian locale.
1586
	 * 
1587
	 * @param orderAmount
1588
	 *            The amount to convert.
1589
	 * @return the string representation of the given amount.
1590
	 */
1591
	private PdfPCell getAmountInWordsCell(double orderAmount) {
1592
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
1593
		StringBuilder amountInWords = new StringBuilder("Rs. ");
1594
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
1595
		amountInWords.append(" and ");
1596
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
1597
		amountInWords.append(" paise");
1598
 
1599
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
1600
		amountInWordsCell.setColspan(4);
1601
		return amountInWordsCell;
1602
	}
1603
 
1604
	/**
1605
	 * Returns the item name to be displayed in the invoice table.
1606
	 * 
1607
	 * @param lineitem
1608
	 *            The line item whose name has to be displayed
1609
	 * @param appendIMEI
1610
	 *            Whether to attach the IMEI No. to the item name
1611
	 * @return The name to be displayed for the given line item.
1612
	 */
1613
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
1614
		StringBuffer itemName = new StringBuffer();
1615
		if(lineitem.getBrand()!= null)
1616
			itemName.append(lineitem.getBrand() + " ");
1617
		if(lineitem.getModel_name() != null)
1618
			itemName.append(lineitem.getModel_name() + " ");
1619
		if(lineitem.getModel_number() != null )
1620
			itemName.append(lineitem.getModel_number() + " ");
1621
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
1622
			itemName.append("("+lineitem.getColor()+")");
1623
		if(appendIMEI && lineitem.isSetSerial_number()){
1624
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
1625
		}
1626
 
1627
		return itemName.toString();
1628
	}
1629
 
1630
	/**
1631
	 * 
1632
	 * @param colspan
1633
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
1634
	 *         no. of columns
1635
	 */
1636
	private PdfPCell getEOECell(int colspan) {
1637
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
1638
		eoeCell.setColspan(colspan);
1639
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1640
		return eoeCell;
1641
	}
1642
 
1643
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
1644
		PdfPTable extraInfoTable = new PdfPTable(1);
1645
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1646
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1647
 
1648
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1649
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1650
		ttfFontFactory.register(fontPath, "barcode");
1651
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1652
 
1653
		PdfPCell extraInfoCell;
1654
		if(billingType == BillingType.EXTERNAL){
1655
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
1656
		}else{
1657
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
1658
		}
1659
 
1660
		extraInfoCell.setPaddingTop(20.0f);
1661
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1662
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1663
 
1664
		extraInfoTable.addCell(extraInfoCell);
1665
 
1666
 
1667
		return extraInfoTable;
1668
	}
1669
 
1670
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
1671
		PdfPTable extraInfoTable = new PdfPTable(1);
1672
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1673
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1674
 
1675
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1676
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1677
		ttfFontFactory.register(fontPath, "barcode");
1678
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1679
 
1680
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
1681
 
1682
		extraInfoCell.setPaddingTop(20.0f);
1683
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1684
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1685
 
1686
		extraInfoTable.addCell(extraInfoCell);
1687
 
1688
		return extraInfoTable;
1689
	}
8067 manish.sha 1690
 
1691
	private void generateBarcode(String barcodeString, String fileName){
1692
		Code128Bean bean = new Code128Bean();
7014 rajveer 1693
 
8067 manish.sha 1694
		final int dpi = 60;
1695
 
1696
		//Configure the barcode generator
1697
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
1698
		                                                 //width exactly one pixel
1699
		bean.setFontSize(bean.getFontSize()+1.0f);
1700
		bean.doQuietZone(false);
1701
 
1702
		try {
1703
			File outputFile = new File("/tmp/"+fileName+".png");
1704
			OutputStream out = new FileOutputStream(outputFile);
1705
 
1706
		    //Set up the canvas provider for monochrome PNG output 
1707
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
1708
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
1709
 
1710
		    //Generate the barcode
1711
		    bean.generateBarcode(canvas, barcodeString);
1712
 
1713
		    //Signal end of generation
1714
		    canvas.finish();
1715
		    out.close();
1716
 
1717
		} 
1718
		catch(Exception e){
1719
			logger.error("Exception during generating Barcode : ", e);
1720
		}
1721
	}
1722
 
7014 rajveer 1723
	public static void main(String[] args) throws IOException {
1724
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 1725
		long orderId = 356324;
1726
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 1727
		String userHome = System.getProperty("user.home");
1728
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
1729
		FileOutputStream fos = new FileOutputStream(f);
1730
		baos.writeTo(fos);
1731
		System.out.println("Invoice generated.");
1732
	}
2787 chandransh 1733
}