Skip to content

Commit

Permalink
[FINERACT-1992] Delinquency calculation with pause
Browse files Browse the repository at this point in the history
  • Loading branch information
taskain7 committed Dec 5, 2023
1 parent 977fb20 commit cb40f23
Show file tree
Hide file tree
Showing 22 changed files with 1,005 additions and 196 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,22 @@

import static org.apache.fineract.infrastructure.core.diagnostics.performance.MeasuringUtil.measure;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.infrastructure.businessdate.domain.BusinessDateType;
import org.apache.fineract.infrastructure.core.domain.ActionContext;
import org.apache.fineract.infrastructure.core.domain.ExternalId;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil;
import org.apache.fineract.infrastructure.event.business.domain.loan.LoanDelinquencyRangeChangeBusinessEvent;
import org.apache.fineract.infrastructure.event.business.service.BusinessEventNotifierService;
import org.apache.fineract.portfolio.delinquency.domain.LoanDelinquencyAction;
import org.apache.fineract.portfolio.delinquency.helper.DelinquencyEffectivePauseHelper;
import org.apache.fineract.portfolio.delinquency.service.DelinquencyReadPlatformService;
import org.apache.fineract.portfolio.delinquency.validator.LoanDelinquencyActionData;
import org.apache.fineract.portfolio.loanaccount.domain.Loan;
import org.apache.fineract.portfolio.loanaccount.domain.LoanAccountDomainService;
import org.springframework.stereotype.Component;
Expand All @@ -37,6 +46,9 @@
public class SetLoanDelinquencyTagsBusinessStep implements LoanCOBBusinessStep {

private final LoanAccountDomainService loanAccountDomainService;
private final DelinquencyEffectivePauseHelper delinquencyEffectivePauseHelper;
private final DelinquencyReadPlatformService delinquencyReadPlatformService;
private final BusinessEventNotifierService businessEventNotifierService;

@Override
public Loan execute(Loan loan) {
Expand All @@ -55,7 +67,17 @@ public Loan execute(Loan loan) {
// the
// current date and not the previous (COB) date.
ThreadLocalContextUtil.setActionContext(ActionContext.DEFAULT);
loanAccountDomainService.setLoanDelinquencyTag(loan, DateUtils.getBusinessLocalDate());

final List<LoanDelinquencyAction> savedDelinquencyList = delinquencyReadPlatformService
.retrieveLoanDelinquencyActions(loan.getId());
List<LoanDelinquencyActionData> effectiveDelinquencyList = delinquencyEffectivePauseHelper
.calculateEffectiveDelinquencyList(savedDelinquencyList);

if (!isDelinquencyOnPause(loan, effectiveDelinquencyList)) {
loanAccountDomainService.setLoanDelinquencyTag(loan, DateUtils.getBusinessLocalDate(), effectiveDelinquencyList);
} else {
log.debug("Delinquency is on pause for loan with ID [{}]", loan.getId());
}
} catch (RuntimeException re) {
log.error(
"Received [{}] exception while processing delinquency tag for loan with Id [{}], account number [{}], external Id [{}]",
Expand All @@ -74,6 +96,21 @@ public Loan execute(Loan loan) {
return loan;
}

private boolean isDelinquencyOnPause(Loan loan, List<LoanDelinquencyActionData> effectiveDelinquencyList) {
LocalDate cobBusinessDate = ThreadLocalContextUtil.getBusinessDateByType(BusinessDateType.COB_DATE);
boolean isPaused = isPausedOnDate(cobBusinessDate, effectiveDelinquencyList);
boolean wasPausedOneDayBefore = isPausedOnDate(cobBusinessDate.minusDays(1), effectiveDelinquencyList);
if ((isPaused && !wasPausedOneDayBefore) || (!isPaused && wasPausedOneDayBefore)) {
businessEventNotifierService.notifyPostBusinessEvent(new LoanDelinquencyRangeChangeBusinessEvent(loan));
}
return isPaused;
}

private static boolean isPausedOnDate(LocalDate date, List<LoanDelinquencyActionData> effectiveDelinquencyList) {
return effectiveDelinquencyList.stream()
.anyMatch(pausePeriod -> !pausePeriod.getStartDate().isAfter(date) && !pausePeriod.getEndDate().isBefore(date));
}

@Override
public String getEnumStyledName() {
return "LOAN_DELINQUENCY_CLASSIFICATION";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* 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.portfolio.delinquency.helper;

import java.time.LocalDate;
import java.util.List;
import org.apache.fineract.portfolio.delinquency.domain.LoanDelinquencyAction;
import org.apache.fineract.portfolio.delinquency.validator.LoanDelinquencyActionData;

public interface DelinquencyEffectivePauseHelper {

List<LoanDelinquencyActionData> calculateEffectiveDelinquencyList(List<LoanDelinquencyAction> savedDelinquencyActions);

Long getPausedDaysBeforeDate(List<LoanDelinquencyActionData> effectiveDelinquencyList, LocalDate date);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* 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.portfolio.delinquency.helper;

import static org.apache.fineract.portfolio.delinquency.domain.DelinquencyAction.RESUME;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.portfolio.delinquency.domain.DelinquencyAction;
import org.apache.fineract.portfolio.delinquency.domain.LoanDelinquencyAction;
import org.apache.fineract.portfolio.delinquency.validator.LoanDelinquencyActionData;
import org.springframework.stereotype.Service;

@Service
public class DelinquencyEffectivePauseHelperImpl implements DelinquencyEffectivePauseHelper {

@Override
public List<LoanDelinquencyActionData> calculateEffectiveDelinquencyList(List<LoanDelinquencyAction> savedDelinquencyActions) {
// partition them based on type
Map<DelinquencyAction, List<LoanDelinquencyAction>> partitioned = savedDelinquencyActions.stream()
.collect(Collectors.groupingBy(LoanDelinquencyAction::getAction));
List<LoanDelinquencyActionData> effective = new ArrayList<>();
List<LoanDelinquencyAction> pauses = partitioned.get(DelinquencyAction.PAUSE);
if (pauses != null && pauses.size() > 0) {
for (LoanDelinquencyAction loanDelinquencyAction : pauses) {
Optional<LoanDelinquencyAction> resume = findMatchingResume(loanDelinquencyAction, partitioned.get(RESUME));
LoanDelinquencyActionData loanDelinquencyActionData = new LoanDelinquencyActionData(loanDelinquencyAction);
resume.ifPresent(r -> loanDelinquencyActionData.setEndDate(r.getStartDate()));
effective.add(loanDelinquencyActionData);
}
}
return effective;
}

@Override
public Long getPausedDaysBeforeDate(List<LoanDelinquencyActionData> effectiveDelinquencyList, LocalDate date) {
Long pausedDaysClosedPausePeriods = effectiveDelinquencyList.stream() //
.filter(pausePeriod -> pausePeriod.getStartDate().isBefore(date) && pausePeriod.getEndDate().isBefore(date))
.map(pausePeriod -> DateUtils.getDifferenceInDays(pausePeriod.getStartDate(), pausePeriod.getEndDate())) //
.reduce(0L, Long::sum);
Long pausedDaysRunningPausePeriods = effectiveDelinquencyList.stream() //
.filter(pausePeriod -> pausePeriod.getStartDate().isBefore(date) && !pausePeriod.getEndDate().isBefore(date))
.map(pausePeriod -> DateUtils.getDifferenceInDays(pausePeriod.getStartDate(), date)) //
.reduce(0L, Long::sum);
return Long.sum(pausedDaysClosedPausePeriods, pausedDaysRunningPausePeriods);
}

private Optional<LoanDelinquencyAction> findMatchingResume(LoanDelinquencyAction pause, List<LoanDelinquencyAction> resumes) {
if (resumes != null && resumes.size() > 0) {
for (LoanDelinquencyAction resume : resumes) {
if (!pause.getStartDate().isAfter(resume.getStartDate()) && !resume.getStartDate().isAfter(pause.getEndDate())) {
return Optional.of(resume);
}
}
}
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.apache.fineract.portfolio.delinquency.service;

import java.util.Collection;
import java.util.List;
import org.apache.fineract.portfolio.delinquency.data.DelinquencyBucketData;
import org.apache.fineract.portfolio.delinquency.data.DelinquencyRangeData;
import org.apache.fineract.portfolio.delinquency.data.LoanDelinquencyTagHistoryData;
Expand All @@ -44,6 +45,6 @@ public interface DelinquencyReadPlatformService {

Collection<LoanInstallmentDelinquencyTagData> retrieveLoanInstallmentsCurrentDelinquencyTag(Long loanId);

Collection<LoanDelinquencyAction> retrieveLoanDelinquencyActions(Long loanId);
List<LoanDelinquencyAction> retrieveLoanDelinquencyActions(Long loanId);

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,10 @@
*/
package org.apache.fineract.portfolio.delinquency.service;

import static org.apache.fineract.portfolio.delinquency.domain.DelinquencyAction.RESUME;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collector;
import java.util.stream.Collectors;
Expand All @@ -36,7 +32,6 @@
import org.apache.fineract.portfolio.delinquency.data.DelinquencyRangeData;
import org.apache.fineract.portfolio.delinquency.data.LoanDelinquencyTagHistoryData;
import org.apache.fineract.portfolio.delinquency.data.LoanInstallmentDelinquencyTagData;
import org.apache.fineract.portfolio.delinquency.domain.DelinquencyAction;
import org.apache.fineract.portfolio.delinquency.domain.DelinquencyBucket;
import org.apache.fineract.portfolio.delinquency.domain.DelinquencyBucketRepository;
import org.apache.fineract.portfolio.delinquency.domain.DelinquencyRange;
Expand All @@ -46,6 +41,7 @@
import org.apache.fineract.portfolio.delinquency.domain.LoanDelinquencyTagHistory;
import org.apache.fineract.portfolio.delinquency.domain.LoanDelinquencyTagHistoryRepository;
import org.apache.fineract.portfolio.delinquency.domain.LoanInstallmentDelinquencyTagRepository;
import org.apache.fineract.portfolio.delinquency.helper.DelinquencyEffectivePauseHelper;
import org.apache.fineract.portfolio.delinquency.mapper.DelinquencyBucketMapper;
import org.apache.fineract.portfolio.delinquency.mapper.DelinquencyRangeMapper;
import org.apache.fineract.portfolio.delinquency.mapper.LoanDelinquencyTagMapper;
Expand Down Expand Up @@ -73,6 +69,7 @@ public class DelinquencyReadPlatformServiceImpl implements DelinquencyReadPlatfo
private final LoanDelinquencyDomainService loanDelinquencyDomainService;
private final LoanInstallmentDelinquencyTagRepository repositoryLoanInstallmentDelinquencyTag;
private final LoanDelinquencyActionRepository loanDelinquencyActionRepository;
private final DelinquencyEffectivePauseHelper delinquencyEffectivePauseHelper;

@Override
public Collection<DelinquencyRangeData> retrieveAllDelinquencyRanges() {
Expand Down Expand Up @@ -127,7 +124,11 @@ public CollectionData calculateLoanCollectionData(final Long loanId) {
if (optLoan.isPresent()) {
final Loan loan = optLoan.get();

collectionData = loanDelinquencyDomainService.getOverdueCollectionData(loan);
final List<LoanDelinquencyAction> savedDelinquencyList = retrieveLoanDelinquencyActions(loanId);
List<LoanDelinquencyActionData> effectiveDelinquencyList = delinquencyEffectivePauseHelper
.calculateEffectiveDelinquencyList(savedDelinquencyList);

collectionData = loanDelinquencyDomainService.getOverdueCollectionData(loan, effectiveDelinquencyList);
collectionData.setAvailableDisbursementAmount(loan.getApprovedPrincipal().subtract(loan.getDisbursedAmount()));
collectionData.setNextPaymentDueDate(loan.possibleNextRepaymentDate());

Expand All @@ -143,8 +144,7 @@ public CollectionData calculateLoanCollectionData(final Long loanId) {
collectionData.setLastRepaymentAmount(lastRepaymentTransaction.getAmount());
}

enrichWithDelinquencyPausePeriodInfo(collectionData, retrieveLoanDelinquencyActions(loanId),
ThreadLocalContextUtil.getBusinessDate());
enrichWithDelinquencyPausePeriodInfo(collectionData, effectiveDelinquencyList, ThreadLocalContextUtil.getBusinessDate());

if (optLoan.get().isEnableInstallmentLevelDelinquency()) {
addInstallmentLevelDelinquencyData(collectionData, loanId);
Expand Down Expand Up @@ -188,29 +188,12 @@ private void addInstallmentLevelDelinquencyData(CollectionData collectionData, L
});
}

void enrichWithDelinquencyPausePeriodInfo(CollectionData collectionData, Collection<LoanDelinquencyAction> delinquencyActions,
void enrichWithDelinquencyPausePeriodInfo(CollectionData collectionData, Collection<LoanDelinquencyActionData> effectiveDelinquencyList,
LocalDate businessDate) {
// partition them based on type
Map<DelinquencyAction, List<LoanDelinquencyAction>> partitioned = delinquencyActions.stream()
.collect(Collectors.groupingBy(LoanDelinquencyAction::getAction));

// add the possible resumes to it to create the effective pause periods
if (partitioned.containsKey(DelinquencyAction.PAUSE)) {
List<LoanDelinquencyActionData> effective = new ArrayList<>();
List<LoanDelinquencyAction> pauses = partitioned.get(DelinquencyAction.PAUSE);
for (LoanDelinquencyAction loanDelinquencyAction : pauses) {
Optional<LoanDelinquencyAction> resume = findMatchingResume(loanDelinquencyAction, partitioned.get(RESUME));
LoanDelinquencyActionData loanDelinquencyActionData = new LoanDelinquencyActionData(loanDelinquencyAction);
resume.ifPresent(r -> loanDelinquencyActionData.setEndDate(r.getStartDate()));
effective.add(loanDelinquencyActionData);
}

// order them by start date, and convert to DelinquencyPausePeriod objects
List<DelinquencyPausePeriod> result = effective.stream() //
.sorted(Comparator.comparing(LoanDelinquencyActionData::getStartDate)) //
.map(lda -> toDelinquencyPausePeriod(businessDate, lda)).toList(); //
collectionData.setDelinquencyPausePeriods(result);
}
List<DelinquencyPausePeriod> result = effectiveDelinquencyList.stream() //
.sorted(Comparator.comparing(LoanDelinquencyActionData::getStartDate)) //
.map(lda -> toDelinquencyPausePeriod(businessDate, lda)).toList(); //
collectionData.setDelinquencyPausePeriods(result);
}

@NotNull
Expand All @@ -219,24 +202,13 @@ private static DelinquencyPausePeriod toDelinquencyPausePeriod(LocalDate busines
lda.getStartDate(), lda.getEndDate());
}

private Optional<LoanDelinquencyAction> findMatchingResume(LoanDelinquencyAction pause, List<LoanDelinquencyAction> resumes) {
if (resumes != null && resumes.size() > 0) {
for (LoanDelinquencyAction resume : resumes) {
if (!pause.getStartDate().isAfter(resume.getStartDate()) && !resume.getStartDate().isAfter(pause.getEndDate())) {
return Optional.of(resume);
}
}
}
return Optional.empty();
}

@Override
public Collection<LoanInstallmentDelinquencyTagData> retrieveLoanInstallmentsCurrentDelinquencyTag(Long loanId) {
return repositoryLoanInstallmentDelinquencyTag.findInstallmentDelinquencyTags(loanId);
}

@Override
public Collection<LoanDelinquencyAction> retrieveLoanDelinquencyActions(Long loanId) {
public List<LoanDelinquencyAction> retrieveLoanDelinquencyActions(Long loanId) {
final Optional<Loan> optLoan = this.loanRepository.findById(loanId);
if (optLoan.isPresent()) {
return loanDelinquencyActionRepository.findByLoanOrderById(optLoan.get());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
*/
package org.apache.fineract.portfolio.delinquency.service;

import java.util.List;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.portfolio.delinquency.validator.LoanDelinquencyActionData;
import org.apache.fineract.portfolio.loanaccount.data.LoanScheduleDelinquencyData;
import org.apache.fineract.portfolio.loanaccount.domain.Loan;

Expand All @@ -43,9 +45,11 @@ public interface DelinquencyWritePlatformService {

void cleanLoanDelinquencyTags(Loan loan);

LoanScheduleDelinquencyData calculateDelinquencyData(LoanScheduleDelinquencyData loanScheduleDelinquencyData);
LoanScheduleDelinquencyData calculateDelinquencyData(LoanScheduleDelinquencyData loanScheduleDelinquencyData,
List<LoanDelinquencyActionData> effectiveDelinquencyList);

void applyDelinquencyTagToLoan(LoanScheduleDelinquencyData loanDelinquencyData);
void applyDelinquencyTagToLoan(LoanScheduleDelinquencyData loanDelinquencyData,
List<LoanDelinquencyActionData> effectiveDelinquencyList);

CommandProcessingResult createDelinquencyAction(Long loanId, JsonCommand command);

Expand Down
Loading

0 comments on commit cb40f23

Please sign in to comment.