Subversion Repositories SmartDukaan

Rev

Rev 13313 | Rev 13317 | 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
					}
13316 manish.sha 361
 
362
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
363
						PdfPTable orderItemsDetailTable = new PdfPTable(1);
364
						orderItemsDetailTable.setWidthPercentage(90.0f);
365
						orderItemsDetailTable.setSpacingBefore(5.0f);
366
						orderItemsDetailTable.addCell(new Phrase("SubOrder Ids :", helveticaBold8));
367
						StringBuffer sbOrders = new StringBuffer();
368
 
369
						for(Order o1 : orders){
370
							sbOrders.append(o1.getId()+",");
371
						}
372
 
373
 
374
						String orderIds = sbOrders.toString();
375
						orderIds = orderIds.substring(0, orderIds.length()-1);
376
 
377
						orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
378
						orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
379
 
380
						StringBuffer sbImeis = new StringBuffer();
381
 
382
						for(Order o1 : orders){
383
							if(o1.getLineitems().get(0).getSerial_number()!=null){
384
								sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
385
							}
386
						}
387
 
388
						String imeis = sbImeis.toString();
389
						imeis = imeis.substring(0, imeis.length()-1);
390
 
391
						orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
392
 
393
						document.add(new DottedLineSeparator());
394
						document.add(orderItemsDetailTable);
395
					}
396
 
13276 manish.sha 397
					document.newPage();
7014 rajveer 398
				}
13276 manish.sha 399
			} else {
400
				for(Order singleOrder : orders){
401
					List<Order> ordersList = new ArrayList<Order>();
402
					ordersList.add(singleOrder);
403
					Warehouse warehouse = null;
404
					Provider provider = null;
405
					String destCode = null;
406
					Warehouse shippingLocation = null;
407
					int barcodeFontSize = 0;
408
					String invoiceFormat = "Individual";
409
					try {
410
						warehouse = iclient.getWarehouse(singleOrder.getWarehouse_id());
411
						long providerId = singleOrder.getLogistics_provider_id();
412
						provider = logisticsClient.getProvider(providerId);
413
						if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
414
							destCode = provider.getPickup().toString();
415
						else
416
							destCode = logisticsClient.getDestinationCode(providerId, singleOrder.getCustomer_pincode());
4361 rajveer 417
 
13276 manish.sha 418
						barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
419
						shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId()); 
420
					} catch (InventoryServiceException ise) {
421
						logger.error("Error while getting the warehouse information.", ise);
422
						return baosPDF;
423
					} catch (LogisticsServiceException lse) {
424
						logger.error("Error while getting the provider information.", lse);
425
						return baosPDF;
426
					} catch (ConfigException ce) {
427
						logger.error("Error while getting the fontsize for the given provider", ce);
428
						return baosPDF;
429
					} catch (TException te) {
430
						logger.error("Error while getting some essential information from the services", te);
431
						return baosPDF;
7014 rajveer 432
					}
13276 manish.sha 433
 
434
					if(printAll && warehouse.getBillingType() == BillingType.OURS_EXTERNAL){
435
						for(Order order : ordersList){
436
							if(isFirst){
437
								document.add(getFixedTextTable(16, "Spice Online Retail Pvt Ltd"));
438
								isFirst = false;
439
							}
440
							document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
441
							continue;
442
						}
443
					}
444
					PdfPTable dispatchAdviceTable = null;
445
					Order order = ordersList.get(0);
446
					if(ordersList.size()==1){					
447
						if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
8303 amar.kumar 448
							dispatchAdviceTable = new PdfPTable(1);
13276 manish.sha 449
						}  else if(new Long(order.getSource()).intValue() == OrderSource.FLIPKART.getValue()) {
450
							dispatchAdviceTable = new PdfPTable(1);
451
						}  else if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7)) {
452
							if(order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
453
								dispatchAdviceTable = new PdfPTable(1);
454
							} else { 
455
								if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty()) {
456
									dispatchAdviceTable = new PdfPTable(1);
457
								} else {
458
									EbayInvoiceGenerationService invoiceGenerationService = new EbayInvoiceGenerationService();
459
									dispatchAdviceTable = invoiceGenerationService.getDispatchAdviceTable(orderId, warehouseId);
460
								}
461
							}
462
						}
463
						else {
464
							dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
465
						}
466
					} else {
467
						dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
468
					}
469
 
470
					dispatchAdviceTable.setSpacingAfter(10.0f);
471
					dispatchAdviceTable.setWidthPercentage(90.0f);
472
					document.add(dispatchAdviceTable);
473
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
474
						document.newPage();
475
					}
476
 
477
					if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7) &&(ordersList.size()==1)) {
478
						if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty() 
479
								|| order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
480
							if(withBill){
481
								PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
482
								taxTable.setSpacingBefore(5.0f);
483
								taxTable.setWidthPercentage(90.0f);
484
								document.add(new DottedLineSeparator());
485
								document.add(taxTable);
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
							}
8303 amar.kumar 493
						} else {
13276 manish.sha 494
							document.newPage();
8303 amar.kumar 495
						}
13276 manish.sha 496
					} else if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue() &&(ordersList.size()==1)) {
8303 amar.kumar 497
						if(withBill){
13276 manish.sha 498
							PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
8303 amar.kumar 499
							taxTable.setSpacingBefore(5.0f);
500
							taxTable.setWidthPercentage(90.0f);
501
							document.add(new DottedLineSeparator());
502
							document.add(taxTable);
503
						}else{
504
							PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
505
							extraInfoTable.setSpacingBefore(5.0f);
506
							extraInfoTable.setWidthPercentage(90.0f);
507
							document.add(new DottedLineSeparator());
508
							document.add(extraInfoTable);
509
						}
510
					}
8488 amar.kumar 511
					if(withBill){
13276 manish.sha 512
						PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
8488 amar.kumar 513
						taxTable.setSpacingBefore(5.0f);
514
						taxTable.setWidthPercentage(90.0f);
515
						document.add(new DottedLineSeparator());
516
						document.add(taxTable);
13276 manish.sha 517
						if(order.getSource() == OrderSource.FLIPKART.getValue()) {
518
							//document.add(new DottedLineSeparator());
519
							document.add(getFlipkartBarCodes(order));
520
						}
521
 
8488 amar.kumar 522
					}else{
523
						PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
524
						extraInfoTable.setSpacingBefore(5.0f);
525
						extraInfoTable.setWidthPercentage(90.0f);
526
						document.add(new DottedLineSeparator());
527
						document.add(extraInfoTable);
528
					}
13276 manish.sha 529
 
530
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
531
						PdfPTable orderItemsDetailTable = new PdfPTable(1);
532
						orderItemsDetailTable.setWidthPercentage(90.0f);
533
						orderItemsDetailTable.setSpacingBefore(5.0f);
13313 manish.sha 534
						orderItemsDetailTable.addCell(new Phrase("SubOrder Ids :", helveticaBold8));
13276 manish.sha 535
						StringBuffer sbOrders = new StringBuffer();
536
 
537
						for(Order o1 : orders){
538
							sbOrders.append(o1.getId()+",");
539
						}
540
 
541
 
542
						String orderIds = sbOrders.toString();
