Subversion Repositories SmartDukaan

Rev

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