Subversion Repositories SmartDukaan

Rev

Rev 19964 | Rev 19973 | 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;
18875 manish.sha 11
import in.shop2020.model.v1.catalog.CatalogServiceException;
7190 amar.kumar 12
import in.shop2020.model.v1.catalog.Item;
6746 rajveer 13
import in.shop2020.model.v1.inventory.BillingType;
5948 mandeep.dh 14
import in.shop2020.model.v1.inventory.InventoryServiceException;
5945 mandeep.dh 15
import in.shop2020.model.v1.inventory.Warehouse;
7528 rajveer 16
import in.shop2020.model.v1.order.AmazonOrder;
5527 anupam.sin 17
import in.shop2020.model.v1.order.Attribute;
8182 amar.kumar 18
import in.shop2020.model.v1.order.EbayOrder;
13691 manish.sha 19
import in.shop2020.model.v1.order.HsOrder;
2787 chandransh 20
import in.shop2020.model.v1.order.LineItem;
21
import in.shop2020.model.v1.order.Order;
7318 rajveer 22
import in.shop2020.model.v1.order.OrderSource;
4361 rajveer 23
import in.shop2020.model.v1.order.OrderStatus;
5527 anupam.sin 24
import in.shop2020.model.v1.order.OrderType;
10310 amar.kumar 25
import in.shop2020.model.v1.order.ProductCondition;
8488 amar.kumar 26
import in.shop2020.model.v1.order.SnapdealOrder;
8996 amar.kumar 27
import in.shop2020.model.v1.order.FlipkartOrder;
9432 amar.kumar 28
import in.shop2020.model.v1.order.TaxType;
18530 manish.sha 29
import in.shop2020.model.v1.user.Address;
7190 amar.kumar 30
import in.shop2020.thrift.clients.CatalogClient;
3132 rajveer 31
import in.shop2020.thrift.clients.LogisticsClient;
32
import in.shop2020.thrift.clients.TransactionClient;
2787 chandransh 33
import in.shop2020.thrift.clients.config.ConfigClient;
5948 mandeep.dh 34
import in.shop2020.thrift.clients.InventoryClient;
18530 manish.sha 35
import in.shop2020.thrift.clients.UserClient;
2787 chandransh 36
 
8067 manish.sha 37
import java.awt.image.BufferedImage;
2787 chandransh 38
import java.io.ByteArrayOutputStream;
39
import java.io.File;
40
import java.io.FileOutputStream;
41
import java.io.IOException;
8067 manish.sha 42
import java.io.OutputStream;
2787 chandransh 43
import java.text.DateFormat;
44
import java.text.DecimalFormat;
19950 amit.gupta 45
import java.text.SimpleDateFormat;
4361 rajveer 46
import java.util.ArrayList;
2787 chandransh 47
import java.util.Date;
13276 manish.sha 48
import java.util.HashMap;
2787 chandransh 49
import java.util.List;
50
import java.util.Locale;
13276 manish.sha 51
import java.util.Map;
2787 chandransh 52
 
53
import javax.servlet.ServletException;
54
import javax.servlet.ServletOutputStream;
55
import javax.servlet.http.HttpServlet;
56
import javax.servlet.http.HttpServletRequest;
57
import javax.servlet.http.HttpServletResponse;
58
 
7014 rajveer 59
import org.apache.commons.lang.StringUtils;
2787 chandransh 60
import org.apache.commons.lang.WordUtils;
61
import org.apache.thrift.TException;
8067 manish.sha 62
import org.krysalis.barcode4j.impl.code128.Code128Bean;
63
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
64
import org.krysalis.barcode4j.tools.UnitConv;
2787 chandransh 65
import org.slf4j.Logger;
66
import org.slf4j.LoggerFactory;
67
 
68
import com.ibm.icu.text.RuleBasedNumberFormat;
69
 
70
import com.itextpdf.text.Document;
71
import com.itextpdf.text.Element;
72
import com.itextpdf.text.Font;
73
import com.itextpdf.text.FontFactory;
74
import com.itextpdf.text.FontFactoryImp;
75
import com.itextpdf.text.Image;
18875 manish.sha 76
import com.itextpdf.text.PageSize;
2787 chandransh 77
import com.itextpdf.text.Paragraph;
78
import com.itextpdf.text.Phrase;
79
import com.itextpdf.text.Rectangle;
80
import com.itextpdf.text.Font.FontFamily;
8034 manish.sha 81
import com.itextpdf.text.pdf.Barcode128;
2787 chandransh 82
import com.itextpdf.text.pdf.BaseFont;
8037 manish.sha 83
import com.itextpdf.text.pdf.PdfContentByte;
2787 chandransh 84
import com.itextpdf.text.pdf.PdfPCell;
85
import com.itextpdf.text.pdf.PdfPTable;
86
import com.itextpdf.text.pdf.PdfWriter;
87
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
88
 
89
@SuppressWarnings("serial")
90
public class InvoiceServlet extends HttpServlet {
7014 rajveer 91
 
92
	private static Logger logger = LoggerFactory.getLogger(InvoiceServlet.class);
19958 amit.gupta 93
	public static long cutoffTime = 0;
19950 amit.gupta 94
 
95
	static {
96
		try {
97
		String cutOffDate = ConfigClient.getClient().get("warehouse_company_cutoff_date");
19965 amit.gupta 98
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
19950 amit.gupta 99
		cutoffTime = df.parse(cutOffDate).getTime();
100
		} catch(Exception e) {
101
			logger.info("Could not read cutoff time");
102
		}
103
	}
7014 rajveer 104
	@Override
105
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
106
		long orderId = Long.parseLong(request.getParameter("id"));
13276 manish.sha 107
		String logisticsTxnId  = request.getParameter("logisticsTxnId");
7014 rajveer 108
		long warehouseId = Long.parseLong(request.getParameter("warehouse"));
109
		boolean withBill = false;
110
		boolean printAll = false;
111
		try {
112
			withBill = Boolean.parseBoolean(request.getParameter("withBill"));
113
		} catch(Exception e){
114
			logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
115
		}
116
		try {
117
			printAll = Boolean.parseBoolean(request.getParameter("printAll"));
118
		} catch(Exception e){
119
			logger.warn("Couldn't infer whether bill should be printed. Not printing the bill.", e);
120
		}
121
 
13276 manish.sha 122
		if(logisticsTxnId!=null && !logisticsTxnId.isEmpty()){
123
			logger.info("Printing invoice for master order id: " + logisticsTxnId);
124
		}else{
125
			logger.info("Printing invoice for order id: " + orderId);
126
		}
8182 amar.kumar 127
 
8194 amar.kumar 128
		ByteArrayOutputStream baos = null;
8182 amar.kumar 129
 
130
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
131
		baos = invoiceGenerationService.generateInvoice(orderId, withBill, printAll, warehouseId);
7014 rajveer 132
 
133
		response.setContentType("application/pdf");
13276 manish.sha 134
		if(logisticsTxnId!=null && !logisticsTxnId.isEmpty()){
135
			response.setHeader("Content-disposition", "inline; filename=invoice-"+logisticsTxnId+".pdf" );
136
		} else {
137
			response.setHeader("Content-disposition", "inline; filename=invoice-"+orderId+".pdf" );
138
		}
7014 rajveer 139
 
140
		ServletOutputStream sos;
141
		try {
142
			sos = response.getOutputStream();
143
			baos.writeTo(sos);
144
			sos.flush();
145
		} catch (IOException e) {
146
			logger.error("Encountered error while sending invoice response: ", e);
147
		}
148
	}
2787 chandransh 149
}
150
 
151
class InvoiceGenerationService {
152
 
7014 rajveer 153
	private static Logger logger = LoggerFactory.getLogger(InvoiceGenerationService.class);
2787 chandransh 154
 
7014 rajveer 155
	private TransactionClient tsc = null;
156
	private InventoryClient csc = null;
157
	private LogisticsClient lsc = null;
7190 amar.kumar 158
	private CatalogClient ctsc = null;
18530 manish.sha 159
	private UserClient usc = null;
2787 chandransh 160
 
7014 rajveer 161
	private static Locale indianLocale = new Locale("en", "IN");
19950 amit.gupta 162
	private static String SORPL = "Spice Online Retail Pvt Ltd";
19957 amit.gupta 163
	private static String NEWCOMP = "Spice & Online Retail Pvt Ltd";
7014 rajveer 164
	private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");
19260 manish.sha 165
	private DecimalFormat weightFormat = new DecimalFormat("#0.000");
2787 chandransh 166
 
7994 manish.sha 167
	//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
168
	private static final Font helvetica6 = FontFactory.getFont(FontFactory.HELVETICA, 6);
7995 manish.sha 169
	//End:-Added By Manish Sharma for FedEx Integration  - Shipment Creation on 21-Aug-2013
7014 rajveer 170
	private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
171
	private static final Font helvetica10 = FontFactory.getFont(FontFactory.HELVETICA, 10);
172
	private static final Font helvetica12 = FontFactory.getFont(FontFactory.HELVETICA, 12);
173
	private static final Font helvetica16 = FontFactory.getFont(FontFactory.HELVETICA, 16);
8551 manish.sha 174
	private static final Font helvetica22 = FontFactory.getFont(FontFactory.HELVETICA, 22);
2787 chandransh 175
 
7014 rajveer 176
	private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
177
	private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);
178
 
179
	private static final String delhiPincodePrefix = "11";
9319 amar.kumar 180
	private static final String[] maharashtraPincodePrefix = {"40", "41", "42", "43", "44"};
16196 manish.sha 181
	private static final String[] karnatakaPincodePrefix = {"56", "57", "58", "59"};
12809 manish.sha 182
	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"};
18657 manish.sha 183
	private Address billingAddress;
19950 amit.gupta 184
	private String companyName=NEWCOMP;
7014 rajveer 185
 
186
	public InvoiceGenerationService() {
187
		try {
188
			tsc = new TransactionClient();
189
			csc = new InventoryClient();
190
			lsc = new LogisticsClient();
7190 amar.kumar 191
			ctsc = new CatalogClient();
18530 manish.sha 192
			usc = new UserClient();
7014 rajveer 193
		} catch (Exception e) {
194
			logger.error("Error while instantiating thrift clients.", e);
195
		}
196
	}
197
 
