Subversion Repositories SmartDukaan

Rev

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