Subversion Repositories SmartDukaan

Rev

Rev 20741 | Rev 20746 | 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){
20742 kshitij.so 918
			PdfPCell spnCell = new PdfPCell(new Phrase("SPN: 08611123323A123", helveticaBold12));
20741 kshitij.so 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);
20742 kshitij.so 1234
 
1235
 
18769 manish.sha 1236
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true, false);
18657 manish.sha 1237
		if (order.getOrderType().equals(OrderType.B2B)) {
1238
			if(billingAddress!=null){
1239
				if(order.getCustomer_state().trim().equalsIgnoreCase(billingAddress.getState())){
1240
					phrase = new Phrase("TAX INVOICE", helveticaBold12);
1241
				}else{
1242
					phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1243
				}
1244
			}else{
1245
				phrase = new Phrase("TAX INVOICE", helveticaBold12);
1246
			}
1247
		} else {
1248
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1249
		}
18693 manish.sha 1250
 
1251
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
1252
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1253
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
1254
 
7014 rajveer 1255
		PdfPTable orderDetails = getOrderDetails(order, provider);
1256
 
1257
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
1258
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1259
		addrAndOrderDetailsTable.addCell(customerAddress);
1260
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
1261
		addrAndOrderDetailsTable.addCell(orderDetails);
1262
 
9319 amar.kumar 1263
		boolean isVAT = isVatApplicable(order);
13276 manish.sha 1264
		PdfPTable invoiceTable = getBottomInvoiceTable(orderList, isVAT, invoiceFormat);
7014 rajveer 1265
 
10607 manish.sha 1266
		PdfPTable regAddAndDisCellTable = new PdfPTable(2);
1267
 
20686 amit.gupta 1268
		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 1269
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1270
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
19985 amit.gupta 1271
		PdfPCell regAddressCell = new PdfPCell(new Phrase(sellerInfo.getOrganisationName() + "\n" +
1272
										"Regd. Add. " +  sellerInfo.getRegisteredAddress() + "\n" + 
1273
										(StringUtils.isEmpty(sellerInfo.getCinNumber())? "" :"CIN: " + sellerInfo.getCinNumber() + "\n") +  
19973 amit.gupta 1274
										"Tel. No. +91-9818116289 E-mail. help@saholic.com Website. www.saholic.com", helvetica6));
10607 manish.sha 1275
		regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1276
		regAddressCell.setBorder(Rectangle.NO_BORDER);
1277
		/*SPICE ONLINE RETAIL PRIVATE LIMITED
1278
		Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
1279
		CIN: U74140DL2008PTC183856
1280
		Tel. No. 0120-2479977
1281
		E-mail. help@saholic.com
1282
		Website. www.saholic.com*/
9014 amar.kumar 1283
		PdfPCell powerTextCell = new PdfPCell(new Phrase("Powered By  Flipkart", helvetica8));
1284
		powerTextCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1285
		powerTextCell.setBorder(Rectangle.NO_BORDER);
1286
		powerTextCell.setPaddingBottom(30.0f);
8104 manish.sha 1287
 
1288
		logoTitleAndOurAddressTable.addCell(logoTable);
8110 manish.sha 1289
		logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
1290
		logoTitleAndOurAddressTable.addCell(sorlAddress);
8104 manish.sha 1291
 
10607 manish.sha 1292
		regAddAndDisCellTable.addCell(disclaimerCell);
1293
		regAddAndDisCellTable.addCell(regAddressCell);
1294
 
8104 manish.sha 1295
		taxTable.addCell(logoTitleAndOurAddressTable);
7014 rajveer 1296
		taxTable.addCell(addrAndOrderDetailsTable);
1297
		taxTable.addCell(invoiceTable);
10608 manish.sha 1298
		taxTable.addCell(regAddAndDisCellTable);
9014 amar.kumar 1299
		if(order.getSource() == OrderSource.FLIPKART.getValue()) {
1300
			taxTable.addCell(powerTextCell);
1301
 
1302
		}
10320 amar.kumar 1303
		if(order.getProductCondition().equals(ProductCondition.BAD)){
10328 amar.kumar 1304
			PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
10320 amar.kumar 1305
					"may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
1306
					"are not returnable, exchangeable or refundable under any circumstances. No " +
1307
					"warranty is assured on these items." ,
10329 amar.kumar 1308
					new Font(FontFamily.TIMES_ROMAN, 8f)));
10328 amar.kumar 1309
			badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1310
			badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
1311
			taxTable.addCell(badSaleDisclaimerCell);
10320 amar.kumar 1312
		}
7014 rajveer 1313
		return taxTable;
1314
	}
9009 amar.kumar 1315
 