198
	public ByteArrayOutputStream generateInvoice(long orderId, boolean withBill, boolean printAll, long warehouseId) {
199
		ByteArrayOutputStream baosPDF = null;
200
		in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
201
		in.shop2020.model.v1.inventory.InventoryService.Client iclient = csc.getClient();
202
		in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
18875 manish.sha 203
 
19958 amit.gupta 204
		//Sort out all variables related to company date here
205
 
7014 rajveer 206
		try {
207
			baosPDF = new ByteArrayOutputStream();
208
 
209
			Document document = new Document();
8039 manish.sha 210
			PdfWriter.getInstance(document, baosPDF);
7014 rajveer 211
			document.addAuthor("shop2020");
212
			//document.addTitle("Invoice No: " + order.getInvoice_number());
213
			document.open();
13276 manish.sha 214
			//document.bo
7014 rajveer 215
 
216
			List<Order> orders = new ArrayList<Order>();
13276 manish.sha 217
			Map<String, List<Order>> logisticsTxnIdOrdersMap = new HashMap<String, List<Order>>();
7014 rajveer 218
			if(printAll){
219
				try {
220
					List<OrderStatus> statuses = new ArrayList<OrderStatus>();
221
					statuses.add(OrderStatus.ACCEPTED);
13276 manish.sha 222
					if(!tclient.isAlive()){
223
						tclient = tsc.getClient();
224
					}
7014 rajveer 225
					orders = tclient.getAllOrders(statuses, 0, 0, warehouseId);
13276 manish.sha 226
					for(Order o:orders){
227
						if(o.isSetLogisticsTransactionId()){
228
							if(logisticsTxnIdOrdersMap.containsKey(o.getLogisticsTransactionId())){
229
								List<Order> groupOrdersList = logisticsTxnIdOrdersMap.get(o.getLogisticsTransactionId());
230
								groupOrdersList.add(o);
231
								logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
232
							}else {
233
								List<Order> groupOrdersList = new ArrayList<Order>();
234
								groupOrdersList.add(o);
235
								logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
236
							}
237
						}
238
					}
7014 rajveer 239
				} catch (Exception e) {
240
					logger.error("Error while getting order information", e);
241
					return baosPDF; 
4361 rajveer 242
				}
7014 rajveer 243
			}else{
13276 manish.sha 244
				if(!tclient.isAlive()){
245
					tclient = tsc.getClient();
246
				}
247
				orders.add(tclient.getOrder(orderId));
248
				Order o = orders.get(0);
249
				if(o.isSetLogisticsTransactionId()){
250
					List<Order> groupOrdersList = tclient.getGroupOrdersByLogisticsTxnId(o.getLogisticsTransactionId());
251
					logisticsTxnIdOrdersMap.put(o.getLogisticsTransactionId(), groupOrdersList);
252
				}
7014 rajveer 253
			}
254
			boolean isFirst = true;
13276 manish.sha 255
			if(logisticsTxnIdOrdersMap!=null && logisticsTxnIdOrdersMap.size()>0){
256
				for(String logisticsTxnId : logisticsTxnIdOrdersMap.keySet()){
257
					List<Order> ordersList = logisticsTxnIdOrdersMap.get(logisticsTxnId);
258
					Order singleOrder = ordersList.get(0);
259
					Warehouse warehouse = null;
260
					Provider provider = null;
261
					String destCode = null;
262
					Warehouse shippingLocation = null;
263
					int barcodeFontSize = 0;
264
					String invoiceFormat = null;
265
					try {
19958 amit.gupta 266
						if(singleOrder.getWarehouse_id() == 7 && InvoiceServlet.cutoffTime > singleOrder.getBilling_timestamp() ){
267
							companyName = SORPL;
268
							warehouse = iclient.getWarehouse(7151);
269
						} else {
270
							warehouse = iclient.getWarehouse(singleOrder.getWarehouse_id());
271
						}
13276 manish.sha 272
						long providerId = singleOrder.getLogistics_provider_id();
273
						provider = logisticsClient.getProvider(providerId);
274
						if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
275
							destCode = provider.getPickup().toString();
276
						else
277
							destCode = logisticsClient.getDestinationCode(providerId, singleOrder.getCustomer_pincode());
5387 rajveer 278
 
13276 manish.sha 279
						barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
19958 amit.gupta 280
 
13276 manish.sha 281
						shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId());
282
						invoiceFormat = tclient.getInvoiceFormatLogisticsTxnId(singleOrder.getTransactionId(), Long.parseLong(logisticsTxnId.split("-")[1])); 
283
					} catch (InventoryServiceException ise) {
284
						logger.error("Error while getting the warehouse information.", ise);
285
						return baosPDF;
286
					} catch (LogisticsServiceException lse) {
287
						logger.error("Error while getting the provider information.", lse);
288
						return baosPDF;
289
					} catch (ConfigException ce) {
290
						logger.error("Error while getting the fontsize for the given provider", ce);
291
						return baosPDF;
292
					} catch (TException te) {
293
						logger.error("Error while getting some essential information from the services", te);
294
						return baosPDF;
295
					}
296
 
297
					if(printAll && warehouse.getBillingType() == BillingType.OURS_EXTERNAL){
298
						for(Order order : ordersList){
299
							if(isFirst){
19950 amit.gupta 300
								document.add(getFixedTextTable(16, companyName));
13276 manish.sha 301
								isFirst = false;
302
							}
303
							document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
304
							continue;
305
						}
306
					}
307
					PdfPTable dispatchAdviceTable = null;
308
					Order order = ordersList.get(0);
309
					if(ordersList.size()==1){					
310
						if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
311
							dispatchAdviceTable = new PdfPTable(1);
312
						}  else if(new Long(order.getSource()).intValue() == OrderSource.FLIPKART.getValue()) {
313
							dispatchAdviceTable = new PdfPTable(1);
13691 manish.sha 314
						}  else if(new Long(order.getSource()).intValue() == OrderSource.HOMESHOP18.getValue()) {
315
							dispatchAdviceTable = new PdfPTable(1);
13276 manish.sha 316
						}  else if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7)) {
317
							if(order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
318
								dispatchAdviceTable = new PdfPTable(1);
319
							} else { 
320
								if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty()) {
321
									dispatchAdviceTable = new PdfPTable(1);
322
								} else {
323
									EbayInvoiceGenerationService invoiceGenerationService = new EbayInvoiceGenerationService();
324
									dispatchAdviceTable = invoiceGenerationService.getDispatchAdviceTable(orderId, warehouseId);
325
								}
326
							}
327
						}
328
						else {
329
							dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
330
						}
331
					} else {
332
						dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
333
					}
334
 
335
					dispatchAdviceTable.setSpacingAfter(10.0f);
336
					dispatchAdviceTable.setWidthPercentage(90.0f);
337
					document.add(dispatchAdviceTable);
338
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
19516 manish.sha 339
						if(ordersList.size()>3 || (order.getLogistics_provider_id()==7 && (order.isLogisticsCod() || (!order.isLogisticsCod() && ordersList.size()>1))) 
340
								|| (order.getLogistics_provider_id()==46 && (order.isLogisticsCod() || (!order.isLogisticsCod() && ordersList.size()>1)))){
13320 manish.sha 341
							document.newPage();
342
						}
13276 manish.sha 343
					}
344
 
345
					if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7) &&(ordersList.size()==1)) {
346
						if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty() 
347
								|| order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
348
							if(withBill){
349
								PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
350
								taxTable.setSpacingBefore(5.0f);
351
								taxTable.setWidthPercentage(90.0f);
352
								document.add(new DottedLineSeparator());
353
								document.add(taxTable);
354
							}else{
355
								PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
356
								extraInfoTable.setSpacingBefore(5.0f);
357
								extraInfoTable.setWidthPercentage(90.0f);
358
								document.add(new DottedLineSeparator());
359
								document.add(extraInfoTable);
360
							}
361
						} else {
362
							document.newPage();
363
						}
364
					} else if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue() &&(ordersList.size()==1)) {
365
						if(withBill){
366
							PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
367
							taxTable.setSpacingBefore(5.0f);
368
							taxTable.setWidthPercentage(90.0f);
369
							document.add(new DottedLineSeparator());
370
							document.add(taxTable);
371
						}else{
372
							PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
373
							extraInfoTable.setSpacingBefore(5.0f);
374
							extraInfoTable.setWidthPercentage(90.0f);
375
							document.add(new DottedLineSeparator());
376
							document.add(extraInfoTable);
377
						}
378
					}
379
					if(withBill){
380
						PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
381
						taxTable.setSpacingBefore(5.0f);
382
						taxTable.setWidthPercentage(90.0f);
383
						document.add(new DottedLineSeparator());
384
						document.add(taxTable);
385
						if(order.getSource() == OrderSource.FLIPKART.getValue()) {
386
							//document.add(new DottedLineSeparator());
387
							document.add(getFlipkartBarCodes(order));
388
						}
2787 chandransh 389
 
13276 manish.sha 390
					}else{
391
						PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
392
						extraInfoTable.setSpacingBefore(5.0f);
393
						extraInfoTable.setWidthPercentage(90.0f);
394
						document.add(new DottedLineSeparator());
395
						document.add(extraInfoTable);
396
					}
13316 manish.sha 397
 
398
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
399
						PdfPTable orderItemsDetailTable = new PdfPTable(1);
400
						orderItemsDetailTable.setWidthPercentage(90.0f);
401
						orderItemsDetailTable.setSpacingBefore(5.0f);
402
						orderItemsDetailTable.addCell(new Phrase("SubOrder Ids :", helveticaBold8));
403
						StringBuffer sbOrders = new StringBuffer();
404
 
13318 manish.sha 405
						for(Order o1 : ordersList){
13316 manish.sha 406
							sbOrders.append(o1.getId()+",");
407
						}
408
 
409
 
410
						String orderIds = sbOrders.toString();
411
						orderIds = orderIds.substring(0, orderIds.length()-1);
13319 manish.sha 412
 
13316 manish.sha 413
						StringBuffer sbImeis = new StringBuffer();
414
 
13317 manish.sha 415
						for(Order o1 : ordersList){
13316 manish.sha 416
							if(o1.getLineitems().get(0).getSerial_number()!=null){
417
								sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
418
							}
419
						}
420
 
13319 manish.sha 421
						orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
13316 manish.sha 422
 
13319 manish.sha 423
						if(sbImeis.length()>0){
424
							orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
425
							logger.info("Imeis List:- " + sbImeis);
426
							String imeis = sbImeis.toString();
13490 manish.sha 427
							if(imeis.endsWith(","))
428
								imeis = imeis.substring(0, imeis.length()-1);
13319 manish.sha 429
							logger.info("Final Imeis List:- " + sbImeis);
430
 
431
							orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
432
						}
433
 
13316 manish.sha 434
						document.add(orderItemsDetailTable);
435
					}
18779 manish.sha 436
					PdfPTable billingAddressTable = getCustomerAddressTable(order, null, true, helvetica8, true, true);
18778 manish.sha 437
					if(billingAddress!=null){
438
						billingAddressTable.setWidthPercentage(90.0f);
439
						billingAddressTable.setSpacingBefore(5.0f);
440
						billingAddressTable.addCell(new Phrase("Billing Address :", helveticaBold8));
441
						billingAddressTable.addCell(new Phrase(billingAddress.getName() +" "+billingAddress.getLine1()
442
								+billingAddress.getLine2() +" "+billingAddress.getCity() + "," + billingAddress.getState()
443
								+" -"+billingAddress.getPin(), helvetica8));
444
						document.add(billingAddressTable);
445
					}
13316 manish.sha 446
 
13276 manish.sha 447
					document.newPage();
7014 rajveer 448
				}
13276 manish.sha 449
			} else {
450
				for(Order singleOrder : orders){
451
					List<Order> ordersList = new ArrayList<Order>();
452
					ordersList.add(singleOrder);
453
					Warehouse warehouse = null;
454
					Provider provider = null;
455
					String destCode = null;
456
					Warehouse shippingLocation = null;
457
					int barcodeFontSize = 0;
458
					String invoiceFormat = "Individual";
459
					try {
460
						warehouse = iclient.getWarehouse(singleOrder.getWarehouse_id());
461
						long providerId = singleOrder.getLogistics_provider_id();
462
						provider = logisticsClient.getProvider(providerId);
463
						if(provider.getPickup().equals(PickUpType.SELF) || provider.getPickup().equals(PickUpType.RUNNER))
464
							destCode = provider.getPickup().toString();
465
						else
466
							destCode = logisticsClient.getDestinationCode(providerId, singleOrder.getCustomer_pincode());
4361 rajveer 467
 
13276 manish.sha 468
						barcodeFontSize = Integer.parseInt(ConfigClient.getClient().get(provider.getName().toLowerCase() + "_barcode_fontsize"));
469
						shippingLocation = CatalogUtils.getWarehouse(warehouse.getShippingWarehouseId()); 
470
					} catch (InventoryServiceException ise) {
471
						logger.error("Error while getting the warehouse information.", ise);
472
						return baosPDF;
473
					} catch (LogisticsServiceException lse) {
474
						logger.error("Error while getting the provider information.", lse);
475
						return baosPDF;
476
					} catch (ConfigException ce) {
477
						logger.error("Error while getting the fontsize for the given provider", ce);
478
						return baosPDF;
479
					} catch (TException te) {
480
						logger.error("Error while getting some essential information from the services", te);
481
						return baosPDF;
7014 rajveer 482
					}
13276 manish.sha 483
 
484
					if(printAll && warehouse.getBillingType() == BillingType.OURS_EXTERNAL){
485
						for(Order order : ordersList){
486
							if(isFirst){
19950 amit.gupta 487
								document.add(getFixedTextTable(16, companyName));
13276 manish.sha 488
								isFirst = false;
489
							}
490
							document.add(getExtraInfoTable(order, provider, 16, warehouse.getBillingType()));
491
							continue;
492
						}
493
					}
494
					PdfPTable dispatchAdviceTable = null;
495
					Order order = ordersList.get(0);
496
					if(ordersList.size()==1){					
497
						if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue()) {
8303 amar.kumar 498
							dispatchAdviceTable = new PdfPTable(1);
13276 manish.sha 499
						}  else if(new Long(order.getSource()).intValue() == OrderSource.FLIPKART.getValue()) {
500
							dispatchAdviceTable = new PdfPTable(1);
13705 manish.sha 501
						}  else if(new Long(order.getSource()).intValue() == OrderSource.HOMESHOP18.getValue()) {
502
							dispatchAdviceTable = new PdfPTable(1);
13276 manish.sha 503
						}  else if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7)) {
504
							if(order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
505
								dispatchAdviceTable = new PdfPTable(1);
506
							} else { 
507
								if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty()) {
508
									dispatchAdviceTable = new PdfPTable(1);
509
								} else {
510
									EbayInvoiceGenerationService invoiceGenerationService = new EbayInvoiceGenerationService();
511
									dispatchAdviceTable = invoiceGenerationService.getDispatchAdviceTable(orderId, warehouseId);
512
								}
513
							}
