Subversion Repositories SmartDukaan

Rev

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