This is an automated email from the ASF dual-hosted git repository.

adamsaghy pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/fineract.git

commit 92b2fdd77b2cee7bf8ee438e5636e15752589d6b
Merge: 687290e197 7f4556ae8f
Author: Adam Saghy <[email protected]>
AuthorDate: Thu Nov 5 17:11:49 2026 +0000

    Merge pull request #6614 from Ashutosh-Panda2004/FINERACT-2908
    
    FINERACT-2908: Withhold tax when the Post Interest For Savings job posts 
interest

 .../portfolio/savings/data/SavingsAccountData.java |  11 +-
 .../data/SavingsAccountTransactionData.java        |   4 +
 .../SavingsAccountReadPlatformServiceImpl.java     | 151 ++++++++++++
 .../SavingsAccountReadPlatformServiceImplTest.java |  94 +++++++-
 .../service/SavingsSchedularInterestPoster.java    | 111 ++++++++-
 .../SavingsSchedularInterestPosterTest.java        | 261 +++++++++++++++++++++
 .../SavingsInterestPostingJobIntegrationTest.java  | 256 ++++++++++++++++++++
 7 files changed, 884 insertions(+), 4 deletions(-)

diff --cc 
fineract-savings/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularInterestPoster.java
index bceb5543f7,b809c03be0..0e9a52aaba
--- 
a/fineract-savings/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularInterestPoster.java
+++ 
b/fineract-savings/src/main/java/org/apache/fineract/portfolio/savings/service/SavingsSchedularInterestPoster.java
@@@ -132,32 -132,32 +135,37 @@@ public class SavingsSchedularInterestPo
                      final String key = 
savingsAccountTransactionData.getRefNo();
                      final SavingsAccountTransactionData dataFromFetch = 
savingsAccountTransactionDataHashMap.get(key);
                      
savingsAccountTransactionData.setId(dataFromFetch.getId());
-                     if (savingsAccountData.getGlAccountIdForSavingsControl() 
!= 0
+                     if 
(savingsAccountTransactionData.isWithHoldTaxAndNotReversed()) {
+                         addWithholdTaxJournalEntries(paramsForGLInsertion, 
savingsAccountData, savingsAccountTransactionData, currencyCode,
+                                 userId);
+                     } else if 
(savingsAccountData.getGlAccountIdForSavingsControl() != 0
                              && 
savingsAccountData.getGlAccountIdForInterestOnSavings() != 0) {
                          OffsetDateTime auditDatetime = 
DateUtils.getAuditOffsetDateTime();
 -                        BigDecimal amount = 
savingsAccountTransactionData.getAmount();
 -                        // interest posted to an overdrawn account pays down 
the overdraft first, as in the accounting
 -                        // processors; the debit side is the same for both 
parts
 -                        final BigDecimal overdraftAmount = 
savingsAccountTransactionData.getTransactionType().isInterestPosting()
 -                                ? 
savingsAccountTransactionData.getOverdraftAmount()
 -                                : null;
 -                        if (MathUtil.isGreaterThanZero(overdraftAmount)) {
 +                        if 
(savingsAccountTransactionData.getTransactionType().isInterestPosting()) {
 +                            // booked from the same rules as a manual posting 
in the accounting processors
 +                            for (final Leg leg : 
SavingsInterestPostingLegs.legsFor(
 +                                    
savingsAccountData.isCashBasedAccountingEnabledOnSavingsProduct(),
 +                                    
savingsAccountTransactionData.getAmount(), 
savingsAccountTransactionData.getOverdraftAmount())) {
 +                                addJournalEntryPair(paramsForGLInsertion, 
savingsAccountData, savingsAccountTransactionData,
 +                                        glAccountId(savingsAccountData, 
leg.accountTypeToDebit()),
 +                                        glAccountId(savingsAccountData, 
leg.accountTypeToCredit()), leg.amount(), currencyCode, userId,
 +                                        auditDatetime);
 +                            }
 +                        } else if 
(savingsAccountTransactionData.getTransactionType().isOverDraftInterestPosting())
 {
                              addJournalEntryPair(paramsForGLInsertion, 
savingsAccountData, savingsAccountTransactionData,
 -                                    
savingsAccountData.getGlAccountIdForOverdraftPorfolio(), overdraftAmount, 
currencyCode, userId,
 -                                    auditDatetime);
 -                            amount = amount.subtract(overdraftAmount);
 -                        }
 -                        if (MathUtil.isGreaterThanZero(amount)) {
 -                            addJournalEntryPair(paramsForGLInsertion, 
savingsAccountData, savingsAccountTransactionData,
 -                                    
savingsAccountTransactionData.getAccountCredit(), amount, currencyCode, userId, 
auditDatetime);
 +                                    
savingsAccountTransactionData.getAccountDebit(), 
savingsAccountTransactionData.getAccountCredit(),
 +                                    
savingsAccountTransactionData.getAmount(), currencyCode, userId, auditDatetime);
 +                        } else {
 +                            // the job only has GL rules for the transactions 
it posts; another type would otherwise be
 +                            // booked without accounts and fail the whole 
batch insert with a less obvious error
 +                            throw new IllegalStateException("The Post 
Interest For Savings job has no GL rule for transaction type "
 +                                    + 
savingsAccountTransactionData.getTransactionType().getCode() + " on savings 
account "
 +                                    + savingsAccountData.getId());
                          }
                      }
- 
+                 } else if (savingsAccountTransactionData.getId() != null && 
savingsAccountTransactionData.isWithHoldTaxAndReversed()) {
+                     
addJournalEntryReversalsForWithholdTax(paramsForGLInsertion, 
savingsAccountData, savingsAccountTransactionData,
+                             currencyCode, userId);
                  }
              }
          }
