Compare commits

...
12 Commits
Author SHA1 Message Date
keshav 99ef5edfd8 Merge branch 'dev-latest' of https://git.lincpay.tech/CBSNexora/cbsnexora-backend into dev-latest
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
2026-10-12 10:25:19 +05:30
keshav 9df8e924a1 feat: recurring deposit product rules, lien, auto debit, missed installment penalty, and jobs 2026-10-12 10:25:12 +05:30
nitesh 1922455996 Merge branch 'dev-latest' of https://git.lincpay.tech/CBSNexora/cbsnexora-backend into dev-latest
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
2026-10-07 10:18:27 +05:30
keshav cca4ae583f Merge branch 'dev-latest' of https://git.lincpay.tech/CBSNexora/cbsnexora-backend into dev-latest
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
2026-10-07 10:14:13 +05:30
keshav 99a7e04872 feat: updates for tds services, rbi reserve config, and cashier api resources 2026-10-07 10:14:04 +05:30
niteshandClaude Opus 5 ac7873a51e feat(shares): add preview-validate endpoint, fix document attachment 500
ClerkShareWithdrawalRequestApiResource: extracted validate(Long)'s checklist
logic into buildShareWithdrawalChecks(Map<?, ?>) and added a new
POST /preview-validate endpoint that runs it against a draft submission (same
fields submit() accepts, same Sundry-downgrade rule applied first) instead of
an already-persisted request. Lets the clerk see the exact checklist a manager
will see on approval before the request is even submitted, with zero risk of
the two checklists drifting apart, since both now call the same method. The
one check validate() runs that a draft cannot -- "Maker and Checker are
different users" -- is reported as a fixed reminder instead of silently
dropped, since the clerk previewing this is necessarily the maker and no
checker has been chosen yet.

DocumentReadPlatformServiceImpl.retrieveDocumentContent(): a document/signature
whose m_document row survives but whose underlying file is missing from the
content store (the usual cause is a database copied between environments
without its file store) was throwing an uncaught ContentStoreException,
surfacing as a raw 500 on every fetch. Now caught and converted to the same
DocumentNotFoundException (404) ImageReadPlatformServiceImpl already uses for
the identical situation on client photos, so the frontend's existing
graceful-fallback handling for a missing attachment applies here too.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-06 22:40:12 +05:30
niteshandClaude Opus 5 643427bd1a fix(shares): correct share transaction lookup and validate NONE settlements
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
redemptionValueOf() read from "m_share_account_transaction" with a
"share_account_id" column. The table is m_share_account_transactions and the
column is account_id, so every share withdrawal approval failed with a
BadSqlGrammarException on the Share Sundry balance guard, before any posting was
attempted. The lookup now also filters on is_active, matching
ShareAdvanceCollectionApiResource.shareValueOf(), so a reversed purchase cannot
price a redemption.

validate() branched on "GL" versus everything else, but approve() handles a
third settlement mode: submit() downgrades a request to NONE when the clerk
names the product's own Share Sundry GL as the destination, and that mode posts
Dr Share Capital / Cr Share Sundry and stops. Validating it as a savings
settlement reported a missing fund source mapping that no posting in this mode
ever reads, so a correct request showed a failed check. NONE is now reported as
not applicable for both the linked-savings and the fund-source checks.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-06 19:03:51 +05:30
niteshandClaude Sonnet 5 6c7c0f8445 build: freeze the default (non-release/maintenance branch) jar version
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
git-versioning's rev{} fallback previously derived the SNAPSHOT version from
the nearest reachable git tag (major.(minor+1).0-SNAPSHOT), so the built jar's
name drifted as tags moved. Pins it to a fixed 1.15.0-SNAPSHOT instead so the
jar name stays predictable across builds on dev-latest/feature branches.
release/*.*.* and maintenance/*.* branches still version off their own tags,
unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 12:42:12 +05:30
niteshandClaude Sonnet 5 88157ee9d6 Revert "Enforce same-user maker-checker restriction"
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
Reverts commits 2afd4aaf8 and 11a0d502b (both by anshul, same title).
Restores the CHECKER_SUPER_USER self-approval bypass in CommandSourceService
and the six *EditWritePlatformServiceJpaRepositoryImpl classes, and restores
the original isSameMakerCheckerEnabled()/isCheckerSuperUser()-gated same-user
check in PortfolioCommandSourceWritePlatformServiceImpl. Removes the
0588_persist_manually_enabled_maker_checker_permissions.xml migration added
alongside the restriction.

The unconditional same-user block these commits introduced was blocking
legitimate single-admin operation/testing (e.g. creating and then activating
a client as the same CHECKER_SUPER_USER), with no way to resolve it from
inside the app.

11a0d502b's only change (0012_seed_default_platform_api_client.xml comment
wording) is a no-op here: that exact text was independently reworded again by
82336cbe9 after 11a0d502b landed, so there is nothing left of 11a0d502b's
change to revert in that file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 10:02:34 +05:30
niteshandClaude Sonnet 5 760fff8d3e fix(permissions): persist manually-enabled Teller/Cashier maker-checker settings
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Same pattern as 0588_persist_manually_enabled_maker_checker_permissions:
converts a manually-applied Configure Maker Checker Tasks change into a
repeatable migration, this time for the Teller/Cashier module. Found by
diffing can_maker_checker across every permission code common to
fineract_lincpay and a reference environment -- ALLOCATECASHIER_TELLER,
ALLOCATECASHTOCASHIER_TELLER, SETTLECASHFROMCASHIER_TELLER, and
UPDATECASHIERALLOCATION_TELLER were true there but still seeded false here,
confirming they were toggled on manually and never captured for any other
environment (including UAT). The _CHECKER permissions already exist and are
already granted to Clerk/Teller/Branch Manager, so approval works as soon
as this migration runs -- no role-grant changes needed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-05 16:29:26 +05:30
keshav d7ff4e4a7b Merge remote-tracking branch 'origin/dev-latest' into dev-latest
Fineract E2E Tests / E2E Tests (Shard 5 of 10) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, build-core) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (main, cucumber) (push) Canceled after 0s
Fineract Build & Cucumber tests (without E2E tests) / verify (progressive-loan, build-progressive-loan) (push) Canceled after 0s
Fineract Docker Builds / build (false, docker-compose-postgresql.yml, postgresql) (push) Canceled after 0s
Fineract Docker Builds / build (true, docker-compose.yml, mariadb) (push) Canceled after 0s
Fineract Documentation build / build (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 1 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 10 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 2 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 3 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 4 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 7 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 8 of 10) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 9 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-1) (push) Canceled after 0s
Fineract E2E Tests / E2E Tests (Shard 6 of 10) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MariaDB / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - MySQL / test (test-core-5) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-1) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-2) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-3) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-4) (push) Canceled after 0s
Fineract Cargo & Unit- & Integration tests - PostgreSQL / test (test-core-5) (push) Canceled after 0s
Fineract Liquibase Only mode - PostgreSQL / test (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with ActiveMQ (push) Canceled after 0s
Fineract Messaging Smoke Tests / Smoke Test with Kafka (push) Canceled after 0s
2026-10-05 12:43:38 +05:30
keshav 7068d65422 feat: teller uniqueness, cashier allocation office check and interest posting report updates 2026-10-05 12:42:44 +05:30
110 changed files with 6905 additions and 1881 deletions
+1 -1
View File
@@ -154,7 +154,7 @@ gitVersioning.apply {
}
}
rev {
version = '${describe.tag.version.major}.${describe.tag.version.minor.next}.0-SNAPSHOT'
version = '1.15.0-SNAPSHOT'
}
}
@@ -33,4 +33,6 @@ public interface TellerRepository extends JpaRepository<Teller, Long>, JpaSpecif
Collection<Teller> findTellerByOfficeId(Long officeId);
long countByDeletedFalse();
long countByOfficeIdAndDeletedFalse(Long officeId);
}
@@ -58,4 +58,9 @@ public class TellerRepositoryWrapper {
public boolean existsAny() {
return this.repository.countByDeletedFalse() > 0;
}
/** Whether the branch already has a (not deleted) teller — each branch keeps one vault of its own. */
public boolean existsInOffice(final Long officeId) {
return this.repository.countByOfficeIdAndDeletedFalse(officeId) > 0;
}
}
@@ -28,4 +28,9 @@ public class TellerAlreadyExistsException extends AbstractPlatformDomainRuleExce
public TellerAlreadyExistsException() {
super(ERROR_MESSAGE_CODE, DEFAULT_ERROR_MESSAGE);
}
public TellerAlreadyExistsException(final String officeName) {
super(ERROR_MESSAGE_CODE, "Cannot create teller: " + officeName + " already has a teller. Each branch has one teller.",
officeName);
}
}
@@ -137,16 +137,7 @@ public class CommandSourceService {
String permission = commandSource.getPermissionCode();
boolean isMakerChecker = configurationDomainService.isMakerCheckerEnabledForTask(permission);
if (isMakerChecker || result.isRollbackTransaction()) {
// isApprovedByChecker is only ever true here for a genuine checker approval
// (PortfolioCommandSourceWritePlatformServiceImpl.approveEntry(), which has already run
// validateMakerCheckerTransaction() and confirmed the approver is not the maker) or a user
// editing their own account details (CommandWrapper.isChangeOfOwnUserDetails() - maker-checker
// genuinely does not apply there). On the ORIGINAL submission this is always false and `user`
// here is always the maker themselves, so there is deliberately no CHECKER_SUPER_USER (or any
// other) bypass at this point: holding CHECKER_SUPER_USER lets a user approve someone ELSE's
// request without needing the specific <TASK>_CHECKER permission, it must never let a maker
// auto-approve their own submission just by holding it.
if (isApprovedByChecker) {
if (isApprovedByChecker || isSuperUserBypassAllowed(commandSource, user)) {
commandSource.markAsChecked(user);
} else {
if (commandSource.isSanitized()) {
@@ -160,6 +151,26 @@ public class CommandSourceService {
return result;
}
private boolean isSuperUserBypassAllowed(CommandSource commandSource, AppUser user) {
if (!user.isCheckerSuperUser()) {
return false;
}
if ("GLACCOUNT".equalsIgnoreCase(commandSource.getEntityName())
|| "CBSBASEINTERESTRATE".equalsIgnoreCase(commandSource.getEntityName())
|| "CHARGE".equalsIgnoreCase(commandSource.getEntityName())
|| "LOANPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|| "SAVINGSPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|| "CURRENTPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|| "SHAREPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|| "FIXEDDEPOSITPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|| "RECURRINGDEPOSITPRODUCT".equalsIgnoreCase(commandSource.getEntityName())
|| "USER".equalsIgnoreCase(commandSource.getEntityName())
|| "ROLE".equalsIgnoreCase(commandSource.getEntityName())) {
return false;
}
return true;
}
private void sanitizeJson(@NonNull CommandSource commandSource, Set<String> sanitizeKeys) {
if (sanitizeKeys == null || sanitizeKeys.isEmpty()) {
return;
@@ -3157,6 +3157,15 @@ public class CommandWrapperBuilder {
return this;
}
public CommandWrapperBuilder extendTenureRecurringDepositAccount(final Long accountId) {
this.actionName = "EXTENDTENURE";
this.entityName = "RECURRINGDEPOSITACCOUNT";
this.entityId = accountId;
this.savingsId = accountId;
this.href = "/recurringdepositaccounts/" + accountId + "?command=extendTenure";
return this;
}
public CommandWrapperBuilder prematureCloseRecurringDepositAccount(final Long accountId) {
this.actionName = "PREMATURECLOSE";
this.entityName = "RECURRINGDEPOSITACCOUNT";
@@ -48,12 +48,6 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
private final FromJsonHelper fromApiJsonHelper;
private final CommandProcessingService processAndLogCommandService;
private final SchedulerJobRunnerReadService schedulerJobRunnerReadService;
// No longer consulted by validateMakerCheckerTransaction() below: the maker-identity rule (a user
// can never approve their own submission) is now unconditional and isSameMakerCheckerEnabled() no
// longer overrides it. Left injected rather than removed - enable-same-maker-checker is still a
// live, independently-configurable global switch (System -> Configurations); deleting this field,
// and by extension deciding that switch should stop existing altogether, is a separate decision
// from closing this specific self-approval loophole.
private final ConfigurationDomainService configurationService;
@Override
@@ -129,20 +123,14 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
AppUser appUser = this.context.authenticatedUser();
String permissionCode = commandSource.getPermissionCode();
appUser.validateHasCheckerPermissionTo(permissionCode);
// Maker-identity rule: the user who submitted a command may never be the one who approves
// (or rejects) it - this is a fixed platform rule, not overridable by CHECKER_SUPER_USER (that
// permission still lets its holder action a DIFFERENT user's request without needing the
// specific <TASK>_CHECKER permission - see validateHasCheckerPermissionTo() above - it just no
// longer lets them action their own) and not overridable by the enable-same-maker-checker
// global switch (isSameMakerCheckerEnabled() is deliberately no longer consulted here; that
// configuration is left in place and unused for this decision rather than removed, since
// deleting a still-configurable global setting is a separate decision from this one).
AppUser maker = commandSource.getMaker();
if (maker == null) {
throw new UnsupportedCommandException(permissionCode, "Maker user is missing.");
}
if (Objects.equals(appUser.getId(), maker.getId())) {
throw new UnsupportedCommandException(permissionCode, "Can not be checked by the same user.");
if (!configurationService.isSameMakerCheckerEnabled() && !appUser.isCheckerSuperUser()) {
AppUser maker = commandSource.getMaker();
if (maker == null) {
throw new UnsupportedCommandException(permissionCode, "Maker user is missing.");
}
if (Objects.equals(appUser.getId(), maker.getId())) {
throw new UnsupportedCommandException(permissionCode, "Can not be checked by the same user.");
}
}
return commandSource;
}
@@ -75,6 +75,8 @@ public enum JobName {
AML_STR_WEEKLY_DIGEST("AML STR Weekly Digest"), //
CLIENT_BEHAVIOUR_WINDOW("Client Behaviour Window Computation"), //
SAVE_RBI_FORM_A_RETURN("Save RBI Form A Return"), //
EXECUTE_RD_AUTO_DEBIT("Execute RD Auto Debit"), //
APPLY_RD_MISSED_INSTALLMENT_PENALTY("Apply RD Missed Installment Penalty"), //
; //
private final String name;
@@ -432,6 +432,10 @@ public final class DepositsApiConstants {
recurringDepositRequestData.add("prematureWithdrawalOption");
recurringDepositRequestData.add("tenureFlexibility");
recurringDepositRequestData.add("lienMarked");
recurringDepositRequestData.add("lienPercentage");
recurringDepositRequestData.add("missedInstallmentGraceDays");
recurringDepositRequestData.add("missedInstallmentPenaltyType");
recurringDepositRequestData.add("missedInstallmentPenaltyAmount");
recurringDepositRequestData.add("withdrawalFeeForTransfers");
recurringDepositRequestData.add("enableLockinPeriod");
recurringDepositRequestData.add("maturityInstructions");
@@ -491,6 +495,10 @@ public final class DepositsApiConstants {
recurringDepositRequestData.add("prematureWithdrawalOption");
recurringDepositRequestData.add("tenureFlexibility");
recurringDepositRequestData.add("lienMarked");
recurringDepositRequestData.add("lienPercentage");
recurringDepositRequestData.add("missedInstallmentGraceDays");
recurringDepositRequestData.add("missedInstallmentPenaltyType");
recurringDepositRequestData.add("missedInstallmentPenaltyAmount");
recurringDepositRequestData.add("maturityInstructions");
recurringDepositRequestData.add("creditMaturityProceeds");
recurringDepositRequestData.add("penaltyGracePeriodMissedInstallments");
@@ -648,6 +656,8 @@ public final class DepositsApiConstants {
recurringDepositRequestData.add(SavingsApiConstants.balanceSwapOptionParamName);
recurringDepositRequestData.add(SavingsApiConstants.msmeParamName);
recurringDepositRequestData.add(SavingsApiConstants.autoDebitFacilityParamName);
// Lien Marked: how much of this deposit may be given as loan, capped by its product's percentage.
recurringDepositRequestData.add("lienPercentage");
recurringDepositRequestData.add(isSeniorCitizenParamName);
recurringDepositRequestData.add(seniorCitizenInterestRateParamName);
return recurringDepositRequestData;
@@ -234,6 +234,20 @@ public final class SavingsAccountData implements Serializable {
return this.transferInterestToLinkedAccount;
}
/**
* True for a recurring deposit opened under a product whose Interest Calculation Type is "Simple": its interest
* never compounds. Transient because it is only read by the batch interest-posting engine.
*/
private transient boolean simpleInterest;
public void setSimpleInterest(final boolean simpleInterest) {
this.simpleInterest = simpleInterest;
}
public boolean isSimpleInterest() {
return this.simpleInterest;
}
public static SavingsAccountData importInstanceIndividual(Long clientId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate,
BigDecimal nominalAnnualInterestRate, EnumOptionData interestCompoundingPeriodTypeEnum,
EnumOptionData interestPostingPeriodTypeEnum, EnumOptionData interestCalculationTypeEnum,
@@ -180,6 +180,12 @@ public final class SavingsHelper {
immediateWithdrawalOfInterest);
}
public Money calculateInterestForAllPostingPeriods(final MonetaryCurrency currency, final List<PostingPeriod> allPeriods,
LocalDate accountLockedUntil, Boolean immediateWithdrawalOfInterest, final boolean simpleInterest) {
return COMPOUND_INTEREST_HELPER.calculateInterestForAllPostingPeriods(currency, allPeriods, accountLockedUntil,
immediateWithdrawalOfInterest, simpleInterest);
}
public Collection<Long> fetchPostInterestTransactionIds(Long accountId) {
return this.accountTransfersReadPlatformService.fetchPostInterestTransactionIds(accountId);
}
@@ -40,6 +40,18 @@ public class CompoundInterestHelper {
*/
public Money calculateInterestForAllPostingPeriods(final MonetaryCurrency currency, final List<PostingPeriod> allPeriods,
LocalDate lockUntil, Boolean interestTransferEnabled) {
return calculateInterestForAllPostingPeriods(currency, allPeriods, lockUntil, interestTransferEnabled, false);
}
/**
* @param simpleInterest
* - when true, earned interest is never added back to the balance it is earned on, so every period
* earns on the principal alone (a recurring deposit whose product's Interest Calculation Type is
* "Simple"). Compounding and posting periods still decide when interest is recognised and posted;
* they just stop changing how much is earned.
*/
public Money calculateInterestForAllPostingPeriods(final MonetaryCurrency currency, final List<PostingPeriod> allPeriods,
LocalDate lockUntil, Boolean interestTransferEnabled, final boolean simpleInterest) {
// sum up the 'rounded' values that are posted each posting period
Money interestEarned = Money.zero(currency);
@@ -47,7 +59,8 @@ public class CompoundInterestHelper {
// total interest earned in previous periods but not yet recognised
BigDecimal compoundedInterest = BigDecimal.ZERO;
BigDecimal unCompoundedInterest = BigDecimal.ZERO;
final CompoundInterestValues compoundInterestValues = new CompoundInterestValues(compoundedInterest, unCompoundedInterest);
final CompoundInterestValues compoundInterestValues = simpleInterest ? new SimpleInterestValues()
: new CompoundInterestValues(compoundedInterest, unCompoundedInterest);
for (final PostingPeriod postingPeriod : allPeriods) {
final BigDecimal interestEarnedThisPeriod = postingPeriod.calculateInterest(compoundInterestValues);
@@ -67,4 +80,25 @@ public class CompoundInterestHelper {
return interestEarned;
}
/**
* Interest values that refuse to compound: whatever a compounding period hands over to be compounded is dropped,
* so the balance interest is earned on never includes interest already earned.
*/
private static final class SimpleInterestValues extends CompoundInterestValues {
SimpleInterestValues() {
super(BigDecimal.ZERO, BigDecimal.ZERO);
}
@Override
public void setCompoundedInterest(final BigDecimal interestToBeCompounded) {
super.setCompoundedInterest(BigDecimal.ZERO);
}
@Override
public boolean isSimpleInterest() {
return true;
}
}
}
@@ -50,4 +50,9 @@ public class CompoundInterestValues {
this.uncompoundedInterest = BigDecimal.ZERO;
}
/** True when earned interest must never earn interest itself - not across periods, and not within one either. */
public boolean isSimpleInterest() {
return false;
}
}
@@ -94,6 +94,18 @@ public final class DailyCompoundingPeriod implements CompoundingPeriod {
return interestEarned;
}
/** Interest on each day's balance alone, none of it added to the balance - for simple interest. */
public BigDecimal calculateSimpleInterest(final BigDecimal interestRateAsFraction, final long daysInYear,
final BigDecimal minBalanceForInterestCalculation, final BigDecimal overdraftInterestRateAsFraction,
final BigDecimal minOverdraftForInterestCalculation) {
BigDecimal interestEarned = BigDecimal.ZERO;
for (final EndOfDayBalance balance : this.endOfDayBalances) {
interestEarned = interestEarned.add(balance.calculateInterestOnBalance(BigDecimal.ZERO, interestRateAsFraction, daysInYear,
minBalanceForInterestCalculation, overdraftInterestRateAsFraction, minOverdraftForInterestCalculation));
}
return interestEarned;
}
@Override
public LocalDateInterval getPeriodInterval() {
return this.periodInterval;
@@ -301,10 +301,17 @@ public final class PostingPeriod {
// to be applied to the balanced for interest calculation
for (final CompoundingPeriod compoundingPeriod : this.compoundingPeriods) {
final BigDecimal interestUnrounded = compoundingPeriod.calculateInterest(this.interestCompoundingType,
this.interestCalculationType, compoundInterestValues.getcompoundedInterest(), this.interestRateAsFraction,
this.daysInYear, this.minBalanceForInterestCalculation.getAmount(), this.overdraftInterestRateAsFraction,
this.minOverdraftForInterestCalculation.getAmount());
// A daily compounding period compounds day by day inside itself, so simple interest has to bypass it - zeroing
// what is carried between periods alone still left a month's interest earning interest within the month.
final BigDecimal interestUnrounded = compoundInterestValues.isSimpleInterest()
&& compoundingPeriod instanceof DailyCompoundingPeriod dailyPeriod
? dailyPeriod.calculateSimpleInterest(this.interestRateAsFraction, this.daysInYear,
this.minBalanceForInterestCalculation.getAmount(), this.overdraftInterestRateAsFraction,
this.minOverdraftForInterestCalculation.getAmount())
: compoundingPeriod.calculateInterest(this.interestCompoundingType, this.interestCalculationType,
compoundInterestValues.getcompoundedInterest(), this.interestRateAsFraction, this.daysInYear,
this.minBalanceForInterestCalculation.getAmount(), this.overdraftInterestRateAsFraction,
this.minOverdraftForInterestCalculation.getAmount());
BigDecimal unCompoundedInterest = compoundInterestValues.getuncompoundedInterest().add(interestUnrounded);
compoundInterestValues.setuncompoundedInterest(unCompoundedInterest);
LocalDate compoundingPeriodEndDate = compoundingPeriod.getPeriodInterval().endDate();
@@ -18,20 +18,29 @@
*/
package org.apache.fineract.infrastructure.documentmanagement.service;
import java.io.FileNotFoundException;
import java.nio.file.NoSuchFileException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.infrastructure.contentstore.service.ContentStoreService;
import org.apache.fineract.infrastructure.core.exception.AbstractPlatformDomainRuleException;
import org.apache.fineract.infrastructure.documentmanagement.data.DocumentContent;
import org.apache.fineract.infrastructure.documentmanagement.data.DocumentData;
import org.apache.fineract.infrastructure.documentmanagement.domain.DocumentRepository;
import org.apache.fineract.infrastructure.documentmanagement.exception.DocumentInvalidRequestException;
import org.apache.fineract.infrastructure.documentmanagement.exception.DocumentNotFoundException;
import org.apache.fineract.infrastructure.documentmanagement.mapping.DocumentMapper;
import org.springframework.stereotype.Service;
@Slf4j
@Service
@RequiredArgsConstructor
public class DocumentReadPlatformServiceImpl implements DocumentReadPlatformService {
/** Bound on the cause walk below, so a self-referencing cause chain cannot spin. */
private static final int MAX_CAUSE_DEPTH = 10;
private final ContentStoreService storeService;
private final DocumentRepository documentRepository;
private final DocumentMapper documentMapper;
@@ -52,9 +61,39 @@ public class DocumentReadPlatformServiceImpl implements DocumentReadPlatformServ
public DocumentContent retrieveDocumentContent(final String entityType, final Long entityId, final Long documentId) {
final var doc = documentRepository.findByIdAndParentEntityTypeAndParentEntityId(documentId, entityType, entityId)
.orElseThrow(() -> new DocumentNotFoundException(entityType, entityId, documentId));
final var is = storeService.download(doc.getLocation());
try {
final var is = storeService.download(doc.getLocation());
return documentMapper.map(doc, is);
} catch (final AbstractPlatformDomainRuleException e) {
throw e;
} catch (final Exception e) {
if (isMissingFromContentStore(e)) {
// The m_document row survives but the file it points at does not — the usual cause is
// a database copied between environments without its file store (see the identical
// guard in ImageReadPlatformServiceImpl). For the caller that is simply "this document
// has no content", not a server fault, so report it the same way as a missing document
// instead of letting a raw ContentStoreException surface as a 500.
log.warn("Document {} for {} {} is recorded but missing from the content store; treating it as not found", documentId,
entityType, entityId);
throw new DocumentNotFoundException(entityType, entityId, documentId);
}
throw new DocumentInvalidRequestException(e);
}
}
return documentMapper.map(doc, is);
/**
* Whether a failure bottoms out in "the stored file is not there", however it was wrapped on the
* way up (the file store rethrows as ContentStoreException).
*/
private boolean isMissingFromContentStore(final Throwable failure) {
Throwable cause = failure;
for (int depth = 0; cause != null && depth < MAX_CAUSE_DEPTH; depth++) {
if (cause instanceof NoSuchFileException || cause instanceof FileNotFoundException) {
return true;
}
cause = cause.getCause();
}
return false;
}
@Override
@@ -650,7 +650,7 @@ public class AccountingProcessorHelper {
*/
public void createInterestPostingJournalEntriesForSavings(final Office office, final String currencyCode,
final Long savingsProductId, final Long paymentTypeId, final Long savingsId, final String transactionId,
final LocalDate transactionDate, final BigDecimal amount, final boolean isReversal) {
final LocalDate transactionDate, final BigDecimal amount, final boolean isReversal, final boolean payableCarriesAccrual) {
final GLAccount controlAccount = getLinkedGLAccountForSavingsProduct(savingsProductId,
CashAccountsForSavings.SAVINGS_CONTROL.getValue(), paymentTypeId);
@@ -665,10 +665,14 @@ public class AccountingProcessorHelper {
.ofNullable(optionalLinkedGLAccountForSavingsProduct(savingsProductId,
AccrualAccountsForSavings.INTEREST_PAYABLE.getValue(), paymentTypeId))
.or(() -> Optional.ofNullable(namedSavingsGlAccount(savingsProductId,
SAVINGS_INTEREST_PAYABLE_MAPPING, "Fixed Deposit Interest Payable", "Interest Payable", "Interest Payable Account")))
SAVINGS_INTEREST_PAYABLE_MAPPING, "Fixed Deposit Interest Payable", "Recurring Deposit Interest Payable",
"Interest Payable", "Interest Payable Account")))
.orElse(controlAccount);
// The RD product screen saves its paid account as "Recurring Deposit Interest Paid"; without that name here an
// RD's interest skipped the paid leg even when the product had one mapped.
final GLAccount paidAccount = Optional.ofNullable(namedSavingsGlAccount(savingsProductId,
SAVINGS_INTEREST_PAID_MAPPING, "Fixed Deposit Interest Paid", "Interest Paid", "Interest Paid Account"))
SAVINGS_INTEREST_PAID_MAPPING, "Fixed Deposit Interest Paid", "Recurring Deposit Interest Paid", "Interest Paid",
"Interest Paid Account"))
.orElse(payableAccount);
log.info("createInterestPostingJournalEntriesForSavings: savingsProductId={}, payableAccount=[{} - {}], paidAccount=[{} - {}], controlAccount=[{} - {}], interestExpense=[{} - {}], amount={}, isReversal={}",
@@ -706,6 +710,19 @@ public class AccountingProcessorHelper {
// debit balance would come back negative and every posting would raise a shortfall larger
// than the interest itself.
final boolean payableIsLiability = GLAccountType.LIABILITY.getValue().equals(payableAccount.getType());
if (!payableCarriesAccrual) {
// Cash basis: nothing ever accrues into the payable, so whatever already sits on it - an opening balance
// brought over at migration, or another product's interest sharing the GL - is not this interest. Reading
// it as "already accrued" skipped the expense and drew that balance down instead, leaving the cost off the
// P&L. The whole amount is charged and raised, and a reversal or clawback takes it back the same way.
if (payableIsLiability) {
postSavingsLeg(office, currencyCode, interestOnSavingsAccount, payableAccount, savingsId, transactionId, transactionDate,
amount, isReversal);
}
postPayableToMember(office, currencyCode, payableAccount, paidAccount, controlAccount, savingsId, transactionId,
transactionDate, amount, isReversal);
return;
}
final BigDecimal alreadyAccrued = payableBalance(office, payableAccount, currencyCode);
final BigDecimal shortfall = amount.subtract(alreadyAccrued).max(BigDecimal.ZERO);
log.info("createInterestPostingJournalEntriesForSavings: alreadyAccrued={}, shortfall={}, payableIsLiability={}, isReversal={}",
@@ -718,6 +735,14 @@ public class AccountingProcessorHelper {
shortfall, false);
}
postPayableToMember(office, currencyCode, payableAccount, paidAccount, controlAccount, savingsId, transactionId, transactionDate,
amount, isReversal);
}
/** Stages 2 and 3: out of the payable, through the paid account when the product names one, into the member. */
private void postPayableToMember(final Office office, final String currencyCode, final GLAccount payableAccount,
final GLAccount paidAccount, final GLAccount controlAccount, final Long savingsId, final String transactionId,
final LocalDate transactionDate, final BigDecimal amount, final boolean isReversal) {
final boolean hasSeparatePaidAccount = !payableAccount.getId().equals(paidAccount.getId());
if (hasSeparatePaidAccount) {
log.info("createInterestPostingJournalEntriesForSavings: posting Stage 2 [Dr {} / Cr {} = {}] and Stage 3 [Dr {} / Cr {} = {}]",
@@ -194,7 +194,7 @@ public class AccrualBasedAccountingProcessorForSavings implements AccountingProc
// payable-to-control pair that used to be here, which skipped interest-paid
// entirely and left the expense off the P&L.
this.helper.createInterestPostingJournalEntriesForSavings(office, currencyCode, savingsProductId, paymentTypeId,
savingsId, transactionId, transactionDate, postingAmount, effectiveIsReversal);
savingsId, transactionId, transactionDate, postingAmount, effectiveIsReversal, true);
}
}
@@ -186,7 +186,7 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess
// to the plain Dr Interest On Savings / Cr Savings Control pair for a product
// that names neither.
this.helper.createInterestPostingJournalEntriesForSavings(office, currencyCode, savingsProductId, paymentTypeId,
savingsId, transactionId, transactionDate, postingAmount, effectiveIsReversal);
savingsId, transactionId, transactionDate, postingAmount, effectiveIsReversal, false);
}
}
@@ -294,8 +294,14 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc
SavingProductAccountingParams.TRANSFERS_SUSPENSE.getValue(), savingProductId,
CashAccountsForSavings.TRANSFERS_SUSPENSE.getValue());
// FD and RD products switch dormancy on with "dormancyAlert" (DepositProductAssembler derives the product's
// tracking flag from it) and never send isDormancyTrackingActive, so reading only that dropped the escheat
// account the screen had asked for - the product then tracked dormancy with no escheat account mapped.
final Boolean isDormancyTrackingActive = this.fromApiJsonHelper.extractBooleanNamed(isDormancyTrackingActiveParamName, element);
if (null != isDormancyTrackingActive && isDormancyTrackingActive) {
final Boolean dormancyAlert = this.fromApiJsonHelper.parameterExists("dormancyAlert", element)
? this.fromApiJsonHelper.extractBooleanNamed("dormancyAlert", element)
: null;
if (Boolean.TRUE.equals(isDormancyTrackingActive) || Boolean.TRUE.equals(dormancyAlert)) {
this.savingsProductToGLAccountMappingHelper.saveSavingsToLiabilityAccountMapping(element,
SavingProductAccountingParams.ESCHEAT_LIABILITY.getValue(), savingProductId,
CashAccountsForSavings.ESCHEAT_LIABILITY.getValue());
@@ -130,7 +130,12 @@ public class TellerManagementReadPlatformServiceImpl implements TellerManagement
@Override
public Collection<TellerData> getTellers(Long officeId) {
return retrieveAllTellers(false);
if (officeId == null) {
return retrieveAllTellers(false);
}
// The tellers of that one branch. The officeId used to be ignored, so the head office, whose
// hierarchy covers every branch, counted each branch's vault and cashiers as its own at day close.
return retrieveAllTellers(false).stream().filter(t -> officeId.equals(t.getOfficeId())).toList();
}
@Override
@@ -70,10 +70,6 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer
try {
this.context.authenticatedUser();
if (this.tellerRepositoryWrapper.existsAny()) {
throw new TellerAlreadyExistsException();
}
final Long officeId = command.longValueOfParameterNamed("officeId");
this.fromApiJsonDeserializer.validateForCreateAndUpdateTeller(command.json());
@@ -81,6 +77,12 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer
// final Office parent =
// validateUserPriviledgeOnOfficeAndRetrieve(currentUser, officeId);
final Office tellerOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
// One teller (vault) per branch, not one for the whole bank: each branch holds and settles
// its own cash, so a second branch needs a vault of its own.
if (this.tellerRepositoryWrapper.existsInOffice(officeId)) {
throw new TellerAlreadyExistsException(tellerOffice.getName());
}
final Teller teller = Teller.fromJson(tellerOffice, command);
// pre save to generate id for use in office hierarchy
@@ -27,6 +27,7 @@ import static org.apache.fineract.portfolio.account.api.AccountTransfersApiConst
import com.google.common.collect.Lists;
import java.math.BigDecimal;
import java.math.MathContext;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
@@ -44,6 +45,7 @@ import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder;
import org.apache.fineract.infrastructure.core.domain.ExternalId;
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.infrastructure.core.service.ExternalIdFactory;
import org.apache.fineract.organisation.monetary.domain.Money;
import org.apache.fineract.organisation.monetary.domain.MonetaryCurrency;
@@ -74,11 +76,13 @@ import org.apache.fineract.portfolio.paymentdetail.domain.PaymentDetail;
import org.apache.fineract.portfolio.savings.SavingsTransactionBooleanValues;
import org.apache.fineract.portfolio.savings.domain.GSIMRepositoy;
import org.apache.fineract.portfolio.savings.domain.GroupSavingsIndividualMonitoring;
import org.apache.fineract.portfolio.savings.domain.RecurringDepositAccount;
import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
import org.apache.fineract.portfolio.savings.domain.SavingsAccountAssembler;
import org.apache.fineract.portfolio.savings.domain.SavingsAccountTransaction;
import org.apache.fineract.portfolio.savings.service.SavingsAccountDomainService;
import org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformService;
import org.apache.fineract.portfolio.tds.service.SavingsInterestTdsService;
import org.springframework.transaction.annotation.Transactional;
@RequiredArgsConstructor
@@ -102,6 +106,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
private final CurrentAccountTransactionRepository currentAccountTransactionRepository;
private final AccountingProcessorHelper accountingProcessorHelper;
private final KycRestrictionGuard kycRestrictionGuard;
private final SavingsInterestTdsService savingsInterestTdsService;
@Transactional
@Override
@@ -147,6 +152,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount, fmt, transactionDate,
transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill);
applyToRecurringDepositSchedule(toSavingsAccount, deposit);
if (!fromSavingsAccount.getCurrency().getCode().equals(toSavingsAccount.getCurrency().getCode())) {
throw new DifferentCurrenciesException(fromSavingsAccount.getCurrency().getCode(),
@@ -202,6 +208,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount, fmt, transactionDate,
transactionAmount, paymentDetail, isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill);
applyToRecurringDepositSchedule(toSavingsAccount, deposit);
final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler.assembleLoanToSavingsTransfer(command,
fromLoanAccount, toSavingsAccount, deposit, loanRefundTransaction);
@@ -407,11 +414,15 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount,
accountTransferDTO.getFmt(), transactionDate, accountTransferDTO.getTransactionAmount(),
accountTransferDTO.getPaymentDetail(), isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill);
applyToRecurringDepositSchedule(toSavingsAccount, deposit);
accountTransferDetails = this.accountTransferAssembler.assembleSavingsToSavingsTransfer(accountTransferDTO, fromSavingsAccount,
toSavingsAccount, withdrawal, deposit);
this.accountTransferDetailRepository.saveAndFlush(accountTransferDetails);
transferTransactionId = accountTransferDetails.getId();
// FD/RD interest reaching a savings account is where TDS is tracked and, once due, deducted.
this.savingsInterestTdsService.onTransfer(fromSavingsAccount, toSavingsAccount, deposit,
AccountTransferType.fromInt(accountTransferDTO.getTransferType()));
} else if (isLoanToSavingsAccountTransfer(accountTransferDTO.getFromAccountType(), accountTransferDTO.getToAccountType())) {
@@ -449,6 +460,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount,
accountTransferDTO.getFmt(), accountTransferDTO.getTransactionDate(), accountTransferDTO.getTransactionAmount(),
accountTransferDTO.getPaymentDetail(), isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill);
applyToRecurringDepositSchedule(toSavingsAccount, deposit);
accountTransferDetails = this.accountTransferAssembler.assembleLoanToSavingsTransfer(accountTransferDTO, fromLoanAccount,
toSavingsAccount, deposit, loanTransaction);
this.accountTransferDetailRepository.saveAndFlush(accountTransferDetails);
@@ -483,6 +495,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
accountTransferDTO.getFmt(), accountTransferDTO.getTransactionDate(),
accountTransferDTO.getTransactionAmount(), accountTransferDTO.getPaymentDetail(),
isAccountTransfer, isRegularTransaction, backdatedTxnsAllowedTill, true);
applyToRecurringDepositSchedule(toSavingsAccount, deposit);
if (accountTransferDetails == null) {
accountTransferDetails = AccountTransferDetails.currentToSavingsTransfer(
@@ -644,6 +657,26 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
return accountTransferDetails;
}
/**
* Money transferred into a recurring deposit is an installment payment, exactly like a counter deposit through
* DepositAccountDomainServiceJpa#handleRDDeposit. The generic deposit above only credits the balance, so without
* this the deposit's schedule kept showing the installment as unpaid and overdue, and its projected maturity
* amount never moved - for manual transfers, standing instructions and RD Auto Debit alike. Any other destination
* is left untouched.
*/
private void applyToRecurringDepositSchedule(final SavingsAccount toSavingsAccount, final SavingsAccountTransaction deposit) {
if (!(toSavingsAccount instanceof RecurringDepositAccount recurringDeposit)) {
return;
}
final boolean isPreMatureClosure = false;
recurringDeposit.updateDepositAmount(deposit.getAmount());
recurringDeposit.handleScheduleInstallments(deposit);
recurringDeposit.updateMaturityDateAndAmount(MathContext.DECIMAL64, isPreMatureClosure,
this.configurationDomainService.isSavingsInterestPostingAtCurrentPeriodEnd(),
this.configurationDomainService.retrieveFinancialYearBeginningMonth());
recurringDeposit.updateOverduePayments(DateUtils.getBusinessLocalDate());
}
private boolean isLoanToSavingsAccountTransfer(final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType) {
return fromAccountType.isLoanAccount() && toAccountType.isSavingsAccount();
}
@@ -703,8 +736,8 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
currentAccountRepository.save(account);
if (account.getProductId() != null && txn.getId() != null) {
final String currentTxnId = "CA" + txn.getId();
accountingProcessorHelper.createCurrentControlToFinancialActivityJournalEntries(account.getOffice(),
account.getCurrencyCode(), account.getProductId(), FinancialActivity.LIABILITY_TRANSFER.getValue(),
accountingProcessorHelper.createCurrentControlToFinancialActivityJournalEntries(account.getOffice(),
account.getCurrencyCode(), account.getProductId(), FinancialActivity.LIABILITY_TRANSFER.getValue(),
account.getId(), currentTxnId, txnDate, amount);
}
return txn;
@@ -715,7 +748,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
* Throws {@link GeneralPlatformDomainRuleException} if balance is insufficient.
*/
private CurrentAccountTransaction performCurrentWithdrawal(final CurrentAccount account, final BigDecimal amount,
final LocalDate txnDate, final Long counterpartProductId, final boolean counterpartIsCurrent,
final LocalDate txnDate, final Long counterpartProductId, final boolean counterpartIsCurrent,
final Long counterpartEntityId) {
kycRestrictionGuard.checkCurrentAccount(account.getId(), KycRestrictionGuard.Operation.TRANSFER);
final BigDecimal balance = account.getAccountBalanceDerived() != null ? account.getAccountBalanceDerived() : BigDecimal.ZERO;
@@ -735,7 +768,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
(account.getTotalWithdrawalsDerived() != null ? account.getTotalWithdrawalsDerived() : BigDecimal.ZERO).add(amount));
currentAccountRepository.save(account);
// Post journal entries: DR current account GL, CR counterpart GL — each with correct entity/account number
postCurrentAccountTransferJournalEntries(account, txn, amount, txnDate, true, counterpartProductId, counterpartIsCurrent,
postCurrentAccountTransferJournalEntries(account, txn, amount, txnDate, true, counterpartProductId, counterpartIsCurrent,
counterpartEntityId);
return txn;
}
@@ -744,7 +777,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
* Deposit amount into a current account and save the transaction.
*/
private CurrentAccountTransaction performCurrentDeposit(final CurrentAccount account, final BigDecimal amount,
final LocalDate txnDate, final Long counterpartProductId, final boolean counterpartIsCurrent,
final LocalDate txnDate, final Long counterpartProductId, final boolean counterpartIsCurrent,
final Long counterpartEntityId) {
kycRestrictionGuard.checkCurrentAccount(account.getId(), KycRestrictionGuard.Operation.CREDIT);
final BigDecimal balance = account.getAccountBalanceDerived() != null ? account.getAccountBalanceDerived() : BigDecimal.ZERO;
@@ -757,7 +790,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
(account.getTotalDepositsDerived() != null ? account.getTotalDepositsDerived() : BigDecimal.ZERO).add(amount));
currentAccountRepository.save(account);
// Post journal entries: DR counterpart GL, CR current account GL — each with correct entity/account number
postCurrentAccountTransferJournalEntries(account, txn, amount, txnDate, false, counterpartProductId, counterpartIsCurrent,
postCurrentAccountTransferJournalEntries(account, txn, amount, txnDate, false, counterpartProductId, counterpartIsCurrent,
counterpartEntityId);
return txn;
}
@@ -803,13 +836,13 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
final String currentTxnId = "CA" + txn.getId();
if (isWithdrawal) {
// DR: current account GL CR: counterpart (savings/current) GL
accountingProcessorHelper.createDirectTransferJournalEntries(account.getOffice(), account.getCurrencyCode(),
account.getProductId(), true, account.getId(), counterpartProductId, counterpartIsCurrent, counterpartEntityId,
accountingProcessorHelper.createDirectTransferJournalEntries(account.getOffice(), account.getCurrencyCode(),
account.getProductId(), true, account.getId(), counterpartProductId, counterpartIsCurrent, counterpartEntityId,
currentTxnId, txnDate, amount);
} else {
// DR: counterpart (savings/current) GL CR: current account GL
accountingProcessorHelper.createDirectTransferJournalEntries(account.getOffice(), account.getCurrencyCode(),
counterpartProductId, counterpartIsCurrent, counterpartEntityId, account.getProductId(), true, account.getId(),
accountingProcessorHelper.createDirectTransferJournalEntries(account.getOffice(), account.getCurrencyCode(),
counterpartProductId, counterpartIsCurrent, counterpartEntityId, account.getProductId(), true, account.getId(),
currentTxnId, txnDate, amount);
}
}
@@ -852,6 +885,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer
final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount, fmt, transactionDate,
transactionAmount, paymentDetail, true, true, backdatedTxnsAllowedTill);
applyToRecurringDepositSchedule(toSavingsAccount, deposit);
final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler.assembleLoanToSavingsTransfer(command,
fromLoanAccount, toSavingsAccount, deposit, loanRefundTransaction);
@@ -61,6 +61,7 @@ import org.apache.fineract.portfolio.savings.domain.GSIMRepositoy;
import org.apache.fineract.portfolio.savings.domain.SavingsAccountAssembler;
import org.apache.fineract.portfolio.savings.service.SavingsAccountDomainService;
import org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformService;
import org.apache.fineract.portfolio.tds.service.SavingsInterestTdsService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -97,12 +98,14 @@ public class AccountConfiguration {
GSIMRepositoy gsimRepository, ConfigurationDomainService configurationDomainService, ExternalIdFactory externalIdFactory,
FineractProperties fineractProperties, CurrentAccountRepository currentAccountRepository,
CurrentAccountTransactionRepository currentAccountTransactionRepository,
AccountingProcessorHelper accountingProcessorHelper, KycRestrictionGuard kycRestrictionGuard) {
AccountingProcessorHelper accountingProcessorHelper, KycRestrictionGuard kycRestrictionGuard,
SavingsInterestTdsService savingsInterestTdsService) {
return new AccountTransfersWritePlatformServiceImpl(accountTransfersDataValidator, accountTransferAssembler,
accountTransferRepository, savingsAccountAssembler, savingsAccountDomainService, loanAccountAssembler,
loanAccountDomainService, savingsAccountWritePlatformService, accountTransferDetailRepository, loanReadPlatformService,
gsimRepository, configurationDomainService, externalIdFactory, fineractProperties,
currentAccountRepository, currentAccountTransactionRepository, accountingProcessorHelper, kycRestrictionGuard);
currentAccountRepository, currentAccountTransactionRepository, accountingProcessorHelper, kycRestrictionGuard,
savingsInterestTdsService);
}
@Bean
@@ -71,6 +71,20 @@ import org.springframework.transaction.annotation.Transactional;
@Produces({ MediaType.APPLICATION_JSON })
public class BranchDayRegisterApiResource {
/**
* The branch whose counter took a breakdown {@code std}: the teller office of its officer's cashier
* allocation if that allocation already existed when the cash was counted, otherwise the officer's
* own office. A person moved to another branch's teller keeps what they took at the old branch
* there.
*/
private static final String COUNTER_OFFICE_OF_STD = """
COALESCE((SELECT t.office_id FROM m_appuser au JOIN m_cashiers mc ON mc.staff_id = au.staff_id
JOIN m_tellers t ON t.id = mc.teller_id
WHERE au.id = std.officer_id""" + CountedCashLedger.SINCE_ALLOCATION + """
LIMIT 1),
(SELECT au.office_id FROM m_appuser au WHERE au.id = std.officer_id))
""";
private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context;
private final FromJsonHelper fromJsonHelper;
@@ -108,11 +122,26 @@ public class BranchDayRegisterApiResource {
result.put("officeId", officeId);
result.put("canOperate", canOperateDay(currentUser));
result.put("days", mapDays(rows));
result.put("today", LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString());
result.put("today", DateUtils.getBusinessLocalDate().toString());
result.put("openDay", findOpenDay(officeId));
return gson.toJson(result);
}
// ── GET /v1/branchday/today ── the bank's "today" ─────────────────────────
/**
* The business date while enable-business-date is on, the tenant's own date while it is off.
* Every screen that defaults a date to "today" reads this, rather than the browser clock or the
* business-date API (which returns the stored date even when the feature is off). Open to any
* signed-in user — cashiers and clerks cannot read the configuration that says which applies.
*/
@GET
@Path("today")
public String today() {
this.context.authenticatedUser();
return gson.toJson(Map.of("today", DateUtils.getBusinessLocalDate().toString()));
}
// ── GET /v1/branchday/missed ── days left open ────────────────────────────
/**
@@ -125,7 +154,7 @@ public class BranchDayRegisterApiResource {
public String missed(@QueryParam("officeId") final Long officeIdParam) {
final AppUser currentUser = this.context.authenticatedUser();
final Long officeId = resolveOffice(officeIdParam, currentUser);
final LocalDate today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
final LocalDate today = DateUtils.getBusinessLocalDate();
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
SELECT r.id, r.office_id, o.name AS office_name, r.business_date,
@@ -195,8 +224,8 @@ public class BranchDayRegisterApiResource {
// Scoped to this office through the officer who took the cash (appuser -> staff -> cashier ->
// teller -> office). Unscoped, a branch's own "does the physical count agree with the books"
// cross-check was being compared against every branch's counted cash at once, which makes it
// wrong at every office but the first. A row whose officer maps to no cashier is still
// counted, for the same reason as the withdrawal legs in bookBreakdown.
// wrong at every office but the first. A row whose officer has no cashier allocation counts
// at the officer's own office (see COUNTER_OFFICE_OF_STD), not at every office.
//
// Which rows are real counted cash is CountedCashLedger's rule, not this screen's -- see the
// note there on why a manual GL entry's decoded reference is kept and a stamped millisecond
@@ -205,23 +234,15 @@ public class BranchDayRegisterApiResource {
SELECT COALESCE(SUM(std.total_amount), 0) FROM m_savings_txn_denomination std
WHERE std.txn_date = ? AND std.txn_type = 'DEPOSIT'
AND """ + CountedCashLedger.COUNTED_ROW + """
AND (std.officer_id IS NULL
OR NOT EXISTS (SELECT 1 FROM m_appuser au JOIN m_cashiers c ON c.staff_id = au.staff_id
WHERE au.id = std.officer_id)
OR EXISTS (SELECT 1 FROM m_appuser au JOIN m_cashiers c ON c.staff_id = au.staff_id
JOIN m_tellers t ON t.id = c.teller_id
WHERE au.id = std.officer_id AND t.office_id = ?))
AND (std.officer_id IS NULL OR (""" + COUNTER_OFFICE_OF_STD + """
) = ?)
""", BigDecimal.class, Date.valueOf(businessDate), officeId));
final BigDecimal countedOut = zero(jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(std.total_amount), 0) FROM m_savings_txn_denomination std
WHERE std.txn_date = ? AND std.txn_type = 'WITHDRAWAL'
AND """ + CountedCashLedger.COUNTED_ROW + """
AND (std.officer_id IS NULL
OR NOT EXISTS (SELECT 1 FROM m_appuser au JOIN m_cashiers c ON c.staff_id = au.staff_id
WHERE au.id = std.officer_id)
OR EXISTS (SELECT 1 FROM m_appuser au JOIN m_cashiers c ON c.staff_id = au.staff_id
JOIN m_tellers t ON t.id = c.teller_id
WHERE au.id = std.officer_id AND t.office_id = ?))
AND (std.officer_id IS NULL OR (""" + COUNTER_OFFICE_OF_STD + """
) = ?)
""", BigDecimal.class, Date.valueOf(businessDate), officeId));
result.put("denominationIn", countedIn);
result.put("denominationOut", countedOut);
@@ -247,7 +268,7 @@ public class BranchDayRegisterApiResource {
final var root = this.fromJsonHelper.parse(body);
final Long officeId = resolveOffice(this.fromJsonHelper.extractLongNamed("officeId", root), currentUser);
final LocalDate businessDate = extractDate(root, "businessDate",
LocalDate.now(DateUtils.getDateTimeZoneOfTenant()));
DateUtils.getBusinessLocalDate());
final BigDecimal openingCash = this.fromJsonHelper.extractBigDecimalWithLocaleNamed("openingCash", root);
final List<Map<String, Object>> denominations = extractDenominations(root, "denominations");
final String openingDifferenceReason = this.fromJsonHelper.extractStringNamed("openingDifferenceReason", root);
@@ -441,7 +462,7 @@ public class BranchDayRegisterApiResource {
final var root = this.fromJsonHelper.parse(body);
final Long officeId = resolveOffice(this.fromJsonHelper.extractLongNamed("officeId", root), currentUser);
final LocalDate businessDate = extractDate(root, "businessDate",
LocalDate.now(DateUtils.getDateTimeZoneOfTenant()));
DateUtils.getBusinessLocalDate());
final List<Map<String, Object>> denominations = extractDenominations(root, "denominations");
final String openingDifferenceReason = this.fromJsonHelper.extractStringNamed("openingDifferenceReason", root);
@@ -609,11 +630,9 @@ public class BranchDayRegisterApiResource {
// never opened is not waited for.
final boolean isHeadOffice = interestPostingReportService.isHeadOffice(officeId);
if (isHeadOffice) {
final List<String> stillOpen = jdbcTemplate.queryForList("""
SELECT o.name FROM m_branch_day_register r JOIN m_office o ON o.id = r.office_id
WHERE r.business_date = ? AND r.closed_at IS NULL AND r.office_id <> ?
ORDER BY o.name
""", String.class, Date.valueOf(businessDate), officeId);
// Any day still open counts, not only today's: a branch whose earlier day was never closed is
// still working and has not posted its interest.
final List<String> stillOpen = interestPostingReportService.branchesStillOpen(businessDate, officeId);
if (!stillOpen.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.branchday.branches.still.open",
"Cannot close the head office yet — these branches have not closed the day: " + String.join(", ", stillOpen)
@@ -770,11 +789,13 @@ public class BranchDayRegisterApiResource {
final Long registerId = ((Number) found.get(0).get("id")).longValue();
saveDenominationDetail(registerId, "CLOSING", denominations);
snapshotVaultDenominations(officeId, registerId, businessDate);
final int depositsClosed = closeMaturedZeroBalanceRecurringDeposits(officeId, businessDate, currentUser);
final Map<String, Object> res = new LinkedHashMap<>();
res.put("officeId", officeId);
res.put("businessDate", businessDate.toString());
res.put("status", "CLOSED");
res.put("zeroBalanceDepositsClosed", depositsClosed);
res.put("closingCash", closingCash);
res.put("bookCash", bookCash);
res.put("cashDifference", difference);
@@ -782,6 +803,38 @@ public class BranchDayRegisterApiResource {
return gson.toJson(res);
}
/**
* "Account Closed with Zero balance in Day Closing" on a recurring deposit product: at the branch's day close, each
* of its recurring deposits that has MATURED with nothing left in it - no balance, and no loan holding a lien on it
* - is marked Closed on that business date, so it no longer waits in the matured list.
*
* Only matured deposits: a running deposit sits at zero between opening and its first installment, and must never
* be closed for that. Nothing is paid out (there is nothing to pay), so no transaction or journal entry is made.
*
* @return how many deposits were closed
*/
private int closeMaturedZeroBalanceRecurringDeposits(final Long officeId, final LocalDate businessDate, final AppUser currentUser) {
final int closed = jdbcTemplate.update("""
UPDATE m_savings_account sa
SET status_enum = 600, closedon_date = ?, closedon_userid = ?
FROM m_savings_product sp, m_client c
WHERE sp.id = sa.product_id AND c.id = sa.client_id AND c.office_id = ?
AND sa.deposit_type_enum = 300 AND sa.status_enum = 800
AND COALESCE(sp.account_closed_zero_balance_in_day_closing, false) = true
AND COALESCE(sa.account_balance_derived, 0) = 0
AND NOT EXISTS (SELECT 1 FROM m_portfolio_account_associations paa
JOIN m_guarantor_funding_details gfd ON gfd.account_associations_id = paa.id
JOIN m_loan l ON l.id = paa.loan_account_id
WHERE paa.linked_savings_account_id = sa.id AND gfd.status_enum = 100
AND l.loan_status_id IN (100, 200, 300)
AND COALESCE(gfd.amount_remaining_derived, gfd.amount) > 0)
""", Date.valueOf(businessDate), currentUser.getId(), officeId);
if (closed > 0) {
log.info("Day close {}: office {} closed {} matured recurring deposit(s) with zero balance", businessDate, officeId, closed);
}
return closed;
}
// ── GET /v1/branchday/denominations ── the note/coin breakdown behind a day's lump sum ────
/**
@@ -797,7 +850,7 @@ public class BranchDayRegisterApiResource {
final Long officeId = resolveOffice(officeIdParam, currentUser);
final LocalDate businessDate = (businessDateParam != null && !businessDateParam.isBlank())
? LocalDate.parse(businessDateParam)
: LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
: DateUtils.getBusinessLocalDate();
final List<Long> registerIds = jdbcTemplate.queryForList(
"SELECT id FROM m_branch_day_register WHERE office_id = ? AND business_date = ?",
@@ -1058,6 +1111,9 @@ public class BranchDayRegisterApiResource {
final Map<String, Object> r = rows.get(0);
final Map<String, Object> m = new LinkedHashMap<>();
m.put("id", r.get("id"));
// The close screen fetches this office's tellers with it; left out, it fetched every teller
// the user can see, and the head office counted each branch's vault as its own.
m.put("officeId", r.get("office_id"));
m.put("businessDate", str(r.get("business_date")));
m.put("openedByName", r.get("opened_by_name"));
m.put("openedAt", str(r.get("opened_at")));
@@ -1111,11 +1167,13 @@ public class BranchDayRegisterApiResource {
(rs, n) -> rs.getBigDecimal(1), officeId, date).stream().findFirst().orElse(null);
final BigDecimal opening = ownOpening != null ? ownOpening : lastClosingCash(officeId, businessDate);
// By the counter that took the cash. A savings deposit carries no office_id, and the old
// "OR office_id IS NULL" counted every such deposit in the bank at every branch.
final BigDecimal savingsDeposits = zero(jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(amount), 0) FROM m_cashier_deposit_request
WHERE status = 'APPROVED'
AND COALESCE(txn_date, CAST(submitted_at AS DATE)) = ?
AND (office_id = ? OR office_id IS NULL)
AND COALESCE(counter_office_id, office_id) = ?
""", BigDecimal.class, date, officeId));
// Cash paid over the counter to buy a demand draft is real cash arriving at the branch too --
@@ -166,8 +166,8 @@ public class CashierDepositRequestApiResource {
client_id, client_name, amount,
payment_type_id, payment_type_name, description, cheque_no, bank_name, txn_date,
status, cashier_id, cashier_name, cashier_username, denomination_data, activity_log, submitted_at,
dd_face_value, dd_charges, dd_gst_percentage, dd_gst_amount, entry_type_cv_id)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
dd_face_value, dd_charges, dd_gst_percentage, dd_gst_amount, entry_type_cv_id, counter_office_id)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
RETURNING id
""",
Long.class,
@@ -179,7 +179,7 @@ public class CashierDepositRequestApiResource {
"PENDING",
currentUser.getId(), currentUser.getDisplayName(), currentUser.getUsername(),
denominationData, activityLog, Timestamp.from(Instant.now()),
ddFaceValue, ddCharges, ddGstPercentage, ddGstAmount, entryTypeCvId
ddFaceValue, ddCharges, ddGstPercentage, ddGstAmount, entryTypeCvId, counterOfficeId(currentUser)
);
// Globally unique voucher number from the central m_voucher register
@@ -691,6 +691,20 @@ public class CashierDepositRequestApiResource {
.orElse(Map.of());
}
/**
* The branch whose counter took the cash: the office of the teller the user is allocated to as a
* cashier, otherwise the user's own office. office_id cannot say this -- a savings deposit carries
* none, and a GL deposit's is the GL's branch -- and the day close totals each branch's cash by it.
*/
private Long counterOfficeId(final AppUser user) {
final List<Long> tellerOffice = user.getStaff() == null ? List.of()
: jdbcTemplate.queryForList("""
SELECT t.office_id FROM m_cashiers c JOIN m_tellers t ON t.id = c.teller_id
WHERE c.staff_id = ? LIMIT 1
""", Long.class, user.getStaff().getId());
return tellerOffice.isEmpty() ? user.getOffice().getId() : tellerOffice.get(0);
}
private Map<?, ?> loadRecord(final Long id) {
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
SELECT id, voucher_no, account_no, account_type, savings_account_id,
@@ -713,7 +727,7 @@ public class CashierDepositRequestApiResource {
final Long savingsAccountId, final BigDecimal amount,
final Object paymentTypeId, final String txnDateStr, final String note) {
final String today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String today = DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String date = txnDateStr != null && !txnDateStr.isBlank() ? formatForFineract(txnDateStr) : today;
final JsonObject payload = new JsonObject();
@@ -747,7 +761,7 @@ public class CashierDepositRequestApiResource {
final Long accountId, final BigDecimal amount,
final Object paymentTypeId, final String txnDateStr, final String note) {
final String today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String today = DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String date = txnDateStr != null && !txnDateStr.isBlank() ? formatForFineract(txnDateStr) : today;
final JsonObject payload = new JsonObject();
@@ -776,7 +790,7 @@ public class CashierDepositRequestApiResource {
final Long accountId, final BigDecimal amount,
final Object paymentTypeId, final String txnDateStr, final String note) {
final String today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String today = DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String date = txnDateStr != null && !txnDateStr.isBlank() ? formatForFineract(txnDateStr) : today;
final JsonObject payload = new JsonObject();
@@ -830,7 +844,7 @@ public class CashierDepositRequestApiResource {
return;
}
final String today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String today = DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String date = txnDateStr != null && !txnDateStr.isBlank() ? formatForFineract(txnDateStr) : today;
final JsonObject payload = new JsonObject();
@@ -853,7 +867,7 @@ public class CashierDepositRequestApiResource {
final Long currentAccountId, final BigDecimal amount,
final Object paymentTypeId, final String txnDateStr, final String note) {
final String today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String today = DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String date = txnDateStr != null && !txnDateStr.isBlank() ? formatForFineract(txnDateStr) : today;
final JsonObject payload = new JsonObject();
@@ -962,7 +976,7 @@ public class CashierDepositRequestApiResource {
final Object paymentTypeId, final String txnDateStr, final String note,
final boolean isDeposit) {
final String today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String today = DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
final String date = txnDateStr != null && !txnDateStr.isBlank() ? formatForFineract(txnDateStr) : today;
// Deposit (CR): cashier receives cash → credit selected GL, debit cash vault (contra)
@@ -1059,8 +1073,9 @@ public class CashierDepositRequestApiResource {
value, count, BigDecimal.valueOf((long) value * count),
// Dated on the request's own date, which is what the branch day's book figure reads.
// CURRENT_DATE is the database clock, so a deposit keyed on one date could land in the
// drawer on another and leave both days' cash wrong.
txnDate != null && !txnDate.isBlank() ? Date.valueOf(txnDate) : null,
// drawer on another and leave both days' cash wrong. No date falls back to the
// business date for the same reason.
Date.valueOf(txnDate != null && !txnDate.isBlank() ? LocalDate.parse(txnDate) : DateUtils.getBusinessLocalDate()),
cashierId, cashierUsername, paymentTypeName
);
}
@@ -1165,7 +1180,7 @@ public class CashierDepositRequestApiResource {
final LocalDate ld = LocalDate.parse(isoDate, DateTimeFormatter.ISO_LOCAL_DATE);
return ld.format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
} catch (Exception e) {
return LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
return DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ofPattern("dd MMMM yyyy"));
}
}
@@ -93,7 +93,7 @@ public class CashReconciliationApiResource {
+ "AND " + CountedCashLedger.COUNTED_ROW
+ "AND std.officer_id IN ("
+ " SELECT au.id FROM m_appuser au "
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?) "
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ") "
+ "GROUP BY std.denomination_id, std.denomination_value, dm.kind";
// Out: settlements to vault
@@ -123,7 +123,7 @@ public class CashReconciliationApiResource {
+ "AND " + CountedCashLedger.COUNTED_ROW
+ "AND std.officer_id IN ("
+ " SELECT au.id FROM m_appuser au "
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?) "
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ") "
+ "GROUP BY std.denomination_id, std.denomination_value, dm.kind";
// In: cash exchange — customer gave denomination TO cashier (RECEIVED direction)
@@ -83,7 +83,7 @@ public class CashReportApiResource {
public String dayBook(@QueryParam("date") final String date, @QueryParam("side") final String side,
@QueryParam("status") final String status) {
final String txnDate = (date != null && !date.isBlank()) ? date : LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String txnDate = (date != null && !date.isBlank()) ? date : DateUtils.getBusinessLocalDate().toString();
final List<Map<String, Object>> rows = new ArrayList<>();
@@ -470,7 +470,7 @@ public class CashReportApiResource {
@GET
@Path("closing")
public String closing(@QueryParam("date") String date) {
final String txnDate = (date != null && !date.isBlank()) ? date : LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String txnDate = (date != null && !date.isBlank()) ? date : DateUtils.getBusinessLocalDate().toString();
// A closing report for a cashier is that one drawer, so it is scoped the way `excess` and
// `cashierPosition` already are; a head cashier or admin gets null and still sees the branch.
@@ -671,25 +671,25 @@ public class CashReportApiResource {
// day itself: taken from the vault, in over the counter, out over the counter, settled
// back. What is left is what should physically be in the drawer.
result.put("todayVaultIn", dayLegTotal(
"SELECT COALESCE(SUM(ctd.count * ctd.denomination_value), 0) FROM m_cash_transfer_detail ctd"
"SELECT COALESCE(SUM(CAST(ctd.count AS BIGINT) * ctd.denomination_value), 0) FROM m_cash_transfer_detail ctd"
+ " JOIN m_cash_transfer ct ON ct.id = ctd.transfer_id"
+ " WHERE ct.to_cashier_id = ? AND ct.transfer_date = CAST(? AS DATE)"
+ " AND COALESCE(ct.is_reversed, false) = false",
scopedCashierId, txnDate));
result.put("todaySettledOut", dayLegTotal(
"SELECT COALESCE(SUM(csd.count * csd.denomination_value), 0) FROM m_cash_settlement_detail csd"
"SELECT COALESCE(SUM(CAST(csd.count AS BIGINT) * csd.denomination_value), 0) FROM m_cash_settlement_detail csd"
+ " JOIN m_cash_settlement cs ON cs.id = csd.settlement_id"
+ " WHERE cs.from_cashier_id = ? AND cs.settlement_date = CAST(? AS DATE)"
+ " AND COALESCE(cs.is_reversed, false) = false",
scopedCashierId, txnDate));
result.put("todayInterCashierIn", dayLegTotal(
"SELECT COALESCE(SUM(icd.count * icd.denomination_value), 0) FROM m_cash_inter_cashier_detail icd"
"SELECT COALESCE(SUM(CAST(icd.count AS BIGINT) * icd.denomination_value), 0) FROM m_cash_inter_cashier_detail icd"
+ " JOIN m_cash_inter_cashier ic ON ic.id = icd.inter_cashier_id"
+ " WHERE ic.to_cashier_id = ? AND ic.transfer_date = CAST(? AS DATE)"
+ " AND COALESCE(ic.is_reversed, false) = false",
scopedCashierId, txnDate));
result.put("todayInterCashierOut", dayLegTotal(
"SELECT COALESCE(SUM(icd.count * icd.denomination_value), 0) FROM m_cash_inter_cashier_detail icd"
"SELECT COALESCE(SUM(CAST(icd.count AS BIGINT) * icd.denomination_value), 0) FROM m_cash_inter_cashier_detail icd"
+ " JOIN m_cash_inter_cashier ic ON ic.id = icd.inter_cashier_id"
+ " WHERE ic.from_cashier_id = ? AND ic.transfer_date = CAST(? AS DATE)"
+ " AND COALESCE(ic.is_reversed, false) = false",
@@ -721,7 +721,7 @@ public class CashReportApiResource {
final Long scopedCashierId) {
final String cashierFilter = scopedCashierId != null ? "AND std.officer_id IN ("
+ " SELECT au.id FROM m_appuser au "
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?) " : "";
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ") " : "";
final String vaultCashierFilter = scopedCashierId != null ? "AND ct.to_cashier_id = ? " : "";
final String settleCashierFilter = scopedCashierId != null ? "AND cs.from_cashier_id = ? " : "";
@@ -938,7 +938,7 @@ public class CashReportApiResource {
return gson.toJson(result);
}
final String today = LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String today = DateUtils.getBusinessLocalDate().toString();
// Find the earliest transfer date before today for which no settlement exists on or after that date
final String sql = "SELECT MIN(ct.transfer_date) AS earliest_unsettled "
@@ -1001,7 +1001,7 @@ public class CashReportApiResource {
@Path("cashier-position")
public String cashierPosition(@QueryParam("cashierId") Long cashierId,
@QueryParam("asOfDate") String asOfDate) {
final String dateFilter = (asOfDate != null && !asOfDate.isBlank()) ? asOfDate : LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String dateFilter = (asOfDate != null && !asOfDate.isBlank()) ? asOfDate : DateUtils.getBusinessLocalDate().toString();
// CASHIER role: always scope to their own position only
final Long scopedId = cashierRoleHelper.getCashierIdForFiltering();
@@ -1032,7 +1032,7 @@ public class CashReportApiResource {
@GET
@Path("cashier-position/me")
public String cashierPositionMe(@QueryParam("asOfDate") String asOfDate) {
final String dateFilter = (asOfDate != null && !asOfDate.isBlank()) ? asOfDate : LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String dateFilter = (asOfDate != null && !asOfDate.isBlank()) ? asOfDate : DateUtils.getBusinessLocalDate().toString();
Long appUserId;
try {
appUserId = context.authenticatedUser().getId();
@@ -1070,7 +1070,7 @@ public class CashReportApiResource {
public String vaultPosition(@QueryParam("tellerId") final Long tellerId,
@QueryParam("asOfDate") final String asOfDate) {
final String dateFilter = (asOfDate != null && !asOfDate.isBlank()) ? asOfDate
: LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
: DateUtils.getBusinessLocalDate().toString();
if (tellerId == null) {
final List<Long> tellerIds = jdbcTemplate.queryForList("SELECT id FROM m_tellers ORDER BY id", Long.class);
@@ -1092,7 +1092,7 @@ public class CashReportApiResource {
@Path("cashier-morning")
public String cashierMorning(@QueryParam("cashierId") Long cashierId,
@QueryParam("date") String date) {
final String txnDate = (date != null && !date.isBlank()) ? date : LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String txnDate = (date != null && !date.isBlank()) ? date : DateUtils.getBusinessLocalDate().toString();
if (cashierId == null) {
Map<String, Object> empty = new LinkedHashMap<>();
empty.put("cashierId", null);
@@ -1171,7 +1171,7 @@ public class CashReportApiResource {
+ "WHERE std.txn_type = 'DEPOSIT' AND std.txn_date <= CAST(? AS DATE) "
+ "AND std.officer_id IN ("
+ " SELECT au.id FROM m_appuser au "
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?) " + COUNTER_NOT_REVERSED
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ") " + COUNTER_NOT_REVERSED
+ "GROUP BY std.denomination_id, std.denomination_value, dm.kind";
// Settlements back to vault
@@ -1197,7 +1197,7 @@ public class CashReportApiResource {
+ "WHERE std.txn_type = 'WITHDRAWAL' AND std.txn_date <= CAST(? AS DATE) "
+ "AND std.officer_id IN ("
+ " SELECT au.id FROM m_appuser au "
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?) " + COUNTER_NOT_REVERSED
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ") " + COUNTER_NOT_REVERSED
+ "GROUP BY std.denomination_id, std.denomination_value, dm.kind";
// Exchange IN: customer gave denomination to cashier (RECEIVED direction)
@@ -1304,7 +1304,7 @@ public class CashReportApiResource {
@QueryParam("offset") Integer offset,
@QueryParam("limit") Integer limit) {
final String txnDate = (date != null && !date.isBlank()) ? date : LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String txnDate = (date != null && !date.isBlank()) ? date : DateUtils.getBusinessLocalDate().toString();
final int resolvedLimit = (limit != null && limit > 0) ? limit : 20;
final int resolvedOffset = (offset != null && offset >= 0) ? offset : 0;
@@ -1315,13 +1315,13 @@ public class CashReportApiResource {
if (cashierId != null) {
officerFilter = "AND std.officer_id IN ("
+ "SELECT au.id FROM m_appuser au "
+ "JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?)";
+ "JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ")";
baseParams = new Object[] { txnDate, cashierId };
} else if (tellerId != null) {
officerFilter = "AND std.officer_id IN ("
+ "SELECT au.id FROM m_appuser au "
+ "JOIN m_cashiers mc ON mc.staff_id = au.staff_id "
+ "JOIN m_tellers mt ON mt.id = mc.teller_id WHERE mt.id = ?)";
+ "JOIN m_tellers mt ON mt.id = mc.teller_id WHERE mt.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ")";
baseParams = new Object[] { txnDate, tellerId };
} else {
officerFilter = "AND std.officer_id IN ("
@@ -89,7 +89,7 @@ public class CashSettlementApiResource {
}
final LocalDate settlementDate = json.has("settlementDate") && !json.get("settlementDate").isJsonNull()
? LocalDate.parse(json.get("settlementDate").getAsString()) : LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
? LocalDate.parse(json.get("settlementDate").getAsString()) : DateUtils.getBusinessLocalDate();
final String fromParty = json.has("fromParty") && !json.get("fromParty").isJsonNull()
? json.get("fromParty").getAsString() : null;
final String toParty = json.has("toParty") && !json.get("toParty").isJsonNull()
@@ -226,7 +226,7 @@ public class CashSettlementApiResource {
}
glDispatchService.allocateCashToCashier(glTellerId,
settlement.getFromCashierId(), settlement.getSettlementAmount(), "INR",
LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ISO_LOCAL_DATE),
DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ISO_LOCAL_DATE),
"Reversal of cash settlement #" + id + (reason != null ? ": " + reason : ""));
} catch (Exception ignored) {
// intentionally ignored
@@ -247,7 +247,7 @@ public class CashSettlementApiResource {
throw new PlatformDataIntegrityException("error.msg.cashsettlement.cashier.required",
"cashierId query param is required.");
}
final String settlementDate = (date != null && !date.isBlank()) ? date : LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).toString();
final String settlementDate = (date != null && !date.isBlank()) ? date : DateUtils.getBusinessLocalDate().toString();
Integer count = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM m_cash_settlement WHERE from_cashier_id = ? AND settlement_date = CAST(? AS DATE) AND (is_reversed IS NULL OR is_reversed = false)",
Integer.class, cashierId, settlementDate);
@@ -146,7 +146,7 @@ public class CashTransferApiResource {
} catch (Exception ignored) {
// intentionally ignored
}
final LocalDate txnDate = transferDate != null ? transferDate : LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
final LocalDate txnDate = transferDate != null ? transferDate : DateUtils.getBusinessLocalDate();
glDispatchService.allocateCashToCashier(glTellerId, toCashierId, total,
currencyCode, txnDate.format(DateTimeFormatter.ISO_LOCAL_DATE),
note != null ? note : "");
@@ -206,7 +206,7 @@ public class CashTransferApiResource {
}
glDispatchService.settleCashFromCashier(glTellerId,
transfer.getToCashierId(), transfer.getTransferAmount(), "INR",
java.time.LocalDate.now(DateUtils.getDateTimeZoneOfTenant()).format(DateTimeFormatter.ISO_LOCAL_DATE),
DateUtils.getBusinessLocalDate().format(DateTimeFormatter.ISO_LOCAL_DATE),
"Reversal of cash transfer #" + id + (reason != null ? ": " + reason : ""));
} catch (Exception ignored) {
// intentionally ignored
@@ -291,7 +291,7 @@ public class CashTransferApiResource {
"Vault/teller " + fromTellerId + " was not found.");
}
final LocalDate businessDate = transferDate != null ? transferDate : LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
final LocalDate businessDate = transferDate != null ? transferDate : DateUtils.getBusinessLocalDate();
final java.sql.Date sqlBusinessDate = java.sql.Date.valueOf(businessDate);
final List<Long> registerIds = jdbcTemplate.query("""
@@ -91,7 +91,7 @@ public class CashierGlDenominationApiResource {
final String txnDateStr = fromJsonHelper.extractStringNamed("txnDate", root);
final LocalDate txnDate = (txnDateStr != null && !txnDateStr.isBlank())
? LocalDate.parse(txnDateStr)
: LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
: DateUtils.getBusinessLocalDate();
if (!fromJsonHelper.parameterExists("denominationBreakdown", root)) {
return "{\"result\":\"skipped\"}";
@@ -889,7 +889,7 @@ public class ShareAdvanceCollectionApiResource {
final Long resolvedClientId = toLong(dep.get("client_id"));
final LocalDate collectionDate = dep.get("txn_date") instanceof java.sql.Date
? ((java.sql.Date) dep.get("txn_date")).toLocalDate()
: LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
: DateUtils.getBusinessLocalDate();
final String receiptNo = nextReceiptNo();
// What the cashier actually typed at save time, when they typed anything -- that is what
// the Apply Share screen's Description column exists to show. Falls back to a plain
@@ -927,7 +927,7 @@ public class ShareAdvanceCollectionApiResource {
final Object submittedAt = req.get("submitted_at");
final LocalDate collectionDate = (actionedAt != null ? actionedAt : submittedAt) instanceof java.sql.Timestamp
? ((java.sql.Timestamp) (actionedAt != null ? actionedAt : submittedAt)).toLocalDateTime().toLocalDate()
: LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
: DateUtils.getBusinessLocalDate();
final String voucherNo = (String) req.get("voucher_no");
final String receiptNo = nextReceiptNo();
final String reqDescription = (String) req.get("description");
@@ -1006,7 +1006,7 @@ public class ShareAdvanceCollectionApiResource {
final Long officeId = dep.get("office_id") != null ? toLong(dep.get("office_id")) : loadClientOfficeId(clientId);
final String currency = dep.get("currency_code") != null ? (String) dep.get("currency_code") : "INR";
final LocalDate collectionDate = dep.get("txn_date") instanceof java.sql.Date ? ((java.sql.Date) dep.get("txn_date")).toLocalDate()
: LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
: DateUtils.getBusinessLocalDate();
// What the cashier actually typed at save time, when they typed anything -- same preference
// as autoAdoptShareCollectionTagged, so a receipt reads identically whether it got here by
@@ -1093,7 +1093,7 @@ public class ShareAdvanceCollectionApiResource {
final Object submittedAt = req.get("submitted_at");
final LocalDate collectionDate = (actionedAt != null ? actionedAt : submittedAt) instanceof java.sql.Timestamp
? ((java.sql.Timestamp) (actionedAt != null ? actionedAt : submittedAt)).toLocalDateTime().toLocalDate()
: LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
: DateUtils.getBusinessLocalDate();
final String receiptNo = nextReceiptNo();
final String reqDescription = (String) req.get("description");
@@ -1338,7 +1338,7 @@ public class ShareAdvanceCollectionApiResource {
private LocalDate parseDate(final String raw) {
if (raw == null || raw.isBlank()) {
return LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
return DateUtils.getBusinessLocalDate();
}
try {
return LocalDate.parse(raw);
@@ -176,6 +176,7 @@ public class ClerkDisbursementRequestApiResource {
// A GL leg carries no savingsAccountId and the guard ignores it.
// A CURRENT leg carries the current account's id in savingsAccountId, so it is checked against
// m_current_account -- checking it as a savings id would test some unrelated savings account.
rejectRecurringDepositLeg(entry, entryAccountType);
if (entry.has("savingsAccountId") && !entry.get("savingsAccountId").isJsonNull()) {
final KycRestrictionGuard.Operation operation = "Dr".equals(dbCr) ? KycRestrictionGuard.Operation.TRANSFER
: KycRestrictionGuard.Operation.CREDIT;
@@ -486,6 +487,8 @@ public class ClerkDisbursementRequestApiResource {
throw apiError(400, "Account ID missing for entry: " + acNo
+ ". Clerk must re-submit with account details loaded.");
}
// Also refuses requests raised before RD legs were blocked at submit.
rejectRecurringDepositLeg(entry, entryType);
}
}
@@ -932,6 +935,7 @@ public class ClerkDisbursementRequestApiResource {
if (amt.compareTo(BigDecimal.ZERO) <= 0)
throw apiError(400, "Amount must be greater than zero. Account: "
+ (e.has("accountNo") ? e.get("accountNo").getAsString() : "?"));
rejectRecurringDepositLeg(e, acTyp);
drAccountIds.add(e.get("savingsAccountId").getAsLong());
}
for (final JsonObject e : crEntries) {
@@ -944,6 +948,7 @@ public class ClerkDisbursementRequestApiResource {
if (amt.compareTo(BigDecimal.ZERO) <= 0)
throw apiError(400, "Amount must be greater than zero. Account: "
+ (e.has("accountNo") ? e.get("accountNo").getAsString() : "?"));
rejectRecurringDepositLeg(e, acTyp);
final Long crId = e.get("savingsAccountId").getAsLong();
if (drAccountIds.contains(crId)) throw apiError(400,
"Account " + (e.has("accountNo") ? e.get("accountNo").getAsString() : crId)
@@ -1193,6 +1198,31 @@ public class ClerkDisbursementRequestApiResource {
.findFirst().orElse(null);
}
/** m_savings_account.deposit_type_enum of a recurring deposit (Fineract's DepositAccountType.RECURRING_DEPOSIT). */
private static final int DEPOSIT_TYPE_RECURRING = 300;
/**
* A recurring deposit cannot be a leg of any clerk request. Every request type here posts straight into the
* account with a direct insert, which never reaches the RD's installment schedule: the installments stay unpaid,
* Auto Debit collects them a second time and the maturity amount is computed on the wrong schedule. RD
* installments come in through the cashier's Receipt (the RD deposit command) or the RD's own Auto Debit.
* Looked up by id, not trusted from the entry's label; a CURRENT leg's id belongs to m_current_account.
*/
private void rejectRecurringDepositLeg(final JsonObject entry, final String accountType) {
if ("GL".equals(accountType) || "CURRENT".equals(accountType) || !entry.has("savingsAccountId")
|| entry.get("savingsAccountId").isJsonNull()) {
return;
}
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT account_no FROM m_savings_account WHERE id = ? AND deposit_type_enum = ?",
entry.get("savingsAccountId").getAsLong(), DEPOSIT_TYPE_RECURRING);
if (!rows.isEmpty()) {
throw apiError(422, "Recurring deposit " + rows.get(0).get("account_no")
+ " cannot be used in a clerk Disbursement, Collection, Fund Transfer or Bank Transfer."
+ " Pay RD installments through a cashier Receipt or Auto Debit.");
}
}
/** Savings status_enum for an account still open for business (Fineract's SavingsAccountStatusType.ACTIVE). */
private static final int SAVINGS_STATUS_ACTIVE = 300;
@@ -390,6 +390,101 @@ public class ClerkShareWithdrawalRequestApiResource {
public String validate(@PathParam("id") final Long id) {
final AppUser currentUser = context.authenticatedUser();
final Map<?, ?> record = loadRecord(id);
final List<Map<String, Object>> checks = buildShareWithdrawalChecks(record);
final Long makerId = ((Number) record.get("clerk_id")).longValue();
final boolean makerCheckerOk = !makerId.equals(currentUser.getId());
checks.add(checkResult("Maker and Checker are different users", makerCheckerOk,
makerCheckerOk ? "Confirmed different users" : "You submitted this request — another manager must approve it"));
final boolean allPassed = checks.stream().allMatch(c -> Boolean.TRUE.equals(c.get("pass")));
final JsonObject res = new JsonObject();
res.addProperty("allPassed", allPassed);
res.add("checks", gson.toJsonTree(checks));
return gson.toJson(res);
}
/**
* Lets the clerk see the same checklist the approver will see, before the request is even
* submitted — so a request that is going to fail a check (a missing GL mapping, an unverified
* KYC, an open AML alert) is caught while someone can still fix it, not after a manager has
* already spent time reviewing it. Takes the same fields {@link #submit(String)} does and
* applies the identical Sundry-downgrade rule, so what this previews is exactly what would be
* stored and exactly what {@link #validate(Long)} would later report on the saved request —
* never a second, independently-drifting copy of the rules.
*
* <p>
* The one check {@link #validate(Long)} runs that this cannot — "Maker and Checker are
* different users" — has no real answer yet: the clerk previewing this *is* the maker, and no
* checker has been chosen. It is reported here as a fixed reminder rather than silently
* dropped, so the clerk sees why the two lists differ by exactly that one row, and knows the
* rule is still enforced later, at {@code approve()}.
*/
@POST
@Path("/preview-validate")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String previewValidate(final String body) {
context.authenticatedUser();
final JsonElement root = fromJsonHelper.parse(body);
final Long shareAccountId = fromJsonHelper.extractLongNamed("shareAccountId", root);
if (shareAccountId == null) {
throw apiError(400, "Share account id is required");
}
final Long requestedShares = fromJsonHelper.extractLongNamed("requestedShares", root);
final String resolutionNumber = fromJsonHelper.extractStringNamed("resolutionNumber", root);
final String meetingDate = fromJsonHelper.extractStringNamed("meetingDate", root);
final Long settlementPaymentTypeId = fromJsonHelper.extractLongNamed("settlementPaymentTypeId", root);
final String settlementModeRaw = fromJsonHelper.extractStringNamed("settlementMode", root);
String settlementMode = settlementModeRaw == null || settlementModeRaw.isBlank() ? "SAVINGS"
: settlementModeRaw.trim().toUpperCase();
Long settlementGlAccountId = fromJsonHelper.extractLongNamed("settlementGlAccountId", root);
// Mirrors submit()'s own downgrade: naming the product's own Share Sundry GL as the
// destination means "stop here", not a real GL settlement — see submit() for the rationale.
if ("GL".equals(settlementMode) && settlementGlAccountId != null) {
final Long productId = jdbcTemplate.queryForList("SELECT product_id FROM m_share_account WHERE id = ?", shareAccountId)
.stream().findFirst().map(r -> ((Number) r.get("product_id")).longValue()).orElse(null);
if (productId != null) {
final Long glSundry = resolveGl(productId, FA_SHARES_SUSPENSE);
if (glSundry != null && glSundry.equals(settlementGlAccountId)) {
settlementMode = "NONE";
settlementGlAccountId = null;
}
}
}
final Map<String, Object> draftRecord = new java.util.HashMap<>();
draftRecord.put("resolution_number", resolutionNumber);
draftRecord.put("meeting_date", meetingDate);
draftRecord.put("share_account_id", shareAccountId);
draftRecord.put("requested_shares", requestedShares != null ? requestedShares : 0L);
draftRecord.put("settlement_mode", settlementMode);
draftRecord.put("settlement_gl_account_id", settlementGlAccountId);
draftRecord.put("settlement_payment_type_id", settlementPaymentTypeId);
final List<Map<String, Object>> checks = buildShareWithdrawalChecks(draftRecord);
checks.add(checkResult("Maker and Checker are different users", true,
"Verified automatically when a different manager approves"));
final boolean allPassed = checks.stream().allMatch(c -> Boolean.TRUE.equals(c.get("pass")));
final JsonObject res = new JsonObject();
res.addProperty("allPassed", allPassed);
res.add("checks", gson.toJsonTree(checks));
return gson.toJson(res);
}
/**
* The full checklist a checker sees before approving a share withdrawal — share balance and
* status, loan/tenure/guarantor exposure, settlement destination and payment type, and client
* KYC/risk/AML standing. Shared verbatim between {@link #validate(Long)} (an already-submitted
* request) and {@link #previewValidate(String)} (a draft that does not exist yet), so the two
* can never silently diverge. Reads {@code record} by the same string keys both callers
* populate: resolution_number, meeting_date, share_account_id, requested_shares,
* settlement_mode, settlement_gl_account_id, settlement_payment_type_id.
*/
private List<Map<String, Object>> buildShareWithdrawalChecks(final Map<?, ?> record) {
final List<Map<String, Object>> checks = new ArrayList<>();
final String resolutionNumber = (String) record.get("resolution_number");
@@ -451,8 +546,18 @@ public class ClerkShareWithdrawalRequestApiResource {
// not-applicable rather than failed for a GL request — a share account with no linked
// savings is a perfectly valid GL-settlement case.
final boolean glSettlementMode = "GL".equals(record.get("settlement_mode"));
checks.add(glSettlementMode
? checkResult("Linked savings account is Active", true, "Not applicable — settlement is a GL book-transfer")
// 'NONE' is the third mode approve() handles, and submit() produces it on its own: a clerk who
// names the product's own Share Sundry GL as the destination is saying "stop here", so the
// request is downgraded from GL to NONE and approve() posts Dr Share Capital / Cr Share Sundry
// and nothing further. Like a GL settlement it never reaches a savings account, so the
// savings-side checks below do not apply to it either — running them reports a missing fund
// source mapping that no posting in this mode is ever going to read.
final boolean sundryOnlySettlement = "NONE".equals(record.get("settlement_mode"));
final boolean noSavingsLeg = glSettlementMode || sundryOnlySettlement;
checks.add(noSavingsLeg
? checkResult("Linked savings account is Active", true, sundryOnlySettlement
? "Not applicable — the redemption rests in Share Sundry"
: "Not applicable — settlement is a GL book-transfer")
: checkResult("Linked savings account is Active", savingsAccountId != null && savingsStatus != null && savingsStatus == 300,
savingsAccountId == null ? "No linked savings account configured"
: "Account #" + savingsAccountId + " — " + savingsStatusLabel(savingsStatus)));
@@ -541,6 +646,9 @@ public class ClerkShareWithdrawalRequestApiResource {
final boolean settlementGlPresent = glAccountIdObj != null;
checks.add(checkResult("Settlement GL Account recorded", settlementGlPresent,
settlementGlPresent ? glCodeOf(((Number) glAccountIdObj).longValue()) : "Missing"));
} else if (sundryOnlySettlement) {
checks.add(checkResult("Settlement destination recorded", true,
"Share Sundry — the redemption stops there, so no fund source mapping is read"));
} else {
boolean glMappingOk = false;
String glMappingDetail = "Linked savings account or settlement payment type missing — cannot check";
@@ -579,16 +687,7 @@ public class ClerkShareWithdrawalRequestApiResource {
openAlerts != null && openAlerts > 0 ? openAlerts + " open alert(s)" : "None"));
}
final Long makerId = ((Number) record.get("clerk_id")).longValue();
final boolean makerCheckerOk = !makerId.equals(currentUser.getId());
checks.add(checkResult("Maker and Checker are different users", makerCheckerOk,
makerCheckerOk ? "Confirmed different users" : "You submitted this request — another manager must approve it"));
final boolean allPassed = checks.stream().allMatch(c -> Boolean.TRUE.equals(c.get("pass")));
final JsonObject res = new JsonObject();
res.addProperty("allPassed", allPassed);
res.add("checks", gson.toJsonTree(checks));
return gson.toJson(res);
return checks;
}
private Map<String, Object> checkResult(final String label, final boolean pass, final String detail) {
@@ -992,8 +1091,8 @@ public class ClerkShareWithdrawalRequestApiResource {
// The purchase that issued the holding - type 500. Its unit price is what the member paid.
final BigDecimal unitPrice = jdbcTemplate
.queryForList("""
SELECT unit_price FROM m_share_account_transaction
WHERE share_account_id = ? AND type_enum = 500 AND unit_price IS NOT NULL
SELECT unit_price FROM m_share_account_transactions
WHERE account_id = ? AND is_active = true AND type_enum = 500 AND unit_price IS NOT NULL
ORDER BY id DESC LIMIT 1
""", BigDecimal.class, shareAccountId)
.stream().findFirst().orElse(null);
@@ -130,9 +130,19 @@ public final class CountedCashLedger {
+ " AND (rct.is_reversed = true OR " + breakdownDiffersFrom("rct.amount") + "))"
+ " AND" + REAL_TXN_ID + ") ";
/**
* Over the aliases {@code std} and {@code mc} (the cashier a breakdown's officer maps to): only what
* the login counted once this allocation existed. A breakdown is tied to a cashier through its
* officer's login, so without this a person moved from one branch's teller to another's carried
* every rupee they had ever taken -- at the old branch too -- into the new drawer. An allocation
* with no recorded creation time keeps its whole history.
*/
public static final String SINCE_ALLOCATION = " AND (mc.created_at IS NULL OR std.created_at IS NULL"
+ " OR std.created_at >= mc.created_at)";
/** Sub-rupee tolerance: a paisa-exact amount is handed over as the nearest whole rupee. */
private static String breakdownDiffersFrom(final String amountColumn) {
return "ABS(" + amountColumn + " - (SELECT SUM(sd.count * sd.denomination_value)"
return "ABS(" + amountColumn + " - (SELECT SUM(CAST(sd.count AS BIGINT) * sd.denomination_value)"
+ " FROM m_savings_txn_denomination sd WHERE sd.txn_id = std.txn_id"
+ " AND sd.account_no IS NOT DISTINCT FROM std.account_no)) >= 1";
}
@@ -288,7 +288,7 @@ public class DenominationBreakdownWriter {
+ " WHERE std.txn_type = 'DEPOSIT'"
+ " AND " + CountedCashLedger.COUNTED_ROW
+ " AND std.officer_id IN (SELECT au.id FROM m_appuser au"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?)"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ")"
+ " GROUP BY std.denomination_id"
+ " UNION ALL"
+ " SELECT ced.denomination_id, CAST(SUM(ced.count) AS BIGINT)"
@@ -312,7 +312,7 @@ public class DenominationBreakdownWriter {
+ " WHERE std.txn_type = 'WITHDRAWAL'"
+ " AND " + CountedCashLedger.COUNTED_ROW
+ " AND std.officer_id IN (SELECT au.id FROM m_appuser au"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?)"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ")"
+ " GROUP BY std.denomination_id"
+ " UNION ALL"
+ " SELECT ced.denomination_id, CAST(-SUM(ced.count) AS BIGINT)"
@@ -409,7 +409,7 @@ public class DenominationBreakdownWriter {
+ " WHERE std.txn_type = 'DEPOSIT'"
+ " AND " + CountedCashLedger.COUNTED_ROW
+ " AND std.officer_id IN (SELECT au.id FROM m_appuser au"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?)"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ")"
+ " GROUP BY std.denomination_id"
+ " UNION ALL"
+ " SELECT ced.denomination_id, CAST(SUM(ced.count) AS BIGINT)"
@@ -433,7 +433,7 @@ public class DenominationBreakdownWriter {
+ " WHERE std.txn_type = 'WITHDRAWAL'"
+ " AND " + CountedCashLedger.COUNTED_ROW
+ " AND std.officer_id IN (SELECT au.id FROM m_appuser au"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?)"
+ " JOIN m_cashiers mc ON mc.staff_id = au.staff_id WHERE mc.id = ?" + CountedCashLedger.SINCE_ALLOCATION + ")"
+ " GROUP BY std.denomination_id"
+ " UNION ALL"
+ " SELECT ced.denomination_id, CAST(-SUM(ced.count) AS BIGINT)"
@@ -55,6 +55,7 @@ import org.apache.fineract.portfolio.loanaccount.guarantor.exception.InvalidGuar
import org.apache.fineract.portfolio.loanaccount.guarantor.serialization.GuarantorCommandFromApiJsonDeserializer;
import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
import org.apache.fineract.portfolio.savings.domain.SavingsAccountAssembler;
import org.apache.fineract.portfolio.savings.service.RecurringDepositLienService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -79,6 +80,7 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto
private final SavingsAccountAssembler savingsAccountAssembler;
private final AccountAssociationsRepository accountAssociationsRepository;
private final GuarantorDomainService guarantorDomainService;
private final RecurringDepositLienService recurringDepositLienService;
@Autowired
public GuarantorWritePlatformServiceJpaRepositoryIImpl(final LoanRepositoryWrapper loanRepositoryWrapper,
@@ -86,7 +88,9 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto
final StaffRepositoryWrapper staffRepositoryWrapper, final GroupRepositoryWrapper groupRepositoryWrapper,
final GuarantorCommandFromApiJsonDeserializer fromApiJsonDeserializer,
final CodeValueRepositoryWrapper codeValueRepositoryWrapper, final SavingsAccountAssembler savingsAccountAssembler,
final AccountAssociationsRepository accountAssociationsRepository, final GuarantorDomainService guarantorDomainService) {
final AccountAssociationsRepository accountAssociationsRepository, final GuarantorDomainService guarantorDomainService,
final RecurringDepositLienService recurringDepositLienService) {
this.recurringDepositLienService = recurringDepositLienService;
this.loanRepositoryWrapper = loanRepositoryWrapper;
this.clientRepositoryWrapper = clientRepositoryWrapper;
this.groupRepositoryWrapper = groupRepositoryWrapper;
@@ -120,6 +124,9 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto
final SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(guarantorCommand.getSavingsId(),
backdatedTxnsAllowedTill);
validateGuarantorSavingsAccountActivationDateWithLoanSubmittedOnDate(loan, savingsAccount);
// A recurring deposit pledged here is a lien on it: its product must allow that, and it can
// never secure more than the balance it has not already pledged.
this.recurringDepositLienService.validatePledge(savingsAccount, guarantorCommand.getAmount(), loan.getId());
accountAssociations = AccountAssociations.associateSavingsAccount(loan, savingsAccount,
AccountAssociationType.GUARANTOR_ACCOUNT_ASSOCIATION.getValue(), backdatedTxnsAllowedTill);
@@ -71,9 +71,11 @@ public class RbiReserveConfigApiResource {
static {
ROLE_DESCRIPTIONS.put("CASH_IN_HAND",
"Cash the bank itself holds - vault and teller balances. Counts toward CRR maintained.");
ROLE_DESCRIPTIONS.put("BALANCE_WITH_OTHER_BANKS",
"Current account balances the bank holds with other banks. Counts toward CRR maintained. "
+ "Pin every such account - a bank typically banks with several.");
// BALANCE_WITH_OTHER_BANKS is deliberately not offered. It belongs to the older working
// report, and the statutory Form 1 this bank files has no line for it: balances with other
// banks are reported there under III(a), III(b)(i) or VI, depending on which bank holds
// them. Left on the screen it invited a mapping that would raise item X without appearing
// anywhere on the form to say where the figure came from.
ROLE_DESCRIPTIONS.put("DEMAND_TIME_LIABILITIES",
"Deposit liabilities forming the DTL base that CRR and SLR are charged on. "
+ "Pin the deposit accounts and any interest accrued on them.");
@@ -210,12 +212,14 @@ public class RbiReserveConfigApiResource {
ROLE_USAGE.put(role, "OSS 2 (RoE) — movement over the quarter");
} else {
ROLE_GROUPS.put(role, "RESERVE");
// Both ratios are settled on Form 1 - Part B is section 18, Part C section 24 - so
// the part is named rather than a separate return that does not exist.
if ("SLR_INVESTMENTS".equals(role)) {
ROLE_USAGE.put(role, "Form 9 (SLR) — maintained");
ROLE_USAGE.put(role, "Form 1 Part C (SLR) — maintained");
} else if ("DEMAND_TIME_LIABILITIES".equals(role)) {
ROLE_USAGE.put(role, "Form 1 & Form 9 — base");
ROLE_USAGE.put(role, "Form 1 — base for both ratios");
} else {
ROLE_USAGE.put(role, "Form 1 (CRR) — maintained");
ROLE_USAGE.put(role, "Form 1 Part B (CRR) — maintained");
}
}
}
@@ -1084,6 +1084,15 @@ public class RbiReserveReturnApiResource {
*/
private static LocalDate requirePastOrPresent(final LocalDate date, final String what) {
final LocalDate today = DateUtils.getBusinessLocalDate();
// A year the ledger could not hold. A date field hands over whatever has been typed so far,
// so a half-typed year arrives as a real date - "0026-09-30" parses cleanly - and the return
// then reads a period no bank has entries for and reports every line nil.
if (date.getYear() < 1900) {
throw new PlatformDataIntegrityException("error.msg.rbireservereturn.year.incomplete",
what + " (" + date + ") has a year below 1900, which looks like a date still being "
+ "typed rather than a period to report.",
what, date.toString());
}
if (date.isAfter(today)) {
throw new PlatformDataIntegrityException("error.msg.rbireservereturn.future.date",
what + " (" + date + ") is in the future; the bank's business date is " + today
@@ -1130,6 +1139,8 @@ public class RbiReserveReturnApiResource {
public String form1Statutory(@QueryParam("reportingDate") final String reportingDateParam,
@QueryParam("firstColumnDate") final String firstColumnDateParam,
@QueryParam("secondColumnDate") final String secondColumnDateParam,
@QueryParam("firstBaseDate") final String firstBaseDateParam,
@QueryParam("secondBaseDate") final String secondBaseDateParam,
@QueryParam("officeId") final Long officeId) {
this.context.authenticatedUser().validateHasReadPermission(RESOURCE_NAME_FOR_PERMISSION);
@@ -1174,15 +1185,51 @@ public class RbiReserveReturnApiResource {
}
// The third column is the base the current fortnight's ratios are charged on - the last
// Friday of the second preceding fortnight - not the reporting date.
// matching close one month earlier - not the reporting date.
//
// It was the reporting date. Since the return is now made up to the second column, that
// made the third column a copy of the second: two identically dated columns carrying
// identical figures, which reads as a filled form and says nothing. The base belongs on the
// face of the form because every required amount below is computed from it, and a reviewer
// cannot check a requirement whose base is not stated.
final LocalDate currentBase = formOneBaseDate(currentClose);
final List<LocalDate> columnDates = List.of(previousClose, currentClose, currentBase);
// Each close has its own base, and either can be given outright.
//
// Derived, the base is the matching close one month earlier, which is
// what the rules fix it at. But a bank migrating onto the system, or filing a corrected
// return for a period whose base fell before its ledger starts, has a base date that the
// rule produces and the ledger cannot answer - and the ratio then reads nil against real
// liabilities. Given explicitly, the date entered is used and stated on the form, so a
// reader can see which base each column was charged on.
final LocalDate previousBase = firstBaseDateParam == null || firstBaseDateParam.isBlank()
? formOneBaseDate(previousClose)
: requirePastOrPresent(LocalDate.parse(firstBaseDateParam), "The first column's base date");
final LocalDate currentBase = secondBaseDateParam == null || secondBaseDateParam.isBlank()
? formOneBaseDate(currentClose)
: requirePastOrPresent(LocalDate.parse(secondBaseDateParam), "The second column's base date");
// A base dated after the close it serves would charge the ratio on liabilities the bank had
// not yet taken on - the figure would be arithmetically fine and mean nothing.
if (previousBase.isAfter(previousClose)) {
throw new PlatformDataIntegrityException("error.msg.rbireservereturn.base.after.close",
"The first column's base date (" + previousBase + ") falls after the close it is charged on ("
+ previousClose + ").",
previousBase.toString(), previousClose.toString());
}
if (currentBase.isAfter(currentClose)) {
throw new PlatformDataIntegrityException("error.msg.rbireservereturn.base.after.close",
"The second column's base date (" + currentBase + ") falls after the close it is charged on ("
+ currentClose + ").",
currentBase.toString(), currentClose.toString());
}
// Two columns, one per fortnight close. The base dates are not columns of their own: they
// are stated against the lines they settle, and a third column headed with one printed the
// base's own balances beside the closes', which read as a third period the bank was
// reporting rather than as the figures the ratios were charged on.
final List<LocalDate> columnDates = List.of(previousClose, currentClose);
// One base per column, in the same order, so each column is charged on its own base rather
// than both on one.
final List<LocalDate> baseDates = List.of(previousBase, currentBase);
final Map<String, Object> response = new LinkedHashMap<>();
response.put("formCode", "FORM_1_STATUTORY");
@@ -1190,6 +1237,9 @@ public class RbiReserveReturnApiResource {
response.put("statutoryReference", "Banking Regulation (Co-operative Societies) Rules, 1966");
response.put("reportingDate", reportingDate.toString());
response.put("columns", columnDates.stream().map(LocalDate::toString).toList());
// Stated beside the columns so a reader can see which date each ratio was charged on,
// without the base needing a column of its own.
response.put("baseColumns", baseDates.stream().map(LocalDate::toString).toList());
final Rate crr = rateInForce("CRR", reportingDate);
final Rate slr = rateInForce("SLR", reportingDate);
@@ -1197,10 +1247,14 @@ public class RbiReserveReturnApiResource {
response.put("slrPercentage", slr == null ? null : slr.percentage);
final List<Map<String, Object>> parts = new ArrayList<>();
parts.add(formOnePartA(columnDates, officeId, crr, slr));
parts.add(formOnePartA(columnDates, baseDates, officeId, crr, slr));
response.put("partA", parts.get(0));
response.put("partB", formOnePartB(columnDates, officeId, crr));
response.put("partC", formOnePartC(columnDates, officeId, slr));
response.put("partB", formOnePartB(columnDates, baseDates, officeId, crr));
response.put("partC", formOnePartC(columnDates, baseDates, officeId, slr));
// Every day of the month the closes fall in, charged on each day's own base. The form
// reports two closes; compliance turns on every day between them.
response.put("daily", formOneDaily(previousClose.withDayOfMonth(1), currentClose, officeId, crr, slr));
final List<String> unmet = new ArrayList<>();
if (crr == null) {
@@ -1219,9 +1273,8 @@ public class RbiReserveReturnApiResource {
final BigDecimal baseLiabilities = formOneNetLiabilities(currentBase, officeId);
if (baseLiabilities.compareTo(BigDecimal.ZERO) == 0) {
unmet.add("Both ratios are charged on the net liabilities of " + currentBase
+ " — the last Friday of the second preceding fortnight — and the ledger holds "
+ "none on that date. The required amounts are therefore nil. They are nil "
+ "because the base is nil, not because nothing is required.");
+ ", and the ledger holds none on that date. The required amounts are therefore "
+ "nil — nil because the base is nil, not because nothing is required.");
}
response.put("unmetRequirements", unmet);
@@ -1229,20 +1282,26 @@ public class RbiReserveReturnApiResource {
}
/** Part A: the liabilities and assets the two ratios are worked out from. */
private Map<String, Object> formOnePartA(final List<LocalDate> dates, final Long officeId, final Rate crr,
private Map<String, Object> formOnePartA(final List<LocalDate> dates, final List<LocalDate> bases, final Long officeId, final Rate crr,
final Rate slr) {
final List<Map<String, Object>> lines = new ArrayList<>();
lines.add(formOneHeading("I. LIABILITIES IN INDIA TO THE BANKING SYSTEM"));
lines.add(formOneHeading("(a) Demand Liabilities"));
final List<BigDecimal> iai = formOneLine(lines, "(i) Current account balances of SBI, its subsidiaries and the corresponding new banks",
// The labels below are the printed form's own wording, kept word for word. A shortened line
// reads more easily on screen but this form is filed and signed, and a reader checking it
// against the paper return has to find each line by its text - a paraphrase makes them stop
// and work out whether it is the same line.
lines.add(formOneHeading("I. LIABILITIES IN INDIA TO THE BANKING SYSTEM :"));
lines.add(formOneHeading("(a) Demand Liabilities:"));
final List<BigDecimal> iai = formOneLine(lines,
"(i) Total of credit balances in current accounts maintained with the co-operative bank by State Bank of India,"
+ " subsidiary banks and corresponding new banks.",
"FORM1_I_A_I_SBI_CURRENT", dates, officeId, 2);
final List<BigDecimal> iaii = formOneLine(lines, "(ii) Other demand liabilities to the banking system",
final List<BigDecimal> iaii = formOneLine(lines, "(ii) Total of other demand liabilites to the banking system",
"FORM1_I_A_II_OTHER_DEMAND_BS", dates, officeId, 2);
final List<BigDecimal> ib = formOneLine(lines, "(b) Time liabilities to the banking system", "FORM1_I_B_TIME_BS",
final List<BigDecimal> ib = formOneLine(lines, "(b) Time Liabilities to the banking system", "FORM1_I_B_TIME_BS",
dates, officeId, 1);
final List<BigDecimal> totalI = sumOf(iai, iaii, ib);
lines.add(formOneTotal("TOTAL OF I", totalI));
lines.add(formOneTotal("TOTAL OF I : >>>>>>>>>>>", totalI));
lines.add(formOneHeading("II. LIABILITIES IN INDIA TO OTHERS"));
// Demand and time come from the one DTL head, split by the class each mapped account
@@ -1254,23 +1313,25 @@ public class RbiReserveReturnApiResource {
iiA.add(dtl.demandAmount);
iiB.add(dtl.timeAmount);
}
lines.add(formOneRow("(A) Demand liabilities", "DEMAND_TIME_LIABILITIES", iiA, 1));
lines.add(formOneRow("(B) Time liabilities", "DEMAND_TIME_LIABILITIES", iiB, 1));
lines.add(formOneRow("(A) DEMAND LIABILITIES :", "DEMAND_TIME_LIABILITIES", iiA, 1));
lines.add(formOneRow("(B) TIME LIABILITIES :", "DEMAND_TIME_LIABILITIES", iiB, 1));
final List<BigDecimal> totalII = sumOf(iiA, iiB);
lines.add(formOneTotal("TOTAL OF II", totalII));
lines.add(formOneTotal("TOTAL OF II : >>>>>>>>>>>", totalII));
lines.add(formOneHeading("III. ASSETS IN INDIA WITH THE BANKING SYSTEM"));
final List<BigDecimal> iiiA = formOneLine(lines, "(A) Current account balances with SBI, its subsidiaries and the corresponding new banks",
final List<BigDecimal> iiiA = formOneLine(lines,
"(A) TOTAL OF CREDIT BALANCES IN CURRENT ACCOUNT maintained with S.B.I, Subsidiary Banks & corresponding new banks",
"FORM1_III_A_SBI_CURRENT", dates, officeId, 1);
lines.add(formOneHeading("(B) Other assets with the banking system"));
final List<BigDecimal> iiiBi = formOneLine(lines, "(i) Balances in all accounts other than III(A)",
lines.add(formOneHeading("(B) TOTAL OF OTHER ASSETS WITH THE BANKING SYSTEM, VIZ."));
final List<BigDecimal> iiiBi = formOneLine(lines,
"(i) Balances in all Accounts other than those included in item III (a) :",
"FORM1_III_B_I_OTHER_BALANCES", dates, officeId, 2);
final List<BigDecimal> iiiBii = formOneLine(lines, "(ii) Money at call and short notice",
final List<BigDecimal> iiiBii = formOneLine(lines, "(ii) Money at Call and Short notice :",
"FORM1_III_B_II_MONEY_AT_CALL_BS", dates, officeId, 2);
final List<BigDecimal> iiiBiv = formOneLine(lines, "(iv) Advances and any other assets",
final List<BigDecimal> iiiBiv = formOneLine(lines, "(iv) Advances & any other Assets :",
"FORM1_III_B_IV_ADVANCES_BS", dates, officeId, 2);
final List<BigDecimal> totalIII = sumOf(iiiA, iiiBi, iiiBii, iiiBiv);
lines.add(formOneTotal("TOTAL OF III", totalIII));
lines.add(formOneTotal("TOTAL OF III : >>>>>>>>>>", totalIII));
// IV: the banking system nets out, and what is left is added to the liabilities to others.
// Floored at zero per column - the form's own wording, "(I - III) + II if minus figure",
@@ -1279,29 +1340,54 @@ public class RbiReserveReturnApiResource {
for (int i = 0; i < dates.size(); i++) {
iv.add(totalI.get(i).subtract(totalIII.get(i)).max(BigDecimal.ZERO).add(totalII.get(i)));
}
lines.add(formOneTotal("IV. TOTAL (NET) DEMAND AND TIME LIABILITIES FOR THE PURPOSE OF SECTIONS 18 AND 24", iv));
// The form carries IV twice, and the difference between the two is the whole of how the
// ratios work. (a) is this column's own liabilities - what the bank owed on the close being
// reported. (b) is the base: the same figure read at the earlier close, and the only one the
// requirement is actually charged on. A form showing one IV reads as though the bank had to
// hold a ratio of today's liabilities, which is not what either section says.
lines.add(formOneTotal(
"IV. a) TOTAL (NET) DEMAND & TIME LIABILITIES FOR THE PURPOSE OF SEC.18 & 24 OF THE ACT = (I-III)+II IF MINUS"
+ " FIGURE [CURRENT FORTNIGHT]",
iv));
final List<BigDecimal> ivBase = new ArrayList<>();
final List<String> ivBaseDates = new ArrayList<>();
for (int i = 0; i < dates.size(); i++) {
final LocalDate base = baseFor(bases, dates, i);
ivBaseDates.add(base.toString());
ivBase.add(formOneNetLiabilities(base, officeId));
}
// The printed form words this "AS ON THE LAST FRIDAY OF THE SECOND PRECEDING FORTNIGHT",
// which is the Act's rule. This bank does not file on that rule - its base is the matching
// fortnight close one month earlier, which formOneBaseDate computes - so the line says BASE
// DATE and leaves the dates themselves to the column headings. A heading that named a
// Friday the return never used would be a statement nobody could check.
final Map<String, Object> ivBaseRow = formOneTotal(
"IV. b) DEMAND AND TIME LIABILITY OF BASE DATE FOR THE PURPOSE OF SEC.18 & 24",
ivBase);
ivBaseRow.put("baseDates", ivBaseDates);
lines.add(ivBaseRow);
final List<BigDecimal> v = formOneLine(lines, "V. CASH ON HAND", "CASH_IN_HAND", dates, officeId, 0);
final List<BigDecimal> v = formOneLine(lines, "V. CASH ON HAND :", "CASH_IN_HAND", dates, officeId, 0);
lines.add(formOneHeading("VI. BALANCE IN CURRENT ACCOUNTS WITH"));
final List<BigDecimal> viA = formOneLine(lines, "(a) Reserve Bank of India", "FORM1_VI_A_RBI_CURRENT", dates,
lines.add(formOneHeading("VI. BALANCE IN CURRENT ACCOUNTS WITH :"));
final List<BigDecimal> viA = formOneLine(lines, "(a) Reserve Bank of India :", "FORM1_VI_A_RBI_CURRENT", dates,
officeId, 1);
final List<BigDecimal> viB = formOneLine(lines, "(b) State Co-operative Bank of the state concerned",
final List<BigDecimal> viB = formOneLine(lines, "(b) State Co.Op.Bank of the State Concerned :",
"FORM1_VI_B_STATE_COOP_CURRENT", dates, officeId, 1);
final List<BigDecimal> viC = formOneLine(lines, "(c) District Central Co-operative Bank of the district concerned",
final List<BigDecimal> viC = formOneLine(lines, "(c) Central Co.Op.Bank of the Dist.Concerned :",
"FORM1_VI_C_DCCB_CURRENT", dates, officeId, 1);
final List<BigDecimal> totalVI = sumOf(viA, viB, viC);
lines.add(formOneTotal("TOTAL OF VI", totalVI));
lines.add(formOneTotal("TOTAL OF VI : >>>>>>>>>>", totalVI));
lines.add(formOneHeading("VII. BALANCES OF ALL OTHER TYPES WITH"));
final List<BigDecimal> viiA = formOneLine(lines, "(a) State Co-operative Bank of the state concerned",
lines.add(formOneHeading("VII. Balance Of all Other types With :"));
final List<BigDecimal> viiA = formOneLine(lines, "(a) State Co.Op.Bank of the State Concerned :",
"FORM1_VII_A_STATE_COOP_OTHER", dates, officeId, 1);
final List<BigDecimal> viiB = formOneLine(lines, "(b) District Central Co-operative Bank",
final List<BigDecimal> viiB = formOneLine(lines, "(B) CENTRAL CO.OP.BANK OF THE DIST.CONCERNED",
"FORM1_VII_B_DCCB_OTHER", dates, officeId, 1);
final List<BigDecimal> viiC = formOneLine(lines, "(c) Investment in Government securities",
final List<BigDecimal> viiC = formOneLine(lines, "(C) INVESTMENT OF GOVT. SECURITY",
"FORM1_VII_C_GOVT_SECURITIES", dates, officeId, 1);
final List<BigDecimal> totalVII = sumOf(viiA, viiB, viiC);
lines.add(formOneTotal("TOTAL OF VII", totalVII));
lines.add(formOneTotal("TOTAL OF VII : >>>>>>>>>>", totalVII));
// VIII: only the excess counts. Where the banking system's claim on this bank exceeds the
// bank's own balance there is nothing to carry into the cash reserve, so it floors at zero.
@@ -1309,39 +1395,27 @@ public class RbiReserveReturnApiResource {
for (int i = 0; i < dates.size(); i++) {
viii.add(iiiA.get(i).subtract(iai.get(i)).max(BigDecimal.ZERO));
}
lines.add(formOneTotal("VIII. NET BALANCE IN CURRENT ACCOUNTS — excess of III(A) over I(a)(i)", viii));
// The liabilities the ratios are charged on: the last Friday of the second preceding
// fortnight, read per column rather than once, so each column states its own base.
final List<BigDecimal> baseDateDtl = new ArrayList<>();
final List<String> baseDates = new ArrayList<>();
for (final LocalDate date : dates) {
final LocalDate base = formOneBaseDate(date);
baseDates.add(base.toString());
baseDateDtl.add(formOneNetLiabilities(base, officeId));
}
final Map<String, Object> baseRow = formOneTotal(
"DEMAND AND TIME LIABILITIES OF THE BASE DATE — last Friday of the second preceding fortnight",
baseDateDtl);
baseRow.put("baseDates", baseDates);
lines.add(baseRow);
lines.add(formOneTotal("VIII. Net balance in current accounts i.e.excess of III (a) over I (a) (i) :", viii));
// The base liabilities are IV(b) above - it used to be repeated as a row of its own at the
// foot of the part, which put the same figure on the form twice under two different names.
final Map<String, Object> part = new LinkedHashMap<>();
part.put("title", "PART A");
part.put("lines", lines);
part.put("baseDates", baseDates);
part.put("baseDateLiabilities", baseDateDtl);
part.put("baseDates", ivBaseDates);
part.put("baseDateLiabilities", ivBase);
return part;
}
/** Part B: compliance with section 18 — the cash reserve. */
private Map<String, Object> formOnePartB(final List<LocalDate> dates, final Long officeId, final Rate crr) {
private Map<String, Object> formOnePartB(final List<LocalDate> dates, final List<LocalDate> bases, final Long officeId, final Rate crr) {
final List<Map<String, Object>> lines = new ArrayList<>();
final List<BigDecimal> required = new ArrayList<>();
final List<BigDecimal> maintained = new ArrayList<>();
for (final LocalDate date : dates) {
final BigDecimal base = formOneNetLiabilities(formOneBaseDate(date), officeId);
for (int i = 0; i < dates.size(); i++) {
final LocalDate date = dates.get(i);
final BigDecimal base = formOneNetLiabilities(baseFor(bases, dates, i), officeId);
required.add(crr == null ? BigDecimal.ZERO
: base.multiply(crr.percentage).divide(HUNDRED, 2, RoundingMode.HALF_UP));
// X = V + VI + VIII, the form's own definition.
@@ -1354,12 +1428,16 @@ public class RbiReserveReturnApiResource {
maintained.add(cash.add(currentAccounts).add(netCurrent));
}
lines.add(formOneTotal("IX. " + (crr == null ? "CRR" : crr.percentage + "%")
+ " of IV as on the last Friday of the second preceding fortnight", required));
lines.add(formOneTotal("X. CASH RESERVE ACTUALLY MAINTAINED (V + VI + VIII)", maintained));
// The rate is named against IV(b), not IV, because that is the figure it is charged on. The
// template's own wording says "Last Friday of the Second Preceding fortnight"; this bank's
// base rule is the matching close of the previous month, so the line says IV(b) and leaves
// the base date itself to the column heading rather than claiming a Friday it did not use.
lines.add(formOneTotal("IX. " + (crr == null ? "CRR rate not set" : crr.percentage + " PERCENT") + " OF IV AS ON THE BASE DATE",
required));
lines.add(formOneTotal("X. CASH RESERVE ACTUALLY MAINTAINED := V+VI+VIII", maintained));
final Map<String, Object> part = new LinkedHashMap<>();
part.put("title", "PART B — Compliance with Section 18");
part.put("title", "PART B : COMPLIANCE WITH SECTION 18. (Not applicable to scheduled state co-op. Bank)");
part.put("lines", lines);
part.put("required", required);
part.put("maintained", maintained);
@@ -1368,44 +1446,49 @@ public class RbiReserveReturnApiResource {
}
/** Part C: compliance with section 24 — the liquid assets. */
private Map<String, Object> formOnePartC(final List<LocalDate> dates, final Long officeId, final Rate slr) {
private Map<String, Object> formOnePartC(final List<LocalDate> dates, final List<LocalDate> bases, final Long officeId, final Rate slr) {
final List<Map<String, Object>> lines = new ArrayList<>();
final List<BigDecimal> required = new ArrayList<>();
final List<BigDecimal> cashAndOther = new ArrayList<>();
final List<BigDecimal> gold = new ArrayList<>();
final List<BigDecimal> securities = new ArrayList<>();
for (final LocalDate date : dates) {
final BigDecimal base = formOneNetLiabilities(formOneBaseDate(date), officeId);
for (int i = 0; i < dates.size(); i++) {
final LocalDate date = dates.get(i);
final BigDecimal base = formOneNetLiabilities(baseFor(bases, dates, i), officeId);
final BigDecimal slrRequired = slr == null ? BigDecimal.ZERO
: base.multiply(slr.percentage).divide(HUNDRED, 2, RoundingMode.HALF_UP);
required.add(slrRequired);
// XII(a) is the cash reserve held OVER the section 18 requirement, plus the other
// balances of part VII. Only the excess counts: the part of the cash reserve that meets
// section 18 is already committed and cannot also meet section 24.
// XII(a) is the cash reserve held OVER the section 18 requirement, plus the government
// securities of VII(c). Only the excess cash counts: the part of the cash reserve that
// meets section 18 is already committed and cannot also meet section 24.
//
// VII(c) alone, not the whole of VII. VII(a) and VII(b) are balances with the State
// Co-operative Bank and the District Central Co-operative Bank - deposits placed with
// other co-operative banks, which section 24 does not admit as liquid assets. Counting
// them here overstated what the bank held against SLR by the whole of those deposits.
final BigDecimal crrRequired = formOnePartBRequired(date, officeId);
final BigDecimal crrMaintained = formOnePartBMaintained(date, officeId);
final BigDecimal excessCash = crrMaintained.subtract(crrRequired).max(BigDecimal.ZERO);
final BigDecimal otherBalances = figureFor("FORM1_VII_A_STATE_COOP_OTHER", date, officeId).amount
.add(figureFor("FORM1_VII_B_DCCB_OTHER", date, officeId).amount)
.add(figureFor("FORM1_VII_C_GOVT_SECURITIES", date, officeId).amount);
cashAndOther.add(excessCash.add(otherBalances));
final BigDecimal governmentSecurities = figureFor("FORM1_VII_C_GOVT_SECURITIES", date, officeId).amount;
cashAndOther.add(excessCash.add(governmentSecurities));
gold.add(figureFor("FORMA_SLR_GOLD", date, officeId).amount);
securities.add(figureFor("SLR_INVESTMENTS", date, officeId).amount);
}
lines.add(formOneTotal("XI. " + (slr == null ? "SLR" : slr.percentage + "%")
+ " of IV as on the last Friday of the second preceding fortnight", required));
lines.add(formOneHeading("XII. ASSETS ACTUALLY MAINTAINED"));
lines.add(formOneRow("(a) Cash and other balances maintained in India (X − IX + VII)", null, cashAndOther, 1));
// Charged on IV(b) like the cash reserve above, and named the same way.
lines.add(formOneTotal("XI. " + (slr == null ? "SLR rate not set" : slr.percentage + " percent") + " (or a higher specified percentage) of IV as on the base date",
required));
lines.add(formOneHeading("XII. ASSETS ACTUALLY MAINTAINED :"));
lines.add(formOneRow("(a) Cash and other balances maintained in India i.e. X-IX+VII :", null, cashAndOther, 1));
lines.add(formOneRow("(b) Gold", "FORMA_SLR_GOLD", gold, 1));
lines.add(formOneRow("(c) Unencumbered approved securities", "SLR_INVESTMENTS", securities, 1));
lines.add(formOneRow("(c) Unencombered approved Securites $$", "SLR_INVESTMENTS", securities, 1));
final List<BigDecimal> totalXII = sumOf(cashAndOther, gold, securities);
lines.add(formOneTotal("TOTAL OF XII", totalXII));
lines.add(formOneTotal("Total of XII.....................................", totalXII));
final Map<String, Object> part = new LinkedHashMap<>();
part.put("title", "PART C — Compliance with Section 24");
part.put("title", "PART C : COMPLIANCE WITH SECTION 24 (Not applicable to scheduled state co-op. banks)");
part.put("lines", lines);
part.put("required", required);
part.put("maintained", totalXII);
@@ -1413,6 +1496,115 @@ public class RbiReserveReturnApiResource {
return part;
}
/**
* Every day of the period the form covers, with what each ratio required that day and what was
* held against it.
*
* <p>
* The form itself reports two closes, and a bank that held nothing for thirteen days and topped
* up on the fourteenth has a form that reads as compliant. Both ratios are reckoned over the
* whole period, so the day-by-day position is what the compliance actually turns on - and it is
* the figure an inspector asks for first.
*
* <p>
* Each day is charged on ITS OWN base, read through the same rule the columns use, so a day in
* the first fortnight is measured against a different requirement from one in the second. A
* single required amount applied across the month would show every day of one fortnight passing
* or failing for the wrong reason.
*
* @param from the first day reported, usually the start of the month the closes fall in.
* @param to the last, which is the later close.
*/
private Map<String, Object> formOneDaily(final LocalDate from, final LocalDate to, final Long officeId,
final Rate crr, final Rate slr) {
final List<Map<String, Object>> days = new ArrayList<>();
BigDecimal crrTotal = BigDecimal.ZERO;
BigDecimal slrTotal = BigDecimal.ZERO;
BigDecimal crrLowest = null;
BigDecimal slrLowest = null;
LocalDate crrLowestOn = null;
LocalDate slrLowestOn = null;
int crrShortDays = 0;
int slrShortDays = 0;
for (LocalDate day = from; !day.isAfter(to); day = day.plusDays(1)) {
final BigDecimal base = formOneNetLiabilities(formOneBaseDate(day), officeId);
final BigDecimal crrRequired = crr == null ? BigDecimal.ZERO
: base.multiply(crr.percentage).divide(HUNDRED, 2, RoundingMode.HALF_UP);
final BigDecimal slrRequired = slr == null ? BigDecimal.ZERO
: base.multiply(slr.percentage).divide(HUNDRED, 2, RoundingMode.HALF_UP);
final BigDecimal crrHeld = formOnePartBMaintained(day, officeId);
// SLR counts the cash held OVER the section 18 requirement, plus the other balances and
// the securities - the same definition Part C uses, so the two cannot disagree.
final BigDecimal excessCash = crrHeld.subtract(crrRequired).max(BigDecimal.ZERO);
final BigDecimal slrHeld = excessCash
.add(figureFor("FORM1_VII_A_STATE_COOP_OTHER", day, officeId).amount)
.add(figureFor("FORM1_VII_B_DCCB_OTHER", day, officeId).amount)
.add(figureFor("FORM1_VII_C_GOVT_SECURITIES", day, officeId).amount)
.add(figureFor("FORMA_SLR_GOLD", day, officeId).amount)
.add(figureFor("SLR_INVESTMENTS", day, officeId).amount);
final BigDecimal crrSurplus = crrHeld.subtract(crrRequired);
final BigDecimal slrSurplus = slrHeld.subtract(slrRequired);
if (crrSurplus.compareTo(BigDecimal.ZERO) < 0) {
crrShortDays++;
}
if (slrSurplus.compareTo(BigDecimal.ZERO) < 0) {
slrShortDays++;
}
crrTotal = crrTotal.add(crrHeld);
slrTotal = slrTotal.add(slrHeld);
if (crrLowest == null || crrHeld.compareTo(crrLowest) < 0) {
crrLowest = crrHeld;
crrLowestOn = day;
}
if (slrLowest == null || slrHeld.compareTo(slrLowest) < 0) {
slrLowest = slrHeld;
slrLowestOn = day;
}
final Map<String, Object> row = new LinkedHashMap<>();
row.put("date", day.toString());
row.put("baseDate", formOneBaseDate(day).toString());
// The liabilities the day was charged on, stated rather than left to be divided back out
// of the requirement: the CIMS daily sheets carry it as a column of its own, and on a day
// whose rate is unset the requirement is zero, which no division recovers a base from.
row.put("baseLiabilities", base);
// The day's OWN liabilities, which the base above does not show. The base holds still
// for a whole fortnight, so a table carrying only it cannot say whether the bank's
// liabilities rose or fell on any particular day - every row of the fortnight reads the
// same. This moves daily, and the gap between the two is the lag the rules build in.
row.put("ownLiabilities", formOneNetLiabilities(day, officeId));
row.put("crrRequired", crrRequired);
row.put("crrMaintained", crrHeld);
row.put("crrSurplus", crrSurplus);
row.put("slrRequired", slrRequired);
row.put("slrMaintained", slrHeld);
row.put("slrSurplus", slrSurplus);
days.add(row);
}
final Map<String, Object> out = new LinkedHashMap<>();
out.put("from", from.toString());
out.put("to", to.toString());
out.put("days", days);
out.put("dayCount", days.size());
final BigDecimal count = BigDecimal.valueOf(Math.max(days.size(), 1));
out.put("crrAverage", crrTotal.divide(count, 2, RoundingMode.HALF_UP));
out.put("slrAverage", slrTotal.divide(count, 2, RoundingMode.HALF_UP));
out.put("crrLowest", crrLowest == null ? BigDecimal.ZERO : crrLowest);
out.put("crrLowestOn", crrLowestOn == null ? null : crrLowestOn.toString());
out.put("slrLowest", slrLowest == null ? BigDecimal.ZERO : slrLowest);
out.put("slrLowestOn", slrLowestOn == null ? null : slrLowestOn.toString());
// Counted rather than left for a reader to spot: a single day short is a breach, and on a
// table of thirty rows it is exactly what the eye skips.
out.put("crrShortDays", crrShortDays);
out.put("slrShortDays", slrShortDays);
return out;
}
private BigDecimal formOnePartBRequired(final LocalDate date, final Long officeId) {
final Rate crr = rateInForce("CRR", date);
if (crr == null) {
@@ -1433,23 +1625,47 @@ public class RbiReserveReturnApiResource {
}
/**
* The date both ratios are charged on: the last Friday of the SECOND PRECEDING fortnight.
* The base date a column's ratios are charged on.
*
* <p>
* Counted in fortnights, not in weeks. For a column closing 15 August the fortnight it belongs
* to is 1-15 August, the first preceding one is 16-31 July, and the second is 1-15 July - so
* the base falls in the first half of July, roughly six weeks back rather than the four a
* straight subtraction would give. Reading the rate off a date a fortnight too late would
* report a requirement the bank never had time to meet, which is the whole point of the lag.
* Taken from the list the caller supplied, so a base entered by hand reaches every part of the
* form rather than only the column heading. Where no list was given - or it is shorter than the
* columns - the statutory rule applies.
*/
private LocalDate baseFor(final List<LocalDate> bases, final List<LocalDate> dates, final int index) {
if (bases != null && index < bases.size() && bases.get(index) != null) {
return bases.get(index);
}
return formOneBaseDate(dates.get(index));
}
/**
* The date a column's ratios are charged on: the previous month's matching fortnight close.
*
* <p>
* Within that fortnight the form takes its last Friday, shifted off a holiday the same way
* every other reporting date is.
* Which fortnight the column falls in settles it, not the day it carries. The 1st to the 15th
* charge on the 15th of the previous month; anything later charges on the previous month's END,
* whatever day that is. So 30 September charges on 31 August - and so does 20 September, since
* both sit in the second fortnight and the second fortnight closes with the month.
*
* <p>
* Keyed on the fortnight rather than on the day number because the two closes are not the same
* kind of date: the 15th is fixed, the month end moves between 28 and 31. Matching day for day
* would charge 30 September on 30 August, a date that closes nothing.
*
* <p>
* RBI's own wording is "the last Friday of the second preceding fortnight", and that rule has
* been tried here twice. Both times it was taken out again for the same reason: it puts the base
* on a weekday that moves and roughly six weeks back, and the dates it produces do not match the
* returns this bank has already filed by hand. The fortnight closes this bank files on are the
* 15th and the month end. Where a particular return needs some other base, it can be entered by
* hand through {@code baseFor} above, which is why that path exists.
*/
private LocalDate formOneBaseDate(final LocalDate columnDate) {
final LocalDate ownClose = fortnightCloseOnOrAfter(columnDate);
final LocalDate secondPrecedingClose = fortnightCloseBefore(fortnightCloseBefore(ownClose));
return precedingWorkingDay(reportingFridayOnOrBefore(secondPrecedingClose));
final LocalDate previousMonthEnd = columnDate.withDayOfMonth(1).minusDays(1);
// Which fortnight the column falls in settles the base, not the day it carries. The first
// fortnight closes on the 15th; everything after it closes on the month end.
return columnDate.getDayOfMonth() <= 15 ? previousMonthEnd.withDayOfMonth(15) : previousMonthEnd;
}
/**
@@ -1579,7 +1795,10 @@ public class RbiReserveReturnApiResource {
final LocalDate previousClose = requested.withDayOfMonth(1).minusDays(1);
final LocalDate base = formOneBaseDate(currentClose);
final List<LocalDate> columnDates = List.of(previousClose, currentClose, base);
// Two columns, as on Form 1. The base is stated against the lines it settles rather than
// given a column, where its balances would read as a third period being reported.
final List<LocalDate> columnDates = List.of(previousClose, currentClose);
final List<LocalDate> baseDates = List.of(formOneBaseDate(previousClose), base);
final Map<String, Object> response = new LinkedHashMap<>();
response.put("formCode", "FORM_9_STATUTORY");
@@ -1590,6 +1809,7 @@ public class RbiReserveReturnApiResource {
response.put("monthEnd", nominalMonthEnd.toString());
response.put("monthComplete", monthComplete);
response.put("columns", columnDates.stream().map(LocalDate::toString).toList());
response.put("baseColumns", baseDates.stream().map(LocalDate::toString).toList());
final Rate crr = rateInForce("CRR", currentClose);
final Rate slr = rateInForce("SLR", currentClose);
@@ -1599,8 +1819,11 @@ public class RbiReserveReturnApiResource {
// Part A establishes the liabilities both ratios are charged on, so it is needed here even
// though only section 24 is settled below: without it the required amount at XI is a figure
// with nothing behind it.
response.put("partA", formOnePartA(columnDates, officeId, crr, slr));
response.put("partC", formOnePartC(columnDates, officeId, slr));
response.put("partA", formOnePartA(columnDates, baseDates, officeId, crr, slr));
response.put("partC", formOnePartC(columnDates, baseDates, officeId, slr));
// Every day of the month, as on Form 1. Section 24 is reckoned over the period too, so a
// month-end position that passes says nothing about the days behind it.
response.put("daily", formOneDaily(currentClose.withDayOfMonth(1), currentClose, officeId, crr, slr));
final List<String> unmet = new ArrayList<>();
if (slr == null) {
@@ -1620,9 +1843,9 @@ public class RbiReserveReturnApiResource {
// As on Form 1: a nil base makes the requirement nil, and the form then reads the same as a
// bank with nothing to maintain. Said with the date so the nil can be read for what it is.
if (formOneNetLiabilities(base, officeId).compareTo(BigDecimal.ZERO) == 0) {
unmet.add("The ratio is charged on the net liabilities of " + base + " — the last Friday "
+ "of the second preceding fortnight — and the ledger holds none on that date. "
+ "The required amount is therefore nil, because the base is nil.");
unmet.add("The ratio is charged on the net liabilities of " + base
+ ", and the ledger holds none on that date. The required amount is therefore "
+ "nil, because the base is nil.");
}
response.put("unmetRequirements", unmet);
return gson.toJson(response);
@@ -95,7 +95,9 @@ public class RbiFormAAutoSaveService {
// No column dates passed: today IS a fortnight close - the check above returned
// otherwise - so the form derives its own pair from it, which is the pair an unattended
// run should file. A filer needing a different period enters both dates on the screen.
report = gson.fromJson(returnApiResource.form1Statutory(today.toString(), null, null, null),
// No base dates passed either: an unattended run files the base the rules fix, which is
// what a saved return should carry. A filer needing a different base enters it on screen.
report = gson.fromJson(returnApiResource.form1Statutory(today.toString(), null, null, null, null, null),
JsonObject.class);
} catch (final RuntimeException e) {
// A return that cannot be computed is not an error worth failing the batch over - an
@@ -361,6 +361,9 @@ public class RecurringDepositAccountsApiResource {
} else if (is(commandParam, "close")) {
final CommandWrapper commandRequest = builder.closeRecurringDepositAccount(accountId).build();
result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "extendTenure")) {
final CommandWrapper commandRequest = builder.extendTenureRecurringDepositAccount(accountId).build();
result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
} else if (is(commandParam, "prematureClose")) {
final CommandWrapper commandRequest = builder.prematureCloseRecurringDepositAccount(accountId).build();
result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest);
@@ -377,7 +380,7 @@ public class RecurringDepositAccountsApiResource {
if (result == null) {
throw new UnrecognizedQueryParamException("command", commandParam,
new Object[] { "reject", "withdrawnByApplicant", "approve", "undoapproval", "activate", "calculateInterest",
"postInterest", "close", "prematureClose", "calculatePrematureAmount" });
"postInterest", "close", "prematureClose", "calculatePrematureAmount", "extendTenure" });
}
return this.toApiJsonSerializer.serialize(result);
@@ -0,0 +1,205 @@
/**
* 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.api;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.time.LocalDate;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.apache.fineract.portfolio.savings.DepositsApiConstants;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/**
* RD Dashboard's data source: every Recurring Deposit still running (ACTIVE, or MATURED and waiting to be closed) in
* the user's office hierarchy, each with its installment position worked out as of the business date, plus the
* month's closures and penalty income for the summary cards.
*
* <p>
* An installment counts as paid by the deposit's cumulative deposits, not by the schedule's own completed flag - the
* same rule {@code RecurringDepositMissedInstallmentPenaltyService} uses, since money paid in advance at the counter is
* not always allocated to the installment it covers. The dashboard and the penalty job therefore agree on which
* installments are overdue.
*/
@Path("/v1/recurringdepositaccounts/dashboard")
@Component
@Tag(name = "Recurring Deposit Accounts", description = "RD Dashboard: running RDs with their installment position.")
@RequiredArgsConstructor
public class RecurringDepositDashboardApiResource {
/** DepositAccountType.RECURRING_DEPOSIT. */
private static final int RECURRING_DEPOSIT = 300;
/** SavingsAccountStatusType values. */
private static final int ACTIVE = 300;
private static final int CLOSED = 600;
private static final int PRE_MATURE_CLOSURE = 700;
private static final int MATURED = 800;
/** SavingsAccountTransactionType.DEPOSIT. */
private static final int DEPOSIT = 1;
private static final String ROWS_SQL = """
WITH rd AS (
SELECT sa.id, sa.account_no, sa.client_id, sa.product_id, sa.status_enum, sa.account_balance_derived,
sa.auto_debit_facility, sa.linked_account_no, c.display_name AS client_name, o.id AS office_id,
o.name AS office_name
FROM m_savings_account sa
JOIN m_client c ON c.id = sa.client_id
JOIN m_office o ON o.id = c.office_id
WHERE sa.deposit_type_enum = ? AND sa.status_enum IN (?, ?) AND o.hierarchy LIKE ?
),
paid AS (
SELECT t.savings_account_id AS id, SUM(t.amount) AS total_paid,
SUM(t.amount) FILTER (WHERE t.transaction_date BETWEEN ? AND ?) AS paid_this_month
FROM m_savings_account_transaction t
JOIN rd ON rd.id = t.savings_account_id
WHERE t.transaction_type_enum = ? AND t.is_reversed = false
GROUP BY t.savings_account_id
),
sched AS (
SELECT s.savings_account_id AS id, s.duedate, s.deposit_amount,
SUM(s.deposit_amount) OVER (PARTITION BY s.savings_account_id ORDER BY s.duedate, s.installment) AS cum_due
FROM m_mandatory_savings_schedule s
JOIN rd ON rd.id = s.savings_account_id
),
pos AS (
SELECT sc.id,
COUNT(*) AS total_installments,
COUNT(*) FILTER (WHERE sc.cum_due <= COALESCE(p.total_paid, 0)) AS paid_installments,
MIN(sc.duedate) FILTER (WHERE sc.cum_due > COALESCE(p.total_paid, 0)) AS next_unpaid_due,
COUNT(*) FILTER (WHERE sc.cum_due > COALESCE(p.total_paid, 0) AND sc.duedate < ?) AS overdue_installments,
GREATEST(COALESCE(SUM(sc.deposit_amount) FILTER (WHERE sc.duedate < ?), 0) - COALESCE(MAX(p.total_paid), 0), 0)
AS overdue_amount,
COUNT(*) FILTER (WHERE sc.duedate = ?) AS due_today_count,
COUNT(*) FILTER (WHERE sc.duedate = ? AND sc.cum_due <= COALESCE(p.total_paid, 0)) AS due_today_paid,
COALESCE(SUM(sc.deposit_amount) FILTER (WHERE sc.duedate BETWEEN ? AND ?), 0) AS due_this_month,
COALESCE(SUM(sc.deposit_amount) FILTER (WHERE sc.duedate BETWEEN ? AND ?
AND sc.cum_due <= COALESCE(p.total_paid, 0)), 0) AS received_this_month
FROM sched sc
LEFT JOIN paid p ON p.id = sc.id
GROUP BY sc.id
),
pen AS (
SELECT pe.savings_account_id AS id, COUNT(*) AS penalty_count, SUM(pe.penalty_amount) AS penalty_amount
FROM m_rd_installment_penalty pe
JOIN rd ON rd.id = pe.savings_account_id
GROUP BY pe.savings_account_id
),
lien AS (
SELECT paa.linked_savings_account_id AS id, SUM(COALESCE(gfd.amount_remaining_derived, gfd.amount)) AS lien_amount
FROM m_guarantor_funding_details gfd
JOIN m_portfolio_account_associations paa ON paa.id = gfd.account_associations_id
JOIN m_loan l ON l.id = paa.loan_account_id
JOIN rd ON rd.id = paa.linked_savings_account_id
WHERE gfd.status_enum = 100 AND l.loan_status_id IN (100, 200, 300)
AND COALESCE(gfd.amount_remaining_derived, gfd.amount) > 0
GROUP BY paa.linked_savings_account_id
)
SELECT rd.id AS "id", rd.account_no AS "accountNo", rd.client_id AS "clientId", rd.client_name AS "clientName",
rd.office_id AS "officeId", rd.office_name AS "officeName", sp.id AS "productId", sp.name AS "productName",
rd.status_enum AS "status", rd.account_balance_derived AS "balance",
rdd.mandatory_recommended_deposit_amount AS "installmentAmount",
TO_CHAR(datp.maturity_date, 'YYYY-MM-DD') AS "maturityDate", datp.maturity_amount AS "maturityAmount",
COALESCE(rd.auto_debit_facility, false) AS "autoDebit", rd.linked_account_no AS "linkedAccountNo",
COALESCE(sp.missed_installment_grace_days, 0) AS "graceDays",
COALESCE(sp.penalty_grace_period_missed_installments, false) AS "penaltyEnabled",
COALESCE(pos.total_installments, 0) AS "totalInstallments",
COALESCE(pos.paid_installments, 0) AS "paidInstallments",
TO_CHAR(pos.next_unpaid_due, 'YYYY-MM-DD') AS "nextDueDate",
COALESCE(pos.overdue_installments, 0) AS "overdueInstallments",
COALESCE(pos.overdue_amount, 0) AS "overdueAmount",
COALESCE(pos.due_today_count, 0) AS "dueTodayCount",
COALESCE(pos.due_today_paid, 0) AS "dueTodayPaid",
COALESCE(pos.due_this_month, 0) AS "dueThisMonth",
COALESCE(pos.received_this_month, 0) AS "receivedThisMonth",
COALESCE(p.paid_this_month, 0) AS "paidThisMonth",
COALESCE(pen.penalty_count, 0) AS "penaltyCount",
COALESCE(pen.penalty_amount, 0) AS "penaltyAmount",
COALESCE(lien.lien_amount, 0) AS "lienAmount"
FROM rd
JOIN m_savings_product sp ON sp.id = rd.product_id
LEFT JOIN m_deposit_account_term_and_preclosure datp ON datp.savings_account_id = rd.id
LEFT JOIN m_deposit_account_recurring_detail rdd ON rdd.savings_account_id = rd.id
LEFT JOIN pos ON pos.id = rd.id
LEFT JOIN paid p ON p.id = rd.id
LEFT JOIN pen ON pen.id = rd.id
LEFT JOIN lien ON lien.id = rd.id
ORDER BY pos.next_unpaid_due NULLS LAST, rd.account_no
""";
/** RDs closed this month, split by how they ended. */
private static final String CLOSED_THIS_MONTH_SQL = """
SELECT COUNT(*) FILTER (WHERE sa.status_enum = ?) AS matured_closed,
COUNT(*) FILTER (WHERE sa.status_enum = ?) AS premature_closed
FROM m_savings_account sa
JOIN m_client c ON c.id = sa.client_id
JOIN m_office o ON o.id = c.office_id
WHERE sa.deposit_type_enum = ? AND sa.closedon_date BETWEEN ? AND ? AND o.hierarchy LIKE ?
""";
/** Missed-installment penalties charged, this month and in all, on RDs in the hierarchy (closed ones included). */
private static final String PENALTY_INCOME_SQL = """
SELECT COALESCE(SUM(pe.penalty_amount) FILTER (WHERE pe.applied_on_date BETWEEN ? AND ?), 0) AS this_month,
COALESCE(SUM(pe.penalty_amount), 0) AS total
FROM m_rd_installment_penalty pe
JOIN m_savings_account sa ON sa.id = pe.savings_account_id
JOIN m_client c ON c.id = sa.client_id
JOIN m_office o ON o.id = c.office_id
WHERE o.hierarchy LIKE ?
""";
private final PlatformSecurityContext context;
private final JdbcTemplate jdbcTemplate;
private final Gson gson = new Gson();
@GET
@Produces(MediaType.APPLICATION_JSON)
public String retrieve() {
this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME);
final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy() + "%";
// "Today" is the business date - the branch's working day, not the server clock.
final LocalDate today = DateUtils.getBusinessLocalDate();
final LocalDate monthStart = today.withDayOfMonth(1);
final LocalDate monthEnd = today.withDayOfMonth(today.lengthOfMonth());
final List<Map<String, Object>> rows = this.jdbcTemplate.queryForList(ROWS_SQL, RECURRING_DEPOSIT, ACTIVE, MATURED, hierarchy,
monthStart, monthEnd, DEPOSIT, today, today, today, today, monthStart, monthEnd, monthStart, monthEnd);
final Map<String, Object> closed = this.jdbcTemplate.queryForMap(CLOSED_THIS_MONTH_SQL, CLOSED, PRE_MATURE_CLOSURE,
RECURRING_DEPOSIT, monthStart, monthEnd, hierarchy);
final Map<String, Object> penalty = this.jdbcTemplate.queryForMap(PENALTY_INCOME_SQL, monthStart, monthEnd, hierarchy);
final Map<String, Object> result = new LinkedHashMap<>();
result.put("businessDate", today.toString());
result.put("maturedClosedThisMonth", closed.get("matured_closed"));
result.put("prematureClosedThisMonth", closed.get("premature_closed"));
result.put("penaltyIncomeThisMonth", penalty.get("this_month"));
result.put("penaltyIncomeTotal", penalty.get("total"));
result.put("accounts", rows);
return this.gson.toJson(result);
}
}
@@ -0,0 +1,80 @@
/**
* 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.api;
import com.google.gson.Gson;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.apache.fineract.portfolio.savings.DepositsApiConstants;
import org.apache.fineract.portfolio.savings.service.RecurringDepositLienService;
import org.springframework.stereotype.Component;
/**
* Read-only: the loans a recurring deposit currently secures and how much of it each one holds, plus how much more
* could be given as loan against it today, so the RD screens can show the lien, its limit, and why the deposit cannot
* be closed.
*/
@Path("/v1/recurringdepositaccounts/{accountId}/liens")
@Component
@Tag(name = "Recurring Deposit Account", description = "Liens on a recurring deposit pledged as loan security.")
@RequiredArgsConstructor
public class RecurringDepositLienApiResource {
private final PlatformSecurityContext context;
private final RecurringDepositLienService recurringDepositLienService;
private final Gson gson = new Gson();
@GET
@Produces(MediaType.APPLICATION_JSON)
public String retrieve(@PathParam("accountId") final Long accountId) {
this.context.authenticatedUser().validateHasReadPermission(DepositsApiConstants.RECURRING_DEPOSIT_ACCOUNT_RESOURCE_NAME);
final List<RecurringDepositLienService.Lien> liens = this.recurringDepositLienService.activeLiens(accountId);
final Map<String, Object> result = new LinkedHashMap<>();
final BigDecimal totalLien = liens.stream().map(RecurringDepositLienService.Lien::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
result.put("totalLienAmount", totalLien);
final RecurringDepositLienService.LienLimit limit = this.recurringDepositLienService.lienLimit(accountId);
if (limit != null) {
result.put("lienAllowed", limit.lienAllowed());
result.put("lienPercentage", limit.accountPercentage());
result.put("productLienPercentage", limit.productPercentage());
result.put("effectiveLienPercentage", limit.effectivePercentage());
result.put("maxLoanAmount", limit.maxLoanAmount());
result.put("availableForLoan", limit.maxLoanAmount().subtract(totalLien).max(BigDecimal.ZERO));
}
result.put("liens", liens.stream().map(lien -> {
final Map<String, Object> row = new LinkedHashMap<>();
row.put("loanId", lien.loanId());
row.put("loanAccountNo", lien.loanAccountNo());
row.put("loanStatus", lien.loanStatus());
row.put("amount", lien.amount());
return row;
}).toList());
return this.gson.toJson(result);
}
}
@@ -580,7 +580,7 @@ public class SavingsDailyInterestService {
final BigDecimal balance = jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(CASE
WHEN t.transaction_type_enum IN (1, 3, 8) THEN t.amount
WHEN t.transaction_type_enum IN (2, 4, 5, 7) THEN -t.amount
WHEN t.transaction_type_enum IN (2, 4, 5, 7, 18) THEN -t.amount
ELSE 0 END), 0)
FROM m_savings_account_transaction t
WHERE t.savings_account_id = ?
@@ -597,7 +597,7 @@ public class SavingsDailyInterestService {
SELECT t.transaction_date AS d,
SUM(CASE
WHEN t.transaction_type_enum IN (1, 3, 8) THEN t.amount
WHEN t.transaction_type_enum IN (2, 4, 5, 7) THEN -t.amount
WHEN t.transaction_type_enum IN (2, 4, 5, 7, 18) THEN -t.amount
ELSE 0 END) AS net
FROM m_savings_account_transaction t
WHERE t.savings_account_id = ?
@@ -613,7 +613,7 @@ public class SavingsDailyInterestService {
final BigDecimal movement = jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(CASE
WHEN t.transaction_type_enum IN (1, 3, 8) THEN t.amount
WHEN t.transaction_type_enum IN (2, 4, 5, 7) THEN -t.amount
WHEN t.transaction_type_enum IN (2, 4, 5, 7, 18) THEN -t.amount
ELSE 0 END), 0)
FROM m_savings_account_transaction t
WHERE t.savings_account_id = ?
@@ -222,9 +222,10 @@ public class SavingsInterestPostingReportService {
return jdbcTemplate.queryForList("""
SELECT r.id FROM m_savings_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 = ?)
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.savings_product_id
""", Long.class, businessDate, headOfficeId, businessDate);
""", Long.class, businessDate, headOfficeId, businessDate, businessDate);
}
/** Every approved report still waiting, for the nightly safety net. */
@@ -245,15 +246,15 @@ public class SavingsInterestPostingReportService {
// ── reading ──────────────────────────────────────────────────────────────────────────────────
/**
* Reports for the screen. A branch user sees only their branch; a head office user sees every
* branch, so it can act for one that did not open. canAct says whether this user may regenerate
* or approve the report.
* 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 or approve the report, and blockedReason why not.
*/
public List<Map<String, Object>> list(final LocalDate postingDate, final String status, final Long productId, final Long officeId,
final AppUser user) {
final String scope, final AppUser user) {
final Long userOffice = officeOf(user);
final boolean headOffice = isHeadOffice(userOffice);
final Long branch = headOffice ? officeId : userOffice;
final boolean others = "others".equalsIgnoreCase(scope) && isHeadOffice(userOffice);
final Long branch = others ? officeId : userOffice;
final StringBuilder sql = new StringBuilder("""
SELECT r.id, r.savings_product_id AS "productId", p.name AS "productName", r.office_id AS "officeId",
@@ -287,6 +288,10 @@ public class SavingsInterestPostingReportService {
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();
@@ -294,7 +299,9 @@ public class SavingsInterestPostingReportService {
for (final Map<String, Object> row : jdbcTemplate.queryForList(sql.toString(), params.toArray())) {
final Map<String, Object> out = new LinkedHashMap<>(row);
final Long reportOffice = row.get("officeId") == null ? null : ((Number) row.get("officeId")).longValue();
out.put("canAct", reportOffice != null && mayAct(userOffice, reportOffice, businessDate));
final String blocked = reportOffice == null ? "No branch on this report." : actBlockedReason(userOffice, reportOffice, businessDate);
out.put("canAct", blocked == null);
out.put("blockedReason", blocked);
rows.add(out);
}
return rows;
@@ -339,6 +346,45 @@ public class SavingsInterestPostingReportService {
return report;
}
/**
* What each savings account has earned so far in its current cycle — what it would be paid if
* interest were posted today. Read-only: nothing is saved, approved or posted. The ledger is first
* brought up to the business date (which moves no money) so the figure includes today.
*
* <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 LocalDate businessDate = DateUtils.getBusinessLocalDate();
transactionTemplate.executeWithoutResult(status -> accrualService.accrueForDate(businessDate));
final Long userOffice = officeOf(user);
final Long branch = isHeadOffice(userOffice) ? officeId : userOffice;
final StringBuilder sql = new StringBuilder("""
SELECT COALESCE(c.office_id, g.office_id) AS "officeId", o.name AS "officeName",
p.id AS "productId", p.name AS "productName", sa.id AS "savingsAccountId", sa.account_no AS "accountNo",
COALESCE(c.display_name, g.display_name) AS "clientName", d.closing_balance AS "balance",
d.interest_rate AS "rate", d.cycle_start_date AS "cycleStart", d.posting_date AS "postingDate",
d.balance_date AS "asOf", ROUND(d.cycle_cumulative_interest, 2) AS "interest"
FROM m_savings_daily_interest d
JOIN m_savings_account sa ON sa.id = d.savings_account_id
JOIN m_savings_product p ON p.id = d.savings_product_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_office o ON o.id = COALESCE(c.office_id, g.office_id)
WHERE p.deposit_type_enum = 100
AND sa.status_enum = ?
AND d.savings_transaction_id IS NULL
""");
final List<Object> params = new ArrayList<>(List.of(ACTIVE));
if (branch != null) {
sql.append(" AND COALESCE(c.office_id, g.office_id) = ?");
params.add(branch);
}
sql.append(" ORDER BY o.name, p.name, sa.account_no");
return jdbcTemplate.queryForList(sql.toString(), params.toArray());
}
/**
* Branch and product interest for the head office: per report, how many customers and how much
* interest, and where it stands. Superseded reports are left out — each line is the report that
@@ -375,9 +421,13 @@ public class SavingsInterestPostingReportService {
/**
* Branch and product pairs with interest due by the date that have no report yet — the noon job ran
* before they had anything due, or failed. Limited to what the user may act on.
* before they had anything due, or failed.
*
* <p>
* {@code scope} "own" (the default) lists the user's own branch. "others", for a head office user,
* lists the other branches — each with canAct, and where the head office may not act for it, why.
*/
public List<Map<String, Object>> dueWithoutReport(final LocalDate postingDate, final AppUser user) {
public List<Map<String, Object>> dueWithoutReport(final LocalDate postingDate, final AppUser user, final String scope) {
final List<Map<String, Object>> out = new ArrayList<>();
// A future date has nothing due yet, and offering to generate for it would label this cycle's
// part-earned interest with a date it has not reached.
@@ -386,15 +436,21 @@ public class SavingsInterestPostingReportService {
return out;
}
final Long userOffice = officeOf(user);
for (final DueKey due : dueKeys(postingDate, isHeadOffice(userOffice) ? null : userOffice)) {
if (activeReportId(due.productId(), due.officeId(), postingDate) == null
&& mayAct(userOffice, due.officeId(), businessDate)) {
final boolean others = "others".equalsIgnoreCase(scope) && isHeadOffice(userOffice);
for (final DueKey due : dueKeys(postingDate, others ? null : userOffice)) {
if (others == due.officeId().equals(userOffice)) {
continue;
}
if (activeReportId(due.productId(), due.officeId(), postingDate) == null) {
final Map<String, Object> row = new LinkedHashMap<>();
row.put("productId", due.productId());
row.put("productName", productName(due.productId()));
row.put("officeId", due.officeId());
row.put("officeName", jdbcTemplate.queryForObject("SELECT name FROM m_office WHERE id = ?", String.class, due.officeId()));
row.put("officeName", officeName(due.officeId()));
row.put("postingDate", postingDate.toString());
final String blocked = actBlockedReason(userOffice, due.officeId(), businessDate);
row.put("canAct", blocked == null);
row.put("blockedReason", blocked);
out.add(row);
}
}
@@ -408,36 +464,79 @@ public class SavingsInterestPostingReportService {
return !parent.isEmpty() && parent.get(0) == null;
}
/** Whether the branch opened its day on the date — the head office may act only for one that did not. */
/**
* Whether the branch is working on the date: it opened that day, or a day it opened earlier is still
* not closed. A branch with yesterday's day still open is open — it closes that day and goes on.
*/
public boolean branchOpenedOn(final Long officeId, final LocalDate businessDate) {
final Long rows = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM m_branch_day_register WHERE office_id = ? AND business_date = ?",
Long.class, officeId, businessDate);
final Long rows = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM m_branch_day_register
WHERE office_id = ? AND (business_date = ? OR (closed_at IS NULL AND business_date <= ?))
""", Long.class, officeId, businessDate, businessDate);
return rows != null && rows > 0;
}
private boolean mayAct(final Long userOffice, final Long reportOffice, final LocalDate businessDate) {
/** The branches, other than those given, that still have a day open on or before the date. */
public List<String> branchesStillOpen(final LocalDate businessDate, final Long... excludeOfficeIds) {
final StringBuilder sql = new StringBuilder("""
SELECT DISTINCT o.name FROM m_branch_day_register r JOIN m_office o ON o.id = r.office_id
WHERE r.closed_at IS NULL AND r.business_date <= ?
""");
final List<Object> params = new ArrayList<>(List.of(businessDate));
for (final Long exclude : excludeOfficeIds) {
sql.append(" AND r.office_id <> ?");
params.add(exclude);
}
sql.append(" ORDER BY o.name");
return jdbcTemplate.queryForList(sql.toString(), String.class, params.toArray());
}
/**
* Null where the user may generate or approve the branch's report, otherwise why not.
*
* <p>
* A branch always acts for itself. The head office acts for another branch only when that branch
* has not opened at all, and only once every branch that did open has closed — the head office's
* own close being the last of the day, so nothing is taken out of a branch that may still open.
*/
private String actBlockedReason(final Long userOffice, final Long reportOffice, final LocalDate businessDate) {
if (userOffice == null) {
return false;
return "No branch is set for this user.";
}
if (userOffice.equals(reportOffice)) {
return true;
return null;
}
return isHeadOffice(userOffice) && !branchOpenedOn(reportOffice, businessDate);
final String branch = officeName(reportOffice);
if (!isHeadOffice(userOffice)) {
return "Only " + branch + " can generate or approve its own interest posting report.";
}
if (branchOpenedOn(reportOffice, businessDate)) {
return branch + " is open — it generates and approves its own report.";
}
final List<String> stillOpen = 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;
}
private boolean mayAct(final Long userOffice, final Long reportOffice, final LocalDate businessDate) {
return actBlockedReason(userOffice, reportOffice, businessDate) == 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);
if (userOffice != null && userOffice.equals(reportOffice)) {
return false;
final String blocked = actBlockedReason(userOffice, reportOffice, businessDate);
if (blocked != null) {
throw new PlatformDataIntegrityException("error.msg.savingsinterestreport.other.branch", blocked);
}
if (mayAct(userOffice, reportOffice, businessDate)) {
return true;
}
final String branch = jdbcTemplate.queryForObject("SELECT name FROM m_office WHERE id = ?", String.class, reportOffice);
throw new PlatformDataIntegrityException("error.msg.savingsinterestreport.other.branch",
"Only " + branch + " can generate or approve its own interest posting report. The head office may do so only on a day "
+ branch + " has not opened.");
return !reportOffice.equals(userOffice);
}
private String officeName(final Long officeId) {
return jdbcTemplate.queryForObject("SELECT name FROM m_office WHERE id = ?", String.class, officeId);
}
private static Long officeOf(final AppUser user) {
@@ -65,20 +65,34 @@ public class SavingsInterestPostingReportApiResource {
/** 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("productId") final Long productId, @QueryParam("officeId") final Long officeId,
@QueryParam("scope") final String scope) {
final AppUser user = context.authenticatedUser();
user.validateHasReadPermission(RESOURCE);
return gson.toJson(reportService.list(parseDate(postingDate), status, productId, officeId, user).stream().map(this::plain).toList());
return gson.toJson(reportService.list(parseDate(postingDate), status, productId, officeId, scope, user).stream().map(this::plain).toList());
}
/** Who is looking: their branch, and whether it is the head office (which gets the Other branches tab). */
@GET
@Path("/context")
public String userContext() {
final AppUser user = 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", reportService.isHeadOffice(officeId));
return gson.toJson(result);
}
/** Branch and product pairs with interest due by the date and no report yet, that this user may generate. */
@GET
@Path("/due-without-report")
public String dueWithoutReport(@QueryParam("postingDate") final String postingDate) {
public String dueWithoutReport(@QueryParam("postingDate") final String postingDate, @QueryParam("scope") final String scope) {
final AppUser user = context.authenticatedUser();
user.validateHasReadPermission(RESOURCE);
final LocalDate date = postingDate == null || postingDate.isBlank() ? DateUtils.getBusinessLocalDate() : parseDate(postingDate);
return gson.toJson(reportService.dueWithoutReport(date, user));
return gson.toJson(reportService.dueWithoutReport(date, user, scope));
}
/**
@@ -99,6 +113,15 @@ public class SavingsInterestPostingReportApiResource {
return gson.toJson(result);
}
/** Interest each account has earned so far this cycle, as if posted today. View only — nothing is saved. */
@GET
@Path("/preview")
public String preview(@QueryParam("officeId") final Long officeId) {
final AppUser user = context.authenticatedUser();
user.validateHasReadPermission(RESOURCE);
return gson.toJson(reportService.preview(officeId, user).stream().map(this::plain).toList());
}
/** The head office's view: per branch and product, customers paid and interest, over a date range. */
@GET
@Path("/summary")
@@ -180,6 +180,7 @@ public class DepositProductDataValidator {
}
validateRecurringDetailForCreate(element, baseDataValidator);
validateLienPercentage(element, baseDataValidator);
if (!hasRdSlabs) {
validateChartsData(element, baseDataValidator);
@@ -215,6 +216,7 @@ public class DepositProductDataValidator {
}
validateRecurringDepositUpdate(element, baseDataValidator);
validateLienPercentage(element, baseDataValidator);
// RD products now use the CBS base chart as a read-only template, so
// product updates no longer require a charts payload.
@@ -225,6 +227,40 @@ public class DepositProductDataValidator {
throwExceptionIfValidationWarningsExist(dataValidationErrors);
}
/** Lien Marked's loan limit: a share of the deposit's balance, so above 0 and at most 100. Optional. */
private void validateLienPercentage(final JsonElement element, final DataValidatorBuilder baseDataValidator) {
if (!this.fromApiJsonHelper.parameterExists("lienPercentage", element)) {
return;
}
final BigDecimal lienPercentage = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("lienPercentage", element);
baseDataValidator.reset().parameter("lienPercentage").value(lienPercentage).ignoreIfNull().positiveAmount()
.notGreaterThanMax(BigDecimal.valueOf(100));
validateMissedInstallmentPenalty(element, baseDataValidator);
}
/**
* Missed-installment penalty: grace days are whole days from 0, the type is 1 (flat amount) or 2 (% of the
* installment), and the amount is positive - at most 100 when it is a percentage. All optional.
*/
private void validateMissedInstallmentPenalty(final JsonElement element, final DataValidatorBuilder baseDataValidator) {
if (this.fromApiJsonHelper.parameterExists("missedInstallmentGraceDays", element)) {
final Integer graceDays = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("missedInstallmentGraceDays", element);
baseDataValidator.reset().parameter("missedInstallmentGraceDays").value(graceDays).ignoreIfNull().integerZeroOrGreater();
}
Integer penaltyType = null;
if (this.fromApiJsonHelper.parameterExists("missedInstallmentPenaltyType", element)) {
penaltyType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("missedInstallmentPenaltyType", element);
baseDataValidator.reset().parameter("missedInstallmentPenaltyType").value(penaltyType).ignoreIfNull().isOneOfTheseValues(1, 2);
}
if (this.fromApiJsonHelper.parameterExists("missedInstallmentPenaltyAmount", element)) {
final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("missedInstallmentPenaltyAmount", element);
baseDataValidator.reset().parameter("missedInstallmentPenaltyAmount").value(amount).ignoreIfNull().positiveAmount();
if (amount != null && Integer.valueOf(2).equals(penaltyType)) {
baseDataValidator.reset().parameter("missedInstallmentPenaltyAmount").value(amount).notGreaterThanMax(BigDecimal.valueOf(100));
}
}
}
private void validateDepositDetailForCreate(final JsonElement element, final FromJsonHelper fromApiJsonHelper,
final DataValidatorBuilder baseDataValidator, final DepositAccountType accountType) {
final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element);
@@ -67,4 +67,7 @@ public interface DepositAccountDomainService {
Long handleFDAccountPayment(FixedDepositAccount account, PaymentDetail paymentDetail, AppUser user, JsonCommand command,
Map<String, Object> changes);
/** Names the journal entries of the recurring deposit's interest credits that have no narration yet. */
void narrateRdInterestPostings(RecurringDepositAccount account);
}
@@ -72,6 +72,7 @@ import org.apache.fineract.portfolio.savings.DepositAccountOnClosureType;
import org.apache.fineract.portfolio.savings.DepositAccountType;
import org.apache.fineract.portfolio.savings.DepositsApiConstants;
import org.apache.fineract.portfolio.savings.PrematureClosureReasonType;
import org.apache.fineract.portfolio.savings.SavingsAccountTransactionType;
import org.apache.fineract.portfolio.savings.SavingsApiConstants;
import org.apache.fineract.portfolio.savings.SavingsPeriodFrequencyType;
import org.apache.fineract.portfolio.savings.SavingsTransactionBooleanValues;
@@ -79,6 +80,7 @@ import org.apache.fineract.portfolio.savings.data.FdInterestRateEffectiveData;
import org.apache.fineract.portfolio.savings.data.FdInterestRateSlabData;
import org.apache.fineract.portfolio.savings.service.FdBaseInterestRateReadPlatformService;
import org.apache.fineract.portfolio.savings.service.SavingsAccountDomainService;
import org.apache.fineract.portfolio.tds.service.SavingsInterestTdsService;
import org.apache.fineract.useradministration.domain.AppUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@@ -103,6 +105,7 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
private final FdBaseInterestRateReadPlatformService fdBaseInterestRateReadPlatformService;
private final FromJsonHelper fromApiJsonHelper;
private final JdbcTemplate jdbcTemplate;
private final SavingsInterestTdsService savingsInterestTdsService;
@Transactional
@Override
@@ -277,9 +280,13 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
updateAlreadyPostedTransactions(existingTransactionIds, account);
postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer);
} else {
// Paid out in cash or to a GL, so the interest never reaches savings: TDS is tracked and taken here.
final SavingsInterestTdsService.DirectPayout tds = this.savingsInterestTdsService.deductOnDirectPayout(account, closedDate,
directPayoutKind(onClosureType));
final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(),
paymentDetail, false, isRegularTransaction);
savingsTransactionId = withdrawal.getId();
this.savingsInterestTdsService.recordDirectPayout(tds, withdrawal, existingTransactionIds);
}
account.close(user, command, changes);
@@ -400,10 +407,13 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
account.updateClosedStatus();
account.updateOnAccountClosureStatus(onClosureType);
} else {
final SavingsInterestTdsService.DirectPayout tds = this.savingsInterestTdsService.deductOnDirectPayout(account, closedDate,
directPayoutKind(onClosureType));
final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(),
paymentDetail, false, isRegularTransaction);
savingsTransactionId = withdrawal.getId();
updateAlreadyPostedTransactions(existingTransactionIds, account);
this.savingsInterestTdsService.recordDirectPayout(tds, withdrawal, existingTransactionIds);
}
// if(!processMaturityInstructionOnly)
@@ -438,14 +448,47 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale);
final LocalDate closedDate = command.localDateValueOfParameterNamed(SavingsApiConstants.closedOnDateParamName);
Long savingsTransactionId = null;
// Checked before anything is posted or paid out, so a wrong date is reported as such.
account.validateMaturityClosureDate(closedDate);
account.postMaturityInterest(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, closedDate, postReversals);
// Paid out late: the days between maturity and today earn the product's post-maturity rate, so every closure
// branch below - reinvest, transfer or withdraw - carries it.
account.postOverdueMaturityInterest(closedDate, postReversals);
final BigDecimal transactionAmount = account.getAccountBalance();
final Integer onAccountClosureId = command.integerValueOfParameterNamed(onAccountClosureIdParamName);
final DepositAccountOnClosureType onClosureType = DepositAccountOnClosureType.fromInt(onAccountClosureId);
if (onClosureType.isReinvest()) {
BigDecimal reInvestAmount;
if (onClosureType.isReinvestPrincipal()) {
reInvestAmount = account.getDepositAmount();
// getDepositAmount() is the deposit's contracted total (every installment it was meant to receive),
// not what actually came in. Capped at the balance, or a deposit with missed installments - or none -
// would open its successor with money that was never paid.
reInvestAmount = account.getDepositAmount() == null ? account.getAccountBalance()
: account.getDepositAmount().min(account.getAccountBalance());
// Principal only: the interest part does not go into the new deposit, so it has to be paid
// somewhere real first - the savings account named on the request, else the one chosen when
// the deposit was opened, else its linked savings account. Previously the full balance was
// withdrawn while only the principal was redeposited, so the interest simply vanished.
final BigDecimal interestPart = account.getAccountBalance().subtract(reInvestAmount);
if (interestPart.signum() > 0) {
final Long interestTargetId = resolveRdPayoutSavingsId(account,
command.longValueOfParameterNamed(toSavingsAccountIdParamName));
if (interestTargetId == null) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.reinvest.principal.needs.savings",
"Reinvest Principal Only pays the interest out to a savings account - choose one, or link a Savings account to this deposit.");
}
final SavingsAccount interestTarget = this.depositAccountAssembler.assembleFrom(interestTargetId,
DepositAccountType.SAVINGS_DEPOSIT);
final boolean isExceptionForBalanceCheck = false;
final String description = "RD " + account.getAccountNumber() + " interest to savings "
+ interestTarget.getAccountNumber() + " (maturity, principal reinvested)";
final AccountTransferDTO interestTransfer = new AccountTransferDTO(closedDate, interestPart, PortfolioAccountType.SAVINGS,
PortfolioAccountType.SAVINGS, null, null, description, locale, fmt, null, null, null, null, null,
AccountTransferType.INTEREST_TRANSFER.getValue(), null, null, ExternalId.empty(), null, interestTarget, account,
isRegularTransaction, isExceptionForBalanceCheck);
narrateTransfer(this.accountTransfersWritePlatformService.transferFunds(interestTransfer), description);
updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
}
} else {
reInvestAmount = account.getAccountBalance();
}
@@ -461,31 +504,44 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
frequency = frequency == -1 ? 1 : frequency;
reinvestedDeposit.generateSchedule(frequencyType, frequency, calendar);
reinvestedDeposit.processAccountUponActivation(fmt, postReversals, relaxingDaysConfigForPivotDate);
// The opening credit is on the new deposit but its stored balance was never recomputed, so it read 0
// until something else touched the account.
reinvestedDeposit.updateSavingsAccountSummary(reinvestedDeposit.getTransactions());
reinvestedDeposit.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd,
financialYearBeginningMonth);
this.savingsAccountRepository.save(reinvestedDeposit);
this.savingsAccountRepository.saveAndFlush(reinvestedDeposit);
autoGenerateAccountNumber(reinvestedDeposit);
// The money moves deposit-to-deposit and never touches cash: the new deposit's opening credit and the
// old deposit's withdrawal below both post against transfers-in-suspense, which nets to nil. Before
// this the opening credit posted no journal entry at all and the withdrawal posted as cash paid out,
// leaving the RD control GL short and cash overstated by the whole reinvested amount.
final boolean isInternalTransferLeg = true;
postJournalEntries(reinvestedDeposit, new HashSet<>(), new HashSet<>(), isInternalTransferLeg);
final boolean applyWithdrawFee = false;
final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(),
paymentDetail, false, isRegularTransaction);
paymentDetail, applyWithdrawFee, isRegularTransaction, isInternalTransferLeg);
savingsTransactionId = withdrawal.getId();
// The withdrawal posted journal entries for everything new on the account (the maturity interest
// included), so every transaction now on it is accounted for.
updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
changes.put("reinvestedDepositId", reinvestedDeposit.getId());
} else if (onClosureType.isTransferToSavings()) {
final Long toSavingsId = command.longValueOfParameterNamed(toSavingsAccountIdParamName);
final String transferDescription = command.stringValueOfParameterNamed(transferDescriptionParamName);
final SavingsAccount toSavingsAccount = this.depositAccountAssembler.assembleFrom(toSavingsId,
DepositAccountType.SAVINGS_DEPOSIT);
final boolean isExceptionForBalanceCheck = false;
final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(closedDate, transactionAmount,
PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, transferDescription, locale, fmt, null, null,
null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null,
toSavingsAccount, account, isRegularTransaction, isExceptionForBalanceCheck);
this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO);
transferRdPayoutToSavings(account, toSavingsAccount, closedDate, "maturity", transferDescription, locale, fmt,
isRegularTransaction);
updateAlreadyPostedTransactions(existingTransactionIds, account);
} else {
final SavingsInterestTdsService.DirectPayout tds = this.savingsInterestTdsService.deductOnDirectPayout(account, closedDate,
directPayoutKind(onClosureType));
final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(),
paymentDetail, false, isRegularTransaction);
savingsTransactionId = withdrawal.getId();
this.savingsInterestTdsService.recordDirectPayout(tds, withdrawal, existingTransactionIds);
}
account.close(user, command, changes);
@@ -493,10 +549,28 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
this.savingsAccountRepository.save(account);
postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer);
narrateRdInterestPostings(account);
return savingsTransactionId;
}
/**
* Where a recurring deposit's proceeds may be paid when no account was named for this closure: the savings
* account chosen when it was opened, else its own linked Savings account (Deposit Account Link).
*/
private Long resolveRdPayoutSavingsId(final RecurringDepositAccount account, final Long requestedSavingsId) {
if (requestedSavingsId != null) {
return requestedSavingsId;
}
if (account.getTransferToSavingsAccountId() != null) {
return account.getTransferToSavingsAccountId();
}
if (account.getLinkedAccountId() != null && "SAVINGS".equalsIgnoreCase(account.getLinkedAccountType())) {
return account.getLinkedAccountId();
}
return null;
}
private CalendarInstance getCalendarInstance(final RecurringDepositAccount account, RecurringDepositAccount reinvestedDeposit) {
CalendarInstance calendarInstance = null;
CalendarInstance parentCalendarInstance = this.calendarInstanceRepository.findByEntityIdAndEntityTypeIdAndCalendarTypeId(
@@ -855,6 +929,9 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
updateAlreadyPostedTransactions(existingTransactionIds, account);
} else if (closureType.isTransferToGl()) {
final Long toGlAccountId = command.longValueOfParameterNamed(DepositsApiConstants.toGlAccountIdParamName);
// Taken before the proceeds are read, so the GL receives the payout net of TDS.
final SavingsInterestTdsService.DirectPayout tds = this.savingsInterestTdsService.deductOnDirectPayout(account, closedDate,
"GL");
final BigDecimal proceeds = account.getAccountBalance();
// Declared as an account transfer so the withdrawal's own entry credits the Liability Transfer
// account rather than cash/vault -- nothing is paid over the counter here. The offset below then
@@ -865,15 +942,19 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
isRegularTransaction, isInternalTransfer);
savingsTransactionId = withdrawal.getId();
updateAlreadyPostedTransactions(existingTransactionIds, account);
this.savingsInterestTdsService.recordDirectPayout(tds, withdrawal, existingTransactionIds);
postClosureProceedsToGlAccount(account, toGlAccountId, proceeds, closedDate,
command.stringValueOfParameterNamed(transferDescriptionParamName));
} else {
final SavingsInterestTdsService.DirectPayout tds = this.savingsInterestTdsService.deductOnDirectPayout(account, closedDate,
"CASH");
final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(),
paymentDetail, false, isRegularTransaction);
savingsTransactionId = withdrawal.getId();
// handleWithdrawal() posts this withdrawal's journal entries itself, so mark it as already
// accounted for or the postJournalEntries() call below posts it a second time.
updateAlreadyPostedTransactions(existingTransactionIds, account);
this.savingsInterestTdsService.recordDirectPayout(tds, withdrawal, existingTransactionIds);
}
account.prematureClosure(user, command, changes);
@@ -1134,10 +1215,13 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
}
} else {
final SavingsInterestTdsService.DirectPayout tds = this.savingsInterestTdsService.deductOnDirectPayout(account, closedDate,
directPayoutKind(onClosureType));
final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(),
paymentDetail, false, isRegularTransaction);
savingsTransactionId = withdrawal.getId();
updateAlreadyPostedTransactions(existingTransactionIds, account);
this.savingsInterestTdsService.recordDirectPayout(tds, withdrawal, existingTransactionIds);
if (alreadyMatured) {
account.close(user, command, changes);
@@ -1175,6 +1259,9 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormatter.ofPattern(command.dateFormat()).withLocale(locale);
Long savingsTransactionId = null;
// The reason decides the penalty (and, for a deceased holder, lock-in) before any interest is worked out.
account.applyPrematureClosureReason(
PrematureClosureReasonType.fromInt(command.integerValueOfParameterNamed(prematureClosureReasonIdParamName)));
// post interest
account.postPreMaturityInterest(closedDate, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd,
financialYearBeginningMonth, postReversals);
@@ -1183,29 +1270,51 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
DepositAccountOnClosureType closureType = DepositAccountOnClosureType.fromInt(closureTypeValue);
if (closureType.isTransferToSavings()) {
final boolean isExceptionForBalanceCheck = false;
final Long toSavingsId = command.longValueOfParameterNamed(toSavingsAccountIdParamName);
final String transferDescription = command.stringValueOfParameterNamed(transferDescriptionParamName);
final SavingsAccount toSavingsAccount = this.depositAccountAssembler.assembleFrom(toSavingsId,
DepositAccountType.SAVINGS_DEPOSIT);
final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(closedDate, account.getAccountBalance(),
PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, transferDescription, locale, fmt, null, null,
null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null,
toSavingsAccount, account, isRegularTransaction, isExceptionForBalanceCheck);
this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO);
transferRdPayoutToSavings(account, toSavingsAccount, closedDate, "premature closure", transferDescription, locale, fmt,
isRegularTransaction);
updateAlreadyPostedTransactions(existingTransactionIds, account);
} else {
final SavingsInterestTdsService.DirectPayout tds = this.savingsInterestTdsService.deductOnDirectPayout(account, closedDate,
directPayoutKind(closureType));
final SavingsAccountTransaction withdrawal = this.handleWithdrawal(account, fmt, closedDate, account.getAccountBalance(),
paymentDetail, false, isRegularTransaction);
savingsTransactionId = withdrawal.getId();
this.savingsInterestTdsService.recordDirectPayout(tds, withdrawal, existingTransactionIds);
}
account.prematureClosure(user, command, changes);
this.savingsAccountRepository.save(account);
postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds, isAccountTransfer);
narrateRdInterestPostings(account);
return savingsTransactionId;
}
/**
* Names the journal entries of every interest credit on the recurring deposit that has none yet - the term's
* interest posted at maturity or premature closure, and any post-maturity interest - so the ledger shows whose
* interest it is. Called once the closure's own entries are posted, which is the last of them to be written.
*/
@Override
public void narrateRdInterestPostings(final RecurringDepositAccount account) {
final String narration = "RD " + account.getAccountNumber() + " interest credited";
narrateJournalEntries("""
SELECT id FROM m_savings_account_transaction
WHERE savings_account_id = ? AND transaction_type_enum = ? AND is_reversed = false
""", narration, account.getId(), SavingsAccountTransactionType.INTEREST_POSTING.getValue());
// An interest credit taken back (a premature closure, or a maturity whose final rate came out lower, credits
// the recalculated interest instead): its original entries are already named, so this names only the reversing
// entries.
narrateJournalEntries("""
SELECT id FROM m_savings_account_transaction
WHERE savings_account_id = ? AND transaction_type_enum = ? AND is_reversed = true
""", "RD " + account.getAccountNumber() + " interest reversed - recalculated on closure", account.getId(),
SavingsAccountTransactionType.INTEREST_POSTING.getValue());
}
private void updateExistingTransactionsDetails(SavingsAccount account, Set<Long> existingTransactionIds,
Set<Long> existingReversedTransactionIds) {
existingTransactionIds.addAll(account.findExistingTransactionIds());
@@ -1222,6 +1331,76 @@ public class DepositAccountDomainServiceJpa implements DepositAccountDomainServi
this.journalEntryWritePlatformService.createJournalEntriesForSavings(accountingBridgeData);
}
/**
* Pays a closing recurring deposit into a savings account as two credits - its interest, then the principal -
* each described with the deposit's account number, so the savings statement shows which RD the money came from
* and how much of it is interest.
*
* <p>
* The interest goes first and as an interest transfer: TDS counts as interest only what a payout carries beyond
* the interest already swept out of the deposit, so with the interest swept first the principal transfer after it
* is never mistaken for interest, and the interest is tracked for TDS on its own credit.
*/
private void transferRdPayoutToSavings(final RecurringDepositAccount account, final SavingsAccount toSavingsAccount,
final LocalDate closedDate, final String closureLabel, final String clerkNote, final Locale locale,
final DateTimeFormatter fmt, final boolean isRegularTransaction) {
final boolean isExceptionForBalanceCheck = false;
final String note = clerkNote == null || clerkNote.isBlank() ? "" : " - " + clerkNote.trim();
final String rd = "RD " + account.getAccountNumber();
final BigDecimal interest = account.getInterestInBalance();
final BigDecimal principal = account.getAccountBalance().subtract(interest);
if (interest.signum() > 0) {
final String description = rd + " interest to savings " + toSavingsAccount.getAccountNumber() + " (" + closureLabel + ")" + note;
final Long transferId = this.accountTransfersWritePlatformService.transferFunds(new AccountTransferDTO(closedDate, interest,
PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, description, locale, fmt, null, null, null, null,
null, AccountTransferType.INTEREST_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, account,
isRegularTransaction, isExceptionForBalanceCheck));
narrateTransfer(transferId, description);
}
if (principal.signum() > 0) {
final String description = rd + " principal to savings " + toSavingsAccount.getAccountNumber() + " (" + closureLabel + ")"
+ note;
final Long transferId = this.accountTransfersWritePlatformService.transferFunds(new AccountTransferDTO(closedDate, principal,
PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS, null, null, description, locale, fmt, null, null, null, null,
null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, account,
isRegularTransaction, isExceptionForBalanceCheck));
narrateTransfer(transferId, description);
}
}
/**
* Writes a narration onto the journal entries of both sides of a transfer. The entries are posted while the
* transfer is still being made, before its own record - and so its description - exists, so they are named here
* once it does.
*/
private void narrateTransfer(final Long transferDetailsId, final String narration) {
if (transferDetailsId == null) {
return;
}
narrateJournalEntries("""
SELECT from_savings_transaction_id FROM m_account_transfer_transaction WHERE account_transfer_details_id = ?
UNION SELECT to_savings_transaction_id FROM m_account_transfer_transaction WHERE account_transfer_details_id = ?
""", narration, transferDetailsId, transferDetailsId);
}
/** Sets the narration of the not-yet-narrated journal entries of the savings transactions the query returns. */
private void narrateJournalEntries(final String transactionIdsSql, final String narration, final Object... args) {
final List<Long> transactionIds = this.jdbcTemplate.queryForList(transactionIdsSql, Long.class, args);
for (final Long transactionId : transactionIds) {
if (transactionId != null) {
this.jdbcTemplate.update(
"UPDATE acc_gl_journal_entry SET description = ? WHERE savings_transaction_id = ? AND (description IS NULL OR description = '')",
narration, transactionId);
}
}
}
/** How a closure that does not go to savings paid out, for the TDS tracking record. */
private static String directPayoutKind(final DepositAccountOnClosureType closureType) {
return closureType != null && closureType.isTransferToGl() ? "GL" : "CASH";
}
private void updateAlreadyPostedTransactions(final Set<Long> existingTransactionIds, final SavingsAccount savingsAccount) {
// accountTransfersWritePlatformService.transferFunds() already posts accounting for the
// withdrawal it creates on this account (via SavingsAccountDomainServiceJpa#handleWithdrawal),
@@ -0,0 +1,43 @@
/**
* 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.handler;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.commands.annotation.CommandType;
import org.apache.fineract.commands.handler.NewCommandSourceHandler;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.portfolio.savings.service.DepositAccountWritePlatformService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** Tenure Flexibility: lengthens a running recurring deposit's term. */
@Service
@RequiredArgsConstructor
@CommandType(entity = "RECURRINGDEPOSITACCOUNT", action = "EXTENDTENURE")
public class ExtendTenureRecurringDepositAccountCommandHandler implements NewCommandSourceHandler {
private final DepositAccountWritePlatformService depositAccountWritePlatformService;
@Transactional
@Override
public CommandProcessingResult processCommand(final JsonCommand command) {
return this.depositAccountWritePlatformService.extendRecurringDepositTenure(command.entityId(), command);
}
}
@@ -0,0 +1,62 @@
/**
* 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.jobs.applyrdmissedinstallmentpenalty;
import org.apache.fineract.infrastructure.jobs.service.JobName;
import org.apache.fineract.portfolio.savings.service.RecurringDepositMissedInstallmentPenaltyService;
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.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
/**
* Runs the RD missed-installment penalty. The service decides what is due and isolates each installment, so the step
* is a thin trigger and the rules live in one place.
*/
@Configuration
public class ApplyRdMissedInstallmentPenaltyJobConfig {
@Autowired
private JobRepository jobRepository;
@Autowired
private PlatformTransactionManager transactionManager;
@Autowired
private RecurringDepositMissedInstallmentPenaltyService recurringDepositMissedInstallmentPenaltyService;
@Bean
protected Step applyRdMissedInstallmentPenaltyStep() {
return new StepBuilder(JobName.APPLY_RD_MISSED_INSTALLMENT_PENALTY.name(), jobRepository).tasklet((contribution, chunkContext) -> {
recurringDepositMissedInstallmentPenaltyService.applyPenalties();
return RepeatStatus.FINISHED;
}, transactionManager).build();
}
@Bean
public Job applyRdMissedInstallmentPenaltyJob() {
return new JobBuilder(JobName.APPLY_RD_MISSED_INSTALLMENT_PENALTY.name(), jobRepository).start(applyRdMissedInstallmentPenaltyStep())
.incrementer(new RunIdIncrementer()).build();
}
}
@@ -0,0 +1,60 @@
/**
* 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.jobs.executerdautodebit;
import org.apache.fineract.infrastructure.jobs.service.JobName;
import org.apache.fineract.portfolio.savings.service.RecurringDepositAutoDebitService;
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 ExecuteRdAutoDebitJobConfig {
@Autowired
private JobRepository jobRepository;
@Autowired
private PlatformTransactionManager transactionManager;
@Autowired
private RecurringDepositAutoDebitService recurringDepositAutoDebitService;
@Bean
public ExecuteRdAutoDebitTasklet executeRdAutoDebitTasklet() {
return new ExecuteRdAutoDebitTasklet(recurringDepositAutoDebitService);
}
@Bean
protected Step executeRdAutoDebitStep() {
return new StepBuilder(JobName.EXECUTE_RD_AUTO_DEBIT.name(), jobRepository).tasklet(executeRdAutoDebitTasklet(), transactionManager)
.build();
}
@Bean
public Job executeRdAutoDebitJob() {
return new JobBuilder(JobName.EXECUTE_RD_AUTO_DEBIT.name(), jobRepository).start(executeRdAutoDebitStep())
.incrementer(new RunIdIncrementer()).build();
}
}
@@ -0,0 +1,42 @@
/**
* 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.jobs.executerdautodebit;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.portfolio.savings.service.RecurringDepositAutoDebitService;
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;
/**
* Runs RD Auto Debit. The service decides what is due and isolates each installment, so the tasklet stays a thin
* trigger and the rules live in one place.
*/
@RequiredArgsConstructor
public class ExecuteRdAutoDebitTasklet implements Tasklet {
private final RecurringDepositAutoDebitService service;
@Override
public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext) {
service.collectDueInstallments();
return RepeatStatus.FINISHED;
}
}
@@ -61,6 +61,16 @@ public class UpdateDepositsAccountMaturityDetailsTasklet implements Tasklet {
}
}
// Recurring deposits still running: credit any posting period (monthly, quarterly... per product) that ended
// before today. The query above only returns deposits that have reached maturity.
for (final Long rdId : depositAccountReadPlatformService.retrieveRunningRecurringDepositIds()) {
try {
depositAccountWritePlatformService.postRecurringDepositPeriodicInterest(rdId);
} catch (final Exception ex) {
log.error("Periodic interest posting failed for recurring deposit id {}", rdId, ex);
}
}
log.debug("{}: Records affected by updateMaturityDetailsOfDepositAccounts: {}", ThreadLocalContextUtil.getTenant().getName(),
depositAccounts.size());
return RepeatStatus.FINISHED;
@@ -250,11 +250,7 @@ public class CurrentAccountEditWritePlatformServiceJpaRepositoryImpl implements
.findByCurrentAccountIdAndStatus(currentAccountId, CurrentAccountPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new CurrentAccountNoPendingEditException(currentAccountId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see ShareAccountEditWritePlatformServiceJpaRepositoryImpl and
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement elsewhere.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new CurrentAccountEditSelfApprovalNotAllowedException(currentAccountId);
}
@@ -310,11 +306,7 @@ public class CurrentAccountEditWritePlatformServiceJpaRepositoryImpl implements
.findByCurrentAccountIdAndStatus(currentAccountId, CurrentAccountPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new CurrentAccountNoPendingEditException(currentAccountId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see ShareAccountEditWritePlatformServiceJpaRepositoryImpl and
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement elsewhere.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new CurrentAccountEditSelfApprovalNotAllowedException(currentAccountId);
}
@@ -46,6 +46,7 @@ import org.apache.fineract.portfolio.savings.domain.FixedDepositAccount;
import org.apache.fineract.portfolio.savings.domain.RecurringDepositAccount;
import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
@RequiredArgsConstructor
public class DepositAccountPreMatureCalculationPlatformServiceImpl implements DepositAccountPreMatureCalculationPlatformService {
@@ -117,12 +118,19 @@ public class DepositAccountPreMatureCalculationPlatformServiceImpl implements De
paymentTypeOptions, savingsAccountDatas, fd.getNominalAnnualInterestRate());
} else if (depositAccountType.isRecurringDeposit()) {
final RecurringDepositAccount rd = (RecurringDepositAccount) account;
// Same reason rules the real closure applies, so the preview pays exactly what the closure will.
rd.applyPrematureClosureReason(prematureClosureReason);
accountData = RecurringDepositAccountData.preClosureDetails(
account.getId(), rd.calculatePreMatureAmount(interestCalculatedToDate, isPreMatureClosure,
isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth),
onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas);
}
// A preview, not a closure: working the payout out resets the account's own interest rate to the premature
// rate and refreshes its interest-earned summary on the managed entity, and committing that left an RD that
// was only previewed showing the penalty rate (4.5% instead of 6.5%) as if it had been broken. Nothing the
// calculation touched may be saved.
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return accountData;
}
}
@@ -61,6 +61,9 @@ public interface DepositAccountReadPlatformService {
Collection<DepositAccountData> retrieveForMaturityUpdate();
/** Active recurring deposits that have not reached maturity yet - their posting periods are credited nightly. */
Collection<Long> retrieveRunningRecurringDepositIds();
SavingsAccountTransactionData retrieveRecurringAccountDepositTransactionTemplate(Long accountId);
Collection<AccountTransferDTO> retrieveDataForInterestTransfer();
@@ -283,6 +283,18 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
return this.jdbcTemplate.query(sqlBuilder.toString(), DEPOSIT_ACCOUNT_LOOKUP_MAPPER, depositAccountType.getValue());
}
@Override
public Collection<Long> retrieveRunningRecurringDepositIds() {
return this.jdbcTemplate.queryForList("""
SELECT da.id FROM m_savings_account da
JOIN m_deposit_account_term_and_preclosure dat ON dat.savings_account_id = da.id
WHERE da.deposit_type_enum = ? AND da.status_enum = ?
AND (dat.maturity_date IS NULL OR dat.maturity_date > ?)
ORDER BY da.id
""", Long.class, DepositAccountType.RECURRING_DEPOSIT.getValue(), SavingsAccountStatusType.ACTIVE.getValue(),
DateUtils.getBusinessLocalDate());
}
@Override
public Collection<DepositAccountData> retrieveForMaturityUpdate() {
@@ -2057,6 +2069,8 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
sqlBuilder.append("dptp.max_deposit_term_type_enum as maxDepositTermTypeId, ");
sqlBuilder.append("dptp.in_multiples_of_deposit_term as inMultiplesOfDepositTerm, ");
sqlBuilder.append("dptp.in_multiples_of_deposit_term_type_enum as inMultiplesOfDepositTermTypeId, ");
// Lien Marked's loan limit, so the opening screen can default to it and refuse anything above it.
sqlBuilder.append("sa.lien_percentage as lienPercentage, ");
sqlBuilder.append("sa.account_type as accountType, sa.customer_segment as customerSegment, ");
sqlBuilder.append("sa.product_code as productCode, ");
sqlBuilder.append("sa.effective_date as effectiveDate, sa.effective_to as effectiveTo, sa.end_date as endDate, ");
@@ -2183,6 +2197,7 @@ public class DepositAccountReadPlatformServiceImpl implements DepositAccountRead
rs.getBoolean("deceasedSettlement"),
rs.getBoolean("allowDebitTxnAfterDueDate")
);
result.setLienPercentage(rs.getBigDecimal("lienPercentage"));
return result;
}
@@ -24,6 +24,7 @@ import static org.apache.fineract.portfolio.savings.SavingsApiConstants.amountPa
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.chargeIdParamName;
import static org.apache.fineract.portfolio.savings.SavingsApiConstants.dueAsOfDateParamName;
import com.google.gson.JsonObject;
import java.math.BigDecimal;
import java.math.MathContext;
import java.time.LocalDate;
@@ -44,6 +45,7 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.fineract.accounting.journalentry.service.JournalEntryWritePlatformService;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
import org.apache.fineract.infrastructure.core.data.ApiParameterError;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder;
@@ -147,6 +149,8 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
private final DepositAccountOnHoldTransactionRepository depositAccountOnHoldTransactionRepository;
private final DenominationBreakdownWriter denominationBreakdownWriter;
private final JdbcTemplate jdbcTemplate;
private final RecurringDepositLienService recurringDepositLienService;
private final RecurringDepositProductRules recurringDepositProductRules;
@Transactional
@Override
@@ -639,7 +643,12 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
final SavingsAccount account = this.depositAccountAssembler.assembleFrom(savingsId, depositAccountType);
checkClientOrGroupActive(account);
postInterest(account);
if (account instanceof RecurringDepositAccount rdAccount) {
// A recurring deposit is credited by its posting periods only - the same credits the nightly job makes.
postRecurringDepositPeriodicInterest(rdAccount);
} else {
postInterest(account);
}
return new CommandProcessingResultBuilder() //
.withEntityId(savingsId) //
.withOfficeId(account.officeId()) //
@@ -650,6 +659,28 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
}
@Transactional
@Override
public void postRecurringDepositPeriodicInterest(final Long recurringDepositId) {
final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler.assembleFrom(recurringDepositId,
DepositAccountType.RECURRING_DEPOSIT);
postRecurringDepositPeriodicInterest(account);
}
/**
* Credits a recurring deposit's completed posting periods (monthly, quarterly... per its product) with their own
* journal entries, named after the deposit.
*/
private void postRecurringDepositPeriodicInterest(final RecurringDepositAccount rdAccount) {
final Set<Long> existingTransactionIds = new HashSet<>();
final Set<Long> existingReversedTransactionIds = new HashSet<>();
updateExistingTransactionsDetails(rdAccount, existingTransactionIds, existingReversedTransactionIds);
rdAccount.postPeriodicInterest(this.configurationDomainService.isSavingsInterestPostingAtCurrentPeriodEnd(),
this.configurationDomainService.retrieveFinancialYearBeginningMonth(), false);
this.savingAccountRepositoryWrapper.saveAndFlush(rdAccount);
postJournalEntries(rdAccount, existingTransactionIds, existingReversedTransactionIds);
this.depositAccountDomainService.narrateRdInterestPostings(rdAccount);
}
private void postInterest(final SavingsAccount account) {
final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
@@ -931,6 +962,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler.assembleFrom(savingsId,
DepositAccountType.RECURRING_DEPOSIT);
checkClientOrGroupActive(account);
this.recurringDepositLienService.assertNoActiveLien(savingsId, "closed");
this.depositAccountDomainService.handleRDAccountClosure(account, paymentDetail, user, command, changes);
@@ -1047,6 +1079,43 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
}
@Transactional
@Override
public CommandProcessingResult extendRecurringDepositTenure(final Long savingsId, final JsonCommand command) {
this.context.authenticatedUser();
final Integer newDepositPeriod = command.integerValueOfParameterNamed(DepositsApiConstants.depositPeriodParamName);
final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler.assembleFrom(savingsId,
DepositAccountType.RECURRING_DEPOSIT);
checkClientOrGroupActive(account);
// The added installments follow the deposit's own collection calendar (monthly unless it was opened otherwise).
PeriodFrequencyType frequencyType = PeriodFrequencyType.MONTHS;
Integer frequency = 1;
final CalendarInstance calendarInstance = this.calendarInstanceRepository.findByEntityIdAndEntityTypeIdAndCalendarTypeId(savingsId,
CalendarEntityType.SAVINGS.getValue(), CalendarType.COLLECTION.getValue());
if (calendarInstance != null && calendarInstance.getCalendar() != null) {
final String recurrence = calendarInstance.getCalendar().getRecurrence();
frequencyType = CalendarFrequencyType.from(CalendarUtils.getFrequency(recurrence));
frequency = CalendarUtils.getInterval(recurrence);
frequency = frequency == -1 ? 1 : frequency;
}
final Map<String, Object> changes = account.extendTenure(newDepositPeriod, frequencyType, frequency,
this.configurationDomainService.isSavingsInterestPostingAtCurrentPeriodEnd(),
this.configurationDomainService.retrieveFinancialYearBeginningMonth());
this.recurringDepositProductRules.validateMaturityWithinProductEndDate(account);
this.savingAccountRepositoryWrapper.saveAndFlush(account);
return new CommandProcessingResultBuilder() //
.withEntityId(savingsId) //
.withOfficeId(account.officeId()) //
.withClientId(account.clientId()) //
.withGroupId(account.groupId()) //
.withSavingsId(savingsId) //
.with(changes) //
.build();
}
@Override
public CommandProcessingResult prematureCloseRDAccount(final Long savingsId, final JsonCommand command) {
final AppUser user = this.context.authenticatedUser();
@@ -1059,6 +1128,7 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler.assembleFrom(savingsId,
DepositAccountType.RECURRING_DEPOSIT);
checkClientOrGroupActive(account);
this.recurringDepositLienService.assertNoActiveLien(savingsId, "closed prematurely");
if (account.maturityDate() == null) {
final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
@@ -1589,11 +1659,76 @@ public class DepositAccountWritePlatformServiceJpaRepositoryImpl implements Depo
}
}
} else if (depositAccountType.isRecurringDeposit()) {
((RecurringDepositAccount) account).updateMaturityStatus(isSavingsInterestPostingAtCurrentPeriodEnd,
financialYearBeginningMonth, postReversals);
final RecurringDepositAccount rdAccount = (RecurringDepositAccount) account;
// Every night: credit any posting period (the product's Interest Posting Period) that ended before today.
rdAccount.postPeriodicInterest(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postReversals);
rdAccount.updateMaturityStatus(isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth, postReversals);
final JsonCommand maturityClosure = rdMaturityInstructionCommand(rdAccount);
if (maturityClosure != null) {
// Same order as the FD branch above: give the maturity interest its own journal entry first and
// mark it posted, so neither the closure's withdrawal nor the final call below posts it again.
this.savingAccountRepositoryWrapper.saveAndFlush(account);
postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);
updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
this.depositAccountDomainService.handleRDAccountClosure(rdAccount, null, this.context.authenticatedUser(),
maturityClosure, new HashMap<>());
// The closure posted its own entries for everything it created.
updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
}
}
this.savingAccountRepositoryWrapper.saveAndFlush(account);
postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);
if (account instanceof RecurringDepositAccount rdAccount) {
// The term's interest credited on the maturity date, named in the ledger as soon as it is posted.
this.depositAccountDomainService.narrateRdInterestPostings(rdAccount);
}
}
/**
* The close command that carries out a recurring deposit's maturity instruction tonight, or null when it must
* wait for staff instead. It runs only when the product has Maturity Instructions on, the deposit has just
* matured, it was opened with Transfer to Savings or a Reinvest option, nothing holds a lien on it, and - for a
* transfer - there is a savings account to pay into (the one chosen at opening, else the linked Savings account).
* Anything else stays Matured, earning the post-maturity rate until someone closes it.
*/
private JsonCommand rdMaturityInstructionCommand(final RecurringDepositAccount rdAccount) {
if (!rdAccount.isMatured() || rdAccount.savingsProduct() == null || !rdAccount.savingsProduct().isMaturityInstructions()) {
return null;
}
final DepositAccountOnClosureType instruction = DepositAccountOnClosureType.fromInt(rdAccount.getOnAccountClosureId());
if (!(instruction.isTransferToSavings() || instruction.isReinvest()) || instruction.isPartialReinvest()) {
return null;
}
if (rdAccount.getAccountBalance() == null || rdAccount.getAccountBalance().signum() <= 0) {
// Nothing was ever paid in: there is nothing to transfer or reinvest, so a person has to look at it.
log.info("RD {} matured with no balance; maturity instruction left for staff", rdAccount.getAccountNumber());
return null;
}
if (!this.recurringDepositLienService.activeLiens(rdAccount.getId()).isEmpty()) {
log.info("RD {} matured with a lien on it; maturity instruction left for staff", rdAccount.getAccountNumber());
return null;
}
Long payoutSavingsId = rdAccount.getTransferToSavingsAccountId();
if (payoutSavingsId == null && rdAccount.getLinkedAccountId() != null
&& "SAVINGS".equalsIgnoreCase(rdAccount.getLinkedAccountType())) {
payoutSavingsId = rdAccount.getLinkedAccountId();
}
// Transfer always needs a destination; Reinvest Principal Only needs one for the interest part.
if (payoutSavingsId == null && (instruction.isTransferToSavings() || instruction.isReinvestPrincipal())) {
log.warn("RD {} matured with instruction {} but no savings account to pay into; left for staff", rdAccount.getAccountNumber(),
instruction.getCode());
return null;
}
final JsonObject closure = new JsonObject();
closure.addProperty(SavingsApiConstants.closedOnDateParamName, rdAccount.maturityDate().toString());
closure.addProperty(SavingsApiConstants.dateFormatParamName, "yyyy-MM-dd");
closure.addProperty(SavingsApiConstants.localeParamName, "en");
closure.addProperty(DepositsApiConstants.onAccountClosureIdParamName, instruction.getValue());
if (payoutSavingsId != null) {
closure.addProperty(DepositsApiConstants.toSavingsAccountIdParamName, payoutSavingsId);
}
closure.addProperty(DepositsApiConstants.transferDescriptionParamName, "Apply maturity instructions");
return JsonCommand.fromJsonElement(rdAccount.getId(), closure, new FromJsonHelper());
}
@Transactional
@@ -127,6 +127,7 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl
private final BusinessEventNotifierService businessEventNotifierService;
private final SavingsAccountAssembler savingsAccountAssembler;
private final ClientNomineeWritePlatformService clientNomineeWritePlatformService;
private final RecurringDepositProductRules recurringDepositProductRules;
/*
* Guaranteed to throw an exception no matter what the data integrity issue is.
@@ -302,9 +303,12 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl
frequency = frequency == -1 ? 1 : frequency;
account.generateSchedule(frequencyType, frequency, calendar);
final boolean isPreMatureClosure = false;
// The simple/compounding flag must be on the account before its maturity is projected.
this.recurringDepositProductRules.applyInterestCalculationType(account);
account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd,
financialYearBeginningMonth);
account.validateApplicableInterestRate();
this.recurringDepositProductRules.validateOnSubmit(account, command);
savingAccountRepository.save(account);
// Save nominees if provided in payload (same transaction)
@@ -551,12 +555,15 @@ public class DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl impl
frequency = frequency == -1 ? 1 : frequency;
account.generateSchedule(frequencyType, frequency, calendar);
final boolean isPreMatureClosure = false;
// An application is not yet a contract, so an edit (possibly to a different product) re-reads it.
this.recurringDepositProductRules.applyInterestCalculationType(account);
account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd,
financialYearBeginningMonth);
account.validateApplicableInterestRate();
this.savingAccountRepository.save(account);
}
this.recurringDepositProductRules.validateOnModify(account, command);
// update calendar details
if (!account.isCalendarInherited()) {
@@ -499,6 +499,10 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead
sqlBuilder.append("sp.balance_frequency as balanceFrequency, ");
sqlBuilder.append("sp.account_closed_zero_balance_in_day_closing as accountClosedZeroBalanceInDayClosing, ");
sqlBuilder.append("sp.balance_swap_option as balanceSwapOption, sp.msme as msme, ");
sqlBuilder.append("sp.lien_percentage as lienPercentage, ");
sqlBuilder.append("sp.missed_installment_grace_days as missedInstallmentGraceDays, ");
sqlBuilder.append("sp.missed_installment_penalty_type as missedInstallmentPenaltyType, ");
sqlBuilder.append("sp.missed_installment_penalty_amount as missedInstallmentPenaltyAmount, ");
sqlBuilder.append("sp.auto_debit_facility as autoDebitFacility, sp.loan_facility as loanFacility, ");
sqlBuilder.append("sp.premature_withdrawal_option as prematureWithdrawalOption, sp.tenure_flexibility as tenureFlexibility, ");
sqlBuilder.append("sp.lien_marked as lienMarked, sp.maturity_instructions as maturityInstructions, ");
@@ -623,6 +627,10 @@ public class DepositProductReadPlatformServiceImpl implements DepositProductRead
result.setPrematureWithdrawalOption(prematureWithdrawalOption);
result.setTenureFlexibility(tenureFlexibility);
result.setLienMarked(lienMarked);
result.setLienPercentage(rs.getBigDecimal("lienPercentage"));
result.setMissedInstallmentGraceDays(JdbcSupport.getInteger(rs, "missedInstallmentGraceDays"));
result.setMissedInstallmentPenaltyType(JdbcSupport.getInteger(rs, "missedInstallmentPenaltyType"));
result.setMissedInstallmentPenaltyAmount(rs.getBigDecimal("missedInstallmentPenaltyAmount"));
result.setMaturityInstructions(maturityInstructions);
result.setCreditMaturityProceeds(creditMaturityProceeds);
result.setPenaltyGracePeriodMissedInstallments(penaltyGracePeriodMissedInstallments);
@@ -260,11 +260,7 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_FD, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsProductSelfApprovalNotAllowedException(productId);
}
@@ -354,11 +350,7 @@ public class FixedDepositProductWritePlatformServiceJpaRepositoryImpl implements
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_FD, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsProductSelfApprovalNotAllowedException(productId);
}
@@ -29,19 +29,47 @@ import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
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.api.JsonQuery;
import org.apache.fineract.infrastructure.core.domain.LocalDateInterval;
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
import org.apache.fineract.organisation.monetary.domain.MoneyHelper;
import org.springframework.stereotype.Service;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.organisation.monetary.domain.MonetaryCurrency;
import org.apache.fineract.organisation.monetary.domain.Money;
import org.apache.fineract.organisation.monetary.domain.MoneyHelper;
import org.apache.fineract.portfolio.savings.SavingsCompoundingInterestPeriodType;
import org.apache.fineract.portfolio.savings.SavingsInterestCalculationDaysInYearType;
import org.apache.fineract.portfolio.savings.SavingsInterestCalculationType;
import org.apache.fineract.portfolio.savings.SavingsPostingInterestPeriodType;
import org.apache.fineract.portfolio.savings.domain.SavingsHelper;
import org.apache.fineract.portfolio.savings.domain.interest.PostingPeriod;
import org.apache.fineract.portfolio.savings.domain.interest.SavingsAccountTransactionDetailsForPostingPeriod;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class RecurringDepositAccountInterestCalculationServiceImpl implements RecurringDepositAccountInterestCalculationService {
private static final String PRODUCT_ID_PARAM = "productId";
private final FromJsonHelper fromApiJsonHelper;
private final JdbcTemplate jdbcTemplate;
private final SavingsHelper savingsHelper;
private final ConfigurationDomainService configurationDomainService;
private final RecurringDepositProductRules recurringDepositProductRules;
/** The interest settings of an RD product, as an account opened under it will be calculated with. */
private record ProductInterestTerms(SavingsCompoundingInterestPeriodType compounding, SavingsPostingInterestPeriodType posting,
SavingsInterestCalculationType calculationType, SavingsInterestCalculationDaysInYearType daysInYear, boolean simpleInterest,
BigDecimal minBalanceForInterest, MonetaryCurrency currency) {}
@Override
public HashMap<String, Object> calculateInterest(JsonQuery query) {
@@ -53,27 +81,120 @@ public class RecurringDepositAccountInterestCalculationServiceImpl implements Re
element);
LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed("submittedOnDate", element);
if (submittedOnDate == null) {
submittedOnDate = LocalDate.now(DateUtils.getDateTimeZoneOfTenant());
submittedOnDate = DateUtils.getBusinessLocalDate();
}
final Long productId = this.fromApiJsonHelper.extractLongNamed(PRODUCT_ID_PARAM, element);
final ProductInterestTerms terms = productId == null ? null : productInterestTerms(productId);
BigDecimal maturityAmount = this.calculateInterestInternal(depositAmount, annualInterestRate, tenureInMonths,
interestCompoundingPeriodInMonths, submittedOnDate);
final HashMap<String, Object> result = new HashMap<>();
BigDecimal totalPrincipal = depositAmount.multiply(BigDecimal.valueOf(tenureInMonths));
BigDecimal maturityAmount;
if (terms != null) {
// The product's own settings, through the same engine an opened account is calculated with - so the figure
// shown before opening is the maturity amount the account will carry.
final List<Map<String, Object>> postings = new ArrayList<>();
final BigDecimal totalInterest = projectInterest(terms, depositAmount, annualInterestRate, tenureInMonths.intValue(),
submittedOnDate, postings);
maturityAmount = totalPrincipal.add(totalInterest);
result.put("interestCalculation", terms.simpleInterest() ? "Simple" : "Compounding");
result.put("compoundingPeriod", terms.compounding().name());
result.put("postingPeriod", terms.posting().name());
result.put("postingSchedule", postings);
result.put("daysInYear", terms.daysInYear().getValue());
} else {
maturityAmount = this.calculateInterestInternal(depositAmount, annualInterestRate, tenureInMonths,
interestCompoundingPeriodInMonths, submittedOnDate);
result.put("daysInYear", 365);
}
BigDecimal totalInterest = maturityAmount.subtract(totalPrincipal);
String warning = "This is an approximate calculated amount - it may vary slightly when the account is created";
String warning = terms != null ? "Calculated with the product's interest settings, assuming every installment is paid on its due date"
: "This is an approximate calculated amount - it may vary slightly when the account is created";
HashMap<String, Object> result = new HashMap<>();
result.put("maturityAmount", maturityAmount);
result.put("totalPrincipal", totalPrincipal);
result.put("totalInterest", totalInterest);
result.put("daysInYear", 365); // Standard for this product as per image
result.put("warning", warning);
return result;
}
private ProductInterestTerms productInterestTerms(final Long productId) {
try {
return this.jdbcTemplate.queryForObject("""
SELECT interest_compounding_period_enum, interest_posting_period_enum, interest_calculation_type_enum,
interest_calculation_days_in_year_type_enum, interest_calculate_selector,
min_balance_for_interest_calculation, currency_code, currency_digits, currency_multiplesof
FROM m_savings_product WHERE id = ? AND deposit_type_enum = 300
""", (rs, rowNum) -> {
final Integer selector = (Integer) rs.getObject("interest_calculate_selector");
final Integer multiplesOf = (Integer) rs.getObject("currency_multiplesof");
return new ProductInterestTerms(SavingsCompoundingInterestPeriodType.fromInt(rs.getInt("interest_compounding_period_enum")),
SavingsPostingInterestPeriodType.fromInt(rs.getInt("interest_posting_period_enum")),
SavingsInterestCalculationType.fromInt(rs.getInt("interest_calculation_type_enum")),
SavingsInterestCalculationDaysInYearType.fromInt(rs.getInt("interest_calculation_days_in_year_type_enum")),
this.recurringDepositProductRules.isSimpleInterestOption(selector), rs.getBigDecimal("min_balance_for_interest_calculation"),
new MonetaryCurrency(rs.getString("currency_code"), rs.getInt("currency_digits"), multiplesOf));
}, productId);
} catch (final EmptyResultDataAccessException e) {
return null;
}
}
/**
* Interest on a deposit of {@code installment} every month from {@code startDate} for {@code months} months, worked
* out by the account engine itself (posting periods, compounding periods, daily balances, days in year, simple or
* compounding) up to the day before maturity - the same calculation that gives an opened account its maturity
* amount. Each posting period's credit is added to {@code postings}.
*/
private BigDecimal projectInterest(final ProductInterestTerms terms, final BigDecimal installment, final BigDecimal annualRate,
final int months, final LocalDate startDate, final List<Map<String, Object>> postings) {
final LocalDate termEnd = startDate.plusMonths(months).minusDays(1);
final MonetaryCurrency currency = terms.currency();
final List<SavingsAccountTransactionDetailsForPostingPeriod> deposits = new ArrayList<>();
for (int k = 0; k < months; k++) {
final LocalDate dueDate = startDate.plusMonths(k);
final LocalDate balanceEnd = k == months - 1 ? termEnd : startDate.plusMonths(k + 1L).minusDays(1);
final BigDecimal runningBalance = installment.multiply(BigDecimal.valueOf(k + 1L));
final int days = LocalDateInterval.create(dueDate, balanceEnd).daysInPeriodInclusiveOfEndDate();
deposits.add(new SavingsAccountTransactionDetailsForPostingPeriod(null, dueDate, balanceEnd, runningBalance, installment, currency,
days, true, false, false, false, false));
}
final Integer financialYearBeginningMonth = this.configurationDomainService.retrieveFinancialYearBeginningMonth();
final boolean postingAtPeriodEnd = this.configurationDomainService.isSavingsInterestPostingAtCurrentPeriodEnd();
final List<LocalDateInterval> intervals = this.savingsHelper.determineInterestPostingPeriods(startDate, termEnd, terms.posting(),
financialYearBeginningMonth, new ArrayList<>());
final BigDecimal rateAsFraction = annualRate.divide(BigDecimal.valueOf(100L), MathContext.DECIMAL64);
final Money minBalance = Money.of(currency, terms.minBalanceForInterest() == null ? BigDecimal.ZERO : terms.minBalanceForInterest());
final List<PostingPeriod> periods = new ArrayList<>();
Money periodStartingBalance = Money.zero(currency);
for (final LocalDateInterval interval : intervals) {
final PostingPeriod period = PostingPeriod.createFrom(interval, periodStartingBalance, deposits, currency, terms.compounding(),
terms.calculationType(), rateAsFraction, terms.daysInYear().getValue(), termEnd, new ArrayList<>(), false, minBalance,
postingAtPeriodEnd, false, financialYearBeginningMonth);
periodStartingBalance = period.closingBalance();
periods.add(period);
}
this.savingsHelper.calculateInterestForAllPostingPeriods(currency, periods, null, false, terms.simpleInterest());
BigDecimal total = BigDecimal.ZERO;
for (final PostingPeriod period : periods) {
final BigDecimal interest = period.getInterestEarned().getAmount();
total = total.add(interest);
final Map<String, Object> posting = new LinkedHashMap<>();
// The last period is credited on the maturity date itself.
final LocalDate periodEnd = period.getPeriodInterval().endDate();
final LocalDate postedOn = periodEnd.isBefore(termEnd) ? periodEnd : termEnd.plusDays(1);
posting.put("date", postedOn.toString());
posting.put("interest", interest);
postings.add(posting);
}
return total;
}
public BigDecimal calculateInterestInternal(BigDecimal installmentAmount, BigDecimal annualInterestRate, Long tenureInMonths,
Long interestCompoundingPeriodInMonths, LocalDate submittedOnDate) {
MathContext mc = MoneyHelper.getMathContext();
@@ -89,39 +210,31 @@ public class RecurringDepositAccountInterestCalculationServiceImpl implements Re
for (int m = 1; m <= totalMonths; m++) {
// Add monthly installment at the start of the month
currentBalance = currentBalance.add(installmentAmount);
// Get actual days in the current month
int daysInMonth = date.lengthOfMonth();
// Calculate interest for the month using daily compounding
double multiplier = Math.pow(1.0 + dailyRate, daysInMonth);
currentBalance = currentBalance.multiply(BigDecimal.valueOf(multiplier), mc);
// Move to next month
date = date.plusMonths(1);
}
maturityAmount = currentBalance;
} else {
// Periodic Compounding (Monthly, Quarterly, etc.)
BigDecimal monthlyRate = annualInterestRate.divide(BigDecimal.valueOf(1200), mc);
BigDecimal i = monthlyRate;
int n = totalMonths;
// Standard RD formula for monthly compounding:
// M = P * ((1+i)^n - 1) / i * (1+i)
// For other periods, we can approximate or use a loop.
// Using loop for consistency with various compounding periods.
BigDecimal compoundingFrequencyMonths = BigDecimal.valueOf(interestCompoundingPeriodInMonths);
BigDecimal ratePerCompounding = annualInterestRate.divide(BigDecimal.valueOf(100), mc)
.multiply(compoundingFrequencyMonths).divide(BigDecimal.valueOf(12), mc);
BigDecimal ratePerCompounding = annualInterestRate.divide(BigDecimal.valueOf(100), mc).multiply(compoundingFrequencyMonths)
.divide(BigDecimal.valueOf(12), mc);
for (int m = 1; m <= totalMonths; m++) {
BigDecimal monthsRemaining = BigDecimal.valueOf(totalMonths - m + 1);
BigDecimal numberOfCompoundings = monthsRemaining.divide(compoundingFrequencyMonths, mc);
BigDecimal installmentMaturity = installmentAmount.multiply(
BigDecimal.ONE.add(ratePerCompounding).pow(numberOfCompoundings.intValue(), mc), mc);
BigDecimal installmentMaturity = installmentAmount
.multiply(BigDecimal.ONE.add(ratePerCompounding).pow(numberOfCompoundings.intValue(), mc), mc);
// Add remaining partial compounding period interest (simple interest for the rest)
BigDecimal remainingMonths = monthsRemaining.remainder(compoundingFrequencyMonths);
if (remainingMonths.compareTo(BigDecimal.ZERO) > 0) {
@@ -129,11 +242,11 @@ public class RecurringDepositAccountInterestCalculationServiceImpl implements Re
.divide(BigDecimal.valueOf(1200), mc);
installmentMaturity = installmentMaturity.add(partialInterest);
}
maturityAmount = maturityAmount.add(installmentMaturity);
}
}
return maturityAmount.setScale(2, RoundingMode.HALF_UP);
}
}
@@ -0,0 +1,157 @@
/**
* 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.service;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.infrastructure.core.domain.ExternalId;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.portfolio.account.PortfolioAccountType;
import org.apache.fineract.portfolio.account.data.AccountTransferDTO;
import org.apache.fineract.portfolio.account.domain.AccountTransferType;
import org.apache.fineract.portfolio.account.service.AccountTransfersWritePlatformService;
import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
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;
/**
* RD Auto Debit: on each due date, collects the installment of every recurring deposit opened with Auto Debit from
* the Savings account linked to it, as an ordinary account transfer (debit the savings account, credit the deposit),
* so it is booked, journalled and shown on both statements exactly like a transfer the customer made themselves.
*
* <ul>
* <li>Only installments due on or before the business date and not yet fully paid are collected - oldest first, one
* transfer each, each in its own transaction.</li>
* <li>An installment the savings account cannot cover is skipped and stays overdue; nothing is partly collected, and
* the rest of that deposit's installments wait for the next run so they are never paid out of order. Every other
* deposit is unaffected.</li>
* <li>Retrying is the product's choice ("Allow Debit Txn after due date"): with it on, anything still unpaid is
* collected on a later run; with it off, an installment is debited only on its due date and a missed one stays
* overdue for the customer to pay (and for the missed-installment penalty, if the product has one).</li>
* </ul>
*/
@Slf4j
@Service
public class RecurringDepositAutoDebitService {
/**
* Unpaid installments, plus per deposit what has been due up to today and what has actually been paid in. The two
* totals matter because a deposit opened without "adjust advance payments" never allocates money paid before a
* due date to that installment - the schedule shows it unpaid though the customer already paid at the counter.
*/
private static final String DUE_INSTALLMENTS_SQL = """
SELECT rd.id AS rd_id, rd.linked_account_id AS savings_id, s.duedate AS due_date,
s.deposit_amount - COALESCE(s.deposit_amount_completed_derived, 0) AS outstanding,
(SELECT COALESCE(SUM(s2.deposit_amount), 0) FROM m_mandatory_savings_schedule s2
WHERE s2.savings_account_id = rd.id AND s2.duedate <= ?) AS total_due,
(SELECT COALESCE(SUM(t.amount), 0) FROM m_savings_account_transaction t
WHERE t.savings_account_id = rd.id AND t.transaction_type_enum = 1 AND t.is_reversed = false) AS total_paid
FROM m_savings_account rd
JOIN m_savings_product sp ON sp.id = rd.product_id
JOIN m_mandatory_savings_schedule s ON s.savings_account_id = rd.id
JOIN m_savings_account sav ON sav.id = rd.linked_account_id
WHERE rd.deposit_type_enum = 300
AND rd.status_enum = 300
AND rd.auto_debit_facility = true
AND UPPER(rd.linked_account_type) = 'SAVINGS'
AND sav.deposit_type_enum = 100
AND sav.status_enum = 300
AND COALESCE(s.completed_derived, false) = false
AND s.duedate <= ?
AND (COALESCE(sp.allow_debit_txn_after_due_date, false) = true OR s.duedate = ?)
AND s.deposit_amount > COALESCE(s.deposit_amount_completed_derived, 0)
ORDER BY rd.id, s.duedate
""";
private final JdbcTemplate jdbcTemplate;
private final AccountTransfersWritePlatformService accountTransfersWritePlatformService;
private final TransactionTemplate perInstallmentTransaction;
public RecurringDepositAutoDebitService(final JdbcTemplate jdbcTemplate,
final AccountTransfersWritePlatformService accountTransfersWritePlatformService,
final PlatformTransactionManager transactionManager) {
this.jdbcTemplate = jdbcTemplate;
this.accountTransfersWritePlatformService = accountTransfersWritePlatformService;
this.perInstallmentTransaction = new TransactionTemplate(transactionManager);
this.perInstallmentTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
/** @return how many installments were collected */
public int collectDueInstallments() {
final LocalDate businessDate = DateUtils.getBusinessLocalDate();
final List<DueInstallment> dueInstallments = this.jdbcTemplate.query(DUE_INSTALLMENTS_SQL,
(rs, rowNum) -> new DueInstallment(rs.getLong("rd_id"), rs.getLong("savings_id"), rs.getObject("due_date", LocalDate.class),
rs.getBigDecimal("outstanding"), rs.getBigDecimal("total_due").subtract(rs.getBigDecimal("total_paid"))),
businessDate, businessDate, businessDate);
int collected = 0;
Long blockedDeposit = null;
Long currentDeposit = null;
BigDecimal stillShort = BigDecimal.ZERO;
for (final DueInstallment installment : dueInstallments) {
if (installment.recurringDepositId().equals(blockedDeposit)) {
continue;
}
if (!installment.recurringDepositId().equals(currentDeposit)) {
currentDeposit = installment.recurringDepositId();
// What the customer still owes up to today - zero when they already paid it at the counter.
stillShort = installment.shortfall().max(BigDecimal.ZERO);
}
final BigDecimal amount = installment.outstanding().min(stillShort);
if (amount.signum() <= 0) {
continue;
}
try {
this.perInstallmentTransaction.executeWithoutResult(status -> collect(installment, amount, businessDate));
stillShort = stillShort.subtract(amount);
collected++;
} catch (final RuntimeException e) {
// Most often the linked savings account is short of funds. Leave this deposit's remaining
// installments for the next run rather than paying a later one ahead of the one that failed.
blockedDeposit = installment.recurringDepositId();
log.warn("RD Auto Debit could not collect the installment due {} on recurring deposit {} from savings account {}: {}",
installment.dueDate(), installment.recurringDepositId(), installment.savingsAccountId(), e.getMessage());
}
}
log.info("RD Auto Debit collected {} of {} due installment(s) on {}", collected, dueInstallments.size(), businessDate);
return collected;
}
private void collect(final DueInstallment installment, final BigDecimal amount, final LocalDate businessDate) {
final SavingsAccount fromSavingsAccount = null;
final SavingsAccount toSavingsAccount = null;
final boolean isRegularTransaction = true;
final boolean isExceptionForBalanceCheck = false;
final AccountTransferDTO transfer = new AccountTransferDTO(businessDate, amount, PortfolioAccountType.SAVINGS,
PortfolioAccountType.SAVINGS, installment.savingsAccountId(), installment.recurringDepositId(),
"RD Auto Debit - installment due " + installment.dueDate(), null, null, null, null, null, null, null,
AccountTransferType.ACCOUNT_TRANSFER.getValue(), null, null, ExternalId.empty(), null, toSavingsAccount, fromSavingsAccount,
isRegularTransaction, isExceptionForBalanceCheck);
this.accountTransfersWritePlatformService.transferFunds(transfer);
}
/** shortfall = everything due on the deposit up to today, less everything actually paid into it. */
private record DueInstallment(Long recurringDepositId, Long savingsAccountId, LocalDate dueDate, BigDecimal outstanding,
BigDecimal shortfall) {}
}
@@ -0,0 +1,176 @@
/**
* 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.service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
/**
* Lien on a recurring deposit pledged as security for a loan.
*
* <p>
* The lien itself is the existing guarantor mechanism: adding the deposit as a guarantor account on a loan records a
* funding line, and the guarantor module places the amount on hold when the loan is approved/disbursed, releases it as
* the loan is repaid, and releases the rest when the loan closes. What this class adds is what that mechanism never
* did for a recurring deposit:
* <ul>
* <li>only an RD whose product has <b>Lien Marked</b> on may be pledged, and never for more than the product's lien
* percentage of its balance (the whole balance when none is set), less what it already secures;</li>
* <li>a pledged RD cannot be closed - premature or on maturity - while any loan it secures is still pending or
* running. Before this, the hold only surfaced as an "insufficient balance" error deep inside the closure, and a pledge
* on a loan not yet approved (no hold placed yet) did not stop the deposit being paid out at all;</li>
* <li>which loans hold how much, so the RD screens can show it.</li>
* </ul>
*/
@Service
@RequiredArgsConstructor
public class RecurringDepositLienService {
/**
* Pledges still in force: the funding line is active and the loan is submitted (100), approved (200) or active
* (300). A loan that is closed, rejected or withdrawn no longer binds the deposit.
*/
private static final String ACTIVE_LIENS_SQL = """
SELECT l.id AS loan_id, l.account_no AS loan_account_no, l.loan_status_id AS loan_status,
COALESCE(gfd.amount_remaining_derived, gfd.amount) AS lien_amount
FROM m_guarantor_funding_details gfd
JOIN m_portfolio_account_associations paa ON paa.id = gfd.account_associations_id
JOIN m_loan l ON l.id = paa.loan_account_id
WHERE paa.linked_savings_account_id = ?
AND gfd.status_enum = 100
AND l.loan_status_id IN (100, 200, 300)
AND COALESCE(gfd.amount_remaining_derived, gfd.amount) > 0
ORDER BY l.id
""";
private static final BigDecimal ONE_HUNDRED = BigDecimal.valueOf(100);
private final JdbcTemplate jdbcTemplate;
public record Lien(Long loanId, String loanAccountNo, Integer loanStatus, BigDecimal amount) {}
/**
* The loan limit a deposit carries today: whether its product allows a lien at all, the percentage that applies
* (the deposit's own, else its product's, else 100), and what that comes to on the current balance.
*/
public record LienLimit(boolean lienAllowed, BigDecimal accountPercentage, BigDecimal productPercentage,
BigDecimal effectivePercentage, BigDecimal balance, BigDecimal maxLoanAmount) {}
private static final String LIEN_LIMIT_SQL = """
SELECT sp.lien_marked AS lien_marked, sa.lien_percentage AS account_pct, sp.lien_percentage AS product_pct,
COALESCE(sa.account_balance_derived, 0) AS balance
FROM m_savings_account sa
JOIN m_savings_product sp ON sp.id = sa.product_id
WHERE sa.id = ?
""";
public LienLimit lienLimit(final Long depositAccountId) {
final List<LienLimit> rows = this.jdbcTemplate.query(LIEN_LIMIT_SQL, (rs, rowNum) -> {
final boolean lienAllowed = rs.getBoolean("lien_marked");
final BigDecimal accountPct = rs.getBigDecimal("account_pct");
final BigDecimal productPct = rs.getBigDecimal("product_pct");
final BigDecimal balance = rs.getBigDecimal("balance");
final BigDecimal effective = accountPct != null ? accountPct : productPct != null ? productPct : ONE_HUNDRED;
final BigDecimal maxLoan = lienAllowed ? balance.multiply(effective).divide(ONE_HUNDRED, 2, RoundingMode.DOWN)
: BigDecimal.ZERO;
return new LienLimit(lienAllowed, accountPct, productPct, effective, balance, maxLoan);
}, depositAccountId);
return rows.isEmpty() ? null : rows.get(0);
}
public List<Lien> activeLiens(final Long depositAccountId) {
return this.jdbcTemplate.query(ACTIVE_LIENS_SQL, (rs, rowNum) -> new Lien(rs.getLong("loan_id"), rs.getString("loan_account_no"),
rs.getInt("loan_status"), rs.getBigDecimal("lien_amount")), depositAccountId);
}
public BigDecimal totalLien(final Long depositAccountId) {
return activeLiens(depositAccountId).stream().map(Lien::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
}
/** Refuses to pay out a recurring deposit that still secures a loan. */
public void assertNoActiveLien(final Long depositAccountId, final String action) {
final List<Lien> liens = activeLiens(depositAccountId);
if (liens.isEmpty()) {
return;
}
final BigDecimal total = liens.stream().map(Lien::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
final String loans = liens.stream().map(lien -> lien.loanAccountNo() + " (" + money(lien.amount()) + ")")
.collect(Collectors.joining(", "));
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.lien.marked",
"This recurring deposit has a lien of " + money(total) + " for loan(s) " + loans + ". It cannot be " + action
+ " until the loan is repaid or the guarantee is released.",
depositAccountId, total);
}
/**
* Rules for pledging an account as loan security. Only recurring deposits are checked here; other account types
* keep the guarantor module's existing behaviour.
*
* @param excludingLoanId
* the loan being edited, whose own earlier pledge must not count against the new amount
*/
public void validatePledge(final SavingsAccount account, final BigDecimal amount, final Long excludingLoanId) {
if (account == null || !account.depositAccountType().isRecurringDeposit()) {
return;
}
if (account.savingsProduct() == null || !account.savingsProduct().isLienMarked()) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.lien.not.allowed",
"Recurring deposit " + account.getAccountNumber() + " cannot be pledged: its product does not have Lien Marked enabled.",
account.getId());
}
if (!account.isActive()) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.lien.account.not.active",
"Recurring deposit " + account.getAccountNumber() + " is not active, so it cannot be pledged.", account.getId());
}
final BigDecimal alreadyPledged = activeLiens(account.getId()).stream()
.filter(lien -> excludingLoanId == null || !excludingLoanId.equals(lien.loanId())).map(Lien::amount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
// The lien percentage caps the total lien at that share of the balance as it stands now, when the loan is
// taken (90% of 1,00,000 = 90,000 across every loan the deposit secures). The deposit's own percentage, set
// when it was opened, wins; else the product's; neither means the whole balance.
final BigDecimal lienPercentage = account.getLienPercentage() != null ? account.getLienPercentage()
: account.savingsProduct().getLienPercentage();
final BigDecimal balance = account.getAccountBalance();
final BigDecimal pledgeable = lienPercentage == null ? balance
: balance.multiply(lienPercentage).divide(ONE_HUNDRED, 2, RoundingMode.DOWN);
final BigDecimal available = pledgeable.subtract(alreadyPledged);
if (amount != null && amount.compareTo(available) > 0) {
final String limitText = lienPercentage == null ? "balance " + balance.toPlainString()
: lienPercentage.stripTrailingZeros().toPlainString() + "% of balance " + balance.toPlainString() + " = "
+ pledgeable.toPlainString();
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.lien.exceeds.limit",
"Recurring deposit " + account.getAccountNumber() + " can secure at most " + available.max(BigDecimal.ZERO).toPlainString()
+ " (" + limitText + ", less " + money(alreadyPledged) + " already pledged); "
+ money(amount) + " was requested.",
account.getId(), amount, available);
}
}
/** Rupees to the paisa for messages - "10000.00", not the stored "10000.000000". */
private static String money(final BigDecimal amount) {
return amount == null ? "0.00" : amount.setScale(2, RoundingMode.HALF_UP).toPlainString();
}
}
@@ -0,0 +1,242 @@
/**
* 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.service;
import com.google.gson.JsonObject;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.data.CommandProcessingResult;
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.portfolio.savings.DepositAccountType;
import org.springframework.dao.EmptyResultDataAccessException;
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;
/**
* Missed-installment penalty for recurring deposits (product setting "Penalty / Grace Period for Missed
* Installments").
*
* <p>
* Every day, each installment still unpaid when its due date plus the product's grace days has passed is charged
* the product's penalty once - a flat amount, or a percentage of the installment. The penalty is the system charge
* "RD Missed Installment Penalty" added to the deposit and paid out of its balance, so it shows on the statement as
* a charge and is booked to the product's Income From Penalties account like any other penalty.
*
* <ul>
* <li>One penalty per installment, ever: m_rd_installment_penalty records which installments have been charged,
* and an installment paid late afterwards is not charged again.</li>
* <li>Paying an installment within the grace days costs nothing.</li>
* <li>When the deposit does not yet hold enough to pay the penalty (the first installment missed, say), the charge
* stays on the account as due and every later run tries again.</li>
* </ul>
*/
@Slf4j
@Service
public class RecurringDepositMissedInstallmentPenaltyService {
public static final String PENALTY_CHARGE_NAME = "RD Missed Installment Penalty";
public static final int PENALTY_TYPE_FLAT = 1;
public static final int PENALTY_TYPE_PERCENT = 2;
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final BigDecimal ONE_HUNDRED = BigDecimal.valueOf(100);
/** Unpaid installments of active RDs whose product has the penalty on and that have not been penalised yet. */
private static final String CANDIDATES_SQL = """
SELECT s.id AS installment_id, rd.id AS rd_id, s.duedate AS due_date, s.deposit_amount AS installment_amount,
COALESCE(sp.missed_installment_grace_days, 0) AS grace_days,
COALESCE(sp.missed_installment_penalty_type, 1) AS penalty_type,
sp.missed_installment_penalty_amount AS penalty_amount,
(SELECT COALESCE(SUM(s2.deposit_amount), 0) FROM m_mandatory_savings_schedule s2
WHERE s2.savings_account_id = rd.id AND s2.duedate <= s.duedate) AS due_through_installment,
(SELECT COALESCE(SUM(t.amount), 0) FROM m_savings_account_transaction t
WHERE t.savings_account_id = rd.id AND t.transaction_type_enum = 1 AND t.is_reversed = false) AS total_paid
FROM m_savings_account rd
JOIN m_savings_product sp ON sp.id = rd.product_id
JOIN m_mandatory_savings_schedule s ON s.savings_account_id = rd.id
WHERE rd.deposit_type_enum = 300
AND rd.status_enum = 300
AND sp.penalty_grace_period_missed_installments = true
AND COALESCE(sp.missed_installment_penalty_amount, 0) > 0
AND COALESCE(s.completed_derived, false) = false
AND s.deposit_amount > COALESCE(s.deposit_amount_completed_derived, 0)
AND s.duedate < ?
AND NOT EXISTS (SELECT 1 FROM m_rd_installment_penalty p WHERE p.installment_id = s.id)
ORDER BY rd.id, s.duedate
""";
/**
* Penalty charges still unpaid on active recurring deposits. Found by the penalty charge definition rather than
* through the tracking table, so nothing depends on the charge id being known at the moment it was added.
*/
private static final String UNPAID_SQL = """
SELECT sac.savings_account_id AS rd_id, sac.id AS charge_id, sac.amount_outstanding_derived AS outstanding
FROM m_savings_account_charge sac
JOIN m_savings_account rd ON rd.id = sac.savings_account_id
WHERE sac.charge_id = ?
AND rd.deposit_type_enum = 300
AND rd.status_enum = 300
AND sac.is_active = true
AND COALESCE(sac.is_paid_derived, false) = false
AND COALESCE(sac.waived, false) = false
AND sac.amount_outstanding_derived > 0
ORDER BY sac.id
""";
private final JdbcTemplate jdbcTemplate;
private final DepositAccountWritePlatformService depositAccountWritePlatformService;
private final FromJsonHelper fromJsonHelper;
private final TransactionTemplate ownTransaction;
public RecurringDepositMissedInstallmentPenaltyService(final JdbcTemplate jdbcTemplate,
final DepositAccountWritePlatformService depositAccountWritePlatformService, final FromJsonHelper fromJsonHelper,
final PlatformTransactionManager transactionManager) {
this.jdbcTemplate = jdbcTemplate;
this.depositAccountWritePlatformService = depositAccountWritePlatformService;
this.fromJsonHelper = fromJsonHelper;
this.ownTransaction = new TransactionTemplate(transactionManager);
this.ownTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
/**
* paidInFull: everything due up to and including this installment has actually been paid into the deposit - e.g.
* in advance at the counter, which a deposit opened without "adjust advance payments" never allocates to the
* installment itself. Such an installment only looks unpaid and must not be penalised.
*/
private record Candidate(Long installmentId, Long rdId, LocalDate dueDate, BigDecimal installmentAmount, int graceDays, int penaltyType,
BigDecimal penaltyAmount, boolean paidInFull) {}
private record Unpaid(Long rdId, Long chargeId, BigDecimal outstanding) {}
/** @return how many installments were newly penalised */
public int applyPenalties() {
final LocalDate businessDate = DateUtils.getBusinessLocalDate();
final Long penaltyChargeId = penaltyChargeId();
if (penaltyChargeId == null) {
log.warn("Charge '{}' not found - missed-installment penalties cannot be applied", PENALTY_CHARGE_NAME);
return 0;
}
final List<Candidate> candidates = this.jdbcTemplate.query(CANDIDATES_SQL,
(rs, rowNum) -> new Candidate(rs.getLong("installment_id"), rs.getLong("rd_id"), rs.getObject("due_date", LocalDate.class),
rs.getBigDecimal("installment_amount"), rs.getInt("grace_days"), rs.getInt("penalty_type"),
rs.getBigDecimal("penalty_amount"),
rs.getBigDecimal("total_paid").compareTo(rs.getBigDecimal("due_through_installment")) >= 0),
businessDate);
int penalised = 0;
for (final Candidate candidate : candidates) {
// Grace: due on the 10th with 5 grace days is penalised from the 16th.
if (!candidate.dueDate().plusDays(candidate.graceDays()).isBefore(businessDate) || candidate.paidInFull()) {
continue;
}
final BigDecimal penalty = penaltyFor(candidate);
if (penalty.signum() <= 0) {
continue;
}
try {
this.ownTransaction.executeWithoutResult(status -> charge(candidate, penalty, penaltyChargeId, businessDate));
penalised++;
} catch (final RuntimeException e) {
log.warn("Could not charge the missed-installment penalty on RD {} (installment due {}): {}", candidate.rdId(),
candidate.dueDate(), e.getMessage());
}
}
// Collect everything now due - tonight's penalties and any an earlier run could not cover.
collectUnpaid(penaltyChargeId, businessDate);
log.info("RD missed-installment penalty: {} installment(s) penalised on {}", penalised, businessDate);
return penalised;
}
/** Flat amount, or the percentage of this installment, rounded to the paisa. */
static BigDecimal penaltyFor(final Candidate candidate) {
if (candidate.penaltyType() == PENALTY_TYPE_PERCENT) {
return candidate.installmentAmount().multiply(candidate.penaltyAmount()).divide(ONE_HUNDRED, 2, RoundingMode.HALF_UP);
}
return candidate.penaltyAmount().setScale(2, RoundingMode.HALF_UP);
}
/** Records the installment as penalised and adds the penalty charge to the deposit, as one unit. */
private void charge(final Candidate candidate, final BigDecimal penalty, final Long penaltyChargeId, final LocalDate businessDate) {
this.jdbcTemplate.update("""
INSERT INTO m_rd_installment_penalty (installment_id, savings_account_id, penalty_amount, applied_on_date)
VALUES (?, ?, ?, ?)
""", candidate.installmentId(), candidate.rdId(), penalty, businessDate);
final JsonObject body = new JsonObject();
body.addProperty("chargeId", penaltyChargeId);
body.addProperty("amount", penalty);
body.addProperty("dueDate", businessDate.toString());
body.addProperty("dateFormat", DATE_FORMAT);
body.addProperty("locale", "en");
final CommandProcessingResult result = this.depositAccountWritePlatformService.addSavingsAccountCharge(command(body, candidate.rdId()),
DepositAccountType.RECURRING_DEPOSIT);
// The charge's id is only known here if the add happened to flush; keep the link when it is, for reference.
if (result.getResourceId() != null) {
this.jdbcTemplate.update("UPDATE m_rd_installment_penalty SET savings_account_charge_id = ? WHERE installment_id = ?",
result.getResourceId(), candidate.installmentId());
}
}
private void collectUnpaid(final Long penaltyChargeId, final LocalDate businessDate) {
final List<Unpaid> unpaid = this.jdbcTemplate.query(UNPAID_SQL,
(rs, rowNum) -> new Unpaid(rs.getLong("rd_id"), rs.getLong("charge_id"), rs.getBigDecimal("outstanding")), penaltyChargeId);
for (final Unpaid charge : unpaid) {
tryPay(charge.rdId(), charge.chargeId(), charge.outstanding(), businessDate);
}
}
/** Pays the penalty from the deposit's balance; if it cannot be covered yet the charge simply stays due. */
private void tryPay(final Long rdId, final Long chargeId, final BigDecimal amount, final LocalDate businessDate) {
final JsonObject body = new JsonObject();
body.addProperty("amount", amount);
body.addProperty("dueDate", businessDate.toString());
body.addProperty("dateFormat", DATE_FORMAT);
body.addProperty("locale", "en");
try {
this.ownTransaction.executeWithoutResult(status -> this.depositAccountWritePlatformService.payCharge(rdId, chargeId,
command(body, rdId), DepositAccountType.RECURRING_DEPOSIT));
} catch (final RuntimeException e) {
log.info("Missed-installment penalty {} on RD {} left due (not collected yet): {}", chargeId, rdId, e.getMessage());
}
}
private Long penaltyChargeId() {
try {
return this.jdbcTemplate.queryForObject(
"SELECT id FROM m_charge WHERE name = ? AND is_deleted = false AND is_active = true ORDER BY id LIMIT 1", Long.class,
PENALTY_CHARGE_NAME);
} catch (final EmptyResultDataAccessException e) {
return null;
}
}
/** A command carrying the deposit's id the way the charge endpoints receive it from the API. */
private JsonCommand command(final JsonObject body, final Long rdId) {
return new JsonCommand(null, body.toString(), body, this.fromJsonHelper, null, rdId, null, null, null, null, rdId, null, null,
null, null, null, null, null);
}
}
@@ -0,0 +1,301 @@
/**
* 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.service;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.math.BigDecimal;
import java.time.LocalDate;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.fineract.infrastructure.codes.domain.CodeValueRepository;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
import org.apache.fineract.portfolio.savings.domain.DepositProductAmountDetails;
import org.apache.fineract.portfolio.savings.domain.RecurringDepositAccount;
import org.apache.fineract.portfolio.savings.domain.RecurringDepositProduct;
import org.apache.fineract.portfolio.savings.domain.SavingsProduct;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
/**
* The recurring-deposit product settings that only mean something when an account is opened against them. Each one
* used to be stored on the product and then ignored; they are enforced here, on the server, so a client that skips
* the screen's own checks cannot open an account the product does not allow.
*
* <ul>
* <li>Effective Date - the first day the product can be used. No account may be opened before it.</li>
* <li>Effective To - the last day the product is on sale. No new account may be opened after it; accounts already
* open run to maturity as normal.</li>
* <li>End Date - the day the product is wound up. No account may be opened that would still be running after it, so
* every account opened under the product has matured by then.</li>
* <li>Deposit Amount Min / Max - bounds on the installment the customer commits to each period.</li>
* <li>Nomination Facility - when on, at least one nominee is required; when off, nominees cannot be recorded.</li>
* <li>Auto Debit Facility - only offered when the product allows it, and only with a linked Savings account to debit,
* since that is where the installment is collected from.</li>
* <li>Interest Calculation Type - copied onto the account as its simple/compounding flag (see
* {@link #isSimpleInterestOption}).</li>
* </ul>
*/
@Component
@RequiredArgsConstructor
public class RecurringDepositProductRules {
/** Label of the InterestCalculationTypeOption code value that switches a recurring deposit to simple interest. */
public static final String SIMPLE_INTEREST_OPTION_LABEL = "Simple";
private static final String LINKED_ACCOUNT_TYPE_SAVINGS = "SAVINGS";
private static final BigDecimal ONE_HUNDRED = BigDecimal.valueOf(100);
private final CodeValueRepository codeValueRepository;
private final JdbcTemplate jdbcTemplate;
/**
* Fixes the account's simple/compounding flag from its product. Must run before the maturity amount is projected,
* which is calculated with it.
*/
public void applyInterestCalculationType(final RecurringDepositAccount account) {
account.setSimpleInterest(isSimpleInterestOption(account.savingsProduct().getInterestCalculateSelector()));
}
/** Rules for a brand-new application. Runs after the maturity date is known, which End Date is checked against. */
public void validateOnSubmit(final RecurringDepositAccount account, final JsonCommand command) {
final SavingsProduct product = account.savingsProduct();
applyProductPreClosurePenalty(account, product);
applyLienPercentage(account, product, command, true);
validateOpeningWindow(account, product);
validateInstallmentAmount(account, product);
validateNomination(product, command);
validateAutoDebit(account, product);
validateIntroducer(account, product);
}
/**
* Rules for an application edited before approval. Nominees are only checked when the edit sends them, since an
* edit that leaves them out keeps the ones already recorded.
*/
public void validateOnModify(final RecurringDepositAccount account, final JsonCommand command) {
final SavingsProduct product = account.savingsProduct();
applyProductPreClosurePenalty(account, product);
applyLienPercentage(account, product, command, false);
validateOpeningWindow(account, product);
validateInstallmentAmount(account, product);
if (hasNomineesProperty(command)) {
validateNomination(product, command);
}
validateAutoDebit(account, product);
validateIntroducer(account, product);
}
/**
* Whether a product's Interest Calculation Type is "Simple". The option is a tenant-editable code value, so it is
* matched by label rather than by a hard-coded id; anything else - no selection, "Compounding", an unknown id - is
* compounding, which is how every recurring deposit was calculated before the option was honoured.
*/
public boolean isSimpleInterestOption(final Integer interestCalculateSelector) {
if (interestCalculateSelector == null) {
return false;
}
return this.codeValueRepository.findById(interestCalculateSelector.longValue())
.map(codeValue -> SIMPLE_INTEREST_OPTION_LABEL.equalsIgnoreCase(StringUtils.trim(codeValue.getLabel()))).orElse(false);
}
/**
* How much of this deposit may be given as loan. Only a Lien Marked product allows a lien at all; the account's
* percentage may be lowered from the product's but never raised above it. When the application sends none, a new
* account takes the product's percentage and an edited one keeps what it had.
*/
private void applyLienPercentage(final RecurringDepositAccount account, final SavingsProduct product, final JsonCommand command,
final boolean isSubmit) {
if (!product.isLienMarked()) {
account.setLienPercentage(null);
return;
}
final BigDecimal productLimit = product.getLienPercentage() == null ? ONE_HUNDRED : product.getLienPercentage();
if (!command.parameterExists("lienPercentage") || command.bigDecimalValueOfParameterNamed("lienPercentage") == null) {
if (isSubmit) {
account.setLienPercentage(product.getLienPercentage());
}
return;
}
final BigDecimal requested = command.bigDecimalValueOfParameterNamed("lienPercentage");
if (requested.signum() <= 0 || requested.compareTo(productLimit) > 0) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.lien.percentage.out.of.range",
"Loan against this deposit must be more than 0% and at most " + productLimit.stripTrailingZeros().toPlainString()
+ "% (the limit of product '" + product.getName() + "'); " + requested.stripTrailingZeros().toPlainString() + "% was entered.",
requested, productLimit);
}
account.setLienPercentage(requested);
}
private void validateOpeningWindow(final RecurringDepositAccount account, final SavingsProduct product) {
final LocalDate openedOn = account.getSubmittedOnDate();
if (openedOn == null) {
return;
}
final LocalDate effectiveFrom = product.getEffectiveDate();
if (effectiveFrom != null && openedOn.isBefore(effectiveFrom)) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.product.not.yet.effective",
"Product '" + product.getName() + "' can only be used from " + effectiveFrom + "; this application is dated "
+ openedOn + ".",
effectiveFrom, openedOn);
}
final LocalDate effectiveTo = product.getEffectiveTo();
if (effectiveTo != null && openedOn.isAfter(effectiveTo)) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.product.closed.for.new.accounts",
"Product '" + product.getName() + "' stopped accepting new accounts after " + effectiveTo
+ "; this application is dated " + openedOn + ".",
effectiveTo, openedOn);
}
final LocalDate endDate = product.getEndDate();
final LocalDate maturityDate = account.maturityDate();
if (endDate != null && maturityDate != null && maturityDate.isAfter(endDate)) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.maturity.after.product.end.date",
"This deposit would mature on " + maturityDate + ", after product '" + product.getName() + "' ends on " + endDate
+ ". Choose a shorter tenure.",
maturityDate, endDate);
}
}
/**
* "Apply Penal Interest (less)" is the product's decision, not the account's: whatever the application sent, the
* deposit takes the product's penalty - on or off, the same percentage and the same period (Whole Term / Till
* Premature Withdrawal). A product without the penalty means no penal interest on premature closure.
*/
private void applyProductPreClosurePenalty(final RecurringDepositAccount account, final SavingsProduct product) {
if (product instanceof RecurringDepositProduct rdProduct && rdProduct.depositProductTermAndPreClosure() != null) {
account.applyProductPreClosurePenalty(rdProduct.depositProductTermAndPreClosure().depositPreClosureDetail());
}
}
/** A deposit whose tenure is extended must still mature on or before its product's End Date. */
public void validateMaturityWithinProductEndDate(final RecurringDepositAccount account) {
final SavingsProduct product = account.savingsProduct();
final LocalDate endDate = product.getEndDate();
final LocalDate maturityDate = account.maturityDate();
if (endDate != null && maturityDate != null && maturityDate.isAfter(endDate)) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.maturity.after.product.end.date",
"This deposit would mature on " + maturityDate + ", after product '" + product.getName() + "' ends on " + endDate
+ ". Choose a shorter tenure.",
maturityDate, endDate);
}
}
private void validateInstallmentAmount(final RecurringDepositAccount account, final SavingsProduct product) {
if (!(product instanceof RecurringDepositProduct rdProduct) || rdProduct.depositProductTermAndPreClosure() == null) {
return;
}
final DepositProductAmountDetails limits = rdProduct.depositProductTermAndPreClosure().depositProductAmountDetails();
final BigDecimal installment = account.getRecurringDetail() == null ? null
: account.getRecurringDetail().mandatoryRecommendedDepositAmount();
if (limits == null || installment == null) {
return;
}
final BigDecimal min = limits.getMinDepositAmount();
if (min != null && min.signum() > 0 && installment.compareTo(min) < 0) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.installment.below.product.minimum",
"Installment amount " + installment.stripTrailingZeros().toPlainString() + " is below the product minimum of " + min.stripTrailingZeros().toPlainString()
+ ".",
installment, min);
}
final BigDecimal max = limits.getMaxDepositAmount();
if (max != null && max.signum() > 0 && installment.compareTo(max) > 0) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.installment.above.product.maximum",
"Installment amount " + installment.stripTrailingZeros().toPlainString() + " is above the product maximum of " + max.stripTrailingZeros().toPlainString()
+ ".",
installment, max);
}
}
private void validateNomination(final SavingsProduct product, final JsonCommand command) {
final boolean hasNominees = hasNominees(command);
if (product.isNominationFacility() && !hasNominees) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.nominee.required",
"Product '" + product.getName() + "' has Nomination Facility enabled - add at least one nominee.");
}
if (!product.isNominationFacility() && hasNominees) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.nomination.not.offered",
"Product '" + product.getName() + "' does not offer a Nomination Facility, so nominees cannot be recorded.");
}
}
/**
* "Introducer Required" on the product: the deposit must name an introducer - an existing, active customer of the
* bank, and not the depositor themselves.
*/
private void validateIntroducer(final RecurringDepositAccount account, final SavingsProduct product) {
if (!product.isIntroducerRequired()) {
return;
}
final Long introducerId = account.getIntroducerClientId();
if (introducerId == null) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.introducer.required",
"Product '" + product.getName() + "' requires an introducer - choose an existing customer as introducer.");
}
if (introducerId.equals(account.clientId())) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.introducer.self",
"The depositor cannot be their own introducer.");
}
final Integer active = this.jdbcTemplate.queryForObject("SELECT COUNT(*) FROM m_client WHERE id = ? AND status_enum = 300",
Integer.class, introducerId);
if (active == null || active == 0) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.introducer.not.active",
"The introducer must be an active customer of the bank.");
}
}
private void validateAutoDebit(final RecurringDepositAccount account, final SavingsProduct product) {
if (!Boolean.TRUE.equals(account.getAutoDebitFacility())) {
return;
}
if (!product.isAutoDebitFacility()) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.auto.debit.not.offered",
"Product '" + product.getName() + "' does not offer Auto Debit.");
}
final Long linkedAccountId = account.getLinkedAccountId();
if (linkedAccountId == null || !LINKED_ACCOUNT_TYPE_SAVINGS.equalsIgnoreCase(account.getLinkedAccountType())) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.auto.debit.linked.savings.required",
"Auto Debit collects each installment from the linked account, so link an active Savings account to use it.");
}
final Integer matches = this.jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM m_savings_account WHERE id = ? AND client_id = ? AND deposit_type_enum = 100 AND status_enum = 300",
Integer.class, linkedAccountId, account.clientId());
if (matches == null || matches == 0) {
throw new GeneralPlatformDomainRuleException("error.msg.recurringdeposit.auto.debit.linked.savings.not.active",
"Linked account " + linkedAccountId + " is not an active Savings account of this client, so Auto Debit cannot use it.",
linkedAccountId);
}
}
private static boolean hasNomineesProperty(final JsonCommand command) {
final JsonObject root = command.parsedJson().getAsJsonObject();
return root.has("nominees") || root.has("nominee");
}
private static boolean hasNominees(final JsonCommand command) {
final JsonObject root = command.parsedJson().getAsJsonObject();
final JsonElement nominees = root.get("nominees");
if (nominees != null && nominees.isJsonArray()) {
return !nominees.getAsJsonArray().isEmpty();
}
final JsonElement nominee = root.get("nominee");
return nominee != null && nominee.isJsonObject();
}
}
@@ -264,11 +264,7 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_RD, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsProductSelfApprovalNotAllowedException(productId);
}
@@ -361,11 +357,7 @@ public class RecurringDepositProductWritePlatformServiceJpaRepositoryImpl implem
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_RD, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsProductSelfApprovalNotAllowedException(productId);
}
@@ -203,11 +203,7 @@ public class SavingsAccountEditWritePlatformServiceJpaRepositoryImpl implements
.findBySavingsAccountIdAndStatus(savingsId, SavingsAccountPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsAccountNoPendingEditException(savingsId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsAccountEditSelfApprovalNotAllowedException(savingsId);
}
@@ -269,11 +265,7 @@ public class SavingsAccountEditWritePlatformServiceJpaRepositoryImpl implements
.findBySavingsAccountIdAndStatus(savingsId, SavingsAccountPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsAccountNoPendingEditException(savingsId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsAccountEditSelfApprovalNotAllowedException(savingsId);
}
@@ -374,8 +374,10 @@ public class SavingsAccountInterestPostingServiceImpl implements SavingsAccountI
// this runs per account inside a batch job, so a null deposit type must not take the whole run down.
final boolean interestTransferEnabled = savingsAccountData.isTransferInterestToLinkedAccount()
&& DepositAccountType.FIXED_DEPOSIT.getValue().equals(savingsAccountData.getDepositTypeId());
// A simple-interest recurring deposit must post here exactly what its own maturity projection promised, so the
// flag is the same one SavingsAccount#calculateInterestUsing honours.
this.savingsHelper.calculateInterestForAllPostingPeriods(monetaryCurrency, allPostingPeriods,
getLockedInUntilLocalDate(savingsAccountData), interestTransferEnabled);
getLockedInUntilLocalDate(savingsAccountData), interestTransferEnabled, savingsAccountData.isSimpleInterest());
savingsAccountData.getSummary().updateFromInterestPeriodSummaries(monetaryCurrency, allPostingPeriods);
@@ -438,10 +438,12 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead
LocalDate yesterday = DateUtils.getBusinessLocalDate().minusDays(1);
// A product on the daily-interest timetable is paid by the pooled posting instead
// (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.
// FD products are never on that timetable, so they still post here. A recurring deposit (deposit_type_enum
// 300) is left out: its posting periods are credited by the nightly deposit maturity job instead
// (RecurringDepositAccount#postPeriodicInterest), at the chart rate and on deposits alone. The filters sit inside the paging subquery so a page is never cut short by
// accounts that are then dropped.
String sql = "select " + this.savingAccountMapperForInterestPosting.schema()
+ "join (select a.id from m_savings_account a where a.id > ? and a.status_enum = ? "
+ "join (select a.id from m_savings_account a where a.id > ? and a.status_enum = ? and a.deposit_type_enum <> 300 "
+ "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 ";
if (backdatedTxnsAllowedTill) {
@@ -470,6 +472,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead
sqlBuilder.append("sa.id as id, sa.account_no as accountNo, sa.external_id as externalId, ");
sqlBuilder.append("sa.deposit_type_enum as depositType, ");
sqlBuilder.append("datp.transfer_interest_to_linked_account as transferInterestToLinkedAccount, ");
sqlBuilder.append("sa.is_simple_interest as isSimpleInterest, ");
sqlBuilder.append("c.id as clientId, c.office_id as clientOfficeId, ");
sqlBuilder.append("g.id as groupId, g.office_id as groupOfficeId, ");
sqlBuilder.append("sa.status_enum as statusEnum, ");
@@ -839,6 +842,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead
// Monthly-payout deposits must not compound: their interest leaves the account every
// period, so each period earns on the principal alone.
savingsAccountData.setTransferInterestToLinkedAccount(rs.getBoolean("transferInterestToLinkedAccount"));
savingsAccountData.setSimpleInterest(rs.getBoolean("isSimpleInterest"));
}
if (!transMap.containsValue(transactionId)) {
@@ -420,11 +420,7 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_SAVINGS, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsProductSelfApprovalNotAllowedException(productId);
}
@@ -528,11 +524,7 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_SAVINGS, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new SavingsProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new SavingsProductSelfApprovalNotAllowedException(productId);
}
@@ -106,6 +106,8 @@ import org.apache.fineract.commands.domain.CommandSourceRepository;
import org.apache.fineract.portfolio.savings.domain.SavingsProductFacilityLimitRepository;
import org.apache.fineract.portfolio.savings.domain.SavingsProductRepository;
import org.apache.fineract.portfolio.savings.service.FacilityChargeAutoApplyService;
import org.apache.fineract.portfolio.savings.service.RecurringDepositLienService;
import org.apache.fineract.portfolio.savings.service.RecurringDepositProductRules;
import org.apache.fineract.portfolio.savings.service.DepositAccountInterestRateChartReadPlatformService;
import org.apache.fineract.portfolio.savings.service.DepositAccountInterestRateChartReadPlatformServiceImpl;
import org.apache.fineract.portfolio.savings.service.DepositAccountOnHoldTransactionReadPlatformService;
@@ -297,7 +299,8 @@ public class SavingsConfiguration {
ConfigurationDomainService configurationDomainService, HolidayRepositoryWrapper holidayRepository,
WorkingDaysRepositoryWrapper workingDaysRepository,
DepositAccountOnHoldTransactionRepository depositAccountOnHoldTransactionRepository,
DenominationBreakdownWriter denominationBreakdownWriter, JdbcTemplate jdbcTemplate
DenominationBreakdownWriter denominationBreakdownWriter, JdbcTemplate jdbcTemplate,
RecurringDepositLienService recurringDepositLienService, RecurringDepositProductRules recurringDepositProductRules
) {
return new DepositAccountWritePlatformServiceJpaRepositoryImpl(context, savingAccountRepositoryWrapper,
@@ -307,7 +310,7 @@ public class SavingsConfiguration {
chargeRepository, savingsAccountChargeRepository, accountAssociationsReadPlatformService,
accountTransfersWritePlatformService, depositAccountReadPlatformService, calendarInstanceRepository,
configurationDomainService, holidayRepository, workingDaysRepository, depositAccountOnHoldTransactionRepository,
denominationBreakdownWriter, jdbcTemplate);
denominationBreakdownWriter, jdbcTemplate, recurringDepositLienService, recurringDepositProductRules);
}
@Bean
@@ -323,13 +326,14 @@ public class SavingsConfiguration {
FromJsonHelper fromJsonHelper, CalendarInstanceRepository calendarInstanceRepository,
ConfigurationDomainService configurationDomainService, AccountNumberFormatRepositoryWrapper accountNumberFormatRepository,
BusinessEventNotifierService businessEventNotifierService, SavingsAccountAssembler savingsAccountAssembler,
ClientNomineeWritePlatformService clientNomineeWritePlatformService) {
ClientNomineeWritePlatformService clientNomineeWritePlatformService,
RecurringDepositProductRules recurringDepositProductRules) {
return new DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl(context, savingAccountRepository,
fixedDepositAccountRepository, recurringDepositAccountRepository, depositAccountAssembler, depositAccountDataValidator,
accountNumberGenerator, clientRepository, groupRepository, savingsProductRepository, noteRepository, staffRepository,
savingsAccountApplicationTransitionApiJsonValidator, savingsAccountChargeAssembler, accountAssociationsRepository,
fromJsonHelper, calendarInstanceRepository, configurationDomainService, accountNumberFormatRepository,
businessEventNotifierService, savingsAccountAssembler, clientNomineeWritePlatformService);
businessEventNotifierService, savingsAccountAssembler, clientNomineeWritePlatformService, recurringDepositProductRules);
}
@Bean
@@ -172,12 +172,7 @@ public class ShareAccountEditWritePlatformServiceJpaRepositoryImpl implements Sh
.findByShareAccountIdAndStatus(shareAccountId, ShareAccountPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new ShareAccountNoPendingEditException(shareAccountId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - that permission still lets them approve someone ELSE's request,
// it just no longer lets them bypass the hold on their own (matches
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction(), the
// equivalent rule for the classic command pipeline).
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new ShareAccountEditSelfApprovalNotAllowedException(shareAccountId);
}
@@ -219,12 +214,7 @@ public class ShareAccountEditWritePlatformServiceJpaRepositoryImpl implements Sh
.findByShareAccountIdAndStatus(shareAccountId, ShareAccountPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new ShareAccountNoPendingEditException(shareAccountId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - that permission still lets them approve someone ELSE's request,
// it just no longer lets them bypass the hold on their own (matches
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction(), the
// equivalent rule for the classic command pipeline).
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new ShareAccountEditSelfApprovalNotAllowedException(shareAccountId);
}
@@ -882,11 +882,7 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_SHARE, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new ShareProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new ShareProductSelfApprovalNotAllowedException(productId);
}
@@ -972,11 +968,7 @@ public class ShareProductWritePlatformServiceJpaRepositoryImpl implements ShareP
.findByProductTypeAndProductIdAndStatus(ProductPendingEdit.TYPE_SHARE, productId, ProductPendingEdit.STATUS_PENDING)
.orElseThrow(() -> new ShareProductNoPendingEditException(productId));
// Maker-identity rule: the same user can never approve their own submission, even when they
// hold CHECKER_SUPER_USER - see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction() for the
// equivalent enforcement in the classic command pipeline.
if (pendingEdit.getMaker().getId().equals(checker.getId())) {
if (pendingEdit.getMaker().getId().equals(checker.getId()) && !checker.isCheckerSuperUser()) {
throw new ShareProductSelfApprovalNotAllowedException(productId);
}
@@ -281,7 +281,9 @@ public class SponsorDDReadPlatformServiceImpl implements SponsorDDReadPlatformSe
+ "m.gst_percentage, m.gst_payable_gl_account_id, gst.name as gst_payable_gl_account_name, gst.gl_code as gst_payable_gl_code, "
+ "m.dd_limit_amount "
+ "from m_sponsor_dd_gl_mapping m "
+ "join acc_gl_account payable on payable.id = m.dd_payable_gl_account_id "
// Left join: DD Payable moved to the sponsor bank (0570) and became nullable here (0573), so
// an inner join dropped the whole row and the settings screen reopened blank.
+ "left join acc_gl_account payable on payable.id = m.dd_payable_gl_account_id "
+ "left join acc_gl_account clearing on clearing.id = m.cheque_clearing_gl_account_id "
+ "left join acc_gl_account cash on cash.id = m.cash_gl_account_id "
+ "left join acc_gl_account charges on charges.id = m.charges_income_gl_account_id "
@@ -310,7 +312,7 @@ public class SponsorDDReadPlatformServiceImpl implements SponsorDDReadPlatformSe
final Long id = rs.getLong("id");
final Long sponsorBankId = rs.getObject("sponsor_bank_id") != null ? rs.getLong("sponsor_bank_id") : null;
final String sponsorBankName = rs.getString("sponsor_bank_name");
final Long ddPayableGlAccountId = rs.getLong("dd_payable_gl_account_id");
final Long ddPayableGlAccountId = rs.getObject("dd_payable_gl_account_id") != null ? rs.getLong("dd_payable_gl_account_id") : null;
final String ddPayableGlAccountName = rs.getString("dd_payable_gl_account_name");
final String ddPayableGlCode = rs.getString("dd_payable_gl_code");
final Long chequeClearingGlAccountId = rs.getObject("cheque_clearing_gl_account_id") != null ? rs.getLong("cheque_clearing_gl_account_id") : null;
@@ -52,10 +52,10 @@ public class TdsInterestApiResource {
@Produces({ MediaType.APPLICATION_JSON })
@Operation(summary = "Deposit interest per customer for a financial year",
description = "financialYear is the opening calendar year: 2026 means 1 Apr 2026 to 31 Mar 2027. Defaults to the year the business date falls in.")
public String retrieve(@QueryParam("financialYear") final Integer financialYear) {
public String retrieve(@QueryParam("financialYear") final Integer financialYear, @QueryParam("clientId") final Long clientId) {
this.context.authenticatedUser();
final List<TdsDeducteeData> deductees = this.readPlatformService
.retrieveForFinancialYear(financialYear != null ? financialYear : currentFinancialYear());
.retrieveForFinancialYear(financialYear != null ? financialYear : currentFinancialYear(), clientId);
return this.toApiJsonSerializer.serialize(deductees);
}
@@ -0,0 +1,490 @@
/**
* 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.tds.api;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
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.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.accounting.glaccount.validation.GLAccountTransactionGuard;
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.tds.service.TdsSql;
import org.apache.fineract.useradministration.domain.AppUser;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* The two TDS records the bank keeps by hand: the declarations customers give at the counter, and the
* challans Head Office remits the deducted tax with.
*
* <p>
* Both feed the deduction and the reports directly. A declaration stops the deduction from the day it
* is accepted; a challan is what the remittance report reconciles the deducted tax against.
*/
@Path("/v1/tds")
@Component
@RequiredArgsConstructor
@Produces({ MediaType.APPLICATION_JSON })
public class TdsRecordsApiResource {
private static final String DECLARATION = "TDSDECLARATION";
private static final String CHALLAN = "TDSCHALLAN";
private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context;
private final FromJsonHelper fromJsonHelper;
private final Gson gson = new Gson();
// ─────────────────────────── declarations ───────────────────────────
/** A customer's declarations, every year and revoked ones included, newest year first. */
@GET
@Path("declarations")
public String declarations(@QueryParam("clientId") final Long clientId, @QueryParam("fy") final String fy) {
final AppUser user = this.context.authenticatedUser();
if (clientId == null && fy == null) {
throw new PlatformDataIntegrityException("error.msg.tds.declarations.filter.required", "Give a clientId or a fy.");
}
final List<Object> params = new ArrayList<>();
final StringBuilder where = new StringBuilder(" WHERE o.hierarchy LIKE ?");
params.add(user.getOffice().getHierarchy() + "%");
if (clientId != null) {
where.append(" AND d.client_id = ?");
params.add(clientId);
}
if (fy != null) {
where.append(" AND d.fy_label = ?");
params.add(fy);
}
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
SELECT d.id, d.client_id, c.display_name AS client_name, d.fy_label, d.form_type, d.uin, d.accepted_on,
d.estimated_income, d.is_revoked, d.revoked_on, d.revoke_reason
FROM m_tds_declaration d
JOIN m_client c ON c.id = d.client_id
JOIN m_office o ON o.id = c.office_id
""" + where + " ORDER BY d.fy_label DESC, d.accepted_on DESC", params.toArray());
final List<Map<String, Object>> out = new ArrayList<>();
for (final Map<String, Object> r : rows) {
final Map<String, Object> o = new LinkedHashMap<>();
o.put("id", r.get("id"));
o.put("clientId", r.get("client_id"));
o.put("clientName", r.get("client_name"));
o.put("fy", r.get("fy_label"));
o.put("formType", r.get("form_type"));
o.put("uin", r.get("uin"));
o.put("acceptedOn", str(r.get("accepted_on")));
o.put("estimatedIncome", r.get("estimated_income"));
o.put("revoked", r.get("is_revoked"));
o.put("revokedOn", str(r.get("revoked_on")));
o.put("revokeReason", r.get("revoke_reason"));
out.add(o);
}
return gson.toJson(out);
}
/**
* Records a declaration. One live declaration per customer per year; the form must be the one the
* year's configuration names (Form 121 from 2026-27, 15G/15H before), the date must fall in the year
* and not in the future, and the customer must have a PAN - a declaration without one is invalid.
*/
@POST
@Path("declarations")
@Consumes({ MediaType.APPLICATION_JSON })
@Transactional
public String createDeclaration(final String body) {
final AppUser user = this.context.authenticatedUser();
user.validateHasPermissionTo("CREATE_" + DECLARATION);
final JsonObject root = this.fromJsonHelper.parse(body).getAsJsonObject();
final Long clientId = requiredLong(root, "clientId");
assertInScope(user, clientId);
final String fy = requiredText(root, "fy");
final String formType = requiredText(root, "formType").toUpperCase();
final LocalDate acceptedOn = requiredDate(root, "acceptedOn");
final String uin = optionalText(root, "uin");
final BigDecimal estimatedIncome = root.has("estimatedIncome") && !root.get("estimatedIncome").isJsonNull()
&& !root.get("estimatedIncome").getAsString().isBlank() ? root.get("estimatedIncome").getAsBigDecimal() : null;
final List<Map<String, Object>> cfg = jdbcTemplate.queryForList("SELECT declaration_form FROM m_tds_fy_config WHERE fy_label = ?",
fy);
if (cfg.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.fy.not.configured",
"Financial year " + fy + " is not set up under Organization › TDS Configuration.");
}
final String yearForm = (String) cfg.get(0).get("declaration_form");
final boolean merged = "121".equals(yearForm);
if (merged ? !"121".equals(formType) : !("15G".equals(formType) || "15H".equals(formType))) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.form.wrong.for.year",
merged ? "From " + fy + " the declaration is Form 121." : "For " + fy + " the declaration is Form 15G or 15H.");
}
final int startYear = Integer.parseInt(fy.substring(0, 4));
final LocalDate fyStart = LocalDate.of(startYear, 4, 1);
final LocalDate fyEnd = LocalDate.of(startYear + 1, 3, 31);
if (acceptedOn.isBefore(fyStart) || acceptedOn.isAfter(fyEnd)) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.date.outside.year",
"The acceptance date must fall inside " + fy + ".");
}
if (acceptedOn.isAfter(DateUtils.getBusinessLocalDate())) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.date.in.future",
"A declaration cannot be accepted on a future date.");
}
final Map<String, Object> person = jdbcTemplate.queryForMap("""
SELECT c.date_of_birth,
(SELECT k.pan_number FROM m_client_kyc k
WHERE k.client_id = c.id AND COALESCE(k.is_deleted, false) = false
ORDER BY k.id DESC LIMIT 1) AS pan
FROM m_client c WHERE c.id = ?
""", clientId);
if (!TdsSql.isWellFormedPan((String) person.get("pan"))) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.pan.required",
"A declaration is valid only with the customer's PAN. Record a PAN on the KYC first.");
}
if (!merged) {
final java.sql.Date dob = (java.sql.Date) person.get("date_of_birth");
final boolean senior = TdsSql.isSeniorInFy(dob == null ? null : dob.toLocalDate(), fyEnd);
if (senior != "15H".equals(formType)) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.form.wrong.for.age",
senior ? "This customer is 60 or over in " + fy + ", so the form is 15H." : "This customer is under 60 in " + fy
+ ", so the form is 15G.");
}
}
final Integer live = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM m_tds_declaration WHERE client_id = ? AND fy_label = ? AND is_revoked = false", Integer.class,
clientId, fy);
if (live != null && live > 0) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.duplicate",
"This customer already has a declaration on record for " + fy + ". Revoke it first to replace it.");
}
jdbcTemplate.update("""
INSERT INTO m_tds_declaration (client_id, fy_label, form_type, uin, accepted_on, estimated_income,
is_revoked, created_by, created_on)
VALUES (?, ?, ?, ?, ?, ?, false, ?, now())
""", clientId, fy, formType, uin, acceptedOn, estimatedIncome, user.getId());
return declarations(clientId, null);
}
/**
* Withdraws a declaration from a date. Interest credited from then on is deducted again; what was
* paid gross while it stood stays paid gross, because it was lawful at the time.
*/
@POST
@Path("declarations/{id}/revoke")
@Consumes({ MediaType.APPLICATION_JSON })
@Transactional
public String revokeDeclaration(@PathParam("id") final Long id, final String body) {
final AppUser user = this.context.authenticatedUser();
user.validateHasPermissionTo("UPDATE_" + DECLARATION);
final JsonObject root = this.fromJsonHelper.parse(body).getAsJsonObject();
final List<Long> owner = jdbcTemplate.queryForList("SELECT client_id FROM m_tds_declaration WHERE id = ? AND is_revoked = false",
Long.class, id);
if (owner.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.tds.declaration.not.found", "No live declaration " + id + ".");
}
assertInScope(user, owner.get(0));
final String reason = requiredText(root, "reason");
jdbcTemplate.update("""
UPDATE m_tds_declaration
SET is_revoked = true, revoked_on = ?, revoke_reason = ?, revoked_by = ?
WHERE id = ?
""", DateUtils.getBusinessLocalDate(), reason, user.getId(), id);
return declarations(owner.get(0), null);
}
// ─────────────────────────── challans ───────────────────────────
/** Every challan entered for the year, reversed ones included so the trail stays visible. */
@GET
@Path("challans")
public String challans(@QueryParam("fy") final String fy) {
this.context.authenticatedUser();
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
SELECT ch.id, ch.fy_label, ch.deduction_month, ch.amount, ch.challan_no, ch.bsr_code, ch.deposited_on,
ch.paid_from_gl_account_id, g.gl_code, g.name AS gl_name, ch.journal_transaction_id, ch.remarks,
ch.is_reversed
FROM m_tds_challan ch
JOIN acc_gl_account g ON g.id = ch.paid_from_gl_account_id
WHERE ch.fy_label = ?
ORDER BY ch.deduction_month, ch.deposited_on, ch.id
""", fy);
final List<Map<String, Object>> out = new ArrayList<>();
for (final Map<String, Object> r : rows) {
final Map<String, Object> o = new LinkedHashMap<>();
o.put("id", r.get("id"));
o.put("fy", r.get("fy_label"));
o.put("month", r.get("deduction_month"));
o.put("amount", r.get("amount"));
o.put("challanNo", r.get("challan_no"));
o.put("bsrCode", r.get("bsr_code"));
o.put("depositedOn", str(r.get("deposited_on")));
o.put("paidFromGlAccountId", r.get("paid_from_gl_account_id"));
o.put("paidFrom", r.get("gl_code") + " · " + r.get("gl_name"));
o.put("journalTransactionId", r.get("journal_transaction_id"));
o.put("remarks", r.get("remarks"));
o.put("reversed", r.get("is_reversed"));
out.add(o);
}
return gson.toJson(out);
}
/**
* Tax actually deducted, month by month, for the year: the TDS debits on savings accounts for FD/RD
* interest received there. This is what the challans must add up to.
*/
@GET
@Path("deducted")
public String deducted(@QueryParam("fy") final String fy) {
this.context.authenticatedUser();
requireFy(fy);
final List<Map<String, Object>> rows = jdbcTemplate.queryForList("""
SELECT TO_CHAR(d.deducted_on, 'YYYY-MM') AS month, SUM(d.amount) AS amount, COUNT(*) AS postings
FROM m_tds_deduction d
JOIN m_savings_account_transaction t ON t.id = d.savings_transaction_id AND t.is_reversed = false
WHERE d.fy_label = ?
GROUP BY 1 ORDER BY 1
""", fy);
// The business date, not the wall clock: whether a challan is overdue is judged on the day the
// books are on.
final Map<String, Object> out = new LinkedHashMap<>();
out.put("asAt", DateUtils.getBusinessLocalDate().toString());
out.put("months", rows);
return gson.toJson(out);
}
/** Accounts the tax can be paid out of: active, postable asset accounts (bank, cash). */
@GET
@Path("challans/template")
public String challanTemplate() {
this.context.authenticatedUser().validateHasPermissionTo("CREATE_" + CHALLAN);
final List<Map<String, Object>> accounts = jdbcTemplate.queryForList("""
SELECT id, gl_code AS "glCode", name FROM acc_gl_account
WHERE disabled = false AND account_usage = 1 AND classification_enum = 1
ORDER BY gl_code
""");
final Map<String, Object> out = new LinkedHashMap<>();
out.put("paidFromOptions", accounts);
return gson.toJson(out);
}
/**
* Records a remittance and posts it: Dr TDS payable / Cr the account paid from, at Head Office.
* Only Head Office remits - the bank files one return under one TAN.
*/
@POST
@Path("challans")
@Consumes({ MediaType.APPLICATION_JSON })
@Transactional
public String createChallan(final String body) {
final AppUser user = this.context.authenticatedUser();
user.validateHasPermissionTo("CREATE_" + CHALLAN);
assertHeadOffice(user);
final JsonObject root = this.fromJsonHelper.parse(body).getAsJsonObject();
final String fy = requireFy(requiredText(root, "fy"));
final String month = requiredText(root, "month");
if (!month.matches("\\d{4}-\\d{2}")) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.month.invalid", "Month must look like 2026-06.");
}
final int startYear = Integer.parseInt(fy.substring(0, 4));
final LocalDate monthStart = LocalDate.parse(month + "-01");
if (monthStart.isBefore(LocalDate.of(startYear, 4, 1)) || monthStart.isAfter(LocalDate.of(startYear + 1, 3, 1))) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.month.outside.year", "The month must fall inside " + fy + ".");
}
final BigDecimal amount = root.get("amount").getAsBigDecimal();
if (amount.signum() <= 0) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.amount.invalid", "Amount must be more than zero.");
}
final String challanNo = requiredText(root, "challanNo");
final String bsrCode = requiredText(root, "bsrCode");
if (!bsrCode.matches("\\d{7}")) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.bsr.invalid", "BSR code is 7 digits.");
}
final LocalDate depositedOn = requiredDate(root, "depositedOn");
if (depositedOn.isAfter(DateUtils.getBusinessLocalDate())) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.date.in.future", "Deposit date cannot be in the future.");
}
final Long paidFrom = requiredLong(root, "paidFromGlAccountId");
final String remarks = optionalText(root, "remarks");
final Integer dup = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM m_tds_challan WHERE challan_no = ? AND bsr_code = ? AND deposited_on = ? AND is_reversed = false",
Integer.class, challanNo, bsrCode, depositedOn);
if (dup != null && dup > 0) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.duplicate", "This challan is already on record.");
}
final Long tdsPayable = tdsPayableGl();
final long officeId = user.getOffice().getId();
final String currency = jdbcTemplate.queryForObject("SELECT code FROM m_organisation_currency ORDER BY id LIMIT 1", String.class);
final String txnId = "TDSCH-" + UUID.randomUUID().toString().substring(0, 18);
final String narration = "TDS remitted for " + month + " · challan " + challanNo + " · BSR " + bsrCode;
journalEntry(officeId, currency, tdsPayable, depositedOn, amount, true, txnId, narration, user.getId());
journalEntry(officeId, currency, paidFrom, depositedOn, amount, false, txnId, narration, user.getId());
jdbcTemplate.update("""
INSERT INTO m_tds_challan (fy_label, deduction_month, amount, challan_no, bsr_code, deposited_on,
paid_from_gl_account_id, office_id, journal_transaction_id, remarks,
is_reversed, created_by, created_on)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, false, ?, now())
""", fy, month, amount, challanNo, bsrCode, depositedOn, paidFrom, officeId, txnId, remarks, user.getId());
return challans(fy);
}
/** Undoes a challan entered in error: the entry is reversed with an opposite one, the row kept. */
@POST
@Path("challans/{id}/reverse")
@Transactional
public String reverseChallan(@PathParam("id") final Long id) {
final AppUser user = this.context.authenticatedUser();
user.validateHasPermissionTo("UPDATE_" + CHALLAN);
assertHeadOffice(user);
final List<Map<String, Object>> rows = jdbcTemplate.queryForList(
"SELECT fy_label, amount, paid_from_gl_account_id, office_id, journal_transaction_id, challan_no FROM m_tds_challan"
+ " WHERE id = ? AND is_reversed = false",
id);
if (rows.isEmpty()) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.not.found", "No live challan " + id + ".");
}
final Map<String, Object> ch = rows.get(0);
final String currency = jdbcTemplate.queryForObject("SELECT code FROM m_organisation_currency ORDER BY id LIMIT 1", String.class);
final LocalDate today = DateUtils.getBusinessLocalDate();
final String txnId = "TDSCHR-" + UUID.randomUUID().toString().substring(0, 17);
final String narration = "Reversal of TDS challan " + ch.get("challan_no");
final long officeId = ((Number) ch.get("office_id")).longValue();
final BigDecimal amount = (BigDecimal) ch.get("amount");
journalEntry(officeId, currency, tdsPayableGl(), today, amount, false, txnId, narration, user.getId());
journalEntry(officeId, currency, ((Number) ch.get("paid_from_gl_account_id")).longValue(), today, amount, true, txnId, narration,
user.getId());
jdbcTemplate.update("UPDATE m_tds_challan SET is_reversed = true WHERE id = ?", id);
return challans((String) ch.get("fy_label"));
}
// ─────────────────────────── helpers ───────────────────────────
/** Fineract convention: type_enum 2 = DEBIT, 1 = CREDIT. */
private void journalEntry(final long officeId, final String currency, final Long glAccountId, final LocalDate date,
final BigDecimal amount, final boolean debit, final String reference, final String narration, final Long userId) {
GLAccountTransactionGuard.assertPostable(jdbcTemplate, glAccountId);
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,
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, false, false, true, 0, 0, ?, ?,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)
""", officeId, glAccountId, currency, reference, date, date, debit ? 2 : 1, amount, narration, userId, userId, date);
}
private Long tdsPayableGl() {
final List<Long> gl = jdbcTemplate.queryForList("SELECT gl_account_id FROM m_tds_gl_config WHERE config_key = 'TDS_PAYABLE'",
Long.class);
if (gl.isEmpty() || gl.get(0) == null) {
throw new PlatformDataIntegrityException("error.msg.tds.payable.gl.not.configured",
"No TDS payable account is set. Choose one under Organization › TDS Configuration.");
}
return gl.get(0);
}
private void assertHeadOffice(final AppUser user) {
if (user.getOffice().getParent() != null) {
throw new PlatformDataIntegrityException("error.msg.tds.challan.head.office.only",
"TDS is remitted by Head Office. A branch login cannot record a challan.");
}
}
/** A user may act only on customers of their own office or the offices below it. */
private void assertInScope(final AppUser user, final Long clientId) {
final Integer n = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM m_client c JOIN m_office o ON o.id = c.office_id
WHERE c.id = ? AND o.hierarchy LIKE ?
""", Integer.class, clientId, user.getOffice().getHierarchy() + "%");
if (n == null || n == 0) {
throw new PlatformDataIntegrityException("error.msg.tds.client.out.of.scope",
"Customer " + clientId + " does not belong to your office.");
}
}
private static String requireFy(final String fy) {
if (fy == null || !fy.matches("\\d{4}-\\d{2}")) {
throw new PlatformDataIntegrityException("error.msg.tds.fy.invalid", "Financial year must look like 2026-27.");
}
return fy;
}
private static String str(final Object v) {
return v == null ? null : String.valueOf(v);
}
private static String optionalText(final JsonObject root, final String name) {
if (!root.has(name) || root.get(name).isJsonNull()) {
return null;
}
final String v = root.get(name).getAsString().trim();
return v.isEmpty() ? null : v;
}
private static String requiredText(final JsonObject root, final String name) {
final String v = optionalText(root, name);
if (v == null) {
throw new PlatformDataIntegrityException("error.msg.tds." + name + ".required", name + " is required.");
}
return v;
}
private static Long requiredLong(final JsonObject root, final String name) {
try {
return Long.valueOf(requiredText(root, name));
} catch (NumberFormatException e) {
throw new PlatformDataIntegrityException("error.msg.tds." + name + ".invalid", name + " must be a number.");
}
}
/** yyyy-MM-dd. */
private static LocalDate requiredDate(final JsonObject root, final String name) {
try {
return LocalDate.parse(requiredText(root, name));
} catch (DateTimeParseException e) {
throw new PlatformDataIntegrityException("error.msg.tds." + name + ".invalid", name + " must be a date like 2026-09-15.");
}
}
}
@@ -0,0 +1,27 @@
/**
* 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.tds.data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
/** A 15G / 15H / Form 121 declaration: one customer, one financial year, from the day it was accepted. */
public record TdsDeclarationData(Long id, Long clientId, String fy, String formType, String uin, LocalDate acceptedOn,
BigDecimal estimatedIncome, boolean revoked, LocalDate revokedOn, String revokeReason) implements Serializable {}
@@ -19,12 +19,13 @@
package org.apache.fineract.portfolio.tds.data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
/**
* A customer whose deposit interest the branch must consider for deduction under section 194A,
* together with the accounts and the interest actually credited to them.
* A customer whose deposit interest the branch must consider for deduction, together with the
* accounts and the interest actually credited to them.
*
* <p>
* The section bites on time deposits, so savings accounts are carried here as well but marked by
@@ -32,23 +33,31 @@ import java.util.List;
* separately. Sending only the fixed and recurring deposits would hide from the branch that the
* customer holds a savings balance at all, which is the first thing an officer checks when a
* customer disputes a deduction.
*
* <p>
* The customer here is the <em>deductee</em>: a minor's deposit is listed under the guardian and a
* joint deposit under its primary holder, because that is whose PAN the tax is deducted against.
*/
public record TdsDeducteeData(Long clientId, String customerId, String name, String pan, LocalDate dateOfBirth,
String branchName, String form15Type, List<TdsAccountData> accounts) implements Serializable {
String branchName, List<TdsDeclarationData> declarations, List<TdsAccountData> accounts) implements Serializable {
/**
* One deposit account and the interest posted to it.
* One deposit account, the interest posted to it and the TDS actually deducted from it.
*
* @param depositTypeCode
* Fineract's own code - {@code depositAccountType.fixedDeposit},
* {@code recurringDeposit} or {@code savingsDeposit}. This is what decides whether
* the charge applies at all, so it is sent as the platform states it rather than as
* a flag this report worked out for itself.
* @param clientId
* the deductee, which is the account holder unless the account is a minor's or joint
* @param holderClientId
* the account's own holder, shown when it differs from the deductee
*/
public record TdsAccountData(Long id, String accountNo, String depositTypeCode, String accountStatus,
Long clientId, LocalDate openedOn, List<TdsInterestCreditData> credits) implements Serializable {}
public record TdsAccountData(Long id, String accountNo, String depositTypeCode, Long clientId, Long holderClientId,
String holderName, String accountStatus, LocalDate openedOn, List<TdsInterestCreditData> credits,
List<TdsInterestCreditData> deductions) implements Serializable {}
/** One interest posting: the date it was credited and the amount. */
public record TdsInterestCreditData(LocalDate date, java.math.BigDecimal amount, String accountNo)
implements Serializable {}
/** One interest posting, or one TDS deduction: the date and the amount. */
public record TdsInterestCreditData(LocalDate date, BigDecimal amount, String accountNo) implements Serializable {}
}
@@ -0,0 +1,389 @@
/**
* 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.tds.service;
import jakarta.persistence.EntityManager;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fineract.accounting.journalentry.service.JournalEntryWritePlatformService;
import org.apache.fineract.infrastructure.core.exception.GeneralPlatformDomainRuleException;
import org.apache.fineract.portfolio.account.domain.AccountTransferType;
import org.apache.fineract.portfolio.savings.DepositAccountType;
import org.apache.fineract.portfolio.savings.domain.SavingsAccount;
import org.apache.fineract.portfolio.savings.domain.SavingsAccountRepositoryWrapper;
import org.apache.fineract.portfolio.savings.domain.SavingsAccountTransaction;
import org.apache.fineract.portfolio.savings.domain.SavingsAccountTransactionRepository;
import org.apache.fineract.portfolio.tax.domain.TaxComponent;
import org.apache.fineract.portfolio.tax.domain.TaxComponentRepository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
/**
* TDS on FD/RD interest, tracked and deducted where the interest is received.
*
* <p>
* Normally that is the customer's savings account: every time money moves from a fixed or recurring
* deposit into savings, the interest in it is recorded against the deductee (see
* {@link TdsSql#deducteeOf}) and any TDS due is debited from that savings account. The periodic
* interest sweep is all interest; a maturity or closure payout is principal and interest together, so
* only the interest not already received is counted. The FD and RD are not debited.
*
* <p>
* When a maturity or closure pays out in cash, by cheque or to a GL account instead, the interest never
* reaches savings, so it is tracked at the payout and the TDS comes out of the payout itself. A full
* reinvestment pays nothing out and is not taxed here.
*
* <p>
* The rules, all for one financial year and one deductee:
* <ol>
* <li>The FD/RD interest received, across every branch, is added up. The savings account's own interest
* is not - it is outside the charge.</li>
* <li>A declaration shields the interest received from the day it is accepted. Interest received
* before it stays liable.</li>
* <li>Nothing is deducted while the total stays within the threshold (senior or general).</li>
* <li>Once over it, the whole year's interest is liable - not merely the excess - at the PAN rate, or
* the higher rate without a valid PAN.</li>
* <li>What is deducted now is that liability less everything already deducted this year, so the credit
* that crosses the threshold catches up the earlier ones, and nothing is ever deducted twice.</li>
* </ol>
*
* <p>
* The tax is posted as a withhold-tax transaction through a tax component whose credit account is the
* TDS payable account set on Organization › TDS Configuration, so the passbook shows it and the
* account's own accounting writes Dr deposit liability / Cr TDS payable.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class SavingsInterestTdsService {
/** The tax component every TDS deduction is booked through. Kept in step with the GL setting. */
public static final String TDS_COMPONENT_NAME = "TDS on deposit interest";
private final JdbcTemplate jdbcTemplate;
private final TaxComponentRepository taxComponentRepository;
private final EntityManager entityManager;
private final SavingsAccountRepositoryWrapper savingsAccountRepository;
private final SavingsAccountTransactionRepository savingsAccountTransactionRepository;
private final JournalEntryWritePlatformService journalEntryWritePlatformService;
/**
* Called once a savings-to-savings transfer has been saved.
*
* @param deposit
* the credit on the receiving savings account
*/
public void onTransfer(final SavingsAccount from, final SavingsAccount to, final SavingsAccountTransaction deposit,
final AccountTransferType transferType) {
if (from == null || to == null || deposit == null || deposit.getId() == null || !isTimeDeposit(from)) {
return;
}
final DepositAccountType toType = to.depositAccountType();
if (toType == null || !toType.isSavingsDeposit()) {
return;
}
final boolean sweep = transferType != null && transferType.isInterestTransfer();
final BigDecimal interest = sweep ? deposit.getAmount()
: interestInPayout(from.getId(), postedFromDatabase(from.getId()), deposit.getAmount());
if (interest.compareTo(BigDecimal.ZERO) <= 0) {
return;
}
final LocalDate date = deposit.getTransactionDate();
final Year year = Year.of(date);
final Long deductee = deducteeOf(from, year);
if (deductee == null) {
return;
}
final Long receiptId = insertReceipt(deductee, to.getId(), deposit.getId(), from.getId(), sweep ? "INTEREST" : "PAYOUT", year,
date, interest);
final Due due = dueFor(deductee, year, date, BigDecimal.ZERO);
if (due == null) {
return;
}
final Set<Long> existingIds = new HashSet<>(to.findExistingTransactionIds());
final Set<Long> existingReversedIds = new HashSet<>(to.findExistingReversedTransactionIds());
final SavingsAccountTransaction tds = to.deductTds(date, due.amount(), Map.of(due.component(), due.amount()));
// Saved on its own first, as Fineract does for every new transaction: saving only the account
// merges it, and the id lands on the merged copy - this instance stays null, which broke both
// the deduction row and the journal entry's transaction reference.
this.savingsAccountTransactionRepository.saveAndFlush(tds);
this.savingsAccountRepository.saveAndFlush(to);
this.journalEntryWritePlatformService.createJournalEntriesForSavings(
to.deriveAccountingBridgeData(to.getCurrency().getCode(), existingIds, existingReversedIds, false, false));
recordDeduction(deductee, to.getId(), tds.getId(), from.getId(), receiptId, year, date, due);
}
/**
* Interest paid straight out of an FD/RD at maturity or closure - in cash, by cheque, or to a GL
* account - never reaches a savings account, so it is tracked here instead, and any TDS it makes due
* is taken out of the payout itself.
*
* <p>
* Call just before the closing withdrawal is worked out: the deduction is added to the deposit, so a
* withdrawal of the account balance pays out what is left. The deposit is not saved here - the
* closing withdrawal saves it and posts the deduction's accounting along with its own. Then call
* {@link #recordDirectPayout}.
*
* @param kind
* CASH or GL, for the tracking record
* @return what to record once the withdrawal exists, or null when the payout carried no interest
*/
public DirectPayout deductOnDirectPayout(final SavingsAccount deposit, final LocalDate date, final String kind) {
if (deposit == null || deposit.getId() == null || date == null || !isTimeDeposit(deposit)) {
return null;
}
// From memory: the maturity or pre-closure interest posted moments ago is not saved yet.
BigDecimal posted = BigDecimal.ZERO;
for (final SavingsAccountTransaction t : deposit.getTransactions()) {
if (t.isInterestPostingAndNotReversed() && !t.isReversalTransaction()) {
posted = posted.add(t.getAmount());
}
}
final BigDecimal interest = interestInPayout(deposit.getId(), posted, deposit.getAccountBalance());
if (interest.compareTo(BigDecimal.ZERO) <= 0) {
return null;
}
final Year year = Year.of(date);
final Long deductee = deducteeOf(deposit, year);
if (deductee == null) {
return null;
}
final Due due = dueFor(deductee, year, date, interest);
final SavingsAccountTransaction tds = due == null ? null
: deposit.deductTds(date, due.amount(), Map.of(due.component(), due.amount()));
return new DirectPayout(deposit.getId(), deductee, year, date, interest, kind, due, tds);
}
/**
* Records the tracking row and the deduction for a direct payout, once the closing withdrawal has been
* saved, and marks the deduction as already posted so the caller's own journal run does not post it a
* second time - the withdrawal posted it.
*/
public void recordDirectPayout(final DirectPayout payout, final SavingsAccountTransaction withdrawal,
final Set<Long> alreadyPostedTransactionIds) {
if (payout == null || withdrawal == null || withdrawal.getId() == null) {
return;
}
final Long receiptId = insertReceipt(payout.deductee(), payout.accountId(), withdrawal.getId(), payout.accountId(), payout.kind(),
payout.year(), payout.date(), payout.interest());
if (payout.tds() != null && payout.tds().getId() != null) {
recordDeduction(payout.deductee(), payout.accountId(), payout.tds().getId(), payout.accountId(), receiptId, payout.year(),
payout.date(), payout.due());
if (alreadyPostedTransactionIds != null) {
alreadyPostedTransactionIds.add(payout.tds().getId());
}
}
}
/** What {@link #deductOnDirectPayout} worked out, held until the withdrawal is saved. */
public record DirectPayout(Long accountId, Long deductee, Year year, LocalDate date, BigDecimal interest, String kind, Due due,
SavingsAccountTransaction tds) {}
/** TDS due now, and what it was worked out on. */
public record Due(BigDecimal amount, BigDecimal ratePercent, BigDecimal liableInterest, TaxComponent component) {}
/** One Indian financial year. */
public record Year(LocalDate start, LocalDate end, String label) {
static Year of(final LocalDate date) {
final int startYear = TdsSql.fyStartYear(date);
return new Year(LocalDate.of(startYear, 4, 1), LocalDate.of(startYear + 1, 3, 31), TdsSql.fyLabel(startYear));
}
}
private static boolean isTimeDeposit(final SavingsAccount account) {
final DepositAccountType type = account.depositAccountType();
return type != null && (type.isFixedDeposit() || type.isRecurringDeposit());
}
private Long deducteeOf(final SavingsAccount deposit, final Year year) {
return jdbcTemplate.queryForObject("SELECT " + TdsSql.deducteeOf("sa") + " FROM m_savings_account sa WHERE sa.id = ?", Long.class,
year.start(), deposit.getId());
}
private Long insertReceipt(final Long deductee, final Long receivingAccountId, final Long txnId, final Long sourceAccountId,
final String kind, final Year year, final LocalDate date, final BigDecimal interest) {
return jdbcTemplate.queryForObject("""
INSERT INTO m_tds_interest_receipt (deductee_client_id, savings_account_id, savings_transaction_id, source_account_id,
kind, fy_label, received_on, interest_amount, created_on)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, now()) RETURNING id
""", Long.class, deductee, receivingAccountId, txnId, sourceAccountId, kind, year.label(), date, interest);
}
private void recordDeduction(final Long deductee, final Long accountId, final Long txnId, final Long sourceAccountId,
final Long receiptId, final Year year, final LocalDate date, final Due due) {
jdbcTemplate.update("""
INSERT INTO m_tds_deduction (deductee_client_id, savings_account_id, savings_transaction_id, source_account_id, receipt_id,
fy_label, deducted_on, amount, rate_percentage, interest_base, created_on)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, now())
""", deductee, accountId, txnId, sourceAccountId, receiptId, year.label(), date, due.amount(), due.ratePercent(),
due.liableInterest());
}
/**
* The TDS due for the deductee now, or null when nothing is.
*
* @param extraInterest
* interest received on {@code date} that is not on record yet
*/
private Due dueFor(final Long deductee, final Year year, final LocalDate date, final BigDecimal extraInterest) {
final List<Map<String, Object>> cfgRows = jdbcTemplate.queryForList("""
SELECT threshold_general, threshold_senior, rate_pan_percentage, rate_no_pan_percentage, round_to
FROM m_tds_fy_config WHERE fy_label = ?
""", year.label());
if (cfgRows.isEmpty()) {
// Tracked, but not deducted: the TDS screens show the same gap and the administrator fixes it there.
log.warn("No TDS configuration for FY {}; interest for client {} tracked but not taxed", year.label(), deductee);
return null;
}
final Map<String, Object> cfg = cfgRows.get(0);
final List<LocalDate> accepted = jdbcTemplate.queryForList("""
SELECT accepted_on FROM m_tds_declaration
WHERE client_id = ? AND fy_label = ? AND is_revoked = false
ORDER BY accepted_on
""", LocalDate.class, deductee, year.label());
final LocalDate shieldedFrom = accepted.isEmpty() ? year.end().plusDays(1) : accepted.get(0);
final Map<String, Object> totals = jdbcTemplate.queryForMap("""
SELECT COALESCE(SUM(r.interest_amount), 0) AS interest,
COALESCE(SUM(CASE WHEN r.received_on < ? THEN r.interest_amount END), 0) AS liable
FROM m_tds_interest_receipt r
JOIN m_savings_account_transaction t ON t.id = r.savings_transaction_id AND t.is_reversed = false
WHERE r.deductee_client_id = ? AND r.fy_label = ? AND r.received_on <= ?
""", shieldedFrom, deductee, year.label(), date);
final BigDecimal yearInterest = ((BigDecimal) totals.get("interest")).add(extraInterest);
final BigDecimal liableInterest = ((BigDecimal) totals.get("liable"))
.add(date.isBefore(shieldedFrom) ? extraInterest : BigDecimal.ZERO);
final BigDecimal deducted = jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(d.amount), 0)
FROM m_tds_deduction d
JOIN m_savings_account_transaction t ON t.id = d.savings_transaction_id AND t.is_reversed = false
WHERE d.deductee_client_id = ? AND d.fy_label = ?
""", BigDecimal.class, deductee, year.label());
final Map<String, Object> person = jdbcTemplate.queryForMap("""
SELECT c.date_of_birth,
(SELECT k.pan_number FROM m_client_kyc k
WHERE k.client_id = c.id AND COALESCE(k.is_deleted, false) = false
ORDER BY k.id DESC LIMIT 1) AS pan
FROM m_client c WHERE c.id = ?
""", deductee);
final java.sql.Date dob = (java.sql.Date) person.get("date_of_birth");
final boolean senior = TdsSql.isSeniorInFy(dob == null ? null : dob.toLocalDate(), year.end());
final BigDecimal threshold = (BigDecimal) cfg.get(senior ? "threshold_senior" : "threshold_general");
if (yearInterest.compareTo(threshold) <= 0) {
return null;
}
final boolean panOk = TdsSql.isWellFormedPan((String) person.get("pan"));
final BigDecimal ratePercent = (BigDecimal) cfg.get(panOk ? "rate_pan_percentage" : "rate_no_pan_percentage");
final int roundTo = ((Number) cfg.get("round_to")).intValue();
final BigDecimal liability = TdsSql.roundToMultiple(liableInterest.multiply(ratePercent).movePointLeft(2), roundTo);
final BigDecimal already = deducted == null ? BigDecimal.ZERO : deducted;
final BigDecimal amount = liability.subtract(already);
if (amount.compareTo(BigDecimal.ZERO) <= 0) {
return null;
}
log.info("TDS {} due for client {} (FY {}: interest {}, liability {}, already deducted {})", amount, deductee, year.label(),
yearInterest, liability, already);
return new Due(amount, ratePercent, liableInterest, tdsComponent(ratePercent));
}
private BigDecimal postedFromDatabase(final Long accountId) {
return jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(amount), 0) FROM m_savings_account_transaction
WHERE savings_account_id = ? AND transaction_type_enum = ? AND is_reversed = false
""", BigDecimal.class, accountId, TdsSql.INTEREST_POSTING);
}
/**
* The interest inside a maturity or closure payout: interest posted on the deposit that has not been
* received already - through the interest sweep or an earlier payout. Capped at the payout.
*
* <p>
* On a premature closure the months already swept to savings stand as they were; only the interest
* for the days since is paid out now, and only that is counted.
*/
private BigDecimal interestInPayout(final Long sourceAccountId, final BigDecimal posted, final BigDecimal payout) {
final BigDecimal swept = jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(att.amount), 0)
FROM m_account_transfer_transaction att
JOIN m_account_transfer_details d ON d.id = att.account_transfer_details_id
WHERE d.from_savings_account_id = ? AND d.transfer_type = ? AND att.is_reversed = false
""", BigDecimal.class, sourceAccountId, AccountTransferType.INTEREST_TRANSFER.getValue());
final BigDecimal paidOut = jdbcTemplate.queryForObject("""
SELECT COALESCE(SUM(r.interest_amount), 0)
FROM m_tds_interest_receipt r
JOIN m_savings_account_transaction t ON t.id = r.savings_transaction_id AND t.is_reversed = false
WHERE r.source_account_id = ? AND r.kind <> 'INTEREST'
""", BigDecimal.class, sourceAccountId);
final BigDecimal unpaid = posted.subtract(swept).subtract(paidOut);
if (unpaid.compareTo(BigDecimal.ZERO) <= 0 || payout == null) {
return BigDecimal.ZERO;
}
return unpaid.min(payout);
}
/**
* The tax component the deduction is booked through, created on first use and re-pointed whenever
* the TDS payable account on the configuration screen changes.
*/
private TaxComponent tdsComponent(final BigDecimal ratePercent) {
final List<Long> gl = jdbcTemplate.queryForList("SELECT gl_account_id FROM m_tds_gl_config WHERE config_key = 'TDS_PAYABLE'",
Long.class);
if (gl.isEmpty() || gl.get(0) == null) {
throw new GeneralPlatformDomainRuleException("error.msg.tds.payable.gl.not.configured",
"TDS is due on this interest but no TDS payable account is set. Choose one under Organization › TDS Configuration.");
}
final Long glId = gl.get(0);
final List<Long> existing = jdbcTemplate.queryForList("SELECT id FROM m_tax_component WHERE name = ? ORDER BY id", Long.class,
TDS_COMPONENT_NAME);
final Long id;
boolean repointed = false;
if (existing.isEmpty()) {
id = jdbcTemplate.queryForObject("""
INSERT INTO m_tax_component (name, percentage, credit_account_type_enum, credit_account_id, start_date,
createdby_id, created_date, lastmodifiedby_id, lastmodified_date)
SELECT ?, ?, 2, ?, DATE '2000-01-01', MIN(u.id), now(), MIN(u.id), now() FROM m_appuser u
RETURNING id
""", Long.class, TDS_COMPONENT_NAME, ratePercent, glId);
} else {
id = existing.get(0);
repointed = jdbcTemplate.update("UPDATE m_tax_component SET credit_account_type_enum = 2, credit_account_id = ? WHERE id = ?"
+ " AND (credit_account_id IS DISTINCT FROM ? OR credit_account_type_enum IS DISTINCT FROM 2)", glId, id, glId) > 0;
}
final TaxComponent component = taxComponentRepository.findById(id).orElseThrow();
// Written behind JPA's back, so a copy already in this session would still credit the old account.
if (repointed) {
entityManager.refresh(component);
}
return component;
}
}
@@ -29,6 +29,8 @@ public interface TdsInterestReadPlatformService {
* @param financialYear
* the Indian financial year as its opening calendar year - 2026 means 1 Apr 2026 to
* 31 Mar 2027
* @param clientId
* one customer only, or null for everyone in the user's scope
*/
List<TdsDeducteeData> retrieveForFinancialYear(int financialYear);
List<TdsDeducteeData> retrieveForFinancialYear(int financialYear, Long clientId);
}
@@ -27,6 +27,8 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.apache.fineract.portfolio.tds.data.TdsDeclarationData;
import org.apache.fineract.portfolio.tds.data.TdsDeducteeData;
import org.apache.fineract.portfolio.tds.data.TdsDeducteeData.TdsAccountData;
import org.apache.fineract.portfolio.tds.data.TdsDeducteeData.TdsInterestCreditData;
@@ -35,8 +37,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Reads the interest the bank actually credited, so the deduction is worked out from the ledger
* rather than from a balance and a rate.
* Reads the interest the bank actually credited, and the TDS it actually deducted, so the register is
* worked out from the ledger rather than from a balance and a rate.
*/
@Service
@RequiredArgsConstructor
@@ -44,109 +46,150 @@ import org.springframework.transaction.annotation.Transactional;
public class TdsInterestReadPlatformServiceImpl implements TdsInterestReadPlatformService {
/**
* Interest posting - NOT a deposit, a withdrawal, a fee or a transfer.
* Every account, grouped under the client whose PAN carries its deduction, with what counts for TDS
* inside the year.
*
* <p>
* This single condition is what makes the figure an interest figure. A deposit is the
* customer's own money arriving and is not income; a withdrawal and a fee are not income
* either. Only what the bank itself credited as interest can be deducted against, so the
* transaction type is filtered here rather than being inferred later from an amount.
*
* @see org.apache.fineract.portfolio.savings.SavingsAccountTransactionType#INTEREST_POSTING
*/
private static final int INTEREST_POSTING = 3;
/**
* Every deposit the customer holds, with the interest credited to each inside the year.
* On a fixed or recurring deposit, "interest" is the FD/RD interest that reached the customer's
* savings account (m_tds_interest_receipt) and "deductions" the TDS debited there for it
* (m_tds_deduction) - TDS is tracked and taken where the interest is received, and the deposit
* itself is never debited. Interest still sitting in a deposit is not counted until it is paid out.
* Rows whose savings transaction has been reversed are left out: reversed money was never received.
*
* <p>
* Savings accounts are included deliberately. Section 194A does not reach them, and the caller
* keeps their interest out of the aggregate - but the branch still has to see that the customer
* holds one, and the row on screen shows it as exempt rather than leaving it out entirely.
* On a savings account, "interest" is its own interest postings. The charge does not reach them, and
* the caller keeps them out of the aggregate - but the branch still has to see them.
*
* <p>
* Reversed postings are excluded: a reversed posting was never income, and leaving it in would
* deduct tax on interest the customer never received.
* Scoped to the signed-in user's office and the offices below it, on the deductee's office. A branch
* login therefore receives only its own customers. Each customer still arrives with every one of
* their deposits, wherever held, because the threshold is tested on the bank as a whole.
*/
private static final String SQL = """
WITH acc AS (
SELECT sa.id, sa.account_no, sa.deposit_type_enum, sa.activatedon_date, sa.account_status,
sa.client_id AS holder_id, %s AS deductee_id
FROM m_savings_account sa
WHERE sa.client_id IS NOT NULL
),
lines AS (
SELECT t.savings_account_id AS account_id, 'C' AS kind, t.transaction_date AS d, t.amount AS amt
FROM m_savings_account_transaction t
JOIN m_savings_account s ON s.id = t.savings_account_id AND s.deposit_type_enum = 100
WHERE t.transaction_type_enum = ? AND t.is_reversed = false AND t.transaction_date BETWEEN ? AND ?
UNION ALL
SELECT r.source_account_id, 'C', r.received_on, r.interest_amount
FROM m_tds_interest_receipt r
JOIN m_savings_account_transaction t ON t.id = r.savings_transaction_id AND t.is_reversed = false
WHERE r.received_on BETWEEN ? AND ?
UNION ALL
SELECT dd.source_account_id, 'D', dd.deducted_on, dd.amount
FROM m_tds_deduction dd
JOIN m_savings_account_transaction t ON t.id = dd.savings_transaction_id AND t.is_reversed = false
WHERE dd.deducted_on BETWEEN ? AND ?
)
SELECT c.id AS client_id,
c.account_no AS customer_id,
c.display_name AS name,
c.date_of_birth AS date_of_birth,
k.pan_number AS pan,
k.form15_type AS form15_type,
(SELECT k.pan_number FROM m_client_kyc k
WHERE k.client_id = c.id AND COALESCE(k.is_deleted, false) = false
ORDER BY k.id DESC LIMIT 1) AS pan,
o.name AS branch_name,
sa.id AS account_id,
sa.account_no AS account_no,
sa.activatedon_date AS opened_on,
CASE sa.deposit_type_enum
a.id AS account_id,
a.account_no AS account_no,
a.activatedon_date AS opened_on,
a.account_status AS account_status,
a.holder_id AS holder_id,
h.display_name AS holder_name,
CASE a.deposit_type_enum
WHEN 100 THEN 'depositAccountType.savingsDeposit'
WHEN 200 THEN 'depositAccountType.fixedDeposit'
WHEN 300 THEN 'depositAccountType.recurringDeposit'
ELSE 'depositAccountType.unknown' END AS deposit_type_code,
t.transaction_date AS credit_date,
t.amount AS credit_amount
FROM m_savings_account sa
JOIN m_client c ON c.id = sa.client_id
LEFT JOIN m_office o ON o.id = c.office_id
LEFT JOIN m_client_kyc k ON k.client_id = c.id
LEFT JOIN m_savings_account_transaction t
ON t.savings_account_id = sa.id
AND t.transaction_type_enum = ?
AND t.is_reversed = false
AND t.transaction_date >= ?
AND t.transaction_date <= ?
WHERE sa.client_id IS NOT NULL
ORDER BY c.display_name, sa.account_no, t.transaction_date
""";
l.kind AS line_kind,
l.d AS txn_date,
l.amt AS txn_amount
FROM acc a
JOIN m_client c ON c.id = a.deductee_id
JOIN m_office o ON o.id = c.office_id
JOIN m_client h ON h.id = a.holder_id
LEFT JOIN lines l ON l.account_id = a.id
WHERE o.hierarchy LIKE ?
AND (CAST(? AS BIGINT) IS NULL OR c.id = CAST(? AS BIGINT))
ORDER BY c.display_name, a.account_no, l.d
""".formatted(TdsSql.deducteeOf("sa"));
private final JdbcTemplate jdbcTemplate;
private final PlatformSecurityContext context;
@Override
public List<TdsDeducteeData> retrieveForFinancialYear(final int financialYear) {
public List<TdsDeducteeData> retrieveForFinancialYear(final int financialYear, final Long onlyClientId) {
// The Indian financial year, 1 April to 31 March.
final LocalDate from = LocalDate.of(financialYear, 4, 1);
final LocalDate to = LocalDate.of(financialYear + 1, 3, 31);
final java.sql.Date f = java.sql.Date.valueOf(from);
final java.sql.Date t = java.sql.Date.valueOf(to);
final String hierarchy = this.context.authenticatedUser().getOffice().getHierarchy() + "%";
final Map<Long, Deductee> byClient = new LinkedHashMap<>();
jdbcTemplate.query(SQL, rs -> {
final long clientId = rs.getLong("client_id");
final Deductee deductee = byClient.computeIfAbsent(clientId,
id -> new Deductee(id, readString(rs, "customer_id"), readString(rs, "name"),
readString(rs, "pan"), readDate(rs, "date_of_birth"), readString(rs, "branch_name"),
readString(rs, "form15_type")));
id -> new Deductee(id, readString(rs, "customer_id"), readString(rs, "name"), readString(rs, "pan"),
readDate(rs, "date_of_birth"), readString(rs, "branch_name")));
final long accountId = rs.getLong("account_id");
final Account account = deductee.accounts.computeIfAbsent(accountId, id -> new Account(id,
readString(rs, "account_no"), readString(rs, "deposit_type_code"), readDate(rs, "opened_on")));
final Account account = deductee.accounts.computeIfAbsent(accountId,
id -> new Account(id, readString(rs, "account_no"), readString(rs, "deposit_type_code"), readLong(rs, "holder_id"),
readString(rs, "holder_name"), readString(rs, "account_status"), readDate(rs, "opened_on")));
// Null where the outer join found no posting inside the year: the account is still
// listed, it simply earned nothing in the window.
final java.sql.Date creditDate = rs.getDate("credit_date");
if (creditDate != null) {
final BigDecimal amount = rs.getBigDecimal("credit_amount");
account.credits.add(new TdsInterestCreditData(creditDate.toLocalDate(), amount, account.accountNo));
// Null where the outer join found nothing inside the year: the account is still listed, it
// simply earned nothing in the window.
final java.sql.Date date = rs.getDate("txn_date");
if (date != null) {
final BigDecimal amount = rs.getBigDecimal("txn_amount");
final TdsInterestCreditData line = new TdsInterestCreditData(date.toLocalDate(), amount, account.accountNo);
if ("D".equals(rs.getString("line_kind"))) {
account.deductions.add(line);
} else {
account.credits.add(line);
}
}
}, INTEREST_POSTING, java.sql.Date.valueOf(from), java.sql.Date.valueOf(to));
}, f, TdsSql.INTEREST_POSTING, f, t, f, t, f, t, hierarchy, onlyClientId, onlyClientId);
final Map<Long, List<TdsDeclarationData>> declarations = declarationsFor(TdsSql.fyLabel(financialYear));
final List<TdsDeducteeData> result = new ArrayList<>();
for (final Deductee d : byClient.values()) {
final List<TdsAccountData> accounts = new ArrayList<>();
for (final Account a : d.accounts.values()) {
// accountStatus is the RBI holding pattern (SINGLE / JOINT / MINOR) the caller uses
// to decide whose PAN carries the deduction. Fineract does not model it on the
// savings account, so it is left null and the caller falls back to the account
// holder rather than inventing a joint holder who may not exist.
accounts.add(
new TdsAccountData(a.id, a.accountNo, a.depositTypeCode, null, d.clientId, a.openedOn, a.credits));
accounts.add(new TdsAccountData(a.id, a.accountNo, a.depositTypeCode, d.clientId, a.holderId, a.holderName, a.accountStatus,
a.openedOn, a.credits, a.deductions));
}
result.add(new TdsDeducteeData(d.clientId, d.customerId, d.name, d.pan, d.dateOfBirth, d.branchName,
d.form15Type, accounts));
declarations.getOrDefault(d.clientId, List.of()), accounts));
}
return result;
}
private Map<Long, List<TdsDeclarationData>> declarationsFor(final String fy) {
final Map<Long, List<TdsDeclarationData>> out = new LinkedHashMap<>();
jdbcTemplate.query("""
SELECT id, client_id, fy_label, form_type, uin, accepted_on, estimated_income
FROM m_tds_declaration
WHERE fy_label = ? AND is_revoked = false
ORDER BY accepted_on
""", rs -> {
final TdsDeclarationData d = new TdsDeclarationData(rs.getLong("id"), rs.getLong("client_id"), rs.getString("fy_label"),
rs.getString("form_type"), rs.getString("uin"), readDate(rs, "accepted_on"), rs.getBigDecimal("estimated_income"),
false, null, null);
out.computeIfAbsent(d.clientId(), k -> new ArrayList<>()).add(d);
}, fy);
return out;
}
private static String readString(final ResultSet rs, final String column) {
try {
return rs.getString(column);
@@ -155,6 +198,15 @@ public class TdsInterestReadPlatformServiceImpl implements TdsInterestReadPlatfo
}
}
private static Long readLong(final ResultSet rs, final String column) {
try {
final long v = rs.getLong(column);
return rs.wasNull() ? null : v;
} catch (final SQLException e) {
throw new IllegalStateException("Could not read column " + column, e);
}
}
private static LocalDate readDate(final ResultSet rs, final String column) {
try {
final java.sql.Date value = rs.getDate(column);
@@ -173,18 +225,15 @@ public class TdsInterestReadPlatformServiceImpl implements TdsInterestReadPlatfo
private final String pan;
private final LocalDate dateOfBirth;
private final String branchName;
private final String form15Type;
private final Map<Long, Account> accounts = new LinkedHashMap<>();
private Deductee(Long clientId, String customerId, String name, String pan, LocalDate dateOfBirth,
String branchName, String form15Type) {
private Deductee(Long clientId, String customerId, String name, String pan, LocalDate dateOfBirth, String branchName) {
this.clientId = clientId;
this.customerId = customerId;
this.name = name;
this.pan = pan;
this.dateOfBirth = dateOfBirth;
this.branchName = branchName;
this.form15Type = form15Type;
}
}
@@ -193,13 +242,21 @@ public class TdsInterestReadPlatformServiceImpl implements TdsInterestReadPlatfo
private final Long id;
private final String accountNo;
private final String depositTypeCode;
private final Long holderId;
private final String holderName;
private final String accountStatus;
private final LocalDate openedOn;
private final List<TdsInterestCreditData> credits = new ArrayList<>();
private final List<TdsInterestCreditData> deductions = new ArrayList<>();
private Account(Long id, String accountNo, String depositTypeCode, LocalDate openedOn) {
private Account(Long id, String accountNo, String depositTypeCode, Long holderId, String holderName, String accountStatus,
LocalDate openedOn) {
this.id = id;
this.accountNo = accountNo;
this.depositTypeCode = depositTypeCode;
this.holderId = holderId;
this.holderName = holderName;
this.accountStatus = accountStatus;
this.openedOn = openedOn;
}
}
@@ -0,0 +1,95 @@
/**
* 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.tds.service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.regex.Pattern;
/**
* The TDS rules both the deduction and the report must agree on, kept in one place so the passbook
* and the register cannot drift apart.
*/
public final class TdsSql {
public static final int INTEREST_POSTING = 3;
public static final int WITHHOLD_TAX = 18;
public static final int FIXED_DEPOSIT = 200;
public static final int RECURRING_DEPOSIT = 300;
/** A well-formed PAN with a recognised holder type - the same test the screens apply. */
private static final Pattern PAN = Pattern.compile("^[A-Z]{5}[0-9]{4}[A-Z]$");
private static final String PAN_HOLDER_TYPES = "ABCFGHJLPT";
private TdsSql() {}
/**
* The client whose PAN carries the deduction for an account, as SQL over the alias given.
*
* <ul>
* <li>A minor's account follows the guardian - the interest is clubbed into the guardian's income.
* Minor means under 18 on the first day of the year, so one year has one deductee.</li>
* <li>A joint account follows the holder flagged primary - one deposit, one deductee.</li>
* <li>Anything else follows the account holder.</li>
* </ul>
*
* Takes one bind parameter: the financial year's first day.
*/
public static String deducteeOf(final String sa) {
return """
(CASE
WHEN UPPER(COALESCE(%1$s.account_status, '')) = 'MINOR' AND %1$s.guardian_client_id IS NOT NULL
AND (%1$s.minor_date_of_birth IS NULL
OR %1$s.minor_date_of_birth > CAST(? AS DATE) - INTERVAL '18 years')
THEN %1$s.guardian_client_id
WHEN UPPER(COALESCE(%1$s.account_status, '')) = 'JOINT'
THEN COALESCE((SELECT MIN(j.client_id) FROM m_savings_account_joint_holders j
WHERE j.savings_account_id = %1$s.id AND j.is_primary = true), %1$s.client_id)
ELSE %1$s.client_id
END)""".formatted(sa);
}
public static boolean isWellFormedPan(final String pan) {
final String p = pan == null ? "" : pan.trim().toUpperCase();
return PAN.matcher(p).matches() && PAN_HOLDER_TYPES.indexOf(p.charAt(3)) >= 0;
}
/** Age reached by the last day of the year: 60 at any point in it makes a senior citizen. */
public static boolean isSeniorInFy(final LocalDate dateOfBirth, final LocalDate fyEnd) {
return dateOfBirth != null && !dateOfBirth.plusYears(60).isAfter(fyEnd);
}
public static int fyStartYear(final LocalDate date) {
return date.getMonthValue() >= 4 ? date.getYear() : date.getYear() - 1;
}
/** '2026-27' for any date from 1 Apr 2026 to 31 Mar 2027. */
public static String fyLabel(final int startYear) {
return startYear + "-" + String.format("%02d", (startYear + 1) % 100);
}
public static BigDecimal roundToMultiple(final BigDecimal value, final int to) {
if (to <= 1) {
return value.setScale(0, RoundingMode.HALF_UP);
}
final BigDecimal step = BigDecimal.valueOf(to);
return value.divide(step, 0, RoundingMode.HALF_UP).multiply(step);
}
}
@@ -46,7 +46,7 @@ fineract.security.oauth2.client.registrations.frontend-client.require-authorizat
fineract.tenant.host=${FINERACT_DEFAULT_TENANTDB_HOSTNAME:localhost}
fineract.tenant.port=${FINERACT_DEFAULT_TENANTDB_PORT:5432}
fineract.tenant.username=${FINERACT_DEFAULT_TENANTDB_UID:postgres}
fineract.tenant.password=${FINERACT_DEFAULT_TENANTDB_PWD:313863}
fineract.tenant.password=${FINERACT_DEFAULT_TENANTDB_PWD:Keshav@898966}
fineract.tenant.parameters=${FINERACT_DEFAULT_TENANTDB_CONN_PARAMS:}
fineract.tenant.timezone=${FINERACT_DEFAULT_TENANTDB_TIMEZONE:Asia/Kolkata}
fineract.tenant.identifier=${FINERACT_DEFAULT_TENANTDB_IDENTIFIER:default}
@@ -415,7 +415,7 @@ server.tomcat.mbeanregistry.enabled=${FINERACT_SERVER_TOMCAT_MBEANREGISTRY_ENABL
spring.datasource.hikari.driverClassName=${FINERACT_HIKARI_DRIVER_SOURCE_CLASS_NAME:org.postgresql.Driver}
spring.datasource.hikari.jdbcUrl=${FINERACT_HIKARI_JDBC_URL:jdbc:postgresql://localhost:5432/fineract_tenants}
spring.datasource.hikari.username=${FINERACT_HIKARI_USERNAME:postgres}
spring.datasource.hikari.password=${FINERACT_HIKARI_PASSWORD:313863}
spring.datasource.hikari.password=${FINERACT_HIKARI_PASSWORD:Keshav@898966}
spring.datasource.hikari.minimumIdle=${FINERACT_HIKARI_MINIMUM_IDLE:3}
spring.datasource.hikari.maximumPoolSize=${FINERACT_HIKARI_MAXIMUM_POOL_SIZE:10}
spring.datasource.hikari.idleTimeout=${FINERACT_HIKARI_IDLE_TIMEOUT:60000}
@@ -163,5 +163,13 @@
<include file="parts/0588_add_premature_closure_reason.xml" relativeToChangelogFile="true"/>
<include file="parts/0589_savings_interest_posting_report.xml" relativeToChangelogFile="true"/>
<include file="parts/0590_savings_interest_posting_report_by_branch.xml" relativeToChangelogFile="true"/>
<include file="parts/0588_persist_manually_enabled_maker_checker_permissions.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/0592_tds_declarations_and_challans.xml" relativeToChangelogFile="true"/>
<include file="parts/0593_tds_interest_receipts_and_deductions.xml" relativeToChangelogFile="true"/>
<include file="parts/0594_recurring_deposit_product_rules.xml" relativeToChangelogFile="true"/>
<include file="parts/0595_recurring_deposit_lien_percentage.xml" relativeToChangelogFile="true"/>
<include file="parts/0596_recurring_deposit_missed_installment_penalty.xml" relativeToChangelogFile="true"/>
<include file="parts/0597_enable_recurring_deposit_product_maker_checker.xml" relativeToChangelogFile="true"/>
<include file="parts/0598_recurring_deposit_extend_tenure_permission.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>
@@ -1,73 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<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.1.xsd">
<!-- Converts manually-applied Configure Maker Checker Tasks changes into a repeatable migration.
During Admin -> Organization and Admin -> System testing, can_maker_checker was switched on
(via System -> Configure Maker Checker Tasks) for the 28 permissions below, directly in the
dev database - none of that was ever captured by a migration, so a fresh/other environment
restored from this changelog history would come up with every one of them still at its
originally-seeded false value. Every code here was independently confirmed, via read-only
inspection of both its origin changeset and the live database, to be seeded can_maker_checker
= false and currently true in the running dev DB with no existing changeset already covering
the flip (the one precedent for this pattern, DELETE_OFFICE, was flipped by changeset
0538_enable_maker_checker_for_delete_office and is deliberately left untouched here).
This changeset only ever moves can_maker_checker from false to true for these exact codes -
entity_name, action_name, grouping and every other column are left exactly as their origin
changeset defined them (including the pre-existing DELETE_ACCOUNTNUMBERFORMAT entity_name
drift, which is out of scope for this change and is not corrected here). No _CHECKER row is
touched: those already exist for every code below (added earlier by 0583/0586, or by base
Fineract for the stock codes), and can_maker_checker is not a column on a _CHECKER row.
Grouped by the screen each permission belongs to:
- Currency Configuration: UPDATE_CURRENCY
- Manage Funds: CREATE_FUND
- Working Days: UPDATE_WORKINGDAYS
- Payment Type: CREATE_PAYMENTTYPE, UPDATE_PAYMENTTYPE, DELETE_PAYMENTTYPE
- Sponsor Banks: CREATE_SPONSORBANK, UPDATE_SPONSORBANK
- Branch Profile: UPDATE_BRANCHPROFILE
- Manage Data Tables: CREATE_DATATABLE, UPDATE_DATATABLE, DELETE_DATATABLE
- Manage Codes: CREATE_CODE, UPDATE_CODE, DELETE_CODE,
CREATE_CODEVALUE, UPDATE_CODEVALUE, DELETE_CODEVALUE
- Manage Reports: CREATE_REPORT, UPDATE_REPORT, DELETE_REPORT
- Manage Hooks: CREATE_HOOK, UPDATE_HOOK, DELETE_HOOK
- Account Number Preferences: CREATE_ACCOUNTNUMBERFORMAT, DELETE_ACCOUNTNUMBERFORMAT
- Manage User Agreement: CREATE_USERAGREEMENT
- Manage Jobs (COB Workflow Step Reorder): UPDATE_BATCH_BUSINESS_STEP
Deliberately NOT included (confirmed still false, or out of scope, and left untouched):
- UPDATE_PERMISSION, UPDATE_CONFIGURATION (the Configure Maker Checker Tasks self-lockout
exclusion added by PermissionReadPlatformServiceImpl stays in effect; these remain false)
- UPDATE_SPONSORDDGLMAPPING, all Entity-to-Entity Mapping, External Services and Manage
Survey permissions (confirmed still false - never actually toggled on)
- CREATE_ROLE/UPDATE_ROLE/DELETE_ROLE/etc., CREATE_GLACCOUNT, CREATE_CHARGE,
CREATE_LOANPRODUCT, CREATE_SAVINGSPRODUCT and other permissions observed to already be
true in the live DB but belonging to Accounting/Products/Roles modules, not Admin ->
Organization or Admin -> System - out of scope for this change and left as pre-existing
drift for a separate decision. -->
<changeSet id="0588_persist_manually_enabled_maker_checker_permissions" author="cbs-anshul">
<update tableName="m_permission">
<column name="can_maker_checker" valueBoolean="true"/>
<where>code IN (
'UPDATE_CURRENCY',
'CREATE_FUND',
'UPDATE_WORKINGDAYS',
'CREATE_PAYMENTTYPE', 'UPDATE_PAYMENTTYPE', 'DELETE_PAYMENTTYPE',
'CREATE_SPONSORBANK', 'UPDATE_SPONSORBANK',
'UPDATE_BRANCHPROFILE',
'CREATE_DATATABLE', 'UPDATE_DATATABLE', 'DELETE_DATATABLE',
'CREATE_CODE', 'UPDATE_CODE', 'DELETE_CODE',
'CREATE_CODEVALUE', 'UPDATE_CODEVALUE', 'DELETE_CODEVALUE',
'CREATE_REPORT', 'UPDATE_REPORT', 'DELETE_REPORT',
'CREATE_HOOK', 'UPDATE_HOOK', 'DELETE_HOOK',
'CREATE_ACCOUNTNUMBERFORMAT', 'DELETE_ACCOUNTNUMBERFORMAT',
'CREATE_USERAGREEMENT',
'UPDATE_BATCH_BUSINESS_STEP'
)</where>
</update>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<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.1.xsd">
<!--
Cash taken over a counter belongs to the drawer and the branch that took it, not to whoever the
same login is allocated to today.
m_cashiers.created_at: a cashier position is built from the counter deposits and withdrawals of
the cashier's login, so a person moved from one branch's teller to another's carried every
rupee they had ever taken into the new drawer. The position now counts only what was taken
once the allocation existed. Existing rows take the time their ALLOCATECASHIER command ran;
a row with no such command stays NULL and keeps its whole history, as before.
m_cashier_deposit_request.counter_office_id: savings deposits are submitted with no office_id,
and the day close counted every such deposit at every branch. The counter's office is now
stored at submit. Existing rows take the teller office of the submitter's allocation if it
already existed when the deposit was submitted, otherwise the submitter's own office.
-->
<changeSet id="0591_cashier_created_at" author="fineract">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="m_cashiers" columnName="created_at"/>
</not>
</preConditions>
<addColumn tableName="m_cashiers">
<column name="created_at" type="TIMESTAMP"/>
</addColumn>
<sql>
UPDATE m_cashiers mc
SET created_at = (SELECT CAST(MIN(cs.made_on_date_utc) AS TIMESTAMP)
FROM m_portfolio_command_source cs
WHERE cs.entity_name = 'TELLER' AND cs.action_name = 'ALLOCATECASHIER'
AND cs.subresource_id = mc.id)
</sql>
<addDefaultValue tableName="m_cashiers" columnName="created_at" columnDataType="TIMESTAMP"
defaultValueComputed="CURRENT_TIMESTAMP"/>
</changeSet>
<changeSet id="0591_deposit_request_counter_office" author="fineract">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="m_cashier_deposit_request" columnName="counter_office_id"/>
</not>
</preConditions>
<addColumn tableName="m_cashier_deposit_request">
<column name="counter_office_id" type="BIGINT"/>
</addColumn>
<sql>
UPDATE m_cashier_deposit_request r
SET counter_office_id = COALESCE(
(SELECT t.office_id FROM m_appuser au
JOIN m_cashiers c ON c.staff_id = au.staff_id
JOIN m_tellers t ON t.id = c.teller_id
WHERE au.id = r.cashier_id
AND (c.created_at IS NULL OR r.submitted_at IS NULL OR r.submitted_at >= c.created_at)
LIMIT 1),
(SELECT au.office_id FROM m_appuser au WHERE au.id = r.cashier_id),
r.office_id)
</sql>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<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.1.xsd">
<!-- Same pattern as 0588_persist_manually_enabled_maker_checker_permissions: converts a
manually-applied Configure Maker Checker Tasks change into a repeatable migration, this time
for the Teller/Cashier module. Found by diffing can_maker_checker across every permission code
common to fineract_lincpay and a reference environment (fineract_default) - these 4 were true
in the reference but still seeded false here, confirming they were toggled on manually there
and never captured for any other environment (including this one and UAT).
Grouped by the screen each permission belongs to (Organization -> Manage Tellers -> allocate/
settle cash for a cashier):
ALLOCATECASHIER_TELLER, ALLOCATECASHTOCASHIER_TELLER,
SETTLECASHFROMCASHIER_TELLER, UPDATECASHIERALLOCATION_TELLER
No _CHECKER row is touched: those already exist for every code below (seeded by base
Fineract), and can_maker_checker is not a column on a _CHECKER row. -->
<changeSet id="0592_enable_teller_cashier_maker_checker" author="cbs-nitesh">
<update tableName="m_permission">
<column name="can_maker_checker" valueBoolean="true"/>
<where>code IN (
'ALLOCATECASHIER_TELLER',
'ALLOCATECASHTOCASHIER_TELLER',
'SETTLECASHFROMCASHIER_TELLER',
'UPDATECASHIERALLOCATION_TELLER'
)</where>
</update>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,217 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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">
<!--
The two records TDS on deposit interest was missing.
m_tds_declaration - a 15G / 15H / Form 121 declaration, one per customer per financial year.
The KYC record only ever carried the form type and a year, so a declaration given in
September shielded interest back to April, and nothing marked a new year as needing a new
form. A declaration operates from the day the branch accepts it, for that year only, so both
the year and the acceptance date are kept here.
m_tds_challan - tax actually remitted to the Government. The remittance report used to make
challan numbers, BSR codes and deposit dates up; every row here is one the bank entered,
posted against the TDS payable account.
Constraints sit inside createTable: a separate tableExists-guarded changeSet would see the
table already present and skip them.
-->
<changeSet author="fineract" id="0592-1-create-tds-declaration">
<preConditions onFail="MARK_RAN">
<not><tableExists tableName="m_tds_declaration"/></not>
</preConditions>
<createTable tableName="m_tds_declaration">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="client_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_declaration_client"
referencedTableName="m_client" referencedColumnNames="id"/>
</column>
<!-- '2026-27'. -->
<column name="fy_label" type="VARCHAR(7)">
<constraints nullable="false"/>
</column>
<!-- 15G, 15H or 121. -->
<column name="form_type" type="VARCHAR(5)">
<constraints nullable="false"/>
</column>
<column name="uin" type="VARCHAR(30)"/>
<!-- The day the branch accepted it. Interest credited before this date is not shielded. -->
<column name="accepted_on" type="DATE">
<constraints nullable="false"/>
</column>
<column name="estimated_income" type="DECIMAL(19,6)"/>
<column name="is_revoked" type="BOOLEAN" defaultValueBoolean="false">
<constraints nullable="false"/>
</column>
<column name="revoked_on" type="DATE"/>
<column name="revoke_reason" type="VARCHAR(500)"/>
<column name="created_by" type="BIGINT"/>
<column name="created_on" type="TIMESTAMP WITH TIME ZONE"/>
<column name="revoked_by" type="BIGINT"/>
</createTable>
<createIndex tableName="m_tds_declaration" indexName="idx_tds_declaration_client_fy">
<column name="client_id"/>
<column name="fy_label"/>
</createIndex>
</changeSet>
<changeSet author="fineract" id="0592-2-create-tds-challan">
<preConditions onFail="MARK_RAN">
<not><tableExists tableName="m_tds_challan"/></not>
</preConditions>
<createTable tableName="m_tds_challan">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="fy_label" type="VARCHAR(7)">
<constraints nullable="false"/>
</column>
<!-- Month the tax was deducted in, '2026-06'. The due date follows from it. -->
<column name="deduction_month" type="VARCHAR(7)">
<constraints nullable="false"/>
</column>
<column name="amount" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<column name="challan_no" type="VARCHAR(30)">
<constraints nullable="false"/>
</column>
<column name="bsr_code" type="VARCHAR(10)">
<constraints nullable="false"/>
</column>
<column name="deposited_on" type="DATE">
<constraints nullable="false"/>
</column>
<!-- Bank or cash account the tax was paid out of: Dr TDS payable / Cr this account. -->
<column name="paid_from_gl_account_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_challan_paid_from"
referencedTableName="acc_gl_account" referencedColumnNames="id"/>
</column>
<column name="office_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_challan_office"
referencedTableName="m_office" referencedColumnNames="id"/>
</column>
<!-- acc_gl_journal_entry.transaction_id of the remittance entry. -->
<column name="journal_transaction_id" type="VARCHAR(50)"/>
<column name="remarks" type="VARCHAR(500)"/>
<column name="is_reversed" type="BOOLEAN" defaultValueBoolean="false">
<constraints nullable="false"/>
</column>
<column name="created_by" type="BIGINT"/>
<column name="created_on" type="TIMESTAMP WITH TIME ZONE"/>
</createTable>
<createIndex tableName="m_tds_challan" indexName="idx_tds_challan_fy">
<column name="fy_label"/>
</createIndex>
</changeSet>
<changeSet author="fineract" id="0592-3-tds-declaration-challan-permissions">
<preConditions onFail="MARK_RAN">
<and>
<tableExists tableName="m_permission"/>
<sqlCheck expectedResult="0">
SELECT COUNT(*) FROM m_permission
WHERE code IN ('CREATE_TDSDECLARATION', 'UPDATE_TDSDECLARATION', 'CREATE_TDSCHALLAN', 'UPDATE_TDSCHALLAN')
</sqlCheck>
</and>
</preConditions>
<insert tableName="m_permission">
<column name="grouping" value="portfolio"/>
<column name="code" value="CREATE_TDSDECLARATION"/>
<column name="entity_name" value="TDSDECLARATION"/>
<column name="action_name" value="CREATE"/>
<column name="can_maker_checker" valueBoolean="false"/>
</insert>
<insert tableName="m_permission">
<column name="grouping" value="portfolio"/>
<column name="code" value="UPDATE_TDSDECLARATION"/>
<column name="entity_name" value="TDSDECLARATION"/>
<column name="action_name" value="UPDATE"/>
<column name="can_maker_checker" valueBoolean="false"/>
</insert>
<insert tableName="m_permission">
<column name="grouping" value="organisation"/>
<column name="code" value="CREATE_TDSCHALLAN"/>
<column name="entity_name" value="TDSCHALLAN"/>
<column name="action_name" value="CREATE"/>
<column name="can_maker_checker" valueBoolean="false"/>
</insert>
<insert tableName="m_permission">
<column name="grouping" value="organisation"/>
<column name="code" value="UPDATE_TDSCHALLAN"/>
<column name="entity_name" value="TDSCHALLAN"/>
<column name="action_name" value="UPDATE"/>
<column name="can_maker_checker" valueBoolean="false"/>
</insert>
</changeSet>
<changeSet author="fineract" id="0592-4-grant-tds-declaration-challan-permissions">
<preConditions onFail="MARK_RAN">
<and>
<tableExists tableName="m_role_permission"/>
<sqlCheck expectedResult="0">
SELECT COUNT(*) FROM m_role_permission rp
JOIN m_permission p ON p.id = rp.permission_id
WHERE p.code IN ('CREATE_TDSDECLARATION', 'UPDATE_TDSDECLARATION', 'CREATE_TDSCHALLAN', 'UPDATE_TDSCHALLAN')
</sqlCheck>
</and>
</preConditions>
<!-- Declarations are taken at the counter, so every role records them. Challans are a Head
Office remittance, so only the roles that hold the TDS configuration post them. -->
<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 ('CREATE_TDSDECLARATION', 'UPDATE_TDSDECLARATION');
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 ('CREATE_TDSCHALLAN', 'UPDATE_TDSCHALLAN')
AND (LOWER(r.name) LIKE '%manager%' OR LOWER(r.name) = 'super user');
</sql>
</changeSet>
<changeSet author="fineract" id="0592-5-carry-over-kyc-declarations">
<preConditions onFail="MARK_RAN">
<tableExists tableName="m_tds_declaration"/>
</preConditions>
<!-- Only KYC rows that were actually switched on and name a year. The acceptance date was never
recorded, so the year's first day stands in, which is what the screens assumed until now. -->
<sql>
INSERT INTO m_tds_declaration (client_id, fy_label, form_type, accepted_on, is_revoked, created_on)
SELECT k.client_id, k.form15_fy, UPPER(k.form15_type),
TO_DATE(SUBSTRING(k.form15_fy FROM 1 FOR 4) || '-04-01', 'YYYY-MM-DD'), false, now()
FROM m_client_kyc k
WHERE k.form15_applicable = true
AND k.form15_fy ~ '^[0-9]{4}-[0-9]{2}$'
AND UPPER(k.form15_type) IN ('15G', '15H', '121')
AND COALESCE(k.is_deleted, false) = false;
</sql>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,143 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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">
<!--
TDS on FD/RD interest is tracked and deducted where the interest is received: the customer's
savings account. The FD and RD accounts themselves are left alone.
m_tds_interest_receipt - one row per credit into a savings account that carried FD/RD interest:
the periodic interest sweep in full, or the interest part of a maturity / closure payout. This
is the running total the threshold is tested against. A savings credit is otherwise just a
deposit, so without this record there is no telling interest from the customer's own money.
m_tds_deduction - one row per TDS debit on a savings account, tied to the deductee, so the
tax already taken this year is known per customer.
A row only counts while its savings transaction stands - reversing the transaction takes it out.
-->
<changeSet author="fineract" id="0593-1-create-tds-interest-receipt">
<preConditions onFail="MARK_RAN">
<not><tableExists tableName="m_tds_interest_receipt"/></not>
</preConditions>
<createTable tableName="m_tds_interest_receipt">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<!-- Whose PAN the interest is taxed against: the FD/RD's holder, guardian or primary joint holder. -->
<column name="deductee_client_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_receipt_client"
referencedTableName="m_client" referencedColumnNames="id"/>
</column>
<!-- The savings account the interest was credited to. -->
<column name="savings_account_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_receipt_savings"
referencedTableName="m_savings_account" referencedColumnNames="id"/>
</column>
<column name="savings_transaction_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_receipt_txn"
referencedTableName="m_savings_account_transaction" referencedColumnNames="id"/>
</column>
<!-- The FD or RD the interest came from. -->
<column name="source_account_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_receipt_source"
referencedTableName="m_savings_account" referencedColumnNames="id"/>
</column>
<!-- INTEREST: a periodic interest sweep. PAYOUT: the interest part of a maturity or closure payout. -->
<column name="kind" type="VARCHAR(10)">
<constraints nullable="false"/>
</column>
<column name="fy_label" type="VARCHAR(7)">
<constraints nullable="false"/>
</column>
<column name="received_on" type="DATE">
<constraints nullable="false"/>
</column>
<column name="interest_amount" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<column name="created_on" type="TIMESTAMP WITH TIME ZONE"/>
</createTable>
<createIndex tableName="m_tds_interest_receipt" indexName="idx_tds_receipt_deductee_fy">
<column name="deductee_client_id"/>
<column name="fy_label"/>
</createIndex>
<createIndex tableName="m_tds_interest_receipt" indexName="idx_tds_receipt_source">
<column name="source_account_id"/>
</createIndex>
</changeSet>
<changeSet author="fineract" id="0593-2-create-tds-deduction">
<preConditions onFail="MARK_RAN">
<not><tableExists tableName="m_tds_deduction"/></not>
</preConditions>
<createTable tableName="m_tds_deduction">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<column name="deductee_client_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_deduction_client"
referencedTableName="m_client" referencedColumnNames="id"/>
</column>
<column name="savings_account_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_deduction_savings"
referencedTableName="m_savings_account" referencedColumnNames="id"/>
</column>
<!-- The withhold-tax debit on the savings account. -->
<column name="savings_transaction_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_deduction_txn"
referencedTableName="m_savings_account_transaction" referencedColumnNames="id"/>
</column>
<!-- The FD or RD whose interest triggered it. -->
<column name="source_account_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_deduction_source"
referencedTableName="m_savings_account" referencedColumnNames="id"/>
</column>
<column name="receipt_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_tds_deduction_receipt"
referencedTableName="m_tds_interest_receipt" referencedColumnNames="id"/>
</column>
<column name="fy_label" type="VARCHAR(7)">
<constraints nullable="false"/>
</column>
<column name="deducted_on" type="DATE">
<constraints nullable="false"/>
</column>
<column name="amount" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<column name="rate_percentage" type="DECIMAL(9,4)">
<constraints nullable="false"/>
</column>
<!-- Interest the year's liability was worked out on, at the time. -->
<column name="interest_base" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<column name="created_on" type="TIMESTAMP WITH TIME ZONE"/>
</createTable>
<createIndex tableName="m_tds_deduction" indexName="idx_tds_deduction_deductee_fy">
<column name="deductee_client_id"/>
<column name="fy_label"/>
</createIndex>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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">
<!--
Recurring deposit product settings that used to be stored and ignored.
1. Interest Calculation Type gains a "Simple" option. A recurring deposit opened under a product set to
Simple never compounds its interest. The choice is copied onto the account when it opens
(is_simple_interest) and kept for its life, like its chart and compounding period, so a later product
edit cannot change what an open deposit was promised. Every existing account defaults to false -
compounding - which is how all of them were calculated until now, so nothing already open moves.
2. RD Auto Debit job: collects each due installment of a deposit opened with Auto Debit from the
Savings account linked to it.
-->
<changeSet author="fineract" id="0594-1-savings-account-is-simple-interest">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="m_savings_account" columnName="is_simple_interest"/>
</not>
</preConditions>
<addColumn tableName="m_savings_account">
<column name="is_simple_interest" type="BOOLEAN" defaultValueBoolean="false">
<constraints nullable="false"/>
</column>
</addColumn>
</changeSet>
<changeSet author="fineract" id="0594-2-interest-calculation-type-simple">
<!-- Matched by label in code (RecurringDepositProductRules), so a tenant that already added its own
"Simple" value keeps it and no duplicate is created. -->
<sql>
INSERT INTO m_code_value (code_id, code_value, code_description, order_position, code_score, is_active, is_mandatory)
SELECT c.id, 'Simple', 'Simple', 3, NULL, true, false FROM m_code c
WHERE c.code_name = 'InterestCalculationTypeOption'
AND NOT EXISTS (SELECT 1 FROM m_code_value v WHERE v.code_id = c.id AND LOWER(v.code_value) = 'simple');
</sql>
</changeSet>
<changeSet author="fineract" id="0594-3-execute-rd-auto-debit-job">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">SELECT COUNT(*) FROM job WHERE name = 'Execute RD Auto Debit'</sqlCheck>
</preConditions>
<insert tableName="job">
<column name="name" value="Execute RD Auto Debit"/>
<column name="display_name" value="Execute RD Auto Debit"/>
<!-- short_name is NOT NULL and capped at 8 characters; see 0145_job_short_name.xml. -->
<column name="short_name" value="RDAUTODB"/>
<!-- 00:30 daily: after the midnight business-date sync, so "due today" means the new day. Anything a
run cannot collect stays overdue and is retried by the next run. -->
<column name="cron_expression" value="0 30 0 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="Execute RD Auto DebitJobDetail1 _ 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>
</databaseChangeLog>
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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">
<!--
Lien Marked's loan limit: the most a deposit may secure, as a percentage of its balance (e.g. 90 = a loan of
up to 90% of what is in the deposit). Null keeps today's behaviour - the whole unpledged balance.
Added to the product and to the pending-edit table, since a product edit waits there for approval and is
replayed from it; a column only on the product would be dropped by every approved edit.
-->
<changeSet author="fineract" id="0595-1-savings-product-lien-percentage">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="m_savings_product" columnName="lien_percentage"/>
</not>
</preConditions>
<addColumn tableName="m_savings_product">
<column name="lien_percentage" type="DECIMAL(5,2)"/>
</addColumn>
</changeSet>
<changeSet author="fineract" id="0595-2-saving-product-temp-lien-percentage">
<preConditions onFail="MARK_RAN">
<tableExists tableName="m_saving_product_temp"/>
<not>
<columnExists tableName="m_saving_product_temp" columnName="lien_percentage"/>
</not>
</preConditions>
<addColumn tableName="m_saving_product_temp">
<column name="lien_percentage" type="DECIMAL(5,2)"/>
</addColumn>
</changeSet>
<!-- The deposit's own limit, chosen when it is opened (never above its product's). Null = product's. -->
<changeSet author="fineract" id="0595-3-savings-account-lien-percentage">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="m_savings_account" columnName="lien_percentage"/>
</not>
</preConditions>
<addColumn tableName="m_savings_account">
<column name="lien_percentage" type="DECIMAL(5,2)"/>
</addColumn>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,128 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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">
<!--
Missed-installment penalty for recurring deposits ("Penalty / Grace Period for Missed Installments").
The product gains grace days, a penalty type (1 = flat amount, 2 = % of the installment) and the amount -
on the product and on the pending-edit table, since a product edit waits there for approval and is replayed
from it. A daily job charges each installment still unpaid after its grace days once, using the system
charge seeded below, and records it in m_rd_installment_penalty so it is never charged twice.
-->
<changeSet author="fineract" id="0596-1-savings-product-missed-installment-penalty">
<preConditions onFail="MARK_RAN">
<not>
<columnExists tableName="m_savings_product" columnName="missed_installment_penalty_amount"/>
</not>
</preConditions>
<addColumn tableName="m_savings_product">
<column name="missed_installment_grace_days" type="INT"/>
<column name="missed_installment_penalty_type" type="INT"/>
<column name="missed_installment_penalty_amount" type="DECIMAL(19,6)"/>
</addColumn>
</changeSet>
<changeSet author="fineract" id="0596-2-saving-product-temp-missed-installment-penalty">
<preConditions onFail="MARK_RAN">
<tableExists tableName="m_saving_product_temp"/>
<not>
<columnExists tableName="m_saving_product_temp" columnName="missed_installment_penalty_amount"/>
</not>
</preConditions>
<addColumn tableName="m_saving_product_temp">
<column name="missed_installment_grace_days" type="INT"/>
<column name="missed_installment_penalty_type" type="INT"/>
<column name="missed_installment_penalty_amount" type="DECIMAL(19,6)"/>
</addColumn>
</changeSet>
<changeSet author="fineract" id="0596-3-rd-installment-penalty-table">
<preConditions onFail="MARK_RAN">
<not>
<tableExists tableName="m_rd_installment_penalty"/>
</not>
</preConditions>
<createTable tableName="m_rd_installment_penalty">
<column name="id" type="BIGINT" autoIncrement="true">
<constraints primaryKey="true" nullable="false"/>
</column>
<!-- One penalty per installment, ever. -->
<column name="installment_id" type="BIGINT">
<constraints nullable="false" unique="true" uniqueConstraintName="uq_rd_installment_penalty_installment"/>
</column>
<column name="savings_account_id" type="BIGINT">
<constraints nullable="false" foreignKeyName="fk_rd_installment_penalty_account"
referencedTableName="m_savings_account" referencedColumnNames="id"/>
</column>
<column name="savings_account_charge_id" type="BIGINT"/>
<column name="penalty_amount" type="DECIMAL(19,6)">
<constraints nullable="false"/>
</column>
<column name="applied_on_date" type="DATE">
<constraints nullable="false"/>
</column>
</createTable>
</changeSet>
<changeSet author="fineract" id="0596-4-rd-missed-installment-penalty-charge">
<!-- Specified-due-date savings penalty in the organisation's currency; the amount is set per installment by
the job, so the definition's own amount stays 0. Matched by name, so a tenant's own copy is reused. -->
<sql>
INSERT INTO m_charge (name, currency_code, charge_applies_to_enum, charge_time_enum, charge_calculation_enum,
amount, is_penalty, is_active, is_deleted)
SELECT 'RD Missed Installment Penalty', oc.code, 2, 2, 1, 0, true, true, false
FROM (SELECT code FROM m_organisation_currency ORDER BY id LIMIT 1) oc
WHERE NOT EXISTS (SELECT 1 FROM m_charge c WHERE c.name = 'RD Missed Installment Penalty' AND c.is_deleted = false);
</sql>
</changeSet>
<changeSet author="fineract" id="0596-5-apply-rd-missed-installment-penalty-job">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="0">SELECT COUNT(*) FROM job WHERE name = 'Apply RD Missed Installment Penalty'</sqlCheck>
</preConditions>
<insert tableName="job">
<column name="name" value="Apply RD Missed Installment Penalty"/>
<column name="display_name" value="Apply RD Missed Installment Penalty"/>
<!-- short_name is NOT NULL and capped at 8 characters; see 0145_job_short_name.xml. -->
<column name="short_name" value="RDPENLTY"/>
<!-- 00:45 daily: after the business-date sync and after RD Auto Debit (00:30), so an installment the
auto debit collects tonight is never penalised. -->
<column name="cron_expression" value="0 45 0 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="Apply RD Missed Installment PenaltyJobDetail1 _ 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>
</databaseChangeLog>
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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">
<!--
Recurring deposit product creation goes to the checker like every other product. 0472 covered loan, savings,
current and share products and 0474 fixed deposits; recurring deposits were left out, so a new RD product
went live the moment it was saved.
-->
<changeSet id="0597_add_recurringdepositproduct_checker_permission_if_not_exists" author="fineract">
<sql>
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
SELECT 'portfolio', 'CREATE_RECURRINGDEPOSITPRODUCT_CHECKER', 'RECURRINGDEPOSITPRODUCT', 'CREATE_CHECKER', FALSE
WHERE NOT EXISTS (
SELECT 1 FROM m_permission WHERE code = 'CREATE_RECURRINGDEPOSITPRODUCT_CHECKER'
);
</sql>
</changeSet>
<changeSet id="0597_enable_recurring_deposit_product_creation_maker_checker" author="fineract">
<preConditions onFail="MARK_RAN">
<sqlCheck expectedResult="1">
SELECT COUNT(*) FROM m_permission WHERE code = 'CREATE_RECURRINGDEPOSITPRODUCT'
</sqlCheck>
</preConditions>
<sql>
UPDATE m_permission
SET can_maker_checker = TRUE
WHERE code = 'CREATE_RECURRINGDEPOSITPRODUCT';
</sql>
</changeSet>
<changeSet id="0597_grant_recurring_deposit_product_creation_maker_checker_permissions_to_roles" author="fineract">
<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 r.name = 'Super user'
AND p.code IN ('CREATE_RECURRINGDEPOSITPRODUCT', 'CREATE_RECURRINGDEPOSITPRODUCT_CHECKER')
AND NOT EXISTS (
SELECT 1 FROM m_role_permission rp
WHERE rp.role_id = r.id AND rp.permission_id = p.id
);
INSERT INTO m_role_permission (role_id, permission_id)
SELECT DISTINCT ur.role_id, p.id
FROM m_appuser u
JOIN m_appuser_role ur ON ur.appuser_id = u.id
CROSS JOIN m_permission p
WHERE u.username = 'bankadmin'
AND p.code IN ('CREATE_RECURRINGDEPOSITPRODUCT', 'CREATE_RECURRINGDEPOSITPRODUCT_CHECKER')
AND NOT EXISTS (
SELECT 1 FROM m_role_permission rp
WHERE rp.role_id = ur.role_id AND rp.permission_id = p.id
);
INSERT INTO m_role_permission (role_id, permission_id)
SELECT r.id, p.id
FROM m_role r
CROSS JOIN m_permission p
WHERE LOWER(r.name) = 'clerk'
AND p.code IN ('CREATE_RECURRINGDEPOSITPRODUCT', 'CREATE_RECURRINGDEPOSITPRODUCT_CHECKER')
AND NOT EXISTS (
SELECT 1 FROM m_role_permission rp
WHERE rp.role_id = r.id AND rp.permission_id = p.id
);
</sql>
</changeSet>
</databaseChangeLog>
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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">
<!--
Tenure Flexibility: extending a running recurring deposit's term. Goes to the checker like a premature closure,
and is granted to whichever roles may prematurely close a recurring deposit.
-->
<changeSet id="0598_add_recurring_deposit_extend_tenure_permissions" author="fineract">
<sql>
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
SELECT 'transaction_savings', 'EXTENDTENURE_RECURRINGDEPOSITACCOUNT', 'RECURRINGDEPOSITACCOUNT', 'EXTENDTENURE', TRUE
WHERE NOT EXISTS (SELECT 1 FROM m_permission WHERE code = 'EXTENDTENURE_RECURRINGDEPOSITACCOUNT');
INSERT INTO m_permission (grouping, code, entity_name, action_name, can_maker_checker)
SELECT 'transaction_savings', 'EXTENDTENURE_RECURRINGDEPOSITACCOUNT_CHECKER', 'RECURRINGDEPOSITACCOUNT', 'EXTENDTENURE_CHECKER', FALSE
WHERE NOT EXISTS (SELECT 1 FROM m_permission WHERE code = 'EXTENDTENURE_RECURRINGDEPOSITACCOUNT_CHECKER');
</sql>
</changeSet>
<changeSet id="0598_grant_recurring_deposit_extend_tenure_permissions" author="fineract">
<sql>
INSERT INTO m_role_permission (role_id, permission_id)
SELECT DISTINCT rp.role_id, np.id
FROM m_role_permission rp
JOIN m_permission op ON op.id = rp.permission_id
JOIN m_permission np ON np.code = REPLACE(op.code, 'PREMATURECLOSE_', 'EXTENDTENURE_')
WHERE op.code IN ('PREMATURECLOSE_RECURRINGDEPOSITACCOUNT', 'PREMATURECLOSE_RECURRINGDEPOSITACCOUNT_CHECKER')
AND NOT EXISTS (SELECT 1 FROM m_role_permission x WHERE x.role_id = rp.role_id AND x.permission_id = np.id);
</sql>
</changeSet>
</databaseChangeLog>
@@ -116,11 +116,7 @@ public class CommandSourceServiceTest {
}
@Test
public void testProcessCommand_NonGLAccount_SuperUser_OwnSubmission_DoesNotBypassMakerChecker() {
// A maker who happens to hold CHECKER_SUPER_USER must not auto-approve their own submission -
// CHECKER_SUPER_USER only ever lets its holder approve a DIFFERENT user's request (see
// PortfolioCommandSourceWritePlatformServiceImpl.validateMakerCheckerTransaction()). This
// replaces the old bypass this test used to assert.
public void testProcessCommand_NonGLAccount_SuperUser_BypassesMakerChecker() {
NewCommandSourceHandler handler = Mockito.mock(NewCommandSourceHandler.class);
JsonCommand jsonCommand = Mockito.mock(JsonCommand.class);
CommandSource commandSource = Mockito.mock(CommandSource.class);
@@ -129,8 +125,6 @@ public class CommandSourceServiceTest {
Mockito.when(commandSource.getPermissionCode()).thenReturn("WITHDRAW_SAVINGSACCOUNT");
Mockito.when(commandSource.getEntityName()).thenReturn("SAVINGSACCOUNT");
Mockito.when(commandSource.getActionName()).thenReturn("WITHDRAW");
Mockito.when(commandSource.getId()).thenReturn(300L);
Mockito.when(commandSource.getResourceId()).thenReturn(400L);
Mockito.when(configurationDomainService.isMakerCheckerEnabledForTask("WITHDRAW_SAVINGSACCOUNT")).thenReturn(true);
Mockito.when(superUser.isCheckerSuperUser()).thenReturn(true);
@@ -138,12 +132,12 @@ public class CommandSourceServiceTest {
.withCommandId(1L).build();
Mockito.when(handler.processCommand(jsonCommand)).thenReturn(dummyResult);
Assertions.assertThrows(org.apache.fineract.commands.exception.RollbackTransactionNotApprovedException.class, () -> {
underTest.processCommand(handler, jsonCommand, commandSource, superUser, false);
});
org.apache.fineract.infrastructure.core.data.CommandProcessingResult result = underTest.processCommand(handler, jsonCommand,
commandSource, superUser, false);
Mockito.verify(commandSource).markAsAwaitingApproval();
Mockito.verify(commandSource, Mockito.never()).markAsChecked(any());
Assertions.assertNotNull(result);
Mockito.verify(commandSource).markAsChecked(superUser);
Mockito.verify(commandSource, Mockito.never()).markAsAwaitingApproval();
}
@Test
@@ -517,6 +511,33 @@ public class CommandSourceServiceTest {
Mockito.verify(commandSource, Mockito.never()).markAsChecked(any());
}
@Test
public void testProcessCommand_RecurringDepositProduct_SuperUser_EnforcesMakerChecker() {
NewCommandSourceHandler handler = Mockito.mock(NewCommandSourceHandler.class);
JsonCommand jsonCommand = Mockito.mock(JsonCommand.class);
CommandSource commandSource = Mockito.mock(CommandSource.class);
AppUser superUser = Mockito.mock(AppUser.class);
Mockito.when(commandSource.getPermissionCode()).thenReturn("CREATE_RECURRINGDEPOSITPRODUCT");
Mockito.when(commandSource.getEntityName()).thenReturn("RECURRINGDEPOSITPRODUCT");
Mockito.when(commandSource.getActionName()).thenReturn("CREATE");
Mockito.when(commandSource.getId()).thenReturn(115L);
Mockito.when(commandSource.getResourceId()).thenReturn(215L);
Mockito.when(configurationDomainService.isMakerCheckerEnabledForTask("CREATE_RECURRINGDEPOSITPRODUCT")).thenReturn(true);
Mockito.when(superUser.isCheckerSuperUser()).thenReturn(true);
org.apache.fineract.infrastructure.core.data.CommandProcessingResult dummyResult = new org.apache.fineract.infrastructure.core.data.CommandProcessingResultBuilder()
.withCommandId(1L).build();
Mockito.when(handler.processCommand(jsonCommand)).thenReturn(dummyResult);
Assertions.assertThrows(org.apache.fineract.commands.exception.RollbackTransactionNotApprovedException.class, () -> {
underTest.processCommand(handler, jsonCommand, commandSource, superUser, false);
});
Mockito.verify(commandSource).markAsAwaitingApproval();
Mockito.verify(commandSource, Mockito.never()).markAsChecked(any());
}
@Test
public void testProcessCommand_FixedDepositProduct_CheckerApproval_MarksAsChecked() {
NewCommandSourceHandler handler = Mockito.mock(NewCommandSourceHandler.class);
@@ -233,7 +233,11 @@ public class InterestRateChart extends AbstractPersistableCustom<Long> {
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource(INTERESTRATE_CHART_RESOURCE_NAME);
this.update(command, actualChanges, baseDataValidator, null, null);
// A chart edited on its own (PUT /interestratecharts/{id}) has no sibling charts to check overlap against and
// no product to read a currency from: new slabs take the currency of the slabs already on the chart.
final String currencyCode = setOfChartSlabs().stream().map(slab -> slab.slabFields().getCurrencyCode())
.filter(Objects::nonNull).findFirst().orElse(null);
this.update(command, actualChanges, baseDataValidator, Set.of(), currencyCode);
throwExceptionIfValidationWarningsExist(dataValidationErrors);
@@ -66,6 +66,10 @@ public class InterestRateChartSlabFields {
return this.amountRangeTo;
}
public String getCurrencyCode() {
return this.currencyCode;
}
@Column(name = "amount_range_to", scale = 6, precision = 19)
private BigDecimal amountRangeTo;

Some files were not shown because too many files have changed in this diff Show More