9319 amar.kumar 1316
	private boolean isVatApplicable(Order order) {
1317
		if(order.getWarehouse_id() == 7) {
1318
			if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
1319
				return true;
1320
			} else {
1321
				return false;
1322
			}
12809 manish.sha 1323
		} else if(order.getWarehouse_id() == 3298){
1324
			for(int i=0; i< telanganaPincodes.length; i++) {
1325
				if(order.getCustomer_pincode().trim().equalsIgnoreCase(telanganaPincodes[i])) {
1326
					return true;
1327
				}
1328
			}
1329
			return false;
16196 manish.sha 1330
		} else if(order.getWarehouse_id() == 1765 || order.getWarehouse_id() == 1768){
1331
			for(int i=0; i< karnatakaPincodePrefix.length; i++) {
1332
				if(order.getCustomer_pincode().startsWith(karnatakaPincodePrefix[i])) {
1333
					return true;
1334
				}
1335
			}
1336
			return false;
12809 manish.sha 1337
		}
1338
		else {
9319 amar.kumar 1339
			for(int i=0; i< maharashtraPincodePrefix.length; i++) {
1340
				if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
1341
					return true;
1342
				}
1343
			}
1344
			return false;
1345
		}
1346
	}
1347
 
9037 amar.kumar 1348
	private PdfPTable getFlipkartBarCodes(Order order) {
1349
		PdfPTable flipkartTable = new PdfPTable(3);
1350
 
1351
		PdfPCell spacerCell = new PdfPCell();
9040 amar.kumar 1352
		spacerCell.setBorder(Rectangle.NO_BORDER);
9037 amar.kumar 1353
		spacerCell.setColspan(3);
9099 amar.kumar 1354
		spacerCell.setPaddingTop(330.0f);
9037 amar.kumar 1355
 
1356
		String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1357
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1358
		ttfFontFactory.register(flipkartCodeFontPath, "barcode");
1359
		Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
1360
 
9040 amar.kumar 1361
		String serialNumber = "0000000000";
9511 manish.sha 1362
		if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
9040 amar.kumar 1363
			serialNumber = order.getLineitems().get(0).getSerial_number();
9511 manish.sha 1364
		} else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
9040 amar.kumar 1365
			serialNumber = order.getLineitems().get(0).getItem_number();
1366
		}
1367
 
1368
		PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
9037 amar.kumar 1369
		serialNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1370
		serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1371
		serialNumberBarCodeCell.setPaddingTop(11.0f);
1372
 
1373
 
1374
		PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
1375
		invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1376
		invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1377
		invoiceNumberBarCodeCell.setPaddingTop(11.0f);
1378
 
1379
		double rate = order.getLineitems().get(0).getVatRate();
1380
		double salesTax = (rate * order.getTotal_amount())/(100 + rate);
9040 amar.kumar 1381
		PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
9037 amar.kumar 1382
		vatAmtBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1383
		vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1384
		vatAmtBarCodeCell.setPaddingTop(11.0f);
1385
 
1386
		flipkartTable.addCell(spacerCell);
1387
		flipkartTable.addCell(serialNumberBarCodeCell);
1388
		flipkartTable.addCell(invoiceNumberBarCodeCell);
1389
		flipkartTable.addCell(vatAmtBarCodeCell);
1390
 
1391
		return flipkartTable;
1392
 
9009 amar.kumar 1393
	}
18657 manish.sha 1394
 
1395
	private void setBillingAddress(long userId, in.shop2020.model.v1.user.UserContextService.Client userClient) throws TException{
1396
		billingAddress = userClient.getBillingAddressForUser(userId);
1397
	}
9009 amar.kumar 1398
 
