Subversion Repositories SmartDukaan

Rev

Rev 18779 | Rev 18875 | 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);
18847 manish.sha 651
		table.setSplitLate(false);
7014 rajveer 652
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 653
 
654
		PdfPTable titleBarTable = new PdfPTable(new float[]{0.4f, 0.4f, 0.2f});
8107 manish.sha 655
		titleBarTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8106 manish.sha 656
 
8103 manish.sha 657
		PdfPTable logoTable = new PdfPTable(2);
658
		addLogoTable(logoTable,order); 
7318 rajveer 659
 
7014 rajveer 660
		PdfPCell titleCell = getTitleCell();
18530 manish.sha 661
		PdfPTable customerTable = getCustomerAddressTable(order, destCode, false, helvetica12, false, false);
13276 manish.sha 662
		PdfPTable providerInfoTable = getProviderTable(order, provider, barCodeFont, totalWeight);
2787 chandransh 663
 
7014 rajveer 664
		PdfPTable dispatchTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
665
		dispatchTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
666
		dispatchTable.addCell(customerTable);
667
		dispatchTable.addCell(new Phrase(" "));
668
		dispatchTable.addCell(providerInfoTable);
2787 chandransh 669
 
13276 manish.sha 670
		PdfPTable invoiceTable = getTopInvoiceTable(orderList, shippingLocation.getTinNumber(), invoiceFormat);
8110 manish.sha 671
		PdfPTable addressTable = new PdfPTable(1);
672
		addressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
673
		addressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
674
 
7014 rajveer 675
		PdfPCell addressCell = getAddressCell(shippingLocation.getLocation() +
17203 manish.sha 676
				" - " + shippingLocation.getPincode() + "\nContact No.- +91-9811247808" + "\n\n");
2787 chandransh 677
 
7014 rajveer 678
		PdfPTable chargesTable = new PdfPTable(1);
679
		chargesTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
680
		chargesTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
681
		if(order.isLogisticsCod()){
13276 manish.sha 682
			chargesTable.addCell(new Phrase("AMOUNT TO BE COLLECTED : Rs " + (totalAmount), helveticaBold12));
7014 rajveer 683
			chargesTable.addCell(new Phrase("RTO ADDRESS:DEL/HPW/111116"));
7994 manish.sha 684
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
685
			if(order.getLogistics_provider_id()==7L){
686
				in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
687
				String fedexCodReturnBarcode = "";
8080 manish.sha 688
				String fedexCodReturnTrackingId = "";
7994 manish.sha 689
				try {
690
					fedexCodReturnBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_BarCode");
8080 manish.sha 691
					fedexCodReturnTrackingId = tclient.getOrderAttributeValue(order.getId(), "FedEx_COD_Return_Tracking_No");
7994 manish.sha 692
				} catch (TException e1) {
693
					logger.error("Error while getting the provider information.", e1);
694
				}
8080 manish.sha 695
				PdfPCell formIdCell= new PdfPCell(new Paragraph("COD Return "+fedexCodReturnTrackingId+" Form id-0325", helvetica6));
8104 manish.sha 696
				formIdCell.setPaddingTop(2.0f);
7994 manish.sha 697
				formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
698
				formIdCell.setBorder(Rectangle.NO_BORDER);
699
				chargesTable.addCell(new Phrase("PRIORITY OVERNIGHT ", helvetica8));
700
				chargesTable.addCell(formIdCell);
8035 manish.sha 701
 
8067 manish.sha 702
				generateBarcode(fedexCodReturnBarcode, "fedex_codr_"+order.getId());
8037 manish.sha 703
 
8067 manish.sha 704
				Image barcodeImage=null;
705
				try {
706
					barcodeImage = Image.getInstance("/tmp/"+"fedex_codr_"+order.getId()+".png");
707
				} catch (Exception e) {
708
					logger.error("Exception during getting Barcode Image for Fedex : ", e);
709
				}
710
 
8173 manish.sha 711
				PdfPTable codReturnTable = new PdfPTable(new float[]{0.6f,0.4f});
712
				codReturnTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
713
				codReturnTable.addCell(barcodeImage);
714
				codReturnTable.addCell(new Phrase(" "));
715
				chargesTable.addCell(codReturnTable);
716
 
7994 manish.sha 717
			}
718
			//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 719
		} else {
720
			chargesTable.addCell(new Phrase("Do not pay any extra charges to the Courier."));  
721
		}
8080 manish.sha 722
 
723
		if(order.getLogistics_provider_id()==7L){
724
			chargesTable.addCell(new Phrase("Term and Condition:- Subject to the Conditions of Carriage which " +
725
					"limits the liability of FedEx for loss, delay or damage to the consignment." +
726
					" Visit http://www.fedex.com/in/domestic/services/terms to view the conitions of Carriage" ,
8082 manish.sha 727
					new Font(FontFamily.TIMES_ROMAN, 8f)));
8080 manish.sha 728
		}
10310 amar.kumar 729
 
8110 manish.sha 730
		addressTable.addCell(new Phrase("If undelivered, return to:", helvetica10));
731
		addressTable.addCell(addressCell);
732
 
7014 rajveer 733
		PdfPTable addressAndNoteTable = new PdfPTable(new float[]{0.3f, 0.7f});
734
		addressAndNoteTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8110 manish.sha 735
		addressAndNoteTable.addCell(addressTable);
7014 rajveer 736
		addressAndNoteTable.addCell(chargesTable);
2787 chandransh 737
 
8106 manish.sha 738
		titleBarTable.addCell(logoTable);
739
		titleBarTable.addCell(titleCell);
740
		titleBarTable.addCell(" ");
741
 
742
		table.addCell(titleBarTable);
7014 rajveer 743
		table.addCell(dispatchTable);
744
		table.addCell(invoiceTable);
745
		table.addCell(addressAndNoteTable);
746
		return table;
747
	}
2787 chandransh 748
 
8103 manish.sha 749
	private void addLogoTable(PdfPTable logoTable,Order order) {
7318 rajveer 750
		logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
751
		logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
752
		logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
8096 manish.sha 753
 
7318 rajveer 754
		PdfPCell logoCell;
755
		String logoPath;
8102 manish.sha 756
 
7556 rajveer 757
		if(order.getSource() == OrderSource.STORE.getValue()){
758
			logoCell = new PdfPCell(new Phrase(""));
759
 
760
		}else{
8102 manish.sha 761
			logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
8094 manish.sha 762
 
7318 rajveer 763
			try {
764
				logoCell = new PdfPCell(Image.getInstance(logoPath), false);
765
			} catch (Exception e) {
766
				//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
767
				logger.warn("Couldn't load the Saholic logo: ", e);
768
				logoCell = new PdfPCell(new Phrase("Saholic Logo"));
769
			}
770
 
771
		}
8090 manish.sha 772
		logoCell.setBorder(Rectangle.NO_BORDER);
773
		logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
8102 manish.sha 774
		logoTable.addCell(logoCell);
775
		logoTable.addCell(" ");
8103 manish.sha 776
 
7318 rajveer 777
	}
778
 
7014 rajveer 779
	private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
780
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
781
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
782
		ttfFontFactory.register(fontPath, "barcode");
783
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
784
		return barCodeFont;
785
	}
2787 chandransh 786
 
7014 rajveer 787
	private PdfPCell getTitleCell() {
788
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
789
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
790
		titleCell.setBorder(Rectangle.NO_BORDER);
791
		return titleCell;
792
	}