543
						orderIds = orderIds.substring(0, orderIds.length()-1);
544
 
545
						orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
546
						orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
547
 
548
						StringBuffer sbImeis = new StringBuffer();
549
 
550
						for(Order o1 : orders){
551
							if(o1.getLineitems().get(0).getSerial_number()!=null){
552
								sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
553
							}
554
						}
555
 
556
						String imeis = sbImeis.toString();
557
						imeis = imeis.substring(0, imeis.length()-1);
558
 
559
						orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
560
 
561
						document.add(new DottedLineSeparator());
562
						document.add(orderItemsDetailTable);
9009 amar.kumar 563
					}
13276 manish.sha 564
					document.newPage();
7014 rajveer 565
				}
566
			}
13276 manish.sha 567
 
568
 
569
 
7014 rajveer 570
			document.close();
571
			baosPDF.close();
572
			// Adding facility to store the bill on the local directory. This will happen for only for Mahipalpur warehouse.
573
			if(withBill && !printAll){
7079 rajveer 574
				String strOrderId = StringUtils.repeat("0", 10-String.valueOf(orderId).length()) + orderId;  
7014 rajveer 575
				String dirPath = "/SaholicInvoices" + File.separator + strOrderId.substring(0, 2) + File.separator + strOrderId.substring(2, 4) + File.separator + strOrderId.substring(4, 6);
576
				String filename = dirPath + File.separator + orderId + ".pdf";
577
				File dirFile = new File(dirPath);
578
				if(!dirFile.exists()){
579
					dirFile.mkdirs();
580
				}
581
				File f = new File(filename);
582
				FileOutputStream fos = new FileOutputStream(f);
583
				baosPDF.writeTo(fos);
584
			}
585
		} catch (Exception e) {
586
			logger.error("Error while generating Invoice: ", e);
587
		}
588
		return baosPDF;
589
	}
3065 chandransh 590
 
13276 manish.sha 591
	private PdfPTable getDispatchAdviceTable(List<Order> orderList, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode, boolean withBill, Warehouse shippingLocation, String invoiceFormat){
592
		Order order = orderList.get(0);
7014 rajveer 593
		Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
13276 manish.sha 594
 
595
		double totalAmount = 0.0;
596
		double totalWeight = 0.0;
597
 
598
		for (Order o: orderList){
13313 manish.sha 599
			totalAmount = totalAmount + o.getTotal_amount()-o.getGvAmount()-o.getAdvanceAmount();
13276 manish.sha 600
			totalWeight = totalWeight + o.getTotal_weight();
601
		}
2787 chandransh 602
 
7014 rajveer 603
		PdfPTable table = new PdfPTable(1);
604
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 605
 
606
		PdfPTable titleBarTable = new PdfPTable(new float[]{0.4f, 0.4f, 0.2f});
8107 manish.sha 607
		titleBarTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 608
 
8103 manish.sha 609
		PdfPTable logoTable = new PdfPTable(2);
610
		addLogoTable(logoTable,order); 
7318 rajveer 611
 
7014 rajveer 612
		PdfPCell titleCell = getTitleCell();
613
		PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false);
13276 manish.sha 614
		PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont, totalWeight);
2787 chandransh 615
 
7014 rajveer 616
		PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
617
		dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
618
		dispatchTable.addCell(customerTable);
619
		dispatchTable.addCell(new Phrase(" "));
620
		dispatchTable.addCell(providerInfoTable);
2787 chandransh 621
 
13276 manish.sha 622
		PdfPTable invoiceTable = getTopInvoiceTable(orderList, shippingLocation.getTinNumber(), invoiceFormat);
8110 manish.sha 623
		PdfPTable addressTable = new PdfPTable(1);
624
		addressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
625
		addressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
626
 
7014 rajveer 627
		PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
8169 manish.sha 628
				" - " + shippingLocation.getPincode() + "\nContact No.- 0120-2479977" + "\n\n");
2787 chandransh 629
 
7014 rajveer 630
		PdfPTable chargesTable = new PdfPTable(1);
631
		chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
632
		chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
633
		if(order.isLogisticsCod()){
13276 manish.sha 634
			chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (totalAmount), helveticaBold12));
7014 rajveer 635
			chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
7994 manish.sha 636
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
637
			if(order.getLogistics_provider_id()==7L){
638
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
639
				String fedexCodReturnBarcode = "";
8080 manish.sha 640
				String fedexCodReturnTrackingId = "";
7994 manish.sha 641
				try {
642
					fedexCodReturnBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_BarCode");
8080 manish.sha 643
					fedexCodReturnTrackingId = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_Tracking_No");
7994 manish.sha 644
				} catch (TException e1) {
645
					logger.error("Error while getting the provider information.", e1);
646
				}
8080 manish.sha 647
				PdfPCell formIdCell= new PdfPCell(new Paragraph("COD Return "+fedexCodReturnTrackingId+" Form id-0325", helvetica6));
8104 manish.sha 648
				formIdCell.setPaddingTop(2.0f);
7994 manish.sha 649
				formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
650
				formIdCell.setBorder(Rectangle.NO_BORDER);
651
				chargesTable.addCell(new Phrase("PRIORITY OVERNIGHT ", helvetica8));
652
				chargesTable.addCell(formIdCell);
8035 manish.sha 653
 
8067 manish.sha 654
				generateBarcode(fedexCodReturnBarcode, "fedex_codr_"+order.getId());
8037 manish.sha 655
 
8067 manish.sha 656
				Image barcodeImage=null;
657
				try {
658
					barcodeImage = Image.getInstance("/tmp/"+"fedex_codr_"+order.getId()+".png");
659
				} catch (Exception e) {
660
					logger.error("Exception during getting Barcode Image for Fedex : ", e);
661
				}
662
 
8173 manish.sha 663
				PdfPTable codReturnTable = new PdfPTable(new float[]{0.6f,0.4f});
664
				codReturnTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
665
				codReturnTable.addCell(barcodeImage);
666
				codReturnTable.addCell(new Phrase(" "));
667
				chargesTable.addCell(codReturnTable);
668
 
7994 manish.sha 669
			}
670
			//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 671
		} else {
672
			chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
673
		}
8080 manish.sha 674
 
675
		if(order.getLogistics_provider_id()==7L){
676
			chargesTable.addCell(new Phrase("Term and Condition:- Subject to the Conditions of Carriage which " +
677
					"limits the liability of FedEx for loss, delay or damage to the consignment." +
678
					" Visit http://www.fedex.com/in/domestic/services/terms to view the conitions of Carriage" ,
8082 manish.sha 679
					new Font(FontFamily.TIMES_ROMAN, 8f)));
8080 manish.sha 680
		}
10310 amar.kumar 681
 
8110 manish.sha 682
		addressTable.addCell(new Phrase("If undelivered, return to:", helvetica10));
683
		addressTable.addCell(addressCell);
684
 
7014 rajveer 685
		PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
686
		addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8110 manish.sha 687
		addressAndNoteTable.addCell(addressTable);
7014 rajveer 688
		addressAndNoteTable.addCell(chargesTable);
2787 chandransh 689
 
8106 manish.sha 690
		titleBarTable.addCell(logoTable);
691
		titleBarTable.addCell(titleCell);
