FINERACT-1971: Handling inline COB execution before batch API execution outside of the batch transaction

This commit is contained in:
Arnold Galovics
2024-02-06 16:00:17 +01:00
committed by Arnold Gálovics
parent 99352c66b2
commit 770719e8ec
11 changed files with 484 additions and 121 deletions
@@ -29,11 +29,13 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.internal.RequestSpecificationImpl;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -42,7 +44,10 @@ import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.apache.fineract.batch.domain.BatchRequest;
import org.apache.fineract.batch.domain.BatchResponse;
import org.apache.fineract.client.models.AdvancedPaymentData;
import org.apache.fineract.client.models.AllowAttributeOverrides;
import org.apache.fineract.client.models.BusinessDateRequest;
@@ -59,6 +64,7 @@ import org.apache.fineract.client.models.PostLoansLoanIdTransactionsRequest;
import org.apache.fineract.client.models.PostLoansRequest;
import org.apache.fineract.client.models.PostLoansResponse;
import org.apache.fineract.client.util.CallFailedRuntimeException;
import org.apache.fineract.integrationtests.common.BatchHelper;
import org.apache.fineract.integrationtests.common.BusinessDateHelper;
import org.apache.fineract.integrationtests.common.ClientHelper;
import org.apache.fineract.integrationtests.common.GlobalConfigurationHelper;
@@ -71,6 +77,8 @@ import org.apache.fineract.integrationtests.common.loans.LoanProductHelper;
import org.apache.fineract.integrationtests.common.loans.LoanProductTestBuilder;
import org.apache.fineract.integrationtests.common.loans.LoanTestLifecycleExtension;
import org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper;
import org.apache.fineract.integrationtests.inlinecob.InlineLoanCOBHelper;
import org.apache.fineract.integrationtests.useradministration.users.UserHelper;
import org.apache.fineract.portfolio.loanaccount.loanschedule.domain.LoanScheduleProcessingType;
import org.apache.fineract.portfolio.loanaccount.loanschedule.domain.LoanScheduleType;
import org.apache.fineract.portfolio.loanproduct.domain.PaymentAllocationType;
@@ -89,13 +97,18 @@ public abstract class BaseLoanIntegrationTest {
protected static final String DATETIME_PATTERN = "dd MMMM yyyy";
protected final ResponseSpecification responseSpec = createResponseSpecification(Matchers.is(200));
protected final RequestSpecification requestSpec = createRequestSpecification();
private final String fullAdminAuthKey = getFullAdminAuthKey();
protected final RequestSpecification requestSpec = createRequestSpecification(fullAdminAuthKey);
private final String nonByPassUserAuthKey = getNonByPassUserAuthKey(requestSpec, responseSpec);
protected final AccountHelper accountHelper = new AccountHelper(requestSpec, responseSpec);
protected final LoanTransactionHelper loanTransactionHelper = new LoanTransactionHelper(requestSpec, responseSpec);
protected final LoanProductHelper loanProductHelper = new LoanProductHelper();
protected JournalEntryHelper journalEntryHelper = new JournalEntryHelper(requestSpec, responseSpec);
protected ClientHelper clientHelper = new ClientHelper(requestSpec, responseSpec);
protected final InlineLoanCOBHelper inlineLoanCOBHelper = new InlineLoanCOBHelper(requestSpec, responseSpec);
protected BusinessDateHelper businessDateHelper = new BusinessDateHelper();
protected DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATETIME_PATTERN);
@@ -119,6 +132,16 @@ public abstract class BaseLoanIntegrationTest {
protected final Account writtenOffAccount = accountHelper.createExpenseAccount();
protected final Account goodwillExpenseAccount = accountHelper.createExpenseAccount();
private String getNonByPassUserAuthKey(RequestSpecification requestSpec, ResponseSpecification responseSpec) {
// creates the user
UserHelper.getSimpleUserWithoutBypassPermission(requestSpec, responseSpec);
return Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey(UserHelper.SIMPLE_USER_NAME, UserHelper.SIMPLE_USER_PASSWORD);
}
private String getFullAdminAuthKey() {
return Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey();
}
// Loan product with proper accounting setup
protected PostLoanProductsRequest createOnePeriod30DaysLongNoInterestPeriodicAccrualProduct() {
return new PostLoanProductsRequest().name(Utils.uniqueRandomStringGenerator("LOAN_PRODUCT_", 6))//
@@ -256,14 +279,14 @@ public abstract class BaseLoanIntegrationTest {
.amortizationType(amortizationType);
}
private static RequestSpecification createRequestSpecification() {
RequestSpecification request = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
request.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
request.header("Fineract-Platform-TenantId", "default");
return request;
private RequestSpecification createRequestSpecification(String authKey) {
RequestSpecification requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
requestSpec.header("Authorization", "Basic " + authKey);
requestSpec.header("Fineract-Platform-TenantId", "default");
return requestSpec;
}
protected static ResponseSpecification createResponseSpecification(Matcher<Integer> statusCodeMatcher) {
protected ResponseSpecification createResponseSpecification(Matcher<Integer> statusCodeMatcher) {
return new ResponseSpecBuilder().expectStatusCode(statusCodeMatcher).build();
}
@@ -317,6 +340,16 @@ public abstract class BaseLoanIntegrationTest {
}
}
protected void executeInlineCOB(Long loanId) {
inlineLoanCOBHelper.executeInlineCOB(List.of(loanId));
}
protected void verifyLastClosedBusinessDate(Long loanId, String lastClosedBusinessDate) {
GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId);
Assertions.assertNotNull(loanDetails.getLastClosedBusinessDate());
Assertions.assertEquals(lastClosedBusinessDate, loanDetails.getLastClosedBusinessDate().format(dateTimeFormatter));
}
protected void disburseLoan(Long loanId, BigDecimal amount, String date) {
loanTransactionHelper.disburseLoan(loanId, new PostLoansLoanIdRequest().actualDisbursementDate(date).dateFormat(DATETIME_PATTERN)
.transactionAmount(amount).locale("en"));
@@ -408,6 +441,16 @@ public abstract class BaseLoanIntegrationTest {
}
}
protected void runAsNonByPass(Runnable runnable) {
RequestSpecificationImpl requestSpecImpl = (RequestSpecificationImpl) requestSpec;
try {
requestSpecImpl.replaceHeader("Authorization", "Basic " + nonByPassUserAuthKey);
runnable.run();
} finally {
requestSpecImpl.replaceHeader("Authorization", "Basic " + fullAdminAuthKey);
}
}
protected PostLoansRequest applyLoanRequest(Long clientId, Long loanProductId, String loanDisbursementDate, Double amount,
int numberOfRepayments) {
return applyLoanRequest(clientId, loanProductId, loanDisbursementDate, amount, numberOfRepayments, null);
@@ -508,6 +551,69 @@ public abstract class BaseLoanIntegrationTest {
return new Installment(principalAmount, interestAmount, feeAmount, totalOutstandingAmount, completed, dueDate);
}
protected BatchRequestBuilder batchRequest() {
return new BatchRequestBuilder(requestSpec, responseSpec);
}
@RequiredArgsConstructor
public static class BatchRequestBuilder {
private final RequestSpecification requestSpec;
private final ResponseSpecification responseSpec;
private List<BatchRequest> requests = new ArrayList<>();
public BatchRequestBuilder rescheduleLoan(Long requestId, Long loanId, String submittedOnDate, String rescheduleFromDate,
String adjustedDueDate) {
BatchRequest bRequest = new BatchRequest();
bRequest.setRequestId(requestId);
bRequest.setRelativeUrl("rescheduleloans");
bRequest.setMethod("POST");
bRequest.setBody("""
{
"loanId": %d,
"rescheduleFromDate": "%s",
"rescheduleReasonId": 1,
"submittedOnDate": "%s",
"rescheduleReasonComment": "",
"adjustedDueDate": "%s",
"graceOnPrincipal": "",
"graceOnInterest": "",
"extraTerms": "",
"newInterestRate": "",
"dateFormat": "%s",
"locale": "en"
}
""".formatted(loanId, rescheduleFromDate, submittedOnDate, adjustedDueDate, DATETIME_PATTERN));
requests.add(bRequest);
return this;
}
public BatchRequestBuilder approveRescheduleLoan(Long requestId, Long rescheduleBatchRequestId, String approvedOnDate) {
BatchRequest bRequest = new BatchRequest();
bRequest.setRequestId(requestId);
bRequest.setRelativeUrl("rescheduleloans/$.resourceId?command=approve");
bRequest.setMethod("POST");
bRequest.setReference(rescheduleBatchRequestId);
bRequest.setBody("""
{
"approvedOnDate": "%s",
"dateFormat": "%s",
"locale": "en"
}
""".formatted(approvedOnDate, DATETIME_PATTERN));
requests.add(bRequest);
return this;
}
public List<BatchResponse> executeEnclosingTransaction() {
return BatchHelper.postBatchRequestsWithEnclosingTransaction(requestSpec, responseSpec, BatchHelper.toJsonString(requests));
}
}
@ToString
@AllArgsConstructor
public static class Transaction {
@@ -18,6 +18,7 @@
*/
package org.apache.fineract.integrationtests;
import static java.lang.Integer.parseInt;
import static org.apache.http.HttpStatus.SC_FORBIDDEN;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -54,6 +55,7 @@ import org.apache.fineract.integrationtests.common.CollateralManagementHelper;
import org.apache.fineract.integrationtests.common.GlobalConfigurationHelper;
import org.apache.fineract.integrationtests.common.Utils;
import org.apache.fineract.integrationtests.common.charges.ChargesHelper;
import org.apache.fineract.integrationtests.common.error.ErrorResponse;
import org.apache.fineract.integrationtests.common.loans.LoanAccountLockHelper;
import org.apache.fineract.integrationtests.common.loans.LoanProductTestBuilder;
import org.apache.fineract.integrationtests.common.loans.LoanTestLifecycleExtension;
@@ -75,14 +77,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test class for {@link org.apache.fineract.batch.command.CommandStrategyProvider}. This tests the response provided by
* commandStrategy by injecting it with a {@code BatchRequest}.
*
* @author RishabhShukla
* @see org.apache.fineract.integrationtests.common.BatchHelper
* @see org.apache.fineract.batch.domain.BatchRequest
*/
@ExtendWith(LoanTestLifecycleExtension.class)
public class BatchApiTest {
@@ -1197,8 +1191,8 @@ public class BatchApiTest {
}
/**
* Test for the successful create client, creat, approve and get loan. A '200' status code is expected on successful
* responses.
* Test for the successful create client, create, approve and get loan. A '200' status code is expected on
* successful responses.
*
* @see org.apache.fineract.batch.command.internal.CreateClientCommandStrategy
* @see org.apache.fineract.batch.command.internal.ApplyLoanCommandStrategy
@@ -2461,10 +2455,11 @@ public class BatchApiTest {
final String jsonifiedRepaymentRequest = BatchHelper.toJsonString(List.of(br));
final List<BatchResponse> repaymentResponse = BatchHelper.postBatchRequestsWithoutEnclosingTransaction(requestSpec,
this.responseSpec, jsonifiedRepaymentRequest);
Assertions.assertEquals(HttpStatus.SC_CONFLICT, repaymentResponse.get(0).getStatusCode(), "Verify Status Code 409 for Locked Loan");
// verify HTTP 409
ResponseSpecification conflictResponseSpec = new ResponseSpecBuilder().expectStatusCode(409).build();
ErrorResponse errorResponse = BatchHelper.postBatchRequestsWithoutEnclosingTransactionError(requestSpec, conflictResponseSpec,
jsonifiedRepaymentRequest);
assertEquals(409, parseInt(errorResponse.getHttpStatusCode()));
}
/**
@@ -2542,10 +2537,11 @@ public class BatchApiTest {
final String jsonifiedRepaymentRequest = BatchHelper.toJsonString(List.of(br));
final List<BatchResponse> repaymentResponse = BatchHelper.postBatchRequestsWithoutEnclosingTransaction(requestSpec,
this.responseSpec, jsonifiedRepaymentRequest);
Assertions.assertEquals(HttpStatus.SC_CONFLICT, repaymentResponse.get(0).getStatusCode(), "Verify Status Code 409 for Locked Loan");
// verify HTTP 409
ResponseSpecification conflictResponseSpec = new ResponseSpecBuilder().expectStatusCode(409).build();
ErrorResponse errorResponse = BatchHelper.postBatchRequestsWithoutEnclosingTransactionError(requestSpec, conflictResponseSpec,
jsonifiedRepaymentRequest);
assertEquals(409, parseInt(errorResponse.getHttpStatusCode()));
}
@Test
@@ -0,0 +1,101 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.integrationtests;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.fineract.batch.domain.BatchResponse;
import org.apache.fineract.client.models.PostLoanProductsRequest;
import org.apache.fineract.client.models.PostLoanProductsResponse;
import org.apache.fineract.client.models.PostLoansLoanIdResponse;
import org.apache.fineract.client.models.PostLoansRequest;
import org.apache.fineract.client.models.PostLoansResponse;
import org.apache.fineract.integrationtests.common.ClientHelper;
import org.apache.http.HttpStatus;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class BatchLoanIntegrationTest extends BaseLoanIntegrationTest {
@Test
public void test_InlineLoanCOB_ShouldExecute_WhenLoanIsBehind_And_RescheduleIsRequestedViaBatchApi() {
AtomicLong createdLoanId = new AtomicLong();
runAt("01 January 2023", () -> {
// Create Client
Long clientId = clientHelper.createClient(ClientHelper.defaultClientCreationRequest()).getClientId();
int numberOfRepayments = 24;
int repaymentEvery = 1;
// Create Loan Product
PostLoanProductsRequest product = createOnePeriod30DaysLongNoInterestPeriodicAccrualProduct() //
.numberOfRepayments(numberOfRepayments) //
.repaymentEvery(repaymentEvery) //
.repaymentFrequencyType(RepaymentFrequencyType.MONTHS.longValue()); //
PostLoanProductsResponse loanProductResponse = loanProductHelper.createLoanProduct(product);
Long loanProductId = loanProductResponse.getResourceId();
// Apply and Approve Loan
double amount = 1250.0;
PostLoansRequest applicationRequest = applyLoanRequest(clientId, loanProductId, "01 January 2023", amount, numberOfRepayments)//
.repaymentEvery(repaymentEvery)//
.loanTermFrequency(numberOfRepayments)//
.repaymentFrequencyType(RepaymentFrequencyType.MONTHS)//
.loanTermFrequencyType(RepaymentFrequencyType.MONTHS);
PostLoansResponse postLoansResponse = loanTransactionHelper.applyLoan(applicationRequest);
PostLoansLoanIdResponse approvedLoanResult = loanTransactionHelper.approveLoan(postLoansResponse.getResourceId(),
approveLoanRequest(amount, "01 January 2023"));
Long loanId = approvedLoanResult.getLoanId();
// disburse Loan
disburseLoan(loanId, BigDecimal.valueOf(1250.0), "01 January 2023");
createdLoanId.set(loanId);
});
runAt("02 January 2023", () -> {
executeInlineCOB(createdLoanId.get());
});
runAt("05 January 2023", () -> {
runAsNonByPass(() -> {
long loanId = createdLoanId.get();
List<BatchResponse> responses = batchRequest() //
.rescheduleLoan(1L, loanId, "01 January 2023", "01 February 2023", "01 March 2023") //
.approveRescheduleLoan(2L, 1L, "01 January 2023") //
.executeEnclosingTransaction(); //
Assertions.assertEquals(HttpStatus.SC_OK, responses.get(0).getStatusCode(),
"Verify Status Code 200 for Create Reschedule Loan request");
Assertions.assertEquals(HttpStatus.SC_OK, responses.get(1).getStatusCode(),
"Verify Status Code 200 for Approve Reschedule Loan request");
verifyLastClosedBusinessDate(loanId, "04 January 2023");
});
});
}
}
@@ -35,6 +35,8 @@ import java.util.stream.Collectors;
import org.apache.fineract.batch.command.internal.CreateTransactionLoanCommandStrategy;
import org.apache.fineract.batch.domain.BatchRequest;
import org.apache.fineract.batch.domain.BatchResponse;
import org.apache.fineract.client.util.JSON;
import org.apache.fineract.integrationtests.common.error.ErrorResponse;
import org.apache.fineract.integrationtests.common.savings.SavingsTransactionData;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
@@ -57,6 +59,8 @@ public final class BatchHelper {
private static final String BATCH_API_WITHOUT_ENCLOSING_URL_EXT = BATCH_API_URL + "&enclosingTransaction=false";
private static final SecureRandom secureRandom = new SecureRandom();
private static final Gson GSON = new JSON().getGson();
private BatchHelper() {
}
@@ -108,6 +112,14 @@ public final class BatchHelper {
return BatchHelper.fromJsonString(response);
}
public static ErrorResponse postBatchRequestsWithoutEnclosingTransactionError(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec, final String jsonifiedBatchRequests) {
final String response = Utils.performServerPost(requestSpec, responseSpec, BATCH_API_WITHOUT_ENCLOSING_URL_EXT,
jsonifiedBatchRequests, null);
LOG.info("BatchHelper Response {}", response);
return GSON.fromJson(response, ErrorResponse.class);
}
/**
* Returns a list of BatchResponse with query parameter enclosing transaction set to true by posting the jsonified
* BatchRequest to the server.
@@ -0,0 +1,27 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.integrationtests.common.error;
import lombok.Data;
@Data
public class ErrorResponse {
private String httpStatusCode;
}
@@ -43,8 +43,9 @@ public final class UserHelper {
private static final String REPAYMENT_LOAN_PERMISSION = "REPAYMENT_LOAN";
private static final String READ_LOAN_PERMISSION = "READ_LOAN";
private static boolean simpleUserCreated = false;
private static String simpleUsername;
public static final String SIMPLE_USER_NAME = Utils.uniqueRandomStringGenerator("NotificationUser", 4);
public static final String SIMPLE_USER_PASSWORD = "aA1qwerty56";
private static boolean SIMPLE_USER_CREATED = false;
private UserHelper() {}
@@ -141,23 +142,22 @@ public final class UserHelper {
public static RequestSpecification getSimpleUserWithoutBypassPermission(final RequestSpecification requestSpec,
final ResponseSpecification responseSpec) {
String password = "aA1qwerty56";
if (!simpleUserCreated) {
String password = SIMPLE_USER_PASSWORD;
if (!SIMPLE_USER_CREATED) {
GetOfficesResponse headOffice = OfficeHelper.getHeadOffice(requestSpec, responseSpec);
simpleUsername = Utils.uniqueRandomStringGenerator("NotificationUser", 4);
String simpleRoleId = createSimpleRole(requestSpec, responseSpec);
PostUsersRequest createUserRequest = new PostUsersRequest().username(simpleUsername)
PostUsersRequest createUserRequest = new PostUsersRequest().username(SIMPLE_USER_NAME)
.firstname(Utils.randomStringGenerator("NotificationFN", 4)).lastname(Utils.randomStringGenerator("NotificationLN", 4))
.email("whatever@mifos.org").password(password).repeatPassword(password).sendPasswordToEmail(false)
.roles(List.of(Long.valueOf(simpleRoleId))).officeId(headOffice.getId());
PostUsersResponse userCreationResponse = UserHelper.createUser(requestSpec, responseSpec, createUserRequest);
Assertions.assertNotNull(userCreationResponse.getResourceId());
simpleUserCreated = true;
SIMPLE_USER_CREATED = true;
}
RequestSpecification responseRequestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
responseRequestSpec.header("Authorization",
"Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey(simpleUsername, password));
"Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey(SIMPLE_USER_NAME, password));
return responseRequestSpec;
}
@@ -172,6 +172,10 @@ public final class UserHelper {
HashMap<String, Boolean> permissionMap = new HashMap<>();
permissionMap.put(REPAYMENT_LOAN_PERMISSION, true);
permissionMap.put(READ_LOAN_PERMISSION, true);
permissionMap.put("READ_RESCHEDULELOAN", true);
permissionMap.put("CREATE_RESCHEDULELOAN", true);
permissionMap.put("REJECT_RESCHEDULELOAN", true);
permissionMap.put("APPROVE_RESCHEDULELOAN", true);
RolesHelper.addPermissionsToRole(requestSpec, responseSpec, roleId, permissionMap);
}
}