2787 chandransh 793
 
13276 manish.sha 794
	private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont, double totalWeight) {
7014 rajveer 795
		PdfPTable providerInfoTable = new PdfPTable(1);
796
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7318 rajveer 797
		if(order.isLogisticsCod()){
8551 manish.sha 798
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica22));
7318 rajveer 799
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
800
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
801
			providerInfoTable.addCell(deliveryTypeCell);
802
		}
803
 
8035 manish.sha 804
 
7014 rajveer 805
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
806
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
807
		providerNameCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 808
		PdfPCell formIdCell= null;
809
		if(order.getLogistics_provider_id()==7L){
810
			if(order.isCod()){
8034 manish.sha 811
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
7994 manish.sha 812
			}
813
			else{
8034 manish.sha 814
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
7994 manish.sha 815
			}
8551 manish.sha 816
			formIdCell.setPaddingTop(1.0f);
8015 rajveer 817
			formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
818
			formIdCell.setBorder(Rectangle.NO_BORDER);
7994 manish.sha 819
		}
8015 rajveer 820
 
7994 manish.sha 821
 
822
		PdfPCell awbNumberCell= null;
8034 manish.sha 823
		String fedexPackageBarcode = "";
7994 manish.sha 824
		if(order.getLogistics_provider_id()!=7L){
825
			awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
8017 manish.sha 826
			awbNumberCell.setPaddingTop(20.0f);
7994 manish.sha 827
		}
828
		else{
8013 rajveer 829
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
830
			try {
831
				fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
832
			} catch (TException e1) {
833
				logger.error("Error while getting the provider information.", e1);
834
			}
8174 manish.sha 835
			awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
836
		}
837
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
838
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
839
 
840
		providerInfoTable.addCell(providerNameCell);
841
		if(formIdCell != null){
842
			providerInfoTable.addCell(formIdCell);
843
		}
844
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
845
		if(order.getLogistics_provider_id()==7L){
8169 manish.sha 846
			generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
847
 
848
			Image barcodeImage=null;
849
			try {
850
				barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
851
			} catch (Exception e) {
852
				logger.error("Exception during getting Barcode Image for Fedex : ", e);
853
			}
8174 manish.sha 854
			providerInfoTable.addCell(barcodeImage);
7994 manish.sha 855
		}
8174 manish.sha 856
		providerInfoTable.addCell(awbNumberCell);
7014 rajveer 857
 
7792 anupam.sin 858
		Warehouse warehouse = null;
859
		try{
860
    		InventoryClient isc = new InventoryClient();
7804 amar.kumar 861
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
7803 amar.kumar 862
		} catch(Exception e) {
7792 anupam.sin 863
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
7805 amar.kumar 864
		    //TODO throw e;
7792 anupam.sin 865
		}
866
		DeliveryType dt =  DeliveryType.PREPAID;
867
        if (order.isLogisticsCod()) {
868
            dt = DeliveryType.COD;
869
        }
7994 manish.sha 870
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
871
        if(order.getLogistics_provider_id()!=7L){
872
	        for (ProviderDetails detail : provider.getDetails()) {
873
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
874
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
875
	            }
876
	        }
7792 anupam.sin 877
        }
7994 manish.sha 878
        else{
879
        	providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
880
        }
881
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 882
		Date awbDate;
883
		if(order.getBilling_timestamp() == 0){
884
			awbDate = new Date();
885
		}else{
886
			awbDate = new Date(order.getBilling_timestamp());
887
		}
8106 manish.sha 888
		if(order.getLogistics_provider_id()!=7L){
889
			providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
890
		}
13322 manish.sha 891
		providerInfoTable.addCell(new Phrase("Weight         : " + totalWeight + " Kg", helvetica8));
8182 amar.kumar 892
		if(order.getSource() == OrderSource.EBAY.getValue()){
893
			EbayOrder ebayOrder = null;
894
			try {
895
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
896
			} catch (TException e) {
897
				logger.error("Error while getting ebay order", e);
898
			}
899
			providerInfoTable.addCell(new Phrase("PaisaPayId            : " + ebayOrder.getPaisaPayId(), helvetica8));
900
			providerInfoTable.addCell(new Phrase("Sales Rec Number: " + ebayOrder.getSalesRecordNumber(), helvetica8));
901
		}
7994 manish.sha 902
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
903
		if(order.getLogistics_provider_id()==7L){
904
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
905
		}
906
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
7014 rajveer 907
		return providerInfoTable;
908
	}
909
 
13276 manish.sha 910
	private PdfPTable getTopInvoiceTable(List<Order> orderList, String tinNo, String invoiceFormat){
7014 rajveer 911
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
912
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
913
 
13276 manish.sha 914
		invoiceTable.addCell(getInvoiceTableHeader(6,orderList.get(0).getLogisticsTransactionId()));
915
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
916
			invoiceTable.addCell(new Phrase("Sr No", helvetica8));
917
		}else{
918
			invoiceTable.addCell(new Phrase("Order No", helvetica8));
919
		}
7014 rajveer 920
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
921
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
922
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
923
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
924
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
13276 manish.sha 925
		double totalAmount = 0.0;
17470 manish.sha 926
		double totalShippingCost = 0.0;
13276 manish.sha 927
		double insuranceAmount = 0.0;
928
		double advanceAmount = 0.0;
929
 
930
 
931
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
932
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
933
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
934
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
935
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
936
			String paymentMode = "";
937
			for(Order order : orderList){
938
				LineItem lineitem = order.getLineitems().get(0);
13496 manish.sha 939
				totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount();
17470 manish.sha 940
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 941
				if(order.getInsurer() > 0) {
942
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
943
				}
944
				if(order.getSource() == OrderSource.STORE.getValue()) {
945
					advanceAmount = advanceAmount + order.getAdvanceAmount();
946
				}
947
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
948
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
949
				}
950
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
951
					itemRateMap.put(lineitem.getItem_id(), lineitem.getUnit_price());
952
				}
953
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
954
					double currentQuantity = itemQuantityMap.get(lineitem.getItem_id()) +lineitem.getQuantity();
955
					itemQuantityMap.put(lineitem.getItem_id(), currentQuantity);
956
				}else{
957
					itemQuantityMap.put(lineitem.getItem_id(), lineitem.getQuantity());
958
				}
959
 
960
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
13492 manish.sha 961
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount());
13276 manish.sha 962
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
963
				}else{
13492 manish.sha 964
					itemTotalAmtMap.put(lineitem.getItem_id(), (order.getTotal_amount()-order.getAdvanceAmount()-order.getInsuranceAmount()));
13276 manish.sha 965
				}
966
				if(paymentMode==null || paymentMode.isEmpty()){
967
					if(order.getPickupStoreId() > 0 && order.isCod() == true)
968
						paymentMode = "In-Store";
969
					else if (order.isCod())
970
						paymentMode = "COD";
971
					else
972
						paymentMode = "Prepaid";
973
				}		
974
			}
975
 
976
			int serialNo = 0;
977
			for(Long itemId : itemNamesMap.keySet()){
978
				serialNo ++;
979
				invoiceTable.addCell(new Phrase(serialNo+ "", helvetica8));
980
				invoiceTable.addCell(new Phrase(paymentMode, helvetica8));
981
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId), helvetica8));
982
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"", helvetica8));
983
				invoiceTable.addCell(new Phrase(itemRateMap.get(itemId)+"", helvetica8));
