Subversion Repositories SmartDukaan

Rev

Rev 19260 | Rev 19277 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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