Subversion Repositories SmartDukaan

Rev

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

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