Subversion Repositories SmartDukaan

Rev

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