692
		titleBarTable.addCell(" ");
693
 
694
		table.addCell(titleBarTable);
7014 rajveer 695
		table.addCell(dispatchTable);
696
		table.addCell(invoiceTable);
697
		table.addCell(addressAndNoteTable);
698
		return table;
699
	}
2787 chandransh 700
 
8103 manish.sha 701
	private void addLogoTable(PdfPTable logoTable,Order order) {
7318 rajveer 702
		logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
703
		logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
704
		logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
8096 manish.sha 705
 
7318 rajveer 706
		PdfPCell logoCell;
707
		String logoPath;
8102 manish.sha 708
 
7556 rajveer 709
		if(order.getSource() == OrderSource.STORE.getValue()){
710
			logoCell = new PdfPCell(new Phrase(""));
711
 
712
		}else{
8102 manish.sha 713
			logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
8094 manish.sha 714
 
7318 rajveer 715
			try {
716
				logoCell = new PdfPCell(Image.getInstance(logoPath), false);
717
			} catch (Exception e) {
718
				//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
719
				logger.warn("Couldn't load the Saholic logo: ", e);
720
				logoCell = new PdfPCell(new Phrase("Saholic Logo"));
721
			}
722
 
723
		}
8090 manish.sha 724
		logoCell.setBorder(Rectangle.NO_BORDER);
725
		logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
8102 manish.sha 726
		logoTable.addCell(logoCell);
727
		logoTable.addCell(" ");
8103 manish.sha 728
 
7318 rajveer 729
	}
730
 
7014 rajveer 731
	private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
732
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
733
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
734
		ttfFontFactory.register(fontPath, "barcode");
735
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
736
		return barCodeFont;
737
	}
2787 chandransh 738
 
7014 rajveer 739
	private PdfPCell getTitleCell() {
740
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
741
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
742
		titleCell.setBorder(Rectangle.NO_BORDER);
743
		return titleCell;
744
	}
2787 chandransh 745
 
13276 manish.sha 746
	private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont, double totalWeight) {
7014 rajveer 747
		PdfPTable providerInfoTable = new PdfPTable(1);
748
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7318 rajveer 749
		if(order.isLogisticsCod()){
8551 manish.sha 750
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica22));
7318 rajveer 751
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
752
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
753
			providerInfoTable.addCell(deliveryTypeCell);
754
		}
755
 
8035 manish.sha 756
 
7014 rajveer 757
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
758
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
759
		providerNameCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 760
		PdfPCell formIdCell= null;
761
		if(order.getLogistics_provider_id()==7L){
762
			if(order.isCod()){
8034 manish.sha 763
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
7994 manish.sha 764
			}
765
			else{
8034 manish.sha 766
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
7994 manish.sha 767
			}
8551 manish.sha 768
			formIdCell.setPaddingTop(1.0f);
8015 rajveer 769
			formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
770
			formIdCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 771
		}
8015 rajveer 772
 
7994 manish.sha 773
 
774
		PdfPCell awbNumberCell= null;
8034 manish.sha 775
		String fedexPackageBarcode = "";
7994 manish.sha 776
		if(order.getLogistics_provider_id()!=7L){
777
			awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
8017 manish.sha 778
			awbNumberCell.setPaddingTop(20.0f);
7994 manish.sha 779
		}
780
		else{
8013 rajveer 781
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
782
			try {
783
				fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
784
			} catch (TException e1) {
785
				logger.error("Error while getting the provider information.", e1);
786
			}
8174 manish.sha 787
			awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
788
		}
789
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
790
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
791
 
792
		providerInfoTable.addCell(providerNameCell);
793
		if(formIdCell != null){
794
			providerInfoTable.addCell(formIdCell);
795
		}
796
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
797
		if(order.getLogistics_provider_id()==7L){
8169 manish.sha 798
			generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
799
 
800
			Image barcodeImage=null;
801
			try {
802
				barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
803
			} catch (Exception e) {
804
				logger.error("Exception during getting Barcode Image for Fedex : ", e);
805
			}
8174 manish.sha 806
			providerInfoTable.addCell(barcodeImage);
7994 manish.sha 807
		}
8174 manish.sha 808
		providerInfoTable.addCell(awbNumberCell);
7014 rajveer 809
 
7792 anupam.sin 810
		Warehouse warehouse = null;
811
		try{
812
    		InventoryClient isc = new InventoryClient();
7804 amar.kumar 813
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
7803 amar.kumar 814
		} catch(Exception e) {
7792 anupam.sin 815
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
7805 amar.kumar 816
		    //TODO throw e;
7792 anupam.sin 817
		}
818
		DeliveryType dt =  DeliveryType.PREPAID;
819
        if (order.isLogisticsCod()) {
820
            dt = DeliveryType.COD;
821
        }
7994 manish.sha 822
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
823
        if(order.getLogistics_provider_id()!=7L){
824
	        for (ProviderDetails detail : provider.getDetails()) {
825
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
826
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
827
	            }
828
	        }
7792 anupam.sin 829
        }
7994 manish.sha 830
        else{
831
        	providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
832
        }
833
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 834
		Date awbDate;
835
		if(order.getBilling_timestamp() == 0){
836
			awbDate = new Date();
837
		}else{
838
			awbDate = new Date(order.getBilling_timestamp());
839
		}
8106 manish.sha 840
		if(order.getLogistics_provider_id()!=7L){
841
			providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
842
		}
7014 rajveer 843
		providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
8182 amar.kumar 844
		if(order.getSource() == OrderSource.EBAY.getValue()){
845
			EbayOrder ebayOrder = null;
846
			try {
847
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
848
			} catch (TException e) {
849
				logger.error("Error while getting ebay order", e);
850
			}
851
			providerInfoTable.addCell(new Phrase("PaisaPayId            : " + ebayOrder.getPaisaPayId(), helvetica8));
852
			providerInfoTable.addCell(new Phrase("Sales Rec Number: " + ebayOrder.getSalesRecordNumber(), helvetica8));
853
		}
7994 manish.sha 854
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
855
		if(order.getLogistics_provider_id()==7L){
856
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
857
		}
858
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 859
		return providerInfoTable;
860
	}
861
 
13276 manish.sha 862
	private PdfPTable getTopInvoiceTable(List<Order> orderList, String tinNo, String invoiceFormat){
7014 rajveer 863
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
864
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
865
 
13276 manish.sha 866
		invoiceTable.addCell(getInvoiceTableHeader(6,orderList.get(0).getLogisticsTransactionId()));
867
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
868
			invoiceTable.addCell(new Phrase("Sr No", helvetica8));
869
		}else{
870
			invoiceTable.addCell(new Phrase("Order No", helvetica8));
871
		}
7014 rajveer 872
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
873
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
874
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
875
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
876
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
13276 manish.sha 877
		double totalAmount = 0.0;
878
		double insuranceAmount = 0.0;
879
		double advanceAmount = 0.0;
880
 
881
 
882
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
883
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
884
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
885
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
886
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
887
			String paymentMode = "";