18530 manish.sha 1399
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce, boolean billingAdd){
7014 rajveer 1400
		PdfPTable customerTable = new PdfPTable(1);
20741 kshitij.so 1401
		//customerTable.addCell(new Phrase("Deliver To :",font));
7014 rajveer 1402
		if(forInvoce || order.getPickupStoreId() == 0){
18530 manish.sha 1403
			in.shop2020.model.v1.user.UserContextService.Client userClient = usc.getClient();
1404
			try {
1405
				if(billingAdd && userClient.isPrivateDealUser(order.getCustomer_id())){
18657 manish.sha 1406
					setBillingAddress(order.getCustomer_id(), userClient);
1407
					if(billingAddress!=null){
18769 manish.sha 1408
						return customerTable;
1409
						/*
18657 manish.sha 1410
						customerTable.addCell(new Phrase(billingAddress.getName(), font));
1411
						customerTable.addCell(new Phrase(billingAddress.getLine1(), font));
1412
						customerTable.addCell(new Phrase(billingAddress.getLine2(), font));
1413
						customerTable.addCell(new Phrase(billingAddress.getCity() + "," + billingAddress.getState(), font));
1414
						customerTable.addCell(new Phrase(billingAddress.getPin(), font));
1415
						customerTable.addCell(new Phrase("Phone : " + (billingAddress.getPhone()== null ? "" : billingAddress.getPhone()), font));
18769 manish.sha 1416
						*/
18657 manish.sha 1417
					}else{
20742 kshitij.so 1418
						if (!forInvoce)
1419
							customerTable.addCell(new Phrase("Deliver To:", font));
18657 manish.sha 1420
						customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1421
						if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1422
							HsOrder hsOrder = null;
1423
							try {
1424
								hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1425
							}catch (TException e) {
1426
								logger.error("Error while getting homeshop18 order", e);
1427
							}
1428
							String hsShippingName = hsOrder.getShippingName();
1429
							if(hsShippingName!=null && !hsShippingName.isEmpty()){
1430
								customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1431
							}
1432
						}
1433
						customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1434
						customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1435
						customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1436
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1437
						if(order.getLogistics_provider_id()!=7L  && order.getLogistics_provider_id()!=46L){
18657 manish.sha 1438
							if(destCode != null)
1439
								customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1440
							else
1441
								customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1442
							}
1443
						else{
1444
							in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1445
							String fedexLocationcode = "";
1446
							try {
1447
								fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1448
							} catch (TException e1) {
1449
								logger.error("Error while getting the provider information.", e1);
1450
							}
1451
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1452
						}
1453
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1454
						if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1455
							customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1456
						}
1457
					}
18530 manish.sha 1458
				}else{
18769 manish.sha 1459
					customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
20742 kshitij.so 1460
					if(!forInvoce)
1461
						customerTable.addCell(new Phrase("Deliver To:", font));
18530 manish.sha 1462
					customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1463
					if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1464
						HsOrder hsOrder = null;
1465
						try {
1466
							hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1467
						}catch (TException e) {
1468
							logger.error("Error while getting homeshop18 order", e);
1469
						}
1470
						String hsShippingName = hsOrder.getShippingName();
1471
						if(hsShippingName!=null && !hsShippingName.isEmpty()){
1472
							customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1473
						}
1474
					}
1475
					customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1476
					customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1477
					customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1478
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
19513 manish.sha 1479
					if(order.getLogistics_provider_id()!=7L  && order.getLogistics_provider_id()!=46L){
18530 manish.sha 1480
						if(destCode != null)
1481
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1482
						else
1483
							customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1484
						}
1485
					else{
1486
						in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1487
						String fedexLocationcode = "";
1488
						try {
1489
							fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1490
						} catch (TException e1) {
1491
							logger.error("Error while getting the provider information.", e1);
1492
						}
1493
						customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1494
					}
1495
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1496
					if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1497
						customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1498
					}
13734 manish.sha 1499
				}
18530 manish.sha 1500
			} catch (TException e2) {
1501
				e2.printStackTrace();
13734 manish.sha 1502
			}
18530 manish.sha 1503
 
7014 rajveer 1504
		}else{
18769 manish.sha 1505
			customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7014 rajveer 1506
			try {
5556 rajveer 1507
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 1508
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
20742 kshitij.so 1509
				if(!forInvoce)
1510
					customerTable.addCell(new Phrase("Deliver To:", font));
7014 rajveer 1511
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
1512
				customerTable.addCell(new Phrase(store.getLine1(), font));
1513
				customerTable.addCell(new Phrase(store.getLine2(), font));
1514
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
1515
				if(destCode != null)
1516
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
1517
				else
1518
					customerTable.addCell(new Phrase(store.getPin(), font));
1519
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 1520
			} catch (TException e) {
1521
				// TODO Auto-generated catch block
1522
				e.printStackTrace();
1523
			}
5527 anupam.sin 1524
 
7014 rajveer 1525
		}
1526
 
1527
		if(order.getOrderType().equals(OrderType.B2B)) {
1528
			String tin = null;
1529
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1530
			List<Attribute> attributes;
1531
			try {
1532
				attributes = tclient.getAllAttributesForOrderId(order.getId());
1533
 
1534
				for(Attribute attribute : attributes) {
1535
					if(attribute.getName().equals("tinNumber")) {
1536
						tin = attribute.getValue();
1537
					}
1538
				}
1539
				if (tin != null) {
1540
					customerTable.addCell(new Phrase("TIN :" + tin, font));
1541
				}
1542
 
1543
			} catch (Exception e) {
1544
				logger.error("Error while getting order attributes", e);
1545
			}
1546
		}
1547
		/*
2787 chandransh 1548
        if(showPaymentMode){
1549
            customerTable.addCell(new Phrase(" ", font));
1550
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 1551
        }*/
7014 rajveer 1552
		return customerTable;
1553
	}
2787 chandransh 1554
 
