Subversion Repositories SmartDukaan

Rev

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