888
			for(Order order : orderList){
889
				LineItem lineitem = order.getLineitems().get(0);
890
				totalAmount = totalAmount + order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount();
891
				if(order.getInsurer() > 0) {
892
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
893
				}
894
				if(order.getSource() == OrderSource.STORE.getValue()) {
895
					advanceAmount = advanceAmount + order.getAdvanceAmount();
896
				}
897
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
898
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
899
				}
900
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
901
					itemRateMap.put(lineitem.getItem_id(), lineitem.getUnit_price());
902
				}
903
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
904
					double currentQuantity = itemQuantityMap.get(lineitem.getItem_id()) +lineitem.getQuantity();
905
					itemQuantityMap.put(lineitem.getItem_id(), currentQuantity);
906
				}else{
907
					itemQuantityMap.put(lineitem.getItem_id(), lineitem.getQuantity());
908
				}
909
 
910
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
911
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount());
912
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
913
				}else{
914
					itemTotalAmtMap.put(lineitem.getItem_id(), (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
915
				}
916
				if(paymentMode==null || paymentMode.isEmpty()){
917
					if(order.getPickupStoreId() > 0 && order.isCod() == true)
918
						paymentMode = "In-Store";
919
					else if (order.isCod())
920
						paymentMode = "COD";
921
					else
922
						paymentMode = "Prepaid";
923
				}		
924
			}
925
 
926
			int serialNo = 0;
927
			for(Long itemId : itemNamesMap.keySet()){
928
				serialNo ++;
929
				invoiceTable.addCell(new Phrase(serialNo+ "", helvetica8));
930
				invoiceTable.addCell(new Phrase(paymentMode, helvetica8));
931
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId), helvetica8));
932
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"", helvetica8));
933
				invoiceTable.addCell(new Phrase(itemRateMap.get(itemId)+"", helvetica8));
934
				invoiceTable.addCell(new Phrase(itemTotalAmtMap.get(itemId)+"", helvetica8));
935
			}
936
 
937
			if(insuranceAmount>0){
938
				invoiceTable.addCell(getInsuranceCell(4));
939
				invoiceTable.addCell(getPriceCell(insuranceAmount));
940
				invoiceTable.addCell(getPriceCell(insuranceAmount));
941
			}
942
			if(advanceAmount>0){
943
				invoiceTable.addCell(getAdvanceAmountCell(4));
944
				invoiceTable.addCell(getPriceCell(advanceAmount));
945
				invoiceTable.addCell(getPriceCell(advanceAmount));
946
			}
947
		}else{
948
			for(Order order : orderList){
949
				populateTopInvoiceTable(order, invoiceTable);
950
				if(order.getInsurer() > 0) {
951
					invoiceTable.addCell(getInsuranceCell(4));
952
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
953
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
954
				}
7014 rajveer 955
 
13276 manish.sha 956
				if(order.getSource() == OrderSource.STORE.getValue()) {
957
					invoiceTable.addCell(getAdvanceAmountCell(4));
958
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
959
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
960
				}
961
				totalAmount = totalAmount + order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount();
962
			}
7014 rajveer 963
		}
7318 rajveer 964
 
7014 rajveer 965
		invoiceTable.addCell(getTotalCell(4));      
966
		invoiceTable.addCell(getRupeesCell());
13276 manish.sha 967
		invoiceTable.addCell(getTotalAmountCell(totalAmount));
968
 
7014 rajveer 969
 
970
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
971
		tinCell.setColspan(6);
972
		tinCell.setPadding(2);
973
		invoiceTable.addCell(tinCell);
974
 
975
		return invoiceTable;
976
	}
977
 
978
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
979
		List<LineItem> lineitems = order.getLineitems();
980
		for (LineItem lineitem : lineitems) {
981
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
982
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
983
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
984
			else if (order.isCod())
985
				invoiceTable.addCell(new Phrase("COD", helvetica8));
986
			else
987
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 988
 
7190 amar.kumar 989
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 990
 
7014 rajveer 991
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 992
 
7014 rajveer 993
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
994
 
995
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
996
		}
997
	}
998
 
999
	private PdfPCell getAddressCell(String address) {
1000
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
1001
		PdfPCell addressCell = new PdfPCell();
1002
		addressCell.addElement(addressParagraph);
1003
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1004
		addressCell.setBorder(Rectangle.NO_BORDER);
1005
		return addressCell;
1006
	}
1007
 
13276 manish.sha 1008
	private PdfPTable getTaxCumRetailInvoiceTable(List<Order> orderList, Provider provider, String ourAddress, String tinNo, String invoiceFormat){
1009
		Order order = orderList.get(0);
7014 rajveer 1010
		PdfPTable taxTable = new PdfPTable(1);
1011
		Phrase phrase = null;
1012
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1013
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
8104 manish.sha 1014
 
8110 manish.sha 1015
		PdfPTable logoTitleAndOurAddressTable = new PdfPTable(new float[]{0.4f, 0.3f, 0.3f});
8107 manish.sha 1016
		logoTitleAndOurAddressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8112 manish.sha 1017
		logoTitleAndOurAddressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
8107 manish.sha 1018
 
8110 manish.sha 1019
 
8103 manish.sha 1020
		PdfPTable logoTable = new PdfPTable(2);
1021
		addLogoTable(logoTable,order); 
7318 rajveer 1022
 
7014 rajveer 1023
		if (order.getOrderType().equals(OrderType.B2B)) {
1024
			phrase = new Phrase("TAX INVOICE", helveticaBold12);
1025
		} else {
1026
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1027
		}
1028
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
1029
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1030
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
1031
 
8169 manish.sha 1032
		Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- 0120-2479977" + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
7014 rajveer 1033
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
1034
		sorlAddressCell.addElement(sorlAddress);
8110 manish.sha 1035
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
7014 rajveer 1036
 
1037
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
1038
		PdfPTable orderDetails = getOrderDetails(order, provider);
1039
 
1040
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
1041
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1042
		addrAndOrderDetailsTable.addCell(customerAddress);
1043
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
1044
		addrAndOrderDetailsTable.addCell(orderDetails);
1045
 
9319 amar.kumar 1046
		boolean isVAT = isVatApplicable(order);
13276 manish.sha 1047
		PdfPTable invoiceTable = getBottomInvoiceTable(orderList, isVAT, invoiceFormat);
7014 rajveer 1048
 
10607 manish.sha 1049
		PdfPTable regAddAndDisCellTable = new PdfPTable(2);
1050
 
7014 rajveer 1051
		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));
1052
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1053
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
7318 rajveer 1054
 
10609 manish.sha 1055
		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 1056
		regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1057
		regAddressCell.setBorder(Rectangle.NO_BORDER);
1058
		/*SPICE ONLINE RETAIL PRIVATE LIMITED
1059
		Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
1060
		CIN: U74140DL2008PTC183856
1061
		Tel. No. 0120-2479977
1062
		E-mail. help@saholic.com
1063
		Website. www.saholic.com*/
9014 amar.kumar 1064
		PdfPCell powerTextCell = new PdfPCell(new Phrase("Powered By  Flipkart", helvetica8));
1065
		powerTextCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1066
		powerTextCell.setBorder(Rectangle.NO_BORDER);
1067
		powerTextCell.setPaddingBottom(30.0f);
8104 manish.sha 1068
 
1069
		logoTitleAndOurAddressTable.addCell(logoTable);