7014 rajveer 1555
	private PdfPTable getOrderDetails(Order order, Provider provider){
1556
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
1557
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 1558
 
7014 rajveer 1559
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
1560
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 1561
 
7014 rajveer 1562
		orderTable.addCell(new Phrase("Date:", helvetica8));
1563
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1564
 
13691 manish.sha 1565
		String hsCourierName = "";
12590 amit.gupta 1566
		if(order.getSource() == OrderSource.AMAZON.getValue() || order.getSource() == OrderSource.JUNGLEE.getValue()){
7528 rajveer 1567
			AmazonOrder aorder = null;
1568
			try {
1569
				aorder = tsc.getClient().getAmazonOrder(order.getId());
1570
			} catch (TException e) {
1571
				logger.error("Error while getting amazon order", e);
1572
			}
12590 amit.gupta 1573
			if(order.getSource() == OrderSource.JUNGLEE.getValue()){
1574
				orderTable.addCell(new Phrase("Junglee Order ID:", helvetica8));
1575
			}else {
1576
				orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
1577
			}
7528 rajveer 1578
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
13691 manish.sha 1579
		} else if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1580
			HsOrder hsOrder = null;
1581
			try {
13706 manish.sha 1582
				hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
13691 manish.sha 1583
			}catch (TException e) {
1584
				logger.error("Error while getting homeshop18 order", e);
1585
			}
1586
			hsCourierName = hsOrder.getCourierName();
1587
			orderTable.addCell(new Phrase("HomeShop18 Order No:", helvetica8));
1588
			orderTable.addCell(new Phrase(hsOrder.getHsOrderNo(), helvetica8));
1589
			orderTable.addCell(new Phrase("HomeShop18 Sub Order No:", helvetica8));
1590
			orderTable.addCell(new Phrase(hsOrder.getHsSubOrderNo(), helvetica8));
1591
 
8182 amar.kumar 1592
		} else if(order.getSource() == OrderSource.EBAY.getValue()){
1593
			EbayOrder ebayOrder = null;
1594
			try {
1595
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1596
			} catch (TException e) {
1597
				logger.error("Error while getting ebay order", e);
1598
			}
1599
			orderTable.addCell(new Phrase("PaisaPayId:", helvetica8));
1600
			orderTable.addCell(new Phrase(ebayOrder.getPaisaPayId(), helvetica8));
1601
			orderTable.addCell(new Phrase("Sales Rec Number:", helvetica8));
1602
			orderTable.addCell(new Phrase(new Long(ebayOrder.getSalesRecordNumber()).toString(), helvetica8));
8488 amar.kumar 1603
		} else if(order.getSource() == OrderSource.SNAPDEAL.getValue()){
1604
			SnapdealOrder snapdealOrder = null;
1605
			try {
11424 kshitij.so 1606
				snapdealOrder = tsc.getClient().getSnapdealOrder(order.getId(), null, null).get(0);
8488 amar.kumar 1607
			} catch (TException e) {
1608
				logger.error("Error while getting snapdeal order", e);
1609
			}
1610
			orderTable.addCell(new Phrase("Snapdeal OrderId:", helvetica8));
1611
			orderTable.addCell(new Phrase(new Long(snapdealOrder.getSubOrderId()).toString(), helvetica8));
8828 amar.kumar 1612
 
1613
			String refernceCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1614
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1615
			ttfFontFactory.register(refernceCodeFontPath, "barcode");
8876 amar.kumar 1616
			Font referenceCodeBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
8828 amar.kumar 1617
 
8874 amar.kumar 1618
			PdfPCell snapdealReferenceBarCodeCell = new PdfPCell(new Paragraph("*" +  snapdealOrder.getReferenceCode() + "*", referenceCodeBarCodeFont));
8828 amar.kumar 1619
			snapdealReferenceBarCodeCell.setBorder(Rectangle.NO_BORDER);
8876 amar.kumar 1620
			snapdealReferenceBarCodeCell.setPaddingTop(9.0f);
1621
			snapdealReferenceBarCodeCell.setColspan(2);
9042 amar.kumar 1622
			snapdealReferenceBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
8876 amar.kumar 1623
			//orderTable.addCell(new Phrase("Snapdeal ReferenceCode:", helvetica8));
8828 amar.kumar 1624
			orderTable.addCell(snapdealReferenceBarCodeCell);
1625
			//orderTable.addCell(new Phrase(snapdealOrder.getReferenceCode(), helvetica8));
7528 rajveer 1626
		}
8989 vikram.rag 1627
		else if(order.getSource() == OrderSource.FLIPKART.getValue()){
1628
			FlipkartOrder flipkartOrder = null;
1629
			try {
1630
				flipkartOrder = tsc.getClient().getFlipkartOrder(order.getId());
1631
			} catch (TException e) {
8996 amar.kumar 1632
				logger.error("Error while getting flipkart order", e);
8989 vikram.rag 1633
			}
1634
			orderTable.addCell(new Phrase("Flipkart OrderId:", helvetica8));
1635
			orderTable.addCell(new Phrase(flipkartOrder.getFlipkartOrderId(), helvetica8));
9037 amar.kumar 1636
 
1637
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1638
			String flipkartBarCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1639
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1640
			ttfFontFactory.register(flipkartBarCodeFontPath, "barcode");
9043 amar.kumar 1641
			Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 18);
9037 amar.kumar 1642
 
9043 amar.kumar 1643
			orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
9037 amar.kumar 1644
			PdfPCell flipkartOrderItemIdBarCodeCell = new PdfPCell(new Paragraph("*" +  new Long(flipkartOrder.getFlipkartSubOrderId()).toString() + "*", flipkartBarCodeFont));
