Subversion Repositories SmartDukaan

Rev

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