Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12653 manish.sha 1
package in.shop2020.support.controllers;
2
 
3
 
4
import java.awt.image.BufferedImage;
5
import java.io.BufferedReader;
6
import java.io.ByteArrayOutputStream;
7
import java.io.File;
8
import java.io.FileOutputStream;
9
import java.io.FileReader;
10
import java.io.IOException;
11
import java.io.OutputStream;
12
import java.text.DateFormat;
13
import java.text.DecimalFormat;
14
import java.util.ArrayList;
15
import java.util.Date;
16
import java.util.HashMap;
17
import java.util.List;
18
import java.util.Locale;
19
import java.util.Map;
20
 
21
import in.shop2020.config.ConfigException;
22
import in.shop2020.logistics.DeliveryType;
23
import in.shop2020.logistics.LogisticsServiceException;
24
import in.shop2020.logistics.PickUpType;
25
import in.shop2020.logistics.PickupStore;
26
import in.shop2020.logistics.Provider;
27
import in.shop2020.logistics.ProviderDetails;
28
import in.shop2020.model.v1.catalog.CatalogService;
29
import in.shop2020.model.v1.catalog.Item;
30
import in.shop2020.model.v1.catalog.ItemType;
31
import in.shop2020.model.v1.inventory.BillingType;
32
import in.shop2020.model.v1.inventory.InventoryService;
33
import in.shop2020.model.v1.inventory.InventoryServiceException;
34
import in.shop2020.model.v1.inventory.Warehouse;
35
import in.shop2020.model.v1.order.AmazonOrder;
36
import in.shop2020.model.v1.order.Attribute;
37
import in.shop2020.model.v1.order.EbayOrder;
38
import in.shop2020.model.v1.order.FlipkartOrder;
39
import in.shop2020.model.v1.order.LineItem;
40
import in.shop2020.model.v1.order.OrderSource;
41
import in.shop2020.model.v1.order.OrderStatus;
42
import in.shop2020.model.v1.order.OrderType;
43
import in.shop2020.model.v1.order.ProductCondition;
44
import in.shop2020.model.v1.order.SnapdealOrder;
45
import in.shop2020.model.v1.order.TaxType;
46
import in.shop2020.model.v1.order.TransactionService;
47
import in.shop2020.support.utils.ReportsUtils;
48
import in.shop2020.thrift.clients.CatalogClient;
49
import in.shop2020.thrift.clients.InventoryClient;
50
import in.shop2020.thrift.clients.LogisticsClient;
51
import in.shop2020.thrift.clients.TransactionClient;
52
import in.shop2020.thrift.clients.config.ConfigClient;
53
import in.shop2020.model.v1.order.Order;
54
 
55
import javax.servlet.ServletOutputStream;
56
import javax.servlet.http.HttpServletRequest;
57
import javax.servlet.http.HttpServletResponse;
58
import javax.servlet.http.HttpSession;
59
 
60
import org.apache.commons.io.FileUtils;
61
import org.apache.commons.lang.StringUtils;
62
import org.apache.commons.lang.WordUtils;
63
import org.apache.struts2.interceptor.ServletRequestAware;
64
import org.apache.struts2.interceptor.ServletResponseAware;
65
import org.apache.struts2.interceptor.SessionAware;
66
import org.apache.thrift.TException;
67
import org.apache.thrift.transport.TTransportException;
68
import org.krysalis.barcode4j.impl.code128.Code128Bean;
69
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
70
import org.krysalis.barcode4j.tools.UnitConv;
71
import org.slf4j.Logger;
72
import org.slf4j.LoggerFactory;
73
 
74
import com.ibm.icu.text.RuleBasedNumberFormat;
75
import com.itextpdf.text.Document;
76
import com.itextpdf.text.Element;
77
import com.itextpdf.text.Font;
78
import com.itextpdf.text.FontFactory;
79
import com.itextpdf.text.FontFactoryImp;
80
import com.itextpdf.text.Image;
81
import com.itextpdf.text.Paragraph;
82
import com.itextpdf.text.Phrase;
83
import com.itextpdf.text.Rectangle;
84
import com.itextpdf.text.Font.FontFamily;
85
import com.itextpdf.text.pdf.BaseFont;
86
import com.itextpdf.text.pdf.PdfPCell;
87
import com.itextpdf.text.pdf.PdfPTable;
88
import com.itextpdf.text.pdf.PdfWriter;
89
import com.itextpdf.text.pdf.draw.DottedLineSeparator;
90
import com.opensymphony.xwork2.ActionSupport;
91
@SuppressWarnings("serial")
92
public class BulkOrderBillingController extends ActionSupport implements ServletResponseAware, ServletRequestAware{
93
 
94
	private HttpServletRequest request;
95
	private HttpSession session;
96
	protected HttpServletResponse response;
97
 
98
	private File bulkBillingFile;
99
	private String errorMsg="";
100
	private String successMsg="";
101
	private String fileNameVal;
102
	private String orderIds;
103
 
104
	private String oneOrderId;
105
 
106
	private long singleTransactionId = 0l;
107
	private long singleUserId = 0l;
108
 
109
	private Map<Long, List<String>> orderImeiListMap = new HashMap<Long, List<String>>(); 
110
 
111
	private static Logger logger = LoggerFactory.getLogger(BulkOrderBillingController.class);
112
 
113
 
114
	@Override
115
	public void setServletRequest(HttpServletRequest request) {
116
		// TODO Auto-generated method stub
117
		this.request = request;
118
		this.session = request.getSession();	
119
	}
120
 
121
	public void setServletResponse(HttpServletResponse response) {
122
		this.response = response;
123
	}
124
 
125
	public String index() {
126
		if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath()))
127
			return "authfail";
128
		return "bulk-order-billing";
129
	}
130
 
