feat(fixed-deposits): FD interest posting approval with pooled GL postings

Adds a maker-checker approval report in front of fixed deposit interest
posting, mirroring the existing savings interest posting report: a
report is generated per branch and product (SINGLE/DOUBLE/SPECIAL), a
second user approves it, and it posts when the branch closes its day.
Day close is blocked until deposit interest due that day is approved.

Ledger entries are pooled per the report's interestPostingDate rather
than raised per deposit: Dr Interest Expense and the Payable/Paid legs
are each raised once for the group's total, and only the final leg
crediting each deposit's own GL is per account — the same pattern the
savings interest posting report already uses, instead of repeating the
full three-stage chain for every deposit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 00:06:00 +05:30
co-authored by Claude Sonnet 5
parent 6c7c0f8445
commit 949f45c4cd
18 changed files with 2383 additions and 4 deletions
@@ -32,6 +32,7 @@ public final class GlobalConfigurationConstants {
public static final String FORCE_PASSWORD_RESET_DAYS = "force-password-reset-days";
public static final String GRACE_ON_PENALTY_POSTING = "grace-on-penalty-posting";
public static final String SAVINGS_INTEREST_POSTING_CURRENT_PERIOD_END = "savings-interest-posting-current-period-end";
public static final String FD_INTEREST_POSTING_APPROVAL = "fd-interest-posting-approval";
public static final String FINANCIAL_YEAR_BEGINNING_MONTH = "financial-year-beginning-month";
public static final String MIN_CLIENTS_IN_GROUP = "min-clients-in-group";
public static final String MAX_CLIENTS_IN_GROUP = "max-clients-in-group";
@@ -69,6 +69,12 @@ public interface ConfigurationDomainService {
boolean isSavingsInterestPostingAtCurrentPeriodEnd();
/**
* Whether fixed deposit interest is reported and approved before it is posted, instead of being
* posted directly by the nightly job.
*/
boolean isFixedDepositInterestPostingApprovalEnabled();
Integer retrieveFinancialYearBeginningMonth();
Integer retrieveMinAllowedClientsInGroup();
@@ -44,6 +44,7 @@ public enum JobName {
APPLY_KYC_EXPIRY_RESTRICTIONS("Apply KYC Expiry Restrictions"), //
SAVINGS_DAILY_INTEREST("Savings Daily Interest Accrual And Posting"), //
SAVINGS_INTEREST_POSTING_REPORT("Generate Savings Interest Posting Report"), //
FD_INTEREST_POSTING_REPORT("Generate Fixed Deposit Interest Posting Report"), //
ADD_PERIODIC_ACCRUAL_ENTRIES_FOR_LOANS_WITH_INCOME_POSTED_AS_TRANSACTIONS(
"Add Accrual Transactions For Loans With Income Posted As Transactions"), //
EXECUTE_REPORT_MAILING_JOBS("Execute Report Mailing Jobs"), //
@@ -0,0 +1,100 @@
/**
* 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.savings;
import java.util.Locale;
/**
* The deposit scheme a fixed deposit product is sold under, held as {@code m_savings_product.fd_type}.
*
* <p>
* The three schemes differ in where a posting of interest ends up, which is what the interest posting
* report has to show and the posting itself has to honour:
*
* <ul>
* <li>{@link #SINGLE} — short deposits, priced from a slab table in days. Interest stays in the
* deposit and is paid with the principal at maturity.</li>
* <li>{@link #DOUBLE} — deposits of a year or more, priced from a slab table in years. Interest is
* compounded back into the deposit, so the maturity value is principal plus interest.</li>
* <li>{@link #SPECIAL} — the monthly income scheme. Interest is posted monthly and swept out to the
* customer's linked savings account, which is why a special deposit cannot be opened without one;
* the deposit itself matures at its principal, the interest having already been paid away.</li>
* </ul>
*
* <p>
* The database column is a string rather than an enum ordinal, so the names here are the stored
* values and must not be renamed. {@link #fromString(String)} is lenient about case and blanks
* because the column carries a default of SINGLE and older products predate the column entirely.
*/
public enum FixedDepositType {
/** Interest is held in the deposit and paid at maturity. The default for a product that names none. */
SINGLE,
/** Interest is compounded into the deposit; the maturity value includes it. */
DOUBLE,
/** Interest is posted monthly and transferred to the linked savings account. */
SPECIAL;
/**
* The scheme named by a stored {@code fd_type}, defaulting to {@link #SINGLE}.
*
* <p>
* A null, blank or unrecognised value reads as SINGLE: that is the column's own default, and a
* product carrying something else is a misconfiguration that must not stop its customers' interest
* from being reported.
*/
public static FixedDepositType fromString(final String fdType) {
if (fdType == null || fdType.isBlank()) {
return SINGLE;
}
for (final FixedDepositType candidate : values()) {
if (candidate.name().equalsIgnoreCase(fdType.trim())) {
return candidate;
}
}
return SINGLE;
}
public static boolean isValid(final String fdType) {
if (fdType == null || fdType.isBlank()) {
return false;
}
for (final FixedDepositType candidate : values()) {
if (candidate.name().equalsIgnoreCase(fdType.trim())) {
return true;
}
}
return false;
}
/** Whether interest leaves the deposit for the linked savings account each time it is posted. */
public boolean isPaidOutMonthly() {
return this == SPECIAL;
}
/** Whether a posting of interest adds to the deposit's own balance. */
public boolean isRetainedInDeposit() {
return this != SPECIAL;
}
/** What a customer sees: "FD Special", "FD Double", "FD Single". */
public String displayName() {
return "FD " + name().charAt(0) + name().substring(1).toLowerCase(Locale.ENGLISH);
}
}
@@ -84,4 +84,8 @@ public final class LedgerTxnPrefix {
// ── Savings ───────────────────────────────────────────────────────────────
/** Pooled savings interest posting for one product and date. */
public static final String SAVINGS_INTEREST_POOLED = "SAVINT";
// ── Fixed deposits ────────────────────────────────────────────────────────
/** Approved fixed deposit interest posting report, for one product, branch and date. */
public static final String FD_INTEREST_POSTED = "FDINT";
}
@@ -191,6 +191,16 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
return property.isEnabled();
}
/**
* Read on every run of the interest posting job and of the day close, so the two paths can never
* both pay the same deposit: with this on the job leaves fixed deposits alone and they are paid
* from an approved report, with it off the job pays them directly as it always did.
*/
@Override
public boolean isFixedDepositInterestPostingApprovalEnabled() {
return getGlobalConfigurationPropertyData(GlobalConfigurationConstants.FD_INTEREST_POSTING_APPROVAL).isEnabled();
}
@Override
public Integer retrieveFinancialYearBeginningMonth() {
final GlobalConfigurationPropertyData property = getGlobalConfigurationPropertyData(
@@ -48,6 +48,8 @@ import org.apache.fineract.portfolio.cashreport.service.VaultPositionService;
import org.apache.fineract.portfolio.denominationmaster.service.CountedCashLedger;
import org.apache.fineract.portfolio.savings.dailyinterest.SavingsDailyInterestOrchestrator;
import org.apache.fineract.portfolio.savings.dailyinterest.SavingsInterestPostingReportService;
import org.apache.fineract.portfolio.savings.fdinterest.FixedDepositInterestPostingOrchestrator;
import org.apache.fineract.portfolio.savings.fdinterest.FixedDepositInterestPostingReportService;
import org.apache.fineract.useradministration.domain.AppUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@@ -91,6 +93,8 @@ public class BranchDayRegisterApiResource {
private final VaultPositionService vaultPositionService;
private final SavingsInterestPostingReportService interestPostingReportService;
private final SavingsDailyInterestOrchestrator savingsDailyInterestOrchestrator;
private final FixedDepositInterestPostingReportService fdInterestPostingReportService;
private final FixedDepositInterestPostingOrchestrator fdInterestPostingOrchestrator;
private final Gson gson = new Gson();
// ── GET /v1/branchday ── the register itself ──────────────────────────────
@@ -232,6 +236,16 @@ public class BranchDayRegisterApiResource {
result.put("denominationIn", countedIn);
result.put("denominationOut", countedOut);
// What will stop this close, so the screen can say so before the button is pressed rather than
// after. The same lists closeDay() refuses on, read-only here.
result.put("savingsInterestPending", interestPostingReportService.reportsBlockingDayClose(officeId, businessDate));
// One call for the deposits: what is blocking, and the products and amounts behind it, so the
// branch sees what it is being asked to approve without leaving the close screen. Pricing a
// branch's deposits is the expensive part and is done once.
final Map<String, Object> fdInterest = fdInterestPostingReportService.dayCloseInterestView(officeId, businessDate);
result.put("fdInterestPending", fdInterest.get("pending"));
result.put("fdInterestDue", fdInterest.get("due"));
return gson.toJson(result);
}
@@ -610,6 +624,17 @@ public class BranchDayRegisterApiResource {
+ ". Approve it under Reports → Interest Posting Reports, then close the day.");
}
// ── And its fixed deposit interest reports, on the same grounds ──
// Only while deposits are on the approval path at all; with that switched off the posting job
// pays them directly and there is nothing here to approve.
final List<String> fdInterestPending = fdInterestPostingReportService.reportsBlockingDayClose(officeId, businessDate);
if (!fdInterestPending.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.branchday.fd.interest.report.pending",
"Cannot close the day — this branch's fixed deposit interest posting report is not approved for: "
+ String.join(", ", fdInterestPending)
+ ". Approve it under Reports → FD Interest Posting Reports, then close the day.");
}
// ── The head office closes last ──
// Every branch that opened the day closes first and posts its own interest; a branch that
// never opened is not waited for.
@@ -745,6 +770,23 @@ public class BranchDayRegisterApiResource {
}
}
// ── And the branch's approved fixed deposit interest, the same way ──
// Separate from the savings run so a deposit product with a GL problem cannot stop savings
// interest that has already posted cleanly, and so the refusal names which of the two failed.
final List<Long> fdToPost = new ArrayList<>(fdInterestPostingReportService.approvedReportIds(officeId, businessDate));
if (isHeadOffice) {
fdToPost.addAll(fdInterestPostingReportService.approvedReportIdsOfBranchesNotOpened(businessDate, officeId));
}
if (!fdToPost.isEmpty()) {
log.info("Day close {}: office {} posting {} approved FD interest report(s)", businessDate, officeId, fdToPost.size());
final List<String> fdFailures = fdInterestPostingOrchestrator.postReports(fdToPost);
if (!fdFailures.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.branchday.fd.interest.posting.failed",
"Cannot close the day — fixed deposit interest could not be posted: " + String.join("; ", fdFailures)
+ ". The report is still approved; fix the cause and close the day again.");
}
}
// "closed_at IS NULL" in the WHERE, not just the read above: the already-closed check and
// this write are two separate statements, so two managers pressing Close at once (or one
// double-click) both got past the check. The second UPDATE then overwrote the first's
@@ -0,0 +1,93 @@
/**
* 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.savings.fdinterest;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Posts approved fixed deposit interest reports, one transaction each.
*
* <p>
* Called as a branch closes its day. A report that cannot be posted does not take the others down
* with it: its failure is written to the report, which stays APPROVED, and reported back to the
* caller so the close can be refused with a reason the branch can act on. Closing again once the
* cause is fixed posts it.
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class FixedDepositInterestPostingOrchestrator {
private final JdbcTemplate jdbcTemplate;
private final FixedDepositInterestPostingService postingService;
private final FixedDepositInterestPostingReportService reportService;
private final PlatformTransactionManager transactionManager;
/**
* Posts each report in a transaction of its own.
*
* @return one message per report that could not be posted, empty where all of them were
*/
public List<String> postReports(final List<Long> reportIds) {
final TransactionTemplate newTransaction = new TransactionTemplate(this.transactionManager);
newTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
final List<String> failures = new ArrayList<>();
for (final Long reportId : reportIds) {
final Map<String, Object> report = this.jdbcTemplate
.queryForMap("SELECT fd_product_id, posting_date FROM m_fd_interest_posting_report WHERE id = ?", reportId);
final long productId = ((Number) report.get("fd_product_id")).longValue();
final LocalDate postingDate = ((java.sql.Date) report.get("posting_date")).toLocalDate();
try {
final BigDecimal paid = newTransaction.execute(status -> this.postingService.postReport(reportId));
log.info("FD interest: report {} for product {} posted {} for {}", reportId, productId, paid, postingDate);
} catch (final RuntimeException e) {
log.error("FD interest: report {} for product {} failed to post for {}", reportId, productId, postingDate, e);
newTransaction.executeWithoutResult(status -> {
this.reportService.recordPostingFailure(reportId, e.getMessage());
this.jdbcTemplate.update("""
UPDATE m_fd_interest_posting_run
SET status = 'FAILED', failure_reason = ?
WHERE report_id = ?
""", truncate(e.getMessage()), reportId);
});
failures.add("report " + reportId + " (product " + productId + "): " + e.getMessage());
}
}
return failures;
}
private static String truncate(final String reason) {
if (reason == null) {
return "unknown failure";
}
return reason.length() > 1000 ? reason.substring(0, 1000) : reason;
}
}
@@ -0,0 +1,893 @@
/**
* 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.savings.fdinterest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.portfolio.savings.FixedDepositType;
import org.apache.fineract.portfolio.savings.SavingsAccountTransactionType;
import org.apache.fineract.portfolio.savings.dailyinterest.SavingsInterestPostingReportService;
import org.apache.fineract.portfolio.savings.data.SavingsAccountData;
import org.apache.fineract.portfolio.savings.data.SavingsAccountTransactionData;
import org.apache.fineract.portfolio.savings.service.SavingsAccountReadPlatformService;
import org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformService;
import org.apache.fineract.useradministration.domain.AppUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
/**
* The fixed deposit interest posting report: what each deposit of one branch will be paid on its
* product's posting date, put in front of that branch before any money moves.
*
* <p>
* One report per branch and product. On a posting date the noon job generates one for every branch
* holding deposits with interest due; a user of that branch may regenerate it at any time — the
* previous report is superseded, not overwritten — and a second user of that branch approves it. The
* branch's approved reports are posted when it closes its day, and until they are approved it cannot
* close. The head office closes last, once every branch open that day has closed.
*
* <p>
* Where the interest ends up is the product's scheme, and the report says so deposit by deposit:
* a {@link FixedDepositType#SPECIAL} deposit's interest leaves for the customer's linked savings
* account, while {@link FixedDepositType#SINGLE} and {@link FixedDepositType#DOUBLE} keep it in the
* deposit until maturity. A checker approving a special product's report is approving payments out
* of the bank, which is why the destination account is on every line.
*
* <p>
* Unlike savings, a deposit has no daily interest ledger to read a figure from: the amount is worked
* out by the same interest engine the posting job uses, run here without the step that writes it
* down. That makes generation the expensive part and it is done once per run, not once per screen.
*/
@Service
@Slf4j
public class FixedDepositInterestPostingReportService {
public static final String GENERATED = "GENERATED";
public static final String APPROVED = "APPROVED";
public static final String POSTED = "POSTED";
public static final String SUPERSEDED = "SUPERSEDED";
private static final int MONEY_SCALE = 2;
private static final RoundingMode MONEY_ROUNDING = RoundingMode.HALF_EVEN;
private final JdbcTemplate jdbcTemplate;
private final SavingsAccountReadPlatformService savingsAccountReadPlatformService;
private final SavingsAccountWritePlatformService savingsAccountWritePlatformService;
private final ConfigurationDomainService configurationDomainService;
private final FixedDepositInterestPostingService postingService;
/**
* Borrowed for the branch rules — which branch may act for which, and whether a branch is working
* today. They are the same rules as for savings and must stay the same: a bank where a branch
* could approve its deposits but not its savings, or the other way round, would be answering the
* question "who closes the day" twice with two different answers.
*/
private final SavingsInterestPostingReportService branchAuthority;
private final TransactionTemplate transactionTemplate;
public FixedDepositInterestPostingReportService(final JdbcTemplate jdbcTemplate,
final SavingsAccountReadPlatformService savingsAccountReadPlatformService,
final SavingsAccountWritePlatformService savingsAccountWritePlatformService,
final ConfigurationDomainService configurationDomainService, final FixedDepositInterestPostingService postingService,
final SavingsInterestPostingReportService branchAuthority, final PlatformTransactionManager transactionManager) {
this.jdbcTemplate = jdbcTemplate;
this.savingsAccountReadPlatformService = savingsAccountReadPlatformService;
this.savingsAccountWritePlatformService = savingsAccountWritePlatformService;
this.configurationDomainService = configurationDomainService;
this.postingService = postingService;
this.branchAuthority = branchAuthority;
// A transaction of its own, as for savings: the noon job runs inside the batch step's
// transaction, and a report committed separately is on screen at once and holds no row locks
// for the rest of the run.
this.transactionTemplate = new TransactionTemplate(transactionManager);
this.transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
/**
* One posting due on one deposit, before it is written down — a deposit with two unpaid periods
* has two of these, one per period, because that is how the engine will look for them again.
*/
public record DueLine(Long accountId, String accountNo, String clientName, Long officeId, Long productId, String fdType,
LocalDate postingDate, BigDecimal interest, BigDecimal balanceBefore, BigDecimal depositAmount, BigDecimal interestRate,
LocalDate maturityDate, Long payoutSavingsAccountId, String payoutAccountNo) {}
/** One unpaid posting the engine worked out: the date it belongs to and what it comes to. */
private record ComputedPosting(Long accountId, LocalDate postingDate, BigDecimal interest) {}
/** A product with interest due in one branch. */
private record DueKey(Long productId, Long officeId) {}
// ── computing what is due ────────────────────────────────────────────────────────────────────
/**
* What every candidate fixed deposit has earned and not yet been paid, as at the posting date.
*
* <p>
* The interest engine is run exactly as the posting job runs it, and then stopped: it returns the
* deposit with its new interest transactions attached in memory, and only the job's batch write
* turns those into rows. Nothing here writes one, so this can be called as often as a screen asks.
*
* <p>
* A deposit the engine finds nothing for — its posting period has not ended yet — contributes no
* line. That is also what makes "due" meaningful at all for a deposit: the cheap database test
* that selects candidates cannot tell a period end from a day in the middle of one.
*
* @param officeId
* one branch, or null for every branch
* @param productId
* one product, or null for every product
*/
public List<DueLine> computeDueInterest(final LocalDate postingDate, final Long officeId, final Long productId) {
final boolean backdatedTxnsAllowedTill = this.configurationDomainService.retrievePivotDateConfig();
final List<SavingsAccountData> candidates = this.savingsAccountReadPlatformService
.retrieveFixedDepositsDueForInterestPosting(backdatedTxnsAllowedTill, postingDate, officeId, productId);
if (candidates.isEmpty()) {
return List.of();
}
final List<ComputedPosting> postings = new ArrayList<>();
for (final SavingsAccountData deposit : candidates) {
postings.addAll(computePostingsFor(deposit, backdatedTxnsAllowedTill));
}
if (postings.isEmpty()) {
return List.of();
}
return describe(postings);
}
/**
* One deposit's unpaid postings, each with the date the engine gave it.
*
* <p>
* The date is kept, never flattened away. The engine decides a period has already been paid by
* looking for an interest transaction on exactly that date, so a posting recorded under any other
* date would be invisible to it and the period would be computed, reported and paid a second time.
* For the same reason two unpaid periods stay two postings rather than being added together.
*
* <p>
* A deposit the engine cannot price — a chart it cannot read, a rate it cannot resolve — is left
* out of the report rather than stopping the branch's other customers from being reported. Missing
* from the report is visible; a wrong figure quietly paid is not.
*/
private List<ComputedPosting> computePostingsFor(final SavingsAccountData deposit, final boolean backdatedTxnsAllowedTill) {
final SavingsAccountData computed;
try {
computed = this.savingsAccountWritePlatformService.postInterest(deposit, false, null, backdatedTxnsAllowedTill);
} catch (final RuntimeException e) {
log.error("FD interest report: deposit {} could not be priced and is left out of the report", deposit.getId(), e);
return List.of();
}
if (computed == null || computed.getSavingsAccountTransactionData() == null) {
return List.of();
}
final List<ComputedPosting> postings = new ArrayList<>();
for (final SavingsAccountTransactionData transaction : computed.getSavingsAccountTransactionData()) {
// Only what this run has just worked out: a transaction with an id is already in the
// account and has been paid.
if (transaction.getId() != null || transaction.getTransactionType() == null
|| transaction.getTransactionType().getId() == null) {
continue;
}
final SavingsAccountTransactionType type = SavingsAccountTransactionType
.fromInt(transaction.getTransactionType().getId().intValue());
if (!type.isInterestPosting() || transaction.getAmount() == null
|| transaction.getAmount().compareTo(BigDecimal.ZERO) <= 0 || transaction.getTransactionDate() == null) {
continue;
}
postings.add(new ComputedPosting(deposit.getId(), transaction.getTransactionDate(), transaction.getAmount()));
}
return postings;
}
/**
* The deposits behind the computed figures, with what a checker needs to judge them: the principal,
* the rate, the maturity date, and for a special deposit the savings account its interest leaves
* for.
*/
private List<DueLine> describe(final List<ComputedPosting> postings) {
final String ids = postings.stream().map(ComputedPosting::accountId).distinct().map(String::valueOf)
.collect(Collectors.joining(","));
final List<Map<String, Object>> rows = this.jdbcTemplate.queryForList("""
SELECT sa.id AS account_id, sa.account_no, sa.product_id,
COALESCE(c.display_name, g.display_name) AS client_name,
COALESCE(c.office_id, g.office_id) AS office_id,
COALESCE(sa.account_balance_derived, 0) AS balance,
sa.nominal_annual_interest_rate AS interest_rate,
sp.fd_type, datp.deposit_amount, datp.maturity_date,
datp.transfer_interest_to_linked_account, datp.transfer_to_savings_account_id,
ls.account_no AS payout_account_no
FROM m_savings_account sa
JOIN m_savings_product sp ON sp.id = sa.product_id
LEFT JOIN m_deposit_account_term_and_preclosure datp ON datp.savings_account_id = sa.id
LEFT JOIN m_client c ON c.id = sa.client_id
LEFT JOIN m_group g ON g.id = sa.group_id
LEFT JOIN m_savings_account ls ON ls.id = datp.transfer_to_savings_account_id
WHERE sa.id IN (%s)
ORDER BY sa.account_no
""".formatted(ids));
final Map<Long, Map<String, Object>> byAccount = new LinkedHashMap<>();
for (final Map<String, Object> row : rows) {
byAccount.put(((Number) row.get("account_id")).longValue(), row);
}
final List<DueLine> lines = new ArrayList<>();
for (final ComputedPosting posting : postings) {
final Map<String, Object> row = byAccount.get(posting.accountId());
if (row == null) {
continue;
}
final Object officeId = row.get("office_id");
if (officeId == null) {
// A deposit whose customer has no branch cannot be put on any branch's report.
log.warn("FD interest report: deposit {} has no branch and is left out", posting.accountId());
continue;
}
final FixedDepositType fdType = FixedDepositType.fromString((String) row.get("fd_type"));
// The destination is only meaningful where the scheme actually pays out and the deposit
// names an account to pay into.
final boolean paysOut = fdType.isPaidOutMonthly() && Boolean.TRUE.equals(row.get("transfer_interest_to_linked_account"));
final Object payoutId = paysOut ? row.get("transfer_to_savings_account_id") : null;
lines.add(new DueLine(posting.accountId(), (String) row.get("account_no"), (String) row.get("client_name"),
((Number) officeId).longValue(), ((Number) row.get("product_id")).longValue(), fdType.name(),
posting.postingDate(), posting.interest(), (BigDecimal) row.get("balance"),
(BigDecimal) row.get("deposit_amount"), (BigDecimal) row.get("interest_rate"),
toLocalDate(row.get("maturity_date")), payoutId == null ? null : ((Number) payoutId).longValue(),
paysOut ? (String) row.get("payout_account_no") : null));
}
return lines;
}
private static LocalDate toLocalDate(final Object value) {
return value instanceof java.sql.Date date ? date.toLocalDate() : null;
}
// ── generation ───────────────────────────────────────────────────────────────────────────────
/**
* The noon job: generates a report for every branch and product with deposit interest due that
* does not already have one.
*
* <p>
* The interest is worked out once for the whole bank and then split by branch and product, since
* pricing a deposit is the expensive part and doing it per report would price the same portfolio
* many times over. Each report is still written in its own transaction, so one that cannot be — a
* GL mapping missing, say — does not stop the others; the failures are raised together at the end
* so the job is recorded as failed.
*
* @return the ids of the reports generated
*/
public List<Long> generateDue(final LocalDate postingDate) {
final List<DueLine> due = computeDueInterest(postingDate, null, null);
final List<Long> generated = new ArrayList<>();
final List<String> failures = new ArrayList<>();
for (final Map.Entry<DueKey, List<DueLine>> group : groupByProductAndOffice(due).entrySet()) {
final DueKey key = group.getKey();
if (activeReportId(key.productId(), key.officeId(), postingDate) != null) {
continue;
}
try {
generated.add(transactionTemplate
.execute(status -> persistReport(key.productId(), key.officeId(), postingDate, "AUTO", null, group.getValue())));
} catch (final RuntimeException e) {
log.error("FD interest report: product {} branch {} could not be reported for {}", key.productId(), key.officeId(),
postingDate, e);
failures.add("product " + key.productId() + " branch " + key.officeId() + ": " + e.getMessage());
}
}
if (!failures.isEmpty()) {
throw new IllegalStateException("Fixed deposit interest posting report could not be generated on " + postingDate + " for "
+ failures.size() + " report(s): " + String.join("; ", failures));
}
return generated;
}
/**
* Generates the report afresh for one branch and product, on the user's request.
*
* <p>
* Not for a date after the business date, whose interest has not been earned yet. A posted report
* cannot be regenerated: its money has moved. An approved one can, and has to be approved again.
*/
public Long regenerate(final Long productId, final Long officeId, final LocalDate postingDate, final AppUser user) {
final LocalDate businessDate = DateUtils.getBusinessLocalDate();
if (postingDate.isAfter(businessDate)) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.future.date",
"The report for " + postingDate + " cannot be generated before that date.");
}
authorize(user, officeId, businessDate);
final List<DueLine> due = computeDueInterest(postingDate, officeId, productId);
return transactionTemplate.execute(status -> persistReport(productId, officeId, postingDate, "MANUAL", user.getId(), due));
}
/**
* Approves a generated report, by someone other than the user who generated it.
*
* <p>
* The two-user rule is the point of the report. Interest posting moves money to customers — and
* out of the bank entirely, for a special deposit paying into a linked savings account — so the
* figures are put up by one person and signed off by another. A branch that cannot find a second
* user has a staffing problem, not a software one; the alternative is a control that any single
* user can walk straight through.
*
* <p>
* A user of the report's branch approves it; the head office may approve it only for a branch that
* did not open that day, and the report records that it did.
*/
public void approve(final Long reportId, final AppUser user) {
final List<Map<String, Object>> found = this.jdbcTemplate
.queryForList("SELECT office_id, generated_by, status FROM m_fd_interest_posting_report WHERE id = ?", reportId);
if (found.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.not.found",
"Fixed deposit interest posting report " + reportId + " does not exist.");
}
final Map<String, Object> report = found.get(0);
final Long officeId = ((Number) report.get("office_id")).longValue();
final Object generatedBy = report.get("generated_by");
if (generatedBy != null && ((Number) generatedBy).longValue() == user.getId()) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.same.maker.checker",
"You generated this report, so you cannot approve it. Another user of this branch has to approve the interest "
+ "before it can be posted. Regenerating it yourself will not change that.");
}
final boolean onBehalf = authorize(user, officeId, DateUtils.getBusinessLocalDate());
final int approved = this.jdbcTemplate.update("""
UPDATE m_fd_interest_posting_report
SET status = 'APPROVED', approved_by = ?, approved_at = CURRENT_TIMESTAMP, approved_on_behalf = ?
WHERE id = ? AND status = 'GENERATED'
""", user.getId(), onBehalf, reportId);
if (approved == 0) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.not.generated",
"Only a report in GENERATED status can be approved. Reload the report — it may have been approved, "
+ "regenerated or posted already.");
}
}
/**
* Writes one report and its lines, superseding whatever stood for that branch, product and date.
*
* <p>
* Runs inside the caller's transaction. Each deposit's interest is rounded to two decimals and the
* paise the rounding loses is given to the largest deposit, where it is proportionally smallest,
* so the report's total is exactly what the branch will pay out.
*/
private Long persistReport(final Long productId, final Long officeId, final LocalDate postingDate, final String mode,
final Long userId, final List<DueLine> lines) {
final List<Map<String, Object>> previous = this.jdbcTemplate.queryForList("""
SELECT id, status FROM m_fd_interest_posting_report
WHERE fd_product_id = ? AND office_id = ? AND posting_date = ? AND status <> 'SUPERSEDED'
FOR UPDATE
""", productId, officeId, postingDate);
for (final Map<String, Object> report : previous) {
if (POSTED.equals(report.get("status"))) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.already.posted",
"Fixed deposit interest for this product and branch on " + postingDate + " has already been posted; the report"
+ " cannot be regenerated.");
}
}
if (lines.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.nothing.due",
"No fixed deposit interest is due for this product in this branch on " + postingDate + ".");
}
this.jdbcTemplate.update("""
UPDATE m_fd_interest_posting_report SET status = 'SUPERSEDED'
WHERE fd_product_id = ? AND office_id = ? AND posting_date = ? AND status IN ('GENERATED', 'APPROVED')
""", productId, officeId, postingDate);
// Refused here, before anybody approves figures that could never be posted.
final FixedDepositInterestPostingService.PostingGlAccounts gls = this.postingService.resolvePostingGlAccounts(productId);
// Oldest period first, so a deposit owed two postings is written down in the order the money
// would actually have reached it, and each line's opening balance follows the one before.
final List<DueLine> ordered = lines.stream()
.sorted(Comparator.comparing(DueLine::postingDate).thenComparing(DueLine::accountNo,
Comparator.nullsLast(Comparator.naturalOrder())))
.toList();
// Rounded per line, not per deposit: one deposit can hold more than one line here.
final List<BigDecimal> rounded = new ArrayList<>(ordered.size());
BigDecimal grossTotal = BigDecimal.ZERO;
BigDecimal roundedTotal = BigDecimal.ZERO;
for (final DueLine line : ordered) {
final BigDecimal value = line.interest().setScale(MONEY_SCALE, MONEY_ROUNDING);
rounded.add(value);
grossTotal = grossTotal.add(line.interest());
roundedTotal = roundedTotal.add(value);
}
final BigDecimal pooled = grossTotal.setScale(MONEY_SCALE, MONEY_ROUNDING);
final BigDecimal residual = pooled.subtract(roundedTotal);
if (residual.signum() != 0) {
int largest = 0;
for (int i = 1; i < ordered.size(); i++) {
final BigDecimal candidate = ordered.get(i).balanceBefore();
final BigDecimal best = ordered.get(largest).balanceBefore();
if ((candidate == null ? BigDecimal.ZERO : candidate).compareTo(best == null ? BigDecimal.ZERO : best) > 0) {
largest = i;
}
}
rounded.set(largest, rounded.get(largest).add(residual));
}
final String fdType = ordered.get(0).fdType();
final Long reportId = this.jdbcTemplate.queryForObject("""
INSERT INTO m_fd_interest_posting_report
(fd_product_id, fd_type, office_id, posting_date, status, total_interest, account_count,
payable_gl_account_id, paid_gl_account_id, generation_mode, generated_by, generated_at)
VALUES (?, ?, ?, ?, 'GENERATED', ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
RETURNING id
""", Long.class, productId, fdType, officeId, postingDate, pooled, ordered.size(), gls.payableGl(), gls.paidGl(), mode,
userId);
// Where a deposit holds two postings, the second opens on the balance the first leaves behind.
final Map<Long, BigDecimal> runningBalance = new LinkedHashMap<>();
for (int i = 0; i < ordered.size(); i++) {
final DueLine line = ordered.get(i);
final BigDecimal interest = rounded.get(i);
final BigDecimal opening = line.balanceBefore() == null ? BigDecimal.ZERO
: line.balanceBefore().setScale(MONEY_SCALE, MONEY_ROUNDING);
final BigDecimal before = runningBalance.getOrDefault(line.accountId(), opening);
// The deposit's balance the moment the interest is credited. A special deposit's interest
// does not stay there — the existing transfer-interest-to-savings job sweeps it to the
// linked account afterwards, which is a transaction of its own — so the destination is on
// the line rather than being netted off here, where it would hide a payment the checker is
// approving.
final BigDecimal after = before.add(interest);
runningBalance.put(line.accountId(), after);
this.jdbcTemplate.update("""
INSERT INTO m_fd_interest_posting_report_line
(report_id, fd_account_id, account_no, client_name, office_id, interest_posting_date, interest_amount,
balance_before, balance_after, deposit_amount, interest_rate, maturity_date, payout_savings_account_id,
payout_account_no)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", reportId, line.accountId(), line.accountNo(), line.clientName(), line.officeId(), line.postingDate(), interest,
before, after, line.depositAmount(), line.interestRate(), line.maturityDate(), line.payoutSavingsAccountId(),
line.payoutAccountNo());
}
log.info("FD interest report {}: product {} ({}) branch {} on {} ({}) — {} across {} posting(s)", reportId, productId, fdType,
officeId, postingDate, mode, pooled, ordered.size());
return reportId;
}
private Map<DueKey, List<DueLine>> groupByProductAndOffice(final List<DueLine> lines) {
final Map<DueKey, List<DueLine>> grouped = new LinkedHashMap<>();
for (final DueLine line : lines) {
grouped.computeIfAbsent(new DueKey(line.productId(), line.officeId()), key -> new ArrayList<>()).add(line);
}
return grouped;
}
// ── day close ────────────────────────────────────────────────────────────────────────────────
/**
* What stops one branch from closing the day: a product with deposit interest due in the branch
* and no approved (or posted) report for the date, and any older report of the branch still
* awaiting approval — one left from a day the branch did not open. A report that was never
* generated blocks the close too, which is why the due figures are worked out here rather than
* trusting the noon job to have run.
*/
public List<String> reportsBlockingDayClose(final Long officeId, final LocalDate businessDate) {
if (!this.configurationDomainService.isFixedDepositInterestPostingApprovalEnabled()) {
return List.of();
}
return blockingFrom(officeId, businessDate, groupByProductAndOffice(computeDueInterest(businessDate, officeId, null)));
}
/**
* What the day close screen shows a branch about its deposits: what is blocking the close, and the
* products and amounts behind it.
*
* <p>
* Both come out of one pricing run, because working out a branch's deposit interest is the
* expensive part and the screen asks for both at once.
*
* @return {@code pending} — the same list {@link #reportsBlockingDayClose} returns — and {@code due},
* one row per product with its deposit count and total
*/
public Map<String, Object> dayCloseInterestView(final Long officeId, final LocalDate businessDate) {
final Map<String, Object> view = new LinkedHashMap<>();
if (!this.configurationDomainService.isFixedDepositInterestPostingApprovalEnabled()) {
view.put("pending", List.of());
view.put("due", List.of());
return view;
}
final Map<DueKey, List<DueLine>> grouped = groupByProductAndOffice(computeDueInterest(businessDate, officeId, null));
view.put("pending", blockingFrom(officeId, businessDate, grouped));
final List<Map<String, Object>> due = new ArrayList<>();
for (final Map.Entry<DueKey, List<DueLine>> group : grouped.entrySet()) {
BigDecimal total = BigDecimal.ZERO;
for (final DueLine line : group.getValue()) {
total = total.add(line.interest());
}
final Map<String, Object> row = new LinkedHashMap<>();
row.put("productId", group.getKey().productId());
row.put("productName", productName(group.getKey().productId()));
row.put("fdType", group.getValue().get(0).fdType());
row.put("accountCount", group.getValue().size());
row.put("totalInterest", total.setScale(MONEY_SCALE, MONEY_ROUNDING));
row.put("reportStatus", reportStatus(group.getKey().productId(), officeId, businessDate));
due.add(row);
}
view.put("due", due);
return view;
}
/** Products due with no approved report, plus any of the branch's reports still awaiting approval. */
private List<String> blockingFrom(final Long officeId, final LocalDate businessDate, final Map<DueKey, List<DueLine>> grouped) {
final Set<String> blocking = new LinkedHashSet<>();
for (final DueKey due : grouped.keySet()) {
final Long settled = this.jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM m_fd_interest_posting_report
WHERE fd_product_id = ? AND office_id = ? AND posting_date = ? AND status IN ('APPROVED', 'POSTED')
""", Long.class, due.productId(), officeId, businessDate);
if (settled == null || settled == 0) {
blocking.add(productName(due.productId()) + " (" + businessDate + ")");
}
}
for (final Map<String, Object> pending : this.jdbcTemplate.queryForList("""
SELECT p.name, r.posting_date FROM m_fd_interest_posting_report r
JOIN m_savings_product p ON p.id = r.fd_product_id
WHERE r.office_id = ? AND r.status = 'GENERATED' AND r.posting_date <= ?
ORDER BY r.posting_date
""", officeId, businessDate)) {
blocking.add(pending.get("name") + " (" + pending.get("posting_date") + ")");
}
return new ArrayList<>(blocking);
}
/** Where this product's report for the branch and date stands, or NONE where there is not one. */
private String reportStatus(final Long productId, final Long officeId, final LocalDate postingDate) {
final List<String> status = this.jdbcTemplate.queryForList("""
SELECT status FROM m_fd_interest_posting_report
WHERE fd_product_id = ? AND office_id = ? AND posting_date = ? AND status <> 'SUPERSEDED'
ORDER BY id DESC LIMIT 1
""", String.class, productId, officeId, postingDate);
return status.isEmpty() ? "NONE" : status.get(0);
}
/** The branch's approved reports, posted when it closes the day. */
public List<Long> approvedReportIds(final Long officeId, final LocalDate upToDate) {
return this.jdbcTemplate.queryForList("""
SELECT id FROM m_fd_interest_posting_report
WHERE status = 'APPROVED' AND office_id = ? AND posting_date <= ?
ORDER BY posting_date, fd_product_id
""", Long.class, officeId, upToDate);
}
/**
* Approved reports of branches that did not open on the date — what the head office posts at its
* own close, the branches having no close of their own that day.
*/
public List<Long> approvedReportIdsOfBranchesNotOpened(final LocalDate businessDate, final Long headOfficeId) {
return this.jdbcTemplate.queryForList("""
SELECT r.id FROM m_fd_interest_posting_report r
WHERE r.status = 'APPROVED' AND r.posting_date <= ? AND r.office_id <> ?
AND NOT EXISTS (SELECT 1 FROM m_branch_day_register b WHERE b.office_id = r.office_id
AND (b.business_date = ? OR (b.closed_at IS NULL AND b.business_date <= ?)))
ORDER BY r.posting_date, r.office_id, r.fd_product_id
""", Long.class, businessDate, headOfficeId, businessDate, businessDate);
}
/** Records why an approved report could not be posted; it stays APPROVED for the next attempt. */
public void recordPostingFailure(final Long reportId, final String reason) {
this.jdbcTemplate.update("UPDATE m_fd_interest_posting_report SET failure_reason = ? WHERE id = ?",
reason == null ? "unknown failure" : reason.length() > 1000 ? reason.substring(0, 1000) : reason, reportId);
}
// ── reading ──────────────────────────────────────────────────────────────────────────────────
/**
* Reports for the screen. {@code scope} "own" (the default) is the user's own branch; "others", for
* a head office user, is every other branch (or one, with officeId). canAct says whether this user
* may regenerate the report, canApprove whether they may approve it, and blockedReason why not.
*/
public List<Map<String, Object>> list(final LocalDate postingDate, final String status, final Long productId, final Long officeId,
final String scope, final AppUser user) {
final Long userOffice = officeOf(user);
final boolean others = "others".equalsIgnoreCase(scope) && this.branchAuthority.isHeadOffice(userOffice);
final Long branch = others ? officeId : userOffice;
final StringBuilder sql = new StringBuilder("""
SELECT r.id, r.fd_product_id AS "productId", p.name AS "productName", r.fd_type AS "fdType",
r.office_id AS "officeId", o.name AS "officeName", r.posting_date AS "postingDate", r.status,
r.total_interest AS "totalInterest", r.account_count AS "accountCount",
r.generation_mode AS "generationMode", r.generated_at AS "generatedAt", gu.username AS "generatedBy",
r.generated_by AS "generatedById", r.approved_at AS "approvedAt", au.username AS "approvedBy",
r.approved_on_behalf AS "approvedOnBehalf", r.posted_at AS "postedAt", r.failure_reason AS "failureReason"
FROM m_fd_interest_posting_report r
JOIN m_savings_product p ON p.id = r.fd_product_id
LEFT JOIN m_office o ON o.id = r.office_id
LEFT JOIN m_appuser gu ON gu.id = r.generated_by
LEFT JOIN m_appuser au ON au.id = r.approved_by
WHERE 1 = 1
""");
final List<Object> params = new ArrayList<>();
if (postingDate != null) {
sql.append(" AND r.posting_date = ?");
params.add(postingDate);
}
if (status != null && !status.isBlank()) {
sql.append(" AND r.status = ?");
params.add(status.trim().toUpperCase());
} else {
sql.append(" AND r.status <> 'SUPERSEDED'");
}
if (productId != null) {
sql.append(" AND r.fd_product_id = ?");
params.add(productId);
}
if (branch != null) {
sql.append(" AND r.office_id = ?");
params.add(branch);
}
if (others) {
sql.append(" AND r.office_id <> ?");
params.add(userOffice);
}
sql.append(" ORDER BY r.posting_date DESC, o.name, p.name, r.id DESC");
final LocalDate businessDate = DateUtils.getBusinessLocalDate();
final List<Map<String, Object>> rows = new ArrayList<>();
for (final Map<String, Object> row : this.jdbcTemplate.queryForList(sql.toString(), params.toArray())) {
final Map<String, Object> out = new LinkedHashMap<>(row);
final Object reportOffice = row.get("officeId");
final String blocked = reportOffice == null ? "No branch on this report."
: actBlockedReason(userOffice, ((Number) reportOffice).longValue(), businessDate);
out.put("canAct", blocked == null);
out.put("blockedReason", blocked);
// The maker cannot be the checker, and the screen says so before the button is pressed.
final Object generatedById = row.get("generatedById");
final boolean ownWork = generatedById != null && user != null && ((Number) generatedById).longValue() == user.getId();
out.put("canApprove", blocked == null && !ownWork && GENERATED.equals(row.get("status")));
out.put("approveBlockedReason",
ownWork ? "You generated this report — another user has to approve it." : blocked);
out.remove("generatedById");
rows.add(out);
}
return rows;
}
public Map<String, Object> detail(final Long reportId) {
final List<Map<String, Object>> found = this.jdbcTemplate.queryForList("""
SELECT r.id, r.fd_product_id AS "productId", p.name AS "productName", r.fd_type AS "fdType",
r.office_id AS "officeId", o.name AS "officeName", r.posting_date AS "postingDate", r.status,
r.total_interest AS "totalInterest", r.account_count AS "accountCount",
r.generation_mode AS "generationMode", r.generated_at AS "generatedAt", gu.username AS "generatedBy",
r.approved_at AS "approvedAt", au.username AS "approvedBy", r.approved_on_behalf AS "approvedOnBehalf",
r.posted_at AS "postedAt", r.failure_reason AS "failureReason",
pg.gl_code AS "payableGlCode", pg.name AS "payableGlName",
dg.gl_code AS "paidGlCode", dg.name AS "paidGlName"
FROM m_fd_interest_posting_report r
JOIN m_savings_product p ON p.id = r.fd_product_id
LEFT JOIN m_office o ON o.id = r.office_id
LEFT JOIN m_appuser gu ON gu.id = r.generated_by
LEFT JOIN m_appuser au ON au.id = r.approved_by
LEFT JOIN acc_gl_account pg ON pg.id = r.payable_gl_account_id
LEFT JOIN acc_gl_account dg ON dg.id = r.paid_gl_account_id
WHERE r.id = ?
""", reportId);
if (found.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.not.found",
"Fixed deposit interest posting report " + reportId + " does not exist.");
}
final Map<String, Object> report = new LinkedHashMap<>(found.get(0));
report.put("lines", this.jdbcTemplate.queryForList("""
SELECT l.fd_account_id AS "fdAccountId", l.account_no AS "accountNo", l.client_name AS "clientName",
l.interest_posting_date AS "interestPostingDate", l.interest_amount AS "interestAmount",
l.balance_before AS "balanceBefore", l.balance_after AS "balanceAfter",
l.deposit_amount AS "depositAmount", l.interest_rate AS "interestRate", l.maturity_date AS "maturityDate",
l.payout_savings_account_id AS "payoutSavingsAccountId", l.payout_account_no AS "payoutAccountNo",
l.payout_transaction_id AS "payoutTransactionId", l.fd_transaction_id AS "fdTransactionId"
FROM m_fd_interest_posting_report_line l
WHERE l.report_id = ?
ORDER BY l.interest_posting_date, l.account_no
""", reportId));
return report;
}
/**
* What each fixed deposit has earned and not been paid, as at the business date — what it would be
* paid if interest were posted today. Read-only: nothing is saved, approved or posted.
*
* <p>
* A branch user sees their own branch; a head office user every branch, or one with officeId.
*/
public List<Map<String, Object>> preview(final Long officeId, final AppUser user) {
final Long userOffice = officeOf(user);
final Long branch = this.branchAuthority.isHeadOffice(userOffice) ? officeId : userOffice;
final List<Map<String, Object>> rows = new ArrayList<>();
for (final DueLine line : computeDueInterest(DateUtils.getBusinessLocalDate(), branch, null)) {
final Map<String, Object> row = new LinkedHashMap<>();
row.put("fdAccountId", line.accountId());
row.put("accountNo", line.accountNo());
row.put("clientName", line.clientName());
row.put("officeId", line.officeId());
row.put("officeName", officeName(line.officeId()));
row.put("productId", line.productId());
row.put("productName", productName(line.productId()));
row.put("fdType", line.fdType());
row.put("interestPostingDate", line.postingDate() == null ? null : line.postingDate().toString());
row.put("depositAmount", line.depositAmount());
row.put("interestRate", line.interestRate());
row.put("maturityDate", line.maturityDate() == null ? null : line.maturityDate().toString());
row.put("balance", line.balanceBefore());
row.put("interest", line.interest().setScale(MONEY_SCALE, MONEY_ROUNDING));
row.put("payoutAccountNo", line.payoutAccountNo());
rows.add(row);
}
return rows;
}
/**
* Branch and product interest for the head office: per report, how many deposits and how much
* interest, and where it stands. Superseded reports are left out.
*/
public List<Map<String, Object>> summary(final LocalDate fromDate, final LocalDate toDate, final Long productId) {
final StringBuilder sql = new StringBuilder("""
SELECT r.id, r.posting_date AS "postingDate", r.office_id AS "officeId", o.name AS "officeName",
r.fd_product_id AS "productId", p.name AS "productName", r.fd_type AS "fdType",
r.account_count AS "accountCount", r.total_interest AS "totalInterest", r.status,
au.username AS "approvedBy", r.approved_on_behalf AS "approvedOnBehalf",
r.approved_at AS "approvedAt", r.posted_at AS "postedAt"
FROM m_fd_interest_posting_report r
JOIN m_savings_product p ON p.id = r.fd_product_id
LEFT JOIN m_office o ON o.id = r.office_id
LEFT JOIN m_appuser au ON au.id = r.approved_by
WHERE r.status <> 'SUPERSEDED'
""");
final List<Object> params = new ArrayList<>();
if (fromDate != null) {
sql.append(" AND r.posting_date >= ?");
params.add(fromDate);
}
if (toDate != null) {
sql.append(" AND r.posting_date <= ?");
params.add(toDate);
}
if (productId != null) {
sql.append(" AND r.fd_product_id = ?");
params.add(productId);
}
sql.append(" ORDER BY r.posting_date DESC, p.name, o.name");
return this.jdbcTemplate.queryForList(sql.toString(), params.toArray());
}
/**
* Branch and product pairs with deposit interest due by the date that have no report yet — the
* noon job ran before they had anything due, or failed.
*/
public List<Map<String, Object>> dueWithoutReport(final LocalDate postingDate, final AppUser user, final String scope) {
final List<Map<String, Object>> out = new ArrayList<>();
final LocalDate businessDate = DateUtils.getBusinessLocalDate();
if (postingDate.isAfter(businessDate)) {
return out;
}
final Long userOffice = officeOf(user);
final boolean others = "others".equalsIgnoreCase(scope) && this.branchAuthority.isHeadOffice(userOffice);
final List<DueLine> due = computeDueInterest(postingDate, others ? null : userOffice, null);
for (final Map.Entry<DueKey, List<DueLine>> group : groupByProductAndOffice(due).entrySet()) {
final DueKey key = group.getKey();
if (others == key.officeId().equals(userOffice)) {
continue;
}
if (activeReportId(key.productId(), key.officeId(), postingDate) != null) {
continue;
}
BigDecimal total = BigDecimal.ZERO;
for (final DueLine line : group.getValue()) {
total = total.add(line.interest());
}
final Map<String, Object> row = new LinkedHashMap<>();
row.put("productId", key.productId());
row.put("productName", productName(key.productId()));
row.put("fdType", group.getValue().get(0).fdType());
row.put("officeId", key.officeId());
row.put("officeName", officeName(key.officeId()));
row.put("postingDate", postingDate.toString());
row.put("accountCount", group.getValue().size());
row.put("totalInterest", total.setScale(MONEY_SCALE, MONEY_ROUNDING));
final String blocked = actBlockedReason(userOffice, key.officeId(), businessDate);
row.put("canAct", blocked == null);
row.put("blockedReason", blocked);
out.add(row);
}
return out;
}
// ── who may act ──────────────────────────────────────────────────────────────────────────────
/**
* Null where the user may generate or approve the branch's report, otherwise why not. The branch
* rules are the savings ones: a branch always acts for itself, and the head office acts for
* another branch only when that branch has not opened at all and every branch that did open has
* closed.
*/
private String actBlockedReason(final Long userOffice, final Long reportOffice, final LocalDate businessDate) {
if (userOffice == null) {
return "No branch is set for this user.";
}
if (userOffice.equals(reportOffice)) {
return null;
}
final String branch = officeName(reportOffice);
if (!this.branchAuthority.isHeadOffice(userOffice)) {
return "Only " + branch + " can generate or approve its own fixed deposit interest posting report.";
}
if (this.branchAuthority.branchOpenedOn(reportOffice, businessDate)) {
return branch + " is open — it generates and approves its own report.";
}
final List<String> stillOpen = this.branchAuthority.branchesStillOpen(businessDate, userOffice, reportOffice);
if (!stillOpen.isEmpty()) {
return "The head office can act for " + branch + " only after every open branch has closed. Still open: "
+ String.join(", ", stillOpen) + ".";
}
return null;
}
/** @return true where the head office is acting on a branch's behalf */
private boolean authorize(final AppUser user, final Long reportOffice, final LocalDate businessDate) {
final Long userOffice = officeOf(user);
final String blocked = actBlockedReason(userOffice, reportOffice, businessDate);
if (blocked != null) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.other.branch", blocked);
}
return !reportOffice.equals(userOffice);
}
public boolean isHeadOffice(final Long officeId) {
return this.branchAuthority.isHeadOffice(officeId);
}
// ── internals ────────────────────────────────────────────────────────────────────────────────
private Long activeReportId(final Long productId, final Long officeId, final LocalDate postingDate) {
final List<Long> ids = this.jdbcTemplate.queryForList("""
SELECT id FROM m_fd_interest_posting_report
WHERE fd_product_id = ? AND office_id = ? AND posting_date = ? AND status <> 'SUPERSEDED'
""", Long.class, productId, officeId, postingDate);
return ids.isEmpty() ? null : ids.get(0);
}
private String productName(final Long productId) {
return this.jdbcTemplate.queryForObject("SELECT name FROM m_savings_product WHERE id = ?", String.class, productId);
}
private String officeName(final Long officeId) {
return this.jdbcTemplate.queryForObject("SELECT name FROM m_office WHERE id = ?", String.class, officeId);
}
private static Long officeOf(final AppUser user) {
return user == null || user.getOffice() == null ? null : user.getOffice().getId();
}
}
@@ -0,0 +1,477 @@
/**
* 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.savings.fdinterest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.accounting.glaccount.validation.GLAccountTransactionGuard;
import org.apache.fineract.accounting.journalentry.service.LedgerTransactionId;
import org.apache.fineract.accounting.journalentry.service.LedgerTxnPrefix;
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Pays an approved fixed deposit interest posting report.
*
* <p>
* Nothing is recomputed here. The report's lines are the authority: each deposit is credited exactly
* what was approved for it, and interest that accrued after the report was generated is not added,
* because the approver signed off on these figures and not on others. The payable and paid accounts
* are those recorded on the report when it was generated.
*
* <p>
* The ledger entries are the three stages fixed deposit interest has always posted through, raised
* once for the whole report rather than once per deposit — the same pooling the savings interest
* posting report uses, for the same reason: a bank's interest cost is one figure in its books, not
* one line per customer repeated three times over.
*
* <pre>
* Dr Interest Expense (report total) → Cr Fixed Deposit Interest Payable
* Dr Interest Payable (report total) → Cr Fixed Deposit Interest Paid
* Dr Interest Paid (report total, once)
* Cr Savings Control (per deposit, naming the account and its own amount)
* </pre>
*
* A product that names no paid account posts the two-stage form, and one that names neither falls
* back to the plain Dr Expense / Cr Control pair — pooled the same way, one expense debit against many
* credits. Where one report holds deposits due for more than one period — a deposit owed two unpaid
* cycles, or a branch posting a stale cycle alongside today's — each {@code interestPostingDate}
* pools on its own: the chain above is raised once per date present on the report, not once overall,
* because the narration and the ledger date belong to the cycle, not to the day it happened to post.
*
* <p>
* Where the interest then goes is the product's scheme, and it is not decided here. A
* {@code SPECIAL} deposit carries {@code transfer_interest_to_linked_account}, and the existing
* transfer-interest-to-savings job sweeps the posted interest to the customer's linked savings
* account as it always has; {@code SINGLE} and {@code DOUBLE} keep it in the deposit. Posting is the
* same act for all three — the money reaches the customer's deposit — so this service does one thing
* and the sweep is left where it already works.
*
* <p>
* The whole report settles in one transaction: a failure leaves nobody half paid and the report still
* APPROVED for the next attempt.
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class FixedDepositInterestPostingService {
private static final int MONEY_SCALE = 2;
private static final RoundingMode MONEY_ROUNDING = RoundingMode.HALF_EVEN;
/** m_savings_account_transaction.transaction_type_enum */
private static final int INTEREST_POSTING = 3;
/** acc_gl_journal_entry.entity_type_enum for a savings entry. */
private static final int ENTITY_TYPE_SAVINGS = 2;
/** {@code CashAccountsForSavings.SAVINGS_CONTROL} */
private static final int GL_SAVINGS_CONTROL = 2;
/** {@code CashAccountsForSavings.INTEREST_ON_SAVINGS} — the expense interest is charged to. */
private static final int GL_INTEREST_ON_SAVINGS = 3;
/** {@code AccrualAccountsForSavings.INTEREST_PAYABLE} — the Interest Payable row on the product. */
private static final int GL_INTEREST_PAYABLE = 17;
/**
* The reserved names a deposit product may map its payable and paid accounts under, most specific
* first. The same lists the scheduler reads, so a product configured for the old path needs no
* change for the new one.
*/
private static final String[] PAYABLE_NAMES = { "Fixed Deposit Interest Payable", "Savings Interest Payable",
"Recurring Deposit Interest Payable", "Interest Payable", "Interest Payable Account" };
private static final String[] PAID_NAMES = { "Fixed Deposit Interest Paid", "Savings Interest Paid",
"Recurring Deposit Interest Paid", "Interest Paid", "Interest Paid Account" };
private final JdbcTemplate jdbcTemplate;
/** The payable and paid accounts a product's interest passes through. */
public record PostingGlAccounts(Long payableGl, Long paidGl) {}
/**
* One deposit's credit, after its transaction and balances are written but before the pooled ledger
* legs are raised — grouped with the others of its {@code interestDate} so the whole group is posted
* as one chain.
*/
private record PaidLine(Long accountId, BigDecimal amount, LocalDate interestDate, Long transactionId) {}
/**
* The payable and paid accounts as the product maps them now, read when a report is generated so a
* product missing one is refused before anybody approves figures that could never be posted.
*
* <p>
* Unlike savings, neither is required: a deposit product that names no payable posts the plain two
* legs it always did, and nulls here say so rather than stopping the report.
*/
public PostingGlAccounts resolvePostingGlAccounts(final long productId) {
if (optionalMappedGlAccount(productId, GL_INTEREST_ON_SAVINGS) == null) {
final String productName = this.jdbcTemplate.queryForObject("SELECT name FROM m_savings_product WHERE id = ?", String.class,
productId);
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.gl.not.mapped",
"Fixed deposit product '" + productName + "' has no Interest On Savings GL mapped. Set it under the product's"
+ " Accounting and generate the report again.");
}
Long payableGl = optionalMappedGlAccount(productId, GL_INTEREST_PAYABLE);
if (payableGl == null) {
payableGl = namedGlAccount(productId, PAYABLE_NAMES);
}
return new PostingGlAccounts(payableGl, namedGlAccount(productId, PAID_NAMES));
}
/**
* Posts one approved report, crediting each deposit exactly what was approved for it.
*
* <p>
* Everything is dated the day it is actually posted — the business date — not the cycle's end: a
* branch that was shut on its posting date posts when it next closes, into a day that is still
* open, and the narration names the date the interest is for.
*
* @return the amount distributed
*/
@Transactional
public BigDecimal postReport(final long reportId) {
final List<Map<String, Object>> reports = this.jdbcTemplate.queryForList("""
SELECT id, fd_product_id, fd_type, office_id, posting_date, status, total_interest, payable_gl_account_id,
paid_gl_account_id
FROM m_fd_interest_posting_report
WHERE id = ?
FOR UPDATE
""", reportId);
if (reports.isEmpty()) {
throw new IllegalStateException("Fixed deposit interest posting report " + reportId + " does not exist");
}
final Map<String, Object> report = reports.get(0);
if (!FixedDepositInterestPostingReportService.APPROVED.equals(report.get("status"))) {
throw new IllegalStateException(
"Fixed deposit interest posting report " + reportId + " is " + report.get("status") + ", not APPROVED");
}
final long productId = ((Number) report.get("fd_product_id")).longValue();
final long officeId = ((Number) report.get("office_id")).longValue();
final LocalDate interestFor = ((java.sql.Date) report.get("posting_date")).toLocalDate();
final LocalDate postedOn = DateUtils.getBusinessLocalDate();
final BigDecimal approved = ((BigDecimal) report.get("total_interest")).setScale(MONEY_SCALE, MONEY_ROUNDING);
final List<Map<String, Object>> lines = this.jdbcTemplate.queryForList("""
SELECT l.id AS line_id, l.fd_account_id, l.interest_posting_date, l.interest_amount, l.fd_transaction_id,
sa.currency_code
FROM m_fd_interest_posting_report_line l
JOIN m_savings_account sa ON sa.id = l.fd_account_id
WHERE l.report_id = ?
ORDER BY l.interest_posting_date, l.fd_account_id
""", reportId);
if (lines.isEmpty()) {
throw new IllegalStateException("Fixed deposit interest posting report " + reportId + " has no deposits to pay");
}
final long runId = openRun(reportId, productId, officeId, interestFor, lines.size());
final Long expenseGl = mappedGlAccount(productId, GL_INTEREST_ON_SAVINGS);
final Long controlGl = mappedGlAccount(productId, GL_SAVINGS_CONTROL);
final PostingGlAccounts current = resolvePostingGlAccounts(productId);
final Long payableGl = report.get("payable_gl_account_id") != null ? ((Number) report.get("payable_gl_account_id")).longValue()
: current.payableGl();
final Long paidGl = report.get("paid_gl_account_id") != null ? ((Number) report.get("paid_gl_account_id")).longValue()
: current.paidGl();
final String currency = (String) lines.get(0).get("currency_code");
// One per report, and deterministic: a retried posting carries the same reference as the legs a
// failed attempt rolled back, and two branches posting the same product never share one.
final String reference = LedgerTransactionId.forDatedSeries(LedgerTxnPrefix.FD_INTEREST_POSTED, postedOn, reportId);
// Each deposit's transaction and balances are settled first; the ledger is raised after, pooled
// by the date its interest belongs to, so a report spanning two cycles raises two chains rather
// than crediting one period's money under the other's date.
final Map<LocalDate, List<PaidLine>> byDate = new LinkedHashMap<>();
BigDecimal distributed = BigDecimal.ZERO;
for (final Map<String, Object> line : lines) {
final PaidLine paid = payDeposit(line, officeId, postedOn);
if (paid == null) {
continue;
}
byDate.computeIfAbsent(paid.interestDate(), key -> new ArrayList<>()).add(paid);
distributed = distributed.add(paid.amount());
}
// If what was paid does not add up to what was approved, nothing commits.
if (approved.compareTo(distributed) != 0) {
throw new IllegalStateException(String.format(
"Fixed deposit interest posting report %d did not balance: approved %s, distributed %s", reportId, approved,
distributed));
}
for (final Map.Entry<LocalDate, List<PaidLine>> group : byDate.entrySet()) {
postPooledLedgerLegs(officeId, currency, group.getKey(), postedOn, group.getValue(), reference, expenseGl, payableGl, paidGl,
controlGl);
}
completeReport(reportId, productId, interestFor, approved, distributed, runId, lines.size());
return distributed;
}
/**
* One deposit's interest transaction and balances, settled without raising any ledger entry — the
* caller pools this with the rest of its date-group before the GL is touched.
*
* <p>
* The transaction carries the date the interest engine gave the period, not the day the branch is
* closing. That is not presentation: the engine decides a period has already been paid by looking
* for an interest transaction on exactly that date, so a posting written under the close date would
* be invisible to it and the same period would be computed and paid again at the next run. The
* close date is kept as the submitted-on stamp, which is what the scheduler has always done.
*
* @return the deposit's credit, or null for a line with nothing to pay
*/
private PaidLine payDeposit(final Map<String, Object> line, final long officeId, final LocalDate postedOn) {
final BigDecimal amount = ((BigDecimal) line.get("interest_amount")).setScale(MONEY_SCALE, MONEY_ROUNDING);
if (amount.compareTo(BigDecimal.ZERO) <= 0) {
return null;
}
final long accountId = ((Number) line.get("fd_account_id")).longValue();
final LocalDate interestDate = ((java.sql.Date) line.get("interest_posting_date")).toLocalDate();
// A resumed or duplicated attempt must not pay anybody twice. The line itself records the
// payment, so this holds even where one deposit has two periods on one report.
if (line.get("fd_transaction_id") != null) {
throw new IllegalStateException("Fixed deposit " + accountId + " was already paid by this report");
}
// The balance as it stands now, not as the report showed it: money may have moved since the
// report was generated, and the transaction's running balance has to follow the deposit.
final BigDecimal currentBalance = this.jdbcTemplate.queryForObject(
"SELECT COALESCE(account_balance_derived, 0) FROM m_savings_account WHERE id = ?", BigDecimal.class, accountId);
final BigDecimal newBalance = currentBalance.add(amount);
final long transactionId = createInterestPostingTransaction(accountId, officeId, interestDate, postedOn, amount, newBalance);
// Earned is only ever raised to what has now been posted, never added to: the engine may
// already have counted this interest as earned, and adding on top of that doubles it. Screens
// read unposted interest as earned - posted, so earned must not fall below posted either.
//
// interest_posted_till_date is what takes the deposit out of the next report's candidates; the
// interest transaction itself is what stops the engine recomputing the same period.
this.jdbcTemplate.update("""
UPDATE m_savings_account
SET account_balance_derived = COALESCE(account_balance_derived, 0) + ?,
total_interest_posted_derived = COALESCE(total_interest_posted_derived, 0) + ?,
total_interest_earned_derived = GREATEST(COALESCE(total_interest_earned_derived, 0),
COALESCE(total_interest_posted_derived, 0) + ?),
interest_posted_till_date = GREATEST(COALESCE(interest_posted_till_date, ?), ?)
WHERE id = ?
""", amount, amount, amount, interestDate, interestDate, accountId);
this.jdbcTemplate.update("UPDATE m_fd_interest_posting_report_line SET fd_transaction_id = ? WHERE id = ?", transactionId,
((Number) line.get("line_id")).longValue());
return new PaidLine(accountId, amount, interestDate, transactionId);
}
/**
* One date-group's chain, pooled: the report's cost moves through the fewer-or-more intermediate
* accounts the product's mappings support as one figure, and only the last leg — crediting each
* deposit — is raised per account. The group's own total is what moves, not the report's, so two
* periods on one report each carry their own entries under their own date.
*/
private void postPooledLedgerLegs(final long officeId, final String currency, final LocalDate interestDate, final LocalDate postedOn,
final List<PaidLine> group, final String reference, final Long expenseGl, final Long payableGl, final Long paidGl,
final Long controlGl) {
final String narration = "Fixed deposit interest for " + interestDate;
BigDecimal total = BigDecimal.ZERO;
for (final PaidLine paid : group) {
total = total.add(paid.amount());
}
final boolean hasPayable = payableGl != null && payableGl != 0 && !payableGl.equals(controlGl);
final boolean hasPaid = paidGl != null && paidGl != 0 && !paidGl.equals(payableGl);
// The chain of pooled accounts the group's cost passes through before it is split: Expense, then
// Payable and Paid where the product maps them — each consecutive pair raised once for the whole
// total. The last account in the chain is what Stage 2 debits before crediting each deposit.
final List<Long> chain = new ArrayList<>();
chain.add(expenseGl);
if (hasPayable) {
chain.add(payableGl);
if (hasPaid) {
chain.add(paidGl);
}
}
for (int i = 0; i < chain.size() - 1; i++) {
journalEntry(officeId, currency, chain.get(i), interestDate, postedOn, total, true, reference, null, null, narration);
journalEntry(officeId, currency, chain.get(i + 1), interestDate, postedOn, total, false, reference, null, null, narration);
}
// Stage 2: one debit for the group's total, and under it a credit to each deposit. Every leg
// carries the report's one transaction id, and every credit names its account and interest
// transaction, so who was paid what reads back from the journal alone.
journalEntry(officeId, currency, chain.get(chain.size() - 1), interestDate, postedOn, total, true, reference, null, null,
narration);
for (final PaidLine paid : group) {
journalEntry(officeId, currency, controlGl, interestDate, postedOn, paid.amount(), false, reference, paid.accountId(),
paid.transactionId(), narration);
}
}
private void completeReport(final long reportId, final long productId, final LocalDate interestFor, final BigDecimal approved,
final BigDecimal distributed, final long runId, final int accountCount) {
this.jdbcTemplate.update("""
UPDATE m_fd_interest_posting_run
SET pooled_amount = ?, distributed_amount = ?, rounding_residual = 0,
status = 'COMPLETED', completed_at = CURRENT_TIMESTAMP
WHERE id = ?
""", approved, distributed, runId);
this.jdbcTemplate.update("""
UPDATE m_fd_interest_posting_report
SET status = 'POSTED', posted_at = CURRENT_TIMESTAMP, posting_run_id = ?, failure_reason = NULL
WHERE id = ?
""", runId, reportId);
log.info("FD interest posting: report {} (product {}, for {}) paid {} across {} deposits", reportId, productId, interestFor,
distributed, accountCount);
}
/** One run per report. A retry of the same report reuses its run. */
private long openRun(final long reportId, final long productId, final long officeId, final LocalDate postingDate,
final int accountCount) {
this.jdbcTemplate.update("""
INSERT INTO m_fd_interest_posting_run
(report_id, fd_product_id, office_id, posting_date, account_count, status)
VALUES (?, ?, ?, ?, ?, 'PENDING')
ON CONFLICT (report_id) DO UPDATE SET
account_count = EXCLUDED.account_count, status = 'PENDING',
started_at = CURRENT_TIMESTAMP, failure_reason = NULL
""", reportId, productId, officeId, postingDate, accountCount);
return this.jdbcTemplate.queryForObject("SELECT id FROM m_fd_interest_posting_run WHERE report_id = ?", Long.class, reportId);
}
/**
* @param interestDate
* the period the interest is for, which is the transaction's own date
* @param postedOn
* the business date it is being written on, kept as the submitted-on stamp
*/
private long createInterestPostingTransaction(final long accountId, final long officeId, final LocalDate interestDate,
final LocalDate postedOn, final BigDecimal amount, final BigDecimal runningBalance) {
this.jdbcTemplate.update("""
INSERT INTO m_savings_account_transaction
(savings_account_id, office_id, is_reversed, is_reversal, is_lien_transaction,
transaction_type_enum, transaction_date, amount, running_balance_derived,
submitted_on_date, created_by, last_modified_by, created_on_utc, last_modified_on_utc)
VALUES (?, ?, false, false, false, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
""", accountId, officeId, INTEREST_POSTING, interestDate, amount, runningBalance, postedOn, systemUserId(),
systemUserId());
return this.jdbcTemplate.queryForObject("""
SELECT id FROM m_savings_account_transaction
WHERE savings_account_id = ? AND transaction_date = ? AND transaction_type_enum = ?
ORDER BY id DESC LIMIT 1
""", Long.class, accountId, interestDate, INTEREST_POSTING);
}
/**
* One journal entry leg. Fineract's {@code type_enum} is 2 = DEBIT, 1 = CREDIT — {@code
* JournalEntryType} declares {@code CREDIT(1)} first.
*
* <p>
* Dated the period the interest is for, as the scheduler dates its own legs, with the business date
* kept as the submitted-on stamp.
*/
private void journalEntry(final long officeId, final String currency, final Long glAccountId, final LocalDate interestDate,
final LocalDate postedOn, final BigDecimal amount, final boolean debit, final String reference, final Long savingsAccountId,
final Long transactionId, final String narration) {
GLAccountTransactionGuard.assertPostable(this.jdbcTemplate, glAccountId);
this.jdbcTemplate.update("""
INSERT INTO acc_gl_journal_entry
(office_id, account_id, currency_code, transaction_id, entry_date, transaction_date, type_enum,
amount, description, entity_type_enum, entity_id, is_running_balance_calculated,
savings_transaction_id, reversed, manual_entry, office_running_balance,
organization_running_balance, created_by, last_modified_by, created_date, lastmodified_date,
created_on_utc, last_modified_on_utc, submitted_on_date)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, false, ?, false, false, 0, 0, ?, ?,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)
""", officeId, glAccountId, currency, reference, interestDate, interestDate, debit ? 2 : 1, amount, narration,
savingsAccountId == null ? null : ENTITY_TYPE_SAVINGS, savingsAccountId, transactionId, systemUserId(), systemUserId(),
postedOn);
}
/**
* The user these rows are attributed to. A day close has a user, but the nightly retry does not and
* the audit columns are NOT NULL, so entries are stamped to the system account either way — as the
* scheduler's own postings always were.
*/
private Long systemUserId() {
final List<Long> ids = this.jdbcTemplate.queryForList("SELECT id FROM m_appuser WHERE username = 'system' ORDER BY id LIMIT 1",
Long.class);
return ids.isEmpty() ? 1L : ids.get(0);
}
private Long mappedGlAccount(final long productId, final int financialAccountType) {
final Long found = optionalMappedGlAccount(productId, financialAccountType);
if (found == null) {
throw new IllegalStateException("Fixed deposit product " + productId + " has no GL account mapped for financial account type "
+ financialAccountType + ". Set the product's Accounting tab before its interest can be posted.");
}
return found;
}
private Long optionalMappedGlAccount(final long productId, final int financialAccountType) {
final List<Long> found = this.jdbcTemplate.queryForList("""
SELECT gl_account_id FROM acc_product_mapping
WHERE product_id = ? AND product_type = 2 AND financial_account_type = ?
LIMIT 1
""", Long.class, productId, financialAccountType);
return found.isEmpty() ? null : found.get(0);
}
/**
* The GL account a product maps under one of the reserved names in {@code other_gl_mappings}, tried
* in order of preference. The column holds an empty string on a product saved with no named
* mappings and casting that to jsonb is an error, so the cast sits inside a subquery that has
* already filtered those rows out.
*/
private Long namedGlAccount(final long productId, final String... accountNames) {
for (final String accountName : accountNames) {
final List<Long> found = this.jdbcTemplate.queryForList("""
SELECT gl.id
FROM (SELECT other_gl_mappings::jsonb AS doc
FROM m_savings_product
WHERE id = ?
AND other_gl_mappings IS NOT NULL
AND other_gl_mappings <> ''
AND other_gl_mappings LIKE '{%') sp
CROSS JOIN LATERAL jsonb_array_elements(
COALESCE(sp.doc -> 'assets', '[]'::jsonb)
|| COALESCE(sp.doc -> 'liabilities', '[]'::jsonb)
|| COALESCE(sp.doc -> 'expenses', '[]'::jsonb)
|| COALESCE(sp.doc -> 'income', '[]'::jsonb)
) AS m(entry)
JOIN acc_gl_account gl ON gl.gl_code = m.entry ->> 'glCode'
WHERE lower(trim(m.entry ->> 'accountName')) = lower(trim(?))
LIMIT 1
""", Long.class, productId, accountName);
if (!found.isEmpty()) {
return found.get(0);
}
}
return null;
}
}
@@ -0,0 +1,229 @@
/**
* 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.savings.fdinterest.api;
import com.google.gson.Gson;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.apache.fineract.portfolio.savings.fdinterest.FixedDepositInterestPostingReportService;
import org.apache.fineract.useradministration.domain.AppUser;
import org.springframework.stereotype.Component;
/**
* The fixed deposit interest posting reports, per branch and product: list, detail, generate, approve,
* the day-close check, and the head office's branch-wise summary.
*
* <p>
* Posting is not offered here. A branch's approved reports are posted when that branch closes the
* day, so there is exactly one way interest reaches a customer's deposit.
*/
@Path("/v1/fixeddepositinterestpostingreports")
@Component
@RequiredArgsConstructor
@Produces({ MediaType.APPLICATION_JSON })
public class FixedDepositInterestPostingReportApiResource {
private static final String RESOURCE = "FDINTERESTREPORT";
private final FixedDepositInterestPostingReportService reportService;
private final ConfigurationDomainService configurationDomainService;
private final PlatformSecurityContext context;
private final FromJsonHelper fromJsonHelper;
private final Gson gson = new Gson();
/** A branch user sees their own branch; a head office user every branch, or one with officeId. */
@GET
public String list(@QueryParam("postingDate") final String postingDate, @QueryParam("status") final String status,
@QueryParam("productId") final Long productId, @QueryParam("officeId") final Long officeId,
@QueryParam("scope") final String scope) {
final AppUser user = this.context.authenticatedUser();
user.validateHasReadPermission(RESOURCE);
return this.gson
.toJson(this.reportService.list(parseDate(postingDate), status, productId, officeId, scope, user).stream()
.map(this::plain).toList());
}
/**
* Who is looking: their branch, whether it is the head office (which gets the Other branches tab),
* and whether deposits are on the approval path at all — with the switch off every screen here is
* empty by design, and the UI should say so rather than look broken.
*/
@GET
@Path("/context")
public String userContext() {
final AppUser user = this.context.authenticatedUser();
final Long officeId = user.getOffice().getId();
final Map<String, Object> result = new LinkedHashMap<>();
result.put("officeId", officeId);
result.put("officeName", user.getOffice().getName());
result.put("headOffice", this.reportService.isHeadOffice(officeId));
result.put("approvalEnabled", this.configurationDomainService.isFixedDepositInterestPostingApprovalEnabled());
return this.gson.toJson(result);
}
/** Branch and product pairs with deposit interest due by the date and no report yet. */
@GET
@Path("/due-without-report")
public String dueWithoutReport(@QueryParam("postingDate") final String postingDate, @QueryParam("scope") final String scope) {
final AppUser user = this.context.authenticatedUser();
user.validateHasReadPermission(RESOURCE);
final LocalDate date = postingDate == null || postingDate.isBlank() ? DateUtils.getBusinessLocalDate() : parseDate(postingDate);
return this.gson.toJson(this.reportService.dueWithoutReport(date, user, scope));
}
/**
* What stops a branch closing the business day: its own deposit reports due and not yet approved,
* and the products and amounts behind them. The day-close screen reads it to warn before the close
* is attempted.
*/
@GET
@Path("/day-close-check")
public String dayCloseCheck(@QueryParam("date") final String date, @QueryParam("officeId") final Long officeIdParam) {
final AppUser user = this.context.authenticatedUser();
final LocalDate businessDate = date == null || date.isBlank() ? DateUtils.getBusinessLocalDate() : parseDate(date);
final Long officeId = officeIdParam != null ? officeIdParam : user.getOffice().getId();
final Map<String, Object> view = this.reportService.dayCloseInterestView(officeId, businessDate);
@SuppressWarnings("unchecked")
final List<String> blocking = (List<String>) view.get("pending");
final Map<String, Object> result = new LinkedHashMap<>();
result.put("businessDate", businessDate.toString());
result.put("canClose", blocking.isEmpty());
result.put("pendingProducts", blocking);
result.put("due", view.get("due"));
return this.gson.toJson(result);
}
/** What each deposit has earned and not been paid, as if posted today. View only — nothing is saved. */
@GET
@Path("/preview")
public String preview(@QueryParam("officeId") final Long officeId) {
final AppUser user = this.context.authenticatedUser();
user.validateHasReadPermission(RESOURCE);
return this.gson.toJson(this.reportService.preview(officeId, user).stream().map(this::plain).toList());
}
/** The head office's view: per branch and product, deposits paid and interest, over a date range. */
@GET
@Path("/summary")
public String summary(@QueryParam("fromDate") final String fromDate, @QueryParam("toDate") final String toDate,
@QueryParam("productId") final Long productId) {
final AppUser user = this.context.authenticatedUser();
user.validateHasReadPermission(RESOURCE);
if (!this.reportService.isHeadOffice(user.getOffice().getId())) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.summary.head.office.only",
"The branch-wise fixed deposit interest summary is for the head office.");
}
return this.gson
.toJson(this.reportService.summary(parseDate(fromDate), parseDate(toDate), productId).stream().map(this::plain).toList());
}
@GET
@Path("/{reportId}")
public String detail(@PathParam("reportId") final Long reportId) {
this.context.authenticatedUser().validateHasReadPermission(RESOURCE);
final Map<String, Object> report = plain(this.reportService.detail(reportId));
@SuppressWarnings("unchecked")
final List<Map<String, Object>> lines = (List<Map<String, Object>>) report.get("lines");
report.put("lines", lines.stream().map(this::plain).toList());
return this.gson.toJson(report);
}
/** {@code ?command=regenerate} with {@code {"productId": .., "officeId": .., "postingDate": "yyyy-MM-dd"}}. */
@POST
@Consumes({ MediaType.APPLICATION_JSON })
public String command(@QueryParam("command") final String command, final String body) {
if (!"regenerate".equalsIgnoreCase(command)) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.unknown.command", "Unsupported command: " + command);
}
final AppUser user = this.context.authenticatedUser();
user.validateHasPermissionTo("REGENERATE_" + RESOURCE);
final var root = this.fromJsonHelper.parse(body);
final Long productId = this.fromJsonHelper.extractLongNamed("productId", root);
final Long officeIdParam = this.fromJsonHelper.extractLongNamed("officeId", root);
final String postingDate = this.fromJsonHelper.extractStringNamed("postingDate", root);
if (productId == null) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.product.required", "Which product?");
}
final Long officeId = officeIdParam != null ? officeIdParam : user.getOffice().getId();
final LocalDate date = postingDate == null || postingDate.isBlank() ? DateUtils.getBusinessLocalDate() : parseDate(postingDate);
final Long reportId = this.reportService.regenerate(productId, officeId, date, user);
return this.gson.toJson(Map.of("reportId", reportId, "status", FixedDepositInterestPostingReportService.GENERATED));
}
/**
* {@code ?command=approve}. A user of the report's branch who did not generate it approves it; see
* the service for the head office's one exception.
*/
@POST
@Path("/{reportId}")
@Consumes({ MediaType.APPLICATION_JSON })
public String reportCommand(@PathParam("reportId") final Long reportId, @QueryParam("command") final String command) {
if (!"approve".equalsIgnoreCase(command)) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.unknown.command", "Unsupported command: " + command);
}
final AppUser user = this.context.authenticatedUser();
user.validateHasPermissionTo("APPROVE_" + RESOURCE);
this.reportService.approve(reportId, user);
return this.gson.toJson(Map.of("reportId", reportId, "status", FixedDepositInterestPostingReportService.APPROVED));
}
private static LocalDate parseDate(final String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
try {
return LocalDate.parse(raw.trim());
} catch (final RuntimeException e) {
throw new PlatformDataIntegrityException("error.msg.fdinterestreport.invalid.date",
"Dates are expected as yyyy-MM-dd, not " + raw);
}
}
/** JDBC dates and timestamps as ISO strings; Gson would otherwise write them in its own locale format. */
private Map<String, Object> plain(final Map<String, Object> row) {
final Map<String, Object> out = new LinkedHashMap<>();
row.forEach((key, value) -> {
if (value instanceof java.sql.Date d) {
out.put(key, d.toLocalDate().toString());
} else if (value instanceof Timestamp t) {
out.put(key, t.toLocalDateTime().toString());
} else {
out.put(key, value);
}
});
return out;
}
}
@@ -0,0 +1,52 @@
/**
* 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.savings.fdinterest.jobs;
import org.apache.fineract.infrastructure.jobs.service.JobName;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
public class FixedDepositInterestPostingReportConfig {
@Autowired
private JobRepository jobRepository;
@Autowired
private PlatformTransactionManager transactionManager;
@Bean
protected Step fdInterestPostingReportStep(final FixedDepositInterestPostingReportTasklet fdInterestPostingReportTasklet) {
return new StepBuilder(JobName.FD_INTEREST_POSTING_REPORT.name(), jobRepository)
.tasklet(fdInterestPostingReportTasklet, transactionManager).build();
}
@Bean
public Job fdInterestPostingReportJob(final FixedDepositInterestPostingReportTasklet fdInterestPostingReportTasklet) {
return new JobBuilder(JobName.FD_INTEREST_POSTING_REPORT.name(), jobRepository)
.start(fdInterestPostingReportStep(fdInterestPostingReportTasklet)).incrementer(new RunIdIncrementer()).build();
}
}
@@ -0,0 +1,57 @@
/**
* 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.savings.fdinterest.jobs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.portfolio.savings.fdinterest.FixedDepositInterestPostingReportService;
import org.springframework.batch.core.StepContribution;
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.stereotype.Component;
/**
* Noon on the business date: generates the interest posting report for every fixed deposit product
* whose interest falls due, so a branch can review and approve it before it closes the day.
*
* <p>
* Does nothing while deposits are off the approval path — the posting job is paying them directly,
* and a report generated alongside it would be approved against money that has already moved.
*/
@RequiredArgsConstructor
@Component
@Slf4j
public class FixedDepositInterestPostingReportTasklet implements Tasklet {
private final FixedDepositInterestPostingReportService reportService;
private final ConfigurationDomainService configurationDomainService;
@Override
public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext) throws Exception {
if (!this.configurationDomainService.isFixedDepositInterestPostingApprovalEnabled()) {
log.info("FD interest posting report: skipped — fixed deposit interest is posted directly by the posting job");
return RepeatStatus.FINISHED;
}
this.reportService.generateDue(DateUtils.getBusinessLocalDate());
return RepeatStatus.FINISHED;
}
}
@@ -36,6 +36,7 @@ import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.fineract.accounting.common.AccountingRuleType;
import org.apache.fineract.accounting.glaccount.data.GLAccountData;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.infrastructure.core.domain.ExternalId;
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
@@ -109,16 +110,24 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead
private final SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper;
private final SavingsDailyInterestService savingsDailyInterestService;
private final ConfigurationDomainService configurationDomainService;
/** m_savings_account.status_enum for an active account. */
private static final Integer ACTIVE_STATUS = 300;
/** m_savings_product.deposit_type_enum for a fixed deposit. */
private static final Integer DEPOSIT_TYPE_FIXED = 200;
public SavingsAccountReadPlatformServiceImpl(final PlatformSecurityContext context, final JdbcTemplate jdbcTemplate,
final SavingsAccountAssembler savingAccountAssembler, PaginationHelper paginationHelper, ColumnValidator columnValidator,
DatabaseSpecificSQLGenerator sqlGenerator, SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper,
final SavingsDailyInterestService savingsDailyInterestService) {
final SavingsDailyInterestService savingsDailyInterestService,
final ConfigurationDomainService configurationDomainService) {
this.context = context;
this.jdbcTemplate = jdbcTemplate;
this.sqlGenerator = sqlGenerator;
this.savingsAccountRepositoryWrapper = savingsAccountRepositoryWrapper;
this.savingsDailyInterestService = savingsDailyInterestService;
this.configurationDomainService = configurationDomainService;
this.transactionTemplateMapper = new SavingsAccountTransactionTemplateMapper();
this.transactionsMapper = new SavingsAccountTransactionsMapper();
this.savingsAccountTransactionsForBatchMapper = new SavingsAccountTransactionsForBatchMapper();
@@ -440,10 +449,19 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead
// (SavingsPooledInterestPostingService). Posting it here too would pay its members twice.
// FD and RD products are never on that timetable, so they still post here. The filter sits inside the paging
// subquery so a page is never cut short by accounts that are then dropped.
//
// Fixed deposits come out on the same grounds once their interest goes through an approved
// report (FixedDepositInterestPostingReportService): the report's figures are posted when the
// branch closes its day, and this job running over the same deposits would pay them twice.
// Recurring deposits are not part of that gate and still post here either way.
final String fixedDepositFilter = this.configurationDomainService.isFixedDepositInterestPostingApprovalEnabled()
? "and a.deposit_type_enum <> " + DEPOSIT_TYPE_FIXED + " "
: "";
String sql = "select " + this.savingAccountMapperForInterestPosting.schema()
+ "join (select a.id from m_savings_account a where a.id > ? and a.status_enum = ? "
+ "and not exists (select 1 from m_savings_interest_posting_schedule s "
+ "where s.savings_product_id = a.product_id and s.is_active = true) limit ?) b on b.id = sa.id ";
+ "where s.savings_product_id = a.product_id and s.is_active = true) " + fixedDepositFilter
+ "limit ?) b on b.id = sa.id ";
if (backdatedTxnsAllowedTill) {
sql = sql
+ "where (CASE WHEN sa.interest_posted_till_date is not null THEN tr.transaction_date >= sa.interest_posted_till_date ELSE tr.transaction_date >= sa.activatedon_date END) ";
@@ -461,6 +479,55 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead
return savingsAccountDataList;
}
/**
* The fixed deposits of one branch, and optionally one product, whose interest may be due on the
* posting date — the candidates an interest posting report is drawn from.
*
* <p>
* "May be" is deliberate. A deposit is selected here on the same cheap test the posting job has
* always used, that its interest has not been posted past the day before, and whether a posting
* period has actually ended is then settled by the interest engine, which is the only thing that
* knows a product's compounding and posting periods. A candidate the engine finds nothing for
* simply contributes no line to the report.
*
* <p>
* Unpaged, unlike the posting job: a report covers one branch and one product and is read in full
* before anybody approves it, so there is no page for a deposit to fall off the end of.
*/
@Override
public List<SavingsAccountData> retrieveFixedDepositsDueForInterestPosting(final boolean backdatedTxnsAllowedTill,
final LocalDate postingDate, final Long officeId, final Long productId) {
final StringBuilder candidates = new StringBuilder("select a.id from m_savings_account a ")
.append("left join m_client ic on ic.id = a.client_id ")
.append("left join m_group ig on ig.id = a.group_id ")
.append("where a.status_enum = ? and a.deposit_type_enum = ? ")
.append("and (a.interest_posted_till_date is null or a.interest_posted_till_date <= ?) ");
final List<Object> params = new ArrayList<>(List.of(ACTIVE_STATUS, DEPOSIT_TYPE_FIXED, postingDate.minusDays(1)));
if (officeId != null) {
candidates.append("and coalesce(ic.office_id, ig.office_id) = ? ");
params.add(officeId);
}
if (productId != null) {
candidates.append("and a.product_id = ? ");
params.add(productId);
}
String sql = "select " + this.savingAccountMapperForInterestPosting.schema() + "join (" + candidates
+ ") b on b.id = sa.id ";
if (backdatedTxnsAllowedTill) {
sql = sql
+ "where (CASE WHEN sa.interest_posted_till_date is not null THEN tr.transaction_date >= sa.interest_posted_till_date ELSE tr.transaction_date >= sa.activatedon_date END) ";
}
sql = sql + " order by sa.id, tr.transaction_date, tr." + CREATED_DATE_DB_FIELD + ", tr.created_date, tr.id";
final List<SavingsAccountData> deposits = this.jdbcTemplate.query(sql, this.savingAccountMapperForInterestPosting, // NOSONAR
params.toArray());
for (final SavingsAccountData deposit : deposits) {
this.savingAccountAssembler.assembleSavings(deposit);
}
return deposits;
}
private static final class SavingAccountMapperForInterestPosting implements ResultSetExtractor<List<SavingsAccountData>> {
private final String schemaSql;
@@ -430,9 +430,9 @@ public class SavingsConfiguration {
SavingsAccountRepositoryWrapper savingsAccountRepositoryWrapper, ColumnValidator columnValidator,
// @Lazy because the accrual service depends on beans from this same package: resolving
// both eagerly closes a cycle and the context fails to start.
@Lazy SavingsDailyInterestService savingsDailyInterestService) {
@Lazy SavingsDailyInterestService savingsDailyInterestService, ConfigurationDomainService configurationDomainService) {
return new SavingsAccountReadPlatformServiceImpl(context, jdbcTemplate, savingAccountAssembler, paginationHelper, columnValidator,
sqlGenerator, savingsAccountRepositoryWrapper, savingsDailyInterestService);
sqlGenerator, savingsAccountRepositoryWrapper, savingsDailyInterestService, configurationDomainService);
}
@Bean
@@ -165,4 +165,5 @@
<include file="parts/0590_savings_interest_posting_report_by_branch.xml" relativeToChangelogFile="true"/>
<include file="parts/0591_cashier_allocation_time_and_deposit_counter_office.xml" relativeToChangelogFile="true"/>
<include file="parts/0592_enable_teller_cashier_maker_checker.xml" relativeToChangelogFile="true"/>
<include file="parts/0593_fd_interest_posting_approval.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>
@@ -0,0 +1,334 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<!--
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.
-->
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.9.xsd">
<!--
Fixed deposit interest stops posting itself.
Until now an FD was paid by the nightly posting job the moment its posting date arrived: the
amount was worked out in memory and written straight to the customer's account, with nothing
in between that anybody could look at, question or sign. The branch learnt what it had paid
by reading the transactions afterwards.
This is the same gate savings interest was put behind in 0589, built for deposits. On a
posting date a report is generated listing every deposit of one branch and one product, what
it has earned, and where that interest is going; an authorised user who did not generate it
approves it; and only the approved figures are posted, as the branch closes its day. A branch
with an unapproved report cannot close.
Where the interest goes is the part that is particular to deposits, and it follows the
product's scheme (m_savings_product.fd_type):
SINGLE interest stays in the deposit and is paid with the principal at maturity
DOUBLE interest is compounded into the deposit, so maturity pays principal plus interest
SPECIAL interest is posted monthly and swept to the customer's linked savings account
so a SPECIAL line also records the savings account the money leaves for, and the transfer it
left on. The report keeps the figures rather than recomputing them at posting time: the
approved list is the authority, and the posting pays exactly what was approved, deposit by
deposit. A regeneration supersedes its predecessor instead of overwriting it, so what was
shown and what was approved stay on the record.
-->
<changeSet author="fineract" id="0593-1-fd-interest-posting-report">
<preConditions onFail="MARK_RAN">
<not><tableExists tableName="m_fd_interest_posting_report"/></not>
</preConditions>
<createTable tableName="m_fd_interest_posting_report">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<!-- Fixed deposit products are savings products with deposit_type_enum 200. -->
<column name="fd_product_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_fdipr_product" referencedTableName="m_savings_product"
referencedColumnNames="id"/>
</column>
<!-- SINGLE, DOUBLE or SPECIAL as the product carried it when the report was generated:
the scheme decides where the interest goes, and a product retyped afterwards must not
change the meaning of figures somebody has already approved. -->
<column name="fd_type" type="VARCHAR(20)" defaultValue="SINGLE">
<constraints nullable="false"/>
</column>
<column name="office_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_fdipr_office" referencedTableName="m_office"
referencedColumnNames="id"/>
</column>
<column name="posting_date" type="DATE">
<constraints nullable="false"/>
</column>
<!-- GENERATED, APPROVED, POSTED, or SUPERSEDED by a regeneration. -->
<column name="status" type="VARCHAR(20)">
<constraints nullable="false"/>
</column>
<column name="total_interest" type="DECIMAL(19,6)" defaultValueNumeric="0">
<constraints nullable="false"/>
</column>
<column name="account_count" type="INT" defaultValueNumeric="0">
<constraints nullable="false"/>
</column>
<!-- As the product mapped them when the report was generated, for display and checking. -->
<column name="payable_gl_account_id" type="BIGINT"/>
<column name="paid_gl_account_id" type="BIGINT"/>
<!-- AUTO from the scheduled run, MANUAL from a regeneration. -->
<column name="generation_mode" type="VARCHAR(10)">
<constraints nullable="false"/>
</column>
<column name="generated_by" type="BIGINT"/>
<column name="generated_at" type="TIMESTAMP" defaultValueComputed="CURRENT_TIMESTAMP">
<constraints nullable="false"/>
</column>
<column name="approved_by" type="BIGINT"/>
<column name="approved_at" type="TIMESTAMP"/>
<!-- True where the head office approved for a branch that did not open that day. -->
<column name="approved_on_behalf" type="BOOLEAN" defaultValueBoolean="false"/>
<column name="posted_at" type="TIMESTAMP"/>
<column name="posting_run_id" type="BIGINT"/>
<!-- Why an approved report could not be posted; the next close retries it. -->
<column name="failure_reason" type="VARCHAR(1000)"/>
</createTable>
<createIndex tableName="m_fd_interest_posting_report" indexName="idx_fdipr_product_date">
<column name="fd_product_id"/>
<column name="posting_date"/>
</createIndex>
<createIndex tableName="m_fd_interest_posting_report" indexName="idx_fdipr_status_date">
<column name="status"/>
<column name="posting_date"/>
</createIndex>
<createIndex tableName="m_fd_interest_posting_report" indexName="idx_fdipr_office_date">
<column name="office_id"/>
<column name="posting_date"/>
</createIndex>
</changeSet>
<changeSet author="fineract" id="0593-2-fd-interest-posting-report-line">
<preConditions onFail="MARK_RAN">
<not><tableExists tableName="m_fd_interest_posting_report_line"/></not>
</preConditions>
<createTable tableName="m_fd_interest_posting_report_line">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="report_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_fdiprl_report"
referencedTableName="m_fd_interest_posting_report" referencedColumnNames="id"/>
</column>
<!-- The fixed deposit itself, which is a row of m_savings_account. -->
<column name="fd_account_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_fdiprl_account" referencedTableName="m_savings_account"
referencedColumnNames="id"/>
</column>
<column name="account_no" type="VARCHAR(50)"/>
<column name="client_name" type="VARCHAR(300)"/>
<column name="office_id" type="BIGINT"/>
<!--
The date the interest engine itself assigned to this posting — the end of the period the
interest was earned in, not the day the branch happens to close.
It is the line's identity, not decoration. The engine decides a period is already paid by
looking for an interest transaction ON that date, so a posting written under any other
date is invisible to it and the same period is computed, reported and paid again. It also
means one deposit can have more than one line on a report: a branch that did not close for
two quarters owes two postings, on two dates, and they stay two.
-->
<column name="interest_posting_date" type="DATE">
<constraints nullable="false"/>
</column>
<column name="interest_amount" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<column name="balance_before" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<column name="balance_after" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<!-- What the deposit is, shown beside what it earned: the checker is approving interest
against a principal, a rate and a term, not against a number on its own. -->
<column name="deposit_amount" type="DECIMAL(19,6)"/>
<column name="interest_rate" type="DECIMAL(19,6)"/>
<column name="maturity_date" type="DATE"/>
<!-- SPECIAL only: the linked savings account this interest is swept to, and the transfer
it left on. Null for SINGLE and DOUBLE, where the interest stays in the deposit. -->
<column name="payout_savings_account_id" type="BIGINT"/>
<column name="payout_account_no" type="VARCHAR(50)"/>
<column name="payout_transaction_id" type="BIGINT"/>
<!-- The interest posting transaction, written when the report is posted. -->
<column name="fd_transaction_id" type="BIGINT"/>
</createTable>
<createIndex tableName="m_fd_interest_posting_report_line" indexName="idx_fdiprl_report">
<column name="report_id"/>
</createIndex>
<createIndex tableName="m_fd_interest_posting_report_line" indexName="idx_fdiprl_account">
<column name="fd_account_id"/>
<column name="interest_posting_date"/>
</createIndex>
</changeSet>
<changeSet author="fineract" id="0593-3-fd-interest-posting-run">
<preConditions onFail="MARK_RAN">
<not><tableExists tableName="m_fd_interest_posting_run"/></not>
</preConditions>
<createTable tableName="m_fd_interest_posting_run">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<!-- One run per report: a retried posting reuses its run rather than opening a second. -->
<column name="report_id" type="BIGINT">
<constraints nullable="false" unique="true" uniqueConstraintName="uq_fdipru_report"/>
</column>
<column name="fd_product_id" type="BIGINT">
<constraints nullable="false"/>
</column>
<column name="office_id" type="BIGINT"/>
<column name="posting_date" type="DATE">
<constraints nullable="false"/>
</column>
<column name="account_count" type="INT" defaultValueNumeric="0">
<constraints nullable="false"/>
</column>
<column name="pooled_amount" type="DECIMAL(19,6)"/>
<column name="distributed_amount" type="DECIMAL(19,6)"/>
<column name="rounding_residual" type="DECIMAL(19,6)"/>
<!-- PENDING, COMPLETED or FAILED. -->
<column name="status" type="VARCHAR(20)">
<constraints nullable="false"/>
</column>
<column name="failure_reason" type="VARCHAR(1000)"/>
<column name="started_at" type="TIMESTAMP" defaultValueComputed="CURRENT_TIMESTAMP"/>
<column name="completed_at" type="TIMESTAMP"/>
</createTable>
</changeSet>
<!--
The scheduled generation. Runs at noon like the savings one, and for the same reason: the
branch has the afternoon to look at the figures and approve them before it closes.
-->
<changeSet author="fineract" id="0593-4-fd-interest-posting-report-job">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">SELECT COUNT(*) FROM job WHERE name = 'Generate Fixed Deposit Interest Posting Report'</sqlCheck>
</preConditions>
<insert tableName="job">
<column name="name" value="Generate Fixed Deposit Interest Posting Report"/>
<column name="display_name" value="Generate Fixed Deposit Interest Posting Report"/>
<column name="short_name" value="FD_IPRPT"/>
<column name="cron_expression" value="0 0 12 1/1 * ? *"/>
<column name="create_time" valueDate="${current_datetime}"/>
<column name="task_priority" valueNumeric="5"/>
<column name="group_name"/>
<column name="previous_run_start_time"/>
<column name="job_key" value="Generate Fixed Deposit Interest Posting ReportJobDetail1 _ DEFAULT"/>
<column name="initializing_errorlog"/>
<column name="is_active" valueBoolean="true"/>
<column name="currently_running" valueBoolean="false"/>
<column name="updates_allowed" valueBoolean="true"/>
<column name="scheduler_group" valueNumeric="1"/>
<column name="is_misfired" valueBoolean="false"/>
<column name="node_id" valueNumeric="1"/>
<column name="is_mismatched_job" valueBoolean="true"/>
</insert>
</changeSet>
<changeSet author="fineract" id="0593-5-fd-interest-posting-report-permissions">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">
SELECT COUNT(*) FROM m_permission WHERE code IN ('READ_FDINTERESTREPORT',
'REGENERATE_FDINTERESTREPORT', 'APPROVE_FDINTERESTREPORT')
</sqlCheck>
</preConditions>
<insert tableName="m_permission">
<column name="grouping" value="portfolio"/>
<column name="code" value="READ_FDINTERESTREPORT"/>
<column name="entity_name" value="FDINTERESTREPORT"/>
<column name="action_name" value="READ"/>
<column name="can_maker_checker" valueBoolean="false"/>
</insert>
<insert tableName="m_permission">
<column name="grouping" value="portfolio"/>
<column name="code" value="REGENERATE_FDINTERESTREPORT"/>
<column name="entity_name" value="FDINTERESTREPORT"/>
<column name="action_name" value="REGENERATE"/>
<column name="can_maker_checker" valueBoolean="false"/>
</insert>
<!--
can_maker_checker stays false on APPROVE: the report IS the maker-checker record. The user
who generates it is the maker and the one who approves it the checker, both held on the
report itself, and the approval is refused if they are the same person. Routing this
through the generic command queue as well would park the approval behind a second approval
and replay it against a staging table it cannot see.
-->
<insert tableName="m_permission">
<column name="grouping" value="portfolio"/>
<column name="code" value="APPROVE_FDINTERESTREPORT"/>
<column name="entity_name" value="FDINTERESTREPORT"/>
<column name="action_name" value="APPROVE"/>
<column name="can_maker_checker" valueBoolean="false"/>
</insert>
</changeSet>
<changeSet author="fineract" id="0593-6-grant-fd-interest-posting-report-permissions">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">
SELECT COUNT(*) FROM m_role_permission rp
JOIN m_permission p ON p.id = rp.permission_id
WHERE p.code IN ('READ_FDINTERESTREPORT', 'REGENERATE_FDINTERESTREPORT',
'APPROVE_FDINTERESTREPORT')
</sqlCheck>
</preConditions>
<!-- Super user and manager-named roles, as 0589 grants the savings equivalent. -->
<sql>
INSERT INTO m_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM m_role r
CROSS JOIN m_permission p
WHERE p.code IN ('READ_FDINTERESTREPORT', 'REGENERATE_FDINTERESTREPORT',
'APPROVE_FDINTERESTREPORT')
AND (LOWER(r.name) LIKE '%manager%' OR LOWER(r.name) = 'super user')
AND NOT EXISTS (
SELECT 1 FROM m_role_permission rp
WHERE rp.role_id = r.id AND rp.permission_id = p.id
)
</sql>
</changeSet>
<!--
The switch back. With this on, fixed deposits are held out of the nightly posting job and paid
only through an approved report; with it off, the job pays them directly as it always did and
the report screens simply have nothing to show. It is here so a bank that hits trouble on the
new path can return to the old one without a code change, and so the two never run at once —
every query that selects deposits for posting reads this same flag.
-->
<changeSet author="fineract" id="0593-7-fd-interest-posting-approval-configuration">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">SELECT COUNT(*) FROM c_configuration WHERE name = 'fd-interest-posting-approval'</sqlCheck>
</preConditions>
<insert tableName="c_configuration">
<column name="name" value="fd-interest-posting-approval"/>
<column name="value" valueNumeric="0"/>
<column name="enabled" valueBoolean="true"/>
<column name="is_trap_door" valueBoolean="false"/>
<column name="description"
value="Fixed deposit interest is reported and approved before it is posted, and posts when the branch closes its day. Turn this off to let the nightly job post fixed deposit interest directly, as it did before."/>
</insert>
</changeSet>
</databaseChangeLog>
@@ -68,6 +68,18 @@ public interface SavingsAccountReadPlatformService {
List<SavingsAccountData> retrieveAllSavingsDataForInterestPosting(boolean backdatedTxnsAllowedTill, int pageSize, Integer status,
Long maxSavingsId);
/**
* The active fixed deposits of one branch — and one product, where given — whose interest may be
* due for posting on the date. The interest engine settles whether any actually is.
*
* @param officeId
* the branch the deposit's customer belongs to, or null for every branch
* @param productId
* one fixed deposit product, or null for every product
*/
List<SavingsAccountData> retrieveFixedDepositsDueForInterestPosting(boolean backdatedTxnsAllowedTill, LocalDate postingDate,
Long officeId, Long productId);
List<SavingsAccountTransactionData> retrieveAllTransactionData(List<String> refNo);
Long retrieveAccountIdByExternalId(ExternalId externalId);