984
				invoiceTable.addCell(new Phrase(itemTotalAmtMap.get(itemId)+"", helvetica8));
985
			}
986
 
987
			if(insuranceAmount>0){
988
				invoiceTable.addCell(getInsuranceCell(4));
989
				invoiceTable.addCell(getPriceCell(insuranceAmount));
990
				invoiceTable.addCell(getPriceCell(insuranceAmount));
991
			}
992
			if(advanceAmount>0){
993
				invoiceTable.addCell(getAdvanceAmountCell(4));
994
				invoiceTable.addCell(getPriceCell(advanceAmount));
995
				invoiceTable.addCell(getPriceCell(advanceAmount));
996
			}
997
		}else{
998
			for(Order order : orderList){
999
				populateTopInvoiceTable(order, invoiceTable);
1000
				if(order.getInsurer() > 0) {
1001
					invoiceTable.addCell(getInsuranceCell(4));
1002
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
1003
					invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
1004
				}
7014 rajveer 1005
 
13276 manish.sha 1006
				if(order.getSource() == OrderSource.STORE.getValue()) {
1007
					invoiceTable.addCell(getAdvanceAmountCell(4));
1008
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
1009
					invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
1010
				}
13494 manish.sha 1011
				totalAmount = totalAmount + order.getTotal_amount()-order.getAdvanceAmount();
17470 manish.sha 1012
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1013
			}
7014 rajveer 1014
		}
17470 manish.sha 1015
		if(totalShippingCost>0){
1016
			invoiceTable.addCell(getShippingCostCell(4));      
17501 manish.sha 1017
			invoiceTable.addCell(getRupeesCell(false));
1018
			invoiceTable.addCell(getPriceCell(totalShippingCost));
17470 manish.sha 1019
		}
7014 rajveer 1020
		invoiceTable.addCell(getTotalCell(4));      
17501 manish.sha 1021
		invoiceTable.addCell(getRupeesCell(true));
17470 manish.sha 1022
		invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
13276 manish.sha 1023
 
7014 rajveer 1024
 
1025
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
1026
		tinCell.setColspan(6);
1027
		tinCell.setPadding(2);
1028
		invoiceTable.addCell(tinCell);
1029
 
1030
		return invoiceTable;
1031
	}
1032
 
1033
	private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
1034
		List<LineItem> lineitems = order.getLineitems();
1035
		for (LineItem lineitem : lineitems) {
1036
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
1037
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
1038
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
1039
			else if (order.isCod())
1040
				invoiceTable.addCell(new Phrase("COD", helvetica8));
1041
			else
1042
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
7318 rajveer 1043
 
7190 amar.kumar 1044
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
2787 chandransh 1045
 
7014 rajveer 1046
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
2787 chandransh 1047
 
7014 rajveer 1048
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
1049
 
1050
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
1051
		}
1052
	}
1053
 
1054
	private PdfPCell getAddressCell(String address) {
1055
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
1056
		PdfPCell addressCell = new PdfPCell();
1057
		addressCell.addElement(addressParagraph);
1058
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1059
		addressCell.setBorder(Rectangle.NO_BORDER);
1060
		return addressCell;
1061
	}
1062
 
13276 manish.sha 1063
	private PdfPTable getTaxCumRetailInvoiceTable(List<Order> orderList, Provider provider, String ourAddress, String tinNo, String invoiceFormat){
1064
		Order order = orderList.get(0);
7014 rajveer 1065
		PdfPTable taxTable = new PdfPTable(1);
1066
		Phrase phrase = null;
18847 manish.sha 1067
		taxTable.setSplitLate(false);
7014 rajveer 1068
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1069
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
8104 manish.sha 1070
 
8110 manish.sha 1071
		PdfPTable logoTitleAndOurAddressTable = new PdfPTable(new float[]{0.4f, 0.3f, 0.3f});
8107 manish.sha 1072
		logoTitleAndOurAddressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
8112 manish.sha 1073
		logoTitleAndOurAddressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
8107 manish.sha 1074
 
8110 manish.sha 1075
 
8103 manish.sha 1076
		PdfPTable logoTable = new PdfPTable(2);
1077
		addLogoTable(logoTable,order); 
7318 rajveer 1078
 
7014 rajveer 1079
 
17203 manish.sha 1080
		Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- +91-9811247808" + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
7014 rajveer 1081
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
1082
		sorlAddressCell.addElement(sorlAddress);
8110 manish.sha 1083
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
7014 rajveer 1084
 
18769 manish.sha 1085
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true, false);
18657 manish.sha 1086
		if (order.getOrderType().equals(OrderType.B2B)) {
1087
			if(billingAddress!=null){
1088
				if(order.getCustomer_state().trim().equalsIgnoreCase(billingAddress.getState())){
1089
					phrase = new Phrase("TAX INVOICE", helveticaBold12);
1090
				}else{
1091
					phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1092
				}
1093
			}else{
1094
				phrase = new Phrase("TAX INVOICE", helveticaBold12);
1095
			}
1096
		} else {
1097
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
1098
		}
18693 manish.sha 1099
 
1100
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
1101
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1102
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
1103
 
7014 rajveer 1104
		PdfPTable orderDetails = getOrderDetails(order, provider);
1105
 
1106
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
1107
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1108
		addrAndOrderDetailsTable.addCell(customerAddress);
1109
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
1110
		addrAndOrderDetailsTable.addCell(orderDetails);
1111
 
9319 amar.kumar 1112
		boolean isVAT = isVatApplicable(order);
13276 manish.sha 1113
		PdfPTable invoiceTable = getBottomInvoiceTable(orderList, isVAT, invoiceFormat);
7014 rajveer 1114
 
10607 manish.sha 1115
		PdfPTable regAddAndDisCellTable = new PdfPTable(2);
1116
 
7014 rajveer 1117
		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));
1118
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1119
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
7318 rajveer 1120
 
17203 manish.sha 1121
		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 1122
		regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1123
		regAddressCell.setBorder(Rectangle.NO_BORDER);
1124
		/*SPICE ONLINE RETAIL PRIVATE LIMITED
1125
		Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
1126
		CIN: U74140DL2008PTC183856
1127
		Tel. No. 0120-2479977
1128
		E-mail. help@saholic.com
1129
		Website. www.saholic.com*/
9014 amar.kumar 1130
		PdfPCell powerTextCell = new PdfPCell(new Phrase("Powered By  Flipkart", helvetica8));
1131
		powerTextCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1132
		powerTextCell.setBorder(Rectangle.NO_BORDER);
1133
		powerTextCell.setPaddingBottom(30.0f);
8104 manish.sha 1134
 
1135
		logoTitleAndOurAddressTable.addCell(logoTable);
8110 manish.sha 1136
		logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
1137
		logoTitleAndOurAddressTable.addCell(sorlAddress);
8104 manish.sha 1138
 
10607 manish.sha 1139
		regAddAndDisCellTable.addCell(disclaimerCell);
1140
		regAddAndDisCellTable.addCell(regAddressCell);
1141
 
8104 manish.sha 1142
		taxTable.addCell(logoTitleAndOurAddressTable);
7014 rajveer 1143
		taxTable.addCell(addrAndOrderDetailsTable);
1144
		taxTable.addCell(invoiceTable);
10608 manish.sha 1145
		taxTable.addCell(regAddAndDisCellTable);
9014 amar.kumar 1146
		if(order.getSource() == OrderSource.FLIPKART.getValue()) {
1147
			taxTable.addCell(powerTextCell);
1148
 
1149
		}