131
	public String create(){
132
 
133
		File fileToCreate = null;
134
		List<Long> orderIdList = new ArrayList<Long>();
135
		Map<Long, Order> ordersMap = new HashMap<Long, Order>();
136
		Map<Long, Map<Long, String>> orderItemsMap = new HashMap<Long, Map<Long, String>>();
137
		Map<Long, Boolean> billingLeftOrderIdMap = new HashMap<Long, Boolean>();
138
		Map<Long, Integer> orderBillingTypeMap = new HashMap<Long, Integer>();
139
		TransactionClient txnClient = null;
140
		CatalogClient catalogClient = null;
141
		InventoryClient inventoryClient = null;
142
		try {
143
			txnClient = new TransactionClient();
144
			catalogClient = new CatalogClient();
145
			inventoryClient = new InventoryClient();
146
		} catch (TTransportException e1) {
147
			// TODO Auto-generated catch block
148
			e1.printStackTrace();
149
		}
150
 
151
		if(bulkBillingFile!=null & fileNameVal !=null && !fileNameVal.isEmpty()){
152
			logger.info("File Name "+bulkBillingFile.getName());
153
			System.out.println("File Name "+bulkBillingFile.getName());
154
 
155
			logger.info("File Name Value "+fileNameVal);
156
			System.out.println("File Name Value "+fileNameVal);
157
			String fileName = fileNameVal;
158
 
159
			try {
160
				if(!fileName.substring(fileName.lastIndexOf(".")+1).equalsIgnoreCase("txt")){
161
					throw new Exception("Not Again! File is not in expected TXT Format");
162
				}
163
				fileToCreate = new File("/tmp/", fileName);
164
 
165
				FileUtils.copyFile(this.bulkBillingFile, fileToCreate);
166
			} catch (Exception e) {
167
				logger.error("Hurray!! Error while writing file used to the local file system", e);
168
				errorMsg = e.getMessage();
169
				return "bulk-order-billing";
170
			}
171
 
172
		}
173
		else {
174
			errorMsg = errorMsg + "<br>Folk, No File Uploaded or file name is blank";
175
		}
176
		if(fileToCreate==null){
177
			errorMsg = errorMsg +" <br> No File to read";
178
			return "bulk-order-billing";
179
		}
180
 
181
		if(orderIds==null || orderIds.trim().isEmpty() || orderIds.trim().length()==0){
182
			errorMsg = errorMsg +" <br> Order Ids ";
183
		} else {
184
			if(orderIds.contains(",")){
185
				for(String s: orderIds.split(",")){
186
					orderIdList.add(Long.parseLong(s.trim()));
187
				}
188
			}else{
189
				orderIdList.add(Long.parseLong(orderIds.trim()));
190
			}
191
		}
192
 
193
		TransactionService.Client tClient = txnClient.getClient();
194
		InventoryService.Client iClient = inventoryClient.getClient();
195
 
196
		try{
197
			List<Order> ordersList = tClient.getOrderList(orderIdList);
198
			if(ordersList!=null && ordersList.size()>0){
199
				long transactionId = ordersList.get(0).getTransactionId();
200
				if(ordersList.size()>1){
201
					for (Order order: ordersList){
202
						if(transactionId== order.getTransactionId()){
203
							List<Attribute> attrList = new ArrayList<Attribute>();
204
							Attribute attr1 = new Attribute();
205
							attr1.setName("Single Invoice");
206
							attr1.setValue("true");
207
							attrList.add(attr1);
208
 
209
							ordersMap.put(order.getId(), order);
210
 
211
							if(!tClient.isAlive()){
212
								tClient = txnClient.getClient();
213
							}
214
							tClient.setOrderAttributes(order.getId(), attrList);
215
 
216
							if(!iClient.isAlive()){
217
								iClient = inventoryClient.getClient();
218
							}
219
 
220
							orderBillingTypeMap.put(order.getId(), iClient.getWarehouse(order.getWarehouse_id()).getBillingType().getValue());
221
							singleTransactionId = transactionId;
222
							singleUserId = order.getCustomer_id();
223
						} else {
224
							billingLeftOrderIdMap.put(order.getId(), Boolean.TRUE);
225
						}
226
					}
227
				} else {
228
					ordersMap.put(ordersList.get(0).getId(), ordersList.get(0));
229
 
230
					List<Attribute> attrList = new ArrayList<Attribute>();
231
					Attribute attr1 = new Attribute();
232
					attr1.setName("Single Invoice");
233
					attr1.setValue("true");
234
					attrList.add(attr1);
235
 
236
					if(!tClient.isAlive()){
237
						tClient = txnClient.getClient();
238
					}
239
					tClient.setOrderAttributes(ordersList.get(0).getId(), attrList);
240
 
241
					if(!iClient.isAlive()){
242
						iClient = inventoryClient.getClient();
243
					}
244
					singleTransactionId = transactionId;
245
					singleUserId = ordersList.get(0).getCustomer_id();
246
					orderBillingTypeMap.put(ordersList.get(0).getId(), iClient.getWarehouse(ordersList.get(0).getWarehouse_id()).getBillingType().getValue());
247
				}
248
			} else {
249
				return "bulk-order-billing";
250
			}
251
 
252
		} catch(Exception e){
253
			e.printStackTrace();
254
		}
255
 
256
		CatalogService.Client cClient = catalogClient.getClient();
257
 
258
 
259
		try{
260
			if(ordersMap!=null && ordersMap.size()>0){
261
				for(Long orderId: ordersMap.keySet()){
262
					Order order = ordersMap.get(orderId);
263
					LineItem lineItem = order.getLineitems().get(0);
264
					if(!cClient.isAlive()){
265
						cClient = catalogClient.getClient();
266
					}
267
					Item orderItem = cClient.getItem(lineItem.getItem_id());
268
					Map<Long, String> itemTypeMap = new HashMap<Long, String>();
269
					if(orderItem.getType()==ItemType.NON_SERIALIZED){
270
						itemTypeMap.put(orderItem.getId(), "NON_SERIALIZED");
271
					} else {
272
						itemTypeMap.put(orderItem.getId(), "SERIALIZED");
273
					}
274
					orderItemsMap.put(orderId, itemTypeMap);
275
				}
276
			}
277
		} catch(Exception e){
278
			e.printStackTrace();
279
		}
280
 
281
		Map<Long,List<String>> serialNumbersMap = new HashMap<Long, List<String>>();
282
		Map<Long,List<String>> itemNumbersMap = new HashMap<Long, List<String>>();
283
		Map<Long,Long> freebieWarehouseIdMap = new HashMap<Long,Long>();
284
		if(fileToCreate.isFile()){
285
			try{
286
				BufferedReader br = new BufferedReader(new FileReader(fileToCreate));
287
				long line = 1;
288
				String strLine;
289
				String[] values;
290
 
291
 
292
				while((strLine = br.readLine())!=null){
293
					if(line==1){
294
						values = strLine.split("\t");						
295
						if(values.length !=4){
296
							errorMsg = errorMsg + " File contains Inappropriate Content ";
297
							addActionError(errorMsg);
298
							return create();
299
						}
300
						line++;
301
						continue;
302
					}
303
					values = strLine.split("\t");
304
					logger.info("Row No "+line);
305
					System.out.print("Row No "+line);
306
					for(String s : values){
307
						logger.info(s);
308
						System.out.print(s);
309
					}
310
					if(!tClient.isAlive()){
311
						tClient = txnClient.getClient();
312
					}
313
 
314
 
315
					long ordId= Long.parseLong(values[0]);
316
					if(billingLeftOrderIdMap.containsKey(ordId)){
317
						line++;
318
						continue;
319
					}
320
 
321
					List<String> serialNumbers = null;
322
					List<String> itemNumbers = null;
323
					Order order = ordersMap.get(ordId);
324
					if(order.isSetFreebieItemId()){
325
						if(!freebieWarehouseIdMap.containsKey(ordId)){
326
							freebieWarehouseIdMap.put(ordId, Long.parseLong(values[3]));
327
						}
328
					} else{
329
						if(!freebieWarehouseIdMap.containsKey(ordId)){
330
							freebieWarehouseIdMap.put(ordId, 0l);
331
						}
332
					}
333
					if("SERIALIZED".equalsIgnoreCase(orderItemsMap.get(order.getId()).get(order.getLineitems().get(0).getItem_id()))){
334
						if(serialNumbersMap.containsKey(ordId)){
335
							serialNumbers = serialNumbersMap.get(ordId);
336
							serialNumbers.add(values[2]);
337
							serialNumbersMap.put(ordId, serialNumbers);
338
						}else{
339
							serialNumbers = new ArrayList<String>();
340
							serialNumbers.add(values[2]);
341
							serialNumbersMap.put(ordId, serialNumbers);
342
						}
343
						if(itemNumbersMap.containsKey(ordId)){
344
							itemNumbers = itemNumbersMap.get(ordId);
345
							itemNumbers.add(values[1]);
346
							itemNumbersMap.put(ordId, itemNumbers);
347
						}else{
348
							itemNumbers = new ArrayList<String>();
349
							itemNumbers.add(values[1]);
350
							itemNumbersMap.put(ordId, itemNumbers);
351
						}
352
 
353
					} else {
354
						if(itemNumbersMap.containsKey(ordId)){
355
							itemNumbers = itemNumbersMap.get(ordId);
356
							itemNumbers.add(values[1]);
357
							itemNumbersMap.put(ordId, itemNumbers);
358
						}else{
359
							itemNumbers = new ArrayList<String>();
360
							itemNumbers.add(values[1]);
361
							itemNumbersMap.put(ordId, itemNumbers);
362
						}
363
					}
364
					/*try{
365
						tClient.addBillingDetails(order.getId(), null, serialNumbers, itemNumbers, Long.parseLong(values[3]), "mp-mmx-admin", (long)(Math.random()*Math.pow(10.0, 7)), orderBillingTypeMap.get(order.getId()), order.getFulfilmentWarehouseId(), false);
366
					} catch(Exception e1){
367
						if(serialNumbers.size()>0){
368
							if(orderImeiListMap.containsKey(order.getId())){
369
								List<String> imeiList = orderImeiListMap.get(order.getId());
370
								imeiList.addAll(serialNumbers);
371
								orderImeiListMap.put(order.getId(), imeiList);
372
							}
373
							else{
374
								orderImeiListMap.put(order.getId(), serialNumbers);
375
							}
376
						}
377
 
378
						if(itemNumbers.size()>0 && serialNumbers.size()==0){
379
							if(orderImeiListMap.containsKey(order.getId())){
380
								List<String> imeiList = orderImeiListMap.get(order.getId());
381
								imeiList.addAll(itemNumbers);
382
								orderImeiListMap.put(order.getId(), imeiList);
383
							}
384
							else{
385
								orderImeiListMap.put(order.getId(), itemNumbers);
386
							}
387
						}
388
						line++;
389
						continue;
390
 
391
					}*/
392
 
393
					line++;
394
				}
395
 
396
				/*if(orderImeiListMap!=null && orderImeiListMap.size()>0){
397
					for(Long orderId : orderImeiListMap.keySet()){
398
						errorMsg = errorMsg + "<br> Error Occured for Order Id: "+ orderId ; 
399
						for(String imei : orderImeiListMap.get(orderId)){
400
							errorMsg = errorMsg + " Imei :" + imei +" ";
401
						}
402
					}
403
				}*/
404
 
405
				for(Order order: ordersMap.values()){
406
					try{
407
						if("SERIALIZED".equalsIgnoreCase(orderItemsMap.get(order.getId()).get(order.getLineitems().get(0).getItem_id()))){
408
							tClient.addBillingDetails(order.getId(), null, serialNumbersMap.get(order.getId()), itemNumbersMap.get(order.getId()), freebieWarehouseIdMap.get(order.getId()), "mp-mmx-admin", (long)(Math.random()*Math.pow(10.0, 7)), orderBillingTypeMap.get(order.getId()), order.getFulfilmentWarehouseId(), false);
409
						}else{
410
							tClient.addBillingDetails(order.getId(), null, new ArrayList<String>(), itemNumbersMap.get(order.getId()), freebieWarehouseIdMap.get(order.getId()), "mp-mmx-admin", (long)(Math.random()*Math.pow(10.0, 7)), orderBillingTypeMap.get(order.getId()), order.getFulfilmentWarehouseId(), false);
411
						}
412
 
413
					} catch(Exception e1){
414
						errorMsg = errorMsg+ "<br>" + "Order Id :" +order.getId()+ " Got Some Error while billing";
415
						logger.error("Order Id :" +order.getId()+ " Got Some Error while billing", e1);
416
						continue;
417
					}
418
				}
419
 
420
				if(billingLeftOrderIdMap!=null && billingLeftOrderIdMap.size()>0){
421
					errorMsg = errorMsg+ "<br>" + "These orders have been left because does not have same transaction id ";
422
					for(Long orderId : billingLeftOrderIdMap.keySet()){
423
						errorMsg = errorMsg+ orderId+ " ";
424
					}
425
				}
426
 
427
 
428
 
429
 
430
			} catch(Exception e){
431
				logger.error(errorMsg, e);
432
			}
433
		}
434
 
435
		if(singleTransactionId>0 && singleUserId>0){
436
			try{
437
				if(!tClient.isAlive()){
438
					tClient = txnClient.getClient();
439
				}
440
				tClient.addInvoiceDetailsToOrders(singleTransactionId, singleUserId);
441
			} catch(Exception e){
442
				errorMsg = errorMsg + "<br>Error while generating invoice number for transaction";
443
				logger.error(errorMsg, e);
444
			}
445
		}
446
 
447
		successMsg="All Orders have been billed sucessfully and also Invoice Number genrated";
448
		return "bulk-order-billing";
449
	}
