Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public interface WorkingCapitalLoanChargeRepository

Long findIdByExternalId(ExternalId externalId);

boolean existsByLoanIdAndActiveTrue(Long loanId);

@Query("select new org.apache.fineract.portfolio.workingcapitalloan.data.WorkingCapitalLoanChargeData("
+ "lc.id, c.id, c.name, lc.chargeTimeType, lc.submittedOnDate, lc.dueDate, lc.chargeCalculationType, oc.code, oc.name, oc.decimalPlaces, oc.inMultiplesOf, oc.displaySymbol,"
+ " oc.nameCode, lc.amount, lc.amountPaid, lc.penaltyCharge, lc.chargePaymentMode, lc.paid, l.id, lc.externalId, l.externalId) from WorkingCapitalLoanCharge lc join fetch lc.charge c join OrganisationCurrency oc on c.currencyCode = oc.code join fetch lc.loan l where l.id = :loanId and lc.id = :id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,13 +216,8 @@ public void applyDiscountFeeAdjustment(final WorkingCapitalLoan loan) {

final List<ProjectedAmortizationScheduleModel.ActualPayment> preservedPayments = currentModel.snapshotActualPayments();

final BigDecimal disbursedAmount = loan.getDisbursementDetails() != null && !loan.getDisbursementDetails().isEmpty()
&& loan.getDisbursementDetails().getFirst().getActualAmount() != null
? loan.getDisbursementDetails().getFirst().getActualAmount()
: BigDecimal.ZERO;
final LocalDate disbursementDate = loan.getDisbursementDetails() != null && !loan.getDisbursementDetails().isEmpty()
? loan.getDisbursementDetails().getFirst().getActualDisbursementDate()
: null;
final BigDecimal disbursedAmount = resolveActualDisbursedAmount(loan);
final LocalDate disbursementDate = resolveActualDisbursementDate(loan);

final ProjectedAmortizationScheduleModel restatedModel = generateProjectedAmortizationScheduleModel(loan, disbursedAmount,
disbursementDate);
Expand All @@ -241,4 +236,19 @@ private LocalDate resolveLoanDisbursementDate(final WorkingCapitalLoan loan) {
}
throw new IllegalStateException("Active loan " + loan.getId() + " has no actual disbursement date");
}

private BigDecimal resolveActualDisbursedAmount(final WorkingCapitalLoan loan) {
if (loan.getDisbursementDetails() != null && !loan.getDisbursementDetails().isEmpty()
&& loan.getDisbursementDetails().getFirst().getActualAmount() != null) {
return loan.getDisbursementDetails().getFirst().getActualAmount();
}
return BigDecimal.ZERO;
}

