Subversion Repositories SmartDukaan

Rev

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

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