8110 manish.sha 1070
		logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
1071
		logoTitleAndOurAddressTable.addCell(sorlAddress);
8104 manish.sha 1072
 
10607 manish.sha 1073
		regAddAndDisCellTable.addCell(disclaimerCell);
1074
		regAddAndDisCellTable.addCell(regAddressCell);
1075
 
8104 manish.sha 1076
		taxTable.addCell(logoTitleAndOurAddressTable);
7014 rajveer 1077
		taxTable.addCell(addrAndOrderDetailsTable);
1078
		taxTable.addCell(invoiceTable);
10608 manish.sha 1079
		taxTable.addCell(regAddAndDisCellTable);
9014 amar.kumar 1080
		if(order.getSource() == OrderSource.FLIPKART.getValue()) {
1081
			taxTable.addCell(powerTextCell);
1082
 
1083
		}
10320 amar.kumar 1084
		if(order.getProductCondition().equals(ProductCondition.BAD)){
10328 amar.kumar 1085
			PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
10320 amar.kumar 1086
					"may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
1087
					"are not returnable, exchangeable or refundable under any circumstances. No " +
1088
					"warranty is assured on these items." ,
10329 amar.kumar 1089
					new Font(FontFamily.TIMES_ROMAN, 8f)));
10328 amar.kumar 1090
			badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1091
			badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
1092
			taxTable.addCell(badSaleDisclaimerCell);
10320 amar.kumar 1093
		}
7014 rajveer 1094
		return taxTable;
1095
	}
9009 amar.kumar 1096
 
9319 amar.kumar 1097
	private boolean isVatApplicable(Order order) {
1098
		if(order.getWarehouse_id() == 7) {
1099
			if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
1100
				return true;
1101
			} else {
1102
				return false;
1103
			}
12809 manish.sha 1104
		} else if(order.getWarehouse_id() == 3298){
1105
			for(int i=0; i< telanganaPincodes.length; i++) {
1106
				if(order.getCustomer_pincode().trim().equalsIgnoreCase(telanganaPincodes[i])) {
1107
					return true;
1108
				}
1109
			}
1110
			return false;
1111
		}
1112
		else {
9319 amar.kumar 1113
			for(int i=0; i< maharashtraPincodePrefix.length; i++) {
1114
				if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
1115
					return true;
1116
				}
1117
			}
1118
			return false;
1119
		}
1120
	}
1121
 
9037 amar.kumar 1122
	private PdfPTable getFlipkartBarCodes(Order order) {
1123
		PdfPTable flipkartTable = new PdfPTable(3);
1124
 
1125
		PdfPCell spacerCell = new PdfPCell();
9040 amar.kumar 1126
		spacerCell.setBorder(Rectangle.NO_BORDER);
9037 amar.kumar 1127
		spacerCell.setColspan(3);
9099 amar.kumar 1128
		spacerCell.setPaddingTop(330.0f);
9037 amar.kumar 1129
 
1130
		String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1131
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1132
		ttfFontFactory.register(flipkartCodeFontPath, "barcode");
1133
		Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
1134
 
9040 amar.kumar 1135
		String serialNumber = "0000000000";
9511 manish.sha 1136
		if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
9040 amar.kumar 1137
			serialNumber = order.getLineitems().get(0).getSerial_number();
9511 manish.sha 1138
		} else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
9040 amar.kumar 1139
			serialNumber = order.getLineitems().get(0).getItem_number();
1140
		}
1141
 
1142
		PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
9037 amar.kumar 1143
		serialNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1144
		serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1145
		serialNumberBarCodeCell.setPaddingTop(11.0f);
1146
 
1147
 
1148
		PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
1149
		invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1150
		invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1151
		invoiceNumberBarCodeCell.setPaddingTop(11.0f);
1152
 
1153
		double rate = order.getLineitems().get(0).getVatRate();
1154
		double salesTax = (rate * order.getTotal_amount())/(100 + rate);
9040 amar.kumar 1155
		PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
9037 amar.kumar 1156
		vatAmtBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1157
		vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1158
		vatAmtBarCodeCell.setPaddingTop(11.0f);
1159
 
1160
		flipkartTable.addCell(spacerCell);
1161
		flipkartTable.addCell(serialNumberBarCodeCell);
1162
		flipkartTable.addCell(invoiceNumberBarCodeCell);
1163
		flipkartTable.addCell(vatAmtBarCodeCell);
1164
 
1165
		return flipkartTable;
1166
 
9009 amar.kumar 1167
	}
1168
 
7014 rajveer 1169
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
1170
		PdfPTable customerTable = new PdfPTable(1);
1171
		customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1172
		if(forInvoce || order.getPickupStoreId() == 0){
1173
			customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1174
			customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1175
			customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1176
			customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
7994 manish.sha 1177
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1178
			if(order.getLogistics_provider_id()!=7L){
1179
				if(destCode != null)
1180
					customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1181
				else
1182
					customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1183
				}
1184
			else{
1185
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1186
				String fedexLocationcode = "";
1187
				try {
1188
					fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1189
				} catch (TException e1) {
1190
					logger.error("Error while getting the provider information.", e1);
1191
				}
1192
				customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1193
			}
1194
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
9100 amar.kumar 1195
			if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1196
				customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1197
			}
7014 rajveer 1198
		}else{
1199
			try {
5556 rajveer 1200
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 1201
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
1202
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
1203
				customerTable.addCell(new Phrase(store.getLine1(), font));
1204
				customerTable.addCell(new Phrase(store.getLine2(), font));
1205
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
1206
				if(destCode != null)
1207
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
1208
				else
1209
					customerTable.addCell(new Phrase(store.getPin(), font));
1210
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 1211
			} catch (TException e) {
1212
				// TODO Auto-generated catch block
1213
				e.printStackTrace();
1214
			}
5527 anupam.sin 1215
 
7014 rajveer 1216
		}
1217
 
1218
		if(order.getOrderType().equals(OrderType.B2B)) {
1219
			String tin = null;
1220
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1221
			List<Attribute> attributes;
1222
			try {
1223
				attributes = tclient.getAllAttributesForOrderId(order.getId());
1224
 
1225
				for(Attribute attribute : attributes) {
1226
					if(attribute.getName().equals("tinNumber")) {
1227
						tin = attribute.getValue();
1228
					}
1229
				}
1230
				if (tin != null) {
1231
					customerTable.addCell(new Phrase("TIN :" + tin, font));
1232
				}
1233
 
1234
			} catch (Exception e) {
1235
				logger.error("Error while getting order attributes", e);
1236
			}
1237
		}
1238
		/*
2787 chandransh 1239
        if(showPaymentMode){
1240
            customerTable.addCell(new Phrase(" ", font));
1241
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 1242
        }*/
7014 rajveer 1243
		return customerTable;
1244
	}
2787 chandransh 1245
 
