Subversion Repositories SmartDukaan

Rev

Rev 20770 | Rev 20818 | 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));
20770 kshitij.so 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);
20811 kshitij.so 923
 
924
		if (provider.getId() ==1L){
925
			PdfPCell spnCell = new PdfPCell(new Phrase("SPN : 09650099008S", helvetica12));
926
			spnCell.setHorizontalAlignment(Element.ALIGN_LEFT);
927
			spnCell.setBorder(Rectangle.NO_BORDER);
928
			providerInfoTable.addCell(spnCell);
929
		}
930
 
7318 rajveer 931
		if(order.isLogisticsCod()){
8551 manish.sha 932
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica22));
7318 rajveer 933
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
934
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
935
			providerInfoTable.addCell(deliveryTypeCell);
936
		}
937
 
8035 manish.sha 938
 
7014 rajveer 939
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
940
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
941
		providerNameCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 942
		PdfPCell formIdCell= null;
19513 manish.sha 943
		if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
7994 manish.sha 944
			if(order.isCod()){
8034 manish.sha 945
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
7994 manish.sha 946
			}
947
			else{
8034 manish.sha 948
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
7994 manish.sha 949
			}
8551 manish.sha 950
			formIdCell.setPaddingTop(1.0f);
8015 rajveer 951
			formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
952
			formIdCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 953
		}
8015 rajveer 954
 
7994 manish.sha 955
 
956
		PdfPCell awbNumberCell= null;
8034 manish.sha 957
		String fedexPackageBarcode = "";
19513 manish.sha 958
		if(order.getLogistics_provider_id()!=7L && order.getLogistics_provider_id()!=46L){
7994 manish.sha 959
			awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
8017 manish.sha 960
			awbNumberCell.setPaddingTop(20.0f);
7994 manish.sha 961
		}
962
		else{
8013 rajveer 963
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
964
			try {
965
				fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
966
			} catch (TException e1) {
967
				logger.error("Error while getting the provider information.", e1);
968
			}
8174 manish.sha 969
			awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
970
		}
971
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
972
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
973
 
974
		providerInfoTable.addCell(providerNameCell);
975
		if(formIdCell != null){
976
			providerInfoTable.addCell(formIdCell);
977
		}
978
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 979
		if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
8169 manish.sha 980
			generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
981
 
982
			Image barcodeImage=null;
983
			try {
984
				barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
985
			} catch (Exception e) {
986
				logger.error("Exception during getting Barcode Image for Fedex : ", e);
987
			}
8174 manish.sha 988
			providerInfoTable.addCell(barcodeImage);
7994 manish.sha 989
		}
8174 manish.sha 990
		providerInfoTable.addCell(awbNumberCell);
7014 rajveer 991
 
7792 anupam.sin 992
		Warehouse warehouse = null;
993
		try{
994
    		InventoryClient isc = new InventoryClient();
7804 amar.kumar 995
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
7803 amar.kumar 996
		} catch(Exception e) {
7792 anupam.sin 997
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
7805 amar.kumar 998
		    //TODO throw e;
7792 anupam.sin 999
		}
1000
		DeliveryType dt =  DeliveryType.PREPAID;
1001
        if (order.isLogisticsCod()) {
1002
            dt = DeliveryType.COD;
1003
        }
7994 manish.sha 1004
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1005
        if(order.getLogistics_provider_id()!=7L && order.getLogistics_provider_id()!=46L){
7994 manish.sha 1006
	        for (ProviderDetails detail : provider.getDetails()) {
1007
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
1008
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
1009
	            }
1010
	        }
7792 anupam.sin 1011
        }
7994 manish.sha 1012
        else{
19515 manish.sha 1013
        	if(order.getLogistics_provider_id()==7L){
1014
        		providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
1015
        	}else{
1016
        		providerInfoTable.addCell(new Phrase("FEDEX EXPRESS SAVER ", helvetica8));
1017
        	}
7994 manish.sha 1018
        }
1019
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 1020
		Date awbDate;
1021
		if(order.getBilling_timestamp() == 0){
1022
			awbDate = new Date();
1023
		}else{
1024
			awbDate = new Date(order.getBilling_timestamp());
1025
		}
19513 manish.sha 1026
		if(order.getLogistics_provider_id()!=7L && order.getLogistics_provider_id()!=46L){
8106 manish.sha 1027
			providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
1028
		}
19260 manish.sha 1029
		providerInfoTable.addCell(new Phrase("Weight         : " + weightFormat.format(totalWeight) + " Kg", helvetica8));
20741 kshitij.so 1030
		if (order.getLogistics_provider_id()==1L){
20746 kshitij.so 1031
			ShipmentLogisticsCostDetail shipmentCostDetail = tsc.getClient().getCostDetailForLogisticsTxnId(order.getLogisticsTransactionId());
1032
			providerInfoTable.addCell(new Phrase("Dimensions(Cms)  : " +shipmentCostDetail.getPackageDimensions(), helvetica8));
20741 kshitij.so 1033
			providerInfoTable.addCell(new Phrase("Pieces  : " + "1", helvetica8));
1034
		}
8182 amar.kumar 1035
		if(order.getSource() == OrderSource.EBAY.getValue()){
1036
			EbayOrder ebayOrder = null;
1037
			try {
1038
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1039
			} catch (TException e) {
1040
				logger.error("Error while getting ebay order", e);
1041
			}
1042
			providerInfoTable.addCell(new Phrase("PaisaPayId            : " + ebayOrder.getPaisaPayId(), helvetica8));
1043
			providerInfoTable.addCell(new Phrase("Sales Rec Number: " + ebayOrder.getSalesRecordNumber(), helvetica8));
1044
		}
7994 manish.sha 1045
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1046
		if(order.getLogistics_provider_id()==7L || order.getLogistics_provider_id()==46L){
7994 manish.sha 1047
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
1048
		}
1049
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 1050
		return providerInfoTable;
1051
	}
1052
 
13276 manish.sha 1053
	private PdfPTable getTopInvoiceTable(List<Order> orderList, String tinNo, String invoiceFormat){
7014 rajveer 1054
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
1055
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1056
 
13276 manish.sha 1057
		invoiceTable.addCell(getInvoiceTableHeader(6,orderList.get(0).getLogisticsTransactionId()));
1058
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1059
			invoiceTable.addCell(new Phrase("Sr No", helvetica8));
1060
		}else{
1061
			invoiceTable.addCell(new Phrase("Order No", helvetica8));
1062
		}
7014 rajveer 1063
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
1064
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
1065
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
1066
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
1067
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
19276 manish.sha 1068
		invoiceTable.setHeaderRows(2);
13276 manish.sha 1069
		double totalAmount = 0.0;
