Subversion Repositories SmartDukaan

Rev

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

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