1645
			flipkartOrderItemIdBarCodeCell.setBorder(Rectangle.NO_BORDER);
1646
			flipkartOrderItemIdBarCodeCell.setPaddingTop(9.0f);
9043 amar.kumar 1647
			//flipkartOrderItemIdBarCodeCell.setColspan(2);
1648
			//flipkartOrderItemIdBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1649
			orderTable.addCell(flipkartOrderItemIdBarCodeCell);
1650
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1651
			//orderTable.addCell(new Phrase(new Long(flipkartOrder.getFlipkartSubOrderId()).toString(), helvetica8));
8989 vikram.rag 1652
		}
1653
 
1654
 
7014 rajveer 1655
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
1656
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
13276 manish.sha 1657
 
1658
		if(OrderType.B2B==order.getOrderType()){
1659
			try {
1660
				String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
1661
				if(poRefVal!=null && poRefVal.length()>0){
1662
					orderTable.addCell(new Phrase("PO Ref:", helvetica8));
1663
					orderTable.addCell(new Phrase(poRefVal, helvetica8));
1664
				}
1665
 
1666
			} catch (TException e) {
1667
				logger.error("Error while getting amazon order", e);
1668
			}
1669
		}
2787 chandransh 1670
 
7014 rajveer 1671
		orderTable.addCell(new Phrase("Courier:", helvetica8));
13691 manish.sha 1672
		if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1673
			orderTable.addCell(new Phrase(hsCourierName, helvetica8));
1674
		} else{
1675
			orderTable.addCell(new Phrase(provider.getName(), helvetica8));
1676
		}
2787 chandransh 1677
 
9038 amar.kumar 1678
		if(order.getAirwaybill_no()!=null && !order.getAirwaybill_no().isEmpty()) {
1679
			orderTable.addCell(new Phrase("AWB No:", helvetica8));
1680
			orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
1681
		}
2787 chandransh 1682
 
7014 rajveer 1683
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
1684
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1685
 
7014 rajveer 1686
		return orderTable;
1687
	}
2787 chandransh 1688
 
13276 manish.sha 1689
	private PdfPTable getBottomInvoiceTable(List<Order> orderList,boolean isVAT, String invoiceFormat){
1690
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
7014 rajveer 1691
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 1692
 
13284 manish.sha 1693
		invoiceTable.addCell(getInvoiceTableHeader(8,orderList.get(0).getLogisticsTransactionId()));
4262 rajveer 1694
 
13276 manish.sha 1695
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1696
			invoiceTable.addCell(new Phrase("Sr No", helveticaBold8));
1697
		}else{
1698
			invoiceTable.addCell(new Phrase("Order No", helveticaBold8));
1699
		}
7014 rajveer 1700
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
1701
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
1702
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
1703
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
13276 manish.sha 1704
		invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
1705
		invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
19260 manish.sha 1706
		invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));
19276 manish.sha 1707
		invoiceTable.setHeaderRows(2);
13276 manish.sha 1708
		double totalAmount = 0.0;
1709
		double insuranceAmount = 0.0;
17470 manish.sha 1710
		double totalShippingCost = 0.0;
13276 manish.sha 1711
		int i=1;
1712
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1713
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1714
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1715
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1716
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1717
			Map<Long, Double> itemTaxPercentageMap = new HashMap<Long, Double>();
1718
			Map<Long, Double> itemTaxValueMap = new HashMap<Long, Double>();
1719
 
1720
			for(Order order : orderList){
1721
				LineItem lineitem = order.getLineitems().get(0);
1722
 
1723
				double orderAmount = order.getTotal_amount();
1724
				double rate = lineitem.getVatRate();
1725
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1726
				totalAmount = totalAmount + orderAmount;
17470 manish.sha 1727
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1728
				double itemPrice = lineitem.getUnit_price();
1729
				double showPrice = (100 * itemPrice)/(100 + rate);
1730
				double totalPrice = lineitem.getTotal_price();
1731
				double showTotalPrice = (100 * totalPrice)/(100 + rate);
1732
 
1733
				if(order.getInsurer() > 0) {
1734
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1735
				}
1736
 
1737
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1738
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1739
				}
1740
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1741
					double quantity = itemQuantityMap.get(lineitem.getItem_id()) + lineitem.getQuantity();
1742
					itemQuantityMap.put(lineitem.getItem_id(), quantity);
1743
				} else {
1744
					itemQuantityMap.put(lineitem.getItem_id(),lineitem.getQuantity());
1745
				}
1746
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1747
					itemRateMap.put(lineitem.getItem_id(), showPrice);
1748
				}
1749
				if(!itemTaxPercentageMap.containsKey(lineitem.getItem_id())){
1750
					itemTaxPercentageMap.put(lineitem.getItem_id(), rate);
1751
				}
