Subversion Repositories SmartDukaan

Rev

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