514
						}
515
						else {
516
							dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
517
						}
518
					} else {
519
						dispatchAdviceTable = getDispatchAdviceTable(ordersList, warehouse, provider, barcodeFontSize, destCode, withBill, shippingLocation, invoiceFormat);
520
					}
521
 
522
					dispatchAdviceTable.setSpacingAfter(10.0f);
523
					dispatchAdviceTable.setWidthPercentage(90.0f);
524
					document.add(dispatchAdviceTable);
525
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
13320 manish.sha 526
						if(ordersList.size()>1){
527
							document.newPage();
528
						}
13276 manish.sha 529
					}
530
 
531
					if ((new Long(order.getSource()).intValue() == OrderSource.EBAY.getValue()) && (order.getLogistics_provider_id()>7) &&(ordersList.size()==1)) {
532
						if (order.getAirwaybill_no()== null || order.getAirwaybill_no().equals("null") || order.getAirwaybill_no().isEmpty() 
533
								|| order.getWarehouse_id() == 7 || order.getWarehouse_id() == 5 || order.getWarehouse_id() == 9) {
534
							if(withBill){
535
								PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
536
								taxTable.setSpacingBefore(5.0f);
537
								taxTable.setWidthPercentage(90.0f);
538
								document.add(new DottedLineSeparator());
539
								document.add(taxTable);
540
							}else{
541
								PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
542
								extraInfoTable.setSpacingBefore(5.0f);
543
								extraInfoTable.setWidthPercentage(90.0f);
544
								document.add(new DottedLineSeparator());
545
								document.add(extraInfoTable);
546
							}
8303 amar.kumar 547
						} else {
13276 manish.sha 548
							document.newPage();
8303 amar.kumar 549
						}
13276 manish.sha 550
					} else if (new Long(order.getSource()).intValue() == OrderSource.SNAPDEAL.getValue() &&(ordersList.size()==1)) {
8303 amar.kumar 551
						if(withBill){
13276 manish.sha 552
							PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
8303 amar.kumar 553
							taxTable.setSpacingBefore(5.0f);
554
							taxTable.setWidthPercentage(90.0f);
555
							document.add(new DottedLineSeparator());
556
							document.add(taxTable);
557
						}else{
558
							PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
559
							extraInfoTable.setSpacingBefore(5.0f);
560
							extraInfoTable.setWidthPercentage(90.0f);
561
							document.add(new DottedLineSeparator());
562
							document.add(extraInfoTable);
563
						}
564
					}
8488 amar.kumar 565
					if(withBill){
13276 manish.sha 566
						PdfPTable taxTable = getTaxCumRetailInvoiceTable(ordersList, provider, shippingLocation.getLocation() + "-" + shippingLocation.getPincode() , shippingLocation.getTinNumber(), invoiceFormat);
8488 amar.kumar 567
						taxTable.setSpacingBefore(5.0f);
568
						taxTable.setWidthPercentage(90.0f);
569
						document.add(new DottedLineSeparator());
570
						document.add(taxTable);
13276 manish.sha 571
						if(order.getSource() == OrderSource.FLIPKART.getValue()) {
572
							//document.add(new DottedLineSeparator());
573
							document.add(getFlipkartBarCodes(order));
574
						}
575
 
8488 amar.kumar 576
					}else{
577
						PdfPTable extraInfoTable = getExtraInfoTable(order, provider, 16, warehouse.getBillingType());
578
						extraInfoTable.setSpacingBefore(5.0f);
579
						extraInfoTable.setWidthPercentage(90.0f);
580
						document.add(new DottedLineSeparator());
581
						document.add(extraInfoTable);
582
					}
13276 manish.sha 583
 
584
					if("Bulk".equalsIgnoreCase(invoiceFormat)){
585
						PdfPTable orderItemsDetailTable = new PdfPTable(1);
586
						orderItemsDetailTable.setWidthPercentage(90.0f);
587
						orderItemsDetailTable.setSpacingBefore(5.0f);
13313 manish.sha 588
						orderItemsDetailTable.addCell(new Phrase("SubOrder Ids :", helveticaBold8));
13276 manish.sha 589
						StringBuffer sbOrders = new StringBuffer();
590
 
591
						for(Order o1 : orders){
592
							sbOrders.append(o1.getId()+",");
593
						}
594
 
595
 
596
						String orderIds = sbOrders.toString();
597
						orderIds = orderIds.substring(0, orderIds.length()-1);
598
 
599
						orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
13319 manish.sha 600
 
13276 manish.sha 601
 
602
						StringBuffer sbImeis = new StringBuffer();
603
 
604
						for(Order o1 : orders){
605
							if(o1.getLineitems().get(0).getSerial_number()!=null){
606
								sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
607
							}
608
						}
609
 
13319 manish.sha 610
						if(sbImeis.length()>0){
611
							orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
612
 
613
							logger.info("Imeis List:- " + sbImeis);
614
							String imeis = sbImeis.toString();
615
							imeis = imeis.substring(0, imeis.length()-2);
616
							logger.info("Final Imeis List:- " + sbImeis);
617
 
618
							orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
619
						}
620
 
13276 manish.sha 621
						document.add(orderItemsDetailTable);
9009 amar.kumar 622
					}
18779 manish.sha 623
					PdfPTable billingAddressTable = getCustomerAddressTable(order, null, true, helvetica8, true, true);
18769 manish.sha 624
					if(billingAddress!=null){
625
						billingAddressTable.setWidthPercentage(90.0f);
626
						billingAddressTable.setSpacingBefore(5.0f);
627
						billingAddressTable.addCell(new Phrase("Billing Address :", helveticaBold8));
628
						billingAddressTable.addCell(new Phrase(billingAddress.getName() +" "+billingAddress.getLine1()
629
								+billingAddress.getLine2() +" "+billingAddress.getCity() + "," + billingAddress.getState()
630
								+" -"+billingAddress.getPin(), helvetica8));
631
						document.add(billingAddressTable);
632
					}
633
 
13276 manish.sha 634
					document.newPage();
7014 rajveer 635
				}
636
			}
13276 manish.sha 637
 
18875 manish.sha 638
 
639
			if(logisticsTxnIdOrdersMap!=null && logisticsTxnIdOrdersMap.size()>0){
640
                for(String logisticsTxnId : logisticsTxnIdOrdersMap.keySet()){
18892 manish.sha 641
                	document.newPage();
18891 manish.sha 642
                	List<Order> ordersList = logisticsTxnIdOrdersMap.get(logisticsTxnId);
18881 manish.sha 643
					PdfPTable headerTable = new PdfPTable(1);
18893 manish.sha 644
					headerTable.setWidthPercentage(90.0f);
645
					headerTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
18875 manish.sha 646
	    	        headerTable.addCell(getInvoiceTableHeader(0,ordersList.get(0).getLogisticsTransactionId()));
647
					PdfPTable packagingTable = getPackagingInfoTable(ordersList);
18876 manish.sha 648
					PdfPTable signTable = new PdfPTable(new float[]{0.1f, 0.8f, 0.1f});
18893 manish.sha 649
					signTable.setWidthPercentage(90.0f);
650
					signTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
18876 manish.sha 651
					signTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
652
					signTable.setSplitLate(false);
653
					signTable.setSpacingBefore(10.0f);
654
					signTable.addCell(new Phrase("Biller",helveticaBold8));
655
					signTable.addCell(new Phrase("",helveticaBold8));
656
					signTable.addCell(new Phrase("Packer",helveticaBold8));
18875 manish.sha 657
					document.add(headerTable);
658
					document.add(packagingTable);
18876 manish.sha 659
					document.add(signTable);
18875 manish.sha 660
				}
661
 
662
			}
663
 
7014 rajveer 664
			document.close();
665
			baosPDF.close();
666
			// Adding facility to store the bill on the local directory. This will happen for only for Mahipalpur warehouse.
667
			if(withBill && !printAll){
7079 rajveer 668
				String strOrderId = StringUtils.repeat("0", 10-String.valueOf(orderId).length()) + orderId;  
7014 rajveer 669
				String dirPath = "/SaholicInvoices" + File.separator + strOrderId.substring(0, 2) + File.separator + strOrderId.substring(2, 4) + File.separator + strOrderId.substring(4, 6);
670
				String filename = dirPath + File.separator + orderId + ".pdf";
671
				File dirFile = new File(dirPath);
672
				if(!dirFile.exists()){
673
					dirFile.mkdirs();
674
				}
675
				File f = new File(filename);
676
				FileOutputStream fos = new FileOutputStream(f);
677
				baosPDF.writeTo(fos);
678
			}
679
		} catch (Exception e) {
680
			logger.error("Error while generating Invoice: ", e);
681
		}
682
		return baosPDF;
683
	}
18875 manish.sha 684
 
685
 
686
	private PdfPTable getPackagingInfoTable(List<Order> orderList) throws CatalogServiceException, TException{
18879 manish.sha 687
		PdfPTable finalTable = new PdfPTable(1);
18891 manish.sha 688
		finalTable.setWidthPercentage(90.0f);
689
		finalTable.setSpacingBefore(5.0f);
690
		finalTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
19276 manish.sha 691
		finalTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
19260 manish.sha 692
		finalTable.setSplitLate(false);
18879 manish.sha 693
		PdfPTable customerAddresTable = new PdfPTable(1);
18891 manish.sha 694
		customerAddresTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
18880 manish.sha 695
		customerAddresTable.addCell(new Phrase("Customer Details: "+orderList.get(0).getCustomer_name() +" "+orderList.get(0).getCustomer_address1()
18879 manish.sha 696
				+orderList.get(0).getCustomer_address2() +" "+orderList.get(0).getCustomer_city() + "," + orderList.get(0).getCustomer_state()
697
				+" -"+orderList.get(0).getCustomer_pincode(), helvetica8));
18891 manish.sha 698
		PdfPTable packagingTable = new PdfPTable(new float[]{0.1f, 0.1f, 0.1f, 0.2f, 0.2f, 0.1f, 0.07f, 0.08f, 0.1f});
699
		packagingTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
18882 manish.sha 700
		packagingTable.addCell(new Phrase("ItemId", helveticaBold8));
18875 manish.sha 701
		packagingTable.addCell(new Phrase("BIN Id", helveticaBold8));
18882 manish.sha 702
		packagingTable.addCell(new Phrase("SubOrder Id", helveticaBold8));
703
		packagingTable.addCell(new Phrase("Item Desc", helveticaBold8));
704
		packagingTable.addCell(new Phrase("Sr Nos", helveticaBold8));
705
		packagingTable.addCell(new Phrase("Rate", helveticaBold8));
18891 manish.sha 706
		packagingTable.addCell(new Phrase("Pack\nSize", helveticaBold8));
18882 manish.sha 707
		packagingTable.addCell(new Phrase("Qty", helveticaBold8));
708
		packagingTable.addCell(new Phrase("Total Pcs.", helveticaBold8));
19260 manish.sha 709
		packagingTable.setHeaderRows(1);
18875 manish.sha 710
 
711
		Map<Long, Item> itemMap = new HashMap<Long, Item>();
712
 
713
		CatalogService.Client catalogClient = ctsc.getClient();
714
		for(Order order:orderList){
715
			if(!itemMap.containsKey(order.getLineitems().get(0).getItem_id())){
716
				itemMap.put(order.getLineitems().get(0).getItem_id(), catalogClient.getItem(order.getLineitems().get(0).getItem_id()));
717
			}
718
		}
719
 
18883 manish.sha 720
		double grandTotalPieces = 0;
721
 
18875 manish.sha 722
		for(Order order:orderList){
723
			packagingTable.addCell(new Phrase(order.getLineitems().get(0).getItem_id()+"", helvetica8));
724
			packagingTable.addCell(new Phrase("", helveticaBold8));
725
			packagingTable.addCell(new Phrase(order.getId()+"", helvetica8));
726
			packagingTable.addCell(new Phrase(getItemDisplayName(order.getLineitems().get(0), false), helvetica8));
727
			if(order.getLineitems().get(0).isSetSerial_number()){
18894 manish.sha 728
				String[] serialNumbers = order.getLineitems().get(0).getSerial_number().split(",");
729
				String serialNoString = "";
730
				for(String serialNo : serialNumbers){
731
					serialNoString += serialNo + "\n";
732
				}
733
				packagingTable.addCell(new Phrase(serialNoString, helvetica8));
18875 manish.sha 734
			}else{
735
				packagingTable.addCell(new Phrase("", helvetica8));
736
			}
18879 manish.sha 737
			packagingTable.addCell(new Phrase(order.getLineitems().get(0).getUnit_price()+"", helvetica8));
18875 manish.sha 738
			packagingTable.addCell(new Phrase(itemMap.get(order.getLineitems().get(0).getItem_id()).getPackQuantity()+"", helvetica8));
739
			packagingTable.addCell(new Phrase(order.getLineitems().get(0).getQuantity()+"", helvetica8));
740
			packagingTable.addCell(new Phrase((order.getLineitems().get(0).getQuantity()*itemMap.get(order.getLineitems().get(0).getItem_id()).getPackQuantity())+"", helvetica8));
18883 manish.sha 741
			grandTotalPieces += order.getLineitems().get(0).getQuantity()*itemMap.get(order.getLineitems().get(0).getItem_id()).getPackQuantity();
18875 manish.sha 742
		}
18883 manish.sha 743
		packagingTable.addCell(getTotalCell(8));
744
		packagingTable.addCell(new Phrase(grandTotalPieces+"", helveticaBold8));
18879 manish.sha 745
		finalTable.addCell(customerAddresTable);
746
		finalTable.addCell(packagingTable);
747
		return finalTable;
18875 manish.sha 748
	}