1752
				if(itemTaxValueMap.containsKey(lineitem.getItem_id())){
1753
					double taxValue = itemTaxValueMap.get(lineitem.getItem_id()) + salesTax;
1754
					itemTaxValueMap.put(lineitem.getItem_id(), taxValue);
1755
				}else{
1756
					itemTaxValueMap.put(lineitem.getItem_id(), salesTax);
1757
				}
1758
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
1759
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + showTotalPrice;
1760
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1761
				}else{
1762
					itemTotalAmtMap.put(lineitem.getItem_id(), showTotalPrice);
1763
				}
1764
			}
1765
 
1766
			for(Long itemId : itemNamesMap.keySet()){
1767
				invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
1768
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId),helvetica8));
1769
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"",helvetica8));
13285 manish.sha 1770
				invoiceTable.addCell(getPriceCell(itemRateMap.get(itemId)));
1771
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)));
1772
				invoiceTable.addCell(new Phrase(itemTaxPercentageMap.get(itemId)+"%",helvetica8));
1773
				invoiceTable.addCell(getPriceCell(itemTaxValueMap.get(itemId)));
1774
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)+itemTaxValueMap.get(itemId)));
13313 manish.sha 1775
				i++;
13276 manish.sha 1776
			}
1777
		}
1778
		else{
9432 amar.kumar 1779
 
13276 manish.sha 1780
			for(Order order :orderList){
1781
				LineItem lineItem = order.getLineitems().get(0);
1782
				double orderAmount = order.getTotal_amount();
1783
				double rate = lineItem.getVatRate();
1784
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1785
 
1786
				invoiceTable.addCell(new Phrase(order.getId()+"", helveticaBold8));
1787
				invoiceTable.addCell(getProductNameCell(lineItem, true, order.getFreebieItemId()));
1788
				invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
1789
 
1790
 
1791
				//populateBottomInvoiceTable(order, invoiceTable, rate);
1792
 
1793
				double itemPrice = lineItem.getUnit_price();
1794
				double showPrice = (100 * itemPrice)/(100 + rate);
1795
				invoiceTable.addCell(getPriceCell(showPrice));
1796
 
1797
				double totalPrice = lineItem.getTotal_price();
1798
				showPrice = (100 * totalPrice)/(100 + rate);
1799
				invoiceTable.addCell(getPriceCell(showPrice));
1800
 
1801
				PdfPCell salesTaxCell = getPriceCell(salesTax);
1802
 
1803
 
1804
				invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
1805
				invoiceTable.addCell(salesTaxCell);
1806
				invoiceTable.addCell(getTotalAmountCell(orderAmount));
1807
 
1808
				if(order.getInsurer() > 0) {
1809
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1810
				}
1811
				totalAmount = totalAmount+ orderAmount;
17470 manish.sha 1812
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1813
				i++;
1814
			}
9432 amar.kumar 1815
		}
7014 rajveer 1816
 
13276 manish.sha 1817
		if(insuranceAmount>0){
1818
			invoiceTable.addCell(getInsuranceCell(7));
1819
			invoiceTable.addCell(getPriceCell(insuranceAmount));
7014 rajveer 1820
		}
17470 manish.sha 1821
		if(totalShippingCost>0){
17501 manish.sha 1822
			invoiceTable.addCell(getShippingCostCell(6));      
1823
			invoiceTable.addCell(getRupeesCell(false));
1824
			invoiceTable.addCell(getPriceCell(totalShippingCost));
17470 manish.sha 1825
		}
13276 manish.sha 1826
		invoiceTable.addCell(getTotalCell(6));
17501 manish.sha 1827
		invoiceTable.addCell(getRupeesCell(true));
17470 manish.sha 1828
		invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
7014 rajveer 1829
 
13276 manish.sha 1830
		invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
17470 manish.sha 1831
		invoiceTable.addCell(getAmountInWordsCell(totalAmount+totalShippingCost));
7014 rajveer 1832
 
13276 manish.sha 1833
		invoiceTable.addCell(getEOECell(8));
7014 rajveer 1834
 
1835
		return invoiceTable;
1836
	}
1837
 
13276 manish.sha 1838
	private PdfPCell getInvoiceTableHeader(int colspan, String masterOrderId) {
1839
		PdfPTable invoiceHeaderTable = new PdfPTable(2);
1840
		PdfPCell masterOrderIdCell = new PdfPCell(new Phrase("Master Order Id- "+masterOrderId, helvetica10));
13320 manish.sha 1841
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1842
			masterOrderIdCell.setBorder(Rectangle.NO_BORDER);
1843
			masterOrderIdCell.setPaddingTop(1);
1844
		}
13281 manish.sha 1845
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
7014 rajveer 1846
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
8551 manish.sha 1847
		invoiceTableHeader.setPaddingTop(1);
13276 manish.sha 1848
		invoiceHeaderTable.addCell(invoiceTableHeader);
13320 manish.sha 1849
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1850
			invoiceHeaderTable.addCell(masterOrderIdCell);