10320 amar.kumar 1150
		if(order.getProductCondition().equals(ProductCondition.BAD)){
10328 amar.kumar 1151
			PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
10320 amar.kumar 1152
					"may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
1153
					"are not returnable, exchangeable or refundable under any circumstances. No " +
1154
					"warranty is assured on these items." ,
10329 amar.kumar 1155
					new Font(FontFamily.TIMES_ROMAN, 8f)));
10328 amar.kumar 1156
			badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1157
			badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
1158
			taxTable.addCell(badSaleDisclaimerCell);
10320 amar.kumar 1159
		}
7014 rajveer 1160
		return taxTable;
1161
	}
9009 amar.kumar 1162
 
9319 amar.kumar 1163
	private boolean isVatApplicable(Order order) {
1164
		if(order.getWarehouse_id() == 7) {
1165
			if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
1166
				return true;
1167
			} else {
1168
				return false;
1169
			}
12809 manish.sha 1170
		} else if(order.getWarehouse_id() == 3298){
1171
			for(int i=0; i< telanganaPincodes.length; i++) {
1172
				if(order.getCustomer_pincode().trim().equalsIgnoreCase(telanganaPincodes[i])) {
1173
					return true;
1174
				}
1175
			}
1176
			return false;
16196 manish.sha 1177
		} else if(order.getWarehouse_id() == 1765 || order.getWarehouse_id() == 1768){
1178
			for(int i=0; i< karnatakaPincodePrefix.length; i++) {
1179
				if(order.getCustomer_pincode().startsWith(karnatakaPincodePrefix[i])) {
1180
					return true;
1181
				}
1182
			}
1183
			return false;
12809 manish.sha 1184
		}
1185
		else {
9319 amar.kumar 1186
			for(int i=0; i< maharashtraPincodePrefix.length; i++) {
1187
				if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
1188
					return true;
1189
				}
1190
			}
1191
			return false;
1192
		}
1193
	}
1194
 
9037 amar.kumar 1195
	private PdfPTable getFlipkartBarCodes(Order order) {
1196
		PdfPTable flipkartTable = new PdfPTable(3);
1197
 
1198
		PdfPCell spacerCell = new PdfPCell();
9040 amar.kumar 1199
		spacerCell.setBorder(Rectangle.NO_BORDER);
9037 amar.kumar 1200
		spacerCell.setColspan(3);
9099 amar.kumar 1201
		spacerCell.setPaddingTop(330.0f);
9037 amar.kumar 1202
 
1203
		String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1204
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1205
		ttfFontFactory.register(flipkartCodeFontPath, "barcode");
1206
		Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
1207
 
9040 amar.kumar 1208
		String serialNumber = "0000000000";
9511 manish.sha 1209
		if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
9040 amar.kumar 1210
			serialNumber = order.getLineitems().get(0).getSerial_number();
9511 manish.sha 1211
		} else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
9040 amar.kumar 1212
			serialNumber = order.getLineitems().get(0).getItem_number();
1213
		}
1214
 
1215
		PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
9037 amar.kumar 1216
		serialNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1217
		serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1218
		serialNumberBarCodeCell.setPaddingTop(11.0f);
1219
 
1220
 
1221
		PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
1222
		invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1223
		invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1224
		invoiceNumberBarCodeCell.setPaddingTop(11.0f);
1225
 
1226
		double rate = order.getLineitems().get(0).getVatRate();
1227
		double salesTax = (rate * order.getTotal_amount())/(100 + rate);
9040 amar.kumar 1228
		PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
9037 amar.kumar 1229
		vatAmtBarCodeCell.setBorder(Rectangle.TOP);
9044 amar.kumar 1230
		vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1231
		vatAmtBarCodeCell.setPaddingTop(11.0f);
1232
 
1233
		flipkartTable.addCell(spacerCell);
1234
		flipkartTable.addCell(serialNumberBarCodeCell);
1235
		flipkartTable.addCell(invoiceNumberBarCodeCell);
1236
		flipkartTable.addCell(vatAmtBarCodeCell);
1237
 
1238
		return flipkartTable;
1239
 
9009 amar.kumar 1240
	}
18657 manish.sha 1241
 
1242
	private void setBillingAddress(long userId, in.shop2020.model.v1.user.UserContextService.Client userClient) throws TException{
1243
		billingAddress = userClient.getBillingAddressForUser(userId);
1244
	}
9009 amar.kumar 1245
 
18530 manish.sha 1246
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce, boolean billingAdd){
7014 rajveer 1247
		PdfPTable customerTable = new PdfPTable(1);
1248
		if(forInvoce || order.getPickupStoreId() == 0){
18530 manish.sha 1249
			in.shop2020.model.v1.user.UserContextService.Client userClient = usc.getClient();
1250
			try {
1251
				if(billingAdd && userClient.isPrivateDealUser(order.getCustomer_id())){
18657 manish.sha 1252
					setBillingAddress(order.getCustomer_id(), userClient);
1253
					if(billingAddress!=null){
18769 manish.sha 1254
						return customerTable;
1255
						/*
18657 manish.sha 1256
						customerTable.addCell(new Phrase(billingAddress.getName(), font));
1257
						customerTable.addCell(new Phrase(billingAddress.getLine1(), font));
1258
						customerTable.addCell(new Phrase(billingAddress.getLine2(), font));
1259
						customerTable.addCell(new Phrase(billingAddress.getCity() + "," + billingAddress.getState(), font));
1260
						customerTable.addCell(new Phrase(billingAddress.getPin(), font));
1261
						customerTable.addCell(new Phrase("Phone : " + (billingAddress.getPhone()== null ? "" : billingAddress.getPhone()), font));
18769 manish.sha 1262
						*/
18657 manish.sha 1263
					}else{
1264
						customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1265
						if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1266
							HsOrder hsOrder = null;
1267
							try {
1268
								hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1269
							}catch (TException e) {
1270
								logger.error("Error while getting homeshop18 order", e);
1271
							}
1272
							String hsShippingName = hsOrder.getShippingName();
1273
							if(hsShippingName!=null && !hsShippingName.isEmpty()){
1274
								customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1275
							}
1276
						}
1277
						customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1278
						customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1279
						customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1280
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1281
						if(order.getLogistics_provider_id()!=7L){
1282
							if(destCode != null)
1283
								customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1284
							else
1285
								customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1286
							}
1287
						else{
1288
							in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1289
							String fedexLocationcode = "";
1290
							try {
1291
								fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1292
							} catch (TException e1) {
1293
								logger.error("Error while getting the provider information.", e1);
1294
							}
1295
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1296
						}
1297
						//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1298
						if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1299
							customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1300
						}
1301
					}
18530 manish.sha 1302
				}else{
18769 manish.sha 1303
					customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
18530 manish.sha 1304
					customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1305
					if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1306
						HsOrder hsOrder = null;
1307
						try {
1308
							hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
1309
						}catch (TException e) {
1310
							logger.error("Error while getting homeshop18 order", e);
1311
						}
1312
						String hsShippingName = hsOrder.getShippingName();
1313
						if(hsShippingName!=null && !hsShippingName.isEmpty()){
1314
							customerTable.addCell(new Phrase("Shipped To: "+hsShippingName, font));
1315
						}
1316
					}
1317
					customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1318
					customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1319
					customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1320
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1321
					if(order.getLogistics_provider_id()!=7L){
1322
						if(destCode != null)
1323
							customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1324
						else
1325
							customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1326
						}
1327
					else{
1328
						in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1329
						String fedexLocationcode = "";
1330
						try {
1331
							fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1332
						} catch (TException e1) {
1333
							logger.error("Error while getting the provider information.", e1);
1334
						}
1335
						customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1336
					}
1337
					//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1338
					if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1339
						customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1340
					}