7014 rajveer 1246
	private PdfPTable getOrderDetails(Order order, Provider provider){
1247
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
1248
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 1249
 
7014 rajveer 1250
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
1251
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 1252
 
7014 rajveer 1253
		orderTable.addCell(new Phrase("Date:", helvetica8));
1254
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1255
 
12590 amit.gupta 1256
		if(order.getSource() == OrderSource.AMAZON.getValue() || order.getSource() == OrderSource.JUNGLEE.getValue()){
7528 rajveer 1257
			AmazonOrder aorder = null;
1258
			try {
1259
				aorder = tsc.getClient().getAmazonOrder(order.getId());
1260
			} catch (TException e) {
1261
				logger.error("Error while getting amazon order", e);
1262
			}
12590 amit.gupta 1263
			if(order.getSource() == OrderSource.JUNGLEE.getValue()){
1264
				orderTable.addCell(new Phrase("Junglee Order ID:", helvetica8));
1265
			}else {
1266
				orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
1267
			}
7528 rajveer 1268
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
8182 amar.kumar 1269
		} else if(order.getSource() == OrderSource.EBAY.getValue()){
1270
			EbayOrder ebayOrder = null;
1271
			try {
1272
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1273
			} catch (TException e) {
1274
				logger.error("Error while getting ebay order", e);
1275
			}
1276
			orderTable.addCell(new Phrase("PaisaPayId:", helvetica8));
1277
			orderTable.addCell(new Phrase(ebayOrder.getPaisaPayId(), helvetica8));
1278
			orderTable.addCell(new Phrase("Sales Rec Number:", helvetica8));
1279
			orderTable.addCell(new Phrase(new Long(ebayOrder.getSalesRecordNumber()).toString(), helvetica8));
8488 amar.kumar 1280
		} else if(order.getSource() == OrderSource.SNAPDEAL.getValue()){
1281
			SnapdealOrder snapdealOrder = null;
1282
			try {
11424 kshitij.so 1283
				snapdealOrder = tsc.getClient().getSnapdealOrder(order.getId(), null, null).get(0);
8488 amar.kumar 1284
			} catch (TException e) {
1285
				logger.error("Error while getting snapdeal order", e);
1286
			}
1287
			orderTable.addCell(new Phrase("Snapdeal OrderId:", helvetica8));
1288
			orderTable.addCell(new Phrase(new Long(snapdealOrder.getSubOrderId()).toString(), helvetica8));
8828 amar.kumar 1289
 
1290
			String refernceCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1291
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1292
			ttfFontFactory.register(refernceCodeFontPath, "barcode");
8876 amar.kumar 1293
			Font referenceCodeBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
8828 amar.kumar 1294
 
8874 amar.kumar 1295
			PdfPCell snapdealReferenceBarCodeCell = new PdfPCell(new Paragraph("*" +  snapdealOrder.getReferenceCode() + "*", referenceCodeBarCodeFont));
8828 amar.kumar 1296
			snapdealReferenceBarCodeCell.setBorder(Rectangle.NO_BORDER);
8876 amar.kumar 1297
			snapdealReferenceBarCodeCell.setPaddingTop(9.0f);
1298
			snapdealReferenceBarCodeCell.setColspan(2);
9042 amar.kumar 1299
			snapdealReferenceBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
8876 amar.kumar 1300
			//orderTable.addCell(new Phrase("Snapdeal ReferenceCode:", helvetica8));
8828 amar.kumar 1301
			orderTable.addCell(snapdealReferenceBarCodeCell);
1302
			//orderTable.addCell(new Phrase(snapdealOrder.getReferenceCode(), helvetica8));
7528 rajveer 1303
		}
8989 vikram.rag 1304
		else if(order.getSource() == OrderSource.FLIPKART.getValue()){
1305
			FlipkartOrder flipkartOrder = null;
1306
			try {
1307
				flipkartOrder = tsc.getClient().getFlipkartOrder(order.getId());
1308
			} catch (TException e) {
8996 amar.kumar 1309
				logger.error("Error while getting flipkart order", e);
8989 vikram.rag 1310
			}
1311
			orderTable.addCell(new Phrase("Flipkart OrderId:", helvetica8));
1312
			orderTable.addCell(new Phrase(flipkartOrder.getFlipkartOrderId(), helvetica8));
9037 amar.kumar 1313
 
1314
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1315
			String flipkartBarCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1316
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1317
			ttfFontFactory.register(flipkartBarCodeFontPath, "barcode");
9043 amar.kumar 1318
			Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 18);
9037 amar.kumar 1319
 
9043 amar.kumar 1320
			orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
9037 amar.kumar 1321
			PdfPCell flipkartOrderItemIdBarCodeCell = new PdfPCell(new Paragraph("*" +  new Long(flipkartOrder.getFlipkartSubOrderId()).toString() + "*", flipkartBarCodeFont));
1322
			flipkartOrderItemIdBarCodeCell.setBorder(Rectangle.NO_BORDER);
1323
			flipkartOrderItemIdBarCodeCell.setPaddingTop(9.0f);
9043 amar.kumar 1324
			//flipkartOrderItemIdBarCodeCell.setColspan(2);
1325
			//flipkartOrderItemIdBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1326
			orderTable.addCell(flipkartOrderItemIdBarCodeCell);
1327
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1328
			//orderTable.addCell(new Phrase(new Long(flipkartOrder.getFlipkartSubOrderId()).toString(), helvetica8));
8989 vikram.rag 1329
		}
1330
 
1331
 
7014 rajveer 1332
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
1333
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
13276 manish.sha 1334
 
1335
		if(OrderType.B2B==order.getOrderType()){
1336
			try {
1337
				String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
1338
				if(poRefVal!=null && poRefVal.length()>0){
1339
					orderTable.addCell(new Phrase("PO Ref:", helvetica8));
1340
					orderTable.addCell(new Phrase(poRefVal, helvetica8));
1341
				}
1342
 
1343
			} catch (TException e) {
1344
				logger.error("Error while getting amazon order", e);
1345
			}
1346
		}
2787 chandransh 1347
 
7014 rajveer 1348
		orderTable.addCell(new Phrase("Courier:", helvetica8));
1349
		orderTable.addCell(new Phrase(provider.getName(), helvetica8));
2787 chandransh 1350
 
9038 amar.kumar 1351
		if(order.getAirwaybill_no()!=null && !order.getAirwaybill_no().isEmpty()) {
1352
			orderTable.addCell(new Phrase("AWB No:", helvetica8));
1353
			orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
1354
		}
2787 chandransh 1355
 
7014 rajveer 1356
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
1357
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1358
 
7014 rajveer 1359
		return orderTable;
1360
	}
2787 chandransh 1361
 
13276 manish.sha 1362
	private PdfPTable getBottomInvoiceTable(List<Order> orderList,boolean isVAT, String invoiceFormat){
1363
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
7014 rajveer 1364
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 1365
 
13284 manish.sha 1366
		invoiceTable.addCell(getInvoiceTableHeader(8,orderList.get(0).getLogisticsTransactionId()));
4262 rajveer 1367
 
13276 manish.sha 1368
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1369
			invoiceTable.addCell(new Phrase("Sr No", helveticaBold8));
1370
		}else{
1371
			invoiceTable.addCell(new Phrase("Order No", helveticaBold8));
1372
		}
7014 rajveer 1373
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
1374
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
1375
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
1376
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
13276 manish.sha 1377
		invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
1378
		invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
1379
		invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));;
1380
		double totalAmount = 0.0;
1381
		double insuranceAmount = 0.0;