450
 
451
	public void downloadInvoice(){
452
		TransactionClient txnClient = null;
453
		try{
454
			txnClient = new TransactionClient();
455
			TransactionService.Client tClient = txnClient.getClient();
456
			Order singleOrder = null;
457
			if(oneOrderId!=null && StringUtils.isNumeric(oneOrderId)){
458
				singleOrder = tClient.getOrder(Long.parseLong(oneOrderId));
459
				if(singleOrder.getSource()!=OrderSource.WEBSITE.getValue()){
460
					errorMsg = "Order source is not Website. Can't Bill using this functionality";
461
					return;
462
				}
463
				if(!singleOrder.isSetInvoice_number()){
464
					errorMsg = "Order has not been billed. Can't generate invoice";
465
					return;
466
				}
467
			}
468
			ByteArrayOutputStream baos = null;
469
 
470
			InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
471
			baos = invoiceGenerationService.generateInvoice(singleOrder.getTransactionId(), singleOrder.getCustomer_id(), true, false);
472
 
473
			logger.info("After this piece of code");
474
			response.setContentType("application/pdf");
475
			response.setHeader("Content-disposition", "inline; filename=invoice-"+singleOrder.getTransactionId()+".pdf" );
476
 
477
			ServletOutputStream sos = response.getOutputStream();
478
			sos.write(baos.toByteArray());
479
			sos.flush();
480
		}
481
		catch(Exception e){
482
			logger.error("Unablke to stream",e);
483
			e.printStackTrace();
484
		}
485
 
486
	}
487
 
488
	public File getBulkBillingFile() {
489
		return bulkBillingFile;
490
	}
491
 
492
	public void setBulkBillingFile(File bulkBillingFile) {
493
		this.bulkBillingFile = bulkBillingFile;
494
	}
495
 
496
	public String getErrorMsg() {
497
		return errorMsg;
498
	}
499
 
500
	public void setErrorMsg(String errorMsg) {
501
		this.errorMsg = errorMsg;
502
	}
503
 
504
	public String getSuccessMsg() {
505
		return successMsg;
506
	}
507
 
508
	public void setSuccessMsg(String successMsg) {
509
		this.successMsg = successMsg;
510
	}
511
 
512
	public String getFileNameVal() {
513
		return fileNameVal;
514
	}
515
 
516
	public void setFileNameVal(String fileNameVal) {
517
		this.fileNameVal = fileNameVal;
518
	}
519
 
520
	public String getOrderIds() {
521
		return orderIds;
522
	}
523
 
524
	public void setOrderIds(String orderIds) {
525
		this.orderIds = orderIds;
526
	}
527
 
528
	public static Warehouse getWarehouse(long warehouseId) {
529
		try{
530
			InventoryClient catalogServiceClient = new InventoryClient();
531
			InventoryService.Client catalogClient = catalogServiceClient.getClient();
532
			return catalogClient.getWarehouse(warehouseId);
533
		}catch(Exception e){
534
			e.printStackTrace();
535
		}
536
		return null;
537
	}
538
 
539
	public String getOneOrderId() {
540
		return oneOrderId;
541
	}
542
 
543
	public void setOneOrderId(String oneOrderId) {
544
		this.oneOrderId = oneOrderId;
545
	}
546
}
547
 
548
 
549
class InvoiceGenerationService {
550
 
551
	private static Logger logger = LoggerFactory.getLogger(InvoiceGenerationService.class);
552
 
553
	private TransactionClient tsc = null;
554
	private InventoryClient csc = null;
555
	private LogisticsClient lsc = null;
556
	private CatalogClient ctsc = null;
557
 
558
	private static Locale indianLocale = new Locale("en", "IN");
559
	private DecimalFormat amountFormat = new DecimalFormat("#,##0.00");
560
 
561
	//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
562
	private static final Font helvetica6 = FontFactory.getFont(FontFactory.HELVETICA, 6);
563
	//End:-Added By Manish Sharma for FedEx Integration  - Shipment Creation on 21-Aug-2013
564
	private static final Font helvetica8 = FontFactory.getFont(FontFactory.HELVETICA, 8);
565
	/*private static final Font helvetica10 = FontFactory.getFont(FontFactory.HELVETICA, 10);
566
	private static final Font helvetica12 = FontFactory.getFont(FontFactory.HELVETICA, 12);*/
567
	private static final Font helvetica16 = FontFactory.getFont(FontFactory.HELVETICA, 16);
568
	//private static final Font helvetica22 = FontFactory.getFont(FontFactory.HELVETICA, 22);
569
 
570
	private static final Font helveticaBold8 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 8);
571
	private static final Font helveticaBold12 = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 12);
572
 
573
	private static final String delhiPincodePrefix = "11";
574
	private static final String[] maharashtraPincodePrefix = {"40", "41", "42", "43", "44"};
575
 
576
	public InvoiceGenerationService() {
577
		try {
578
			tsc = new TransactionClient();
579
			csc = new InventoryClient();
580
			lsc = new LogisticsClient();
581
			ctsc = new CatalogClient();
582
		} catch (Exception e) {
583
			logger.error("Error while instantiating thrift clients.", e);
584
		}
585
	}
586
 