13734 manish.sha 1341
				}
18530 manish.sha 1342
			} catch (TException e2) {
1343
				e2.printStackTrace();
13734 manish.sha 1344
			}
18530 manish.sha 1345
 
7014 rajveer 1346
		}else{
18769 manish.sha 1347
			customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
7014 rajveer 1348
			try {
5556 rajveer 1349
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
7014 rajveer 1350
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
1351
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
1352
				customerTable.addCell(new Phrase(store.getLine1(), font));
1353
				customerTable.addCell(new Phrase(store.getLine2(), font));
1354
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
1355
				if(destCode != null)
1356
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
1357
				else
1358
					customerTable.addCell(new Phrase(store.getPin(), font));
1359
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
5556 rajveer 1360
			} catch (TException e) {
1361
				// TODO Auto-generated catch block
1362
				e.printStackTrace();
1363
			}
5527 anupam.sin 1364
 
7014 rajveer 1365
		}
1366
 
1367
		if(order.getOrderType().equals(OrderType.B2B)) {
1368
			String tin = null;
1369
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1370
			List<Attribute> attributes;
1371
			try {
1372
				attributes = tclient.getAllAttributesForOrderId(order.getId());
1373
 
1374
				for(Attribute attribute : attributes) {
1375
					if(attribute.getName().equals("tinNumber")) {
1376
						tin = attribute.getValue();
1377
					}
1378
				}
1379
				if (tin != null) {
1380
					customerTable.addCell(new Phrase("TIN :" + tin, font));
1381
				}
1382
 
1383
			} catch (Exception e) {
1384
				logger.error("Error while getting order attributes", e);
1385
			}
1386
		}
1387
		/*
2787 chandransh 1388
        if(showPaymentMode){
1389
            customerTable.addCell(new Phrase(" ", font));
1390
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
5856 anupam.sin 1391
        }*/
7014 rajveer 1392
		return customerTable;
1393
	}
2787 chandransh 1394
 
7014 rajveer 1395
	private PdfPTable getOrderDetails(Order order, Provider provider){
1396
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
1397
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
2787 chandransh 1398
 
7014 rajveer 1399
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
1400
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
2787 chandransh 1401
 
7014 rajveer 1402
		orderTable.addCell(new Phrase("Date:", helvetica8));
1403
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1404
 
13691 manish.sha 1405
		String hsCourierName = "";
12590 amit.gupta 1406
		if(order.getSource() == OrderSource.AMAZON.getValue() || order.getSource() == OrderSource.JUNGLEE.getValue()){
7528 rajveer 1407
			AmazonOrder aorder = null;
1408
			try {
1409
				aorder = tsc.getClient().getAmazonOrder(order.getId());
1410
			} catch (TException e) {
1411
				logger.error("Error while getting amazon order", e);
1412
			}
12590 amit.gupta 1413
			if(order.getSource() == OrderSource.JUNGLEE.getValue()){
1414
				orderTable.addCell(new Phrase("Junglee Order ID:", helvetica8));
1415
			}else {
1416
				orderTable.addCell(new Phrase("Amazon Order ID:", helvetica8));
1417
			}
7528 rajveer 1418
			orderTable.addCell(new Phrase(aorder.getAmazonOrderCode(), helvetica8));
13691 manish.sha 1419
		} else if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1420
			HsOrder hsOrder = null;
1421
			try {
13706 manish.sha 1422
				hsOrder = tsc.getClient().getHomeShopOrder(order.getId(), null, null).get(0);
13691 manish.sha 1423
			}catch (TException e) {
1424
				logger.error("Error while getting homeshop18 order", e);
1425
			}
1426
			hsCourierName = hsOrder.getCourierName();
1427
			orderTable.addCell(new Phrase("HomeShop18 Order No:", helvetica8));
1428
			orderTable.addCell(new Phrase(hsOrder.getHsOrderNo(), helvetica8));
1429
			orderTable.addCell(new Phrase("HomeShop18 Sub Order No:", helvetica8));
1430
			orderTable.addCell(new Phrase(hsOrder.getHsSubOrderNo(), helvetica8));
1431
 
8182 amar.kumar 1432
		} else if(order.getSource() == OrderSource.EBAY.getValue()){
1433
			EbayOrder ebayOrder = null;
1434
			try {
1435
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
1436
			} catch (TException e) {
1437
				logger.error("Error while getting ebay order", e);
1438
			}
1439
			orderTable.addCell(new Phrase("PaisaPayId:", helvetica8));
1440
			orderTable.addCell(new Phrase(ebayOrder.getPaisaPayId(), helvetica8));
1441
			orderTable.addCell(new Phrase("Sales Rec Number:", helvetica8));
1442
			orderTable.addCell(new Phrase(new Long(ebayOrder.getSalesRecordNumber()).toString(), helvetica8));
8488 amar.kumar 1443
		} else if(order.getSource() == OrderSource.SNAPDEAL.getValue()){
1444
			SnapdealOrder snapdealOrder = null;
1445
			try {
11424 kshitij.so 1446
				snapdealOrder = tsc.getClient().getSnapdealOrder(order.getId(), null, null).get(0);
8488 amar.kumar 1447
			} catch (TException e) {
1448
				logger.error("Error while getting snapdeal order", e);
1449
			}
1450
			orderTable.addCell(new Phrase("Snapdeal OrderId:", helvetica8));
1451
			orderTable.addCell(new Phrase(new Long(snapdealOrder.getSubOrderId()).toString(), helvetica8));
8828 amar.kumar 1452
 
1453
			String refernceCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1454
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1455
			ttfFontFactory.register(refernceCodeFontPath, "barcode");
8876 amar.kumar 1456
			Font referenceCodeBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
8828 amar.kumar 1457
 
8874 amar.kumar 1458
			PdfPCell snapdealReferenceBarCodeCell = new PdfPCell(new Paragraph("*" +  snapdealOrder.getReferenceCode() + "*", referenceCodeBarCodeFont));
8828 amar.kumar 1459
			snapdealReferenceBarCodeCell.setBorder(Rectangle.NO_BORDER);
8876 amar.kumar 1460
			snapdealReferenceBarCodeCell.setPaddingTop(9.0f);
1461
			snapdealReferenceBarCodeCell.setColspan(2);
9042 amar.kumar 1462
			snapdealReferenceBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
8876 amar.kumar 1463
			//orderTable.addCell(new Phrase("Snapdeal ReferenceCode:", helvetica8));
8828 amar.kumar 1464
			orderTable.addCell(snapdealReferenceBarCodeCell);
1465
			//orderTable.addCell(new Phrase(snapdealOrder.getReferenceCode(), helvetica8));
7528 rajveer 1466
		}