1851
		}else{
1852
			masterOrderIdCell = new PdfPCell(new Phrase(" ", helvetica10));
1853
			invoiceHeaderTable.addCell(masterOrderIdCell);
1854
		}
13283 manish.sha 1855
		PdfPCell headerCell = new PdfPCell(invoiceHeaderTable);
1856
		headerCell.setColspan(colspan);
1857
		return headerCell;
7014 rajveer 1858
	}
1859
 
13276 manish.sha 1860
	/*private void populateBottomInvoiceTable(List<Order> orderList, PdfPTable invoiceTable) {
7014 rajveer 1861
		for (LineItem lineitem : order.getLineitems()) {
1862
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
1863
 
7190 amar.kumar 1864
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 1865
 
1866
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
1867
 
1868
			double itemPrice = lineitem.getUnit_price();
1869
			double showPrice = (100 * itemPrice)/(100 + rate);
1870
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
1871
 
1872
			double totalPrice = lineitem.getTotal_price();
1873
			showPrice = (100 * totalPrice)/(100 + rate);
1874
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
1875
		}
13276 manish.sha 1876
	}*/
7014 rajveer 1877
 
7190 amar.kumar 1878
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 1879
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 1880
		if(freebieItemId!=null && freebieItemId!=0){
1881
			try {
1882
				CatalogService.Client catalogClient = ctsc.getClient();
1883
				Item item = catalogClient.getItem(freebieItemId);
1884
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
1885
			} catch(Exception tex) {
1886
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
1887
			}
1888
		}
7014 rajveer 1889
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
1890
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1891
		return productNameCell;
1892
	}
1893
 
1894
	private PdfPCell getPriceCell(double price) {
1895
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
1896
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1897
		return totalPriceCell;
1898
	}
1899
 
1900
	private PdfPCell getVATLabelCell(boolean isVAT) {
1901
		PdfPCell vatCell = null;
1902
		if(isVAT){
1903
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
1904
		} else {
1905
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
1906
		}
1907
		vatCell.setColspan(3);
1908
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1909
		return vatCell;
1910
	}
1911
 
9432 amar.kumar 1912
	private PdfPCell getCFORMLabelCell() {
1913
		PdfPCell cFormCell = null;
1914
		cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
1915
		cFormCell.setColspan(3);
1916
		cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1917
		return cFormCell;
1918
	}
1919
 
7318 rajveer 1920
	private PdfPCell getAdvanceAmountCell(int colspan) {
1921
		PdfPCell insuranceCell = null;
1922
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
1923
		insuranceCell.setColspan(colspan);
1924
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1925
		return insuranceCell;
1926
	}
1927
 
7014 rajveer 1928
	private PdfPCell getInsuranceCell(int colspan) {
1929
		PdfPCell insuranceCell = null;
13276 manish.sha 1930
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance. T&C Apply", helvetica8));
7014 rajveer 1931
		insuranceCell.setColspan(colspan);
1932
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1933
		return insuranceCell;
1934
	}
1935
 
1936
	private PdfPCell getEmptyCell(int colspan) {
1937
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
1938
		emptyCell.setColspan(colspan);
1939
		return emptyCell;
1940
	}
17470 manish.sha 1941
 
1942
	private PdfPCell getShippingCostCell(int colspan) {
1943
		PdfPCell shippingCostCell = new PdfPCell(new Phrase("Shipping Charges", helvetica8));
1944
		shippingCostCell.setColspan(colspan);
17501 manish.sha 1945
		shippingCostCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
17470 manish.sha 1946
		return shippingCostCell;
1947
	}
1948
 
1949
	private PdfPCell getCodChargesCell(int colspan) {
1950
		PdfPCell codChargesCell = new PdfPCell(new Phrase("COD Charges", helvetica8));
1951
		codChargesCell.setColspan(colspan);
1952
		return codChargesCell;
1953
	}
19003 manish.sha 1954
 
1955
	private PdfPCell getGvAmountCell(int colspan) {
1956
		PdfPCell codChargesCell = new PdfPCell(new Phrase("GV Amount", helvetica8));
1957
		codChargesCell.setColspan(colspan);
1958
		return codChargesCell;
1959
	}
7014 rajveer 1960
 
1961
	private PdfPCell getTotalCell(int colspan) {
13276 manish.sha 1962
		PdfPCell totalCell = new PdfPCell(new Phrase("Grand Total", helveticaBold8));
7014 rajveer 1963
		totalCell.setColspan(colspan);
1964
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1965
		return totalCell;
1966
	}
1967
 
17501 manish.sha 1968
	private PdfPCell getRupeesCell(boolean useBold) {
1969
		PdfPCell rupeesCell;
1970
		if(useBold)
1971
			rupeesCell= new PdfPCell(new Phrase("Rs.", helveticaBold8));
1972
		else
1973
			rupeesCell= new PdfPCell(new Phrase("Rs.", helvetica8));
7014 rajveer 1974
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1975
		return rupeesCell;
1976
	}
1977
 
