MIFOSX-2049 and fix failing test cases

This commit is contained in:
Vishwas Babu A J
2015-09-06 00:04:35 +05:30
parent 66ce3b4873
commit 8f1eb39d5d
17 changed files with 707 additions and 669 deletions
+3 -3
View File
@@ -35848,8 +35848,8 @@ Request Body:
<div class="method-description"> <div class="method-description">
<h4>List Client Charges</h4> <h4>List Client Charges</h4>
<p>The <i>list</i> capability of client charges can support <b>pagination</b> and <b>sorting</b>.</p> <p>The <i>list</i> capability of client charges supports <b>pagination</b>.</p>
<h5>Mandatory Arguments</h5> <h5>Optional Arguments</h5>
<dl class="argument-list"> <dl class="argument-list">
<dt>offset</dt> <dt>offset</dt>
<dd> <dd>
@@ -35867,7 +35867,7 @@ Request Body:
<dd> <dd>
String <span>optional</span> String <span>optional</span>
</dd> </dd>
<dd>Only returns those charges which are pending payment (neither paid or waived).</dd> <dd> Filters charges that are pending payment (neither paid or waived).</dd>
</dl> </dl>
<p>Example Requests:</p> <p>Example Requests:</p>
<div class=apiClick>clients/189/charges</div> <div class=apiClick>clients/189/charges</div>
@@ -7,6 +7,8 @@ package org.mifosplatform.integrationtests;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@@ -45,16 +47,10 @@ public class LoanDisbursementDetailsIntegrationTest {
@Before @Before
public void setup() { public void setup() {
Utils.initializeRESTAssured(); Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType( this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
ContentType.JSON).build(); this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.requestSpec this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
.header("Authorization", this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec);
"Basic "
+ Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200)
.build();
this.loanTransactionHelper = new LoanTransactionHelper(
this.requestSpec, this.responseSpec);
} }
@Test @Test
@@ -64,153 +60,119 @@ public class LoanDisbursementDetailsIntegrationTest {
String installmentAmount = "800"; String installmentAmount = "800";
String withoutInstallmentAmount = ""; String withoutInstallmentAmount = "";
String proposedAmount = "10000"; String proposedAmount = "10000";
createTranches.add(this.loanTransactionHelper.createTrancheDetail(id, createTranches.add(this.loanTransactionHelper.createTrancheDetail(id, "01 June 2015", "5000"));
"01 June 2015", "5000")); createTranches.add(this.loanTransactionHelper.createTrancheDetail(id, "01 Sep 2015", "5000"));
createTranches.add(this.loanTransactionHelper.createTrancheDetail(id,
"01 Sep 2015", "5000"));
final Integer clientID = ClientHelper.createClient(this.requestSpec, final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014");
this.responseSpec, "01 January 2014"); System.out.println(
System.out "---------------------------------CLIENT CREATED WITH ID---------------------------------------------------" + clientID);
.println("---------------------------------CLIENT CREATED WITH ID---------------------------------------------------"
+ clientID);
final Integer loanProductID = this.loanTransactionHelper final Integer loanProductID = this.loanTransactionHelper
.getLoanProductId(new LoanProductTestBuilder() .getLoanProductId(new LoanProductTestBuilder().withInterestTypeAsDecliningBalance().withMoratorium("", "")
.withInterestTypeAsDecliningBalance() .withAmortizationTypeAsEqualInstallments().withTranches(true).build(null));
.withMoratorium("", "") System.out.println("----------------------------------LOAN PRODUCT CREATED WITH ID-------------------------------------------"
.withAmortizationTypeAsEqualInstallments()
.withTranches(true).build(null));
System.out
.println("----------------------------------LOAN PRODUCT CREATED WITH ID-------------------------------------------"
+ loanProductID); + loanProductID);
final Integer loanIDWithEmi = applyForLoanApplicationWithEmiAmount( final Integer loanIDWithEmi = applyForLoanApplicationWithEmiAmount(clientID, loanProductID, proposedAmount, createTranches,
clientID, loanProductID, proposedAmount, createTranches,
installmentAmount); installmentAmount);
System.out System.out
.println("-----------------------------------LOAN CREATED WITH EMI LOANID-------------------------------------------------" .println("-----------------------------------LOAN CREATED WITH EMI LOANID-------------------------------------------------"
+ loanIDWithEmi); + loanIDWithEmi);
HashMap repaymentScheduleWithEmi = (HashMap) this.loanTransactionHelper HashMap repaymentScheduleWithEmi = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec,
.getLoanDetail(this.requestSpec, this.responseSpec,
loanIDWithEmi, "repaymentSchedule"); loanIDWithEmi, "repaymentSchedule");
ArrayList<HashMap> periods = (ArrayList<HashMap>) repaymentScheduleWithEmi ArrayList<HashMap> periods = (ArrayList<HashMap>) repaymentScheduleWithEmi.get("periods");
.get("periods");
assertEquals(periods.size(), 15); assertEquals(periods.size(), 15);
this.validateRepaymentScheduleWithEMI(periods); this.validateRepaymentScheduleWithEMI(periods);
HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan( HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanIDWithEmi);
this.requestSpec, this.responseSpec, loanIDWithEmi);
LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap);
System.out System.out.println("-----------------------------------APPROVE LOAN-----------------------------------------------------------");
.println("-----------------------------------APPROVE LOAN-----------------------------------------------------------"); loanStatusHashMap = this.loanTransactionHelper.approveLoanWithApproveAmount("01 June 2015", "01 June 2015", "10000", loanIDWithEmi,
loanStatusHashMap = this.loanTransactionHelper createTranches);
.approveLoanWithApproveAmount("01 June 2015", "01 June 2015",
"10000", loanIDWithEmi, createTranches);
LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap);
LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap);
System.out System.out.println(
.println("-----------------------------------MULTI DISBURSAL LOAN WITH EMI APPROVED SUCCESSFULLY---------------------------------------"); "-----------------------------------MULTI DISBURSAL LOAN WITH EMI APPROVED SUCCESSFULLY---------------------------------------");
final Integer loanIDWithoutEmi = applyForLoanApplicationWithEmiAmount( final Integer loanIDWithoutEmi = applyForLoanApplicationWithEmiAmount(clientID, loanProductID, proposedAmount, createTranches,
clientID, loanProductID, proposedAmount, createTranches,
withoutInstallmentAmount); withoutInstallmentAmount);
HashMap repaymentScheduleWithoutEmi = (HashMap) this.loanTransactionHelper HashMap repaymentScheduleWithoutEmi = (HashMap) this.loanTransactionHelper.getLoanDetail(this.requestSpec, this.responseSpec,
.getLoanDetail(this.requestSpec, this.responseSpec,
loanIDWithoutEmi, "repaymentSchedule"); loanIDWithoutEmi, "repaymentSchedule");
ArrayList<HashMap> periods1 = (ArrayList<HashMap>) repaymentScheduleWithEmi ArrayList<HashMap> periods1 = (ArrayList<HashMap>) repaymentScheduleWithEmi.get("periods");
.get("periods");
assertEquals(periods1.size(), 15); assertEquals(periods1.size(), 15);
System.out System.out.println(
.println("-----------------------------------LOAN CREATED WITHOUT EMI LOANID-------------------------------------------------" "-----------------------------------LOAN CREATED WITHOUT EMI LOANID-------------------------------------------------"
+ loanIDWithoutEmi); + loanIDWithoutEmi);
/* To be uncommented once issue MIFOSX-2006 is closed. */ /* To be uncommented once issue MIFOSX-2006 is closed. */
// this.validateRepaymentScheduleWithoutEMI(periods1); // this.validateRepaymentScheduleWithoutEMI(periods1);
HashMap loanStatusMap = LoanStatusChecker.getStatusOfLoan( HashMap loanStatusMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanIDWithoutEmi);
this.requestSpec, this.responseSpec, loanIDWithoutEmi);
LoanStatusChecker.verifyLoanIsPending(loanStatusMap); LoanStatusChecker.verifyLoanIsPending(loanStatusMap);
System.out System.out.println("-----------------------------------APPROVE LOAN-----------------------------------------------------------");
.println("-----------------------------------APPROVE LOAN-----------------------------------------------------------"); loanStatusHashMap = this.loanTransactionHelper.approveLoanWithApproveAmount("01 June 2015", "01 June 2015", "10000",
loanStatusHashMap = this.loanTransactionHelper loanIDWithoutEmi, createTranches);
.approveLoanWithApproveAmount("01 June 2015", "01 June 2015",
"10000", loanIDWithoutEmi, createTranches);
LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap);
LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap);
System.out System.out.println(
.println("-----------------------------------MULTI DISBURSAL LOAN WITHOUT EMI APPROVED SUCCESSFULLY---------------------------------------"); "-----------------------------------MULTI DISBURSAL LOAN WITHOUT EMI APPROVED SUCCESSFULLY---------------------------------------");
} }
private void validateRepaymentScheduleWithEMI(ArrayList<HashMap> periods) { private void validateRepaymentScheduleWithEMI(ArrayList<HashMap> periods) {
LoanDisbursementTestBuilder expectedRepaymentSchedule0 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule0 = new LoanDisbursementTestBuilder("[2015, 6, 1]", 0.0f, 0.0f, null, null,
"[2015, 6, 1]", 0.0f, 0.0f, null, null, 5000.0f, null, null, 5000.0f, null, null, null);
null);
LoanDisbursementTestBuilder expectedRepaymentSchedule1 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule1 = new LoanDisbursementTestBuilder("[2015, 7, 1]", 800f, 800.0f, 50.0f,
"[2015, 7, 1]", 800.0f, 800.0f, 50.0f, 750.0f, 4250.0f, 750.0f, 750.0f, 4250.0f, 750.0f, 750.0f, "[2015, 6, 1]");
750.0f, "[2015, 6, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule2 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule2 = new LoanDisbursementTestBuilder("[2015, 8, 1]", 800.0f, 800.0f, 42.5f,
"[2015, 8, 1]", 800.0f, 800.0f, 42.5f, 757.5f, 3492.5f, 757.5f, 757.5f, 3492.5f, 757.5f, 757.5f, "[2015, 7, 1]");
757.5f, "[2015, 7, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule3 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule3 = new LoanDisbursementTestBuilder("[2015, 9, 1]", 0.0f, 0.0f, null, null,
"[2015, 9, 1]", 0.0f, 0.0f, null, null, 5000.0f, null, null, null); 5000.0f, null, null, null);
LoanDisbursementTestBuilder expectedRepaymentSchedule4 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule4 = new LoanDisbursementTestBuilder("[2015, 9, 1]", 800.0f, 800.0f, 34.92f,
"[2015, 9, 1]", 800.0f, 800.0f, 34.92f, 765.08f, 7727.42f, 765.08f, 7727.42f, 765.08f, 765.08f, "[2015, 8, 1]");
765.08f, 765.08f, "[2015, 8, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule5 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule5 = new LoanDisbursementTestBuilder("[2015, 10, 1]", 800.0f, 800.0f, 77.27f,
"[2015, 10, 1]", 800.0f, 800.0f, 77.27f, 722.73f, 7004.69f, 722.73f, 7004.69f, 722.73f, 722.73f, "[2015, 9, 1]");
722.73f, 722.73f, "[2015, 9, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule6 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule6 = new LoanDisbursementTestBuilder("[2015, 11, 1]", 800.0f, 800.0f, 70.05f,
"[2015, 11, 1]", 800.0f, 800.0f, 70.05f, 729.95f, 6274.74f, 729.95f, 6274.74f, 729.95f, 729.95f, "[2015, 10, 1]");
729.95f, 729.95f, "[2015, 10, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule7 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule7 = new LoanDisbursementTestBuilder("[2015, 12, 1]", 800.0f, 800.0f, 62.75f,
"[2015, 12, 1]", 800.0f, 800.0f, 62.75f, 737.25f, 5537.49f, 737.25f, 5537.49f, 737.25f, 737.25f, "[2015, 11, 1]");
737.25f, 737.25f, "[2015, 11, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule8 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule8 = new LoanDisbursementTestBuilder("[2016, 1, 1]", 800.0f, 800.0f, 55.37f,
"[2016, 1, 1]", 800.0f, 800.0f, 55.37f, 744.63f, 4792.86f, 744.63f, 4792.86f, 744.63f, 744.63f, "[2015, 12, 1]");
744.63f, 744.63f, "[2015, 12, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule9 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule9 = new LoanDisbursementTestBuilder("[2016, 2, 1]", 800.0f, 800.0f, 47.93f,
"[2016, 2, 1]", 800.0f, 800.0f, 47.93f, 752.07f, 4040.79f, 752.07f, 4040.79f, 752.07f, 752.07f, "[2016, 1, 1]");
752.07f, 752.07f, "[2016, 1, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule10 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule10 = new LoanDisbursementTestBuilder("[2016, 3, 1]", 800.0f, 800.0f, 40.41f,
"[2016, 3, 1]", 800.0f, 800.0f, 40.41f, 759.59f, 3281.2f, 759.59f, 3281.2f, 759.59f, 759.59f, "[2016, 2, 1]");
759.59f, 759.59f, "[2016, 2, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule11 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule11 = new LoanDisbursementTestBuilder("[2016, 4, 1]", 800.0f, 800.0f, 32.81f,
"[2016, 4, 1]", 800.0f, 800.0f, 32.81f, 767.19f, 2514.01f, 767.19f, 2514.01f, 767.19f, 767.19f, "[2016, 3, 1]");
767.19f, 767.19f, "[2016, 3, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule12 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule12 = new LoanDisbursementTestBuilder("[2016, 5, 1]", 800.0f, 800.0f, 25.14f,
"[2016, 5, 1]", 800.0f, 800.0f, 25.14f, 774.86f, 1739.15f, 774.86f, 1739.15f, 774.86f, 774.86f, "[2016, 4, 1]");
774.86f, 774.86f, "[2016, 4, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule13 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule13 = new LoanDisbursementTestBuilder("[2016, 6, 1]", 800.0f, 800.0f, 17.39f,
"[2016, 6, 1]", 800.0f, 800.0f, 17.39f, 782.61f, 956.54f, 782.61f, 956.54f, 782.61f, 782.61f, "[2016, 5, 1]");
782.61f, 782.61f, "[2016, 5, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule14 = new LoanDisbursementTestBuilder( LoanDisbursementTestBuilder expectedRepaymentSchedule14 = new LoanDisbursementTestBuilder("[2016, 7, 1]", 966.11f, 966.11f, 9.57f,
"[2016, 7, 1]", 966.11f, 966.11f, 9.57f, 956.54f, 0.0f, 956.54f, 0.0f, 956.54f, 956.54f, "[2016, 6, 1]");
956.54f, 956.54f, "[2016, 6, 1]");
ArrayList<LoanDisbursementTestBuilder> list = new ArrayList<LoanDisbursementTestBuilder>(); ArrayList<LoanDisbursementTestBuilder> list = new ArrayList<LoanDisbursementTestBuilder>();
list.add(expectedRepaymentSchedule0); list.add(expectedRepaymentSchedule0);
@@ -234,150 +196,144 @@ public class LoanDisbursementDetailsIntegrationTest {
} }
} }
private void assertRepaymentScheduleValuesWithEMI(HashMap period, private void assertRepaymentScheduleValuesWithEMI(HashMap period, LoanDisbursementTestBuilder expectedRepaymentSchedule, int position) {
LoanDisbursementTestBuilder expectedRepaymentSchedule, int position) {
assertEquals(period.get("dueDate").toString(), assertEquals(period.get("dueDate").toString(), expectedRepaymentSchedule.getDueDate());
expectedRepaymentSchedule.getDueDate()); assertEquals(period.get("principalLoanBalanceOutstanding"), expectedRepaymentSchedule.getPrincipalLoanBalanceOutstanding());
assertEquals(period.get("principalLoanBalanceOutstanding"), System.out.println(period.get("totalOriginalDueForPeriod").toString());
expectedRepaymentSchedule.getPrincipalLoanBalanceOutstanding()); assertEquals(new Float(period.get("totalOriginalDueForPeriod").toString()),
assertEquals(period.get("totalOriginalDueForPeriod"), expectedRepaymentSchedule.getTotalOriginalDueForPeriod().floatValue(), 0.0f);
expectedRepaymentSchedule.getTotalOriginalDueForPeriod());
assertEquals(period.get("totalOutstandingForPeriod"), assertEquals(new Float(period.get("totalOutstandingForPeriod").toString()).floatValue(),
expectedRepaymentSchedule.getTotalOutstandingForPeriod()); expectedRepaymentSchedule.getTotalOutstandingForPeriod(), 0.0f);
if (position != 0 && position != 3) { if (position != 0 && position != 3) {
assertEquals(period.get("interestOutstanding"), assertEquals(new Float(period.get("interestOutstanding").toString()).floatValue(),
expectedRepaymentSchedule.getInterestOutstanding()); expectedRepaymentSchedule.getInterestOutstanding(), 0.0f);
assertEquals(period.get("principalOutstanding"), assertEquals(new Float(period.get("principalOutstanding").toString()).floatValue(),
expectedRepaymentSchedule.getPrincipalOutstanding()); expectedRepaymentSchedule.getPrincipalOutstanding(), 0.0f);
assertEquals(period.get("principalDue"), assertEquals(new Float(period.get("principalDue").toString()).floatValue(), expectedRepaymentSchedule.getPrincipalDue(), 0.0f);
expectedRepaymentSchedule.getPrincipalDue()); assertEquals(new Float(period.get("principalOriginalDue").toString()).floatValue(),
assertEquals(period.get("principalOriginalDue"), expectedRepaymentSchedule.getPrincipalOriginalDue(), 0.0f);
expectedRepaymentSchedule.getPrincipalOriginalDue()); assertEquals(period.get("fromDate").toString(), expectedRepaymentSchedule.getFromDate());
assertEquals(period.get("fromDate").toString(),
expectedRepaymentSchedule.getFromDate());
} }
} }
/* Uncomment and modify test builder values once MIFOSX-2006 is closed. */ /* Uncomment and modify test builder values once MIFOSX-2006 is closed. */
/*private void validateRepaymentScheduleWithoutEMI(ArrayList<HashMap> periods){ /*
LoanDisbursementTestBuilder expectedRepaymentSchedule0 = new LoanDisbursementTestBuilder( * private void validateRepaymentScheduleWithoutEMI(ArrayList<HashMap>
"[2015, 6, 1]", 0.0f, 0.0f, null, null, 5000.0f, null, null, * periods){ LoanDisbursementTestBuilder expectedRepaymentSchedule0 = new
null); * LoanDisbursementTestBuilder( "[2015, 6, 1]", 0.0f, 0.0f, null, null,
* 5000.0f, null, null, null);
LoanDisbursementTestBuilder expectedRepaymentSchedule1 = new LoanDisbursementTestBuilder( *
"[2015, 7, 1]", 800.0f, 800.0f, 50.0f, 750.0f, 4250.0f, 750.0f, * LoanDisbursementTestBuilder expectedRepaymentSchedule1 = new
750.0f, "[2015, 6, 1]"); * LoanDisbursementTestBuilder( "[2015, 7, 1]", 800.0f, 800.0f, 50.0f,
* 750.0f, 4250.0f, 750.0f, 750.0f, "[2015, 6, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule2 = new LoanDisbursementTestBuilder( *
"[2015, 8, 1]", 800.0f, 800.0f, 42.5f, 757.5f, 3492.5f, 757.5f, * LoanDisbursementTestBuilder expectedRepaymentSchedule2 = new
757.5f, "[2015, 7, 1]"); * LoanDisbursementTestBuilder( "[2015, 8, 1]", 800.0f, 800.0f, 42.5f,
* 757.5f, 3492.5f, 757.5f, 757.5f, "[2015, 7, 1]");
LoanDisbursementTestBuilder expectedRepaymentSchedule3 = new LoanDisbursementTestBuilder( *
"[2015, 9, 1]", 0.0f, 0.0f, null, null, 5000.0f, null, null, null); * LoanDisbursementTestBuilder expectedRepaymentSchedule3 = new
* LoanDisbursementTestBuilder( "[2015, 9, 1]", 0.0f, 0.0f, null, null,
LoanDisbursementTestBuilder expectedRepaymentSchedule4 = new LoanDisbursementTestBuilder( * 5000.0f, null, null, null);
"[2015, 9, 1]", 800.0f, 800.0f, 34.92f, 765.08f, 7727.42f, *
765.08f, 765.08f, "[2015, 8, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule4 = new
* LoanDisbursementTestBuilder( "[2015, 9, 1]", 800.0f, 800.0f, 34.92f,
LoanDisbursementTestBuilder expectedRepaymentSchedule5 = new LoanDisbursementTestBuilder( * 765.08f, 7727.42f, 765.08f, 765.08f, "[2015, 8, 1]");
"[2015, 10, 1]", 800.0f, 800.0f, 77.27f, 722.73f, 7004.69f, *
722.73f, 722.73f, "[2015, 9, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule5 = new
* LoanDisbursementTestBuilder( "[2015, 10, 1]", 800.0f, 800.0f, 77.27f,
LoanDisbursementTestBuilder expectedRepaymentSchedule6 = new LoanDisbursementTestBuilder( * 722.73f, 7004.69f, 722.73f, 722.73f, "[2015, 9, 1]");
"[2015, 11, 1]", 800.0f, 800.0f, 70.05f, 729.95f, 6274.74f, *
729.95f, 729.95f, "[2015, 10, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule6 = new
* LoanDisbursementTestBuilder( "[2015, 11, 1]", 800.0f, 800.0f, 70.05f,
LoanDisbursementTestBuilder expectedRepaymentSchedule7 = new LoanDisbursementTestBuilder( * 729.95f, 6274.74f, 729.95f, 729.95f, "[2015, 10, 1]");
"[2015, 12, 1]", 800.0f, 800.0f, 62.75f, 737.25f, 5537.49f, *
737.25f, 737.25f, "[2015, 11, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule7 = new
* LoanDisbursementTestBuilder( "[2015, 12, 1]", 800.0f, 800.0f, 62.75f,
LoanDisbursementTestBuilder expectedRepaymentSchedule8 = new LoanDisbursementTestBuilder( * 737.25f, 5537.49f, 737.25f, 737.25f, "[2015, 11, 1]");
"[2016, 1, 1]", 800.0f, 800.0f, 55.37f, 744.63f, 4792.86f, *
744.63f, 744.63f, "[2015, 12, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule8 = new
* LoanDisbursementTestBuilder( "[2016, 1, 1]", 800.0f, 800.0f, 55.37f,
LoanDisbursementTestBuilder expectedRepaymentSchedule9 = new LoanDisbursementTestBuilder( * 744.63f, 4792.86f, 744.63f, 744.63f, "[2015, 12, 1]");
"[2016, 2, 1]", 800.0f, 800.0f, 47.93f, 752.07f, 4040.79f, *
752.07f, 752.07f, "[2016, 1, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule9 = new
* LoanDisbursementTestBuilder( "[2016, 2, 1]", 800.0f, 800.0f, 47.93f,
LoanDisbursementTestBuilder expectedRepaymentSchedule10 = new LoanDisbursementTestBuilder( * 752.07f, 4040.79f, 752.07f, 752.07f, "[2016, 1, 1]");
"[2016, 3, 1]", 800.0f, 800.0f, 40.41f, 759.59f, 3281.2f, *
759.59f, 759.59f, "[2016, 2, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule10 = new
* LoanDisbursementTestBuilder( "[2016, 3, 1]", 800.0f, 800.0f, 40.41f,
LoanDisbursementTestBuilder expectedRepaymentSchedule11 = new LoanDisbursementTestBuilder( * 759.59f, 3281.2f, 759.59f, 759.59f, "[2016, 2, 1]");
"[2016, 4, 1]", 800.0f, 800.0f, 32.81f, 767.19f, 2514.01f, *
767.19f, 767.19f, "[2016, 3, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule11 = new
* LoanDisbursementTestBuilder( "[2016, 4, 1]", 800.0f, 800.0f, 32.81f,
LoanDisbursementTestBuilder expectedRepaymentSchedule12 = new LoanDisbursementTestBuilder( * 767.19f, 2514.01f, 767.19f, 767.19f, "[2016, 3, 1]");
"[2016, 5, 1]", 800.0f, 800.0f, 25.14f, 774.86f, 1739.15f, *
774.86f, 774.86f, "[2016, 4, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule12 = new
* LoanDisbursementTestBuilder( "[2016, 5, 1]", 800.0f, 800.0f, 25.14f,
LoanDisbursementTestBuilder expectedRepaymentSchedule13 = new LoanDisbursementTestBuilder( * 774.86f, 1739.15f, 774.86f, 774.86f, "[2016, 4, 1]");
"[2016, 6, 1]", 800.0f, 800.0f, 17.39f, 782.61f, 956.54f, *
782.61f, 782.61f, "[2016, 5, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule13 = new
* LoanDisbursementTestBuilder( "[2016, 6, 1]", 800.0f, 800.0f, 17.39f,
LoanDisbursementTestBuilder expectedRepaymentSchedule14 = new LoanDisbursementTestBuilder( * 782.61f, 956.54f, 782.61f, 782.61f, "[2016, 5, 1]");
"[2016, 7, 1]", 966.11f, 966.11f, 9.57f, 956.54f, 0.0f, *
956.54f, 956.54f, "[2016, 6, 1]"); * LoanDisbursementTestBuilder expectedRepaymentSchedule14 = new
* LoanDisbursementTestBuilder( "[2016, 7, 1]", 966.11f, 966.11f, 9.57f,
ArrayList<LoanDisbursementTestBuilder> list = new ArrayList<LoanDisbursementTestBuilder>(); * 956.54f, 0.0f, 956.54f, 956.54f, "[2016, 6, 1]");
list.add(expectedRepaymentSchedule0); *
list.add(expectedRepaymentSchedule1); * ArrayList<LoanDisbursementTestBuilder> list = new
list.add(expectedRepaymentSchedule2); * ArrayList<LoanDisbursementTestBuilder>();
list.add(expectedRepaymentSchedule3); * list.add(expectedRepaymentSchedule0);
list.add(expectedRepaymentSchedule4); * list.add(expectedRepaymentSchedule1);
list.add(expectedRepaymentSchedule5); * list.add(expectedRepaymentSchedule2);
list.add(expectedRepaymentSchedule6); * list.add(expectedRepaymentSchedule3);
list.add(expectedRepaymentSchedule7); * list.add(expectedRepaymentSchedule4);
list.add(expectedRepaymentSchedule8); * list.add(expectedRepaymentSchedule5);
list.add(expectedRepaymentSchedule9); * list.add(expectedRepaymentSchedule6);
list.add(expectedRepaymentSchedule10); * list.add(expectedRepaymentSchedule7);
list.add(expectedRepaymentSchedule11); * list.add(expectedRepaymentSchedule8);
list.add(expectedRepaymentSchedule12); * list.add(expectedRepaymentSchedule9);
list.add(expectedRepaymentSchedule13); * list.add(expectedRepaymentSchedule10);
list.add(expectedRepaymentSchedule14); * list.add(expectedRepaymentSchedule11);
* list.add(expectedRepaymentSchedule12);
for (int i = 0; i < list.size(); i++) { * list.add(expectedRepaymentSchedule13);
this.assertRepaymentScheduleValuesWithoutEMI(periods.get(i), list.get(i), i); * list.add(expectedRepaymentSchedule14);
} *
} * for (int i = 0; i < list.size(); i++) {
* this.assertRepaymentScheduleValuesWithoutEMI(periods.get(i), list.get(i),
private void assertRepaymentScheduleValuesWithoutEMI(HashMap period, * i); } }
LoanDisbursementTestBuilder expectedRepaymentSchedule, int position) { *
* private void assertRepaymentScheduleValuesWithoutEMI(HashMap period,
assertEquals(period.get("dueDate").toString(), * LoanDisbursementTestBuilder expectedRepaymentSchedule, int position) {
expectedRepaymentSchedule.getDueDate()); *
assertEquals(period.get("principalLoanBalanceOutstanding"), * assertEquals(period.get("dueDate").toString(),
expectedRepaymentSchedule.getPrincipalLoanBalanceOutstanding()); * expectedRepaymentSchedule.getDueDate());
assertEquals(period.get("totalOriginalDueForPeriod"), * assertEquals(period.get("principalLoanBalanceOutstanding"),
expectedRepaymentSchedule.getTotalOriginalDueForPeriod()); * expectedRepaymentSchedule.getPrincipalLoanBalanceOutstanding());
assertEquals(period.get("totalOutstandingForPeriod"), * assertEquals(period.get("totalOriginalDueForPeriod"),
expectedRepaymentSchedule.getTotalOutstandingForPeriod()); * expectedRepaymentSchedule.getTotalOriginalDueForPeriod());
* assertEquals(period.get("totalOutstandingForPeriod"),
if (position != 0 && position != 3) { * expectedRepaymentSchedule.getTotalOutstandingForPeriod());
*
assertEquals(period.get("interestOutstanding"), * if (position != 0 && position != 3) {
expectedRepaymentSchedule.getInterestOutstanding()); *
assertEquals(period.get("principalOutstanding"), * assertEquals(period.get("interestOutstanding"),
expectedRepaymentSchedule.getPrincipalOutstanding()); * expectedRepaymentSchedule.getInterestOutstanding());
assertEquals(period.get("principalDue"), * assertEquals(period.get("principalOutstanding"),
expectedRepaymentSchedule.getPrincipalDue()); * expectedRepaymentSchedule.getPrincipalOutstanding());
assertEquals(period.get("principalOriginalDue"), * assertEquals(period.get("principalDue"),
expectedRepaymentSchedule.getPrincipalOriginalDue()); * expectedRepaymentSchedule.getPrincipalDue());
assertEquals(period.get("fromDate").toString(), * assertEquals(period.get("principalOriginalDue"),
expectedRepaymentSchedule.getFromDate()); * expectedRepaymentSchedule.getPrincipalOriginalDue());
} * assertEquals(period.get("fromDate").toString(),
} * expectedRepaymentSchedule.getFromDate()); } }
*/ */
private Integer applyForLoanApplicationWithEmiAmount( private Integer applyForLoanApplicationWithEmiAmount(final Integer clientID, final Integer loanProductID, final String proposedAmount,
final Integer clientID, final Integer loanProductID, List<HashMap> tranches, final String installmentAmount) {
final String proposedAmount, List<HashMap> tranches,
final String installmentAmount) {
System.out System.out.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
final String loanApplicationJSON = new LoanApplicationTestBuilder() final String loanApplicationJSON = new LoanApplicationTestBuilder()
// //
.withPrincipal(proposedAmount) .withPrincipal(proposedAmount)
@@ -386,8 +342,7 @@ public class LoanDisbursementDetailsIntegrationTest {
// //
.withLoanTermFrequencyAsMonths() .withLoanTermFrequencyAsMonths()
// //
.withNumberOfRepayments("12").withRepaymentEveryAfter("1") .withNumberOfRepayments("12").withRepaymentEveryAfter("1").withRepaymentFrequencyTypeAsMonths() //
.withRepaymentFrequencyTypeAsMonths() //
.withInterestRatePerPeriod("1") // .withInterestRatePerPeriod("1") //
.withExpectedDisbursementDate("01 June 2015") // .withExpectedDisbursementDate("01 June 2015") //
.withTranches(tranches) // .withTranches(tranches) //
@@ -406,46 +361,33 @@ public class LoanDisbursementDetailsIntegrationTest {
List<HashMap> createTranches = new ArrayList<>(); List<HashMap> createTranches = new ArrayList<>();
String id = null; String id = null;
createTranches.add(this.loanTransactionHelper.createTrancheDetail(id, createTranches.add(this.loanTransactionHelper.createTrancheDetail(id, "01 March 2014", "1000"));
"01 March 2014", "1000"));
final Integer clientID = ClientHelper.createClient(this.requestSpec, final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2014");
this.responseSpec, "01 January 2014"); System.out.println(
System.out "---------------------------------CLIENT CREATED WITH ID---------------------------------------------------" + clientID);
.println("---------------------------------CLIENT CREATED WITH ID---------------------------------------------------"
+ clientID);
final Integer loanProductID = this.loanTransactionHelper final Integer loanProductID = this.loanTransactionHelper
.getLoanProductId(new LoanProductTestBuilder() .getLoanProductId(new LoanProductTestBuilder().withInterestTypeAsDecliningBalance().withTranches(true).build(null));
.withInterestTypeAsDecliningBalance() System.out.println("----------------------------------LOAN PRODUCT CREATED WITH ID-------------------------------------------"
.withTranches(true).build(null));
System.out
.println("----------------------------------LOAN PRODUCT CREATED WITH ID-------------------------------------------"
+ loanProductID); + loanProductID);
this.loanID = applyForLoanApplicationWithTranches(clientID, this.loanID = applyForLoanApplicationWithTranches(clientID, loanProductID, proposedAmount, createTranches);
loanProductID, proposedAmount, createTranches); System.out.println(
System.out "-----------------------------------LOAN CREATED WITH LOANID-------------------------------------------------" + loanID);
.println("-----------------------------------LOAN CREATED WITH LOANID-------------------------------------------------"
+ loanID);
HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan( HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID);
this.requestSpec, this.responseSpec, loanID);
LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap);
System.out System.out.println("-----------------------------------APPROVE LOAN-----------------------------------------------------------");
.println("-----------------------------------APPROVE LOAN-----------------------------------------------------------"); loanStatusHashMap = this.loanTransactionHelper.approveLoanWithApproveAmount(approveDate, expectedDisbursementDate, approvalAmount,
loanStatusHashMap = this.loanTransactionHelper loanID, createTranches);
.approveLoanWithApproveAmount(approveDate,
expectedDisbursementDate, approvalAmount, loanID,
createTranches);
LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap);
LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap);
System.out System.out.println(
.println("-----------------------------------MULTI DISBURSAL LOAN APPROVED SUCCESSFULLY---------------------------------------"); "-----------------------------------MULTI DISBURSAL LOAN APPROVED SUCCESSFULLY---------------------------------------");
ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper.getLoanDetail(this.requestSpec,
.getLoanDetail(this.requestSpec, this.responseSpec, this.responseSpec, this.loanID, "disbursementDetails");
this.loanID, "disbursementDetails");
this.disbursementId = (Integer) disbursementDetails.get(0).get("id"); this.disbursementId = (Integer) disbursementDetails.get(0).get("id");
this.editLoanDisbursementDetails(); this.editLoanDisbursementDetails();
} }
@@ -458,49 +400,36 @@ public class LoanDisbursementDetailsIntegrationTest {
private void addNewDisbursementDetails() { private void addNewDisbursementDetails() {
List<HashMap> addTranches = new ArrayList<>(); List<HashMap> addTranches = new ArrayList<>();
ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper.getLoanDetail(this.requestSpec,
.getLoanDetail(this.requestSpec, this.responseSpec, this.responseSpec, this.loanID, "disbursementDetails");
this.loanID, "disbursementDetails"); ArrayList expectedDisbursementDate = (ArrayList) disbursementDetails.get(0).get("expectedDisbursementDate");
ArrayList expectedDisbursementDate = (ArrayList) disbursementDetails String date = formatExpectedDisbursementDate(expectedDisbursementDate.toString());
.get(0).get("expectedDisbursementDate");
String date = formatExpectedDisbursementDate(expectedDisbursementDate
.toString());
String id = null; String id = null;
addTranches.add(this.loanTransactionHelper.createTrancheDetail( addTranches.add(this.loanTransactionHelper.createTrancheDetail(disbursementDetails.get(0).get("id").toString(), date,
disbursementDetails.get(0).get("id").toString(), date,
disbursementDetails.get(0).get("principal").toString())); disbursementDetails.get(0).get("principal").toString()));
addTranches.add(this.loanTransactionHelper.createTrancheDetail(id, addTranches.add(this.loanTransactionHelper.createTrancheDetail(id, "3 March 2014", "2000"));
"3 March 2014", "2000")); addTranches.add(this.loanTransactionHelper.createTrancheDetail(id, "4 March 2014", "500"));
addTranches.add(this.loanTransactionHelper.createTrancheDetail(id,
"4 March 2014", "500"));
/* Add disbursement detail */ /* Add disbursement detail */
this.loanTransactionHelper.addAndDeleteDisbursementDetail(this.loanID, this.loanTransactionHelper.addAndDeleteDisbursementDetail(this.loanID, this.approvalAmount, this.expectedDisbursementDate,
this.approvalAmount, this.expectedDisbursementDate,
addTranches, ""); addTranches, "");
} }
private void deleteDisbursmentDetails() { private void deleteDisbursmentDetails() {
List<HashMap> deleteTranches = new ArrayList<>(); List<HashMap> deleteTranches = new ArrayList<>();
ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper.getLoanDetail(this.requestSpec,
.getLoanDetail(this.requestSpec, this.responseSpec, this.responseSpec, this.loanID, "disbursementDetails");
this.loanID, "disbursementDetails");
/* Delete the last tranche */ /* Delete the last tranche */
for (int i = 0; i < disbursementDetails.size() - 1; i++) { for (int i = 0; i < disbursementDetails.size() - 1; i++) {
ArrayList expectedDisbursementDate = (ArrayList) disbursementDetails ArrayList expectedDisbursementDate = (ArrayList) disbursementDetails.get(i).get("expectedDisbursementDate");
.get(i).get("expectedDisbursementDate"); String disbursementDate = formatExpectedDisbursementDate(expectedDisbursementDate.toString());
String disbursementDate = formatExpectedDisbursementDate(expectedDisbursementDate deleteTranches.add(this.loanTransactionHelper.createTrancheDetail(disbursementDetails.get(i).get("id").toString(),
.toString()); disbursementDate, disbursementDetails.get(i).get("principal").toString()));
deleteTranches.add(this.loanTransactionHelper.createTrancheDetail(
disbursementDetails.get(i).get("id").toString(),
disbursementDate,
disbursementDetails.get(i).get("principal").toString()));
} }
/* Add disbursement detail */ /* Add disbursement detail */
this.loanTransactionHelper.addAndDeleteDisbursementDetail(this.loanID, this.loanTransactionHelper.addAndDeleteDisbursementDetail(this.loanID, this.approvalAmount, this.expectedDisbursementDate,
this.approvalAmount, this.expectedDisbursementDate,
deleteTranches, ""); deleteTranches, "");
} }
@@ -508,26 +437,19 @@ public class LoanDisbursementDetailsIntegrationTest {
String updatedExpectedDisbursementDate = "01 March 2014"; String updatedExpectedDisbursementDate = "01 March 2014";
String updatedPrincipal = "900"; String updatedPrincipal = "900";
/* Update */ /* Update */
this.loanTransactionHelper.editDisbursementDetail(this.loanID, this.loanTransactionHelper.editDisbursementDetail(this.loanID, this.disbursementId, this.approvalAmount,
this.disbursementId, this.approvalAmount, this.expectedDisbursementDate, updatedExpectedDisbursementDate, updatedPrincipal, "");
this.expectedDisbursementDate, updatedExpectedDisbursementDate,
updatedPrincipal, "");
/* Validate Edit */ /* Validate Edit */
ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper ArrayList<HashMap> disbursementDetails = (ArrayList<HashMap>) this.loanTransactionHelper.getLoanDetail(this.requestSpec,
.getLoanDetail(this.requestSpec, this.responseSpec, this.responseSpec, this.loanID, "disbursementDetails");
this.loanID, "disbursementDetails"); assertEquals(Float.valueOf(updatedPrincipal), disbursementDetails.get(0).get("principal"));
assertEquals(Float.valueOf(updatedPrincipal), disbursementDetails ArrayList expectedDisbursementDate = (ArrayList) disbursementDetails.get(0).get("expectedDisbursementDate");
.get(0).get("principal")); String date = formatExpectedDisbursementDate(expectedDisbursementDate.toString());
ArrayList expectedDisbursementDate = (ArrayList) disbursementDetails
.get(0).get("expectedDisbursementDate");
String date = formatExpectedDisbursementDate(expectedDisbursementDate
.toString());
assertEquals(updatedExpectedDisbursementDate, date); assertEquals(updatedExpectedDisbursementDate, date);
} }
private String formatExpectedDisbursementDate( private String formatExpectedDisbursementDate(String expectedDisbursementDate) {
String expectedDisbursementDate) {
SimpleDateFormat source = new SimpleDateFormat("[yyyy, MM, dd]"); SimpleDateFormat source = new SimpleDateFormat("[yyyy, MM, dd]");
SimpleDateFormat target = new SimpleDateFormat("dd MMMM yyyy"); SimpleDateFormat target = new SimpleDateFormat("dd MMMM yyyy");
@@ -540,11 +462,9 @@ public class LoanDisbursementDetailsIntegrationTest {
return date; return date;
} }
private Integer applyForLoanApplicationWithTranches(final Integer clientID, private Integer applyForLoanApplicationWithTranches(final Integer clientID, final Integer loanProductID, String principal,
final Integer loanProductID, String principal,
List<HashMap> tranches) { List<HashMap> tranches) {
System.out System.out.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
final String loanApplicationJSON = new LoanApplicationTestBuilder() final String loanApplicationJSON = new LoanApplicationTestBuilder()
// //
.withPrincipal(principal) .withPrincipal(principal)
@@ -553,8 +473,7 @@ public class LoanDisbursementDetailsIntegrationTest {
// //
.withLoanTermFrequencyAsMonths() .withLoanTermFrequencyAsMonths()
// //
.withNumberOfRepayments("5").withRepaymentEveryAfter("1") .withNumberOfRepayments("5").withRepaymentEveryAfter("1").withRepaymentFrequencyTypeAsMonths() //
.withRepaymentFrequencyTypeAsMonths() //
.withInterestRatePerPeriod("2") // .withInterestRatePerPeriod("2") //
.withExpectedDisbursementDate("01 March 2014") // .withExpectedDisbursementDate("01 March 2014") //
.withTranches(tranches) // .withTranches(tranches) //
@@ -74,14 +74,15 @@ public class ClientChargesTest {
final String clientChargePaidTransactionId = ClientHelper.payChargesForClients(this.requestSpec, this.responseSpec, clientId, final String clientChargePaidTransactionId = ClientHelper.payChargesForClients(this.requestSpec, this.responseSpec, clientId,
clientChargeId, ClientHelper.getPayChargeJSON("25 AUGUST 2015", "10")); clientChargeId, ClientHelper.getPayChargeJSON("25 AUGUST 2015", "10"));
Assert.assertNotNull(clientChargePaidTransactionId); Assert.assertNotNull(clientChargePaidTransactionId);
isValidOutstandingAmount(ClientHelper.getClientCharge(requestSpec, responseSpec, clientId.toString()), (float) 190.0); isValidOutstandingAmount(ClientHelper.getClientCharge(requestSpec, responseSpec, clientId.toString(), clientChargeId.toString()),
(float) 190.0);
/** /**
* Revert the paid client charge transaction by passing the * Revert the paid client charge transaction by passing the
* clientChargePaidTransactionId and ensure the same is reverted. * clientChargePaidTransactionId and ensure the same is reverted.
*/ */
final Integer undoTrxnId = ClientHelper.revertClientChargeTransaction(this.requestSpec, this.responseSpec, clientId.toString(), final Integer undoTrxnId = ClientHelper.revertClientChargeTransaction(this.requestSpec, this.responseSpec,
clientChargePaidTransactionId); clientId.toString(), clientChargePaidTransactionId);
Assert.assertNotNull(undoTrxnId); Assert.assertNotNull(undoTrxnId);
isReversedTransaction(clientId.toString(), undoTrxnId.toString()); isReversedTransaction(clientId.toString(), undoTrxnId.toString());
/** /**
@@ -103,8 +104,8 @@ public class ClientChargesTest {
* waiveOffClientChargeTransactionId and ensured the transaction is * waiveOffClientChargeTransactionId and ensured the transaction is
* reversed. * reversed.
*/ */
final Integer undoWaiveTrxnId = ClientHelper.revertClientChargeTransaction(this.requestSpec, this.responseSpec, final Integer undoWaiveTrxnId = ClientHelper.revertClientChargeTransaction(this.requestSpec, this.responseSpec, clientId.toString(),
clientId.toString(), waiveOffClientChargeTransactionId); waiveOffClientChargeTransactionId);
Assert.assertNotNull(undoWaiveTrxnId); Assert.assertNotNull(undoWaiveTrxnId);
isReversedTransaction(clientId.toString(), undoWaiveTrxnId.toString()); isReversedTransaction(clientId.toString(), undoWaiveTrxnId.toString());
/** /**
@@ -130,7 +131,8 @@ public class ClientChargesTest {
clientChargeId, ClientHelper.getPayChargeJSON("25 AUGUST 2015", "100")); clientChargeId, ClientHelper.getPayChargeJSON("25 AUGUST 2015", "100"));
Assert.assertNotNull(chargePaid_responseId); Assert.assertNotNull(chargePaid_responseId);
isValidOutstandingAmount(ClientHelper.getClientCharge(requestSpec, responseSpec, clientId.toString()), (float) 100.0); isValidOutstandingAmount(ClientHelper.getClientCharge(requestSpec, responseSpec, clientId.toString(), clientChargeId.toString()),
(float) 100.0);
} }
@@ -147,8 +149,8 @@ public class ClientChargesTest {
} }
/** /**
* Check whether the outStandingAmount is equal to expected Amount or not after * Check whether the outStandingAmount is equal to expected Amount or not
* paying or after waiving off the client charge. * after paying or after waiving off the client charge.
* *
* @param outStandingAmount * @param outStandingAmount
* @param expectedAmount * @param expectedAmount
@@ -7,7 +7,6 @@ package org.mifosplatform.integrationtests.common;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import org.mifosplatform.integrationtests.common.system.CodeHelper; import org.mifosplatform.integrationtests.common.system.CodeHelper;
@@ -57,12 +56,12 @@ public class ClientHelper {
"clientId"); "clientId");
} }
public static Integer createClientForAccountPreference(final RequestSpecification requestSpec, public static Integer createClientForAccountPreference(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final ResponseSpecification responseSpec, final Integer clientType, String jsonAttributeToGetBack) { final Integer clientType, String jsonAttributeToGetBack) {
final String activationDate = "04 March 2011"; final String activationDate = "04 March 2011";
final String officeId = "1"; final String officeId = "1";
System.out System.out.println(
.println("---------------------------------CREATING A CLIENT BASED ON ACCOUNT PREFERENCE---------------------------------------------"); "---------------------------------CREATING A CLIENT BASED ON ACCOUNT PREFERENCE---------------------------------------------");
return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL, return Utils.performServerPost(requestSpec, responseSpec, CREATE_CLIENT_URL,
getTestClientWithClientTypeAsJSON(activationDate, officeId, clientType.toString()), jsonAttributeToGetBack); getTestClientWithClientTypeAsJSON(activationDate, officeId, clientType.toString()), jsonAttributeToGetBack);
} }
@@ -305,7 +304,7 @@ public class ClientHelper {
final Integer clientId, final String request) { final Integer clientId, final String request) {
System.out.println("--------------------------------- ADD CHARGES FOR Client --------------------------------"); System.out.println("--------------------------------- ADD CHARGES FOR Client --------------------------------");
final String ADD_CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges?" + Utils.TENANT_IDENTIFIER; final String ADD_CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges?" + Utils.TENANT_IDENTIFIER;
final HashMap response = Utils.performServerPost(requestSpec, responseSpec, ADD_CHARGES_URL, request, ""); final HashMap<?, ?> response = Utils.performServerPost(requestSpec, responseSpec, ADD_CHARGES_URL, request, "");
return (Integer) response.get("resourceId"); return (Integer) response.get("resourceId");
} }
@@ -314,7 +313,7 @@ public class ClientHelper {
System.out.println("--------------------------------- PAY CHARGES FOR CLIENT --------------------------------"); System.out.println("--------------------------------- PAY CHARGES FOR CLIENT --------------------------------");
final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?command=paycharge&" final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?command=paycharge&"
+ Utils.TENANT_IDENTIFIER; + Utils.TENANT_IDENTIFIER;
final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, ""); final HashMap<?, ?> response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, "");
return response.get("transactionId") != null ? response.get("transactionId").toString() : null; return response.get("transactionId") != null ? response.get("transactionId").toString() : null;
} }
@@ -324,7 +323,7 @@ public class ClientHelper {
final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?command=waive&" final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?command=waive&"
+ Utils.TENANT_IDENTIFIER; + Utils.TENANT_IDENTIFIER;
final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, ""); final HashMap<?, ?> response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, json, "");
return response.get("transactionId").toString(); return response.get("transactionId").toString();
} }
@@ -334,17 +333,17 @@ public class ClientHelper {
final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/transactions/" + clientChargeId + "?command=undo&" final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/transactions/" + clientChargeId + "?command=undo&"
+ Utils.TENANT_IDENTIFIER; + Utils.TENANT_IDENTIFIER;
final HashMap response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, "", ""); final HashMap<?, ?> response = Utils.performServerPost(requestSpec, responseSpec, CHARGES_URL, "", "");
return (Integer) response.get("resourceId"); return (Integer) response.get("resourceId");
} }
public static Object getClientCharge(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, public static Object getClientCharge(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final String clientId) { final String clientId, final String clientChargeId) {
System.out.println("---------------------------------GET CLIENT CHARGE---------------------------------------------"); System.out.println("---------------------------------GET CLIENT CHARGE---------------------------------------------");
final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges?paid=false&" + Utils.TENANT_IDENTIFIER; final String CHARGES_URL = "/mifosng-provider/api/v1/clients/" + clientId + "/charges/" + clientChargeId + "?"
ArrayList list = Utils.performServerGet(requestSpec, responseSpec, CHARGES_URL, "amountOutstanding"); + Utils.TENANT_IDENTIFIER;
return list != null && !list.isEmpty() ? list.get(0) : null; return Utils.performServerGet(requestSpec, responseSpec, CHARGES_URL, "amountOutstanding");
} }
public static Boolean getClientTransactions(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, public static Boolean getClientTransactions(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
@@ -120,6 +120,20 @@ public final class SearchParameters {
loanId, savingsId, orphansOnly); loanId, savingsId, orphansOnly);
} }
public static SearchParameters forPagination(final Integer offset, final Integer limit) {
final Integer maxLimitAllowed = getCheckedLimit(limit);
final Long staffId = null;
final Long loanId = null;
final Long savingsId = null;
final Boolean orphansOnly = false;
final String orderBy = null;
final String sortOrder = null;
return new SearchParameters(null, null, null, null, null, null, null, offset, maxLimitAllowed, orderBy, sortOrder, staffId, null,
loanId, savingsId, orphansOnly);
}
public static SearchParameters forSavings(final String sqlSearch, final String externalId, final Integer offset, final Integer limit, public static SearchParameters forSavings(final String sqlSearch, final String externalId, final Integer offset, final Integer limit,
final String orderBy, final String sortOrder) { final String orderBy, final String sortOrder) {
@@ -171,10 +185,10 @@ public final class SearchParameters {
this.currencyCode = null; this.currencyCode = null;
} }
public SearchParameters(final String sqlSearch, final Long officeId, final String externalId, final String name, public SearchParameters(final String sqlSearch, final Long officeId, final String externalId, final String name, final String hierarchy,
final String hierarchy, final String firstname, final String lastname, final Integer offset, final Integer limit, final String firstname, final String lastname, final Integer offset, final Integer limit, final String orderBy,
final String orderBy, final String sortOrder, final Long staffId, final String accountNo, final Long loanId, final String sortOrder, final Long staffId, final String accountNo, final Long loanId, final Long savingsId,
final Long savingsId, final Boolean orphansOnly, final String currencyCode) { final Boolean orphansOnly, final String currencyCode) {
this.sqlSearch = sqlSearch; this.sqlSearch = sqlSearch;
this.officeId = officeId; this.officeId = officeId;
this.externalId = externalId; this.externalId = externalId;
@@ -33,6 +33,7 @@ import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamExc
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.core.service.Page; import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.infrastructure.core.service.SearchParameters;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.charge.data.ChargeData; import org.mifosplatform.portfolio.charge.data.ChargeData;
import org.mifosplatform.portfolio.charge.service.ChargeReadPlatformService; import org.mifosplatform.portfolio.charge.service.ChargeReadPlatformService;
@@ -89,9 +90,10 @@ public class ClientChargesApiResource {
new Object[] { ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ALL, new Object[] { ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ALL,
ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ACTIVE, ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_ACTIVE,
ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_INACTIVE }); } ClientApiConstants.CLIENT_CHARGE_QUERY_PARAM_STATUS_VALUE_INACTIVE }); }
final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit);
final Page<ClientChargeData> clientCharges = this.clientChargeReadPlatformService.retrieveClientCharges(clientId, chargeStatus, final Page<ClientChargeData> clientCharges = this.clientChargeReadPlatformService.retrieveClientCharges(clientId, chargeStatus,
pendingPayment, limit, offset); pendingPayment, searchParameters);
return this.toApiJsonSerializer.serialize(settings, clientCharges, ClientApiConstants.CLIENT_CHARGES_RESPONSE_DATA_PARAMETERS); return this.toApiJsonSerializer.serialize(settings, clientCharges, ClientApiConstants.CLIENT_CHARGES_RESPONSE_DATA_PARAMETERS);
} }
@@ -26,6 +26,7 @@ import org.mifosplatform.infrastructure.core.exception.UnrecognizedQueryParamExc
import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.mifosplatform.infrastructure.core.serialization.ApiRequestJsonSerializationSettings;
import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.mifosplatform.infrastructure.core.serialization.DefaultToApiJsonSerializer;
import org.mifosplatform.infrastructure.core.service.Page; import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.infrastructure.core.service.SearchParameters;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.client.data.ClientTransactionData; import org.mifosplatform.portfolio.client.data.ClientTransactionData;
import org.mifosplatform.portfolio.client.service.ClientTransactionReadPlatformService; import org.mifosplatform.portfolio.client.service.ClientTransactionReadPlatformService;
@@ -61,8 +62,10 @@ public class ClientTransactionsApiResource {
public String retrieveAllClientTransactions(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo, public String retrieveAllClientTransactions(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo,
@QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit) { @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit) {
this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME); this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME);
SearchParameters searchParameters = SearchParameters.forPagination(offset, limit);
final Page<ClientTransactionData> clientTransactions = this.clientTransactionReadPlatformService.retrieveAllTransactions(clientId, final Page<ClientTransactionData> clientTransactions = this.clientTransactionReadPlatformService.retrieveAllTransactions(clientId,
limit, offset); searchParameters);
final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters());
return this.toApiJsonSerializer.serialize(settings, clientTransactions, return this.toApiJsonSerializer.serialize(settings, clientTransactions,
@@ -5,6 +5,7 @@
*/ */
package org.mifosplatform.portfolio.client.domain; package org.mifosplatform.portfolio.client.domain;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.portfolio.client.exception.ClientNotActiveException; import org.mifosplatform.portfolio.client.exception.ClientNotActiveException;
import org.mifosplatform.portfolio.client.exception.ClientNotFoundException; import org.mifosplatform.portfolio.client.exception.ClientNotFoundException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@@ -20,10 +21,12 @@ import org.springframework.stereotype.Service;
public class ClientRepositoryWrapper { public class ClientRepositoryWrapper {
private final ClientRepository repository; private final ClientRepository repository;
private final PlatformSecurityContext context;
@Autowired @Autowired
public ClientRepositoryWrapper(final ClientRepository repository) { public ClientRepositoryWrapper(final ClientRepository repository, final PlatformSecurityContext context) {
this.repository = repository; this.repository = repository;
this.context = context;
} }
public Client findOneWithNotFoundDetection(final Long id) { public Client findOneWithNotFoundDetection(final Long id) {
@@ -44,9 +47,11 @@ public class ClientRepositoryWrapper {
this.repository.delete(client); this.repository.delete(client);
} }
public Client getActiveClient(Long clientId) { public Client getActiveClientInUserScope(Long clientId) {
final Client client = this.findOneWithNotFoundDetection(clientId); final Client client = this.findOneWithNotFoundDetection(clientId);
if (client.isNotActive()) { throw new ClientNotActiveException(client.getId()); } if (client.isNotActive()) { throw new ClientNotActiveException(client.getId()); }
this.context.validateAccessRights(client.getOffice().getHierarchy());
return client; return client;
} }
} }
@@ -6,12 +6,12 @@
package org.mifosplatform.portfolio.client.service; package org.mifosplatform.portfolio.client.service;
import org.mifosplatform.infrastructure.core.service.Page; import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.infrastructure.core.service.SearchParameters;
import org.mifosplatform.portfolio.client.data.ClientChargeData; import org.mifosplatform.portfolio.client.data.ClientChargeData;
public interface ClientChargeReadPlatformService { public interface ClientChargeReadPlatformService {
Page<ClientChargeData> retrieveClientCharges(Long clientId, String status, Boolean pendingPayment, SearchParameters parameters);
Page<ClientChargeData> retrieveClientCharges(Long clientId, String status, Boolean isPaid, Integer limit, Integer offset);
ClientChargeData retrieveClientCharge(Long clientId, Long clientChargeId); ClientChargeData retrieveClientCharge(Long clientId, Long clientChargeId);
@@ -16,6 +16,7 @@ import org.mifosplatform.infrastructure.core.domain.JdbcSupport;
import org.mifosplatform.infrastructure.core.service.Page; import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.infrastructure.core.service.PaginationHelper; import org.mifosplatform.infrastructure.core.service.PaginationHelper;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource; import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.infrastructure.core.service.SearchParameters;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.monetary.data.CurrencyData; import org.mifosplatform.organisation.monetary.data.CurrencyData;
import org.mifosplatform.portfolio.charge.data.ChargeData; import org.mifosplatform.portfolio.charge.data.ChargeData;
@@ -118,8 +119,8 @@ public class ClientChargeReadPlatformServiceImpl implements ClientChargeReadPlat
} }
@Override @Override
public Page<ClientChargeData> retrieveClientCharges(Long clientId, String status, Boolean pendingPayment, Integer limit, public Page<ClientChargeData> retrieveClientCharges(Long clientId, String status, Boolean pendingPayment,
Integer offset) { SearchParameters searchParameters) {
final ClientChargeMapper rm = new ClientChargeMapper(); final ClientChargeMapper rm = new ClientChargeMapper();
final StringBuilder sqlBuilder = new StringBuilder(); final StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("select SQL_CALC_FOUND_ROWS ").append(rm.schema()).append(" where cc.client_id=? "); sqlBuilder.append("select SQL_CALC_FOUND_ROWS ").append(rm.schema()).append(" where cc.client_id=? ");
@@ -133,13 +134,21 @@ public class ClientChargeReadPlatformServiceImpl implements ClientChargeReadPlat
// filter for paid charges // filter for paid charges
if (pendingPayment != null && pendingPayment) { if (pendingPayment != null && pendingPayment) {
sqlBuilder.append(" and ( cc.is_paid_derived = 0 and cc.waived = 1) "); sqlBuilder.append(" and ( cc.is_paid_derived = 0 and cc.waived = 0) ");
} else if (pendingPayment != null && !pendingPayment) { } else if (pendingPayment != null && !pendingPayment) {
sqlBuilder.append(" and (cc.is_paid_derived = 1 or cc.waived = 0) "); sqlBuilder.append(" and (cc.is_paid_derived = 1 or cc.waived = 1) ");
}
sqlBuilder.append(" order by cc.charge_time_enum ASC, cc.charge_due_date DESC, cc.is_penalty ASC ");
// apply limit and offsets
if (searchParameters.isLimited()) {
sqlBuilder.append(" limit ").append(searchParameters.getLimit());
if (searchParameters.isOffset()) {
sqlBuilder.append(" offset ").append(searchParameters.getOffset());
}
} }
sqlBuilder.append(
" order by cc.charge_time_enum ASC, cc.charge_due_date DESC, cc.is_penalty ASC " + "limit " + limit + " offset " + offset);
final String sqlCountRows = "SELECT FOUND_ROWS()"; final String sqlCountRows = "SELECT FOUND_ROWS()";
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), new Object[] { clientId }, return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), new Object[] { clientId },
this.clientChargeMapper); this.clientChargeMapper);
@@ -23,6 +23,7 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder; import org.mifosplatform.infrastructure.core.data.DataValidatorBuilder;
import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException; import org.mifosplatform.infrastructure.core.exception.PlatformApiDataValidationException;
import org.mifosplatform.infrastructure.core.exception.PlatformDataIntegrityException;
import org.mifosplatform.infrastructure.core.service.DateUtils; import org.mifosplatform.infrastructure.core.service.DateUtils;
import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext;
import org.mifosplatform.organisation.holiday.domain.HolidayRepositoryWrapper; import org.mifosplatform.organisation.holiday.domain.HolidayRepositoryWrapper;
@@ -43,12 +44,17 @@ import org.mifosplatform.portfolio.client.domain.ClientTransactionRepository;
import org.mifosplatform.portfolio.paymentdetail.domain.PaymentDetail; import org.mifosplatform.portfolio.paymentdetail.domain.PaymentDetail;
import org.mifosplatform.portfolio.paymentdetail.service.PaymentDetailWritePlatformService; import org.mifosplatform.portfolio.paymentdetail.service.PaymentDetailWritePlatformService;
import org.mifosplatform.useradministration.domain.AppUser; import org.mifosplatform.useradministration.domain.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements ClientChargeWritePlatformService { public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements ClientChargeWritePlatformService {
private final static Logger logger = LoggerFactory.getLogger(ClientChargeWritePlatformServiceJpaRepositoryImpl.class);
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final ChargeRepositoryWrapper chargeRepository; private final ChargeRepositoryWrapper chargeRepository;
private final ClientRepositoryWrapper clientRepository; private final ClientRepositoryWrapper clientRepository;
@@ -84,10 +90,10 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
@Override @Override
public CommandProcessingResult addCharge(Long clientId, JsonCommand command) { public CommandProcessingResult addCharge(Long clientId, JsonCommand command) {
try {
this.clientChargeDataValidator.validateAdd(command.json()); this.clientChargeDataValidator.validateAdd(command.json());
final Client client = clientRepository.getActiveClient(clientId); final Client client = clientRepository.getActiveClientInUserScope(clientId);
final Long chargeDefinitionId = command.longValueOfParameterNamed(ClientApiConstants.chargeIdParamName); final Long chargeDefinitionId = command.longValueOfParameterNamed(ClientApiConstants.chargeIdParamName);
final Charge charge = this.chargeRepository.findOneWithNotFoundDetection(chargeDefinitionId); final Charge charge = this.chargeRepository.findOneWithNotFoundDetection(chargeDefinitionId);
@@ -110,13 +116,18 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
.withOfficeId(clientCharge.getClient().getOffice().getId()) // .withOfficeId(clientCharge.getClient().getOffice().getId()) //
.withClientId(clientCharge.getClient().getId()) // .withClientId(clientCharge.getClient().getId()) //
.build(); .build();
} catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(clientId, null, dve);
return CommandProcessingResult.empty();
}
} }
@Override @Override
public CommandProcessingResult payCharge(Long clientId, Long clientChargeId, JsonCommand command) { public CommandProcessingResult payCharge(Long clientId, Long clientChargeId, JsonCommand command) {
try {
this.clientChargeDataValidator.validatePayCharge(command.json()); this.clientChargeDataValidator.validatePayCharge(command.json());
final Client client = this.clientRepository.getActiveClient(clientId); final Client client = this.clientRepository.getActiveClientInUserScope(clientId);
final ClientCharge clientCharge = this.clientChargeRepository.findOneWithNotFoundDetection(clientChargeId); final ClientCharge clientCharge = this.clientChargeRepository.findOneWithNotFoundDetection(clientChargeId);
@@ -152,6 +163,10 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
.withEntityId(clientCharge.getId()) // .withEntityId(clientCharge.getId()) //
.withOfficeId(clientCharge.getClient().getOffice().getId()) // .withOfficeId(clientCharge.getClient().getOffice().getId()) //
.withClientId(clientCharge.getClient().getId()).build(); .withClientId(clientCharge.getClient().getId()).build();
} catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(clientId, clientChargeId, dve);
return CommandProcessingResult.empty();
}
} }
@@ -162,7 +177,8 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
@Override @Override
public CommandProcessingResult waiveCharge(Long clientId, Long clientChargeId) { public CommandProcessingResult waiveCharge(Long clientId, Long clientChargeId) {
final Client client = this.clientRepository.getActiveClient(clientId); try {
final Client client = this.clientRepository.getActiveClientInUserScope(clientId);
final ClientCharge clientCharge = this.clientChargeRepository.findOneWithNotFoundDetection(clientChargeId); final ClientCharge clientCharge = this.clientChargeRepository.findOneWithNotFoundDetection(clientChargeId);
final LocalDate transactionDate = DateUtils.getLocalDateOfTenant(); final LocalDate transactionDate = DateUtils.getLocalDateOfTenant();
@@ -186,11 +202,16 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
.withOfficeId(clientCharge.getClient().getOffice().getId()) // .withOfficeId(clientCharge.getClient().getOffice().getId()) //
.withClientId(clientCharge.getClient().getId()) // .withClientId(clientCharge.getClient().getId()) //
.build(); .build();
} catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(clientId, clientChargeId, dve);
return CommandProcessingResult.empty();
}
} }
@Override @Override
public CommandProcessingResult deleteCharge(Long clientId, Long clientChargeId) { public CommandProcessingResult deleteCharge(Long clientId, Long clientChargeId) {
final Client client = this.clientRepository.getActiveClient(clientId); try {
final Client client = this.clientRepository.getActiveClientInUserScope(clientId);
final ClientCharge clientCharge = this.clientChargeRepository.findOneWithNotFoundDetection(clientChargeId); final ClientCharge clientCharge = this.clientChargeRepository.findOneWithNotFoundDetection(clientChargeId);
// Validate business rules for charge deletion // Validate business rules for charge deletion
@@ -204,12 +225,17 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
.withOfficeId(clientCharge.getClient().getOffice().getId()) // .withOfficeId(clientCharge.getClient().getOffice().getId()) //
.withClientId(clientCharge.getClient().getId()) // .withClientId(clientCharge.getClient().getId()) //
.build(); .build();
} catch (DataIntegrityViolationException dve) {
handleDataIntegrityIssues(clientId, clientChargeId, dve);
return CommandProcessingResult.empty();
}
} }
/** /**
* Validates transaction to ensure that <br> * Validates transaction to ensure that <br>
* charge is active <br> * charge is active <br>
* transaction date is valid (between client activation and todays date) <br> * transaction date is valid (between client activation and todays date)
* <br>
* charge is not already paid or waived <br> * charge is not already paid or waived <br>
* amount is not more than total due * amount is not more than total due
* *
@@ -304,14 +330,16 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
* @return * @return
*/ */
@Override @Override
public CommandProcessingResult updateCharge(Long clientId, JsonCommand command) { public CommandProcessingResult updateCharge(@SuppressWarnings("unused") Long clientId,
// this.clientChargeDataValidator.validateAdd(command.json()); @SuppressWarnings("unused") JsonCommand command) {
// functionality not yet supported
return null; return null;
} }
@Override @Override
@SuppressWarnings("unused")
public CommandProcessingResult inactivateCharge(Long clientId, Long clientChargeId) { public CommandProcessingResult inactivateCharge(Long clientId, Long clientChargeId) {
// TODO Auto-generated method stub // functionality not yet supported
return null; return null;
} }
@@ -378,4 +406,19 @@ public class ClientChargeWritePlatformServiceJpaRepositoryImpl implements Client
return user; return user;
} }
private void handleDataIntegrityIssues(@SuppressWarnings("unused") final Long clientId, final Long clientChargeId,
final DataIntegrityViolationException dve) {
final Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("FK_m_client_charge_paid_by_m_client_charge")) {
throw new PlatformDataIntegrityException("error.msg.client.charge.cannot.be.deleted",
"Client charge with id `" + clientChargeId + "` cannot be deleted as transactions have been made on the same",
"clientChargeId", clientChargeId); }
logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException("error.msg.client.charges.unknown.data.integrity.issue",
"Unknown data integrity issue with resource.");
}
} }
@@ -8,13 +8,14 @@ package org.mifosplatform.portfolio.client.service;
import java.util.Collection; import java.util.Collection;
import org.mifosplatform.infrastructure.core.service.Page; import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.infrastructure.core.service.SearchParameters;
import org.mifosplatform.portfolio.client.data.ClientTransactionData; import org.mifosplatform.portfolio.client.data.ClientTransactionData;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
public interface ClientTransactionReadPlatformService { public interface ClientTransactionReadPlatformService {
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Page<ClientTransactionData> retrieveAllTransactions(Long clientId, Integer limit, Integer offset); public Page<ClientTransactionData> retrieveAllTransactions(Long clientId, SearchParameters parameters);
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Collection<ClientTransactionData> retrieveAllTransactions(final Long clientId, final Long chargeId); public Collection<ClientTransactionData> retrieveAllTransactions(final Long clientId, final Long chargeId);
@@ -16,6 +16,7 @@ import org.mifosplatform.infrastructure.core.domain.JdbcSupport;
import org.mifosplatform.infrastructure.core.service.Page; import org.mifosplatform.infrastructure.core.service.Page;
import org.mifosplatform.infrastructure.core.service.PaginationHelper; import org.mifosplatform.infrastructure.core.service.PaginationHelper;
import org.mifosplatform.infrastructure.core.service.RoutingDataSource; import org.mifosplatform.infrastructure.core.service.RoutingDataSource;
import org.mifosplatform.infrastructure.core.service.SearchParameters;
import org.mifosplatform.organisation.monetary.data.CurrencyData; import org.mifosplatform.organisation.monetary.data.CurrencyData;
import org.mifosplatform.portfolio.client.data.ClientTransactionData; import org.mifosplatform.portfolio.client.data.ClientTransactionData;
import org.mifosplatform.portfolio.client.domain.ClientEnumerations; import org.mifosplatform.portfolio.client.domain.ClientEnumerations;
@@ -121,13 +122,24 @@ public class ClientTransactionReadPlatformServiceImpl implements ClientTransacti
} }
@Override @Override
public Page<ClientTransactionData> retrieveAllTransactions(Long clientId, Integer limit, Integer offset) { public Page<ClientTransactionData> retrieveAllTransactions(Long clientId, SearchParameters searchParameters) {
Object[] parameters = new Object[1]; Object[] parameters = new Object[1];
String sql = "select SQL_CALC_FOUND_ROWS " + this.clientTransactionMapper.schema() + " where c.id = ? "; final StringBuilder sqlBuilder = new StringBuilder();
sqlBuilder.append("select SQL_CALC_FOUND_ROWS ").append(this.clientTransactionMapper.schema()).append(" where c.id = ? ");
parameters[0] = clientId; parameters[0] = clientId;
final String sqlCountRows = "SELECT FOUND_ROWS()"; final String sqlCountRows = "SELECT FOUND_ROWS()";
sql = sql + " order by tr.transaction_date DESC, tr.created_date DESC, tr.id DESC limit " + limit + " offset " + offset; sqlBuilder.append(" order by tr.transaction_date DESC, tr.created_date DESC, tr.id DESC ");
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sql, parameters, this.clientTransactionMapper);
// apply limit and offsets
if (searchParameters.isLimited()) {
sqlBuilder.append(" limit ").append(searchParameters.getLimit());
if (searchParameters.isOffset()) {
sqlBuilder.append(" offset ").append(searchParameters.getOffset());
}
}
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), parameters,
this.clientTransactionMapper);
} }
@Override @Override
@@ -45,7 +45,7 @@ public class ClientTransactionWritePlatformServiceJpaRepositoryImpl implements C
@Override @Override
public CommandProcessingResult undo(Long clientId, Long transactionId) { public CommandProcessingResult undo(Long clientId, Long transactionId) {
final Client client = this.clientRepository.getActiveClient(clientId); final Client client = this.clientRepository.getActiveClientInUserScope(clientId);
final ClientTransaction clientTransaction = this.clientTransactionRepository.findOneWithNotFoundDetection(clientId, transactionId); final ClientTransaction clientTransaction = this.clientTransactionRepository.findOneWithNotFoundDetection(clientId, transactionId);
@@ -19,6 +19,7 @@ public class DisbursementData implements Comparable<DisbursementData> {
private final LocalDate expectedDisbursementDate; private final LocalDate expectedDisbursementDate;
private final LocalDate actualDisbursementDate; private final LocalDate actualDisbursementDate;
private final BigDecimal principal; private final BigDecimal principal;
@SuppressWarnings("unused")
private final String loanChargeId; private final String loanChargeId;
private final BigDecimal chargeAmount; private final BigDecimal chargeAmount;
@@ -373,6 +373,7 @@ public class SavingsAccount extends AbstractPersistable<Long> {
this.summary = new SavingsAccountSummary(); this.summary = new SavingsAccountSummary();
this.allowOverdraft = allowOverdraft; this.allowOverdraft = allowOverdraft;
this.overdraftLimit = overdraftLimit; this.overdraftLimit = overdraftLimit;
esnureOverdraftLimitsSetForOverdraftAccounts();
this.enforceMinRequiredBalance = enforceMinRequiredBalance; this.enforceMinRequiredBalance = enforceMinRequiredBalance;
this.minRequiredBalance = minRequiredBalance; this.minRequiredBalance = minRequiredBalance;
@@ -1110,8 +1111,21 @@ public class SavingsAccount extends AbstractPersistable<Long> {
} }
validateLockinDetails(baseDataValidator); validateLockinDetails(baseDataValidator);
esnureOverdraftLimitsSetForOverdraftAccounts();
} }
/**
* If overdrafts are allowed and the overdraft limit is not set, set the
* same to Zero
**/
private void esnureOverdraftLimitsSetForOverdraftAccounts() {
if (this.allowOverdraft && this.overdraftLimit == null) {
this.overdraftLimit = BigDecimal.ZERO;
}
}
private void validateLockinDetails(final DataValidatorBuilder baseDataValidator) { private void validateLockinDetails(final DataValidatorBuilder baseDataValidator) {
/* /*
@@ -236,11 +236,24 @@ public class SavingsProduct extends AbstractPersistable<Long> {
this.allowOverdraft = allowOverdraft; this.allowOverdraft = allowOverdraft;
this.overdraftLimit = overdraftLimit; this.overdraftLimit = overdraftLimit;
esnureOverdraftLimitsSetForOverdraftAccounts();
this.enforceMinRequiredBalance = enforceMinRequiredBalance; this.enforceMinRequiredBalance = enforceMinRequiredBalance;
this.minRequiredBalance = minRequiredBalance; this.minRequiredBalance = minRequiredBalance;
this.minBalanceForInterestCalculation = minBalanceForInterestCalculation; this.minBalanceForInterestCalculation = minBalanceForInterestCalculation;
} }
/**
* If overdrafts are allowed and the overdraft limit is not set, set the
* same to Zero
**/
private void esnureOverdraftLimitsSetForOverdraftAccounts() {
if (this.allowOverdraft && this.overdraftLimit() == null) {
this.overdraftLimit = BigDecimal.ZERO;
}
}
public MonetaryCurrency currency() { public MonetaryCurrency currency() {
return this.currency.copy(); return this.currency.copy();
} }
@@ -448,6 +461,7 @@ public class SavingsProduct extends AbstractPersistable<Long> {
} }
validateLockinDetails(); validateLockinDetails();
esnureOverdraftLimitsSetForOverdraftAccounts();
return actualChanges; return actualChanges;
} }