8989 vikram.rag 1467
		else if(order.getSource() == OrderSource.FLIPKART.getValue()){
1468
			FlipkartOrder flipkartOrder = null;
1469
			try {
1470
				flipkartOrder = tsc.getClient().getFlipkartOrder(order.getId());
1471
			} catch (TException e) {
8996 amar.kumar 1472
				logger.error("Error while getting flipkart order", e);
8989 vikram.rag 1473
			}
1474
			orderTable.addCell(new Phrase("Flipkart OrderId:", helvetica8));
1475
			orderTable.addCell(new Phrase(flipkartOrder.getFlipkartOrderId(), helvetica8));
9037 amar.kumar 1476
 
1477
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1478
			String flipkartBarCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1479
			FontFactoryImp ttfFontFactory = new FontFactoryImp();
1480
			ttfFontFactory.register(flipkartBarCodeFontPath, "barcode");
9043 amar.kumar 1481
			Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 18);
9037 amar.kumar 1482
 
9043 amar.kumar 1483
			orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
9037 amar.kumar 1484
			PdfPCell flipkartOrderItemIdBarCodeCell = new PdfPCell(new Paragraph("*" +  new Long(flipkartOrder.getFlipkartSubOrderId()).toString() + "*", flipkartBarCodeFont));
1485
			flipkartOrderItemIdBarCodeCell.setBorder(Rectangle.NO_BORDER);
1486
			flipkartOrderItemIdBarCodeCell.setPaddingTop(9.0f);
9043 amar.kumar 1487
			//flipkartOrderItemIdBarCodeCell.setColspan(2);
1488
			//flipkartOrderItemIdBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
9037 amar.kumar 1489
			orderTable.addCell(flipkartOrderItemIdBarCodeCell);
1490
			//orderTable.addCell(new Phrase("Flipkart OrderItemId:", helvetica8));
1491
			//orderTable.addCell(new Phrase(new Long(flipkartOrder.getFlipkartSubOrderId()).toString(), helvetica8));
8989 vikram.rag 1492
		}
1493
 
1494
 
7014 rajveer 1495
		orderTable.addCell(new Phrase("Order Date:", helvetica8));
1496
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getCreated_timestamp())), helvetica8));
13276 manish.sha 1497
 
1498
		if(OrderType.B2B==order.getOrderType()){
1499
			try {
1500
				String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
1501
				if(poRefVal!=null && poRefVal.length()>0){
1502
					orderTable.addCell(new Phrase("PO Ref:", helvetica8));
1503
					orderTable.addCell(new Phrase(poRefVal, helvetica8));
1504
				}
1505
 
1506
			} catch (TException e) {
1507
				logger.error("Error while getting amazon order", e);
1508
			}
1509
		}
2787 chandransh 1510
 
7014 rajveer 1511
		orderTable.addCell(new Phrase("Courier:", helvetica8));
13691 manish.sha 1512
		if(order.getSource() == OrderSource.HOMESHOP18.getValue()){
1513
			orderTable.addCell(new Phrase(hsCourierName, helvetica8));
1514
		} else{
1515
			orderTable.addCell(new Phrase(provider.getName(), helvetica8));
1516
		}
2787 chandransh 1517
 
9038 amar.kumar 1518
		if(order.getAirwaybill_no()!=null && !order.getAirwaybill_no().isEmpty()) {
1519
			orderTable.addCell(new Phrase("AWB No:", helvetica8));
1520
			orderTable.addCell(new Phrase(order.getAirwaybill_no(), helvetica8));
1521
		}
2787 chandransh 1522
 
7014 rajveer 1523
		orderTable.addCell(new Phrase("AWB Date:", helvetica8));
1524
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
2787 chandransh 1525
 
7014 rajveer 1526
		return orderTable;
1527
	}
2787 chandransh 1528
 
13276 manish.sha 1529
	private PdfPTable getBottomInvoiceTable(List<Order> orderList,boolean isVAT, String invoiceFormat){
1530
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
7014 rajveer 1531
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
2787 chandransh 1532
 
13284 manish.sha 1533
		invoiceTable.addCell(getInvoiceTableHeader(8,orderList.get(0).getLogisticsTransactionId()));
4262 rajveer 1534
 
13276 manish.sha 1535
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1536
			invoiceTable.addCell(new Phrase("Sr No", helveticaBold8));
1537
		}else{
1538
			invoiceTable.addCell(new Phrase("Order No", helveticaBold8));
1539
		}
7014 rajveer 1540
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
1541
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
1542
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
1543
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
13276 manish.sha 1544
		invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
1545
		invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
1546
		invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));;
1547
		double totalAmount = 0.0;
1548
		double insuranceAmount = 0.0;
17470 manish.sha 1549
		double totalShippingCost = 0.0;
13276 manish.sha 1550
		int i=1;
1551
		if("Bulk".equalsIgnoreCase(invoiceFormat)){
1552
			Map<Long, String> itemNamesMap= new HashMap<Long, String>();
1553
			Map<Long, Double> itemQuantityMap = new HashMap<Long, Double>();
1554
			Map<Long, Double> itemRateMap = new HashMap<Long, Double>();
1555
			Map<Long, Double> itemTotalAmtMap = new HashMap<Long, Double>();
1556
			Map<Long, Double> itemTaxPercentageMap = new HashMap<Long, Double>();
1557
			Map<Long, Double> itemTaxValueMap = new HashMap<Long, Double>();
1558
 
1559
			for(Order order : orderList){
1560
				LineItem lineitem = order.getLineitems().get(0);
1561
 
1562
				double orderAmount = order.getTotal_amount();
1563
				double rate = lineitem.getVatRate();
1564
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1565
				totalAmount = totalAmount + orderAmount;
17470 manish.sha 1566
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1567
				double itemPrice = lineitem.getUnit_price();
1568
				double showPrice = (100 * itemPrice)/(100 + rate);
1569
				double totalPrice = lineitem.getTotal_price();
1570
				double showTotalPrice = (100 * totalPrice)/(100 + rate);
1571
 
1572
				if(order.getInsurer() > 0) {
1573
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1574
				}
1575
 
1576
				if(!itemNamesMap.containsKey(lineitem.getItem_id())){
1577
					itemNamesMap.put(lineitem.getItem_id(), getItemDisplayName(lineitem, false));
1578
				}
1579
				if(itemQuantityMap.containsKey(lineitem.getItem_id())){
1580
					double quantity = itemQuantityMap.get(lineitem.getItem_id()) + lineitem.getQuantity();
1581
					itemQuantityMap.put(lineitem.getItem_id(), quantity);
1582
				} else {
1583
					itemQuantityMap.put(lineitem.getItem_id(),lineitem.getQuantity());
1584
				}
1585
				if(!itemRateMap.containsKey(lineitem.getItem_id())){
1586
					itemRateMap.put(lineitem.getItem_id(), showPrice);
1587
				}
1588
				if(!itemTaxPercentageMap.containsKey(lineitem.getItem_id())){
1589
					itemTaxPercentageMap.put(lineitem.getItem_id(), rate);
1590
				}
1591
				if(itemTaxValueMap.containsKey(lineitem.getItem_id())){
1592
					double taxValue = itemTaxValueMap.get(lineitem.getItem_id()) + salesTax;
1593
					itemTaxValueMap.put(lineitem.getItem_id(), taxValue);
1594
				}else{
1595
					itemTaxValueMap.put(lineitem.getItem_id(), salesTax);
1596
				}
1597
				if(itemTotalAmtMap.containsKey(lineitem.getItem_id())){
1598
					double totalItemAmount = itemTotalAmtMap.get(lineitem.getItem_id()) + showTotalPrice;
1599
					itemTotalAmtMap.put(lineitem.getItem_id(), totalItemAmount);
1600
				}else{
1601
					itemTotalAmtMap.put(lineitem.getItem_id(), showTotalPrice);
1602
				}
1603
			}
1604
 
1605
			for(Long itemId : itemNamesMap.keySet()){
1606
				invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
1607
				invoiceTable.addCell(new Phrase(itemNamesMap.get(itemId),helvetica8));
1608
				invoiceTable.addCell(new Phrase(itemQuantityMap.get(itemId)+"",helvetica8));
13285 manish.sha 1609
				invoiceTable.addCell(getPriceCell(itemRateMap.get(itemId)));
1610
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)));
1611
				invoiceTable.addCell(new Phrase(itemTaxPercentageMap.get(itemId)+"%",helvetica8));