1382
		int i=1;
1383
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1384
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1385
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1386
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1387
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1388
			Map<Long, Double> itemTaxPercentageMap = new HashMap<Long, Double>();
1389
			Map<Long, Double> itemTaxValueMap = new HashMap<Long, Double>();
1390
 
1391
			for(Order order : orderList){
1392
				LineItem lineitem = order.getLineitems().get(0);
1393
 
1394
				double orderAmount = order.getTotal_amount();
1395
				double rate = lineitem.getVatRate();
1396
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1397
				totalAmount = totalAmount + orderAmount;
1398
				double itemPrice = lineitem.getUnit_price();
1399
				double showPrice = (100 * itemPrice)/(100 + rate);
1400
				double totalPrice = lineitem.getTotal_price();
1401
				double showTotalPrice = (100 * totalPrice)/(100 + rate);
1402
 
1403
				if(order.getInsurer() > 0) {
1404
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1405
				}
1406
 
1407
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1408
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1409
				}
1410
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1411
					double quantity = itemQuantityMap.get(lineitem.getItem_id()) + lineitem.getQuantity();
1412
					itemQuantityMap.put(lineitem.getItem_id(), quantity);
1413
				} else {
1414
					itemQuantityMap.put(lineitem.getItem_id(),lineitem.getQuantity());
1415
				}
1416
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1417
					itemRateMap.put(lineitem.getItem_id(), showPrice);
1418
				}
1419
				if(!itemTaxPercentageMap.containsKey(lineitem.getItem_id())){
1420
					itemTaxPercentageMap.put(lineitem.getItem_id(), rate);
1421
				}
1422
				if(itemTaxValueMap.containsKey(lineitem.getItem_id())){
1423
					double taxValue = itemTaxValueMap.get(lineitem.getItem_id()) + salesTax;
1424
					itemTaxValueMap.put(lineitem.getItem_id(), taxValue);
1425
				}else{
1426
					itemTaxValueMap.put(lineitem.getItem_id(), salesTax);
1427
				}
1428
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
1429
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + showTotalPrice;
1430
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1431
				}else{
1432
					itemTotalAmtMap.put(lineitem.getItem_id(), showTotalPrice);
1433
				}
1434
			}
1435
 
1436
			for(Long itemId : itemNamesMap.keySet()){
1437
				invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
1438
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId),helvetica8));
1439
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"",helvetica8));
13285 manish.sha 1440
				invoiceTable.addCell(getPriceCell(itemRateMap.get(itemId)));
1441
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)));
1442
				invoiceTable.addCell(new Phrase(itemTaxPercentageMap.get(itemId)+"%",helvetica8));
1443
				invoiceTable.addCell(getPriceCell(itemTaxValueMap.get(itemId)));
1444
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)+itemTaxValueMap.get(itemId)));
13313 manish.sha 1445
				i++;
13276 manish.sha 1446
			}
1447
		}
1448
		else{
9432 amar.kumar 1449
 
13276 manish.sha 1450
			for(Order order :orderList){
1451
				LineItem lineItem = order.getLineitems().get(0);
1452
				double orderAmount = order.getTotal_amount();
1453
				double rate = lineItem.getVatRate();
1454
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1455
 
1456
				invoiceTable.addCell(new Phrase(order.getId()+"", helveticaBold8));
1457
				invoiceTable.addCell(getProductNameCell(lineItem, true, order.getFreebieItemId()));
1458
				invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
1459
 
1460
 
1461
				//populateBottomInvoiceTable(order, invoiceTable, rate);
1462
 
1463
				double itemPrice = lineItem.getUnit_price();
1464
				double showPrice = (100 * itemPrice)/(100 + rate);
1465
				invoiceTable.addCell(getPriceCell(showPrice));
1466
 
1467
				double totalPrice = lineItem.getTotal_price();
1468
				showPrice = (100 * totalPrice)/(100 + rate);
1469
				invoiceTable.addCell(getPriceCell(showPrice));
1470
 
1471
				PdfPCell salesTaxCell = getPriceCell(salesTax);
1472
 
1473
 
1474
				invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
1475
				invoiceTable.addCell(salesTaxCell);
1476
				invoiceTable.addCell(getTotalAmountCell(orderAmount));
1477
 
1478
				if(order.getInsurer() > 0) {
1479
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1480
				}
1481
				totalAmount = totalAmount+ orderAmount;
1482
				i++;
1483
			}
9432 amar.kumar 1484
		}
7014 rajveer 1485
 
13276 manish.sha 1486
		if(insuranceAmount>0){
1487
			invoiceTable.addCell(getInsuranceCell(7));
1488
			invoiceTable.addCell(getPriceCell(insuranceAmount));
7014 rajveer 1489
		}
1490
 
13276 manish.sha 1491
		invoiceTable.addCell(getTotalCell(6));
7014 rajveer 1492
		invoiceTable.addCell(getRupeesCell());
13276 manish.sha 1493
		invoiceTable.addCell(getTotalAmountCell(totalAmount));
7014 rajveer 1494
 
13276 manish.sha 1495
		invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
1496
		invoiceTable.addCell(getAmountInWordsCell(totalAmount));
7014 rajveer 1497
 
13276 manish.sha 1498
		invoiceTable.addCell(getEOECell(8));
7014 rajveer 1499
 
1500
		return invoiceTable;
1501
	}
1502
 
13276 manish.sha 1503
	private PdfPCell getInvoiceTableHeader(int colspan, String masterOrderId) {
1504
		PdfPTable invoiceHeaderTable = new PdfPTable(2);
1505
		PdfPCell masterOrderIdCell = new PdfPCell(new Phrase("Master Order Id- "+masterOrderId, helvetica10));
1506
		masterOrderIdCell.setBorder(Rectangle.NO_BORDER);
1507
		masterOrderIdCell.setPaddingTop(1);
13281 manish.sha 1508
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
7014 rajveer 1509
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
8551 manish.sha 1510
		invoiceTableHeader.setPaddingTop(1);
13276 manish.sha 1511
		invoiceHeaderTable.addCell(invoiceTableHeader);
1512
		invoiceHeaderTable.addCell(masterOrderIdCell);
13283 manish.sha 1513
		PdfPCell headerCell = new PdfPCell(invoiceHeaderTable);
1514
		headerCell.setColspan(colspan);
1515
		return headerCell;
7014 rajveer 1516
	}
1517
 
13276 manish.sha 1518
	/*private void populateBottomInvoiceTable(List<Order> orderList, PdfPTable invoiceTable) {
7014 rajveer 1519
		for (LineItem lineitem : order.getLineitems()) {
1520
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
1521
 
7190 amar.kumar 1522
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 1523
 
1524
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
1525
 
1526
			double itemPrice = lineitem.getUnit_price();
1527
			double showPrice = (100 * itemPrice)/(100 + rate);
1528
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
1529
 
1530
			double totalPrice = lineitem.getTotal_price();
1531
			showPrice = (100 * totalPrice)/(100 + rate);
1532
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
1533
		}
13276 manish.sha 1534
	}*/
7014 rajveer 1535
 
