Subversion Repositories SmartDukaan

Rev

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