Subversion Repositories SmartDukaan

Rev

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