3065 chandransh 749
 
13276 manish.sha 750
	private PdfPTable getDispatchAdviceTable(List<Order> orderList, Warehouse warehouse, Provider provider, float barcodeFontSize, String destCode, boolean withBill, Warehouse shippingLocation, String invoiceFormat){
751
		Order order = orderList.get(0);
7014 rajveer 752
		Font barCodeFont = getBarCodeFont(provider, barcodeFontSize);
13276 manish.sha 753
 
754
		double totalAmount = 0.0;
755
		double totalWeight = 0.0;
756
 
757
		for (Order o: orderList){
17470 manish.sha 758
			totalAmount = totalAmount + o.getTotal_amount() +o.getShippingCost()-o.getGvAmount()-o.getAdvanceAmount();
13276 manish.sha 759
			totalWeight = totalWeight + o.getTotal_weight();
760
		}
2787 chandransh 761
 
7014 rajveer 762
		PdfPTable table = new PdfPTable(1);
18847 manish.sha 763
		table.setSplitLate(false);
7014 rajveer 764
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 765
 
766
		PdfPTable titleBarTable = new PdfPTable(new float[]{0.4f, 0.4f, 0.2f});
8107 manish.sha 767
		titleBarTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 768
 
8103 manish.sha 769
		PdfPTable logoTable = new PdfPTable(2);
770
		addLogoTable(logoTable,order); 
7318 rajveer 771
 
7014 rajveer 772
		PdfPCell titleCell = getTitleCell();
18530 manish.sha 773
		PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false, false);
13276 manish.sha 774
		PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont, totalWeight);
2787 chandransh 775
 
7014 rajveer 776
		PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
777
		dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
778
		dispatchTable.addCell(customerTable);
779
		dispatchTable.addCell(new Phrase(" "));
780
		dispatchTable.addCell(providerInfoTable);
2787 chandransh 781
 
13276 manish.sha 782
		PdfPTable invoiceTable = getTopInvoiceTable(orderList, shippingLocation.getTinNumber(), invoiceFormat);
8110 manish.sha 783
		PdfPTable addressTable = new PdfPTable(1);
784
		addressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
785
		addressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
786
 
7014 rajveer 787
		PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
19723 manish.sha 788
				" - " + shippingLocation.getPincode() + "\nContact No.- +91-9818116289" + "\n\n");
2787 chandransh 789
 
7014 rajveer 790
		PdfPTable chargesTable = new PdfPTable(1);
791
		chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
792
		chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
793
		if(order.isLogisticsCod()){
13276 manish.sha 794
			chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (totalAmount), helveticaBold12));
7014 rajveer 795
			chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
7994 manish.sha 796
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 797
			if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
7994 manish.sha 798
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
799
				String fedexCodReturnBarcode = "";
8080 manish.sha 800
				String fedexCodReturnTrackingId = "";
7994 manish.sha 801
				try {
802
					fedexCodReturnBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_BarCode");
8080 manish.sha 803
					fedexCodReturnTrackingId = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_Tracking_No");
7994 manish.sha 804
				} catch (TException e1) {
805
					logger.error("Error while getting the provider information.", e1);
806
				}
8080 manish.sha 807
				PdfPCell formIdCell= new PdfPCell(new Paragraph("COD Return "+fedexCodReturnTrackingId+" Form id-0325", helvetica6));
8104 manish.sha 808
				formIdCell.setPaddingTop(2.0f);
7994 manish.sha 809
				formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
810
				formIdCell.setBorder(Rectangle.NO_BORDER);
811
				chargesTable.addCell(new Phrase("PRIORITY OVERNIGHT ", helvetica8));
812
				chargesTable.addCell(formIdCell);
8035 manish.sha 813
 
8067 manish.sha 814
				generateBarcode(fedexCodReturnBarcode, "fedex_codr_"+order.getId());
8037 manish.sha 815
 
8067 manish.sha 816
				Image barcodeImage=null;
817
				try {
818
					barcodeImage = Image.getInstance("/tmp/"+"fedex_codr_"+order.getId()+".png");
819
				} catch (Exception e) {
820
					logger.error("Exception during getting Barcode Image for Fedex : ", e);
821
				}
822
 
8173 manish.sha 823
				PdfPTable codReturnTable = new PdfPTable(new float[]{0.6f,0.4f});
824
				codReturnTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
825
				codReturnTable.addCell(barcodeImage);
826
				codReturnTable.addCell(new Phrase(" "));
827
				chargesTable.addCell(codReturnTable);
828
 
7994 manish.sha 829
			}
830
			//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 831
		} else {
832
			chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
833
		}
8080 manish.sha 834
 
19513 manish.sha 835
		if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
8080 manish.sha 836
			chargesTable.addCell(new Phrase("Term and Condition:- Subject to the Conditions of Carriage which " +
837
					"limits the liability of FedEx for loss, delay or damage to the consignment." +
838
					" Visit http://www.fedex.com/in/domestic/services/terms to view the conitions of Carriage" ,
8082 manish.sha 839
					new Font(FontFamily.TIMES_ROMAN, 8f)));
8080 manish.sha 840
		}
10310 amar.kumar 841
 
8110 manish.sha 842
		addressTable.addCell(new Phrase("If undelivered, return to:", helvetica10));
843
		addressTable.addCell(addressCell);
844
 
7014 rajveer 845
		PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
846
		addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8110 manish.sha 847
		addressAndNoteTable.addCell(addressTable);
7014 rajveer 848
		addressAndNoteTable.addCell(chargesTable);
2787 chandransh 849
 
8106 manish.sha 850
		titleBarTable.addCell(logoTable);
851
		titleBarTable.addCell(titleCell);
852
		titleBarTable.addCell(" ");
853
 
854
		table.addCell(titleBarTable);
7014 rajveer 855
		table.addCell(dispatchTable);
856
		table.addCell(invoiceTable);
857
		table.addCell(addressAndNoteTable);
858
		return table;
859
	}
2787 chandransh 860
 
8103 manish.sha 861
	private void addLogoTable(PdfPTable logoTable,Order order) {
7318 rajveer 862
		logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
863
		logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
864
		logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
8096 manish.sha 865
 
7318 rajveer 866
		PdfPCell logoCell;
867
		String logoPath;
8102 manish.sha 868
 
7556 rajveer 869
		if(order.getSource() == OrderSource.STORE.getValue()){
870
			logoCell = new PdfPCell(new Phrase(""));
871
 
872
		}else{
8102 manish.sha 873
			logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
8094 manish.sha 874
 
7318 rajveer 875
			try {
876
				logoCell = new PdfPCell(Image.getInstance(logoPath), false);
877
			} catch (Exception e) {
878
				//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
879
				logger.warn("Couldn't load the Saholic logo: ", e);
880
				logoCell = new PdfPCell(new Phrase("Saholic Logo"));
881
			}
882
 
883
		}
8090 manish.sha 884
		logoCell.setBorder(Rectangle.NO_BORDER);
885
		logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
8102 manish.sha 886
		logoTable.addCell(logoCell);
887
		logoTable.addCell(" ");
8103 manish.sha 888
 
7318 rajveer 889
	}
890
 
7014 rajveer 891
	private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
892
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
893
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
894
		ttfFontFactory.register(fontPath, "barcode");
895
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
896
		return barCodeFont;
897
	}
2787 chandransh 898
 
7014 rajveer 899
	private PdfPCell getTitleCell() {
900
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
901
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
902
		titleCell.setBorder(Rectangle.NO_BORDER);
903
		return titleCell;
904
	}
2787 chandransh 905
 
13276 manish.sha 906
	private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont, double totalWeight) {
7014 rajveer 907
		PdfPTable providerInfoTable = new PdfPTable(1);
908
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7318 rajveer 909
		if(order.isLogisticsCod()){
8551 manish.sha 910
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica22));
7318 rajveer 911
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
912
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
913
			providerInfoTable.addCell(deliveryTypeCell);
914
		}
915
 
8035 manish.sha 916
 
7014 rajveer 917
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
918
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
919
		providerNameCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 920
		PdfPCell formIdCell= null;
19513 manish.sha 921
		if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
7994 manish.sha 922
			if(order.isCod()){
8034 manish.sha 923
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
7994 manish.sha 924
			}
925
			else{
8034 manish.sha 926
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
7994 manish.sha 927
			}
8551 manish.sha 928
			formIdCell.setPaddingTop(1.0f);
8015 rajveer 929
			formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
930
			formIdCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 931
		}
8015 rajveer 932
 
7994 manish.sha 933
 
934
		PdfPCell awbNumberCell= null;
8034 manish.sha 935
		String fedexPackageBarcode = "";
19513 manish.sha 936
		if(order.getLogistics_provider_id()!=7L && order.getLogistics_provider_id()!=46L){
7994 manish.sha 937
			awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
8017 manish.sha 938
			awbNumberCell.setPaddingTop(20.0f);
7994 manish.sha 939
		}
940
		else{
8013 rajveer 941
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
942
			try {
943
				fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
944
			} catch (TException e1) {
945
				logger.error("Error while getting the provider information.", e1);
946
			}
8174 manish.sha 947
			awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
948
		}
949
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
950
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
951
 
952
		providerInfoTable.addCell(providerNameCell);
953
		if(formIdCell != null){
954
			providerInfoTable.addCell(formIdCell);
955
		}
956
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 957
		if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
8169 manish.sha 958
			generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
959
 
960
			Image barcodeImage=null;
961
			try {
962
				barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
963
			} catch (Exception e) {
964
				logger.error("Exception during getting Barcode Image for Fedex : ", e);
965
			}
8174 manish.sha 966
			providerInfoTable.addCell(barcodeImage);
7994 manish.sha 967
		}
8174 manish.sha 968
		providerInfoTable.addCell(awbNumberCell);
7014 rajveer 969
 