587
	public ByteArrayOutputStream generateInvoice(long transactionId, long customerId, boolean withBill, boolean printAll) {
588
		ByteArrayOutputStream baosPDF = null;
589
		in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
590
 
591
 
592
		try {
593
			baosPDF = new ByteArrayOutputStream();
594
 
595
			Document document = new Document();
596
			PdfWriter.getInstance(document, baosPDF);
597
			document.addAuthor("shop2020");
598
			//document.addTitle("Invoice No: " + order.getInvoice_number());
599
			document.open();
600
 
601
			List<Order> orders = new ArrayList<Order>();
602
 
603
			if(!tclient.isAlive()){
604
				tclient = tsc.getClient();
605
			}
606
 
607
			List<Order> ordersByTransaction = tclient.getOrdersForTransaction(transactionId, customerId);
608
			for(Order order: ordersByTransaction){
609
				if(order.isSetInvoice_number()){
610
					orders.add(order);
611
				}
612
			}
613
 
614
 
615
 
616
			PdfPTable taxTable = getTaxCumRetailInvoiceTable(orders);
617
			taxTable.setWidthPercentage(90.0f);
618
			taxTable.setSpacingAfter(5.0f);
619
 
620
 
621
			PdfPTable orderItemsDetailTable = new PdfPTable(1);
622
			orderItemsDetailTable.setWidthPercentage(90.0f);
623
			orderItemsDetailTable.setSpacingBefore(5.0f);
624
			orderItemsDetailTable.addCell(new Phrase("Order Reference Ids :", helveticaBold8));
625
			StringBuffer sbOrders = new StringBuffer();
626
 
627
			for(Order o1 : orders){
628
				sbOrders.append(o1.getId()+",");
629
			}
630
 
631
 
632
			String orderIds = sbOrders.toString();
633
			orderIds = orderIds.substring(0, orderIds.length()-1);
634
 
635
			orderItemsDetailTable.addCell(new Phrase(orderIds.toString(), helvetica8));
636
			orderItemsDetailTable.addCell(new Phrase("IMEI Details :", helveticaBold8));
637
 
638
			StringBuffer sbImeis = new StringBuffer();
639
 
640
			for(Order o1 : orders){
641
				sbImeis.append(o1.getLineitems().get(0).getSerial_number()+",");
642
			}
643
 
644
			String imeis = sbImeis.toString();
645
			imeis = imeis.substring(0, imeis.length()-1);
646
 
647
			orderItemsDetailTable.addCell(new Phrase(imeis, helvetica8));
648
 
649
 
650
 
651
 
652
			document.add(taxTable);
653
			document.add(new DottedLineSeparator());
654
			document.add(orderItemsDetailTable);
655
 
656
 
657
 
658
			document.close();
659
			baosPDF.close();
660
			// Adding facility to store the bill on the local directory. This will happen for only for Mahipalpur warehouse.
661
			if(withBill && !printAll){
662
				/*String strOrderId = StringUtils.repeat("0", 10-String.valueOf(transactionId).length()) + transactionId;  
663
				String dirPath = "/SaholicInvoices" + File.separator + strOrderId.substring(0, 2) + File.separator + strOrderId.substring(2, 4) + File.separator + strOrderId.substring(4, 6);
664
				String filename = dirPath + File.separator + transactionId + ".pdf";*/
665
				String  filename = "/tmp/"+"invoice-"+transactionId+".pdf";
666
				/*File dirFile = new File(dirPath);
667
				if(!dirFile.exists()){
668
					dirFile.mkdirs();
669
				}*/
670
				File f = new File(filename);
671
				FileOutputStream fos = new FileOutputStream(f);
672
				baosPDF.writeTo(fos);
673
			}
674
		} catch (Exception e) {
675
			logger.error("Error while generating Invoice: ", e);
676
		}
677
		return baosPDF;
678
	}
679
 
680
 
681
 
682
	private void addLogoTable(PdfPTable logoTable,Order order) {
683
		logoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
684
		logoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
685
		logoTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
686
 
687
		PdfPCell logoCell;
688
		String logoPath;
689
 
690
		if(order.getSource() == OrderSource.STORE.getValue()){
691
			logoCell = new PdfPCell(new Phrase(""));
692
 
693
		}else{
694
			logoPath = InvoiceGenerationService.class.getResource("/logo.jpg").getPath();
695
 
696
			try {
697
				logoCell = new PdfPCell(Image.getInstance(logoPath), false);
698
			} catch (Exception e) {
699
				//Too Many exceptions to catch here: BadElementException, MalformedURLException and IOException
700
				logger.warn("Couldn't load the Saholic logo: ", e);
701
				logoCell = new PdfPCell(new Phrase("Saholic Logo"));
702
			}
703
 
704
		}
705
		logoCell.setBorder(Rectangle.NO_BORDER);
706
		logoCell.setHorizontalAlignment(Element.ALIGN_LEFT);
707
		logoTable.addCell(logoCell);
708
		logoTable.addCell(" ");
709
 
710
	}
711
 
712
	/*private Font getBarCodeFont(Provider provider, float barcodeFontSize) {
713
		String fontPath = InvoiceGenerationService.class.getResource("/" + provider.getName().toLowerCase() + "/barcode.TTF").getPath();
714
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
715
		ttfFontFactory.register(fontPath, "barcode");
716
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
717
		return barCodeFont;
718
	}*/
719
 
720
	/*private PdfPCell getTitleCell() {
721
		PdfPCell titleCell = new PdfPCell(new Phrase("Dispatch Advice", helveticaBold12));
722
		titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
723
		titleCell.setBorder(Rectangle.NO_BORDER);
724
		return titleCell;
725
	}*/
726
 
727
	/*private PdfPTable getProviderTable(Order order, Provider provider, Font barCodeFont) {
728
		PdfPTable providerInfoTable = new PdfPTable(1);
729
		providerInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
730
		if(order.isLogisticsCod()){
731
			PdfPCell deliveryTypeCell = new PdfPCell(new Phrase("COD   ", helvetica22));
732
			deliveryTypeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
733
			deliveryTypeCell.setBorder(Rectangle.NO_BORDER);
734
			providerInfoTable.addCell(deliveryTypeCell);
735
		}
736
 
737
 
738
		PdfPCell providerNameCell = new PdfPCell(new Phrase(provider.getName(), helveticaBold12));
739
		providerNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
740
		providerNameCell.setBorder(Rectangle.NO_BORDER);
741
		PdfPCell formIdCell= null;
742
		if(order.getLogistics_provider_id()==7L){
743
			if(order.isCod()){
744
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0305", helvetica6));
745
			}
746
			else{
747
				formIdCell = new PdfPCell(new Paragraph(order.getAirwaybill_no()+" Form id-0467", helvetica6));
748
			}
749
			formIdCell.setPaddingTop(1.0f);
750
			formIdCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
751
			formIdCell.setBorder(Rectangle.NO_BORDER);
752
		}
753
 
754
 
755
		PdfPCell awbNumberCell= null;
756
		String fedexPackageBarcode = "";
757
		if(order.getLogistics_provider_id()!=7L){
758
			awbNumberCell = new PdfPCell(new Paragraph("*" + order.getAirwaybill_no() + "*", barCodeFont));
759
			awbNumberCell.setPaddingTop(20.0f);
760
		}
761
		else{
762
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
763
			try {
764
				fedexPackageBarcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Package_BarCode");
765
			} catch (TException e1) {
766
				logger.error("Error while getting the provider information.", e1);
767
			}
768
			awbNumberCell = new PdfPCell(new Paragraph(" ", helvetica6));
769
		}
770
		awbNumberCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
771
		awbNumberCell.setBorder(Rectangle.NO_BORDER);
772
 
773
		providerInfoTable.addCell(providerNameCell);
774
		if(formIdCell != null){
775
			providerInfoTable.addCell(formIdCell);
776
		}
777
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
778
		if(order.getLogistics_provider_id()==7L){
779
			generateBarcode(fedexPackageBarcode, "fedex_"+order.getId());
780
 
781
			Image barcodeImage=null;
782
			try {
783
				barcodeImage = Image.getInstance("/tmp/"+"fedex_"+order.getId()+".png");
784
			} catch (Exception e) {
785
				logger.error("Exception during getting Barcode Image for Fedex : ", e);
786
			}
787
			providerInfoTable.addCell(barcodeImage);
788
		}
789
		providerInfoTable.addCell(awbNumberCell);
790
 
791
		Warehouse warehouse = null;
792
		try{
793
    		InventoryClient isc = new InventoryClient();
794
    		warehouse = isc.getClient().getWarehouse(order.getWarehouse_id());
795
		} catch(Exception e) {
796
		    logger.error("Unable to get warehouse for id : " + order.getWarehouse_id(), e);
797
		    //TODO throw e;
798
		}
799
		DeliveryType dt =  DeliveryType.PREPAID;
800
        if (order.isLogisticsCod()) {
801
            dt = DeliveryType.COD;
802
        }
803
        //Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
804
        if(order.getLogistics_provider_id()!=7L){
805
	        for (ProviderDetails detail : provider.getDetails()) {
806
	            if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
807
	                providerInfoTable.addCell(new Phrase("Account No : " + detail.getAccountNo(), helvetica8));
808
	            }
809
	        }
810
        }
811
        else{
812
        	providerInfoTable.addCell(new Phrase("STANDARD OVERNIGHT ", helvetica8));
813
        }
814
        //End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
815
		Date awbDate;
816
		if(order.getBilling_timestamp() == 0){
817
			awbDate = new Date();
818
		}else{
819
			awbDate = new Date(order.getBilling_timestamp());
820
		}
821
		if(order.getLogistics_provider_id()!=7L){
822
			providerInfoTable.addCell(new Phrase("AWB Date   : " + DateFormat.getDateInstance(DateFormat.MEDIUM).format(awbDate), helvetica8));
823
		}
824
		providerInfoTable.addCell(new Phrase("Weight         : " + order.getTotal_weight() + " Kg", helvetica8));
825
		if(order.getSource() == OrderSource.EBAY.getValue()){
826
			EbayOrder ebayOrder = null;
827
			try {
828
				ebayOrder = tsc.getClient().getEbayOrderByOrderId(order.getId());
829
			} catch (TException e) {
830
				logger.error("Error while getting ebay order", e);
831
			}
832
			providerInfoTable.addCell(new Phrase("PaisaPayId            : " + ebayOrder.getPaisaPayId(), helvetica8));
833
			providerInfoTable.addCell(new Phrase("Sales Rec Number: " + ebayOrder.getSalesRecordNumber(), helvetica8));
834
		}
835
		//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
836
		if(order.getLogistics_provider_id()==7L){
837
			providerInfoTable.addCell(new Phrase("Bill T/C Sender      "+ "Bill D/T Sender", helvetica8));
838
		}
839
		//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
840
		return providerInfoTable;
841
	}*/