private LocalDate resolveActualDisbursementDate(final WorkingCapitalLoan loan) {
if (loan.getDisbursementDetails() != null && !loan.getDisbursementDetails().isEmpty()) {
return loan.getDisbursementDetails().getFirst().getActualDisbursementDate();
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public void applyRepayment(Long loanId, LocalDate transactionDate, BigDecimal am
.findByLoanIdAndFromDateLessThanEqualAndToDateGreaterThanEqual(loanId, transactionDate, transactionDate);
BigDecimal transactionAmount = amount;
for (WorkingCapitalLoanDelinquencyRangeSchedule period : pastOpenPeriods) {
BigDecimal payAmount = MathUtil.min(amount, period.getOutstandingAmount(), true);
BigDecimal payAmount = MathUtil.min(transactionAmount, period.getOutstandingAmount(), true);
transactionAmount = transactionAmount.subtract(payAmount);
period.setPaidAmount(period.getPaidAmount().add(payAmount));
period.setOutstandingAmount(period.getOutstandingAmount().subtract(payAmount));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* 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.workingcapitalloan.service;

import java.util.List;
import org.apache.fineract.portfolio.workingcapitalloan.domain.WorkingCapitalLoan;
import org.apache.fineract.portfolio.workingcapitalloan.domain.WorkingCapitalLoanTransaction;

/**
* Reprocesses transaction allocations for a Working Capital loan after a backdated transaction or a transaction
* reversal changes the chronological order.
*
* <p>
* Scope is deliberately narrow: only the allocation split (principal/fee/penalty portions) of affected transactions is
* recalculated, and only by the difference. Transactions themselves are never reversed or replayed, and the
* amortization, delinquency and breach schedules are not rebuilt here — those consume transaction amounts (not
* allocations) and are maintained incrementally by the regular transaction flows.
*
* <p>
* Allocation order only matters when payments compete for charge buckets. A loan without charges allocates every
* repayment-like transaction to principal only, which is order-independent — reprocessing is a no-op in that case.
*/
public interface WorkingCapitalLoanTransactionReprocessingService {

void reprocessTransactions(WorkingCapitalLoan loan);

/**
* Reprocesses using the provided pre-loaded transaction list (avoids a redundant DB query when the caller has
* already fetched them).
*/
void reprocessTransactions(WorkingCapitalLoan loan, List<WorkingCapitalLoanTransaction> allTransactions);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* 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.workingcapitalloan.service;

import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.portfolio.workingcapitalloan.domain.WorkingCapitalLoan;
import org.apache.fineract.portfolio.workingcapitalloan.domain.WorkingCapitalLoanTransaction;
import org.apache.fineract.portfolio.workingcapitalloan.repository.WorkingCapitalLoanChargeRepository;
import org.apache.fineract.portfolio.workingcapitalloan.repository.WorkingCapitalLoanTransactionRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional
public class WorkingCapitalLoanTransactionReprocessingServiceImpl implements WorkingCapitalLoanTransactionReprocessingService {

private final WorkingCapitalLoanTransactionRepository transactionRepository;
private final WorkingCapitalLoanChargeRepository chargeRepository;

@Override
public void reprocessTransactions(final WorkingCapitalLoan loan) {
final List<WorkingCapitalLoanTransaction> allTransactions = transactionRepository
.findByWcLoan_IdOrderByTransactionDateAscIdAsc(loan.getId());
reprocessTransactions(loan, allTransactions);
}

@Override
public void reprocessTransactions(final WorkingCapitalLoan loan, final List<WorkingCapitalLoanTransaction> allTransactions) {

@adamsaghy adamsaghy Jun 10, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we might want to consider a different approach:

  • Quickly we can have a high number of transactions and we would like to avoid to recalculate / reprocess all transactions and the amortization schedule
  • We should focus on the changes in the transaction allocations only

What if:

  • Transaction was reversed:
    • transaction reprocessing should only happen if
      • reverted transaction was repaying any charge -> The next upcoming transaction(s) need to reprocessed till charge is repaid by them, the rest of the transactions does not matter.
      • otherwise it does not matter -> No transaction reprocessing needed!
  • Backdated transaction:
    • transaction reprocessing should only happen if
      • backdated transaction needs to repay any charge -> The next upcoming transaction(s) might need to be reprocessed as they might not or with different amount to pay charges from now.
      • otherwise it does not matter -> No transaction reprocessing needed!
  • If no charges were added on the loan, there is no reprocessing needed at all!
  • If reprocessing was needed, we should have the "new" allocations of the involved transaction(s) and based on this amortization schedule / breach schedule / delinquency schedule balances might need to be updated. But only with the delta (difference). No need to recalculate everything, but only with impacted parts.

// Allocation order only matters when payments compete for charge buckets. Without charges,
// every repayment-like transaction allocates to principal only — min(amount, outstanding) —
// which is order-independent, so a changed chronological order cannot change any allocation.
if (!chargeRepository.existsByLoanIdAndActiveTrue(loan.getId())) {
log.debug("Skipping transaction reprocessing for WC loan {}: no active charges, allocations are order-independent",
loan.getId());
return;
}

// Charge-aware re-allocation (recalculate the affected transactions from the change date
// forward until the charge is covered, then apply only the delta to balances/schedules)
// becomes implementable once the payment allocation strategy covers fees and penalties.
// Until then repayments never allocate to charges, so there is still nothing to redistribute.
log.warn("WC loan {} has active charges; charge-aware transaction reprocessing is not implemented yet "
+ "({} transactions left untouched)", loan.getId(), allTransactions.size());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ public class WorkingCapitalLoanWritePlatformServiceImpl implements WorkingCapita
private final WorkingCapitalLoanTransactionRelationRepository relationRepository;
private final WorkingCapitalLoanPeriodPaymentRateChangeRepository rateChangeRepository;
private final WorkingCapitalLoanDiscountFeeAmortizationService discountFeeAmortizationService;
private final WorkingCapitalLoanTransactionReprocessingService transactionReprocessingService;

@Override
public CommandProcessingResult approveApplication(final Long loanId, final JsonCommand command) {
Expand Down Expand Up @@ -671,10 +672,22 @@ private CommandProcessingResult makeRepaymentLikeTransaction(final Long loanId,
.forPrincipalAllocation(transaction, amountAppliedToOutstanding);
this.allocationRepository.saveAndFlush(allocation);

// The incremental flow handles backdated dates correctly: the amortization model records the
// payment on its actual day and recalculates forward, balance math is order-independent, and
// delinquency/breach schedules allocate by transaction date.
amortizationScheduleWriteService.applyRepayment(loan, transactionDate, amountAppliedToOutstanding);
updateBalanceOnRepayment(loan, transactionAmount);
internalWorkingCapitalLoanPaymentService.makePayment(loanId, amountAppliedToOutstanding, transactionDate);

// A backdated transaction can change how SUBSEQUENT transactions allocate to charges. The
// reprocessing engine recalculates only those allocations and no-ops when the loan has no
// charges (principal-only allocation is order-independent).
final List<WorkingCapitalLoanTransaction> allTransactions = this.transactionRepository
.findByWcLoan_IdOrderByTransactionDateAscIdAsc(loanId);
if (isBackdatedTransaction(allTransactions, transaction)) {
transactionReprocessingService.reprocessTransactions(loan, allTransactions);
}

handleStateChanges(loan, transactionDate);
triggerInlineAmortizationIfLoanClosed(loan, transactionDate);
changes.put("status", loan.getLoanStatus());
Expand Down Expand Up @@ -959,6 +972,15 @@ private void updateBalanceOnCreditBalanceRefund(final WorkingCapitalLoan loan, f
this.balanceRepository.saveAndFlush(balance);
}

private boolean isBackdatedTransaction(final List<WorkingCapitalLoanTransaction> allTransactions,
final WorkingCapitalLoanTransaction newTxn) {
// The same-date ID comparison is defensive only: the just-persisted transaction holds the highest
// ID, so in practice only a strictly later transaction date marks the new one as backdated.
return allTransactions.stream().filter(txn -> !txn.isReversed() && !txn.getId().equals(newTxn.getId()))
.anyMatch(txn -> txn.getTransactionDate().isAfter(newTxn.getTransactionDate())
|| (txn.getTransactionDate().equals(newTxn.getTransactionDate()) && txn.getId().compareTo(newTxn.getId()) > 0));
}

private void reverseTransaction(final WorkingCapitalLoanTransaction txn) {
txn.setReversed(true);
txn.setReversedOnDate(DateUtils.getBusinessLocalDate());
Expand Down
Loading