adamsaghy commented on code in PR #5053:
URL: https://github.com/apache/fineract/pull/5053#discussion_r2432400368
##########
fineract-progressive-loan/src/main/java/org/apache/fineract/portfolio/loanaccount/domain/transactionprocessor/impl/AdvancedPaymentScheduleTransactionProcessor.java:
##########
@@ -2890,71 +2899,362 @@ private void handleReAge(LoanTransaction
loanTransaction, TransactionCtx ctx) {
MonetaryCurrency currency = ctx.getCurrency();
List<LoanRepaymentScheduleInstallment> installments =
ctx.getInstallments();
- AtomicReference<Money> outstandingPrincipalBalance = new
AtomicReference<>(Money.zero(currency));
+ // re-aging logic for interest-bearing loans
+ if (ctx instanceof ProgressiveTransactionCtx progressiveTransactionCtx
+ &&
loanTransaction.getLoan().isInterestBearingAndInterestRecalculationEnabled()) {
+ handleReAgeWithInterestRecalculationEnabled(loanTransaction,
progressiveTransactionCtx);
+ } else if (loanTransaction.getLoan().isInterestBearing() &&
!loanTransaction.getLoan().isInterestRecalculationEnabled()) {
+ // TODO: implement interestRecalculation = false logic
+ throw new NotImplementedException(
+ "Logic for re-aging when interest bearing loan has
interestRecalculation disabled is not implemented");
+ } else {
+ AtomicReference<Money> outstandingPrincipalBalance = new
AtomicReference<>(Money.zero(currency));
+ installments.forEach(i -> {
+ Money principalOutstanding =
i.getPrincipalOutstanding(currency);
+ if (principalOutstanding.isGreaterThanZero()) {
+
outstandingPrincipalBalance.set(outstandingPrincipalBalance.get().add(principalOutstanding));
+ i.addToPrincipal(loanTransaction.getTransactionDate(),
principalOutstanding.negated());
+ }
+ });
+
+
loanTransaction.updateComponentsAndTotal(outstandingPrincipalBalance.get(),
Money.zero(currency), Money.zero(currency),
+ Money.zero(currency));
+
+ Money calculatedPrincipal = Money.zero(currency);
+ Money adjustCalculatedPrincipal = Money.zero(currency);
+ if (outstandingPrincipalBalance.get().isGreaterThanZero()) {
+ calculatedPrincipal = outstandingPrincipalBalance.get()
+
.dividedBy(loanTransaction.getLoanReAgeParameter().getNumberOfInstallments(),
MoneyHelper.getMathContext());
+ Integer installmentAmountInMultiplesOf =
loanTransaction.getLoan().getLoanProductRelatedDetail()
+ .getInstallmentAmountInMultiplesOf();
+ if (installmentAmountInMultiplesOf != null) {
+ calculatedPrincipal =
Money.roundToMultiplesOf(calculatedPrincipal, installmentAmountInMultiplesOf);
+ }
+ adjustCalculatedPrincipal = outstandingPrincipalBalance.get()
+
.minus(calculatedPrincipal.multipliedBy(loanTransaction.getLoanReAgeParameter().getNumberOfInstallments()));
+ }
+
+ Optional<LoanRepaymentScheduleInstallment>
lastNormalInstallmentOptional = installments.stream().filter(i ->
!i.isDownPayment())
+ .filter(i ->
i.getDueDate().isBefore(loanTransaction.getTransactionDate())).reduce((first,
second) -> second);
+
+ int reAgedInstallmentNumber;
+ LocalDate fromDate;
+ Loan loan;
+ if (lastNormalInstallmentOptional.isEmpty()) {
+ LoanRepaymentScheduleInstallment firstNormalInstallment =
installments.stream().filter(i -> !i.isDownPayment())
+
.min(Comparator.comparing(LoanRepaymentScheduleInstallment::getDueDate)).orElseThrow();
+ reAgedInstallmentNumber =
firstNormalInstallment.getInstallmentNumber();
+ fromDate = firstNormalInstallment.getFromDate();
+ loan = firstNormalInstallment.getLoan();
+ } else {
+ LoanRepaymentScheduleInstallment lastNormalInstallment =
lastNormalInstallmentOptional.get();
+ reAgedInstallmentNumber =
lastNormalInstallment.getInstallmentNumber() + 1;
+ fromDate = lastNormalInstallment.getDueDate();
+ loan = lastNormalInstallment.getLoan();
+ }
+
+ LoanRepaymentScheduleInstallment reAgedInstallment =
LoanRepaymentScheduleInstallment.newReAgedInstallment(loan,
+ reAgedInstallmentNumber, fromDate,
loanTransaction.getLoanReAgeParameter().getStartDate(),
+ calculatedPrincipal.getAmount());
+ insertOrReplaceRelatedInstallment(installments, reAgedInstallment,
currency, loanTransaction.getTransactionDate());
+
+ for (int i = 1; i <
loanTransaction.getLoanReAgeParameter().getNumberOfInstallments(); i++) {
+ LocalDate calculatedDueDate =
calculateReAgedInstallmentDueDate(loanTransaction.getLoanReAgeParameter(),
+ reAgedInstallment.getDueDate());
+ int nextReAgedInstallmentNumber =
reAgedInstallment.getInstallmentNumber() + 1;
+ reAgedInstallment =
LoanRepaymentScheduleInstallment.newReAgedInstallment(reAgedInstallment.getLoan(),
+ nextReAgedInstallmentNumber,
reAgedInstallment.getDueDate(), calculatedDueDate,
calculatedPrincipal.getAmount());
+ if (i + 1 ==
loanTransaction.getLoanReAgeParameter().getNumberOfInstallments()) {
+
reAgedInstallment.addToPrincipal(loanTransaction.getTransactionDate(),
adjustCalculatedPrincipal);
+ }
+ insertOrReplaceRelatedInstallment(installments,
reAgedInstallment, currency, loanTransaction.getTransactionDate());
+ }
+ int lastReAgedInstallmentNumber =
reAgedInstallment.getInstallmentNumber();
+ List<LoanRepaymentScheduleInstallment> toRemove =
installments.stream().filter(i -> i != null && !i.isAdditional()
+ && i.getInstallmentNumber() != null &&
i.getInstallmentNumber() > lastReAgedInstallmentNumber).toList();
+ toRemove.forEach(installments::remove);
+ reprocessInstallments(installments);
+ }
+ }
+
+ private void handleReAgeWithInterestRecalculationEnabled(final
LoanTransaction loanTransaction, final ProgressiveTransactionCtx ctx) {
+ final MonetaryCurrency currency = ctx.getCurrency();
+ final Loan loan = loanTransaction.getLoan();
+ final MathContext mc = MoneyHelper.getMathContext();
+ final LocalDate transactionDate = loanTransaction.getTransactionDate();
+ final List<LoanRepaymentScheduleInstallment> installments =
ctx.getInstallments();
+ final List<RepaymentPeriod> repaymentPeriods =
ctx.getModel().repaymentPeriods();
+ final LocalDate reAgingStartDate =
loanTransaction.getLoanReAgeParameter().getStartDate();
+
+ final Optional<LoanTransaction> chargeOffTransaction =
ctx.getAlreadyProcessedTransactions().stream()
+ .filter(t -> ((t.isChargeOff() &&
(loan.hasAccelerateChargeOffStrategy() ||
loan.hasZeroInterestChargeOffStrategy()))
+ || t.isContractTermination()) && !t.isReversed() &&
t.getTransactionDate().isBefore(reAgingStartDate))
+ .findFirst();
+
+ final Optional<LoanTransaction> chargebackTransaction =
ctx.getAlreadyProcessedTransactions().stream()
+ .filter(t -> t.isChargeback() && !t.isReversed() &&
t.getTransactionDate().isBefore(reAgingStartDate)).findFirst();
+
+ final List<RepaymentPeriod> periodsBeforeReAging =
repaymentPeriods.stream()
+ .filter(rp -> rp.getFromDate().isBefore(transactionDate) &&
!rp.isFullyPaid()).toList();
+
+ final RepaymentPeriod lastPeriod = periodsBeforeReAging.getLast();
+
+ final BigDecimal interestBeforeReAging =
chargeOffTransaction.isPresent() ? BigDecimal.ZERO
+ : emiCalculator.getPeriodInterestTillDate(ctx.getModel(),
lastPeriod.getDueDate(), transactionDate, false).getAmount();
+
+ final AtomicReference<Money> outstandingPrincipalBalance = new
AtomicReference<>(Money.zero(currency));
installments.forEach(i -> {
- Money principalOutstanding = i.getPrincipalOutstanding(currency);
+ final Money principalOutstanding =
i.getPrincipalOutstanding(currency);
if (principalOutstanding.isGreaterThanZero()) {
outstandingPrincipalBalance.set(outstandingPrincipalBalance.get().add(principalOutstanding));
- i.addToPrincipal(loanTransaction.getTransactionDate(),
principalOutstanding.negated());
}
});
-
loanTransaction.updateComponentsAndTotal(outstandingPrincipalBalance.get(),
Money.zero(currency), Money.zero(currency),
- Money.zero(currency));
+ final AtomicReference<BigDecimal> interestFromZeroedInstallments = new
AtomicReference<>(interestBeforeReAging);
- Money calculatedPrincipal = Money.zero(currency);
- Money adjustCalculatedPrincipal = Money.zero(currency);
- if (outstandingPrincipalBalance.get().isGreaterThanZero()) {
- calculatedPrincipal = outstandingPrincipalBalance.get()
-
.dividedBy(loanTransaction.getLoanReAgeParameter().getNumberOfInstallments(),
MoneyHelper.getMathContext());
- Integer installmentAmountInMultiplesOf =
loanTransaction.getLoan().getLoanProductRelatedDetail()
- .getInstallmentAmountInMultiplesOf();
- if (installmentAmountInMultiplesOf != null) {
- calculatedPrincipal =
Money.roundToMultiplesOf(calculatedPrincipal, installmentAmountInMultiplesOf);
- }
- adjustCalculatedPrincipal = outstandingPrincipalBalance.get()
-
.minus(calculatedPrincipal.multipliedBy(loanTransaction.getLoanReAgeParameter().getNumberOfInstallments()));
+ installments.stream().filter(installment ->
!installment.isObligationsMet() &&
installment.getDueDate().isBefore(reAgingStartDate))
+ .forEach(installment -> {
+ BigDecimal currentInterest =
interestFromZeroedInstallments.get();
+ BigDecimal additionalInterest =
MathUtil.nullToZero(installment.getInterestOutstanding(currency).getAmount()
+
.add(MathUtil.nullToZero(installment.getCreditedInterest()).negate()));
+
interestFromZeroedInstallments.set(currentInterest.add(additionalInterest));
+ removeOutstandingAmountsFromInstallment(installment,
currency, transactionDate);
+ installment.updateObligationsMet(ctx.getCurrency(),
transactionDate);
+ });
+
+ final AtomicReference<Money> creditedPrincipal = new
AtomicReference<>(Money.zero(currency));
+ periodsBeforeReAging.forEach(rp -> {
+ rp.setEmi(rp.getTotalPaidAmount());
+ rp.getInterestPeriods().forEach(interestPeriod -> {
+ if (chargebackTransaction.isEmpty()
+ ||
(!chargebackTransaction.get().getTransactionDate().isBefore(interestPeriod.getFromDate())
+ ||
chargebackTransaction.get().getTransactionDate().isBefore(interestPeriod.getDueDate())))
{
+
interestPeriod.addBalanceCorrectionAmount(interestPeriod.getBalanceCorrectionAmount().negated());
+ }
+ final Money creditedPrincipalToRemove =
interestPeriod.getCreditedPrincipal();
+
interestPeriod.addCreditedPrincipalAmount(creditedPrincipalToRemove.negated());
+
creditedPrincipal.set(creditedPrincipal.get().add(creditedPrincipalToRemove.getAmount()));
+ });
+ });
+
+ final BigDecimal interestRate = chargeOffTransaction.isPresent() ?
BigDecimal.ZERO
+ :
loan.getLoanRepaymentScheduleDetail().getAnnualNominalInterestRate();
+
+ final LocalDate expectedDisbursementDate = switch
(loanTransaction.getLoanReAgeParameter().getFrequencyType()) {
+ case DAYS ->
reAgingStartDate.minusDays(loanTransaction.getLoanReAgeParameter().getFrequencyNumber());
+ case WEEKS ->
reAgingStartDate.minusWeeks(loanTransaction.getLoanReAgeParameter().getFrequencyNumber());
+ case MONTHS ->
reAgingStartDate.minusMonths(loanTransaction.getLoanReAgeParameter().getFrequencyNumber());
+ case YEARS ->
reAgingStartDate.minusYears(loanTransaction.getLoanReAgeParameter().getFrequencyNumber());
+ case WHOLE_TERM -> throw new IllegalStateException("Unexpected
RecalculationFrequencyType: WHOLE_TERM");
+ case INVALID -> throw new IllegalStateException("Unexpected
RecalculationFrequencyType: INVALID");
+ };
+
+ LocalDate disbursementDate = transactionDate;
+ if (!reAgingStartDate.isAfter(transactionDate)) {
+ disbursementDate = expectedDisbursementDate;
+ }
+ final LoanDisbursementDetails disbursementInfo = new
LoanDisbursementDetails(disbursementDate, disbursementDate,
+ outstandingPrincipalBalance.get().getAmount(),
outstandingPrincipalBalance.get().getAmount(), false);
+ disbursementInfo.updateLoan(loan);
+ final List<DisbursementData> disbursementData =
List.of(disbursementInfo.toData());
+
+ final LoanApplicationTerms loanApplicationTerms = new
LoanApplicationTerms.Builder().submittedOnDate(expectedDisbursementDate)
+
.currency(currency.getCurrencyData()).repaymentsStartingFromDate(reAgingStartDate)
+
.expectedDisbursementDate(expectedDisbursementDate).principal(outstandingPrincipalBalance.get())
+
.loanTermFrequency(loanTransaction.getLoanReAgeParameter().getNumberOfInstallments())
+
.loanTermPeriodFrequencyType(loanTransaction.getLoanReAgeParameter().getFrequencyType())
+
.numberOfRepayments(loanTransaction.getLoanReAgeParameter().getNumberOfInstallments())
+
.repaymentEvery(loanTransaction.getLoanReAgeParameter().getFrequencyNumber())
+
.repaymentPeriodFrequencyType(loanTransaction.getLoanReAgeParameter().getFrequencyType())
+ .interestRatePerPeriod(interestRate)
+
.interestRatePeriodFrequencyType(loan.getLoanRepaymentScheduleDetail().getRepaymentPeriodFrequencyType())
+
.annualNominalInterestRate(interestRate).daysInMonthType(loan.getLoanProduct().fetchDaysInMonthType())
+
.daysInYearType(loan.getLoanProduct().fetchDaysInYearType()).inArrearsTolerance(Money.zero(currency,
mc))
+
.disbursementDatas(disbursementData).isDownPaymentEnabled(false).downPaymentPercentage(ZERO).seedDate(reAgingStartDate)
+ .interestRecognitionOnDisbursementDate(
+
loan.getLoanProduct().getLoanProductRelatedDetail().isInterestRecognitionOnDisbursementDate())
+
.daysInYearCustomStrategy(loan.getLoanProduct().getLoanProductRelatedDetail().getDaysInYearCustomStrategy())
+
.interestMethod(loan.getLoanProductRelatedDetail().getInterestMethod()).allowPartialPeriodInterestCalculation(
+
loan.getLoanProduct().getLoanProductRelatedDetail().isAllowPartialPeriodInterestCalculation())
+ .mc(mc).build();
+ final LoanScheduleModel loanScheduleModelForReAging =
scheduleGenerator.generate(mc, loanApplicationTerms, null, null);
Review Comment:
I dont think we need this. `scheduleGenerator` we should use the existing
model + the EmiCalculator and introduce a new action: "reage" and provide its
parameters. THe EmiCalculator can calculate interim models and update existing
one based on that. After the model is updated we can use to update the existing
repayment installments based on the model alone.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]