842
 
843
	/*private PdfPTable getTopInvoiceTable(Order order, String tinNo){
844
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.2f, 0.2f, 0.3f, 0.1f, 0.1f, 0.1f});
845
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
846
 
847
		invoiceTable.addCell(getInvoiceTableHeader(6));
848
 
849
		invoiceTable.addCell(new Phrase("Order No", helvetica8));
850
		invoiceTable.addCell(new Phrase("Paymode", helvetica8));
851
		invoiceTable.addCell(new Phrase("Product Name", helvetica8));
852
		invoiceTable.addCell(new Phrase("Quantity", helvetica8));
853
		invoiceTable.addCell(new Phrase("Rate", helvetica8));
854
		invoiceTable.addCell(new Phrase("Amount", helvetica8));
855
		populateTopInvoiceTable(order, invoiceTable);
856
 
857
 
858
		if(order.getInsurer() > 0) {
859
			invoiceTable.addCell(getInsuranceCell(4));
860
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
861
			invoiceTable.addCell(getPriceCell(order.getInsuranceAmount()));
862
		}
863
 
864
		if(order.getSource() == OrderSource.STORE.getValue()) {
865
			invoiceTable.addCell(getAdvanceAmountCell(4));
866
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
867
			invoiceTable.addCell(getPriceCell(order.getAdvanceAmount()));
868
		}
869
 
870
		invoiceTable.addCell(getTotalCell(4));      
871
		invoiceTable.addCell(getRupeesCell());
872
		invoiceTable.addCell(getTotalAmountCell(order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
873
 
874
		PdfPCell tinCell = new PdfPCell(new Phrase("TIN NO. " + tinNo, helvetica8));
875
		tinCell.setColspan(6);
876
		tinCell.setPadding(2);
877
		invoiceTable.addCell(tinCell);
878
 
879
		return invoiceTable;
880
	}*/
881
 
882
	/*private void populateTopInvoiceTable(Order order, PdfPTable invoiceTable) {
883
		List<LineItem> lineitems = order.getLineitems();
884
		for (LineItem lineitem : lineitems) {
885
			invoiceTable.addCell(new Phrase(order.getId() + "", helvetica8));
886
			if(order.getPickupStoreId() > 0 && order.isCod() == true)
887
				invoiceTable.addCell(new Phrase("In-Store", helvetica8));
888
			else if (order.isCod())
889
				invoiceTable.addCell(new Phrase("COD", helvetica8));
890
			else
891
				invoiceTable.addCell(new Phrase("Prepaid", helvetica8));
892
 
893
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
894
 
895
			invoiceTable.addCell(new Phrase(lineitem.getQuantity() + "", helvetica8));
896
 
897
			invoiceTable.addCell(getPriceCell(lineitem.getUnit_price()-order.getGvAmount()));
898
 
899
			invoiceTable.addCell(getPriceCell(lineitem.getTotal_price()-order.getGvAmount()));
900
		}
901
	}*/
902
 
903
	/*private PdfPCell getAddressCell(String address) {
904
		Paragraph addressParagraph = new Paragraph(address, new Font(FontFamily.TIMES_ROMAN, 8f));
905
		PdfPCell addressCell = new PdfPCell();
906
		addressCell.addElement(addressParagraph);
907
		addressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
908
		addressCell.setBorder(Rectangle.NO_BORDER);
909
		return addressCell;
910
	}*/
911
 
912
	private PdfPTable getTaxCumRetailInvoiceTable(List<Order> orders){
913
		in.shop2020.model.v1.inventory.InventoryService.Client iclient = csc.getClient();
914
 
915
		String ourAddress = "";
916
		String tinNo = "";
917
 
918
		Order order = null;
919
		for(Order ord: orders){
920
			Warehouse warehouse = null;
921
			Warehouse shippingLocation = null;
922
			order =ord;
923
			try {
924
				warehouse = iclient.getWarehouse(order.getWarehouse_id());
925
				shippingLocation = BulkOrderBillingController.getWarehouse(warehouse.getShippingWarehouseId());
926
				ourAddress = shippingLocation.getLocation() + "-" + shippingLocation.getPincode();
927
				tinNo = shippingLocation.getTinNumber();
928
			} catch (InventoryServiceException ise) {
929
				logger.error("Error while getting the warehouse information.", ise);
930
				return null;
931
			} catch (TException te) {
932
				logger.error("Error while getting some essential information from the services", te);
933
				return null;
934
			}
935
			break;
936
		}
937
 
938
		PdfPTable taxTable = new PdfPTable(1);
939
		Phrase phrase = null;
940
		taxTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
941
		taxTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
942
 
943
		PdfPTable logoTitleAndOurAddressTable = new PdfPTable(new float[]{0.4f, 0.3f, 0.3f});
944
		logoTitleAndOurAddressTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
945
		logoTitleAndOurAddressTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
946
 
947
 
948
		PdfPTable logoTable = new PdfPTable(2);
949
		addLogoTable(logoTable,order); 
950
 
951
		if (order.getOrderType().equals(OrderType.B2B)) {
952
			phrase = new Phrase("TAX INVOICE", helveticaBold12);
953
		} else {
954
			phrase = new Phrase("RETAIL INVOICE", helveticaBold12);
955
		}
956
		PdfPCell retailInvoiceTitleCell = new PdfPCell(phrase);
957
		retailInvoiceTitleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
958
		retailInvoiceTitleCell.setBorder(Rectangle.NO_BORDER);
959
 
960
		Paragraph sorlAddress = new Paragraph(ourAddress + "\n Contact No.- 0120-2479977" + "\nTIN NO. " + tinNo, new Font(FontFamily.TIMES_ROMAN, 8f, Element.ALIGN_CENTER));
961
		PdfPCell sorlAddressCell = new PdfPCell(sorlAddress);
962
		sorlAddressCell.addElement(sorlAddress);
963
		sorlAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
964
 
965
		PdfPTable customerAddress = getCustomerAddressTable(order, null, true, helvetica8, true);
966
		PdfPTable orderDetails = getOrderDetails(order);
967
 
968
		PdfPTable addrAndOrderDetailsTable = new PdfPTable(new float[]{0.5f, 0.1f, 0.4f});
969
		addrAndOrderDetailsTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
970
		addrAndOrderDetailsTable.addCell(customerAddress);
971
		addrAndOrderDetailsTable.addCell(new Phrase(" "));
972
		addrAndOrderDetailsTable.addCell(orderDetails);
973
 
974
		boolean isVAT = isVatApplicable(order);
975
		PdfPTable invoiceTable = getBottomInvoiceTable(orders, isVAT);
976
 
977
		PdfPTable regAddAndDisCellTable = new PdfPTable(2);
978
 
979
		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));
980
		disclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
981
		disclaimerCell.setBorder(Rectangle.NO_BORDER);
982
 
983
		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. 0120-2479977 E-mail. help@saholic.com Website. www.saholic.com", helvetica6));
984
		regAddressCell.setHorizontalAlignment(Element.ALIGN_LEFT);
985
		regAddressCell.setBorder(Rectangle.NO_BORDER);
986
		/*SPICE ONLINE RETAIL PRIVATE LIMITED
987
		Regd. Add. 60-D, STREET NO. C-5, SAINIK FARMS,NEW DELHI-110062
988
		CIN: U74140DL2008PTC183856
989
		Tel. No. 0120-2479977
990
		E-mail. help@saholic.com
991
		Website. www.saholic.com*/
