Subversion Repositories SmartDukaan

Rev

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