Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
4600 varun.gupt 1
package in.shop2020.support.controllers;
2
 
3
import java.io.ByteArrayOutputStream;
4
import java.io.File;
5
import java.io.FileInputStream;
6
import java.io.FileNotFoundException;
7
import java.io.IOException;
8
import java.text.DateFormat;
9
import java.text.ParseException;
10
import java.text.SimpleDateFormat;
11
import java.util.Date;
12
import java.util.HashMap;
13
import java.util.List;
14
import java.util.Map;
15
 
16
import in.shop2020.model.v1.catalog.InventoryService.Client;
17
import in.shop2020.model.v1.catalog.Vendor;
18
import in.shop2020.model.v1.order.LineItem;
19
import in.shop2020.model.v1.order.Order;
20
import in.shop2020.model.v1.order.PaymentSettlement;
21
import in.shop2020.model.v1.order.Transaction;
22
import in.shop2020.model.v1.order.TransactionServiceException;
23
import in.shop2020.payments.Payment;
24
import in.shop2020.payments.PaymentException;
25
import in.shop2020.payments.PaymentGateway;
26
import in.shop2020.thrift.clients.CatalogClient;
27
import in.shop2020.thrift.clients.PaymentClient;
28
import in.shop2020.thrift.clients.TransactionClient;
29
 
30
import javax.servlet.ServletContext;
31
import javax.servlet.ServletOutputStream;
32
import javax.servlet.http.HttpServletRequest;
33
import javax.servlet.http.HttpServletResponse;
34
import javax.servlet.http.HttpSession;
35
 
36
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
37
import org.apache.poi.ss.usermodel.Cell;
38
import org.apache.poi.ss.usermodel.CellStyle;
39
import org.apache.poi.ss.usermodel.Font;
40
import org.apache.poi.ss.usermodel.Row;
41
import org.apache.poi.ss.usermodel.Sheet;
42
import org.apache.poi.ss.usermodel.Workbook;
43
import org.apache.poi.ss.util.CellRangeAddress;
4601 varun.gupt 44
import org.apache.struts2.convention.annotation.InterceptorRef;
45
import org.apache.struts2.convention.annotation.InterceptorRefs;
46
import org.apache.struts2.convention.annotation.Result;
47
import org.apache.struts2.convention.annotation.Results;
4600 varun.gupt 48
import org.apache.struts2.interceptor.ServletRequestAware;
49
import org.apache.struts2.interceptor.ServletResponseAware;
50
import org.apache.struts2.rest.DefaultHttpHeaders;
51
import org.apache.struts2.rest.HttpHeaders;
52
import org.apache.struts2.util.ServletContextAware;
53
import org.apache.thrift.TException;
54
import org.apache.thrift.transport.TTransportException;
55
import org.slf4j.Logger;
56
import org.slf4j.LoggerFactory;
57
 
58
/**
59
 * @author Varun Gupta
60
 * @description: This class handles web requests to generate vendor specific reconciliation reports
61
 *               for given vendor for a given date range
62
 */
63
 