7792 anupam.sin 970
		Warehouse warehouse = null;
971
		try{
972
    		InventoryClient isc = new InventoryClient();
7804 amar.kumar 973
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
7803 amar.kumar 974
		} catch(Exception e) {
7792 anupam.sin 975
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
7805 amar.kumar 976
		    //TODO throw e;
7792 anupam.sin 977
		}
978
		DeliveryType dt =  DeliveryType.PREPAID;
979
        if (order.isLogisticsCod()) {
980
            dt = DeliveryType.COD;
981
        }
7994 manish.sha 982
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 983
        if(order.getLogistics_provider_id()!=7L && order.getLogistics_provider_id()!=46L){
7994 manish.sha 984
	        for (ProviderDetails detail : provider.getDetails()) {
985
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
986
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
987
	            }
988
	        }
7792 anupam.sin 989
        }
7994 manish.sha 990
        else{
19515 manish.sha 991
        	if(order.getLogistics_provider_id()==7L){
992
        		providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
993
        	}else{
994
        		providerInfoTable.addCell(new Phrase("FEDEX EXPRESS SAVER ", helvetica8));
995
        	}
7994 manish.sha 996
        }
997
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 998
		Date awbDate;
999
		if(order.getBilling_timestamp() == 0){
1000
			awbDate = new Date();
1001
		}else{
1002
			awbDate = new Date(order.getBilling_timestamp());
1003
		}
19513 manish.sha 1004
		if(order.getLogistics_provider_id()!=7L && order.getLogistics_provider_id()!=46L){
8106 manish.sha 1005
			providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
1006
		}
19260 manish.sha 1007
		providerInfoTable.addCell(new Phrase("Weight         : " + weightFormat.format(totalWeight) + " Kg", helvetica8));
8182 amar.kumar 1008
		if(order.getSource() == OrderSource.EBAY.getValue()){
1009
			EbayOrder ebayOrder = null;
1010
			try {
1011
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1012
			} catch (TException e) {
1013
				logger.error("Error while getting ebay order", e);
1014
			}
1015
			providerInfoTable.addCell(new Phrase("PaisaPayId            : " + ebayOrder.getPaisaPayId(), helvetica8));
1016
			providerInfoTable.addCell(new Phrase("Sales Rec Number: " + ebayOrder.getSalesRecordNumber(), helvetica8));
1017
		}
7994 manish.sha 1018
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1019
		if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
7994 manish.sha 1020
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
1021
		}
1022
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 1023
		return providerInfoTable;
1024
	}
1025
 
13276 manish.sha 1026
	private PdfPTable getTopInvoiceTable(List<Order> orderList, String tinNo, String invoiceFormat){
7014 rajveer 1027
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
1028
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1029
 
13276 manish.sha 1030
		invoiceTable.addCell(getInvoiceTableHeader(6,orderList.get(0).getLogisticsTransactionId()));
1031
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1032
			invoiceTable.addCell(new Phrase("Sr No", helvetica8));
1033
		}else{
1034
			invoiceTable.addCell(new Phrase("Order No", helvetica8));
1035
		}
7014 rajveer 1036
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
1037
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
1038
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
1039
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
1040
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
19276 manish.sha 1041
		invoiceTable.setHeaderRows(2);
13276 manish.sha 1042
		double totalAmount = 0.0;
17470 manish.sha 1043
		double totalShippingCost = 0.0;
13276 manish.sha 1044
		double insuranceAmount = 0.0;
1045
		double advanceAmount = 0.0;
19003 manish.sha 1046
		double totalGvAmount = 0.0;
13276 manish.sha 1047
 
1048
 
1049
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1050
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1051
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1052
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1053
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1054
			String paymentMode = "";
1055
			for(Order order : orderList){
1056
				LineItem lineitem = order.getLineitems().get(0);
19003 manish.sha 1057
				totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount()-order.getGvAmount();
17470 manish.sha 1058
				totalShippingCost = totalShippingCost + order.getShippingCost();
19003 manish.sha 1059
				totalGvAmount = totalGvAmount + order.getGvAmount();
13276 manish.sha 1060
				if(order.getInsurer() > 0) {
1061
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1062
				}
1063
				if(order.getSource() == OrderSource.STORE.getValue()) {
1064
					advanceAmount = advanceAmount + order.getAdvanceAmount();
1065
				}
1066
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1067
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1068
				}
1069
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1070
					itemRateMap.put(lineitem.getItem_id(), lineitem.getUnit_price());
1071
				}
1072
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1073
					double currentQuantity = itemQuantityMap.get(lineitem.getItem_id()) +lineitem.getQuantity();
1074
					itemQuantityMap.put(lineitem.getItem_id(), currentQuantity);
1075
				}else{
1076
					itemQuantityMap.put(lineitem.getItem_id(), lineitem.getQuantity());
1077
				}
1078
 
1079
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
13492 manish.sha 1080
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount());
13276 manish.sha 1081
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1082
				}else{
13492 manish.sha 1083
					itemTotalAmtMap.put(lineitem.getItem_id(), (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount()));
13276 manish.sha 1084
				}
1085
				if(paymentMode==null || paymentMode.isEmpty()){
1086
					if(order.getPickupStoreId() > 0 && order.isCod() == true)
1087
						paymentMode = "In-Store";
1088
					else if (order.isCod())
1089
						paymentMode = "COD";
1090
					else
1091
						paymentMode = "Prepaid";
1092
				}		
1093
			}
1094
 
1095
			int serialNo = 0;
1096
			for(Long itemId : itemNamesMap.keySet()){
1097
				serialNo ++;
1098
				invoiceTable.addCell(new Phrase(serialNo+ "", helvetica8));
1099
				invoiceTable.addCell(new Phrase(paymentMode, helvetica8));
1100
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId), helvetica8));
1101
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"", helvetica8));
1102
				invoiceTable.addCell(new Phrase(itemRateMap.get(itemId)+"", helvetica8));
1103
				invoiceTable.addCell(new Phrase(itemTotalAmtMap.get(itemId)+"", helvetica8));
1104
			}
1105
 
1106
		}else{
1107
			for(Order order : orderList){
1108
				populateTopInvoiceTable(order, invoiceTable);
1109
				if(order.getInsurer() > 0) {
1110
					invoiceTable.addCell(getInsuranceCell(4));
1111
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
1112
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
1113
				}
7014 rajveer 1114
 
13276 manish.sha 1115
				if(order.getSource() == OrderSource.STORE.getValue()) {
1116
					invoiceTable.addCell(getAdvanceAmountCell(4));
1117
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
1118
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
1119
				}
19003 manish.sha 1120
				if(order.getInsurer() > 0) {
1121
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1122
				}
1123
				if(order.getSource() == OrderSource.STORE.getValue()) {
1124
					advanceAmount = advanceAmount + order.getAdvanceAmount();
1125
				}
1126
				totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount()-order.getGvAmount();
17470 manish.sha 1127
				totalShippingCost = totalShippingCost + order.getShippingCost();
19003 manish.sha 1128
				totalGvAmount = totalGvAmount + order.getGvAmount();
13276 manish.sha 1129
			}
7014 rajveer 1130
		}
19003 manish.sha 1131
		if(insuranceAmount>0){
1132
			invoiceTable.addCell(getInsuranceCell(4));
1133
			invoiceTable.addCell(getPriceCell(insuranceAmount));
1134
			invoiceTable.addCell(getPriceCell(insuranceAmount));
1135
		}
1136
		if(advanceAmount>0){
1137
			invoiceTable.addCell(getAdvanceAmountCell(4));
1138
			invoiceTable.addCell(getPriceCell(advanceAmount));
1139
			invoiceTable.addCell(getPriceCell(advanceAmount));
1140
		}
17470 manish.sha 1141
		if(totalShippingCost>0){
1142
			invoiceTable.addCell(getShippingCostCell(4));      
17501 manish.sha 1143
			invoiceTable.addCell(getRupeesCell(false));
1144
			invoiceTable.addCell(getPriceCell(totalShippingCost));
17470 manish.sha 1145
		}
19003 manish.sha 1146
		if(totalGvAmount>0){
1147
			totalGvAmount = 0-totalGvAmount;
1148
			invoiceTable.addCell(getGvAmountCell(4));      
1149
			invoiceTable.addCell(getRupeesCell(false));
1150
			invoiceTable.addCell(getPriceCell(totalGvAmount));
1151
		}
7014 rajveer 1152
		invoiceTable.addCell(getTotalCell(4));      
17501 manish.sha 1153
		invoiceTable.addCell(getRupeesCell(true));
17470 manish.sha 1154
		invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
13276 manish.sha 1155
 
7014 rajveer 1156
 
1157
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
1158
		tinCell.setColspan(6);
1159
		tinCell.setPadding(2);
1160
		invoiceTable.addCell(tinCell);
1161
 
1162
		return invoiceTable;
1163
	}
1164
 
1165
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
1166
		List<LineItem> lineitems = order.getLineitems();
1167
		for (LineItem lineitem : lineitems) {
1168
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
1169
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
1170
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
1171
			else if (order.isCod())
1172
				invoiceTable.addCell(new Phrase("COD", helvetica8));
1173
			else
1174
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 1175
 
7190 amar.kumar 1176
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 1177
 
7014 rajveer 1178
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 1179
 
19003 manish.sha 1180
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()));
7014 rajveer 1181
 
19003 manish.sha 1182
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
7014 rajveer 1183
		}
1184
	}
1185
 
1186
	private PdfPCell getAddressCell(String address) {
1187
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
1188
		PdfPCell addressCell = new PdfPCell();
1189
		addressCell.addElement(addressParagraph);
1190
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1191
		addressCell.setBorder(Rectangle.NO_BORDER);
1192
		return addressCell;
1193
	}
1194
 
13276 manish.sha 1195
	private PdfPTable getTaxCumRetailInvoiceTable(List<Order> orderList, Provider provider, String ourAddress, String tinNo, String invoiceFormat){
1196
		Order order = orderList.get(0);
7014 rajveer 1197
		PdfPTable taxTable = new PdfPTable(1);
1198
		Phrase phrase = null;
18847 manish.sha 1199
		taxTable.setSplitLate(false);
7014 rajveer 1200
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1201
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
8104 manish.sha 1202
 
8110 manish.sha 1203
		PdfPTable logoTitleAndOurAddressTable = new PdfPTable(new float[]{0.4f, 0.3f, 0.3f});
8107 manish.sha 1204
		logoTitleAndOurAddressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8112 manish.sha 1205
		logoTitleAndOurAddressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
8107 manish.sha 1206
 
8110 manish.sha 1207
 
8103 manish.sha 1208
		PdfPTable logoTable = new PdfPTable(2);
1209
		addLogoTable(logoTable,order); 
7318 rajveer 1210
 
7014 rajveer 1211
 
19723 manish.sha 1212
		Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- +91-9818116289" + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
7014 rajveer 1213
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
1214
		sorlAddressCell.addElement(sorlAddress);
8110 manish.sha 1215
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
7014 rajveer 1216
 
18769 manish.sha 1217
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true, false);
18657 manish.sha 1218
		if (order.getOrderType().equals(OrderType.B2B)) {
1219
			if(billingAddress!=null){
1220
				if(order.getCustomer_state().trim().equalsIgnoreCase(billingAddress.getState())){
1221
					phrase = new Phrase("TAX INVOICE", helveticaBold12);
1222
				}else{
1223
					phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1224
				}
1225
			}else{
1226
				phrase = new Phrase("TAX INVOICE", helveticaBold12);
1227
			}
1228
		} else {
1229
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1230
		}
18693 manish.sha 1231
 
1232
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
1233
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1234
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
1235
 
7014 rajveer 1236
		PdfPTable orderDetails = getOrderDetails(order, provider);
1237
 
1238
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
1239
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1240
		addrAndOrderDetailsTable.addCell(customerAddress);
1241
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
1242
		addrAndOrderDetailsTable.addCell(orderDetails);
1243
 
9319 amar.kumar 1244
		boolean isVAT = isVatApplicable(order);
13276 manish.sha 1245
		PdfPTable invoiceTable = getBottomInvoiceTable(orderList, isVAT, invoiceFormat);
7014 rajveer 1246
 