992
 
993
 
994
		logoTitleAndOurAddressTable.addCell(logoTable);
995
		logoTitleAndOurAddressTable.addCell(retailInvoiceTitleCell);
996
		logoTitleAndOurAddressTable.addCell(sorlAddress);
997
 
998
		regAddAndDisCellTable.addCell(disclaimerCell);
999
		regAddAndDisCellTable.addCell(regAddressCell);
1000
 
1001
		taxTable.addCell(logoTitleAndOurAddressTable);
1002
		taxTable.addCell(addrAndOrderDetailsTable);
1003
		taxTable.addCell(invoiceTable);
1004
		taxTable.addCell(regAddAndDisCellTable);
1005
 
1006
		if(order.getProductCondition().equals(ProductCondition.BAD)){
1007
			PdfPCell badSaleDisclaimerCell = new PdfPCell(new Phrase(" Item(s) above are sold on as is where is basis. They " +
1008
					"may be in dead/defective/damaged/refurbished/incomplete/open condition. These " +
1009
					"are not returnable, exchangeable or refundable under any circumstances. No " +
1010
					"warranty is assured on these items." ,
1011
					new Font(FontFamily.TIMES_ROMAN, 8f)));
1012
			badSaleDisclaimerCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1013
			badSaleDisclaimerCell.setBorder(Rectangle.NO_BORDER);
1014
			taxTable.addCell(badSaleDisclaimerCell);
1015
		}
1016
		return taxTable;
1017
	}
1018
 
1019
	private boolean isVatApplicable(Order order) {
1020
		if(order.getWarehouse_id() == 7) {
1021
			if(order.getCustomer_pincode().startsWith(delhiPincodePrefix)) {
1022
				return true;
1023
			} else {
1024
				return false;
1025
			}
1026
		} else {
1027
			for(int i=0; i< maharashtraPincodePrefix.length; i++) {
1028
				if(order.getCustomer_pincode().startsWith(maharashtraPincodePrefix[i])) {
1029
					return true;
1030
				}
1031
			}
1032
			return false;
1033
		}
1034
	}
1035
 
1036
	/*private PdfPTable getFlipkartBarCodes(Order order) {
1037
		PdfPTable flipkartTable = new PdfPTable(3);
1038
 
1039
		PdfPCell spacerCell = new PdfPCell();
1040
		spacerCell.setBorder(Rectangle.NO_BORDER);
1041
		spacerCell.setColspan(3);
1042
		spacerCell.setPaddingTop(330.0f);
1043
 
1044
		String flipkartCodeFontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1045
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1046
		ttfFontFactory.register(flipkartCodeFontPath, "barcode");
1047
		Font flipkartBarCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, 20);
1048
 
1049
		String serialNumber = "0000000000";
1050
		if(order.getLineitems().get(0).getSerial_number()!=null && !order.getLineitems().get(0).getSerial_number().isEmpty()) {
1051
			serialNumber = order.getLineitems().get(0).getSerial_number();
1052
		} else if(order.getLineitems().get(0).getItem_number()!=null && !order.getLineitems().get(0).getItem_number().isEmpty()) {
1053
			serialNumber = order.getLineitems().get(0).getItem_number();
1054
		}
1055
 
1056
		PdfPCell serialNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  serialNumber + "*", flipkartBarCodeFont));
1057
		serialNumberBarCodeCell.setBorder(Rectangle.TOP);
1058
		serialNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1059
		serialNumberBarCodeCell.setPaddingTop(11.0f);
1060
 
1061
 
1062
		PdfPCell invoiceNumberBarCodeCell = new PdfPCell(new Paragraph("*" +  order.getInvoice_number() + "*", flipkartBarCodeFont));
1063
		invoiceNumberBarCodeCell.setBorder(Rectangle.TOP);
1064
		invoiceNumberBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1065
		invoiceNumberBarCodeCell.setPaddingTop(11.0f);
1066
 
1067
		double rate = order.getLineitems().get(0).getVatRate();
1068
		double salesTax = (rate * order.getTotal_amount())/(100 + rate);
1069
		PdfPCell vatAmtBarCodeCell = new PdfPCell(new Paragraph("*" +  amountFormat.format(salesTax) + "*", flipkartBarCodeFont));
1070
		vatAmtBarCodeCell.setBorder(Rectangle.TOP);
1071
		vatAmtBarCodeCell.setHorizontalAlignment(Element.ALIGN_CENTER);
1072
		vatAmtBarCodeCell.setPaddingTop(11.0f);
1073
 
1074
		flipkartTable.addCell(spacerCell);
1075
		flipkartTable.addCell(serialNumberBarCodeCell);
1076
		flipkartTable.addCell(invoiceNumberBarCodeCell);
1077
		flipkartTable.addCell(vatAmtBarCodeCell);
1078
 
1079
		return flipkartTable;
1080
 
1081
	}*/
1082
 
1083
	private PdfPTable getCustomerAddressTable(Order order, String destCode, boolean showPaymentMode, Font font, boolean forInvoce){
1084
		PdfPTable customerTable = new PdfPTable(1);
1085
		customerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1086
		if(forInvoce || order.getPickupStoreId() == 0){
1087
			customerTable.addCell(new Phrase(order.getCustomer_name(), font));
1088
			customerTable.addCell(new Phrase(order.getCustomer_address1(), font));
1089
			customerTable.addCell(new Phrase(order.getCustomer_address2(), font));
1090
			customerTable.addCell(new Phrase(order.getCustomer_city() + "," + order.getCustomer_state(), font));
1091
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1092
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1093
			if(order.getLogistics_provider_id()!=7L){
1094
				if(destCode != null)
1095
					customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + destCode, helvetica16));
1096
				else
1097
					customerTable.addCell(new Phrase(order.getCustomer_pincode(), font));
1098
			}
1099
			else{
1100
				String fedexLocationcode = "";
1101
				try {
1102
					fedexLocationcode = tclient.getOrderAttributeValue(order.getId(), "FedEx_Location_Code");
1103
				} catch (TException e1) {
1104
					logger.error("Error while getting the provider information.", e1);
1105
				}
1106
				customerTable.addCell(new Phrase(order.getCustomer_pincode() + " - " + fedexLocationcode, helvetica16));
1107
			}
1108
			//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013
1109
			if(order.getCustomer_mobilenumber()!=null && !order.getCustomer_mobilenumber().isEmpty()) {
1110
				customerTable.addCell(new Phrase("Phone : " + (order.getCustomer_mobilenumber()== null ? "" : order.getCustomer_mobilenumber()), font));
1111
			}
1112
 
1113
		}else{
1114
			try {
1115
				in.shop2020.logistics.LogisticsService.Client lclient = (new LogisticsClient()).getClient();
1116
				PickupStore store = lclient.getPickupStore(order.getPickupStoreId());
1117
				customerTable.addCell(new Phrase(order.getCustomer_name() + " \nc/o " + store.getName(), font));
1118
				customerTable.addCell(new Phrase(store.getLine1(), font));
1119
				customerTable.addCell(new Phrase(store.getLine2(), font));
1120
				customerTable.addCell(new Phrase(store.getCity() + "," + store.getState(), font));
1121
				if(destCode != null)
1122
					customerTable.addCell(new Phrase(store.getPin() + " - " + destCode, helvetica16));
1123
				else
1124
					customerTable.addCell(new Phrase(store.getPin(), font));
1125
				customerTable.addCell(new Phrase("Phone :" + store.getPhone(), font));
1126
 
1127
 
1128
			} catch (TException e) {
1129
				// TODO Auto-generated catch block
1130
				e.printStackTrace();
1131
			}
1132
 
1133
		}
1134
 
1135
		if(order.getOrderType().equals(OrderType.B2B)) {
1136
			String tin = null;
1137
			in.shop2020.model.v1.order.TransactionService.Client tclient = tsc.getClient();
1138
			List<Attribute> attributes;
1139
			try {
1140
				attributes = tclient.getAllAttributesForOrderId(order.getId());
1141
 
1142
				for(Attribute attribute : attributes) {
1143
					if(attribute.getName().equals("tinNumber")) {
1144
						tin = attribute.getValue();
1145
					}
1146
				}
1147
				if (tin != null) {
1148
					customerTable.addCell(new Phrase("TIN :" + tin, font));
1149
				}
1150
 
1151
			} catch (Exception e) {
1152
				logger.error("Error while getting order attributes", e);
1153
			}
1154
		}
1155
		/*
1156
        if(showPaymentMode){
1157
            customerTable.addCell(new Phrase(" ", font));
1158
            customerTable.addCell(new Phrase("Payment Mode: Prepaid", font));
1159
        }*/