4601 varun.gupt 64
@InterceptorRefs({
65
    @InterceptorRef("defaultStack"),
66
    @InterceptorRef("login")
67
})
68
@Results({
69
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
70
})
4600 varun.gupt 71
public class VendorReconciliationController implements ServletRequestAware, ServletResponseAware, ServletContextAware {
72
 
73
    private static Logger logger = LoggerFactory.getLogger(VendorReconciliationController.class);
74
 
75
	private enum OrderReportColumn {
76
	    ORDER_ID(0),
77
	    ORDER_DATE(1),
78
		BILLING_NUMBER(2),
79
		BILLING_DATE(3),
80
		DELIVERY_DATE(4),
81
		SETTLEMENT_DATE(5),
82
		CURRENT_STATUS(6),
83
		BRAND(7),
84
		MODEL_NAME(8),
85
		MODEL_NUMBER(9),
86
		COLOR(10),
87
		QUANTITY(11),
88
		UNIT_TRANSFER_PRICE(12),
89
		UNIT_SELLING_PRICE(13),
90
		TOTAL_TRANSFER_PRICE(14),
91
		TOTAL_SELLING_PRICE(15),
92
		GATEWAY_TRANSACTION_ID(16),
93
		PAYMENT_TYPE(17),
94
		PAYMENT_ID(18),
95
		COUPON_CODE(19),
96
		SERVICE_TAX(20),
97
		OTHER_CHARGES(21),
98
		NET_COLLECTION(22);
99
 
100
//		COUPON_CATEGORY(19),
101
//		DISCOUNT(20),
102
 
103
		private int value;
104
 
105
		OrderReportColumn(int value) {
106
			this.value = value;
107
		}
108
		public int getValue(){
109
			return this.value;
110
		}
111
	}
112
 
113
	private enum OrderMismatchColumn	{
114
		ORDER_ID(0),
115
		EXPECTED_COLLECTION(1),
116
		ACTUAL_COLLECTION(2);
117
 
118
		private int value;
119
 
120
		OrderMismatchColumn(int value) {
121
			this.value = value;
122
		}
123
		public int getValue(){
124
			return this.value;
125
		}
126
	}
127
 
128
	private HttpServletRequest request;
129
	private HttpServletResponse response;
130
	private ServletContext context;
131
    private HttpSession session;
132
	private List<Vendor> vendors;
133
	private String reportSource;
134
 
135
	private File hdfcSettlementReport;
136
 
137
	private File ebsSettlementReport;
138
	private File ebsSettlementSummary;
139
 
140
	private String bluedartSettlementDate;
141
	private File bluedartSettlementReport;
142
 
143
	private Map<Long, Map<String, Double>> misMatches = new HashMap<Long, Map<String, Double>>();
144
	private Map<Long, String> ebsSettlementSummaries;
145
 
146
	private final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
147
 
148
	public VendorReconciliationController()	{
149
		try	{
150
			CatalogClient csc = new CatalogClient();
151
			Client catalogClient = csc.getClient();
152
 
153
			vendors = catalogClient.getAllVendors();
154
 
155
			TransactionClient tsc = new TransactionClient();
156
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
157
 
158
			ebsSettlementSummaries = transactionClient.getEBSSettlementSummaries();
159
			System.out.println(ebsSettlementSummaries);
160
 
161
		} catch (Exception e) {
162
			// TODO: handle exception
163
		}
164
	}
165
 
166
	public String index()	{
167
		return "report";
168
	}
169
 
170
	public HttpHeaders create()	{
171
 
172
		String formType = request.getParameter("formtype");
173
		System.out.println(formType);
174
 
175
		if (formType.equals("uploadEBSSettlementSummary")) {
176
			uploadEBSSettlementSummary();
177
 
178
		} else if (formType.equals("uploadEBSSettlements")) {
179
			uploadEBSSettlements();
180
 
181
		} else if (formType.equals("uploadHDFCSettlements")) {
182
			uploadHDFCSettlements();
183
 
184
		} else if (formType.equals("uploadBluedartSettlements")) {
185
			uploadBluedartSettlements();
186
		}
187
		return new DefaultHttpHeaders("report");
188
	}
189
 
190
	public HttpHeaders generateReconciliationReport()	{
191
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
192
 
193
		try	{
194
			//Formatting Form input parameters
195
 
196
		    Date startDate = dateFormat.parse(request.getParameter("start"));
197
			Date endDate = dateFormat.parse(request.getParameter("end"));
198
		    long vendorId = Long.parseLong(request.getParameter("vendor"));
199
 
200
		    logger.info(startDate + " " + endDate + " " + vendorId);
201
 
202
			CatalogClient csc = new CatalogClient();
203
			Client catalogClient= csc.getClient();
204
			vendors = catalogClient.getAllVendors();
205
 
206
			TransactionClient tsc = new TransactionClient();
207
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
208
 
209
			List<Order> orders = transactionClient.getBilledOrdersForVendor(vendorId, startDate.getTime(), endDate.getTime());
210
			logger.info("Order count: " + orders.size());
211
			DateFormat dateFormatForFile = new SimpleDateFormat("dd.MM.yyyy");
212
			String vendorName = getVendorName(vendorId);
213
 
214
			response.setContentType("application/vnd.ms-excel");
215
			response.setHeader("Content-disposition", "inline; filename=" + vendorName + "-reconciliation-from-" + dateFormatForFile.format(startDate) + "-" + dateFormatForFile.format(endDate) + ".xls");
216
 
217
			ServletOutputStream sos;
218
			try {
219
				ByteArrayOutputStream baos = getReconciliationReport(orders, startDate, endDate);
220
				sos = response.getOutputStream();
221
				baos.writeTo(sos);
222
				sos.flush();
223
			} catch (IOException e)	{
224
				logger.error("Error while streaming the hotspot reconciliation report", e);
225
			}
226
		} catch (ParseException e)	{
227
			logger.error("Unable to parse the start or end date", e);
228
		} catch (TransactionServiceException e)	{
229
			logger.error("Error while getting order information from the transaction service", e);
230
		} catch (TException e) {
231
            logger.error("Unable to get the orders or the warehouses", e);
232
		} catch (NullPointerException e)   {
233
            logger.error("NullPointerException", e);
234
		} catch (Exception e)   {
235
            logger.error("Unexpected exception", e);
236
        }
237
		return new DefaultHttpHeaders("report");
238
	}
239
 
240
	public void uploadEBSSettlementSummary()	{
241
 
242
		DateFormat settlementDateFormat = new SimpleDateFormat("dd MMM,yyyy hh:mm:ss a");
243
		DateFormat transactionDateFormat = new SimpleDateFormat("yyyy-MM-dd");
244
 
245
		Workbook wb = null;
246
        try {
247
            wb = new HSSFWorkbook(new FileInputStream(ebsSettlementSummary));
248
        } catch (FileNotFoundException e) {
249
            logger.error("Unable to open the Settlement Summary report", e);
250
        } catch (IOException e) {
251
            logger.error("Unable to open the Settlement Summary report", e);
252
        }
253
        Sheet sheet = wb.getSheetAt(0);
254
 
255
        int indexSettlementId = 0;
256
        int indexSettlementDate = 1;
257
        int indexTransactionDateFrom = 2;
258
        int indexTransactionDateTo = 3;
259
        int indexAmount = 4;
260
 
261
        Row firstRow = sheet.getRow(0);
262
        Row secondRow = sheet.getRow(1);
263
        Row thirdRow = sheet.getRow(2);
264
        Row fourthRow = sheet.getRow(3);
265
        Row fifthRow = sheet.getRow(4);
266
 
267
		TransactionClient tsc;
268
 
269
		try {
270
			tsc = new TransactionClient();
271
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
272
 
273
			for(Row row: sheet)	{
274
				if(row.equals(firstRow) || row.equals(secondRow) || row.equals(thirdRow) || row.equals(fourthRow) || row.equals(fifthRow))	{
275
					continue;
276
				}
277
				long settlementId = (long) row.getCell(indexSettlementId).getNumericCellValue();
278
				String settlementDateStr = row.getCell(indexSettlementDate).getStringCellValue();
279
				String transactionDateFromStr = row.getCell(indexTransactionDateFrom).getStringCellValue();
280
				String transactionDateToStr = row.getCell(indexTransactionDateTo).getStringCellValue();
281
				Double amount = row.getCell(indexAmount).getNumericCellValue();
282
 
283
				Date settlementDate = settlementDateFormat.parse(settlementDateStr);
284
				Date transactionDateFrom = transactionDateFormat.parse(transactionDateFromStr);
285
				Date transactionDateTo = transactionDateFormat.parse(transactionDateToStr);
286
 
287
				try	{
288
					transactionClient.saveEBSSettlementSummary(settlementId, settlementDate.getTime(), transactionDateFrom.getTime(), transactionDateTo.getTime(), amount);
289
 
290
				} catch (Exception e) {
291
					e.printStackTrace();
292
				}
293
			}
294
        } catch (Exception e) {
295
        	e.printStackTrace();
296
		}
297
	}
298
 
299
	public void uploadHDFCSettlements()	{
300
		logger.info("Uploading HDFC settlements");
301
 
302
		Workbook wb = null;
303
		try {
304
			wb = new HSSFWorkbook(new FileInputStream(this.hdfcSettlementReport));
305
		} catch (FileNotFoundException e) {
306
			logger.error("Unable to open the Settlement report", e);
307
		} catch (IOException e) {
308
			logger.error("Unable to open the Settlement report", e);
309
		}
310
		Sheet sheet = wb.getSheetAt(0);
311
 
312
		Row firstRow = sheet.getRow(0);
313
 
314
		int indexRECFMT = 2;
315
		int indexSettlementDate = 7;
316
		int indexPaymentId = 13;
317
		int indexMSF = 14;
318
		int indexServiceTax = 15;
319
		int indexEduCess = 16;
320
		int indexNetCollection = 17;
321
 
322
		TransactionClient tsc;
323
		String paymentIdStr = "";
324
		long paymentId = 0;
325
 
326
		try {
327
			tsc = new TransactionClient();
328
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
329
 
330
			for (Row row: sheet)	{
331
                if(row.equals(firstRow))	continue;
332
 
333
                try	{
334
                    String recfmt = row.getCell(indexRECFMT).getStringCellValue();
335
                    Date settlementDate = row.getCell(indexSettlementDate).getDateCellValue();
336
                	double netCollection = row.getCell(indexNetCollection).getNumericCellValue();
337
                	paymentIdStr = row.getCell(indexPaymentId).getStringCellValue().replace("'", "");
338
                	paymentId = Long.parseLong(paymentIdStr);
339
 
340
                	logger.info("paymentId: " + paymentId + ", recfmt: " + recfmt + ", settlementDate: " + settlementDate + ", netCollection: " + netCollection);
341
 
342
                    if (recfmt.equalsIgnoreCase("CVD"))	{
343
                    	if (netCollection > 0)	netCollection *= -1;
344
                    	transactionClient.savePaymentSettlements(settlementDate.getTime(), 1, paymentId, 0, 0, netCollection);
345
 
346
                    } else	{
347
                    	double msf = row.getCell(indexMSF).getNumericCellValue();
348
                    	double serviceTax = row.getCell(indexServiceTax).getNumericCellValue();
349
                    	double eduCess = row.getCell(indexEduCess).getNumericCellValue();
350
                    	logger.info("msf: " + msf + ", serviceTax: " + serviceTax + ", eduCess: " + eduCess);
351
 
352
                    	transactionClient.savePaymentSettlements(settlementDate.getTime(), 1, paymentId, serviceTax, (eduCess + msf), netCollection);
353
                 	}
354
                } catch (NumberFormatException e) {
355
        			logger.error("NumberFormatException recieved for payment Id," + paymentIdStr + " "+ e);
356
 
357
        		} catch (TransactionServiceException e) {
358
        			logger.error("TransactionServiceException recieved for payment Id," + Long.toString(paymentId) + " " + e);
359
        		}
360
			}
361
		} catch (TTransportException e) {
362
			logger.error("TTransportException recieved for payment Id," + Long.toString(paymentId) + " " + e);
363
 
364
		} catch (TException e) {
365
			logger.error("TException recieved for payment Id," + Long.toString(paymentId) + " " + e);
366
		}
367
	}
368
 
369
	public void uploadEBSSettlements()	{
370
		Workbook wb = null;
371
        try {
372
            wb = new HSSFWorkbook(new FileInputStream(this.ebsSettlementReport));
373
        } catch (FileNotFoundException e) {
374
            logger.error("Unable to open the Settlement report", e);
375
        } catch (IOException e) {
376
            logger.error("Unable to open the Settlement report", e);
377
        }
378
 
379
        Sheet sheet = wb.getSheetAt(0);
380
 
381
		Row firstRow = sheet.getRow(0);
382
		Row secondRow = sheet.getRow(1);
383
 
384
        int indexPaymentId = 2;
385
        int indexTxnType = 5;
386
        int indexAmount = 6;
387
 
388
        Map<Long, Map<String, Double>> map = new HashMap<Long, Map<String,Double>>();
389
        Map <String, Double> record;
390
 
391
        try	{
392
        	for (Row row: sheet)	{
393
                if(row.equals(firstRow) || row.equals(secondRow))	continue;
394
 
395
                long paymentId = Long.parseLong(row.getCell(indexPaymentId).getStringCellValue());
396
                String transactionType = row.getCell(indexTxnType).getStringCellValue();
397
                double amount = row.getCell(indexAmount).getNumericCellValue();
398
 
399
                if(map.containsKey(paymentId))	{
400
                	map.get(paymentId).put(transactionType, amount);
401
 
402
                } else	{
403
                	record = new HashMap<String, Double>();
404
                	record.put(transactionType, amount);
405
                	map.put(paymentId, record);
406
                }
407
        	}
408
        } catch	(NullPointerException e)	{
409
        	logger.error("" + e);
410
        }
411
 
412
		TransactionClient tsc;
413
 
414
        long settlementId = Long.parseLong(request.getParameter("settlementId"));
415
 
416
        try	{
417
			tsc = new TransactionClient();
418
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
419
			long settlementDate = transactionClient.getEBSSettlementDate(settlementId);
420
 
421
        	for (long paymentId: map.keySet())	{
422
            	record = map.get(paymentId);
423
 
424
            	if(record.containsKey("Captured"))	{
425
            		double capturedAmount = record.get("Captured");
426
            		double tdr = record.get("TDR");
427
            		double serviceTax = record.get("ServiceTax");
428
 
429
            		if(tdr < 0)	tdr *= -1;
430
            		if(serviceTax < 0)	serviceTax *= -1;
431
 
432
            		double amount = capturedAmount - tdr - serviceTax;
433
            		transactionClient.savePaymentSettlements(settlementDate, 2, paymentId, serviceTax, tdr, amount);
434
            	} else	{
435
            		double refundedAmount = record.get("Refunded");
436
 
437
            		if (refundedAmount > 0)	refundedAmount *= -1;
438
 
439
            		transactionClient.savePaymentSettlements(settlementDate, 2, paymentId, 0.0, 0.0, refundedAmount);
440
            	}
441
            }
442
        	transactionClient.markEBSSettlementUploaded(settlementId);
443
 
444
        } catch (TTransportException e) {
445
        	logger.error("TTransportException " + e);
446
		} catch (TException e) {
447
        	logger.error("TException " + e);
448
		} catch (TransactionServiceException e) {
449
        	logger.error("TransactionServiceException " + e);
450
		}
451
	}
452
 
453
	public void uploadBluedartSettlements()	{
454
 
455
		Workbook wb = null;
456
        try {
457
            wb = new HSSFWorkbook(new FileInputStream(this.bluedartSettlementReport));
458
        } catch (FileNotFoundException e) {
459
            logger.error("Unable to open the Settlement report", e);
460
        } catch (IOException e) {
461
            logger.error("Unable to open the Settlement report", e);
462
        }
463
 
464
        Sheet sheet = wb.getSheetAt(0);
465
 
466
        Row firstRow = sheet.getRow(0);
467
        logger.info("Cell count:" + firstRow.getPhysicalNumberOfCells());
468
 
469
        int indexAWBno = 4;		//FIXME: add look up string to determine exact cell
470
        int indexAmount = 19;
471
 
472
        TransactionClient tsc;
473
        PaymentClient psc;
474
 
475
        try	{
476
			long settlementDate = DATE_FORMAT.parse(bluedartSettlementDate).getTime();
477
        	tsc = new TransactionClient();
478
        	in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
479
			psc = new PaymentClient();
480
	    	in.shop2020.payments.PaymentService.Client paymentClient = psc.getClient();
481
 
482
        	for (Row row : sheet) {
483
        		try	{
484
        			if(row.equals(firstRow))	continue;
485
        			long awbNumber = (long) row.getCell(indexAWBno).getNumericCellValue();
486
        			double amount = row.getCell(indexAmount).getNumericCellValue();
487
//        			mapAWBAndAmount.put(awbNumber, amount);
488
        			Order order = transactionClient.getOrderForAwb(Long.toString(awbNumber));
489
        			Payment payment = paymentClient.getSuccessfulPaymentForTxnId(order.getTransactionId());
490
        			logger.info("settlementDate: " + settlementDate + ", PaymentId: " + payment.getPaymentId() + ", Amount: " + amount);
491
 
492
        			transactionClient.savePaymentSettlements(settlementDate, 4, payment.getPaymentId(), 0.0, 0, amount);
493
        		} catch (NullPointerException e) {
494
        			logger.error("" + e);
495
 
496
        		} catch (PaymentException e) {
497
        			logger.error("" + e);
498
 
499
				} catch (TransactionServiceException e) {
500
					logger.error("" + e);
501
				}
502
        	}
503
        } catch (ParseException e) {
504
        	logger.error("Could not parse " + bluedartSettlementDate + " " + e);
505
		} catch (TTransportException e) {
506
			logger.error("" + e);
507
        } catch (TException e) {
508
        	logger.error("" + e);
509
        }
510
//        Map<Long, Double> mapAWBAndAmount = new HashMap<Long, Double>();
511
//        
512
//        for (Row row : sheet) {
513
//        	try	{
514
//                if(row.equals(firstRow))	continue;
515
//                long awbNumber = (long) row.getCell(indexAWBno).getNumericCellValue();
516
//                double amount = row.getCell(indexAmount).getNumericCellValue();
517
//                mapAWBAndAmount.put(awbNumber, amount);
518
//        	
519
//        	} catch (NullPointerException e) {
520
//        		logger.error("" + e);
521
//        	}
522
//        }
523
//        
524
//		TransactionClient tsc;
525
//		try {
526
//			tsc = new TransactionClient();
527
//			in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
528
//			
529
//	        transactionClient.saveBluedartSettlements(mapAWBAndAmount);
530
//		} catch (TTransportException e) {
531
//			logger.error("" + e);
532
//		} catch (TransactionServiceException e) {
533
//			logger.error("" + e);
534
//		} catch (TException e) {
535
//			logger.error("" + e);
536
//		}
537
	}
538
 
539
	// Prepares the XLS worksheet object and fills in the data with proper formatting
540
	private ByteArrayOutputStream getReconciliationReport(List<Order> orders, Date startDate, Date endDate)	{
541
		ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
542
 
543
	    Workbook wb = new HSSFWorkbook();
544
 
545
	    //Create the style for the title row
546
	    Font font = wb.createFont();
547
	    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
548
	    CellStyle boldStyle = wb.createCellStyle();
549
	    boldStyle.setFont(font);
550
 
551
	    CellStyle rightAlignStyle = wb.createCellStyle();
552
	    rightAlignStyle.setAlignment(CellStyle.ALIGN_RIGHT);
553
 
554
		Sheet orderSheet = wb.createSheet("Orders");
555
		Sheet mismatchSheet = wb.createSheet("Mismatches");
556
 
557
	    populateOrderSheet(orders, startDate, endDate, orderSheet, boldStyle, rightAlignStyle);
558
	    populateMismatchSheet(mismatchSheet);
559
 
560
		// Write the workbook to the output stream
561
		try {
562
			wb.write(baosXLS);
563
			baosXLS.close();
564
		} catch (IOException e) {
565
			logger.error("Unable to write the hotspot reconciliation report to the byte array", e);
566
		}		
567
		return baosXLS;
568
	}
569
 
570
	private void populateMismatchSheet(Sheet sheet)	{
571
	    int serialNo = 0;
572
		Row titleRow = sheet.createRow(serialNo ++);
573
	    Cell titleCell = titleRow.createCell(0);
574
	    titleCell.setCellValue("Order Reconciliation Report (Mis-matches)");
575
 
576
	    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
577
	    sheet.createRow(serialNo ++);
578
 
579
	    Row headerRow = sheet.createRow(serialNo ++);
580
	    headerRow.createCell(OrderMismatchColumn.ORDER_ID.getValue()).setCellValue("Order Id");
581
	    headerRow.createCell(OrderMismatchColumn.EXPECTED_COLLECTION.getValue()).setCellValue("Expected Collection");
582
	    headerRow.createCell(OrderMismatchColumn.ACTUAL_COLLECTION.getValue()).setCellValue("Actual Collection");
583
 
584
	    for (long orderId: misMatches.keySet())	{
585
	    	Row contentRow = sheet.createRow(serialNo ++);
586
	    	contentRow.createCell(OrderMismatchColumn.ORDER_ID.getValue()).setCellValue(orderId);
587
	    	contentRow.createCell(OrderMismatchColumn.EXPECTED_COLLECTION.getValue()).setCellValue(misMatches.get(orderId).get("expected"));
588
	    	contentRow.createCell(OrderMismatchColumn.ACTUAL_COLLECTION.getValue()).setCellValue(misMatches.get(orderId).get("actual"));
589
	    }
590
	}
591
 
592
	private void populateOrderSheet(List<Order> orders, Date startDate, Date endDate, Sheet sheet, CellStyle style, CellStyle rightAlignStyle) {
593
	    short serialNo = 0;
594
 
595
	    // Create the title row and put all the titles in it. Rows are 0 based.
596
	    Row titleRow = sheet.createRow(serialNo ++);
597
	    Cell titleCell = titleRow.createCell(0);
598
	    titleCell.setCellValue("Order Reconciliation Report (" + DATE_FORMAT.format(startDate) + " - " + DATE_FORMAT.format(endDate) + ")");
599
	    titleCell.setCellStyle(style);
600
 
601
	    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
602
 
603
	    sheet.createRow(serialNo ++);
604
 
605
	    Row headerRow = sheet.createRow(serialNo ++);
606
	    headerRow.createCell(OrderReportColumn.ORDER_ID.getValue()).setCellValue("Order Id");
607
	    headerRow.createCell(OrderReportColumn.ORDER_DATE.getValue()).setCellValue("Order Date");
608
	    headerRow.createCell(OrderReportColumn.BILLING_NUMBER.getValue()).setCellValue("Billing Number");
609
	    headerRow.createCell(OrderReportColumn.BILLING_DATE.getValue()).setCellValue("Billing Date");
610
	    headerRow.createCell(OrderReportColumn.DELIVERY_DATE.getValue()).setCellValue("Delivery Date");
611
	    headerRow.createCell(OrderReportColumn.SETTLEMENT_DATE.getValue()).setCellValue("Settlement Date");
612
	    headerRow.createCell(OrderReportColumn.BRAND.getValue()).setCellValue("Brand");
613
	    headerRow.createCell(OrderReportColumn.MODEL_NAME.getValue()).setCellValue("Model Name");
614
	    headerRow.createCell(OrderReportColumn.MODEL_NUMBER.getValue()).setCellValue("Model Number");
615
	    headerRow.createCell(OrderReportColumn.COLOR.getValue()).setCellValue("Color");
616
	    headerRow.createCell(OrderReportColumn.QUANTITY.getValue()).setCellValue("Quantity");
617
	    headerRow.createCell(OrderReportColumn.UNIT_TRANSFER_PRICE.getValue()).setCellValue("Unit Transfer Price");
618
	    headerRow.createCell(OrderReportColumn.UNIT_SELLING_PRICE.getValue()).setCellValue("Unit Selling Price");
619
	    headerRow.createCell(OrderReportColumn.TOTAL_TRANSFER_PRICE.getValue()).setCellValue("Total Transfer Price");
620
	    headerRow.createCell(OrderReportColumn.TOTAL_SELLING_PRICE.getValue()).setCellValue("Total Selling Price");
621
	    headerRow.createCell(OrderReportColumn.CURRENT_STATUS.getValue()).setCellValue("Current Status");
622
	    headerRow.createCell(OrderReportColumn.GATEWAY_TRANSACTION_ID.getValue()).setCellValue("Gateway Transaction Id");
623
	    headerRow.createCell(OrderReportColumn.PAYMENT_TYPE.getValue()).setCellValue("Payment Type");
624
	    headerRow.createCell(OrderReportColumn.PAYMENT_ID.getValue()).setCellValue("Payment Id");
625
	    headerRow.createCell(OrderReportColumn.COUPON_CODE.getValue()).setCellValue("Coupon Code");
626
//	    headerRow.createCell(OrderReportColumn.COUPON_CATEGORY.getValue()).setCellValue("Coupon Category");
627
//	    headerRow.createCell(OrderReportColumn.DISCOUNT.getValue()).setCellValue("Discount");
628
	    headerRow.createCell(OrderReportColumn.SERVICE_TAX.getValue()).setCellValue("Service Tax");
629
	    headerRow.createCell(OrderReportColumn.OTHER_CHARGES.getValue()).setCellValue("Other Charges");
630
	    headerRow.createCell(OrderReportColumn.NET_COLLECTION.getValue()).setCellValue("Net Collection");
631
 
632
	    sheet.createRow(serialNo ++);
633
 
634
		TransactionClient tsc;
635
    	PaymentClient psc;
636
 
637
		try {
638
			tsc = new TransactionClient();
639
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = tsc.getClient();
640
 
641
			psc = new PaymentClient();
642
	    	in.shop2020.payments.PaymentService.Client paymentClient = psc.getClient();
643
 
644
	    	List<PaymentGateway> tPaymentGateways = paymentClient.getActivePaymentGateways();
645
	    	Map<Long, String> paymentGateways = new HashMap<Long, String>();
646
 
647
	    	for (PaymentGateway tPaymentGateway: tPaymentGateways)	{
648
	    		paymentGateways.put(tPaymentGateway.getId(), tPaymentGateway.getName());
649
	    	}
650
 
651
			for(Order order : orders)	{
652
		    	Row contentRow = sheet.createRow(serialNo++);
653
 
654
			    LineItem lineItem = order.getLineitems().get(0);
655
			    double transferPrice = lineItem.getTransfer_price();
656
			    Payment payment = paymentClient.getSuccessfulPaymentForTxnId(order.getTransactionId());
657
 
658
			    Transaction txn = transactionClient.getTransaction(order.getTransactionId());
659
			    PaymentSettlement paymentSettlement = transactionClient.getSettlementForPaymentId(payment.getPaymentId());
660
 
661
	            double totalSellingPrice = lineItem.getTotal_price();
662
	            double serviceTax = paymentSettlement.getServiceTax();
663
	            double otherCollectionCharges = paymentSettlement.getOtherCharges();
664
	            double netCollection = paymentSettlement.getNetCollection();
665
 
666
	            String paymentType = paymentGateways.get(payment.getGatewayId());
667
 
668
	            if (netCollection < 0.0)	{
669
	            	paymentType = paymentType + "-REFUND";
670
	            }
671
	            double expectedCollection = totalSellingPrice - otherCollectionCharges - serviceTax;
672
 
673
	            //FIXME ignore differences of upto 50 paisa
674
	            if (netCollection > 0.0 && expectedCollection != netCollection)	{
675
	            	Map <String, Double> mismatch = new HashMap<String, Double>();
676
	            	mismatch.put("expected", expectedCollection);
677
	            	mismatch.put("actual", netCollection);
678
	            	misMatches.put(order.getId(), mismatch);
679
	            }
680
 
681
	            contentRow.createCell(OrderReportColumn.ORDER_ID.getValue()).setCellValue(order.getId());
682
	            contentRow.createCell(OrderReportColumn.ORDER_DATE.getValue()).setCellValue(DATE_FORMAT.format(new Date(order.getCreated_timestamp())));
683
			    contentRow.createCell(OrderReportColumn.BILLING_NUMBER.getValue()).setCellValue(order.getInvoice_number());
684
			    contentRow.createCell(OrderReportColumn.BILLING_DATE.getValue()).setCellValue(DATE_FORMAT.format(new Date(order.getBilling_timestamp())));
685
			    contentRow.createCell(OrderReportColumn.DELIVERY_DATE.getValue()).setCellValue(DATE_FORMAT.format(new Date(order.getDelivery_timestamp())));
686
			    contentRow.createCell(OrderReportColumn.SETTLEMENT_DATE.getValue()).setCellValue(DATE_FORMAT.format(new Date(paymentSettlement.getSettlementDate())));
687
			    contentRow.createCell(OrderReportColumn.BRAND.getValue()).setCellValue(getValueForEmptyString(lineItem.getBrand()));
688
			    contentRow.createCell(OrderReportColumn.MODEL_NAME.getValue()).setCellValue(getValueForEmptyString(lineItem.getModel_name()));
689
			    contentRow.createCell(OrderReportColumn.MODEL_NUMBER.getValue()).setCellValue(getValueForEmptyString(lineItem.getModel_number()));
690
			    contentRow.createCell(OrderReportColumn.COLOR.getValue()).setCellValue(getValueForEmptyString(lineItem.getColor()));
691
			    contentRow.createCell(OrderReportColumn.QUANTITY.getValue()).setCellValue(lineItem.getQuantity());
692
			    contentRow.createCell(OrderReportColumn.UNIT_TRANSFER_PRICE.getValue()).setCellValue(transferPrice);
693
			    contentRow.createCell(OrderReportColumn.UNIT_SELLING_PRICE.getValue()).setCellValue(lineItem.getUnit_price());
694
			    contentRow.createCell(OrderReportColumn.TOTAL_TRANSFER_PRICE.getValue()).setCellValue(transferPrice * lineItem.getQuantity());
695
			    contentRow.createCell(OrderReportColumn.TOTAL_SELLING_PRICE.getValue()).setCellValue(totalSellingPrice);
696
			    contentRow.createCell(OrderReportColumn.CURRENT_STATUS.getValue()).setCellValue(order.getStatusDescription());
697
			    contentRow.createCell(OrderReportColumn.GATEWAY_TRANSACTION_ID.getValue()).setCellValue(payment.getGatewayTxnId());
698
			    contentRow.createCell(OrderReportColumn.PAYMENT_TYPE.getValue()).setCellValue(paymentType);
699
			    contentRow.createCell(OrderReportColumn.PAYMENT_ID.getValue()).setCellValue(payment.getPaymentId());
700
			    contentRow.createCell(OrderReportColumn.COUPON_CODE.getValue()).setCellValue(txn.getCoupon_code());
701
			    contentRow.createCell(OrderReportColumn.SERVICE_TAX.getValue()).setCellValue(serviceTax);
702
			    contentRow.createCell(OrderReportColumn.OTHER_CHARGES.getValue()).setCellValue(otherCollectionCharges);
703
			    contentRow.createCell(OrderReportColumn.NET_COLLECTION.getValue()).setCellValue(netCollection);
704
		    }
705
		} catch (TTransportException e) {
706
			e.printStackTrace();
707
		} catch (PaymentException e) {
708
			e.printStackTrace();
709
		} catch (TException e) {
710
			e.printStackTrace();
711
		} catch (TransactionServiceException e) {
712
			e.printStackTrace();
713
		}
714
	}
715
 
716
	public List<Vendor> getAllVendors()	{
717
		return this.vendors;
718
	}
719
 
720
	private String getValueForEmptyString(String s){
721
		if(s==null || s.equals(""))
722
			return "-";
723
		else
724
			return s; 
725
	}
726
 
727
	private String getVendorName(long vendorId)	{
728
		for (Vendor vendor: vendors)	{
729
			if (vendor.getId() == vendorId)	return vendor.getName();
730
		}
731
		return null;
732
	}
733
 
734
	public String getReportSource()	{
735
		return reportSource;
736
	}
737
 
738
	public void setReportSource(String reportSource)	{
739
		this.reportSource = reportSource;
740
	}
741
 
742
    public File getHdfcSettlementReport() {
743
        return hdfcSettlementReport;
744
    }
745
 
746
    public void setHdfcSettlementReport(File hdfcSettlementReport) {
747
        this.hdfcSettlementReport = hdfcSettlementReport;
748
    }
749
 
750
    public File getEbsSettlementSummary()	{
751
    	return ebsSettlementSummary;
752
    }
753
 
754
    public void setEbsSettlementSummary(File ebsSettlementSummary)	{
755
    	this.ebsSettlementSummary = ebsSettlementSummary;
756
    }
757
 
758
    public File getEbsSettlementReport()	{
759
    	return ebsSettlementReport;
760
    }
761
 
762
    public void setEbsSettlementReport(File ebsSettlementReport)	{
763
    	this.ebsSettlementReport = ebsSettlementReport;
764
    }
765
 
766
    public String getBluedartSettlementDate()	{
767
    	return bluedartSettlementDate;
768
    }
769
 
770
    public void setBluedartSettlementDate(String bluedartSettlementDate)	{
771
    	this.bluedartSettlementDate = bluedartSettlementDate;
772
    }
773
 
774
    public File getBluedartSettlementReport()	{
775
    	return bluedartSettlementReport;
776
    }
777
 
778
    public void setBluedartSettlementReport(File bluedartSettlementReport)	{
779
    	this.bluedartSettlementReport = bluedartSettlementReport;
780
    }
781
 
782
	@Override
783
    public void setServletContext(ServletContext context) {
784
        this.context = context;
785
    }
786
 
787
    public String getServletContextPath() {
788
        return context.getContextPath();
789
    }
790
 
791
	@Override
792
	public void setServletResponse(HttpServletResponse response) {
793
		this.response = response;
794
	}
795
 
796
	@Override
797
	public void setServletRequest(HttpServletRequest request) {
798
		this.request = request;
799
		this.session = request.getSession();
800
	}
801
 
802
	public Map<Long, String> getEBSSettlementSummaries()	{
803
		return ebsSettlementSummaries;
804
	}
805
}