Subversion Repositories SmartDukaan

Rev

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