17470 manish.sha 1070
		double totalShippingCost = 0.0;
13276 manish.sha 1071
		double insuranceAmount = 0.0;
1072
		double advanceAmount = 0.0;
19003 manish.sha 1073
		double totalGvAmount = 0.0;
13276 manish.sha 1074
 
1075
 
1076
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1077
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1078
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1079
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1080
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1081
			String paymentMode = "";
1082
			for(Order order : orderList){
1083
				LineItem lineitem = order.getLineitems().get(0);
19003 manish.sha 1084
				totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount()-order.getGvAmount();
17470 manish.sha 1085
				totalShippingCost = totalShippingCost + order.getShippingCost();
19003 manish.sha 1086
				totalGvAmount = totalGvAmount + order.getGvAmount();
13276 manish.sha 1087
				if(order.getInsurer() > 0) {
1088
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1089
				}
1090
				if(order.getSource() == OrderSource.STORE.getValue()) {
1091
					advanceAmount = advanceAmount + order.getAdvanceAmount();
1092
				}
1093
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1094
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1095
				}
1096
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1097
					itemRateMap.put(lineitem.getItem_id(), lineitem.getUnit_price());
1098
				}
1099
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1100
					double currentQuantity = itemQuantityMap.get(lineitem.getItem_id()) +lineitem.getQuantity();
1101
					itemQuantityMap.put(lineitem.getItem_id(), currentQuantity);
1102
				}else{
1103
					itemQuantityMap.put(lineitem.getItem_id(), lineitem.getQuantity());
1104
				}
1105
 
1106
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
13492 manish.sha 1107
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount());
13276 manish.sha 1108
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1109
				}else{
13492 manish.sha 1110
					itemTotalAmtMap.put(lineitem.getItem_id(), (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount()));
13276 manish.sha 1111
				}
1112
				if(paymentMode==null || paymentMode.isEmpty()){
1113
					if(order.getPickupStoreId() > 0 && order.isCod() == true)
1114
						paymentMode = "In-Store";
1115
					else if (order.isCod())
1116
						paymentMode = "COD";
1117
					else
1118
						paymentMode = "Prepaid";
1119
				}		
1120
			}
1121
 
1122
			int serialNo = 0;
1123
			for(Long itemId : itemNamesMap.keySet()){
1124
				serialNo ++;
1125
				invoiceTable.addCell(new Phrase(serialNo+ "", helvetica8));
1126
				invoiceTable.addCell(new Phrase(paymentMode, helvetica8));
1127
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId), helvetica8));
1128
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"", helvetica8));
1129
				invoiceTable.addCell(new Phrase(itemRateMap.get(itemId)+"", helvetica8));
1130
				invoiceTable.addCell(new Phrase(itemTotalAmtMap.get(itemId)+"", helvetica8));
1131
			}
1132
 
1133
		}else{
1134
			for(Order order : orderList){
1135
				populateTopInvoiceTable(order, invoiceTable);
1136
				if(order.getInsurer() > 0) {
1137
					invoiceTable.addCell(getInsuranceCell(4));
1138
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
1139
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
1140
				}
7014 rajveer 1141
 
13276 manish.sha 1142
				if(order.getSource() == OrderSource.STORE.getValue()) {
1143
					invoiceTable.addCell(getAdvanceAmountCell(4));
1144
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
1145
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
1146
				}
19003 manish.sha 1147
				if(order.getInsurer() > 0) {
1148
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1149
				}
1150
				if(order.getSource() == OrderSource.STORE.getValue()) {
1151
					advanceAmount = advanceAmount + order.getAdvanceAmount();
1152
				}
1153
				totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount()-order.getGvAmount();
17470 manish.sha 1154
				totalShippingCost = totalShippingCost + order.getShippingCost();
19003 manish.sha 1155
				totalGvAmount = totalGvAmount + order.getGvAmount();
13276 manish.sha 1156
			}
7014 rajveer 1157
		}
19003 manish.sha 1158
		if(insuranceAmount>0){
1159
			invoiceTable.addCell(getInsuranceCell(4));
1160
			invoiceTable.addCell(getPriceCell(insuranceAmount));
1161
			invoiceTable.addCell(getPriceCell(insuranceAmount));
1162
		}
1163
		if(advanceAmount>0){
1164
			invoiceTable.addCell(getAdvanceAmountCell(4));
1165
			invoiceTable.addCell(getPriceCell(advanceAmount));
1166
			invoiceTable.addCell(getPriceCell(advanceAmount));
1167
		}
17470 manish.sha 1168
		if(totalShippingCost>0){
1169
			invoiceTable.addCell(getShippingCostCell(4));      
17501 manish.sha 1170
			invoiceTable.addCell(getRupeesCell(false));
1171
			invoiceTable.addCell(getPriceCell(totalShippingCost));
17470 manish.sha 1172
		}
19003 manish.sha 1173
		if(totalGvAmount>0){
1174
			totalGvAmount = 0-totalGvAmount;
1175
			invoiceTable.addCell(getGvAmountCell(4));      
1176
			invoiceTable.addCell(getRupeesCell(false));
1177
			invoiceTable.addCell(getPriceCell(totalGvAmount));
1178
		}
7014 rajveer 1179
		invoiceTable.addCell(getTotalCell(4));      
17501 manish.sha 1180
		invoiceTable.addCell(getRupeesCell(true));
17470 manish.sha 1181
		invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
13276 manish.sha 1182
 
7014 rajveer 1183
 
1184
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
1185
		tinCell.setColspan(6);
1186
		tinCell.setPadding(2);
1187
		invoiceTable.addCell(tinCell);
1188
 
1189
		return invoiceTable;
1190
	}
1191
 
1192
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
1193
		List<LineItem> lineitems = order.getLineitems();
1194
		for (LineItem lineitem : lineitems) {
1195
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
1196
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
1197
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
1198
			else if (order.isCod())
1199
				invoiceTable.addCell(new Phrase("COD", helvetica8));
1200
			else
1201
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 1202
 
7190 amar.kumar 1203
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 1204
 
7014 rajveer 1205
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 1206
 
19003 manish.sha 1207
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()));
7014 rajveer 1208
 
19003 manish.sha 1209
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()));
7014 rajveer 1210
		}
1211
	}
1212
 
1213
	private PdfPCell getAddressCell(String address) {
1214
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
1215
		PdfPCell addressCell = new PdfPCell();
1216
		addressCell.addElement(addressParagraph);
1217
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1218
		addressCell.setBorder(Rectangle.NO_BORDER);
1219
		return addressCell;
1220
	}
1221
 