10607 manish.sha 1247
		PdfPTable regAddAndDisCellTable = new PdfPTable(2);
1248
 
7014 rajveer 1249
		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));
1250
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1251
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
19961 amit.gupta 1252
		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. +91-9818116289 E-mail. help@saholic.com Website. www.saholic.com", helvetica6));
1253
		if(companyName.equals(SORPL)){
1254
			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. +91-9818116289 E-mail. help@saholic.com Website. www.saholic.com", helvetica6));
1255
		}
10607 manish.sha 1256
		regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1257
		regAddressCell.setBorder(Rectangle.NO_BORDER);
1258
		/*SPICE ONLINE RETAIL PRIVATE LIMITED
1259
		Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
1260
		CIN: U74140DL2008PTC183856
1261
		Tel. No. 0120-2479977
1262
		E-mail. help@saholic.com
1263
		Website. www.saholic.com*/
9014 amar.kumar 1264
		PdfPCell powerTextCell = new PdfPCell(new Phrase("Powered By  Flipkart", helvetica8));
1265
		powerTextCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1266
		powerTextCell.setBorder(Rectangle.NO_BORDER);
1267
		powerTextCell.setPaddingBottom(30.0f);
8104 manish.sha 1268
 
1269
		logoTitleAndOurAddressTable.addCell(logoTable);
8110 manish.sha 1270
		logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
1271
		logoTitleAndOurAddressTable.addCell(sorlAddress);
8104 manish.sha 1272
 
10607 manish.sha 1273
		regAddAndDisCellTable.addCell(disclaimerCell);
1274
		regAddAndDisCellTable.addCell(regAddressCell);
1275
 
8104 manish.sha 1276
		taxTable.addCell(logoTitleAndOurAddressTable);
7014 rajveer 1277
		taxTable.addCell(addrAndOrderDetailsTable);
1278
		taxTable.addCell(invoiceTable);
10608 manish.sha 1279
		taxTable.addCell(regAddAndDisCellTable);
9014 amar.kumar 1280
		if(order.getSource() == OrderSource.FLIPKART.getValue()) {
1281
			taxTable.addCell(powerTextCell);
1282
 
1283
		}
10320 amar.kumar 1284
		if(order.getProductCondition().equals(ProductCondition.BAD)){
10328 amar.kumar 1285
			PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
10320 amar.kumar 1286
					"may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
1287
					"are not returnable, exchangeable or refundable under any circumstances. No " +
1288
					"warranty is assured on these items." ,
10329 amar.kumar 1289
					new Font(FontFamily.TIMES_ROMAN, 8f)));
10328 amar.kumar 1290
			badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1291
			badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
1292
			taxTable.addCell(badSaleDisclaimerCell);
10320 amar.kumar 1293
		}
7014 rajveer 1294
		return taxTable;
1295
	}
9009 amar.kumar 1296
 
9319 amar.kumar 1297
	private boolean isVatApplicable(Order order) {
1298
		if(order.getWarehouse_id() == 7) {
1299
			if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
1300
				return true;
1301
			} else {
1302
				return false;
1303
			}
12809 manish.sha 1304
		} else if(order.getWarehouse_id() == 3298){
1305
			for(int i=0; i< telanganaPincodes.length; i++) {
1306
				if(order.getCustomer_pincode().trim().equalsIgnoreCase(telanganaPincodes[i])) {
1307
					return true;
1308
				}
1309
			}
1310
			return false;
16196 manish.sha 1311
		} else if(order.getWarehouse_id() == 1765 || order.getWarehouse_id() == 1768){
1312
			for(int i=0; i< karnatakaPincodePrefix.length; i++) {
1313
				if(order.getCustomer_pincode().startsWith(karnatakaPincodePrefix[i])) {
1314
					return true;
1315
				}
1316
			}
1317
			return false;
12809 manish.sha 1318
		}
1319
		else {
9319 amar.kumar 1320
			for(int i=0; i< maharashtraPincodePrefix.length; i++) {
1321
				if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
1322
					return true;
1323
				}
1324
			}
1325
			return false;
1326
		}
1327
	}
1328
 
9037 amar.kumar 1329
	private PdfPTable getFlipkartBarCodes(Order order) {
1330
		PdfPTable flipkartTable = new PdfPTable(3);
1331
 
1332
		PdfPCell spacerCell = new PdfPCell();
9040 amar.kumar 1333
		spacerCell.setBorder(Rectangle.NO_BORDER);
9037 amar.kumar 1334
		spacerCell.setColspan(3);
9099 amar.kumar 1335
		spacerCell.setPaddingTop(330.0f);
9037 amar.kumar 1336
 
1337
		String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1338
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1339
		ttfFontFactory.register(flipkartCodeFontPath, "barcode");
1340
		Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
1341
 
9040 amar.kumar 1342
		String serialNumber = "0000000000";
9511 manish.sha 1343
		if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
9040 amar.kumar 1344
			serialNumber = order.getLineitems().get(0).getSerial_number();
9511 manish.sha 1345
		} else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
9040 amar.kumar 1346
			serialNumber = order.getLineitems().get(0).getItem_number();
1347
		}
1348
 
1349
		PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
9037 amar.kumar 1350
		serialNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1351
		serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1352
		serialNumberBarCodeCell.setPaddingTop(11.0f);
1353
 
1354
 
1355
		PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
1356
		invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1357
		invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1358
		invoiceNumberBarCodeCell.setPaddingTop(11.0f);
1359
 
1360
		double rate = order.getLineitems().get(0).getVatRate();
1361
		double salesTax = (rate * order.getTotal_amount())/(100 + rate);
9040 amar.kumar 1362
		PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
9037 amar.kumar 1363
		vatAmtBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1364
		vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1365
		vatAmtBarCodeCell.setPaddingTop(11.0f);
1366
 
1367
		flipkartTable.addCell(spacerCell);
1368
		flipkartTable.addCell(serialNumberBarCodeCell);
1369
		flipkartTable.addCell(invoiceNumberBarCodeCell);
1370
		flipkartTable.addCell(vatAmtBarCodeCell);
1371
 
1372
		return flipkartTable;
1373
 
9009 amar.kumar 1374
	}
18657 manish.sha 1375
 
1376
	private void setBillingAddress(long userId, in.shop2020.model.v1.user.UserContextService.Client userClient) throws TException{
1377
		billingAddress = userClient.getBillingAddressForUser(userId);
1378
	}
9009 amar.kumar 1379
 
18530 manish.sha 1380
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce, boolean billingAdd){
7014 rajveer 1381
		PdfPTable customerTable = new PdfPTable(1);
1382
		if(forInvoce || order.getPickupStoreId() == 0){
18530 manish.sha 1383
			in.shop2020.model.v1.user.UserContextService.Client userClient = usc.getClient();
1384
			try {
1385
				if(billingAdd && userClient.isPrivateDealUser(order.getCustomer_id())){
18657 manish.sha 1386
					setBillingAddress(order.getCustomer_id(), userClient);
1387
					if(billingAddress!=null){
18769 manish.sha 1388
						return customerTable;
1389
						/*
18657 manish.sha 1390
						customerTable.addCell(new Phrase(billingAddress.getName(), font));
1391
						customerTable.addCell(new Phrase(billingAddress.getLine1(), font));
1392
						customerTable.addCell(new Phrase(billingAddress.getLine2(), font));
1393
						customerTable.addCell(new Phrase(billingAddress.getCity() + "," + billingAddress.getState(), font));
1394
						customerTable.addCell(new Phrase(billingAddress.getPin(), font));
1395
						customerTable.addCell(new Phrase("Phone : " + (billingAddress.getPhone()== null ? "" : billingAddress.getPhone()), font));
18769 manish.sha 1396
						*/
18657 manish.sha 1397
					}else{
1398
						customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1399
						if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1400
							HsOrder hsOrder = null;
1401
							try {
1402
								hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1403
							}catch (TException e) {
1404
								logger.error("Error while getting homeshop18 order", e);
1405
							}
1406
							String hsShippingName = hsOrder.getShippingName();
1407
							if(hsShippingName!=null && !hsShippingName.isEmpty()){
1408
								customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1409
							}
1410
						}
1411
						customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1412
						customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1413
						customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1414
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1415
						if(order.getLogistics_provider_id()!=7L  && order.getLogistics_provider_id()!=46L){
18657 manish.sha 1416
							if(destCode != null)
1417
								customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1418
							else
1419
								customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1420
							}
1421
						else{
1422
							in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1423
							String fedexLocationcode = "";
1424
							try {
1425
								fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1426
							} catch (TException e1) {
1427
								logger.error("Error while getting the provider information.", e1);
1428
							}
1429
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1430
						}
1431
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1432
						if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1433
							customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1434
						}
1435
					}
18530 manish.sha 1436
				}else{
18769 manish.sha 1437
					customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
18530 manish.sha 1438
					customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1439
					if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1440
						HsOrder hsOrder = null;
1441
						try {
1442
							hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1443
						}catch (TException e) {
1444
							logger.error("Error while getting homeshop18 order", e);
1445
						}
1446
						String hsShippingName = hsOrder.getShippingName();
1447
						if(hsShippingName!=null && !hsShippingName.isEmpty()){
1448
							customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1449
						}
1450
					}
1451
					customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1452
					customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1453
					customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1454
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1455
					if(order.getLogistics_provider_id()!=7L  && order.getLogistics_provider_id()!=46L){
18530 manish.sha 1456
						if(destCode != null)
1457
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1458
						else
1459
							customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1460
						}
1461
					else{
1462
						in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1463
						String fedexLocationcode = "";
1464
						try {
1465
							fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1466
						} catch (TException e1) {
1467
							logger.error("Error while getting the provider information.", e1);
1468
						}
1469
						customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1470
					}
1471
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1472
					if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1473
						customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1474
					}
13734 manish.sha 1475
				}
18530 manish.sha 1476
			} catch (TException e2) {
1477
				e2.printStackTrace();
13734 manish.sha 1478
			}
18530 manish.sha 1479
 
7014 rajveer 1480
		}else{
18769 manish.sha 1481
			customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7014 rajveer 1482
			try {
5556 rajveer 1483
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 1484
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
1485
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
1486
				customerTable.addCell(new Phrase(store.getLine1(), font));
1487
				customerTable.addCell(new Phrase(store.getLine2(), font));
1488
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
1489
				if(destCode != null)
1490
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
1491
				else
1492
					customerTable.addCell(new Phrase(store.getPin(), font));
1493
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 1494
			} catch (TException e) {
1495
				// TODO Auto-generated catch block
1496
				e.printStackTrace();
1497
			}
5527 anupam.sin 1498
 
7014 rajveer 1499
		}
1500
 
1501
		if(order.getOrderType().equals(OrderType.B2B)) {
1502
			String tin = null;
1503
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1504
			List<Attribute> attributes;
1505
			try {
1506
				attributes = tclient.getAllAttributesForOrderId(order.getId());
1507
 
1508
				for(Attribute attribute : attributes) {
1509
					if(attribute.getName().equals("tinNumber")) {
1510
						tin = attribute.getValue();
1511
					}
1512
				}
1513
				if (tin != null) {
1514
					customerTable.addCell(new Phrase("TIN :" + tin, font));
1515
				}
1516
 
1517
			} catch (Exception e) {
1518
				logger.error("Error while getting order attributes", e);
1519
			}
1520
		}
1521
		/*
2787 chandransh 1522
        if(showPaymentMode){
1523
            customerTable.addCell(new Phrase(" ", font));
1524
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 1525
        }*/
7014 rajveer 1526
		return customerTable;
1527
	}
2787 chandransh 1528
 
