FINERACT-1840: Fee income is not realised if the loan got fully repaid

This commit is contained in:
Jose Alberto Hernandez
2023-02-03 11:29:11 +01:00
committed by Adam Saghy
parent 3a2f25980f
commit 95ec9eaa37
12 changed files with 489 additions and 121 deletions
@@ -104,7 +104,7 @@ public class JournalEntriesApiResource {
+ "\n" + "journalentries?orderBy=transactionId&sortOrder=DESC\n" + "\n" + "journalentries?runningBalance=true\n" + "\n"
+ "journalentries?transactionDetails=true\n" + "\n" + "journalentries?loanId=12\n" + "\n" + "journalentries?savingsId=24")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = JournalEntryData.class)))) })
@ApiResponse(responseCode = "200", description = "OK", content = @Content(array = @ArraySchema(schema = @Schema(implementation = JournalEntriesApiResourceSwagger.GetJournalEntriesTransactionIdResponse.class)))) })
public String retrieveAll(@Context final UriInfo uriInfo,
@QueryParam("officeId") @Parameter(description = "officeId") final Long officeId,
@QueryParam("glAccountId") @Parameter(description = "glAccountId") final Long glAccountId,
@@ -166,7 +166,7 @@ public class JournalEntriesApiResource {
+ "journalentries/1?fields=officeName,glAccountId,entryType,amount\n" + "\n" + "journalentries/1?runningBalance=true\n" + "\n"
+ "journalentries/1?transactionDetails=true")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = JournalEntryData.class))) })
@ApiResponse(responseCode = "200", description = "OK", content = @Content(schema = @Schema(implementation = JournalEntriesApiResourceSwagger.JournalEntryTransactionItem.class))) })
public String retrieveJournalEntryById(
@PathParam("journalEntryId") @Parameter(description = "journalEntryId") final Long journalEntryId,
@Context final UriInfo uriInfo,
@@ -19,6 +19,12 @@
package org.apache.fineract.accounting.journalentry.api;
import io.swagger.v3.oas.annotations.media.Schema;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import org.apache.fineract.organisation.monetary.api.CurrenciesApiResourceSwagger.CurrencyItem;
import org.apache.fineract.portfolio.note.api.NotesApiResourceSwagger.GetResourceTypeResourceIdNotesResponse;
import org.apache.fineract.portfolio.paymenttype.api.PaymentTypeApiResourceSwagger.GetPaymentTypesResponse;
/**
* Created by sanyam on 25/7/17.
@@ -62,4 +68,112 @@ final class JournalEntriesApiResourceSwagger {
@Schema(description = "1")
public Long officeId;
}
static final class EnumOptionType {
private EnumOptionType() {}
@Schema(example = "2")
public Long id;
@Schema(example = "accountType.asset")
public String code;
@Schema(example = "ASSET")
public String value;
}
static final class JournalEntryTransactionItem {
private JournalEntryTransactionItem() {}
static final class PaymentDetailData {
private PaymentDetailData() {}
@Schema(example = "62")
public Long id;
public GetPaymentTypesResponse paymentType;
@Schema(example = "acc123")
public String accountNumber;
@Schema(example = "che123")
public String checkNumber;
@Schema(example = "rou123")
public String routingCode;
@Schema(example = "rec123")
public String receiptNumber;
@Schema(example = "ban123")
public String bankNumber;
}
static final class TransactionDetails {
private TransactionDetails() {}
@Schema(example = "2")
public Long transactionId;
public EnumOptionType transactionType;
public GetResourceTypeResourceIdNotesResponse noteData;
public PaymentDetailData paymentDetails;
}
@Schema(example = "1")
public Long id;
@Schema(example = "L12")
public String transactionId;
@Schema(example = "1")
public Long entityId;
@Schema(example = "1")
public Long officeId;
@Schema(example = "Head Office")
public String officeName;
@Schema(example = "10")
public Long glAccountId;
@Schema(example = "Cash Account")
public String glAccountName;
@Schema(example = "0123-4567")
public String glAccountCode;
@Schema(example = "[2022, 07, 01]")
public LocalDate transactionDate;
@Schema(example = "[2022, 07, 01]")
public LocalDate submittedOnDate;
@Schema(example = "100.000000")
public Double amount;
@Schema(example = "false")
public boolean reversed;
@Schema(example = "false")
public boolean manualEntry;
@Schema(example = "Manual entry")
public String comments;
@Schema(example = "QWERTY")
public String referenceNumber;
@Schema(example = "1234.56")
public BigDecimal officeRunningBalance;
@Schema(example = "1234.56")
public BigDecimal organizationRunningBalance;
@Schema(example = "false")
public boolean runningBalanceComputed;
@Schema(example = "1")
public Long createdByUserId;
@Schema(example = "mifos")
public String createdByUserName;
@Schema(example = "[2022, 07, 01]")
public LocalDate createdDate;
public CurrencyItem currency;
public EnumOptionType glAccountType;
public EnumOptionType entryType;
public EnumOptionType entityType;
public TransactionDetails transactionDetails;
}
@Schema(description = "GetJournalEntriesTransactionIdResponse")
public static final class GetJournalEntriesTransactionIdResponse {
private GetJournalEntriesTransactionIdResponse() {}
@Schema(example = "2")
public Long totalFilteredRecords;
public List<JournalEntryTransactionItem> pageItems;
}
}
@@ -25,12 +25,32 @@ import org.apache.fineract.organisation.monetary.data.CurrencyData;
/**
* Created by sanyam on 14/8/17.
*/
final class CurrenciesApiResourceSwagger {
public final class CurrenciesApiResourceSwagger {
private CurrenciesApiResourceSwagger() {
}
public static final class CurrencyItem {
private CurrencyItem() {}
@Schema(example = "USD")
public String code;
@Schema(example = "US Dollar")
public String name;
@Schema(example = "2")
public Integer decimalPlaces;
@Schema(example = "100")
public Integer inMultiplesOf;
@Schema(example = "$")
public String displaySymbol;
@Schema(example = "currency.USD")
public String nameCode;
@Schema(example = "US Dollar ($)")
public String displayLabel;
}
@Schema(description = "GetCurrenciesResponse")
public static final class GetCurrenciesResponse {
@@ -3447,10 +3447,10 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
}
}
if (isAllChargesPaid) {
loanLifecycleStateMachine.transition(LoanEvent.REPAID_IN_FULL, this);
this.closedOnDate = transactionDate;
this.actualMaturityDate = transactionDate;
loanLifecycleStateMachine.transition(LoanEvent.REPAID_IN_FULL, this);
} else if (LoanStatus.fromInt(this.loanStatus).isOverpaid()) {
if (this.totalOverpaid == null || BigDecimal.ZERO.compareTo(this.totalOverpaid) == 0) {
this.overpaidOnDate = null;
@@ -3506,6 +3506,39 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
updateLoanOutstandingBalances();
}
public void applyIncomeAccrualTransaction(LocalDate closedDate) {
ExternalId externalId = ExternalId.empty();
boolean isExternalIdAutoGenerationEnabled = TemporaryConfigurationServiceContainer.isExternalIdAutoGenerationEnabled();
if (isPeriodicAccrualAccountingEnabledOnLoanProduct()) {
List<LoanTransaction> updatedAccrualTransactions = retrieveListOfAccrualTransactions();
LocalDate lastAccruedDate = this.getDisbursementDate();
if (!updatedAccrualTransactions.isEmpty()) {
lastAccruedDate = updatedAccrualTransactions.get(updatedAccrualTransactions.size() - 1).getTransactionDate();
}
HashMap<String, Object> feeDetails = new HashMap<>();
determineFeeDetails(lastAccruedDate, closedDate, feeDetails);
if (isExternalIdAutoGenerationEnabled) {
externalId = ExternalId.generate();
}
BigDecimal fee = (BigDecimal) feeDetails.get(FEE);
if (fee == null) {
fee = BigDecimal.ZERO;
}
BigDecimal penalty = (BigDecimal) feeDetails.get(PENALTIES);
if (penalty == null) {
penalty = BigDecimal.ZERO;
}
BigDecimal total = fee.add(penalty);
// TODO: calculate interest?
if (total.compareTo(BigDecimal.ZERO) > 0) {
LoanTransaction accrualTransaction = LoanTransaction.accrueTransaction(this, this.getOffice(), closedDate, total, null, fee,
penalty, externalId);
updateLoanChargesPaidBy(accrualTransaction, feeDetails, null);
addLoanTransaction(accrualTransaction);
}
}
}
private void determineCumulativeIncomeFromInstallments(HashMap<String, BigDecimal> cumulativeIncomeFromInstallments) {
BigDecimal interest = BigDecimal.ZERO;
BigDecimal fee = BigDecimal.ZERO;
@@ -3797,6 +3830,10 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
validateAccountStatus(LoanEvent.WRITE_OFF_OUTSTANDING);
final LocalDate writtenOffOnLocalDate = command.localDateValueOfParameterNamed(TRANSACTION_DATE);
this.closedOnDate = writtenOffOnLocalDate;
this.writtenOffOnDate = writtenOffOnLocalDate;
this.closedBy = currentUser;
final LoanStatus statusEnum = loanLifecycleStateMachine.dryTransition(LoanEvent.WRITE_OFF_OUTSTANDING, this);
LoanTransaction loanTransaction = null;
@@ -3807,7 +3844,6 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
existingTransactionIds.addAll(findExistingTransactionIds());
existingReversedTransactionIds.addAll(findExistingReversedTransactionIds());
final LocalDate writtenOffOnLocalDate = command.localDateValueOfParameterNamed(TRANSACTION_DATE);
final String txnExternalId = command.stringValueOfParameterNamedAllowingNull(EXTERNAL_ID);
ExternalId externalId = ExternalIdFactory.produce(txnExternalId);
@@ -3816,9 +3852,6 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
externalId = ExternalId.generate();
}
this.closedOnDate = writtenOffOnLocalDate;
this.writtenOffOnDate = writtenOffOnLocalDate;
this.closedBy = currentUser;
changes.put(CLOSED_ON_DATE, command.stringValueOfParameterNamed(TRANSACTION_DATE));
changes.put(WRITTEN_OFF_ON_DATE, command.stringValueOfParameterNamed(TRANSACTION_DATE));
changes.put("externalId", externalId);
@@ -3934,12 +3967,12 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
final Money totalOutstanding = this.summary.getTotalOutstanding(loanCurrency());
if (totalOutstanding.isGreaterThanZero() && getInArrearsTolerance().isGreaterThanOrEqualTo(totalOutstanding)) {
this.closedOnDate = closureDate;
final LoanStatus statusEnum = loanLifecycleStateMachine.dryTransition(LoanEvent.REPAID_IN_FULL, this);
if (!statusEnum.hasStateOf(LoanStatus.fromInt(this.loanStatus))) {
loanLifecycleStateMachine.transition(LoanEvent.REPAID_IN_FULL, this);
changes.put(PARAM_STATUS, LoanEnumerations.status(this.loanStatus));
}
this.closedOnDate = closureDate;
changes.put("externalId", externalId);
loanTransaction = LoanTransaction.writeoff(this, getOffice(), closureDate, externalId);
final boolean isLastTransaction = isChronologicallyLatestTransaction(loanTransaction, getLoanTransactions());
@@ -3965,14 +3998,13 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
final Money totalLoanOverpayment = calculateTotalOverpayment();
if (totalLoanOverpayment.isGreaterThanZero() && getInArrearsTolerance().isGreaterThanOrEqualTo(totalLoanOverpayment)) {
// TODO - KW - technically should set somewhere that this loan
// has
// 'overpaid' amount
// has 'overpaid' amount
this.closedOnDate = closureDate;
final LoanStatus statusEnum = loanLifecycleStateMachine.dryTransition(LoanEvent.REPAID_IN_FULL, this);
if (!statusEnum.hasStateOf(LoanStatus.fromInt(this.loanStatus))) {
loanLifecycleStateMachine.transition(LoanEvent.REPAID_IN_FULL, this);
changes.put(PARAM_STATUS, LoanEnumerations.status(this.loanStatus));
}
this.closedOnDate = closureDate;
} else if (totalLoanOverpayment.isGreaterThanZero()) {
final String errorMessage = "The loan is marked as 'Overpaid' and cannot be moved to 'Closed (obligations met).";
throw new InvalidLoanStateTransitionException("close", "loan.is.overpaid", errorMessage, totalLoanOverpayment.toString());
@@ -3995,13 +4027,13 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
final LocalDate rescheduledOn = command.localDateValueOfParameterNamed(TRANSACTION_DATE);
this.closedOnDate = rescheduledOn;
final LoanStatus statusEnum = loanLifecycleStateMachine.dryTransition(LoanEvent.LOAN_RESCHEDULE, this);
if (!statusEnum.hasStateOf(LoanStatus.fromInt(this.loanStatus))) {
loanLifecycleStateMachine.transition(LoanEvent.LOAN_RESCHEDULE, this);
changes.put(PARAM_STATUS, LoanEnumerations.status(this.loanStatus));
}
this.closedOnDate = rescheduledOn;
this.rescheduledOnDate = rescheduledOn;
changes.put(CLOSED_ON_DATE, command.stringValueOfParameterNamed(TRANSACTION_DATE));
changes.put("rescheduledOnDate", command.stringValueOfParameterNamed(TRANSACTION_DATE));
@@ -6121,6 +6153,7 @@ public class Loan extends AbstractAuditableWithUTCDateTimeCustom {
if (this.totalOverpaid == null || BigDecimal.ZERO.compareTo(this.totalOverpaid) == 0) {
this.overpaidOnDate = null;
this.closedOnDate = newCreditBalanceRefundTransaction.getTransactionDate();
defaultLoanLifecycleStateMachine.transition(LoanEvent.LOAN_CREDIT_BALANCE_REFUND, this);
}
@@ -0,0 +1,21 @@
/**
* 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.loanaccount.service;
public interface LoanStatusChangePlatformService {}
@@ -0,0 +1,55 @@
/**
* 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.loanaccount.service;
import javax.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.infrastructure.event.business.BusinessEventListener;
import org.apache.fineract.infrastructure.event.business.domain.loan.LoanStatusChangedBusinessEvent;
import org.apache.fineract.infrastructure.event.business.service.BusinessEventNotifierService;
import org.apache.fineract.portfolio.loanaccount.domain.Loan;
import org.springframework.stereotype.Service;
@Slf4j
@RequiredArgsConstructor
@Service
public class LoanStatusChangePlatformServiceImpl implements LoanStatusChangePlatformService {
private final BusinessEventNotifierService businessEventNotifierService;
@PostConstruct
public void addListeners() {
businessEventNotifierService.addPostBusinessEventListener(LoanStatusChangedBusinessEvent.class, new LoanStatusChangedListener());
}
private static class LoanStatusChangedListener implements BusinessEventListener<LoanStatusChangedBusinessEvent> {
@Override
public void onBusinessEvent(LoanStatusChangedBusinessEvent event) {
final Loan loan = event.get();
log.debug("Loan Status change for loan {}", loan.getId());
// Apply common actions on Loan account closed
if (loan.isClosed()) {
log.debug("Loan Status {} for loan {}", loan.getStatus().getCode(), loan.getId());
loan.applyIncomeAccrualTransaction(loan.getClosedOnDate());
}
}
}
}
@@ -1039,110 +1039,30 @@ final class LoanProductsApiResourceSwagger {
private GetLoanAccountingMappings() {}
static final class GetLoanFundSourceAccount {
static final class GetGlAccountMapping {
private GetLoanFundSourceAccount() {}
@Schema(example = "1")
public Long id;
@Schema(example = "fund source")
public String name;
@Schema(example = "01")
public Integer glCode;
}
static final class GetLoanPortfolioAccount {
private GetLoanPortfolioAccount() {}
@Schema(example = "2")
public Long id;
@Schema(example = "Loan portfolio")
public String name;
@Schema(example = "02")
public Integer glCode;
}
static final class GetLoanTransfersInSuspenseAccount {
private GetLoanTransfersInSuspenseAccount() {}
@Schema(example = "3")
public Long id;
@Schema(example = "transfers")
public String name;
@Schema(example = "03")
public Integer glCode;
}
static final class GetLoanInterestOnLoanAccount {
private GetLoanInterestOnLoanAccount() {}
@Schema(example = "4")
public Long id;
@Schema(example = "income from interest")
public String name;
@Schema(example = "04")
public Integer glCode;
}
static final class GetLoanIncomeFromFeeAccount {
private GetLoanIncomeFromFeeAccount() {}
@Schema(example = "8")
public Long id;
@Schema(example = "income from fees 2")
public String name;
@Schema(example = "10")
public Integer glCode;
}
static final class GetLoanIncomeFromPenaltyAccount {
private GetLoanIncomeFromPenaltyAccount() {}
@Schema(example = "9")
public Long id;
@Schema(example = "income from penalities 2")
public String name;
@Schema(example = "11")
public Integer glCode;
}
static final class GetLoanWriteOffAccount {
private GetLoanWriteOffAccount() {}
private GetGlAccountMapping() {}
@Schema(example = "10")
public Long id;
@Schema(example = "loans written off 2")
@Schema(example = "Cash Account")
public String name;
@Schema(example = "12")
public Integer glCode;
@Schema(example = "012-34-65")
public String glCode;
}
static final class GetLoanOverpaymentLiabilityAccount {
private GetLoanOverpaymentLiabilityAccount() {}
@Schema(example = "11")
public Long id;
@Schema(example = "over payment")
public String name;
@Schema(example = "13")
public Integer glCode;
}
public GetLoanFundSourceAccount fundSourceAccount;
public GetLoanPortfolioAccount loanPortfolioAccount;
public GetLoanTransfersInSuspenseAccount transfersInSuspenseAccount;
public GetLoanInterestOnLoanAccount interestOnLoanAccount;
public GetLoanIncomeFromFeeAccount incomeFromFeeAccount;
public GetLoanIncomeFromPenaltyAccount incomeFromPenaltyAccount;
public GetLoanWriteOffAccount writeOffAccount;
public GetLoanOverpaymentLiabilityAccount overpaymentLiabilityAccount;
public GetGlAccountMapping fundSourceAccount;
public GetGlAccountMapping loanPortfolioAccount;
public GetGlAccountMapping transfersInSuspenseAccount;
public GetGlAccountMapping receivableInterestAccount;
public GetGlAccountMapping receivablePenaltyAccount;
public GetGlAccountMapping interestOnLoanAccount;
public GetGlAccountMapping incomeFromFeeAccount;
public GetGlAccountMapping incomeFromPenaltyAccount;
public GetGlAccountMapping incomeFromRecoveryAccount;
public GetGlAccountMapping writeOffAccount;
public GetGlAccountMapping goodwillCreditAccount;
public GetGlAccountMapping overpaymentLiabilityAccount;
}
static final class GetLoanPaymentChannelToFundSourceMappings {
@@ -1174,7 +1094,7 @@ final class LoanProductsApiResourceSwagger {
}
public GetLoanCharge charge;
public GetLoanAccountingMappings.GetLoanIncomeFromFeeAccount incomeAccount;
public GetLoanAccountingMappings.GetGlAccountMapping incomeAccount;
@Schema(example = "10")
public Long chargeId;
@Schema(example = "39")
@@ -24,7 +24,7 @@ import java.time.ZonedDateTime;
/**
* Created by Chirag Gupta on 12/29/17.
*/
final class NotesApiResourceSwagger {
public final class NotesApiResourceSwagger {
private NotesApiResourceSwagger() {}
@@ -23,7 +23,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
/**
* Created by Chirag Gupta on 01/01/18.
*/
final class PaymentTypeApiResourceSwagger {
public final class PaymentTypeApiResourceSwagger {
private PaymentTypeApiResourceSwagger() {}