13276 manish.sha 1222
	private PdfPTable getTaxCumRetailInvoiceTable(List<Order> orderList, Provider provider, String ourAddress, String tinNo, String invoiceFormat){
1223
		Order order = orderList.get(0);
7014 rajveer 1224
		PdfPTable taxTable = new PdfPTable(1);
1225
		Phrase phrase = null;
18847 manish.sha 1226
		taxTable.setSplitLate(false);
7014 rajveer 1227
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1228
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
8104 manish.sha 1229
 
8110 manish.sha 1230
		PdfPTable logoTitleAndOurAddressTable = new PdfPTable(new float[]{0.4f, 0.3f, 0.3f});
8107 manish.sha 1231
		logoTitleAndOurAddressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8112 manish.sha 1232
		logoTitleAndOurAddressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
8107 manish.sha 1233
 
8110 manish.sha 1234
 
8103 manish.sha 1235
		PdfPTable logoTable = new PdfPTable(2);
1236
		addLogoTable(logoTable,order); 
7318 rajveer 1237
 
7014 rajveer 1238
 
19723 manish.sha 1239
		Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- +91-9818116289" + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
7014 rajveer 1240
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
1241
		sorlAddressCell.addElement(sorlAddress);
8110 manish.sha 1242
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
20742 kshitij.so 1243
 
1244
 
18769 manish.sha 1245
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true, false);
18657 manish.sha 1246
		if (order.getOrderType().equals(OrderType.B2B)) {
1247
			if(billingAddress!=null){
1248
				if(order.getCustomer_state().trim().equalsIgnoreCase(billingAddress.getState())){
1249
					phrase = new Phrase("TAX INVOICE", helveticaBold12);
1250
				}else{
1251
					phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1252
				}
1253
			}else{
1254
				phrase = new Phrase("TAX INVOICE", helveticaBold12);
1255
			}
1256
		} else {
1257
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1258
		}
18693 manish.sha 1259
 
1260
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
1261
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1262
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
1263
 
7014 rajveer 1264
		PdfPTable orderDetails = getOrderDetails(order, provider);
1265
 
1266
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
1267
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1268
		addrAndOrderDetailsTable.addCell(customerAddress);
1269
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
1270
		addrAndOrderDetailsTable.addCell(orderDetails);
1271
 
9319 amar.kumar 1272
		boolean isVAT = isVatApplicable(order);
13276 manish.sha 1273
		PdfPTable invoiceTable = getBottomInvoiceTable(orderList, isVAT, invoiceFormat);
7014 rajveer 1274
 
10607 manish.sha 1275
		PdfPTable regAddAndDisCellTable = new PdfPTable(2);
1276
 
20686 amit.gupta 1277
		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 1278
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1279
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
19985 amit.gupta 1280
		PdfPCell regAddressCell = new PdfPCell(new Phrase(sellerInfo.getOrganisationName() + "\n" +
1281
										"Regd. Add. " +  sellerInfo.getRegisteredAddress() + "\n" + 
1282
										(StringUtils.isEmpty(sellerInfo.getCinNumber())? "" :"CIN: " + sellerInfo.getCinNumber() + "\n") +  
19973 amit.gupta 1283
										"Tel. No. +91-9818116289 E-mail. help@saholic.com Website. www.saholic.com", helvetica6));
10607 manish.sha 1284
		regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1285
		regAddressCell.setBorder(Rectangle.NO_BORDER);
1286
		/*SPICE ONLINE RETAIL PRIVATE LIMITED
1287
		Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
1288
		CIN: U74140DL2008PTC183856
1289
		Tel. No. 0120-2479977
1290
		E-mail. help@saholic.com
1291
		Website. www.saholic.com*/
9014 amar.kumar 1292
		PdfPCell powerTextCell = new PdfPCell(new Phrase("Powered By  Flipkart", helvetica8));
1293
		powerTextCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1294
		powerTextCell.setBorder(Rectangle.NO_BORDER);
1295
		powerTextCell.setPaddingBottom(30.0f);
8104 manish.sha 1296
 
1297
		logoTitleAndOurAddressTable.addCell(logoTable);
8110 manish.sha 1298
		logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
1299
		logoTitleAndOurAddressTable.addCell(sorlAddress);
8104 manish.sha 1300
 
10607 manish.sha 1301
		regAddAndDisCellTable.addCell(disclaimerCell);
1302
		regAddAndDisCellTable.addCell(regAddressCell);
1303
 
8104 manish.sha 1304
		taxTable.addCell(logoTitleAndOurAddressTable);
7014 rajveer 1305
		taxTable.addCell(addrAndOrderDetailsTable);
1306
		taxTable.addCell(invoiceTable);
10608 manish.sha 1307
		taxTable.addCell(regAddAndDisCellTable);
9014 amar.kumar 1308
		if(order.getSource() == OrderSource.FLIPKART.getValue()) {
1309
			taxTable.addCell(powerTextCell);
1310
 
1311
		}
10320 amar.kumar 1312
		if(order.getProductCondition().equals(ProductCondition.BAD)){
10328 amar.kumar 1313
			PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
10320 amar.kumar 1314
					"may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
1315
					"are not returnable, exchangeable or refundable under any circumstances. No " +
1316
					"warranty is assured on these items." ,
10329 amar.kumar 1317
					new Font(FontFamily.TIMES_ROMAN, 8f)));
10328 amar.kumar 1318
			badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1319
			badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
1320
			taxTable.addCell(badSaleDisclaimerCell);
10320 amar.kumar 1321
		}
7014 rajveer 1322
		return taxTable;
1323
	}
9009 amar.kumar 1324
 
9319 amar.kumar 1325
	private boolean isVatApplicable(Order order) {
1326
		if(order.getWarehouse_id() == 7) {
1327
			if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
1328
				return true;
1329
			} else {
1330
				return false;
1331
			}
12809 manish.sha 1332
		} else if(order.getWarehouse_id() == 3298){
1333
			for(int i=0; i< telanganaPincodes.length; i++) {
1334
				if(order.getCustomer_pincode().trim().equalsIgnoreCase(telanganaPincodes[i])) {
1335
					return true;
1336
				}
1337
			}
1338
			return false;
16196 manish.sha 1339
		} else if(order.getWarehouse_id() == 1765 || order.getWarehouse_id() == 1768){
1340
			for(int i=0; i< karnatakaPincodePrefix.length; i++) {
1341
				if(order.getCustomer_pincode().startsWith(karnatakaPincodePrefix[i])) {
1342
					return true;
1343
				}
1344
			}
1345
			return false;
12809 manish.sha 1346
		}
1347
		else {
9319 amar.kumar 1348
			for(int i=0; i< maharashtraPincodePrefix.length; i++) {
1349
				if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
1350
					return true;
1351
				}
1352
			}
1353
			return false;
1354
		}
1355
	}
1356
 
