Subversion Repositories SmartDukaan

Rev

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