Subversion Repositories SmartDukaan

Rev

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

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