9037 amar.kumar 1357
	private PdfPTable getFlipkartBarCodes(Order order) {
1358
		PdfPTable flipkartTable = new PdfPTable(3);
1359
 
1360
		PdfPCell spacerCell = new PdfPCell();
9040 amar.kumar 1361
		spacerCell.setBorder(Rectangle.NO_BORDER);
9037 amar.kumar 1362
		spacerCell.setColspan(3);
9099 amar.kumar 1363
		spacerCell.setPaddingTop(330.0f);
9037 amar.kumar 1364
 
1365
		String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1366
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1367
		ttfFontFactory.register(flipkartCodeFontPath, "barcode");
1368
		Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
1369
 
9040 amar.kumar 1370
		String serialNumber = "0000000000";
9511 manish.sha 1371
		if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
9040 amar.kumar 1372
			serialNumber = order.getLineitems().get(0).getSerial_number();
9511 manish.sha 1373
		} else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
9040 amar.kumar 1374
			serialNumber = order.getLineitems().get(0).getItem_number();
1375
		}
1376
 
1377
		PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
9037 amar.kumar 1378
		serialNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1379
		serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1380
		serialNumberBarCodeCell.setPaddingTop(11.0f);
1381
 
1382
 
1383
		PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
1384
		invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1385
		invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1386
		invoiceNumberBarCodeCell.setPaddingTop(11.0f);
1387
 
1388
		double rate = order.getLineitems().get(0).getVatRate();
1389
		double salesTax = (rate * order.getTotal_amount())/(100 + rate);
9040 amar.kumar 1390
		PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
9037 amar.kumar 1391
		vatAmtBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1392
		vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1393
		vatAmtBarCodeCell.setPaddingTop(11.0f);
1394
 
1395
		flipkartTable.addCell(spacerCell);
1396
		flipkartTable.addCell(serialNumberBarCodeCell);
1397
		flipkartTable.addCell(invoiceNumberBarCodeCell);
1398
		flipkartTable.addCell(vatAmtBarCodeCell);
1399
 
1400
		return flipkartTable;
1401
 
9009 amar.kumar 1402
	}
18657 manish.sha 1403
 
1404
	private void setBillingAddress(long userId, in.shop2020.model.v1.user.UserContextService.Client userClient) throws TException{
1405
		billingAddress = userClient.getBillingAddressForUser(userId);
1406
	}
9009 amar.kumar 1407
 
18530 manish.sha 1408
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce, boolean billingAdd){
7014 rajveer 1409
		PdfPTable customerTable = new PdfPTable(1);
20741 kshitij.so 1410
		//customerTable.addCell(new Phrase("Deliver To :",font));
7014 rajveer 1411
		if(forInvoce || order.getPickupStoreId() == 0){
18530 manish.sha 1412
			in.shop2020.model.v1.user.UserContextService.Client userClient = usc.getClient();
1413
			try {
1414
				if(billingAdd && userClient.isPrivateDealUser(order.getCustomer_id())){
18657 manish.sha 1415
					setBillingAddress(order.getCustomer_id(), userClient);
1416
					if(billingAddress!=null){
18769 manish.sha 1417
						return customerTable;
1418
						/*
18657 manish.sha 1419
						customerTable.addCell(new Phrase(billingAddress.getName(), font));
1420
						customerTable.addCell(new Phrase(billingAddress.getLine1(), font));
1421
						customerTable.addCell(new Phrase(billingAddress.getLine2(), font));
1422
						customerTable.addCell(new Phrase(billingAddress.getCity() + "," + billingAddress.getState(), font));
1423
						customerTable.addCell(new Phrase(billingAddress.getPin(), font));
1424
						customerTable.addCell(new Phrase("Phone : " + (billingAddress.getPhone()== null ? "" : billingAddress.getPhone()), font));
18769 manish.sha 1425
						*/
18657 manish.sha 1426
					}else{
20742 kshitij.so 1427
						if (!forInvoce)
1428
							customerTable.addCell(new Phrase("Deliver To:", font));
18657 manish.sha 1429
						customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1430
						if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1431
							HsOrder hsOrder = null;
1432
							try {
1433
								hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1434
							}catch (TException e) {
1435
								logger.error("Error while getting homeshop18 order", e);
1436
							}
1437
							String hsShippingName = hsOrder.getShippingName();
1438
							if(hsShippingName!=null && !hsShippingName.isEmpty()){
1439
								customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1440
							}
1441
						}
1442
						customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1443
						customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1444
						customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1445
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1446
						if(order.getLogistics_provider_id()!=7L  && order.getLogistics_provider_id()!=46L){
18657 manish.sha 1447
							if(destCode != null)
1448
								customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1449
							else
1450
								customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1451
							}
1452
						else{
1453
							in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1454
							String fedexLocationcode = "";
1455
							try {
1456
								fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1457
							} catch (TException e1) {
1458
								logger.error("Error while getting the provider information.", e1);
1459
							}
1460
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1461
						}
1462
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1463
						if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1464
							customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1465
						}
1466
					}
18530 manish.sha 1467
				}else{
18769 manish.sha 1468
					customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
20742 kshitij.so 1469
					if(!forInvoce)
1470
						customerTable.addCell(new Phrase("Deliver To:", font));
18530 manish.sha 1471
					customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1472
					if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1473
						HsOrder hsOrder = null;
1474
						try {
1475
							hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1476
						}catch (TException e) {
1477
							logger.error("Error while getting homeshop18 order", e);
1478
						}
1479
						String hsShippingName = hsOrder.getShippingName();
1480
						if(hsShippingName!=null && !hsShippingName.isEmpty()){
1481
							customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1482
						}
1483
					}
1484
					customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1485
					customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1486
					customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1487
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1488
					if(order.getLogistics_provider_id()!=7L  && order.getLogistics_provider_id()!=46L){
18530 manish.sha 1489
						if(destCode != null)
1490
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1491
						else
1492
							customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1493
						}
1494
					else{
1495
						in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1496
						String fedexLocationcode = "";
1497
						try {
1498
							fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1499
						} catch (TException e1) {
1500
							logger.error("Error while getting the provider information.", e1);
1501
						}
1502
						customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1503
					}
1504
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1505
					if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1506
						customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1507
					}
13734 manish.sha 1508
				}
18530 manish.sha 1509
			} catch (TException e2) {
1510
				e2.printStackTrace();
13734 manish.sha 1511
			}
18530 manish.sha 1512
 
