From 8b89aaf4136ac2c761df545b84c69b4276eb8437 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Soma=20S=C3=B6r=C3=B6s?= Date: Mon, 26 Aug 2024 17:28:11 +0200 Subject: [PATCH] FINERACT-1981: Interest recalculation - Recalculate Interest For Loan - Business step for COB --- .../service/LoanWritePlatformService.java | 3 + .../service/RecalculateInterestPoster.java | 21 +- ...nInterestRecalculationCOBBusinessStep.java | 64 +++++ .../RecalculateInterestForLoanConfig.java | 14 +- .../RecalculateInterestForLoanTasklet.java | 64 +---- .../service/LoanReadPlatformServiceImpl.java | 5 +- ...WritePlatformServiceJpaRepositoryImpl.java | 7 + .../starter/LoanAccountConfiguration.java | 9 - .../BaseLoanIntegrationTest.java | 6 + .../LoanInterestRecalculationCOBTest.java | 261 ++++++++++++++++++ .../SchedulerJobsTestResults.java | 16 +- 11 files changed, 396 insertions(+), 74 deletions(-) create mode 100644 fineract-provider/src/main/java/org/apache/fineract/cob/loan/LoanInterestRecalculationCOBBusinessStep.java create mode 100644 integration-tests/src/test/java/org/apache/fineract/integrationtests/LoanInterestRecalculationCOBTest.java diff --git a/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java b/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java index c0490df11..4429d3579 100644 --- a/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java +++ b/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformService.java @@ -101,6 +101,9 @@ public interface LoanWritePlatformService { CommandProcessingResult updateDisbursementDateAndAmountForTranche(Long loanId, Long disbursementId, JsonCommand command); + @Transactional + Loan recalculateInterest(Loan loan); + CommandProcessingResult recoverFromGuarantor(Long loanId); void applyMeetingDateChanges(Calendar calendar, Collection loanCalendarInstances); diff --git a/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java b/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java index 396af75ee..a274a9a98 100644 --- a/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java +++ b/fineract-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/service/RecalculateInterestPoster.java @@ -22,27 +22,26 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; -import lombok.NoArgsConstructor; +import lombok.RequiredArgsConstructor; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; +import org.apache.fineract.infrastructure.core.domain.FineractContext; +import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil; import org.apache.fineract.infrastructure.jobs.exception.JobExecutionException; -@NoArgsConstructor +@RequiredArgsConstructor @Slf4j public class RecalculateInterestPoster implements Callable { + @Setter private Collection loanIds; - private LoanWritePlatformService loanWritePlatformService; - - public void setLoanIds(final Collection loanIds) { - this.loanIds = loanIds; - } - - public void setLoanWritePlatformService(final LoanWritePlatformService loanWritePlatformService) { - this.loanWritePlatformService = loanWritePlatformService; - } + @Setter + private FineractContext fineractContext; + private final LoanWritePlatformService loanWritePlatformService; @Override public Void call() throws JobExecutionException { + ThreadLocalContextUtil.init(fineractContext); if (!loanIds.isEmpty()) { List errors = new ArrayList<>(); for (Long loanId : loanIds) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/cob/loan/LoanInterestRecalculationCOBBusinessStep.java b/fineract-provider/src/main/java/org/apache/fineract/cob/loan/LoanInterestRecalculationCOBBusinessStep.java new file mode 100644 index 000000000..cc0c401f3 --- /dev/null +++ b/fineract-provider/src/main/java/org/apache/fineract/cob/loan/LoanInterestRecalculationCOBBusinessStep.java @@ -0,0 +1,64 @@ +/** + * 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.cob.loan; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.fineract.infrastructure.core.domain.ActionContext; +import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil; +import org.apache.fineract.portfolio.loanaccount.domain.Loan; +import org.apache.fineract.portfolio.loanaccount.service.LoanWritePlatformService; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class LoanInterestRecalculationCOBBusinessStep implements LoanCOBBusinessStep { + + private final LoanWritePlatformService loanWritePlatformService; + + @Override + public Loan execute(Loan loan) { + if (!loan.isInterestBearing() || !loan.getStatus().isActive() || loan.isNpa() || loan.isChargedOff() + || !loan.isInterestRecalculationEnabledForProduct()) { + log.debug("Skip processing loan interest recalculation [{}] - reason: not interest bearing loan or not active.", loan.getId()); + return loan; + } + + log.debug("Start processing loan interest recalculation [{}]", loan.getId()); + + ThreadLocalContextUtil.setActionContext(ActionContext.DEFAULT); + + loan = loanWritePlatformService.recalculateInterest(loan); + + log.debug("End processing loan interest recalculation [{}]", loan.getId()); + return loan; + } + + @Override + public String getEnumStyledName() { + return "LOAN_INTEREST_RECALCULATION"; + } + + @Override + public String getHumanReadableName() { + return "Loan Interest Recalculation"; + } + +} diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanConfig.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanConfig.java index 1a84505b1..b07942ad9 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanConfig.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanConfig.java @@ -32,8 +32,11 @@ import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.core.step.builder.StepBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; @@ -52,7 +55,7 @@ public class RecalculateInterestForLoanConfig { private LoanWritePlatformService loanWritePlatformService; @Autowired - private RecalculateInterestPoster recalculateInterestPoster; + private ApplicationContext applicationContext; @Autowired private OfficeReadPlatformService officeReadPlatformService; @@ -73,9 +76,16 @@ public class RecalculateInterestForLoanConfig { .incrementer(new RunIdIncrementer()).build(); } + @Bean + @Scope("prototype") + @ConditionalOnMissingBean(RecalculateInterestPoster.class) + public RecalculateInterestPoster recalculateInterestPoster() { + return new RecalculateInterestPoster(loanWritePlatformService); + } + @Bean public RecalculateInterestForLoanTasklet recalculateInterestForLoanTasklet() { - return new RecalculateInterestForLoanTasklet(loanReadPlatformService, loanWritePlatformService, recalculateInterestPoster, + return new RecalculateInterestForLoanTasklet(loanReadPlatformService, loanWritePlatformService, applicationContext, officeReadPlatformService, taskExecutor); } } diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanTasklet.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanTasklet.java index 5ab55574d..844a6c0b1 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanTasklet.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/jobs/recalculateinterestforloan/RecalculateInterestForLoanTasklet.java @@ -29,7 +29,9 @@ import java.util.concurrent.Future; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.ListUtils; import org.apache.fineract.infrastructure.core.config.TaskExecutorConstant; +import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil; import org.apache.fineract.infrastructure.jobs.exception.JobExecutionException; import org.apache.fineract.organisation.office.data.OfficeData; import org.apache.fineract.organisation.office.exception.OfficeNotFoundException; @@ -43,6 +45,7 @@ import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.ApplicationContext; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @Slf4j @@ -51,7 +54,7 @@ public class RecalculateInterestForLoanTasklet implements Tasklet { private final LoanReadPlatformService loanReadPlatformService; private final LoanWritePlatformService loanWritePlatformService; - private final RecalculateInterestPoster recalculateInterestPoster; + private final ApplicationContext applicationContext; private final OfficeReadPlatformService officeReadPlatformService; @Qualifier(TaskExecutorConstant.CONFIGURABLE_TASK_EXECUTOR_BEAN_NAME) private final ThreadPoolTaskExecutor taskExecutor; @@ -106,67 +109,30 @@ public class RecalculateInterestForLoanTasklet implements Tasklet { do { int totalFilteredRecords = loanIds.size(); log.debug("Starting accrual - total filtered records - {}", totalFilteredRecords); - recalculateInterest(loanIds, threadPoolSize, batchSize); + recalculateInterest(loanIds, threadPoolSize); maxLoanIdInList += pageSize + 1; loanIds = Collections.synchronizedList( this.loanReadPlatformService.fetchLoansForInterestRecalculation(pageSize, maxLoanIdInList, officeHierarchy)); } while (!CollectionUtils.isEmpty(loanIds)); } - private void recalculateInterest(List loanIds, int threadPoolSize, int batchSize) { - - List> posters = new ArrayList<>(); - int fromIndex = 0; - int size = loanIds.size(); - double toGetCeilValue = size / ((double) threadPoolSize); - batchSize = (int) Math.ceil(toGetCeilValue); - - if (batchSize == 0) { + private void recalculateInterest(List loanIds, int threadPoolSize) { + if (loanIds == null || loanIds.isEmpty()) { return; } - int toIndex = (batchSize > size - 1) ? size : batchSize; - while (toIndex < size && loanIds.get(toIndex - 1).equals(loanIds.get(toIndex))) { - toIndex++; - } - boolean lastBatch = false; - int loopCount = size / batchSize + 1; + int actualBatchSize = (int) Math.ceil(loanIds.size() / (double) threadPoolSize); - for (long i = 0; i < loopCount; i++) { - List subList = safeSubList(loanIds, fromIndex, toIndex); - recalculateInterestPoster.setLoanIds(subList); - recalculateInterestPoster.setLoanWritePlatformService(loanWritePlatformService); - posters.add(recalculateInterestPoster); - if (lastBatch) { - break; - } - if (toIndex + batchSize > size - 1) { - lastBatch = true; - } - fromIndex = fromIndex + (toIndex - fromIndex); - toIndex = (toIndex + batchSize > size - 1) ? size : toIndex + batchSize; - while (toIndex < size && loanIds.get(toIndex - 1).equals(loanIds.get(toIndex))) { - toIndex++; - } - } - - List> responses = new ArrayList<>(); - posters.forEach(poster -> responses.add(taskExecutor.submit(poster))); + List> responses = ListUtils.partition(loanIds, actualBatchSize).stream().filter(subList -> !subList.isEmpty()) + .map(subList -> { + RecalculateInterestPoster recalculateInterestPoster = applicationContext.getBean(RecalculateInterestPoster.class); + recalculateInterestPoster.setLoanIds(subList); + recalculateInterestPoster.setFineractContext(ThreadLocalContextUtil.getContext()); + return (Callable) recalculateInterestPoster; + }).map(taskExecutor::submit).toList(); checkCompletion(responses); } - private List safeSubList(List list, int fromIndex, int toIndex) { - int size = list.size(); - if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) { - return Collections.emptyList(); - } - - fromIndex = Math.max(0, fromIndex); - toIndex = Math.min(size, toIndex); - - return list.subList(fromIndex, toIndex); - } - private void checkCompletion(List> responses) { try { for (Future f : responses) { diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java index cda0e6f40..7b745a752 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java @@ -2118,7 +2118,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService, Loa sqlBuilder.append(" left join m_client mc on mc.id = ml.client_id "); sqlBuilder.append(" left join m_office o on mc.office_id = o.id "); sqlBuilder.append(" INNER JOIN m_loan_repayment_schedule mr on mr.loan_id = ml.id "); - sqlBuilder.append(" LEFT JOIN m_loan_disbursement_detail dd on dd.loan_id=ml.id and dd.disbursedon_date is null "); + sqlBuilder.append( + " LEFT JOIN m_loan_disbursement_detail dd on dd.loan_id=ml.id and dd.disbursedon_date is null and dd.is_reversed = false "); // For Floating rate changes sqlBuilder.append( " left join m_product_loan_floating_rates pfr on ml.product_id = pfr.loan_product_id and ml.is_floating_interest_rate = true"); @@ -2129,7 +2130,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService, Loa sqlBuilder.append(" left join m_floating_rates bfr on bfr.is_base_lending_rate = true"); sqlBuilder.append(" left join m_floating_rates_periods bfrp on bfr.id = bfrp.floating_rates_id and bfrp.created_date >= ?"); sqlBuilder.append(" WHERE ml.loan_status_id = ? "); - sqlBuilder.append(" and ml.is_npa = false and ml.is_charged_off = false and dd.is_reversed = false "); + sqlBuilder.append(" and ml.is_npa = false and ml.is_charged_off = false "); sqlBuilder.append(" and (("); sqlBuilder.append("ml.interest_recalculation_enabled = true "); sqlBuilder.append(" and (ml.interest_recalcualated_on is null or ml.interest_recalcualated_on <> ? )"); diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java index 8e02a793c..cc5678f6f 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java @@ -2854,6 +2854,12 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf @Retry(name = "recalculateInterest", fallbackMethod = "fallbackRecalculateInterest") public void recalculateInterest(final long loanId) { Loan loan = this.loanAssembler.assembleFrom(loanId); + recalculateInterest(loan); + } + + @Transactional + @Override + public Loan recalculateInterest(Loan loan) { LocalDate recalculateFrom = loan.fetchInterestRecalculateFromDate(); businessEventNotifierService.notifyPreBusinessEvent(new LoanInterestRecalculationBusinessEvent(loan)); final List existingTransactionIds = new ArrayList<>(); @@ -2883,6 +2889,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf loanAccrualsProcessingService.processAccrualsForInterestRecalculation(loan, loan.repaymentScheduleDetail().isInterestRecalculationEnabled()); businessEventNotifierService.notifyPostBusinessEvent(new LoanInterestRecalculationBusinessEvent(loan)); + return loan; } @Override diff --git a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/starter/LoanAccountConfiguration.java b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/starter/LoanAccountConfiguration.java index 157daff3c..d045c0917 100644 --- a/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/starter/LoanAccountConfiguration.java +++ b/fineract-provider/src/main/java/org/apache/fineract/portfolio/loanaccount/starter/LoanAccountConfiguration.java @@ -121,7 +121,6 @@ import org.apache.fineract.portfolio.loanaccount.service.LoanTransactionRelation import org.apache.fineract.portfolio.loanaccount.service.LoanUtilService; import org.apache.fineract.portfolio.loanaccount.service.LoanWritePlatformService; import org.apache.fineract.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl; -import org.apache.fineract.portfolio.loanaccount.service.RecalculateInterestPoster; import org.apache.fineract.portfolio.loanaccount.service.ReplayedTransactionBusinessEventService; import org.apache.fineract.portfolio.loanaccount.service.ReplayedTransactionBusinessEventServiceImpl; import org.apache.fineract.portfolio.loanproduct.domain.LoanProductRepository; @@ -138,7 +137,6 @@ import org.apache.fineract.portfolio.savings.service.GSIMReadPlatformService; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Scope; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; @@ -380,13 +378,6 @@ public class LoanAccountConfiguration { loanTransactionAssembler, loanAccrualsProcessingService); } - @Bean - @Scope("prototype") - @ConditionalOnMissingBean(RecalculateInterestPoster.class) - public RecalculateInterestPoster recalculateInterestPoster() { - return new RecalculateInterestPoster(); - } - @Bean @ConditionalOnMissingBean(ReplayedTransactionBusinessEventService.class) public ReplayedTransactionBusinessEventService replayedTransactionBusinessEventService( diff --git a/integration-tests/src/test/java/org/apache/fineract/integrationtests/BaseLoanIntegrationTest.java b/integration-tests/src/test/java/org/apache/fineract/integrationtests/BaseLoanIntegrationTest.java index 0228e044a..1a4e225e5 100644 --- a/integration-tests/src/test/java/org/apache/fineract/integrationtests/BaseLoanIntegrationTest.java +++ b/integration-tests/src/test/java/org/apache/fineract/integrationtests/BaseLoanIntegrationTest.java @@ -174,6 +174,12 @@ public abstract class BaseLoanIntegrationTest { assertEquals(paidLate, period.getTotalPaidLateForPeriod()); } + protected static void validateRepaymentPeriod(GetLoansLoanIdResponse loanDetails, Integer index, LocalDate dueDate, double principalDue, + double feeDue, double penaltyDue, double interestDue) { + validateRepaymentPeriod(loanDetails, index, dueDate, principalDue, 0, principalDue, feeDue, 0, feeDue, penaltyDue, 0, penaltyDue, + interestDue, 0, interestDue, 0, 0); + } + protected static void validateRepaymentPeriod(GetLoansLoanIdResponse loanDetails, Integer index, LocalDate dueDate, double principalDue, double principalPaid, double principalOutstanding, double feeDue, double feePaid, double feeOutstanding, double penaltyDue, double penaltyPaid, double penaltyOutstanding, double interestDue, double interestPaid, double interestOutstanding, diff --git a/integration-tests/src/test/java/org/apache/fineract/integrationtests/LoanInterestRecalculationCOBTest.java b/integration-tests/src/test/java/org/apache/fineract/integrationtests/LoanInterestRecalculationCOBTest.java new file mode 100644 index 000000000..dd526c11e --- /dev/null +++ b/integration-tests/src/test/java/org/apache/fineract/integrationtests/LoanInterestRecalculationCOBTest.java @@ -0,0 +1,261 @@ +/** + * 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 static org.apache.fineract.integrationtests.BaseLoanIntegrationTest.RepaymentFrequencyType.DAYS; +import static org.apache.fineract.integrationtests.BaseLoanIntegrationTest.RepaymentFrequencyType.MONTHS; + +import io.restassured.builder.RequestSpecBuilder; +import io.restassured.builder.ResponseSpecBuilder; +import io.restassured.http.ContentType; +import io.restassured.specification.RequestSpecification; +import io.restassured.specification.ResponseSpecification; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import lombok.extern.slf4j.Slf4j; +import org.apache.fineract.client.models.GetLoansLoanIdResponse; +import org.apache.fineract.client.models.PostClientsResponse; +import org.apache.fineract.client.models.PostLoanProductsResponse; +import org.apache.fineract.integrationtests.common.BusinessStepHelper; +import org.apache.fineract.integrationtests.common.ClientHelper; +import org.apache.fineract.integrationtests.common.SchedulerJobHelper; +import org.apache.fineract.integrationtests.common.Utils; +import org.apache.fineract.integrationtests.common.loans.LoanProductTestBuilder; +import org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper; +import org.apache.fineract.integrationtests.inlinecob.InlineLoanCOBHelper; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +@Slf4j +public class LoanInterestRecalculationCOBTest extends BaseLoanIntegrationTest { + + private static ResponseSpecification responseSpec; + private static RequestSpecification requestSpec; + private static LoanTransactionHelper loanTransactionHelper; + private static PostClientsResponse client; + private static InlineLoanCOBHelper inlineLoanCOBHelper; + private static BusinessStepHelper businessStepHelper; + private static SchedulerJobHelper schedulerJobHelper; + + @BeforeAll + public static void setup() { + Utils.initializeRESTAssured(); + requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + requestSpec.header("Fineract-Platform-TenantId", "default"); + responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + loanTransactionHelper = new LoanTransactionHelper(requestSpec, responseSpec); + schedulerJobHelper = new SchedulerJobHelper(requestSpec); + ClientHelper clientHelper = new ClientHelper(requestSpec, responseSpec); + client = clientHelper.createClient(ClientHelper.defaultClientCreationRequest()); + inlineLoanCOBHelper = new InlineLoanCOBHelper(requestSpec, responseSpec); + businessStepHelper = new BusinessStepHelper(); + // setup COB Business Steps to prevent test failing due other integration test configurations + businessStepHelper.updateSteps("LOAN_CLOSE_OF_BUSINESS", "APPLY_CHARGE_TO_OVERDUE_LOANS", "LOAN_DELINQUENCY_CLASSIFICATION", + "CHECK_LOAN_REPAYMENT_DUE", "CHECK_LOAN_REPAYMENT_OVERDUE", "UPDATE_LOAN_ARREARS_AGING", "ADD_PERIODIC_ACCRUAL_ENTRIES", + "EXTERNAL_ASSET_OWNER_TRANSFER", "CHECK_DUE_INSTALLMENTS", "ACCRUAL_ACTIVITY_POSTING", "LOAN_INTEREST_RECALCULATION"); + } + + @Test + public void verifyLoanInstallmentRecalculatedIfThereIsOverdueInstallmentOnProgressiveLoanCOB() { + AtomicReference loanIdRef = new AtomicReference<>(); + runAt("1 January 2023", () -> { + PostLoanProductsResponse loanProduct = loanProductHelper.createLoanProduct( + createOnePeriod30DaysPeriodicAccrualProductWithAdvancedPaymentAllocationAndInterestRecalculation(16.0, 4) + .maxInterestRatePerPeriod(120.0).maxPrincipal(10000.0)); + + Long loanId = applyAndApproveLoan(client.getClientId(), loanProduct.getResourceId(), "1 January 2023", 8000.0, 4, + postLoansRequest -> postLoansRequest.loanTermFrequency(4)// + .loanTermFrequencyType(MONTHS)// + .interestRatePerPeriod(BigDecimal.valueOf(120.0)).interestCalculationPeriodType(DAYS)// + .transactionProcessingStrategyCode(LoanProductTestBuilder.ADVANCED_PAYMENT_ALLOCATION_STRATEGY)// + .repaymentEvery(1)// + .repaymentFrequencyType(MONTHS)// + .principal(BigDecimal.valueOf(8000.0)).maxOutstandingLoanBalance(BigDecimal.valueOf(100000.0))); + loanIdRef.set(loanId); + + disburseLoan(loanId, BigDecimal.valueOf(8000), "1 January 2023"); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + loanDetails.getRepaymentSchedule().getPeriods().forEach(p -> log.info("validateRepaymentPeriod before: {} {} {}", p.getPeriod(), + p.getPrincipalOriginalDue(), p.getInterestOriginalDue()));// + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 1700.66, 0.0, 0.0, 815.34); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 1936.12, 0.0, 0.0, 579.88); + validateRepaymentPeriod(loanDetails, 3, LocalDate.of(2023, 4, 1), 2071.31, 0.0, 0.0, 444.69); + validateRepaymentPeriod(loanDetails, 4, LocalDate.of(2023, 5, 1), 2291.91, 0.0, 0.0, 226.05); + }); + runAt("2 March 2023", () -> { + Long loanId = loanIdRef.get(); + + inlineLoanCOBHelper.executeInlineCOB(List.of(loanId)); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + loanDetails.getRepaymentSchedule().getPeriods().forEach(p -> log.info("validateRepaymentPeriod after: {} {} {}", p.getPeriod(), + p.getPrincipalOriginalDue(), p.getInterestOriginalDue()));// + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 1700.66, 0.0, 0.0, 815.34); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 1936.12, 0.0, 0.0, 579.88); + validateRepaymentPeriod(loanDetails, 3, LocalDate.of(2023, 4, 1), 2071.31, 0.0, 0.0, 444.69); + validateRepaymentPeriod(loanDetails, 4, LocalDate.of(2023, 5, 1), 2291.91, 0.0, 0.0, 226.05); + }); + + } + + @Test + public void verifyLoanInstallmentRecalculatedIfThereIsOverdueInstallmentOnCumulativeLoanCOBStep() { + AtomicReference loanIdRef = new AtomicReference<>(); + runAt("1 January 2023", () -> { + PostLoanProductsResponse loanProduct = loanProductHelper.createLoanProduct(createOnePeriod30DaysPeriodicAccrualProduct(10.0) + .isInterestRecalculationEnabled(true)// + .maxPrincipal(10000.0).minNumberOfRepayments(1).rescheduleStrategyMethod(1).recalculationRestFrequencyType(MONTHS) + .recalculationRestFrequencyInterval(1).recalculationCompoundingFrequencyType(MONTHS) + .recalculationCompoundingFrequencyInterval(30).interestRecalculationCompoundingMethod(1)); + + Long loanId = applyAndApproveLoan(client.getClientId(), loanProduct.getResourceId(), "1 January 2023", 8000.0, 2, + postLoansRequest -> postLoansRequest.loanTermFrequency(2)// + .loanTermFrequencyType(MONTHS)// + .interestRatePerPeriod(BigDecimal.valueOf(10.0)).interestCalculationPeriodType(DAYS)// + .repaymentEvery(1)// + .repaymentFrequencyType(MONTHS)// + .principal(BigDecimal.valueOf(8000.0)).maxOutstandingLoanBalance(BigDecimal.valueOf(100000.0))); + loanIdRef.set(loanId); + + disburseLoan(loanId, BigDecimal.valueOf(8000), "1 January 2023"); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 3783.06, 0.0, 3783.06, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 817.94, + 0.0, 817.94, 0.0, 0.0); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 4216.94, 0.0, 4216.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 385.53, + 0.0, 385.53, 0.0, 0.0); + }); + runAt("2 February 2023", () -> { + Long loanId = loanIdRef.get(); + + inlineLoanCOBHelper.executeInlineCOB(List.of(loanId)); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 3783.06, 0.0, 3783.06, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 817.94, + 0.0, 817.94, 0.0, 0.0); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 4216.94, 0.0, 4216.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 403.23, + 0.0, 403.23, 0.0, 0.0); + }); + + } + + @Test + public void verifyLoanInstallmentRecalculatedIfThereIsOverdueInstallmentOnProgressiveLoanJob() { + AtomicReference loanIdRef = new AtomicReference<>(); + runAt("1 January 2023", () -> { + PostLoanProductsResponse loanProduct = loanProductHelper.createLoanProduct( + createOnePeriod30DaysPeriodicAccrualProductWithAdvancedPaymentAllocationAndInterestRecalculation(16.0, 4) + .maxInterestRatePerPeriod(120.0).maxPrincipal(10000.0)); + + Long loanId = applyAndApproveLoan(client.getClientId(), loanProduct.getResourceId(), "1 January 2023", 8000.0, 4, + postLoansRequest -> postLoansRequest.loanTermFrequency(4)// + .loanTermFrequencyType(MONTHS)// + .interestRatePerPeriod(BigDecimal.valueOf(120.0)).interestCalculationPeriodType(DAYS)// + .transactionProcessingStrategyCode(LoanProductTestBuilder.ADVANCED_PAYMENT_ALLOCATION_STRATEGY)// + .repaymentEvery(1)// + .repaymentFrequencyType(MONTHS)// + .principal(BigDecimal.valueOf(8000.0)).maxOutstandingLoanBalance(BigDecimal.valueOf(100000.0))); + loanIdRef.set(loanId); + + disburseLoan(loanId, BigDecimal.valueOf(8000), "1 January 2023"); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + loanDetails.getRepaymentSchedule().getPeriods().forEach(p -> log.info("validateRepaymentPeriod before: {} {} {}", p.getPeriod(), + p.getPrincipalOriginalDue(), p.getInterestOriginalDue()));// + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 1700.66, 0.0, 0.0, 815.34); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 1936.12, 0.0, 0.0, 579.88); + validateRepaymentPeriod(loanDetails, 3, LocalDate.of(2023, 4, 1), 2071.31, 0.0, 0.0, 444.69); + validateRepaymentPeriod(loanDetails, 4, LocalDate.of(2023, 5, 1), 2291.91, 0.0, 0.0, 226.05); + }); + runAt("2 March 2023", () -> { + Long loanId = loanIdRef.get(); + + schedulerJobHelper.executeAndAwaitJob("Update Loan Arrears Ageing"); + schedulerJobHelper.executeAndAwaitJob("Recalculate Interest For Loans"); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + loanDetails.getRepaymentSchedule().getPeriods().forEach(p -> log.info("validateRepaymentPeriod after: {} {} {}", p.getPeriod(), + p.getPrincipalOriginalDue(), p.getInterestOriginalDue()));// + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 1700.66, 0.0, 0.0, 815.34); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 1936.12, 0.0, 0.0, 579.88); + validateRepaymentPeriod(loanDetails, 3, LocalDate.of(2023, 4, 1), 2071.31, 0.0, 0.0, 444.69); + validateRepaymentPeriod(loanDetails, 4, LocalDate.of(2023, 5, 1), 2291.91, 0.0, 0.0, 226.05); + }); + + } + + @Test + public void verifyLoanInstallmentRecalculatedIfThereIsOverdueInstallmentOnCumulativeLoanJob() { + AtomicReference loanIdRef = new AtomicReference<>(); + runAt("1 January 2023", () -> { + PostLoanProductsResponse loanProduct = loanProductHelper.createLoanProduct(createOnePeriod30DaysPeriodicAccrualProduct(10.0) + .isInterestRecalculationEnabled(true)// + .maxPrincipal(10000.0).minNumberOfRepayments(1).rescheduleStrategyMethod(1).recalculationRestFrequencyType(MONTHS) + .recalculationRestFrequencyInterval(1).recalculationCompoundingFrequencyType(MONTHS) + .recalculationCompoundingFrequencyInterval(30).interestRecalculationCompoundingMethod(1)); + + Long loanId = applyAndApproveLoan(client.getClientId(), loanProduct.getResourceId(), "1 January 2023", 8000.0, 2, + postLoansRequest -> postLoansRequest.loanTermFrequency(2)// + .loanTermFrequencyType(MONTHS)// + .interestRatePerPeriod(BigDecimal.valueOf(10.0)).interestCalculationPeriodType(DAYS)// + .repaymentEvery(1)// + .repaymentFrequencyType(MONTHS)// + .principal(BigDecimal.valueOf(8000.0)).maxOutstandingLoanBalance(BigDecimal.valueOf(100000.0))); + loanIdRef.set(loanId); + + disburseLoan(loanId, BigDecimal.valueOf(8000), "1 January 2023"); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 3783.06, 0.0, 3783.06, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 817.94, + 0.0, 817.94, 0.0, 0.0); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 4216.94, 0.0, 4216.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 385.53, + 0.0, 385.53, 0.0, 0.0); + }); + runAt("2 February 2023", () -> { + Long loanId = loanIdRef.get(); + + schedulerJobHelper.executeAndAwaitJob("Update Loan Arrears Ageing"); + schedulerJobHelper.executeAndAwaitJob("Recalculate Interest For Loans"); + + GetLoansLoanIdResponse loanDetails = loanTransactionHelper.getLoanDetails(loanId); + + validateRepaymentPeriod(loanDetails, 1, LocalDate.of(2023, 2, 1), 3783.06, 0.0, 3783.06, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 817.94, + 0.0, 817.94, 0.0, 0.0); + validateRepaymentPeriod(loanDetails, 2, LocalDate.of(2023, 3, 1), 4216.94, 0.0, 4216.94, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 403.23, + 0.0, 403.23, 0.0, 0.0); + }); + + } + +} diff --git a/integration-tests/src/test/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java b/integration-tests/src/test/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java index 797baefe0..89f92d32d 100644 --- a/integration-tests/src/test/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java +++ b/integration-tests/src/test/java/org/apache/fineract/integrationtests/SchedulerJobsTestResults.java @@ -59,6 +59,7 @@ import org.apache.fineract.client.models.PostLoansLoanIdTransactionsRequest; import org.apache.fineract.client.models.PutJobsJobIDRequest; import org.apache.fineract.infrastructure.businessdate.domain.BusinessDateType; import org.apache.fineract.integrationtests.common.BusinessDateHelper; +import org.apache.fineract.integrationtests.common.BusinessStepHelper; import org.apache.fineract.integrationtests.common.ClientHelper; import org.apache.fineract.integrationtests.common.CollateralManagementHelper; import org.apache.fineract.integrationtests.common.GlobalConfigurationHelper; @@ -86,6 +87,7 @@ import org.apache.fineract.portfolio.account.PortfolioAccountType; import org.apache.fineract.portfolio.account.domain.AccountTransferType; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.MethodOrderer.MethodName; import org.junit.jupiter.api.Order; @@ -121,6 +123,16 @@ public class SchedulerJobsTestResults { private TimeZone systemTimeZone; private DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder().appendPattern("dd MMMM yyyy").toFormatter(); private BusinessDateHelper businessDateHelper; + private static BusinessStepHelper businessStepHelper; + + @BeforeAll + public static void beforeAll() { + businessStepHelper = new BusinessStepHelper(); + // setup COB Business Steps to prevent test failing due other integration test configurations + businessStepHelper.updateSteps("LOAN_CLOSE_OF_BUSINESS", "APPLY_CHARGE_TO_OVERDUE_LOANS", "LOAN_DELINQUENCY_CLASSIFICATION", + "CHECK_LOAN_REPAYMENT_DUE", "CHECK_LOAN_REPAYMENT_OVERDUE", "UPDATE_LOAN_ARREARS_AGING", "ADD_PERIODIC_ACCRUAL_ENTRIES", + "EXTERNAL_ASSET_OWNER_TRANSFER", "CHECK_DUE_INSTALLMENTS", "ACCRUAL_ACTIVITY_POSTING", "LOAN_INTEREST_RECALCULATION"); + } @BeforeEach public void setup() { @@ -1380,7 +1392,9 @@ public class SchedulerJobsTestResults { this.loanTransactionHelper.addChargesForLoan(loanId, LoanTransactionHelper .getSpecifiedDueDateChargesForLoanAsJSON(String.valueOf(penalty), penaltyCharge1AddedDate, "10", null)); - this.schedulerJobHelper.updateSchedulerJob(16L, new PutJobsJobIDRequest().cronExpression("0/5 * * * * ?")); + + this.schedulerJobHelper.updateSchedulerStatus(true); + this.schedulerJobHelper.updateSchedulerJob(16L, new PutJobsJobIDRequest().active(true).cronExpression("0/5 * * * * ?")); Thread.sleep(11000); GetLoansLoanIdResponse loanDetails = this.loanTransactionHelper.getLoanDetails((long) loanId);