1612
				invoiceTable.addCell(getPriceCell(itemTaxValueMap.get(itemId)));
1613
				invoiceTable.addCell(getPriceCell(itemTotalAmtMap.get(itemId)+itemTaxValueMap.get(itemId)));
13313 manish.sha 1614
				i++;
13276 manish.sha 1615
			}
1616
		}
1617
		else{
9432 amar.kumar 1618
 
13276 manish.sha 1619
			for(Order order :orderList){
1620
				LineItem lineItem = order.getLineitems().get(0);
1621
				double orderAmount = order.getTotal_amount();
1622
				double rate = lineItem.getVatRate();
1623
				double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1624
 
1625
				invoiceTable.addCell(new Phrase(order.getId()+"", helveticaBold8));
1626
				invoiceTable.addCell(getProductNameCell(lineItem, true, order.getFreebieItemId()));
1627
				invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
1628
 
1629
 
1630
				//populateBottomInvoiceTable(order, invoiceTable, rate);
1631
 
1632
				double itemPrice = lineItem.getUnit_price();
1633
				double showPrice = (100 * itemPrice)/(100 + rate);
1634
				invoiceTable.addCell(getPriceCell(showPrice));
1635
 
1636
				double totalPrice = lineItem.getTotal_price();
1637
				showPrice = (100 * totalPrice)/(100 + rate);
1638
				invoiceTable.addCell(getPriceCell(showPrice));
1639
 
1640
				PdfPCell salesTaxCell = getPriceCell(salesTax);
1641
 
1642
 
1643
				invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
1644
				invoiceTable.addCell(salesTaxCell);
1645
				invoiceTable.addCell(getTotalAmountCell(orderAmount));
1646
 
1647
				if(order.getInsurer() > 0) {
1648
					insuranceAmount =insuranceAmount + order.getInsuranceAmount();
1649
				}
1650
				totalAmount = totalAmount+ orderAmount;
17470 manish.sha 1651
				totalShippingCost = totalShippingCost + order.getShippingCost();
13276 manish.sha 1652
				i++;
1653
			}
9432 amar.kumar 1654
		}
7014 rajveer 1655
 
13276 manish.sha 1656
		if(insuranceAmount>0){
1657
			invoiceTable.addCell(getInsuranceCell(7));
1658
			invoiceTable.addCell(getPriceCell(insuranceAmount));
7014 rajveer 1659
		}
17470 manish.sha 1660
		if(totalShippingCost>0){
17501 manish.sha 1661
			invoiceTable.addCell(getShippingCostCell(6));      
1662
			invoiceTable.addCell(getRupeesCell(false));
1663
			invoiceTable.addCell(getPriceCell(totalShippingCost));
17470 manish.sha 1664
		}
13276 manish.sha 1665
		invoiceTable.addCell(getTotalCell(6));
17501 manish.sha 1666
		invoiceTable.addCell(getRupeesCell(true));
17470 manish.sha 1667
		invoiceTable.addCell(getTotalAmountCell(totalAmount+totalShippingCost));
7014 rajveer 1668
 
13276 manish.sha 1669
		invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
17470 manish.sha 1670
		invoiceTable.addCell(getAmountInWordsCell(totalAmount+totalShippingCost));
7014 rajveer 1671
 
13276 manish.sha 1672
		invoiceTable.addCell(getEOECell(8));
7014 rajveer 1673
 
1674
		return invoiceTable;
1675
	}
1676
 
13276 manish.sha 1677
	private PdfPCell getInvoiceTableHeader(int colspan, String masterOrderId) {
1678
		PdfPTable invoiceHeaderTable = new PdfPTable(2);
1679
		PdfPCell masterOrderIdCell = new PdfPCell(new Phrase("Master Order Id- "+masterOrderId, helvetica10));
13320 manish.sha 1680
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1681
			masterOrderIdCell.setBorder(Rectangle.NO_BORDER);
1682
			masterOrderIdCell.setPaddingTop(1);
1683
		}
13281 manish.sha 1684
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Details:", helveticaBold12));
7014 rajveer 1685
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
8551 manish.sha 1686
		invoiceTableHeader.setPaddingTop(1);
13276 manish.sha 1687
		invoiceHeaderTable.addCell(invoiceTableHeader);
13320 manish.sha 1688
		if(masterOrderId!=null && !masterOrderId.isEmpty()){
1689
			invoiceHeaderTable.addCell(masterOrderIdCell);
1690
		}else{
1691
			masterOrderIdCell = new PdfPCell(new Phrase(" ", helvetica10));
1692
			invoiceHeaderTable.addCell(masterOrderIdCell);
1693
		}
13283 manish.sha 1694
		PdfPCell headerCell = new PdfPCell(invoiceHeaderTable);
1695
		headerCell.setColspan(colspan);
1696
		return headerCell;
7014 rajveer 1697
	}
1698
 
13276 manish.sha 1699
	/*private void populateBottomInvoiceTable(List<Order> orderList, PdfPTable invoiceTable) {
7014 rajveer 1700
		for (LineItem lineitem : order.getLineitems()) {
1701
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
1702
 
7190 amar.kumar 1703
			invoiceTable.addCell(getProductNameCell(lineitem, true, order.getFreebieItemId()));
7014 rajveer 1704
 
1705
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
1706
 
1707
			double itemPrice = lineitem.getUnit_price();
1708
			double showPrice = (100 * itemPrice)/(100 + rate);
1709
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
1710
 
1711
			double totalPrice = lineitem.getTotal_price();
1712
			showPrice = (100 * totalPrice)/(100 + rate);
1713
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
1714
		}
13276 manish.sha 1715
	}*/
7014 rajveer 1716
 
7190 amar.kumar 1717
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
7014 rajveer 1718
		String itemName = getItemDisplayName(lineitem, appendIMEI);
7190 amar.kumar 1719
		if(freebieItemId!=null && freebieItemId!=0){
1720
			try {
1721
				CatalogService.Client catalogClient = ctsc.getClient();
1722
				Item item = catalogClient.getItem(freebieItemId);
1723
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
1724
			} catch(Exception tex) {
1725
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
1726
			}
1727
		}
7014 rajveer 1728
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
1729
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1730
		return productNameCell;
1731
	}
1732
 
1733
	private PdfPCell getPriceCell(double price) {
1734
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
1735
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1736
		return totalPriceCell;
1737
	}
1738
 
1739
	private PdfPCell getVATLabelCell(boolean isVAT) {
1740
		PdfPCell vatCell = null;
1741
		if(isVAT){
1742
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
1743
		} else {
1744
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
1745
		}
1746
		vatCell.setColspan(3);
1747
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1748
		return vatCell;
1749
	}
1750
 