1978
	private PdfPCell getTotalAmountCell(double orderAmount) {
1979
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
1980
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1981
		return totalAmountCell;
1982
	}
1983
 
1984
	/**
1985
	 * This method uses ICU4J libraries to convert the given amount into words
1986
	 * of Indian locale.
1987
	 * 
1988
	 * @param orderAmount
1989
	 *            The amount to convert.
1990
	 * @return the string representation of the given amount.
1991
	 */
1992
	private PdfPCell getAmountInWordsCell(double orderAmount) {
1993
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
1994
		StringBuilder amountInWords = new StringBuilder("Rs. ");
1995
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
1996
		amountInWords.append(" and ");
1997
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
1998
		amountInWords.append(" paise");
1999
 
2000
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
2001
		amountInWordsCell.setColspan(4);
2002
		return amountInWordsCell;
2003
	}
2004
 
2005
	/**
2006
	 * Returns the item name to be displayed in the invoice table.
2007
	 * 
2008
	 * @param lineitem
2009
	 *            The line item whose name has to be displayed
2010
	 * @param appendIMEI
2011
	 *            Whether to attach the IMEI No. to the item name
2012
	 * @return The name to be displayed for the given line item.
2013
	 */
2014
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
2015
		StringBuffer itemName = new StringBuffer();
2016
		if(lineitem.getBrand()!= null)
2017
			itemName.append(lineitem.getBrand() + " ");
2018
		if(lineitem.getModel_name() != null)
2019
			itemName.append(lineitem.getModel_name() + " ");
2020
		if(lineitem.getModel_number() != null )
2021
			itemName.append(lineitem.getModel_number() + " ");
2022
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
2023
			itemName.append("("+lineitem.getColor()+")");
13320 manish.sha 2024
		if(appendIMEI && lineitem.isSetSerial_number() && !lineitem.getSerial_number().isEmpty()){
7014 rajveer 2025
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
2026
		}
2027
 
2028
		return itemName.toString();
2029
	}
2030
 
2031
	/**
2032
	 * 
2033
	 * @param colspan
2034
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
2035
	 *         no. of columns
2036
	 */
2037
	private PdfPCell getEOECell(int colspan) {
2038
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
2039
		eoeCell.setColspan(colspan);
2040
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
2041
		return eoeCell;
2042
	}
2043
 
2044
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
2045
		PdfPTable extraInfoTable = new PdfPTable(1);
2046
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2047
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2048
 
2049
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
2050
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
2051
		ttfFontFactory.register(fontPath, "barcode");
2052
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
2053
 
2054
		PdfPCell extraInfoCell;
2055
		if(billingType == BillingType.EXTERNAL){
2056
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
2057
		}else{
2058
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
2059
		}
2060
 
2061
		extraInfoCell.setPaddingTop(20.0f);
2062
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
2063
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
2064
 
2065
		extraInfoTable.addCell(extraInfoCell);
2066
 
2067
 
2068
		return extraInfoTable;
2069
	}
2070
 
2071
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
2072
		PdfPTable extraInfoTable = new PdfPTable(1);
2073
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2074
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2075
 
2076
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
2077
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
2078
		ttfFontFactory.register(fontPath, "barcode");
2079
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
2080
 
2081
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
2082
 
2083
		extraInfoCell.setPaddingTop(20.0f);
2084
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
2085
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
2086
 
2087
		extraInfoTable.addCell(extraInfoCell);
2088
 
2089
		return extraInfoTable;
2090
	}
8067 manish.sha 2091
 
2092
	private void generateBarcode(String barcodeString, String fileName){
2093
		Code128Bean bean = new Code128Bean();
7014 rajveer 2094
 
8067 manish.sha 2095
		final int dpi = 60;
2096
 
2097
		//Configure the barcode generator
2098
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
2099
		                                                 //width exactly one pixel
2100
		bean.setFontSize(bean.getFontSize()+1.0f);
2101
		bean.doQuietZone(false);
2102
 
2103
		try {
2104
			File outputFile = new File("/tmp/"+fileName+".png");
2105
			OutputStream out = new FileOutputStream(outputFile);
2106
 
2107
		    //Set up the canvas provider for monochrome PNG output 
2108
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
2109
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
2110
 
2111
		    //Generate the barcode
2112
		    bean.generateBarcode(canvas, barcodeString);
2113
 
2114
		    //Signal end of generation
2115
		    canvas.finish();
2116
		    out.close();
2117
 
2118
		} 
2119
		catch(Exception e){
2120
			logger.error("Exception during generating Barcode : ", e);
2121
		}
2122
	}
2123
 
7014 rajveer 2124
	public static void main(String[] args) throws IOException {
2125
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 2126
		long orderId = 356324;
2127
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 2128
		String userHome = System.getProperty("user.home");
2129
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
2130
		FileOutputStream fos = new FileOutputStream(f);
2131
		baos.writeTo(fos);
2132
		System.out.println("Invoice generated.");
2133
	}
2787 chandransh 2134
}