Subversion Repositories SmartDukaan

Rev

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