9432 amar.kumar 1751
	private PdfPCell getCFORMLabelCell() {
1752
		PdfPCell cFormCell = null;
1753
		cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
1754
		cFormCell.setColspan(3);
1755
		cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1756
		return cFormCell;
1757
	}
1758
 
7318 rajveer 1759
	private PdfPCell getAdvanceAmountCell(int colspan) {
1760
		PdfPCell insuranceCell = null;
1761
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
1762
		insuranceCell.setColspan(colspan);
1763
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1764
		return insuranceCell;
1765
	}
1766
 
7014 rajveer 1767
	private PdfPCell getInsuranceCell(int colspan) {
1768
		PdfPCell insuranceCell = null;
13276 manish.sha 1769
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance. T&C Apply", helvetica8));
7014 rajveer 1770
		insuranceCell.setColspan(colspan);
1771
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1772
		return insuranceCell;
1773
	}
1774
 
1775
	private PdfPCell getEmptyCell(int colspan) {
1776
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
1777
		emptyCell.setColspan(colspan);
1778
		return emptyCell;
1779
	}
17470 manish.sha 1780
 
1781
	private PdfPCell getShippingCostCell(int colspan) {
1782
		PdfPCell shippingCostCell = new PdfPCell(new Phrase("Shipping Charges", helvetica8));
1783
		shippingCostCell.setColspan(colspan);
17501 manish.sha 1784
		shippingCostCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
17470 manish.sha 1785
		return shippingCostCell;
1786
	}
1787
 
1788
	private PdfPCell getCodChargesCell(int colspan) {
1789
		PdfPCell codChargesCell = new PdfPCell(new Phrase("COD Charges", helvetica8));
1790
		codChargesCell.setColspan(colspan);
1791
		return codChargesCell;
1792
	}
7014 rajveer 1793
 
1794
	private PdfPCell getTotalCell(int colspan) {
13276 manish.sha 1795
		PdfPCell totalCell = new PdfPCell(new Phrase("Grand Total", helveticaBold8));
7014 rajveer 1796
		totalCell.setColspan(colspan);
1797
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1798
		return totalCell;
1799
	}
1800
 
17501 manish.sha 1801
	private PdfPCell getRupeesCell(boolean useBold) {
1802
		PdfPCell rupeesCell;
1803
		if(useBold)
1804
			rupeesCell= new PdfPCell(new Phrase("Rs.", helveticaBold8));
1805
		else
1806
			rupeesCell= new PdfPCell(new Phrase("Rs.", helvetica8));
7014 rajveer 1807
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1808
		return rupeesCell;
1809
	}
1810
 
1811
	private PdfPCell getTotalAmountCell(double orderAmount) {
1812
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
1813
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1814
		return totalAmountCell;
1815
	}
1816
 
1817
	/**
1818
	 * This method uses ICU4J libraries to convert the given amount into words
1819
	 * of Indian locale.
1820
	 * 
1821
	 * @param orderAmount
1822
	 *            The amount to convert.
1823
	 * @return the string representation of the given amount.
1824
	 */
1825
	private PdfPCell getAmountInWordsCell(double orderAmount) {
1826
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
1827
		StringBuilder amountInWords = new StringBuilder("Rs. ");
1828
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
1829
		amountInWords.append(" and ");
1830
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
1831
		amountInWords.append(" paise");
1832
 
1833
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
1834
		amountInWordsCell.setColspan(4);
1835
		return amountInWordsCell;
1836
	}
1837
 
1838
	/**
1839
	 * Returns the item name to be displayed in the invoice table.
1840
	 * 
1841
	 * @param lineitem
1842
	 *            The line item whose name has to be displayed
1843
	 * @param appendIMEI
1844
	 *            Whether to attach the IMEI No. to the item name
1845
	 * @return The name to be displayed for the given line item.
1846
	 */
1847
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
1848
		StringBuffer itemName = new StringBuffer();
1849
		if(lineitem.getBrand()!= null)
1850
			itemName.append(lineitem.getBrand() + " ");
1851
		if(lineitem.getModel_name() != null)
1852
			itemName.append(lineitem.getModel_name() + " ");
1853
		if(lineitem.getModel_number() != null )
1854
			itemName.append(lineitem.getModel_number() + " ");
1855
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
1856
			itemName.append("("+lineitem.getColor()+")");
13320 manish.sha 1857
		if(appendIMEI && lineitem.isSetSerial_number() && !lineitem.getSerial_number().isEmpty()){
7014 rajveer 1858
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
1859
		}
1860
 
1861
		return itemName.toString();
1862
	}
1863
 
1864
	/**
1865
	 * 
1866
	 * @param colspan
1867
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
1868
	 *         no. of columns
1869
	 */
1870
	private PdfPCell getEOECell(int colspan) {
1871
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
1872
		eoeCell.setColspan(colspan);
1873
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1874
		return eoeCell;
1875
	}
1876
 
1877
	private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
1878
		PdfPTable extraInfoTable = new PdfPTable(1);
1879
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1880
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1881
 
1882
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1883
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1884
		ttfFontFactory.register(fontPath, "barcode");
1885
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1886
 
1887
		PdfPCell extraInfoCell;
1888
		if(billingType == BillingType.EXTERNAL){
1889
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
1890
		}else{
1891
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
1892
		}
1893
 
1894
		extraInfoCell.setPaddingTop(20.0f);
1895
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1896
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1897
 
1898
		extraInfoTable.addCell(extraInfoCell);
1899
 
1900
 
1901
		return extraInfoTable;
1902
	}
1903
 
1904
	private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
1905
		PdfPTable extraInfoTable = new PdfPTable(1);
1906
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1907
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1908
 
1909
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1910
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1911
		ttfFontFactory.register(fontPath, "barcode");
1912
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1913
 
1914
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
1915
 
1916
		extraInfoCell.setPaddingTop(20.0f);
1917
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1918
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1919
 
1920
		extraInfoTable.addCell(extraInfoCell);
1921
 
1922
		return extraInfoTable;
1923
	}
8067 manish.sha 1924
 
1925
	private void generateBarcode(String barcodeString, String fileName){
1926
		Code128Bean bean = new Code128Bean();
7014 rajveer 1927
 
8067 manish.sha 1928
		final int dpi = 60;
1929
 
1930
		//Configure the barcode generator
1931
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
1932
		                                                 //width exactly one pixel
1933
		bean.setFontSize(bean.getFontSize()+1.0f);
1934
		bean.doQuietZone(false);
1935
 
1936
		try {
1937
			File outputFile = new File("/tmp/"+fileName+".png");
1938
			OutputStream out = new FileOutputStream(outputFile);
1939
 
1940
		    //Set up the canvas provider for monochrome PNG output 
1941
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
1942
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
1943
 
1944
		    //Generate the barcode
1945
		    bean.generateBarcode(canvas, barcodeString);
1946
 
1947
		    //Signal end of generation
1948
		    canvas.finish();
1949
		    out.close();
1950
 
1951
		} 
1952
		catch(Exception e){
1953
			logger.error("Exception during generating Barcode : ", e);
1954
		}
1955
	}
1956
 
7014 rajveer 1957
	public static void main(String[] args) throws IOException {
1958
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
7318 rajveer 1959
		long orderId = 356324;
1960
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
7014 rajveer 1961
		String userHome = System.getProperty("user.home");
1962
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
1963
		FileOutputStream fos = new FileOutputStream(f);
1964
		baos.writeTo(fos);
1965
		System.out.println("Invoice generated.");
1966
	}
2787 chandransh 1967
}