7014 rajveer 1513
		}else{
18769 manish.sha 1514
			customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7014 rajveer 1515
			try {
5556 rajveer 1516
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 1517
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
20742 kshitij.so 1518
				if(!forInvoce)
1519
					customerTable.addCell(new Phrase("Deliver To:", font));
7014 rajveer 1520
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
1521
				customerTable.addCell(new Phrase(store.getLine1(), font));
1522
				customerTable.addCell(new Phrase(store.getLine2(), font));
1523
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
1524
				if(destCode != null)
1525
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
1526
				else
1527
					customerTable.addCell(new Phrase(store.getPin(), font));
1528
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 1529
			} catch (TException e) {
1530
				// TODO Auto-generated catch block
1531
				e.printStackTrace();
1532
			}
5527 anupam.sin 1533
 
7014 rajveer 1534
		}
1535
 
1536
		if(order.getOrderType().equals(OrderType.B2B)) {
1537
			String tin = null;
1538
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1539
			List<Attribute> attributes;
1540
			try {
1541
				attributes = tclient.getAllAttributesForOrderId(order.getId());
1542
 
1543
				for(Attribute attribute : attributes) {
1544
					if(attribute.getName().equals("tinNumber")) {
1545
						tin = attribute.getValue();
1546
					}
1547
				}
1548
				if (tin != null) {
1549
					customerTable.addCell(new Phrase("TIN :" + tin, font));
1550
				}
1551
 
1552
			} catch (Exception e) {
1553
				logger.error("Error while getting order attributes", e);
1554
			}
1555
		}
1556
		/*
2787 chandransh 1557
        if(showPaymentMode){
1558
            customerTable.addCell(new Phrase(" ", font));
1559
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 1560
        }*/
7014 rajveer 1561
		return customerTable;
1562
	}
2787 chandransh 1563
 
7014 rajveer 1564
	private PdfPTable getOrderDetails(Order order, Provider provider){
1565
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
1566
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 1567
 
7014 rajveer 1568
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
1569
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 1570
 
7014 rajveer 1571
		orderTable.addCell(new Phrase("Date:", helvetica8));
1572
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1573
 
13691 manish.sha 1574
		String hsCourierName = "";
12590 amit.gupta 1575
		if(order.getSource() == OrderSource.AMAZON.getValue() || order.getSource() == OrderSource.JUNGLEE.getValue()){
7528 rajveer 1576
			AmazonOrder aorder = null;
1577
			try {
1578
				aorder = tsc.getClient().getAmazonOrder(order.getId());
1579
			} catch (TException e) {
1580
				logger.error("Error while getting amazon order", e);
1581
			}
12590 amit.gupta 1582
			if(order.getSource() == OrderSource.JUNGLEE.getValue()){
1583
				orderTable.addCell(new Phrase("Junglee Order ID:", helvetica8));
1584
			}else {
1585
				orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
1586
			}
7528 rajveer 1587
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
13691 manish.sha 1588
		} else if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1589
			HsOrder hsOrder = null;
1590
			try {
13706 manish.sha 1591
				hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
13691 manish.sha 1592
			}catch (TException e) {
1593
				logger.error("Error while getting homeshop18 order", e);
1594
			}
1595
			hsCourierName = hsOrder.getCourierName();
1596
			orderTable.addCell(new Phrase("HomeShop18 Order No:", helvetica8));
1597
			orderTable.addCell(new Phrase(hsOrder.getHsOrderNo(), helvetica8));
1598
			orderTable.addCell(new Phrase("HomeShop18 Sub Order No:", helvetica8));
1599
			orderTable.addCell(new Phrase(hsOrder.getHsSubOrderNo(), helvetica8));
1600
 
8182 amar.kumar 1601
		} else if(order.getSource() == OrderSource.EBAY.getValue()){
1602
			EbayOrder ebayOrder = null;
1603
			try {
1604
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1605
			} catch (TException e) {
1606
				logger.error("Error while getting ebay order", e);
1607
			}
1608
			orderTable.addCell(new Phrase("PaisaPayId:", helvetica8));
1609
			orderTable.addCell(new Phrase(ebayOrder.getPaisaPayId(), helvetica8));
1610
			orderTable.addCell(new Phrase("Sales Rec Number:", helvetica8));
1611
			orderTable.addCell(new Phrase(new Long(ebayOrder.getSalesRecordNumber()).toString(), helvetica8));
8488 amar.kumar 1612
		} else if(order.getSource() == OrderSource.SNAPDEAL.getValue()){
1613
			SnapdealOrder snapdealOrder = null;
1614
			try {
11424 kshitij.so 1615
				snapdealOrder = tsc.getClient().getSnapdealOrder(order.getId(), null, null).get(0);
8488 amar.kumar 1616
			} catch (TException e) {
1617
				logger.error("Error while getting snapdeal order", e);
1618
			}
1619
			orderTable.addCell(new Phrase("Snapdeal OrderId:", helvetica8));
1620
			orderTable.addCell(new Phrase(new Long(snapdealOrder.getSubOrderId()).toString(), helvetica8));
8828 amar.kumar 1621
 
1622
			String refernceCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1623
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1624
			ttfFontFactory.register(refernceCodeFontPath, "barcode");
8876 amar.kumar 1625
			Font referenceCodeBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
8828 amar.kumar 1626
 
8874 amar.kumar 1627
			PdfPCell snapdealReferenceBarCodeCell = new PdfPCell(new Paragraph("*" +  snapdealOrder.getReferenceCode() + "*", referenceCodeBarCodeFont));
8828 amar.kumar 1628
			snapdealReferenceBarCodeCell.setBorder(Rectangle.NO_BORDER);
8876 amar.kumar 1629
			snapdealReferenceBarCodeCell.setPaddingTop(9.0f);
1630
			snapdealReferenceBarCodeCell.setColspan(2);
9042 amar.kumar 1631
			snapdealReferenceBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
8876 amar.kumar 1632
			//orderTable.addCell(new Phrase("Snapdeal ReferenceCode:", helvetica8));
8828 amar.kumar 1633
			orderTable.addCell(snapdealReferenceBarCodeCell);
1634
			//orderTable.addCell(new Phrase(snapdealOrder.getReferenceCode(), helvetica8));
7528 rajveer 1635
		}
8989 vikram.rag 1636
		else if(order.getSource() == OrderSource.FLIPKART.getValue()){
1637
			FlipkartOrder flipkartOrder = null;
1638
			try {
1639
				flipkartOrder = tsc.getClient().getFlipkartOrder(order.getId());
1640
			} catch (TException e) {
8996 amar.kumar 1641
				logger.error("Error while getting flipkart order", e);
8989 vikram.rag 1642
			}
1643
			orderTable.addCell(new Phrase("Flipkart OrderId:", helvetica8));
1644
			orderTable.addCell(new Phrase(flipkartOrder.getFlipkartOrderId(), helvetica8));
9037 amar.kumar 1645
 
1646
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1647
			String flipkartBarCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1648
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1649
			ttfFontFactory.register(flipkartBarCodeFontPath, "barcode");
9043 amar.kumar 1650
			Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 18);