7014 rajveer 1529
	private PdfPTable getOrderDetails(Order order, Provider provider){
1530
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
1531
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 1532
 
7014 rajveer 1533
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
1534
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 1535
 
7014 rajveer 1536
		orderTable.addCell(new Phrase("Date:", helvetica8));
1537
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1538
 
13691 manish.sha 1539
		String hsCourierName = "";
12590 amit.gupta 1540
		if(order.getSource() == OrderSource.AMAZON.getValue() || order.getSource() == OrderSource.JUNGLEE.getValue()){
7528 rajveer 1541
			AmazonOrder aorder = null;
1542
			try {
1543
				aorder = tsc.getClient().getAmazonOrder(order.getId());
1544
			} catch (TException e) {
1545
				logger.error("Error while getting amazon order", e);
1546
			}
12590 amit.gupta 1547
			if(order.getSource() == OrderSource.JUNGLEE.getValue()){
1548
				orderTable.addCell(new Phrase("Junglee Order ID:", helvetica8));
1549
			}else {
1550
				orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
1551
			}
7528 rajveer 1552
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
13691 manish.sha 1553
		} else if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1554
			HsOrder hsOrder = null;
1555
			try {
13706 manish.sha 1556
				hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
13691 manish.sha 1557
			}catch (TException e) {
1558
				logger.error("Error while getting homeshop18 order", e);
1559
			}
1560
			hsCourierName = hsOrder.getCourierName();
1561
			orderTable.addCell(new Phrase("HomeShop18 Order No:", helvetica8));
1562
			orderTable.addCell(new Phrase(hsOrder.getHsOrderNo(), helvetica8));
1563
			orderTable.addCell(new Phrase("HomeShop18 Sub Order No:", helvetica8));
1564
			orderTable.addCell(new Phrase(hsOrder.getHsSubOrderNo(), helvetica8));
1565
 
8182 amar.kumar 1566
		} else if(order.getSource() == OrderSource.EBAY.getValue()){
1567
			EbayOrder ebayOrder = null;
1568
			try {
1569
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1570
			} catch (TException e) {
1571
				logger.error("Error while getting ebay order", e);
1572
			}
1573
			orderTable.addCell(new Phrase("PaisaPayId:", helvetica8));
1574
			orderTable.addCell(new Phrase(ebayOrder.getPaisaPayId(), helvetica8));
1575
			orderTable.addCell(new Phrase("Sales Rec Number:", helvetica8));
1576
			orderTable.addCell(new Phrase(new Long(ebayOrder.getSalesRecordNumber()).toString(), helvetica8));
8488 amar.kumar 1577
		} else if(order.getSource() == OrderSource.SNAPDEAL.getValue()){
1578
			SnapdealOrder snapdealOrder = null;
1579
			try {
11424 kshitij.so 1580
				snapdealOrder = tsc.getClient().getSnapdealOrder(order.getId(), null, null).get(0);
8488 amar.kumar 1581
			} catch (TException e) {
1582
				logger.error("Error while getting snapdeal order", e);
1583
			}
1584
			orderTable.addCell(new Phrase("Snapdeal OrderId:", helvetica8));
1585
			orderTable.addCell(new Phrase(new Long(snapdealOrder.getSubOrderId()).toString(), helvetica8));
8828 amar.kumar 1586
 
1587
			String refernceCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1588
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1589
			ttfFontFactory.register(refernceCodeFontPath, "barcode");
8876 amar.kumar 1590
			Font referenceCodeBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
8828 amar.kumar 1591
 
8874 amar.kumar 1592
			PdfPCell snapdealReferenceBarCodeCell = new PdfPCell(new Paragraph("*" +  snapdealOrder.getReferenceCode() + "*", referenceCodeBarCodeFont));
8828 amar.kumar 1593
			snapdealReferenceBarCodeCell.setBorder(Rectangle.NO_BORDER);
8876 amar.kumar 1594
			snapdealReferenceBarCodeCell.setPaddingTop(9.0f);
1595
			snapdealReferenceBarCodeCell.setColspan(2);
9042 amar.kumar 1596
			snapdealReferenceBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
8876 amar.kumar 1597
			//orderTable.addCell(new Phrase("Snapdeal ReferenceCode:", helvetica8));
8828 amar.kumar 1598
			orderTable.addCell(snapdealReferenceBarCodeCell);
1599
			//orderTable.addCell(new Phrase(snapdealOrder.getReferenceCode(), helvetica8));
7528 rajveer 1600
		}
8989 vikram.rag 1601
		else if(order.getSource() == OrderSource.FLIPKART.getValue()){
1602
			FlipkartOrder flipkartOrder = null;
1603
			try {
1604
				flipkartOrder = tsc.getClient().getFlipkartOrder(order.getId());
1605
			} catch (TException e) {
8996 amar.kumar 1606
				logger.error("Error while getting flipkart order", e);
8989 vikram.rag 1607
			}
1608
			orderTable.addCell(new Phrase("Flipkart OrderId:", helvetica8));
1609
			orderTable.addCell(new Phrase(flipkartOrder.getFlipkartOrderId(), helvetica8));
9037 amar.kumar 1610
 
1611
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1612
			String flipkartBarCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1613
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1614
			ttfFontFactory.register(flipkartBarCodeFontPath, "barcode");
9043 amar.kumar 1615
			Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 18);
9037 amar.kumar 1616
 
9043 amar.kumar 1617
			orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
9037 amar.kumar 1618
			PdfPCell flipkartOrderItemIdBarCodeCell = new PdfPCell(new Paragraph("*" +  new Long(flipkartOrder.getFlipkartSubOrderId()).toString() + "*", flipkartBarCodeFont));
1619
			flipkartOrderItemIdBarCodeCell.setBorder(Rectangle.NO_BORDER);
1620
			flipkartOrderItemIdBarCodeCell.setPaddingTop(9.0f);
9043 amar.kumar 1621
			//flipkartOrderItemIdBarCodeCell.setColspan(2);
1622
			//flipkartOrderItemIdBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1623
			orderTable.addCell(flipkartOrderItemIdBarCodeCell);
1624
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1625
			//orderTable.addCell(new Phrase(new Long(flipkartOrder.getFlipkartSubOrderId()).toString(), helvetica8));
8989 vikram.rag 1626
		}
1627
 
1628
 
7014 rajveer 1629
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
1630
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
13276 manish.sha 1631
 
1632
		if(OrderType.B2B==order.getOrderType()){
1633
			try {
1634
				String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
1635
				if(poRefVal!=null && poRefVal.length()>0){
1636
					orderTable.addCell(new Phrase("PO Ref:", helvetica8));
1637
					orderTable.addCell(new Phrase(poRefVal, helvetica8));
1638
				}
1639
 
1640
			} catch (TException e) {
1641
				logger.error("Error while getting amazon order", e);
1642
			}
1643
		}
2787 chandransh 1644
 
7014 rajveer 1645
		orderTable.addCell(new Phrase("Courier:", helvetica8));
13691 manish.sha 1646
		if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1647
			orderTable.addCell(new Phrase(hsCourierName, helvetica8));
1648
		} else{
1649
			orderTable.addCell(new Phrase(provider.getName(), helvetica8));
1650
		}
2787 chandransh 1651
 
9038 amar.kumar 1652
		if(order.getAirwaybill_no()!=null && !order.getAirwaybill_no().isEmpty()) {
1653
			orderTable.addCell(new Phrase("AWB No:", helvetica8));
1654
			orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
1655
		}
2787 chandransh 1656
 
7014 rajveer 1657
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
1658
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1659
 
7014 rajveer 1660
		return orderTable;
1661
	}
2787 chandransh 1662
 
13276 manish.sha 1663
	private PdfPTable getBottomInvoiceTable(List<Order> orderList,boolean isVAT, String invoiceFormat){
1664
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
7014 rajveer 1665
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 1666
 
13284 manish.sha 1667
		invoiceTable.addCell(getInvoiceTableHeader(8,orderList.get(0).getLogisticsTransactionId()));
4262 rajveer 1668
 
13276 manish.sha 1669
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1670
			invoiceTable.addCell(new Phrase("Sr No", helveticaBold8));
1671
		}else{
1672
			invoiceTable.addCell(new Phrase("Order No", helveticaBold8));
1673
		}
7014 rajveer 1674
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
1675
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
1676
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
1677
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
13276 manish.sha 1678
		invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
1679
		invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
19260 manish.sha 1680
		invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));
19276 manish.sha 1681
		invoiceTable.setHeaderRows(2);
13276 manish.sha 1682
		double totalAmount = 0.0;
1683
		double insuranceAmount = 0.0;
17470 manish.sha 1684
		double totalShippingCost = 0.0;
13276 manish.sha 1685
		int i=1;
1686
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1687
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1688
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1689
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1690
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1691
			Map<Long, Double> itemTaxPercentageMap = new HashMap<Long, Double>();
1692
			Map<Long, Double> itemTaxValueMap = new HashMap<Long, Double>();
1693
 
1694
			for(Order order : orderList){
1695
				LineItem lineitem = order.getLineitems().get(0);
1696
 
1697
				double orderAmount = order.getTotal_amount();
1698
				double rate = lineitem.getVatRate();
1699
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1700
				totalAmount = totalAmount + orderAmount;
17470 manish.sha 1701
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1702
				double itemPrice = lineitem.getUnit_price();
1703
				double showPrice = (100 * itemPrice)/(100 + rate);
1704
				double totalPrice = lineitem.getTotal_price();
1705
				double showTotalPrice = (100 * totalPrice)/(100 + rate);
1706
 
1707
				if(order.getInsurer() > 0) {
1708
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1709
				}
1710
 
1711
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1712
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1713
				}
1714
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1715
					double quantity = itemQuantityMap.get(lineitem.getItem_id()) + lineitem.getQuantity();
1716
					itemQuantityMap.put(lineitem.getItem_id(), quantity);
1717
				} else {
1718
					itemQuantityMap.put(lineitem.getItem_id(),lineitem.getQuantity());
1719
				}
1720
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1721
					itemRateMap.put(lineitem.getItem_id(), showPrice);
1722
				}
1723
				if(!itemTaxPercentageMap.containsKey(lineitem.getItem_id())){
1724
					itemTaxPercentageMap.put(lineitem.getItem_id(), rate);
1725
				}
1726
				if(itemTaxValueMap.containsKey(lineitem.getItem_id())){
1727
					double taxValue = itemTaxValueMap.get(lineitem.getItem_id()) + salesTax;
1728
					itemTaxValueMap.put(lineitem.getItem_id(), taxValue);
1729
				}else{
1730
					itemTaxValueMap.put(lineitem.getItem_id(), salesTax);
1731
				}
1732
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
1733
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + showTotalPrice;
1734
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1735
				}else{
1736
					itemTotalAmtMap.put(lineitem.getItem_id(), showTotalPrice);
1737
				}
1738
			}
1739
 
1740
			for(Long itemId : itemNamesMap.keySet()){
1741
				invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
1742
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId),helvetica8));
1743
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"",helvetica8));
13285 manish.sha 1744
				invoiceTable.addCell(getPriceCell(itemRateMap.get(itemId)));
1745
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)));
1746
				invoiceTable.addCell(new Phrase(itemTaxPercentageMap.get(itemId)+"%",helvetica8));
1747
				invoiceTable.addCell(getPriceCell(itemTaxValueMap.get(itemId)));
1748
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)+itemTaxValueMap.get(itemId)));
13313 manish.sha 1749
				i++;
13276 manish.sha 1750
			}
1751
		}
1752
		else{
9432 amar.kumar 1753
 
13276 manish.sha 1754
			for(Order order :orderList){
1755
				LineItem lineItem = order.getLineitems().get(0);
1756
				double orderAmount = order.getTotal_amount();
1757
				double rate = lineItem.getVatRate();
1758
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1759
 
1760
				invoiceTable.addCell(new Phrase(order.getId()+"", helveticaBold8));
1761
				invoiceTable.addCell(getProductNameCell(lineItem, true, order.getFreebieItemId()));
1762
				invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
1763
 
1764
 
1765
				//populateBottomInvoiceTable(order, invoiceTable, rate);
1766
 
1767
				double itemPrice = lineItem.getUnit_price();
1768
				double showPrice = (100 * itemPrice)/(100 + rate);
1769
				invoiceTable.addCell(getPriceCell(showPrice));
1770
 
1771
				double totalPrice = lineItem.getTotal_price();
1772
				showPrice = (100 * totalPrice)/(100 + rate);
1773
				invoiceTable.addCell(getPriceCell(showPrice));
1774
 
1775
				PdfPCell salesTaxCell = getPriceCell(salesTax);
1776
 
1777
 
1778
				invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
1779
				invoiceTable.addCell(salesTaxCell);
1780
				invoiceTable.addCell(getTotalAmountCell(orderAmount));
1781
 
1782
				if(order.getInsurer() > 0) {
1783
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1784
				}
1785
				totalAmount = totalAmount+ orderAmount;
17470 manish.sha 1786
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1787
				i++;
1788
			}
9432 amar.kumar 1789
		}