@@@ -167,27 -167,79 +175,91 @@@
          }
      }
  
 +    // the GL accounts the job loaded for the savings product, by mapping 
type; cash and accrual mapping types share
 +    // their values
 +    private static Long glAccountId(final SavingsAccountData 
savingsAccountData, final int accountType) {
 +        return switch (AccrualAccountsForSavings.fromInt(accountType)) {
 +            case SAVINGS_CONTROL -> 
savingsAccountData.getGlAccountIdForSavingsControl();
 +            case INTEREST_ON_SAVINGS -> 
savingsAccountData.getGlAccountIdForInterestOnSavings();
 +            case INTEREST_PAYABLE -> 
savingsAccountData.getGlAccountIdForInterestPayable();
 +            case OVERDRAFT_PORTFOLIO_CONTROL -> 
savingsAccountData.getGlAccountIdForOverdraftPorfolio();
 +            default -> throw new IllegalStateException("The job does not load 
the GL account for savings mapping type " + accountType);
 +        };
 +    }
 +
      private void addJournalEntryPair(final List<Object[]> 
paramsForGLInsertion, final SavingsAccountData savingsAccountData,
 -            final SavingsAccountTransactionData 
savingsAccountTransactionData, final Long creditAccountId, final BigDecimal 
amount,
 -            final String currencyCode, final Long userId, final 
OffsetDateTime auditDatetime) {
 +            final SavingsAccountTransactionData 
savingsAccountTransactionData, final Long debitAccountId, final Long 
creditAccountId,
 +            final BigDecimal amount, final String currencyCode, final Long 
userId, final OffsetDateTime auditDatetime) {
          paramsForGLInsertion.add(journalEntryParams(savingsAccountData, 
savingsAccountTransactionData, creditAccountId,
                  JournalEntryType.CREDIT, amount, currencyCode, userId, 
auditDatetime));
 -        paramsForGLInsertion.add(journalEntryParams(savingsAccountData, 
savingsAccountTransactionData,
 -                savingsAccountTransactionData.getAccountDebit(), 
JournalEntryType.DEBIT, amount, currencyCode, userId, auditDatetime));
 +        paramsForGLInsertion.add(journalEntryParams(savingsAccountData, 
savingsAccountTransactionData, debitAccountId,
 +                JournalEntryType.DEBIT, amount, currencyCode, userId, 
auditDatetime));
      }
  
+     // Mirrors the accounting processors for savings: savings control is 
debited with the total withheld
+     // tax, and the credit account of each tax component is credited with 
that component's share. A tax
+     // component without a credit account falls back to the product's savings 
reference account.
+     private void addWithholdTaxJournalEntries(final List<Object[]> 
paramsForGLInsertion, final SavingsAccountData savingsAccountData,
+             final SavingsAccountTransactionData 
savingsAccountTransactionData, final String currencyCode, final Long userId) {
+         if (savingsAccountData.getGlAccountIdForSavingsControl() == null || 
savingsAccountData.getGlAccountIdForSavingsControl() == 0) {
+             return;
+         }
+         final OffsetDateTime auditDatetime = 
DateUtils.getAuditOffsetDateTime();
+         paramsForGLInsertion.add(
+                 journalEntryParams(savingsAccountData, 
savingsAccountTransactionData, 
savingsAccountData.getGlAccountIdForSavingsControl(),
+                         JournalEntryType.DEBIT, 
savingsAccountTransactionData.getAmount(), currencyCode, userId, 
auditDatetime));
+         if (savingsAccountTransactionData.getTaxDetails() != null) {
+             for (final TaxDetailsData taxDetailsData : 
savingsAccountTransactionData.getTaxDetails()) {
+                 Long creditAccountId = null;
+                 if (taxDetailsData.getTaxComponent() != null && 
taxDetailsData.getTaxComponent().getCreditAccount() != null) {
+                     creditAccountId = 
taxDetailsData.getTaxComponent().getCreditAccount().getId();
+                 }
+                 if (creditAccountId == null) {
+                     creditAccountId = 
savingsAccountData.getGlAccountIdForSavingsReference();
+                 }
+                 if (creditAccountId != null && creditAccountId != 0) {
+                     
paramsForGLInsertion.add(journalEntryParams(savingsAccountData, 
savingsAccountTransactionData, creditAccountId,
+                             JournalEntryType.CREDIT, 
taxDetailsData.getAmount(), currencyCode, userId, auditDatetime));
+                 }
+             }
+         }
+     }
+ 
+     // A withhold tax transaction reversed in the update batch above keeps 
the journal entries it booked
+     // when it was posted, so its tax would stay credited in the GL on top of 
the corrected transaction.
+     // The accounting processors reverse such a transaction by booking 
entries with the debit and credit
+     // sides swapped under the same transaction id, so do the same here: read 
back the entries booked for
+     // the transaction and book the mirror of what is still outstanding per 
GL account. A transaction
+     // whose entries were already reversed nets to zero per account and books 
nothing.
+     private void addJournalEntryReversalsForWithholdTax(final List<Object[]> 
paramsForGLInsertion,
+             final SavingsAccountData savingsAccountData, final 
SavingsAccountTransactionData savingsAccountTransactionData,
+             final String currencyCode, final Long userId) {
+         final List<Map<String, Object>> bookedEntries = 
this.jdbcTemplate.queryForList(queryForJournalEntriesOfTransaction(),
+                 SAVINGS_TRANSACTION_IDENTIFIER + 
savingsAccountTransactionData.getId());
+         final Map<Long, BigDecimal> outstandingByAccountId = new 
LinkedHashMap<>();
+         for (final Map<String, Object> bookedEntry : bookedEntries) {
+             final Long accountId = ((Number) 
bookedEntry.get("account_id")).longValue();
+             final Integer entryType = ((Number) 
bookedEntry.get("type_enum")).intValue();
+             final BigDecimal amount = (BigDecimal) bookedEntry.get("amount");
+             final BigDecimal signedAmount = 
JournalEntryType.fromInt(entryType) == JournalEntryType.DEBIT ? amount : 
amount.negate();
+             outstandingByAccountId.merge(accountId, signedAmount, 
BigDecimal::add);
+         }
+         final OffsetDateTime auditDatetime = 
DateUtils.getAuditOffsetDateTime();
+         for (final Map.Entry<Long, BigDecimal> outstanding : 
outstandingByAccountId.entrySet()) {
+             if (outstanding.getValue().signum() > 0) {
+                 
paramsForGLInsertion.add(journalEntryParams(savingsAccountData, 
savingsAccountTransactionData, outstanding.getKey(),
+                         JournalEntryType.CREDIT, outstanding.getValue(), 
currencyCode, userId, auditDatetime));
+             } else if (outstanding.getValue().signum() < 0) {
+                 
paramsForGLInsertion.add(journalEntryParams(savingsAccountData, 
savingsAccountTransactionData, outstanding.getKey(),
+                         JournalEntryType.DEBIT, 
outstanding.getValue().negate(), currencyCode, userId, auditDatetime));
+             }
+         }
+     }
+ 
+     private String queryForJournalEntriesOfTransaction() {
+         return "SELECT account_id, type_enum, amount FROM 
acc_gl_journal_entry WHERE transaction_id = ?";
+     }
+ 
      private Object[] journalEntryParams(final SavingsAccountData 
savingsAccountData,
              final SavingsAccountTransactionData 
savingsAccountTransactionData, final Long accountId, final JournalEntryType 
type,
              final BigDecimal amount, final String currencyCode, final Long 
userId, final OffsetDateTime auditDatetime) {

Reply via email to