1160
		return customerTable;
1161
	}
1162
 
1163
	private PdfPTable getOrderDetails(Order order){
1164
		PdfPTable orderTable = new PdfPTable(new float[]{0.4f, 0.6f});
1165
		orderTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1166
 
1167
		orderTable.addCell(new Phrase("Invoice No:", helvetica8));
1168
		orderTable.addCell(new Phrase(order.getInvoice_number(), helvetica8));
1169
 
1170
		orderTable.addCell(new Phrase("Date:", helvetica8));
1171
		orderTable.addCell(new Phrase(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date(order.getBilling_timestamp())), helvetica8));
1172
 
1173
		try {
1174
			String poRefVal = tsc.getClient().getOrderAttributeValue(order.getId(), "poRefNumber");
1175
			if(poRefVal!=null && poRefVal.length()>0){
1176
				orderTable.addCell(new Phrase("PO Ref:", helvetica8));
1177
				orderTable.addCell(new Phrase(poRefVal, helvetica8));
1178
			}
1179
 
1180
		} catch (TException e) {
1181
			logger.error("Error while getting amazon order", e);
1182
		}
1183
 
1184
		orderTable.addCell(new Phrase("Tax Type:", helvetica8));
1185
 
1186
		if(order.getTaxType().equals(TaxType.CFORM)) {
1187
			orderTable.addCell(new Phrase("CST Against CForm", helvetica8));
1188
		} else {
1189
 
1190
			if(isVatApplicable(order)){
1191
				orderTable.addCell(new Phrase("VAT", helvetica8));
1192
			} else {
1193
				orderTable.addCell(new Phrase("CST", helvetica8));
1194
			}
1195
			orderTable.addCell(getVATLabelCell(isVatApplicable(order)));
1196
		}
1197
		return orderTable;
1198
	}
1199
 
1200
	private PdfPTable getBottomInvoiceTable(List<Order> orders, boolean isVAT){
1201
		PdfPTable invoiceTable = new PdfPTable(new float[]{0.1f, 0.3f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f});
1202
		invoiceTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1203
 
1204
		invoiceTable.addCell(getInvoiceTableHeader(8));
1205
 
1206
		invoiceTable.addCell(new Phrase("Sl. No.", helveticaBold8));
1207
		invoiceTable.addCell(new Phrase("Description", helveticaBold8));
1208
		invoiceTable.addCell(new Phrase("Quantity", helveticaBold8));
1209
		invoiceTable.addCell(new Phrase("Rate (Rs)", helveticaBold8));
1210
		invoiceTable.addCell(new Phrase("Amount (Rs)", helveticaBold8));
1211
		invoiceTable.addCell(new Phrase("Tax Rate%", helveticaBold8));
1212
		invoiceTable.addCell(new Phrase("Tax (Rs)", helveticaBold8));
1213
		invoiceTable.addCell(new Phrase("Item Total (Rs)", helveticaBold8));
1214
 
1215
		double totalOrdersAmount = 0.0;
1216
		int i=1;
1217
		for(Order order :orders){
1218
			LineItem lineItem = order.getLineitems().get(0);
1219
			double orderAmount = order.getTotal_amount();
1220
			double rate = lineItem.getVatRate();
1221
			double salesTax = (rate * (orderAmount - order.getInsuranceAmount()))/(100 + rate);
1222
 
1223
			invoiceTable.addCell(new Phrase(i+"", helveticaBold8));
1224
			invoiceTable.addCell(getProductNameCell(lineItem, false, order.getFreebieItemId()));
1225
			invoiceTable.addCell(new Phrase("" + lineItem.getQuantity(), helvetica8));
1226
 
1227
 
1228
			//populateBottomInvoiceTable(order, invoiceTable, rate);
1229
 
1230
			double itemPrice = lineItem.getUnit_price();
1231
			double showPrice = (100 * itemPrice)/(100 + rate);
1232
			invoiceTable.addCell(getPriceCell(showPrice));
1233
 
1234
			double totalPrice = lineItem.getTotal_price();
1235
			showPrice = (100 * totalPrice)/(100 + rate);
1236
			invoiceTable.addCell(getPriceCell(showPrice));
1237
 
1238
			PdfPCell salesTaxCell = getPriceCell(salesTax);
1239
 
1240
 
1241
			invoiceTable.addCell(new Phrase(rate + "%", helvetica8));
1242
			invoiceTable.addCell(salesTaxCell);
1243
			invoiceTable.addCell(getTotalAmountCell(orderAmount));
1244
 
1245
			totalOrdersAmount = totalOrdersAmount+ orderAmount;
1246
			i++;
1247
		}
1248
 
1249
 
1250
		invoiceTable.addCell(getEmptyCell(8));
1251
 
1252
		invoiceTable.addCell(getTotalCell(6));
1253
		invoiceTable.addCell(getRupeesCell());
1254
		invoiceTable.addCell(getTotalAmountCell(totalOrdersAmount));
1255
 
1256
		invoiceTable.addCell(new Phrase("Amount in Words:", helveticaBold8));
1257
		invoiceTable.addCell(getAmountInWordsCell(totalOrdersAmount));
1258
 
1259
		invoiceTable.addCell(getEOECell(8));
1260
 
1261
		return invoiceTable;
1262
	}
1263
 
1264
	private PdfPCell getInvoiceTableHeader(int colspan) {
1265
		PdfPCell invoiceTableHeader = new PdfPCell(new Phrase("Order Item Details:", helveticaBold12));
1266
		invoiceTableHeader.setBorder(Rectangle.NO_BORDER);
1267
		invoiceTableHeader.setColspan(colspan);
1268
		invoiceTableHeader.setPaddingTop(1);
1269
		return invoiceTableHeader;
1270
	}
1271
 
1272
	/*private void populateBottomInvoiceTable(Order order, PdfPTable invoiceTable, double rate) {
1273
		for (LineItem lineitem : order.getLineitems()) {
1274
			invoiceTable.addCell(new Phrase("" + order.getId() , helvetica8));
1275
 
1276
			invoiceTable.addCell(getProductNameCell(lineitem, false, order.getFreebieItemId()));
1277
 
1278
			invoiceTable.addCell(new Phrase("" + lineitem.getQuantity(), helvetica8));
1279
 
1280
			double itemPrice = lineitem.getUnit_price();
1281
			double showPrice = (100 * itemPrice)/(100 + rate);
1282
			invoiceTable.addCell(getPriceCell(showPrice)); //Unit Price Cell
1283
 
1284
			double totalPrice = lineitem.getTotal_price();
1285
			showPrice = (100 * totalPrice)/(100 + rate);
1286
			invoiceTable.addCell(getPriceCell(showPrice));  //Total Price Cell
1287
		}
1288
	}*/
1289
 
1290
	private PdfPCell getProductNameCell(LineItem lineitem, boolean appendIMEI, Long freebieItemId) {
1291
		String itemName = getItemDisplayName(lineitem, appendIMEI);
1292
		if(freebieItemId!=null && freebieItemId!=0){
1293
			try {
1294
				CatalogService.Client catalogClient = ctsc.getClient();
1295
				Item item = catalogClient.getItem(freebieItemId);
1296
				itemName = itemName + "\n(Free Item: " + item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + ")";
1297
			} catch(Exception tex) {
1298
				logger.error("Not able to get Freebie Item Details for ItemId:" + freebieItemId, tex);
1299
			}
1300
		}
1301
		PdfPCell productNameCell = new PdfPCell(new Phrase(itemName, helvetica8));
1302
		productNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
1303
		return productNameCell;
1304
	}
1305
 
1306
	private PdfPCell getPriceCell(double price) {
1307
		PdfPCell totalPriceCell = new PdfPCell(new Phrase(amountFormat.format(price), helvetica8));
1308
		totalPriceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1309
		return totalPriceCell;
1310
	}
1311
 
1312
	private PdfPCell getVATLabelCell(boolean isVAT) {
1313
		PdfPCell vatCell = null;
1314
		if(isVAT){
1315
			vatCell = new PdfPCell(new Phrase("VAT", helveticaBold8));
1316
		} else {
1317
			vatCell = new PdfPCell(new Phrase("CST", helveticaBold8));
1318
		}
1319
		vatCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1320
		return vatCell;
1321
	}
1322
 
1323
	private PdfPCell getCFORMLabelCell() {
1324
		PdfPCell cFormCell = null;
1325
		cFormCell = new PdfPCell(new Phrase("CST Against CForm", helveticaBold8));
1326
		cFormCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1327
		return cFormCell;
1328
	}