9037 amar.kumar 1651
 
9043 amar.kumar 1652
			orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
9037 amar.kumar 1653
			PdfPCell flipkartOrderItemIdBarCodeCell = new PdfPCell(new Paragraph("*" +  new Long(flipkartOrder.getFlipkartSubOrderId()).toString() + "*", flipkartBarCodeFont));
1654
			flipkartOrderItemIdBarCodeCell.setBorder(Rectangle.NO_BORDER);
1655
			flipkartOrderItemIdBarCodeCell.setPaddingTop(9.0f);
9043 amar.kumar 1656
			//flipkartOrderItemIdBarCodeCell.setColspan(2);
1657
			//flipkartOrderItemIdBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1658
			orderTable.addCell(flipkartOrderItemIdBarCodeCell);
1659
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1660
			//orderTable.addCell(new Phrase(new Long(flipkartOrder.getFlipkartSubOrderId()).toString(), helvetica8));
8989 vikram.rag 1661
		}
1662
 
1663
 
7014 rajveer 1664
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
1665
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
13276 manish.sha 1666
 
1667
		if(OrderType.B2B==order.getOrderType()){
1668
			try {
1669
				String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
1670
				if(poRefVal!=null && poRefVal.length()>0){
1671
					orderTable.addCell(new Phrase("PO Ref:", helvetica8));
1672
					orderTable.addCell(new Phrase(poRefVal, helvetica8));
1673
				}
1674
 
1675
			} catch (TException e) {
1676
				logger.error("Error while getting amazon order", e);
1677
			}
1678
		}
2787 chandransh 1679
 
7014 rajveer 1680
		orderTable.addCell(new Phrase("Courier:", helvetica8));
13691 manish.sha 1681
		if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1682
			orderTable.addCell(new Phrase(hsCourierName, helvetica8));
1683
		} else{
1684
			orderTable.addCell(new Phrase(provider.getName(), helvetica8));
1685
		}
2787 chandransh 1686
 
9038 amar.kumar 1687
		if(order.getAirwaybill_no()!=null && !order.getAirwaybill_no().isEmpty()) {
1688
			orderTable.addCell(new Phrase("AWB No:", helvetica8));
1689
			orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
1690
		}
2787 chandransh 1691
 
7014 rajveer 1692
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
1693
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1694
 
7014 rajveer 1695
		return orderTable;
1696
	}
2787 chandransh 1697
 
13276 manish.sha 1698
	private PdfPTable getBottomInvoiceTable(List<Order> orderList,boolean isVAT, String invoiceFormat){
1699
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
7014 rajveer 1700
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 1701
 
13284 manish.sha 1702
		invoiceTable.addCell(getInvoiceTableHeader(8,orderList.get(0).getLogisticsTransactionId()));
4262 rajveer 1703
 
13276 manish.sha 1704
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1705
			invoiceTable.addCell(new Phrase("Sr No", helveticaBold8));
1706
		}else{
1707
			invoiceTable.addCell(new Phrase("Order No", helveticaBold8));
1708
		}
7014 rajveer 1709
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
1710
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
1711
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
1712
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
13276 manish.sha 1713
		invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
1714
		invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
19260 manish.sha 1715
		invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));
19276 manish.sha 1716
		invoiceTable.setHeaderRows(2);
13276 manish.sha 1717
		double totalAmount = 0.0;
1718
		double insuranceAmount = 0.0;
17470 manish.sha 1719
		double totalShippingCost = 0.0;
13276 manish.sha 1720
		int i=1;
1721
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1722
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1723
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1724
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1725
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1726
			Map<Long, Double> itemTaxPercentageMap = new HashMap<Long, Double>();
1727
			Map<Long, Double> itemTaxValueMap = new HashMap<Long, Double>();
1728
 
1729
			for(Order order : orderList){
1730
				LineItem lineitem = order.getLineitems().get(0);
1731
 
1732
				double orderAmount = order.getTotal_amount();
1733
				double rate = lineitem.getVatRate();
1734
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1735
				totalAmount = totalAmount + orderAmount;
17470 manish.sha 1736
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1737
				double itemPrice = lineitem.getUnit_price();
1738
				double showPrice = (100 * itemPrice)/(100 + rate);
1739
				double totalPrice = lineitem.getTotal_price();
1740
				double showTotalPrice = (100 * totalPrice)/(100 + rate);
1741
 
1742
				if(order.getInsurer() > 0) {
1743
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1744
				}
1745
 
1746
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1747
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1748
				}
1749
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1750
					double quantity = itemQuantityMap.get(lineitem.getItem_id()) + lineitem.getQuantity();
1751
					itemQuantityMap.put(lineitem.getItem_id(), quantity);
1752
				} else {
1753
					itemQuantityMap.put(lineitem.getItem_id(),lineitem.getQuantity());
1754
				}
1755
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1756
					itemRateMap.put(lineitem.getItem_id(), showPrice);
1757
				}
1758
				if(!itemTaxPercentageMap.containsKey(lineitem.getItem_id())){
1759
					itemTaxPercentageMap.put(lineitem.getItem_id(), rate);
1760
				}
1761
				if(itemTaxValueMap.containsKey(lineitem.getItem_id())){
1762
					double taxValue = itemTaxValueMap.get(lineitem.getItem_id()) + salesTax;
1763
					itemTaxValueMap.put(lineitem.getItem_id(), taxValue);
1764
				}else{
1765
					itemTaxValueMap.put(lineitem.getItem_id(), salesTax);
1766
				}
1767
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
1768
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + showTotalPrice;
1769
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1770
				}else{
1771
					itemTotalAmtMap.put(lineitem.getItem_id(), showTotalPrice);
1772
				}
1773
			}
1774
 
1775
			for(Long itemId : itemNamesMap.keySet()){
1776
				invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
1777
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId),helvetica8));
1778
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"",helvetica8));
13285 manish.sha 1779
				invoiceTable.addCell(getPriceCell(itemRateMap.get(itemId)));
1780
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)));
1781
				invoiceTable.addCell(new Phrase(itemTaxPercentageMap.get(itemId)+"%",helvetica8));
1782
				invoiceTable.addCell(getPriceCell(itemTaxValueMap.get(itemId)));
1783
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)+itemTaxValueMap.get(itemId)));
13313 manish.sha 1784
				i++;
13276 manish.sha 1785
			}
1786
		}
