Subversion Repositories SmartDukaan

Rev

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