1329
 
1330
	/*private PdfPCell getAdvanceAmountCell(int colspan) {
1331
		PdfPCell insuranceCell = null;
1332
		insuranceCell = new PdfPCell(new Phrase("Advance Amount Received", helvetica8));
1333
		insuranceCell.setColspan(colspan);
1334
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1335
		return insuranceCell;
1336
	}*/
1337
 
1338
	/*private PdfPCell getInsuranceCell(int colspan) {
1339
		PdfPCell insuranceCell = null;
1340
		insuranceCell = new PdfPCell(new Phrase("1 Year WorldWide Theft Insurance", helvetica8));
1341
		insuranceCell.setColspan(colspan);
1342
		insuranceCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1343
		return insuranceCell;
1344
	}*/
1345
 
1346
	private PdfPCell getEmptyCell(int colspan) {
1347
		PdfPCell emptyCell = new PdfPCell(new Phrase(" ", helvetica8));
1348
		emptyCell.setColspan(colspan);
1349
		return emptyCell;
1350
	}
1351
 
1352
	private PdfPCell getTotalCell(int colspan) {
1353
		PdfPCell totalCell = new PdfPCell(new Phrase("Grand Total", helveticaBold8));
1354
		totalCell.setColspan(colspan);
1355
		totalCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1356
		return totalCell;
1357
	}
1358
 
1359
	private PdfPCell getRupeesCell() {
1360
		PdfPCell rupeesCell = new PdfPCell(new Phrase("Rs.", helveticaBold8));
1361
		rupeesCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1362
		return rupeesCell;
1363
	}
1364
 
1365
	private PdfPCell getTotalAmountCell(double orderAmount) {
1366
		PdfPCell totalAmountCell = new PdfPCell(new Phrase(amountFormat.format(orderAmount), helveticaBold8));
1367
		totalAmountCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1368
		return totalAmountCell;
1369
	}
1370
 
1371
	/**
1372
	 * This method uses ICU4J libraries to convert the given amount into words
1373
	 * of Indian locale.
1374
	 * 
1375
	 * @param orderAmount
1376
	 *            The amount to convert.
1377
	 * @return the string representation of the given amount.
1378
	 */
1379
	private PdfPCell getAmountInWordsCell(double orderAmount) {
1380
		RuleBasedNumberFormat amountInWordsFormat = new RuleBasedNumberFormat(indianLocale, RuleBasedNumberFormat.SPELLOUT);
1381
		StringBuilder amountInWords = new StringBuilder("Rs. ");
1382
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)orderAmount)));
1383
		amountInWords.append(" and ");
1384
		amountInWords.append(WordUtils.capitalize(amountInWordsFormat.format((int)(orderAmount*100)%100)));
1385
		amountInWords.append(" paise");
1386
 
1387
		PdfPCell amountInWordsCell= new PdfPCell(new Phrase(amountInWords.toString(), helveticaBold8));
1388
		amountInWordsCell.setColspan(4);
1389
		return amountInWordsCell;
1390
	}
1391
 
1392
	/**
1393
	 * Returns the item name to be displayed in the invoice table.
1394
	 * 
1395
	 * @param lineitem
1396
	 *            The line item whose name has to be displayed
1397
	 * @param appendIMEI
1398
	 *            Whether to attach the IMEI No. to the item name
1399
	 * @return The name to be displayed for the given line item.
1400
	 */
1401
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
1402
		StringBuffer itemName = new StringBuffer();
1403
		if(lineitem.getBrand()!= null)
1404
			itemName.append(lineitem.getBrand() + " ");
1405
		if(lineitem.getModel_name() != null)
1406
			itemName.append(lineitem.getModel_name() + " ");
1407
		if(lineitem.getModel_number() != null )
1408
			itemName.append(lineitem.getModel_number() + " ");
1409
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
1410
			itemName.append("("+lineitem.getColor()+")");
1411
		if(appendIMEI && lineitem.isSetSerial_number()){
1412
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
1413
		}
1414
 
1415
		return itemName.toString();
1416
	}
1417
 
1418
	/**
1419
	 * 
1420
	 * @param colspan
1421
	 * @return a PdfPCell containing the E&amp;OE text and spanning the given
1422
	 *         no. of columns
1423
	 */
1424
	private PdfPCell getEOECell(int colspan) {
1425
		PdfPCell eoeCell = new PdfPCell(new Phrase("E & O.E", helvetica8));
1426
		eoeCell.setColspan(colspan);
1427
		eoeCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
1428
		return eoeCell;
1429
	}
1430
 
1431
	/*private PdfPTable getExtraInfoTable(Order order, Provider provider, float barcodeFontSize, BillingType billingType){
1432
		PdfPTable extraInfoTable = new PdfPTable(1);
1433
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1434
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1435
 
1436
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1437
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1438
		ttfFontFactory.register(fontPath, "barcode");
1439
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1440
 
1441
		PdfPCell extraInfoCell;
1442
		if(billingType == BillingType.EXTERNAL){
1443
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getCustomer_name() + "*        *"  + order.getTotal_amount() + "*", barCodeFont));
1444
		}else{
1445
			extraInfoCell = new PdfPCell(new Paragraph( "*" + order.getId() + "*        *" + order.getLineitems().get(0).getTransfer_price() + "*", barCodeFont));	
1446
		}
1447
 
1448
		extraInfoCell.setPaddingTop(20.0f);
1449
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1450
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1451
 
1452
		extraInfoTable.addCell(extraInfoCell);
1453
 
1454
 
1455
		return extraInfoTable;
1456
	}*/
1457
 
1458
	/*private PdfPTable getFixedTextTable(float barcodeFontSize, String printText){
1459
		PdfPTable extraInfoTable = new PdfPTable(1);
1460
		extraInfoTable.getDefaultCell().setBorder(Rectangle.NO_BORDER);
1461
		extraInfoTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
1462
 
1463
		String fontPath = InvoiceGenerationService.class.getResource("/saholic-wn.TTF").getPath();
1464
		FontFactoryImp ttfFontFactory = new FontFactoryImp();
1465
		ttfFontFactory.register(fontPath, "barcode");
1466
		Font barCodeFont = ttfFontFactory.getFont("barcode", BaseFont.CP1252, true, barcodeFontSize);
1467
 
1468
		PdfPCell extraInfoCell = new PdfPCell(new Paragraph( "*" + printText + "*", barCodeFont));
1469
 
1470
		extraInfoCell.setPaddingTop(20.0f);
1471
		extraInfoCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
1472
		extraInfoCell.setBorder(Rectangle.NO_BORDER);
1473
 
1474
		extraInfoTable.addCell(extraInfoCell);
1475
 
1476
		return extraInfoTable;
1477
	}*/
1478
 
1479
	/*private void generateBarcode(String barcodeString, String fileName){
1480
		Code128Bean bean = new Code128Bean();
1481
 
1482
		final int dpi = 60;
1483
 
1484
		//Configure the barcode generator
1485
		bean.setModuleWidth(UnitConv.in2mm(1.0f / dpi)); //makes the narrow bar 
1486
		                                                 //width exactly one pixel
1487
		bean.setFontSize(bean.getFontSize()+1.0f);
1488
		bean.doQuietZone(false);
1489
 
1490
		try {
1491
			File outputFile = new File("/tmp/"+fileName+".png");
1492
			OutputStream out = new FileOutputStream(outputFile);
1493
 
1494
		    //Set up the canvas provider for monochrome PNG output 
1495
		    BitmapCanvasProvider canvas = new BitmapCanvasProvider(
1496
		            out, "image/x-png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);
1497
 
1498
		    //Generate the barcode
1499
		    bean.generateBarcode(canvas, barcodeString);
1500
 
1501
		    //Signal end of generation
1502
		    canvas.finish();
1503
		    out.close();
1504
 
1505
		} 
1506
		catch(Exception e){
1507
			logger.error("Exception during generating Barcode : ", e);
1508
		}
1509
	}*/
1510
 
1511
	/*public static void main(String[] args) throws IOException {
1512
		InvoiceGenerationService invoiceGenerationService = new InvoiceGenerationService();
1513
		long orderId = 356324;
1514
		ByteArrayOutputStream baos = invoiceGenerationService.generateInvoice(orderId, true, false, 1);
1515
		String userHome = System.getProperty("user.home");
1516
		File f = new File(userHome + "/invoice-" + orderId + ".pdf");
1517
		FileOutputStream fos = new FileOutputStream(f);
1518
		baos.writeTo(fos);
1519
		System.out.println("Invoice generated.");
1520
	}*/
1521
}