Subversion Repositories SmartDukaan

Rev

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