1787
		else{
9432 amar.kumar 1788
 
13276 manish.sha 1789
			for(Order order :orderList){
1790
				LineItem lineItem = order.getLineitems().get(0);
1791
				double orderAmount = order.getTotal_amount();
1792
				double rate = lineItem.getVatRate();
1793
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1794
 
1795
				invoiceTable.addCell(new Phrase(order.getId()+"", helveticaBold8));
1796
				invoiceTable.addCell(getProductNameCell(lineItem, true, order.getFreebieItemId()));
1797
				invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
1798
 
1799
 
1800
				//populateBottomInvoiceTable(order, invoiceTable, rate);
1801
 
1802
				double itemPrice = lineItem.getUnit_price();
1803
				double showPrice = (100 * itemPrice)/(100 + rate);
1804
				invoiceTable.addCell(getPriceCell(showPrice));
1805
 
1806
				double totalPrice = lineItem.getTotal_price();
1807
				showPrice = (100 * totalPrice)/(100 + rate);
1808
				invoiceTable.addCell(getPriceCell(showPrice));
1809
 
1810
				PdfPCell salesTaxCell = getPriceCell(salesTax);
1811
 
1812
 
1813
				invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
1814
				invoiceTable.addCell(salesTaxCell);
1815
				invoiceTable.addCell(getTotalAmountCell(orderAmount));
1816
 
1817
				if(order.getInsurer() > 0) {
1818
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1819
				}
1820
				totalAmount = totalAmount+ orderAmount;
17470 manish.sha 1821
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1822
				i++;
1823
			}
9432 amar.kumar 1824
		}
7014 rajveer 1825
 
13276 manish.sha 1826
		if(insuranceAmount>0){
1827
			invoiceTable.addCell(getInsuranceCell(7));
1828
			invoiceTable.addCell(getPriceCell(insuranceAmount));
7014 rajveer 1829
		}
17470 manish.sha 1830
		if(totalShippingCost>0){
17501 manish.sha 1831
			invoiceTable.addCell(getShippingCostCell(6));      
1832
			invoiceTable.addCell(getRupeesCell(false));
1833
			invoiceTable.addCell(getPriceCell(totalShippingCost));
17470 manish.sha 1834
		}
13276 manish.sha 1835
		invoiceTable.addCell(getTotalCell(6));
17501 manish.sha 1836
		invoiceTable.addCell(getRupeesCell(true));
17470 manish.sha 1837
		invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
7014 rajveer 1838
 
13276 manish.sha 1839
		invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
17470 manish.sha 1840
		invoiceTable.addCell(getAmountInWordsCell(totalAmount+totalShippingCost));
7014 rajveer 1841
 
13276 manish.sha 1842
		invoiceTable.addCell(getEOECell(8));
7014 rajveer 1843
 
1844
		return invoiceTable;
1845
	}
1846
 
13276 manish.sha 1847
	private PdfPCell getInvoiceTableHeader(int colspan, String masterOrderId) {
1848
		PdfPTable invoiceHeaderTable = new PdfPTable(2);
1849
		PdfPCell masterOrderIdCell = new PdfPCell(new Phrase("Master Order Id- "+masterOrderId, helvetica10));
13320 manish.sha 1850
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1851
			masterOrderIdCell.setBorder(Rectangle.NO_BORDER);
1852
			masterOrderIdCell.setPaddingTop(1);
1853
		}
13281 manish.sha 1854
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
7014 rajveer 1855
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
8551 manish.sha 1856
		invoiceTableHeader.setPaddingTop(1);
13276 manish.sha 1857
		invoiceHeaderTable.addCell(invoiceTableHeader);
13320 manish.sha 1858
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1859
			invoiceHeaderTable.addCell(masterOrderIdCell);
1860
		}else{
1861
			masterOrderIdCell = new PdfPCell(new Phrase(" ", helvetica10));
1862
			invoiceHeaderTable.addCell(masterOrderIdCell);
1863
		}
13283 manish.sha 1864
		PdfPCell headerCell = new PdfPCell(invoiceHeaderTable);
1865
		headerCell.setColspan(colspan);
1866
		return headerCell;
7014 rajveer 1867
	}
1868
 
13276 manish.sha 1869
	/*private void populateBottomInvoiceTable(List<Order> orderList, PdfPTable invoiceTable) {
7014 rajveer 1870
		for (LineItem lineitem : order.getLineitems()) {
1871
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
1872
 
7190 amar.kumar 1873
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 1874
 
1875
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
1876
 
1877
			double itemPrice = lineitem.getUnit_price();
1878
			double showPrice = (100 * itemPrice)/(100 + rate);
1879
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
1880
 
1881
			double totalPrice = lineitem.getTotal_price();
1882
			showPrice = (100 * totalPrice)/(100 + rate);
1883
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
1884
		}
13276 manish.sha 1885
	}*/
7014 rajveer 1886
 
7190 amar.kumar 1887
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 1888
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 1889
		if(freebieItemId!=null && freebieItemId!=0){
1890
			try {
1891
				CatalogService.Client catalogClient = ctsc.getClient();
1892
				Item item = catalogClient.getItem(freebieItemId);
1893
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
1894
			} catch(Exception tex) {
1895
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
1896
			}
1897
		}
7014 rajveer 1898
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
1899
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1900
		return productNameCell;
1901
	}
1902
 
1903
	private PdfPCell getPriceCell(double price) {
1904
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
1905
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1906
		return totalPriceCell;
1907
	}
1908
 
1909
	private PdfPCell getVATLabelCell(boolean isVAT) {
1910
		PdfPCell vatCell = null;
1911
		if(isVAT){
1912
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
1913
		} else {
1914
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
1915
		}
1916
		vatCell.setColspan(3);
1917
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1918
		return vatCell;
1919
	}
1920
 
9432 amar.kumar 1921
	private PdfPCell getCFORMLabelCell() {
1922
		PdfPCell cFormCell = null;
1923
		cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
1924
		cFormCell.setColspan(3);
1925
		cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1926
		return cFormCell;
1927
	}
1928
 
7318 rajveer 1929
	private PdfPCell getAdvanceAmountCell(int colspan) {
1930
		PdfPCell insuranceCell = null;
1931
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
1932
		insuranceCell.setColspan(colspan);
1933
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1934
		return insuranceCell;
1935
	}
1936
 
7014 rajveer 1937
	private PdfPCell getInsuranceCell(int colspan) {
1938
		PdfPCell insuranceCell = null;
13276 manish.sha 1939
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance. T&C Apply", helvetica8));
7014 rajveer 1940
		insuranceCell.setColspan(colspan);
1941
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1942
		return insuranceCell;
1943
	}
1944
 
1945
	private PdfPCell getEmptyCell(int colspan) {
1946
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
1947
		emptyCell.setColspan(colspan);
1948
		return emptyCell;
1949
	}
17470 manish.sha 1950
 
