Subversion Repositories SmartDukaan

Rev

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

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