7014 rajveer 1790
 
13276 manish.sha 1791
		if(insuranceAmount>0){
1792
			invoiceTable.addCell(getInsuranceCell(7));
1793
			invoiceTable.addCell(getPriceCell(insuranceAmount));
7014 rajveer 1794
		}
17470 manish.sha 1795
		if(totalShippingCost>0){
17501 manish.sha 1796
			invoiceTable.addCell(getShippingCostCell(6));      
1797
			invoiceTable.addCell(getRupeesCell(false));
1798
			invoiceTable.addCell(getPriceCell(totalShippingCost));
17470 manish.sha 1799
		}
13276 manish.sha 1800
		invoiceTable.addCell(getTotalCell(6));
17501 manish.sha 1801
		invoiceTable.addCell(getRupeesCell(true));
17470 manish.sha 1802
		invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
7014 rajveer 1803
 
13276 manish.sha 1804
		invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
17470 manish.sha 1805
		invoiceTable.addCell(getAmountInWordsCell(totalAmount+totalShippingCost));
7014 rajveer 1806
 
13276 manish.sha 1807
		invoiceTable.addCell(getEOECell(8));
7014 rajveer 1808
 
1809
		return invoiceTable;
1810
	}
1811
 
13276 manish.sha 1812
	private PdfPCell getInvoiceTableHeader(int colspan, String masterOrderId) {
1813
		PdfPTable invoiceHeaderTable = new PdfPTable(2);
1814
		PdfPCell masterOrderIdCell = new PdfPCell(new Phrase("Master Order Id- "+masterOrderId, helvetica10));
13320 manish.sha 1815
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1816
			masterOrderIdCell.setBorder(Rectangle.NO_BORDER);
1817
			masterOrderIdCell.setPaddingTop(1);
1818
		}
13281 manish.sha 1819
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
7014 rajveer 1820
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
8551 manish.sha 1821
		invoiceTableHeader.setPaddingTop(1);
13276 manish.sha 1822
		invoiceHeaderTable.addCell(invoiceTableHeader);
13320 manish.sha 1823
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1824
			invoiceHeaderTable.addCell(masterOrderIdCell);
1825
		}else{
1826
			masterOrderIdCell = new PdfPCell(new Phrase(" ", helvetica10));
1827
			invoiceHeaderTable.addCell(masterOrderIdCell);
1828
		}
13283 manish.sha 1829
		PdfPCell headerCell = new PdfPCell(invoiceHeaderTable);
1830
		headerCell.setColspan(colspan);
1831
		return headerCell;
7014 rajveer 1832
	}
1833
 
13276 manish.sha 1834
	/*private void populateBottomInvoiceTable(List<Order> orderList, PdfPTable invoiceTable) {
7014 rajveer 1835
		for (LineItem lineitem : order.getLineitems()) {
1836
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
1837
 
7190 amar.kumar 1838
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 1839
 
1840
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
1841
 
1842
			double itemPrice = lineitem.getUnit_price();
1843
			double showPrice = (100 * itemPrice)/(100 + rate);
1844
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
1845
 
1846
			double totalPrice = lineitem.getTotal_price();
1847
			showPrice = (100 * totalPrice)/(100 + rate);
1848
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
1849
		}
13276 manish.sha 1850
	}*/
7014 rajveer 1851
 
7190 amar.kumar 1852
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 1853
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 1854
		if(freebieItemId!=null && freebieItemId!=0){
1855
			try {
1856
				CatalogService.Client catalogClient = ctsc.getClient();
1857
				Item item = catalogClient.getItem(freebieItemId);
1858
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
1859
			} catch(Exception tex) {
1860
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
1861
			}
1862
		}
7014 rajveer 1863
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
1864
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1865
		return productNameCell;
1866
	}
1867
 
1868
	private PdfPCell getPriceCell(double price) {
1869
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
1870
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1871
		return totalPriceCell;
1872
	}
1873
 
1874
	private PdfPCell getVATLabelCell(boolean isVAT) {
1875
		PdfPCell vatCell = null;
1876
		if(isVAT){
1877
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
1878
		} else {
1879
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
1880
		}
1881
		vatCell.setColspan(3);
1882
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1883
		return vatCell;
1884
	}
1885
 
9432 amar.kumar 1886
	private PdfPCell getCFORMLabelCell() {
1887
		PdfPCell cFormCell = null;
1888
		cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
1889
		cFormCell.setColspan(3);
1890
		cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1891
		return cFormCell;
1892
	}
1893
 
7318 rajveer 1894
	private PdfPCell getAdvanceAmountCell(int colspan) {
1895
		PdfPCell insuranceCell = null;
1896
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
1897
		insuranceCell.setColspan(colspan);
1898
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1899
		return insuranceCell;
1900
	}
1901
 
7014 rajveer 1902
	private PdfPCell getInsuranceCell(int colspan) {
1903
		PdfPCell insuranceCell = null;
13276 manish.sha 1904
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance. T&C Apply", helvetica8));
7014 rajveer 1905
		insuranceCell.setColspan(colspan);
1906
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1907
		return insuranceCell;
1908
	}
1909
 
1910
	private PdfPCell getEmptyCell(int colspan) {
1911
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
1912
		emptyCell.setColspan(colspan);
1913
		return emptyCell;
1914
	}
17470 manish.sha 1915
 
1916
	private PdfPCell getShippingCostCell(int colspan) {
1917
		PdfPCell shippingCostCell = new PdfPCell(new Phrase("Shipping Charges", helvetica8));
1918
		shippingCostCell.setColspan(colspan);
17501 manish.sha 1919
		shippingCostCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
17470 manish.sha 1920
		return shippingCostCell;
1921
	}
1922
 
1923
	private PdfPCell getCodChargesCell(int colspan) {
1924
		PdfPCell codChargesCell = new PdfPCell(new Phrase("COD Charges", helvetica8));
1925
		codChargesCell.setColspan(colspan);
1926
		return codChargesCell;
1927
	}
19003 manish.sha 1928
 
1929
	private PdfPCell getGvAmountCell(int colspan) {
1930
		PdfPCell codChargesCell = new PdfPCell(new Phrase("GV Amount", helvetica8));
1931
		codChargesCell.setColspan(colspan);
1932
		return codChargesCell;
1933
	}
7014 rajveer 1934
 
1935
	private PdfPCell getTotalCell(int colspan) {
13276 manish.sha 1936
		PdfPCell totalCell = new PdfPCell(new Phrase("Grand Total", helveticaBold8));
7014 rajveer 1937
		totalCell.setColspan(colspan);
1938
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1939
		return totalCell;
1940
	}
1941
 
17501 manish.sha 1942
	private PdfPCell getRupeesCell(boolean useBold) {
1943
		PdfPCell rupeesCell;
1944
		if(useBold)
1945
			rupeesCell= new PdfPCell(new Phrase("Rs.", helveticaBold8));
1946
		else
1947
			rupeesCell= new PdfPCell(new Phrase("Rs.", helvetica8));
7014 rajveer 1948
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1949
		return rupeesCell;
1950
	}
1951
 
1952
	private PdfPCell getTotalAmountCell(double orderAmount) {
1953
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
1954
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1955
		return totalAmountCell;
1956
	}
1957
 
1958
	/**
1959
	 * This method uses ICU4J libraries to convert the given amount into words
1960
	 * of Indian locale.
1961
	 * 
1962
	 * @param orderAmount
1963
	 *            The amount to convert.
1964
	 * @return the string representation of the given amount.
1965
	 */
1966
	private PdfPCell getAmountInWordsCell(double orderAmount) {
1967
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
1968
		StringBuilder amountInWords = new StringBuilder("Rs. ");
1969
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
1970
		amountInWords.append(" and ");
1971
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
1972
		amountInWords.append(" paise");
1973
 
1974
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
1975
		amountInWordsCell.setColspan(4);
1976
		return amountInWordsCell;
1977
	}
1978
 
1979
	/**
1980
	 * Returns the item name to be displayed in the invoice table.
1981
	 * 
1982
	 * @param lineitem
1983
	 *            The line item whose name has to be displayed
1984
	 * @param appendIMEI
1985
	 *            Whether to attach the IMEI No. to the item name
1986
	 * @return The name to be displayed for the given line item.
1987
	 */
1988
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
1989
		StringBuffer itemName = new StringBuffer();
1990
		if(lineitem.getBrand()!= null)
1991
			itemName.append(lineitem.getBrand() + " ");
1992
		if(lineitem.getModel_name() != null)
1993
			itemName.append(lineitem.getModel_name() + " ");
1994
		if(lineitem.getModel_number() != null )
1995
			itemName.append(lineitem.getModel_number() + " ");
1996
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
1997
			itemName.append("("+lineitem.getColor()+")");
13320 manish.sha 1998
		if(appendIMEI && lineitem.isSetSerial_number() && !lineitem.getSerial_number().isEmpty()){
7014 rajveer 1999
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
2000
		}
2001
 
2002
		return itemName.toString();
2003
	}
2004
 
2005
	/**
2006
	 * 
2007
	 * @param colspan
2008
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
2009
	 *         no. of columns
2010
	 */
2011
	private PdfPCell getEOECell(int colspan) {
2012
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
2013
		eoeCell.setColspan(colspan);
2014
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
2015
		return eoeCell;
2016
	}
2017
 
2018
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
2019
		PdfPTable extraInfoTable = new PdfPTable(1);
2020
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2021
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2022
 
2023
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
2024
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
2025
		ttfFontFactory.register(fontPath, "barcode");
2026
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
2027
 
2028
		PdfPCell extraInfoCell;
2029
		if(billingType == BillingType.EXTERNAL){
2030
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
2031
		}else{
2032
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
2033
		}
2034
 
2035
		extraInfoCell.setPaddingTop(20.0f);
2036
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
2037
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
2038
 
2039
		extraInfoTable.addCell(extraInfoCell);
2040
 
2041
 
2042
		return extraInfoTable;
2043
	}
2044
 
2045
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
2046
		PdfPTable extraInfoTable = new PdfPTable(1);
2047
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2048
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2049
 
2050
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
2051
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
2052
		ttfFontFactory.register(fontPath, "barcode");
2053
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
2054
 
2055
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
2056
 
2057
		extraInfoCell.setPaddingTop(20.0f);
2058
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
2059
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
2060
 
2061
		extraInfoTable.addCell(extraInfoCell);
2062
 
2063
		return extraInfoTable;
2064
	}
8067 manish.sha 2065
 
2066
	private void generateBarcode(String barcodeString, String fileName){
2067
		Code128Bean bean = new Code128Bean();
7014 rajveer 2068
 
8067 manish.sha 2069
		final int dpi = 60;
2070
 
2071
		//Configure the barcode generator
2072
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
2073
		                                                 //width exactly one pixel
2074
		bean.setFontSize(bean.getFontSize()+1.0f);
2075
		bean.doQuietZone(false);
2076
 
2077
		try {
2078
			File outputFile = new File("/tmp/"+fileName+".png");
2079
			OutputStream out = new FileOutputStream(outputFile);
2080
 
2081
		    //Set up the canvas provider for monochrome PNG output 
2082
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
2083
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
2084
 
2085
		    //Generate the barcode
2086
		    bean.generateBarcode(canvas, barcodeString);
2087
 
2088
		    //Signal end of generation
2089
		    canvas.finish();
2090
		    out.close();
2091
 
2092
		} 
2093
		catch(Exception e){
2094
			logger.error("Exception during generating Barcode : ", e);
2095
		}
2096
	}
2097
 
7014 rajveer 2098
	public static void main(String[] args) throws IOException {
2099
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 2100
		long orderId = 356324;
2101
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 2102
		String userHome = System.getProperty("user.home");
2103
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
2104
		FileOutputStream fos = new FileOutputStream(f);
2105
		baos.writeTo(fos);
2106
		System.out.println("Invoice generated.");
2107
	}
2787 chandransh 2108
}