Subversion Repositories SmartDukaan

Rev

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