Subversion Repositories SmartDukaan

Rev

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