1951
	private PdfPCell getShippingCostCell(int colspan) {
1952
		PdfPCell shippingCostCell = new PdfPCell(new Phrase("Shipping Charges", helvetica8));
1953
		shippingCostCell.setColspan(colspan);
17501 manish.sha 1954
		shippingCostCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
17470 manish.sha 1955
		return shippingCostCell;
1956
	}
1957
 
1958
	private PdfPCell getCodChargesCell(int colspan) {
1959
		PdfPCell codChargesCell = new PdfPCell(new Phrase("COD Charges", helvetica8));
1960
		codChargesCell.setColspan(colspan);
1961
		return codChargesCell;
1962
	}
19003 manish.sha 1963
 
1964
	private PdfPCell getGvAmountCell(int colspan) {
1965
		PdfPCell codChargesCell = new PdfPCell(new Phrase("GV Amount", helvetica8));
1966
		codChargesCell.setColspan(colspan);
1967
		return codChargesCell;
1968
	}
7014 rajveer 1969
 
1970
	private PdfPCell getTotalCell(int colspan) {
13276 manish.sha 1971
		PdfPCell totalCell = new PdfPCell(new Phrase("Grand Total", helveticaBold8));
7014 rajveer 1972
		totalCell.setColspan(colspan);
1973
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1974
		return totalCell;
1975
	}
1976
 
17501 manish.sha 1977
	private PdfPCell getRupeesCell(boolean useBold) {
1978
		PdfPCell rupeesCell;
1979
		if(useBold)
1980
			rupeesCell= new PdfPCell(new Phrase("Rs.", helveticaBold8));
1981
		else
1982
			rupeesCell= new PdfPCell(new Phrase("Rs.", helvetica8));
7014 rajveer 1983
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1984
		return rupeesCell;
1985
	}
1986
 
1987
	private PdfPCell getTotalAmountCell(double orderAmount) {
1988
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
1989
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1990
		return totalAmountCell;
1991
	}
1992
 
1993
	/**
1994
	 * This method uses ICU4J libraries to convert the given amount into words
1995
	 * of Indian locale.
1996
	 * 
1997
	 * @param orderAmount
1998
	 *            The amount to convert.
1999
	 * @return the string representation of the given amount.
2000
	 */
2001
	private PdfPCell getAmountInWordsCell(double orderAmount) {
2002
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
2003
		StringBuilder amountInWords = new StringBuilder("Rs. ");
2004
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
2005
		amountInWords.append(" and ");
2006
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
2007
		amountInWords.append(" paise");
2008
 
2009
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
2010
		amountInWordsCell.setColspan(4);
2011
		return amountInWordsCell;
2012
	}
2013
 
2014
	/**
2015
	 * Returns the item name to be displayed in the invoice table.
2016
	 * 
2017
	 * @param lineitem
2018
	 *            The line item whose name has to be displayed
2019
	 * @param appendIMEI
2020
	 *            Whether to attach the IMEI No. to the item name
2021
	 * @return The name to be displayed for the given line item.
2022
	 */
2023
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
2024
		StringBuffer itemName = new StringBuffer();
2025
		if(lineitem.getBrand()!= null)
2026
			itemName.append(lineitem.getBrand() + " ");
2027
		if(lineitem.getModel_name() != null)
2028
			itemName.append(lineitem.getModel_name() + " ");
2029
		if(lineitem.getModel_number() != null )
2030
			itemName.append(lineitem.getModel_number() + " ");
2031
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
2032
			itemName.append("("+lineitem.getColor()+")");
13320 manish.sha 2033
		if(appendIMEI && lineitem.isSetSerial_number() && !lineitem.getSerial_number().isEmpty()){
7014 rajveer 2034
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
2035
		}
2036
 
2037
		return itemName.toString();
2038
	}
2039
 
2040
	/**
2041
	 * 
2042
	 * @param colspan
2043
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
2044
	 *         no. of columns
2045
	 */
2046
	private PdfPCell getEOECell(int colspan) {
2047
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
2048
		eoeCell.setColspan(colspan);
2049
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
2050
		return eoeCell;
2051
	}
2052
 
2053
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
2054
		PdfPTable extraInfoTable = new PdfPTable(1);
2055
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2056
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2057
 
2058
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
2059
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
2060
		ttfFontFactory.register(fontPath, "barcode");
2061
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
2062
 
2063
		PdfPCell extraInfoCell;
2064
		if(billingType == BillingType.EXTERNAL){
2065
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
2066
		}else{
2067
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
2068
		}
2069
 
2070
		extraInfoCell.setPaddingTop(20.0f);
2071
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
2072
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
2073
 
2074
		extraInfoTable.addCell(extraInfoCell);
2075
 
2076
 
2077
		return extraInfoTable;
2078
	}
2079
 
2080
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
2081
		PdfPTable extraInfoTable = new PdfPTable(1);
2082
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2083
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2084
 
2085
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
2086
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
2087
		ttfFontFactory.register(fontPath, "barcode");
2088
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
2089
 
2090
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
2091
 
2092
		extraInfoCell.setPaddingTop(20.0f);
2093
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
2094
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
2095
 
2096
		extraInfoTable.addCell(extraInfoCell);
2097
 
2098
		return extraInfoTable;
2099
	}
8067 manish.sha 2100
 
2101
	private void generateBarcode(String barcodeString, String fileName){
2102
		Code128Bean bean = new Code128Bean();
7014 rajveer 2103
 
8067 manish.sha 2104
		final int dpi = 60;
2105
 
2106
		//Configure the barcode generator
2107
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
2108
		                                                 //width exactly one pixel
2109
		bean.setFontSize(bean.getFontSize()+1.0f);
2110
		bean.doQuietZone(false);
2111
 
2112
		try {
2113
			File outputFile = new File("/tmp/"+fileName+".png");
2114
			OutputStream out = new FileOutputStream(outputFile);
2115
 
2116
		    //Set up the canvas provider for monochrome PNG output 
2117
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
2118
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
2119
 
2120
		    //Generate the barcode
2121
		    bean.generateBarcode(canvas, barcodeString);
2122
 
2123
		    //Signal end of generation
2124
		    canvas.finish();
2125
		    out.close();
2126
 
2127
		} 
2128
		catch(Exception e){
2129
			logger.error("Exception during generating Barcode : ", e);
2130
		}
2131
	}
2132
 
7014 rajveer 2133
	public static void main(String[] args) throws IOException {
2134
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 2135
		long orderId = 356324;
2136
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 2137
		String userHome = System.getProperty("user.home");
2138
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
2139
		FileOutputStream fos = new FileOutputStream(f);
2140
		baos.writeTo(fos);
2141
		System.out.println("Invoice generated.");
2142
	}
2787 chandransh 2143
}