7190 amar.kumar 1536
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 1537
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 1538
		if(freebieItemId!=null && freebieItemId!=0){
1539
			try {
1540
				CatalogService.Client catalogClient = ctsc.getClient();
1541
				Item item = catalogClient.getItem(freebieItemId);
1542
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
1543
			} catch(Exception tex) {
1544
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
1545
			}
1546
		}
7014 rajveer 1547
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
1548
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1549
		return productNameCell;
1550
	}
1551
 
1552
	private PdfPCell getPriceCell(double price) {
1553
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
1554
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1555
		return totalPriceCell;
1556
	}
1557
 
1558
	private PdfPCell getVATLabelCell(boolean isVAT) {
1559
		PdfPCell vatCell = null;
1560
		if(isVAT){
1561
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
1562
		} else {
1563
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
1564
		}
1565
		vatCell.setColspan(3);
1566
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1567
		return vatCell;
1568
	}
1569
 
9432 amar.kumar 1570
	private PdfPCell getCFORMLabelCell() {
1571
		PdfPCell cFormCell = null;
1572
		cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
1573
		cFormCell.setColspan(3);
1574
		cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1575
		return cFormCell;
1576
	}
1577
 
7318 rajveer 1578
	private PdfPCell getAdvanceAmountCell(int colspan) {
1579
		PdfPCell insuranceCell = null;
1580
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
1581
		insuranceCell.setColspan(colspan);
1582
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1583
		return insuranceCell;
1584
	}
1585
 
7014 rajveer 1586
	private PdfPCell getInsuranceCell(int colspan) {
1587
		PdfPCell insuranceCell = null;
13276 manish.sha 1588
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance. T&C Apply", helvetica8));
7014 rajveer 1589
		insuranceCell.setColspan(colspan);
1590
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1591
		return insuranceCell;
1592
	}
1593
 
1594
	private PdfPCell getEmptyCell(int colspan) {
1595
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
1596
		emptyCell.setColspan(colspan);
1597
		return emptyCell;
1598
	}
1599
 
1600
	private PdfPCell getTotalCell(int colspan) {
13276 manish.sha 1601
		PdfPCell totalCell = new PdfPCell(new Phrase("Grand Total", helveticaBold8));
7014 rajveer 1602
		totalCell.setColspan(colspan);
1603
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1604
		return totalCell;
1605
	}
1606
 
1607
	private PdfPCell getRupeesCell() {
1608
		PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
1609
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1610
		return rupeesCell;
1611
	}
1612
 
1613
	private PdfPCell getTotalAmountCell(double orderAmount) {
1614
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
1615
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1616
		return totalAmountCell;
1617
	}
1618
 
1619
	/**
1620
	 * This method uses ICU4J libraries to convert the given amount into words
1621
	 * of Indian locale.
1622
	 * 
1623
	 * @param orderAmount
1624
	 *            The amount to convert.
1625
	 * @return the string representation of the given amount.
1626
	 */
1627
	private PdfPCell getAmountInWordsCell(double orderAmount) {
1628
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
1629
		StringBuilder amountInWords = new StringBuilder("Rs. ");
1630
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
1631
		amountInWords.append(" and ");
1632
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
1633
		amountInWords.append(" paise");
1634
 
1635
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
1636
		amountInWordsCell.setColspan(4);
1637
		return amountInWordsCell;
1638
	}
1639
 
1640
	/**
1641
	 * Returns the item name to be displayed in the invoice table.
1642
	 * 
1643
	 * @param lineitem
1644
	 *            The line item whose name has to be displayed
1645
	 * @param appendIMEI
1646
	 *            Whether to attach the IMEI No. to the item name
1647
	 * @return The name to be displayed for the given line item.
1648
	 */
1649
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
1650
		StringBuffer itemName = new StringBuffer();
1651
		if(lineitem.getBrand()!= null)
1652
			itemName.append(lineitem.getBrand() + " ");
1653
		if(lineitem.getModel_name() != null)
1654
			itemName.append(lineitem.getModel_name() + " ");
1655
		if(lineitem.getModel_number() != null )
1656
			itemName.append(lineitem.getModel_number() + " ");
1657
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
1658
			itemName.append("("+lineitem.getColor()+")");
1659
		if(appendIMEI && lineitem.isSetSerial_number()){
1660
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
1661
		}
1662
 
1663
		return itemName.toString();
1664
	}
1665
 
1666
	/**
1667
	 * 
1668
	 * @param colspan
1669
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
1670
	 *         no. of columns
1671
	 */
1672
	private PdfPCell getEOECell(int colspan) {
1673
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
1674
		eoeCell.setColspan(colspan);
1675
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1676
		return eoeCell;
1677
	}
1678
 
1679
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
1680
		PdfPTable extraInfoTable = new PdfPTable(1);
1681
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1682
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1683
 
1684
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1685
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1686
		ttfFontFactory.register(fontPath, "barcode");
1687
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1688
 
1689
		PdfPCell extraInfoCell;
1690
		if(billingType == BillingType.EXTERNAL){
1691
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
1692
		}else{
1693
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
1694
		}
1695
 
1696
		extraInfoCell.setPaddingTop(20.0f);
1697
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1698
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1699
 
1700
		extraInfoTable.addCell(extraInfoCell);
1701
 
1702
 
1703
		return extraInfoTable;
1704
	}
1705
 
1706
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
1707
		PdfPTable extraInfoTable = new PdfPTable(1);
1708
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1709
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1710
 
1711
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1712
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1713
		ttfFontFactory.register(fontPath, "barcode");
1714
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1715
 
1716
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
1717
 
1718
		extraInfoCell.setPaddingTop(20.0f);
1719
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1720
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1721
 
1722
		extraInfoTable.addCell(extraInfoCell);
1723
 
1724
		return extraInfoTable;
1725
	}
8067 manish.sha 1726
 
1727
	private void generateBarcode(String barcodeString, String fileName){
1728
		Code128Bean bean = new Code128Bean();
7014 rajveer 1729
 
8067 manish.sha 1730
		final int dpi = 60;
1731
 
1732
		//Configure the barcode generator
1733
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
1734
		                                                 //width exactly one pixel
1735
		bean.setFontSize(bean.getFontSize()+1.0f);
1736
		bean.doQuietZone(false);
1737
 
1738
		try {
1739
			File outputFile = new File("/tmp/"+fileName+".png");
1740
			OutputStream out = new FileOutputStream(outputFile);
1741
 
1742
		    //Set up the canvas provider for monochrome PNG output 
1743
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
1744
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
1745
 
1746
		    //Generate the barcode
1747
		    bean.generateBarcode(canvas, barcodeString);
1748
 
1749
		    //Signal end of generation
1750
		    canvas.finish();
1751
		    out.close();
1752
 
1753
		} 
1754
		catch(Exception e){
1755
			logger.error("Exception during generating Barcode : ", e);
1756
		}
1757
	}
1758
 
7014 rajveer 1759
	public static void main(String[] args) throws IOException {
1760
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 1761
		long orderId = 356324;
1762
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 1763
		String userHome = System.getProperty("user.home");
1764
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
1765
		FileOutputStream fos = new FileOutputStream(f);
1766
		baos.writeTo(fos);
1767
		System.out.println("Invoice generated.");
1768
	}
2787 chandransh 1769
}