Compare commits

...
71 Commits
Author SHA1 Message Date
nitesh 14c5f5070d Revert demo to pre-2026-08-06 state (rollback today's push)
Reverts all commits pushed to demo today (a5124ca3, 858c277a, a1a50ab8,
f72abb09, fcf66657) back to f8c532f7 as a single forward commit, without
rewriting history. All reverted content (Share Withdrawal/Closure feature,
TDS reports, KYC exception tracking, client-edit-email-dialog, form121 tab,
search-select) remains intact on dev and was verified identical before
this revert.
2026-08-06 13:39:40 +05:30
niteshandClaude Sonnet 5 fcf6665772 fix(nav): restore Loan Origination and Investment menus dropped by merge
The "Merge dev into demo" commit silently dropped both top-level nav
entries (desktop and mobile variants) along with their entire menu
panels — Loan Origination's mat-menu and the whole Investment mega-menu
(~150 lines) — because dev never had these menus, so the merge picked
dev's shell.component.html wholesale for this file instead of combining
both sides' additions. The underlying feature modules and routes were
untouched, so this restores only the shell wiring, copied verbatim from
the pre-merge demo revision.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 13:19:24 +05:30
nitesh f72abb0921 Merge remote-tracking branch 'origin/demo' into demo 2026-08-06 13:14:26 +05:30
niteshandClaude Sonnet 5 a1a50ab8a3 chore: update version stamp
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 13:10:52 +05:30
niteshandClaude Sonnet 5 858c277ae3 chore: update version stamp
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 12:17:49 +05:30
Anshul Rathore a5124ca3e8 Merge dev into demo 2026-08-06 10:46:08 +05:30
Anshul Rathore 1a33f9d6ce Merge remote-tracking branch 'origin/dev' into dev
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
2026-08-06 10:45:10 +05:30
Anshul Rathore 983c613b8e feat: update changes 2026-08-06 10:41:28 +05:30
nitesh ddb215decf Merge branch 'dev' of https://git.lincpay.tech/CBSNexora/cbsnexora into dev
Publish Image in Docker Hub / build (push) Canceled after 0s
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
2026-08-05 18:33:57 +05:30
niteshandClaude Sonnet 5 2cc8d979ba fix(shares): fix popup fixed-position bug, add Client Compliance card
backdrop-filter on the list-embedded review popup was making it a new
containing block for its own nested position:fixed dialogs (Validate,
Reject, Confirm-Submit), confining them to the popup's box instead of the
viewport — replaced the blur with a plain darker overlay. Also adds a
permanent Client Compliance card (KYC status, risk category, open AML
alerts) on the review screen so a manager can see it without opening the
Validate popup.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 18:32:48 +05:30
keshav 569f17ef46 kyc exception at client creation time and some tds work
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
2026-08-05 17:23:56 +05:30
niteshandClaude Sonnet 5 cc5cd4c6ab feat(shares): add Share Withdrawal maker-checker workflow with GL settlement
Tests / testRigor (push) Canceled after 0s
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Clerk submits a governed share redemption request (shares, Board Resolution
No., Meeting Date, settlement Payment Type); Bank Manager reviews with a
live backend-validated checklist (account/GL state, not just submit-time
snapshot) before approving, which redeems the shares and settles the
linked savings account in one transaction. Adds a Passbook tab to the
Share Account view, a reusable search-select control, and a Savings
Product "Map Payment Types to Specific Funds" fund-source override (only
Loan Products had this before) so settlement can be GL-mapped correctly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 16:55:21 +05:30
nitesh 8c7d8287f9 Merge branch 'uate' into dev — sync branches to same level
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
2026-08-04 11:35:08 +05:30
keshav 504d7ee7f6 Merge branch 'demo' of https://git.lincpay.tech/CBSNexora/cbsnexora into demo 2026-08-03 10:51:53 +05:30
keshav 26091c68b0 fix(accounting): prioritize specific Fineract error messages when AML marking fails 2026-08-03 10:51:07 +05:30
niteshandClaude Sonnet 5 f8c532f74a fix(tasks): wrap Approval Center tabs instead of scrolling behind pagination arrows
Replace mat-tab-nav-bar with a plain wrapping pill nav so all 16 approval sections stay
visible and one click away, instead of being hidden behind Material's prev/next scroll
arrows on a single-row strip.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 10:36:13 +05:30
keshav 44b41e504a Merge branch 'demo' of https://git.lincpay.tech/CBSNexora/cbsnexora into demo 2026-08-03 10:32:31 +05:30
keshav e8d91c8f60 feat(accounting): add AML manual referral and marking to general ledger entries 2026-08-03 10:31:32 +05:30
nitesh 8dd9767bdf Merge branch 'demo' of https://git.lincpay.tech/CBSNexora/cbsnexora into demo 2026-08-02 21:48:25 +05:30
niteshandClaude Sonnet 5 c868beb344 chore(npa): rename NPA Interest report/menu item to NPA Report
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-02 21:44:46 +05:30
keshav b43ed87771 risk review report with on which aml rule 2026-08-02 21:40:34 +05:30
niteshandClaude Sonnet 5 ebe67cc410 feat(investment,npa): RBI-grounded targets, GL-tracked interest posting, date/search pickers
- Correct Investment portfolio allocation and Loan Origination product-mix targets against
  RBI's UCB SLR/Non-SLR framework and PSL circulars, with a Target Basis column distinguishing
  RBI-mandated vs board-policy rows (Excel export included).
- Expand Investment holdings dataset with more near-term maturities so the Due-Date Diary
  reflects a realistic spread across FD/Govt Security/Non-SLR/Bond.
- Add From/To period-based Interest Calculation & Post (with GL selection for both posting and
  receiving) across the Investment Interest module, FD Entry and Bond Entry screens; fix a bug
  where a posted period kept re-appearing as due since accrual wasn't tracked per-holding.
- Add a reusable DD-MM-YYYY date-picker component and roll it out across all Investment date
  fields.
- NPA Summary Report: drop SMA-0/1/2 from the stage-wise table (kept in Day-wise Overdue only).
- NPA Recovery Report: add Account Type / NPA Category / Target-vs-Actual columns, a shared
  Account Type filter driving both the account picker and the register, and a searchable
  (fixed-position, not clipped by card overflow) account select for long lists.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-02 19:26:19 +05:30
nitesh d7f5bfe5f5 feat(fiu): add Head Office / Branch-wise scoping; remove reconciliation nav dots
FIU: adds a branch selector (Head Office sees all/drills into one branch,
a branch-level login is locked to its own branch) scoping the CTR/STR tabs,
dashboard KPIs and header. A FIU_BRANCH_CODE_TO_CANONICAL map bridges the
module's internal FINnet branch codes to the app-wide BranchMaster codes.
Live backend-driven AML alerts/cases are unchanged (no branch field to scope by).

Shell: removes the "working nav" green-dot indicator from the Reconciliation
mega-menu's 17 report links per request.
2026-08-02 16:06:03 +05:30
nitesh be6103e0b3 Merge branch 'demo' of https://git.lincpay.tech/CBSNexora/cbsnexora into demo 2026-08-02 14:23:46 +05:30
nitesh 5cd9998cfc feat(loan-origination): add full Loan Origination Sanctioning workflow module
New standalone module modelling the pre-disbursement pipeline: Channel intake
(Branch/BC/Self-Apply) -> KYC/OVD & e-KYC fingerprint -> CIC/Credit Bureau
check -> Field Investigation -> Personal Discussion & declaration -> Loan
Committee -> Risk Approval -> Legal Approval -> Customer Signing -> Cheque/ACH
-> Post-Disbursement Check -> Disbursement, per RBI KYC Master Direction, the
mandatory CIC check, and co-operative-bank share-membership rules.

Includes a 12-stage stepper with real approve/reject actions and a date-wise
audit trail, CIC upload + credit-score check, Field Inquiry push + Agent
Report upload, Committee "Reports Required" / Risk "Verification Checklist",
Head-Office-vs-branch scoping, a Pipeline screen (filters, New Application
intake, Channel-wise/BC-wise/Share-Member reports, Disbursement Target vs
Actual, Export to Excel), and a full EMI repayment schedule once disbursed.
2026-08-02 14:22:32 +05:30
keshav 0ca6842bde Merge branch 'demo' of https://git.lincpay.tech/CBSNexora/cbsnexora into demo 2026-08-02 11:49:32 +05:30
keshav 3030e2f34e form 91/98 report, min max value update in AML rule and whihc rule apply day, week, month and some more updates 2026-08-02 11:46:40 +05:30
nitesh b4608cbbe4 feat(npa): add Recovery Management System reports + Recovery Journey popup
Adds loan-type-aware recovery tracking (EMI/Overdrawn/Bullet) with a Recovery
Management Dashboard, Day-wise Overdue/Overdrawn reports, an Agriculture/Gold
market-value report, and a security-value exception check — all derived from
new repaymentType/emiAmount/drawingPower/maturityDate/collateralMarketValue
fields on LoanAccount, wired into Export to Excel and the NPA mega-menu.

Also replaces the always-visible Recovery/Collection Journey card on the
Account Detail Report with a "Recovery Journey" popup: a date-led, icon-coded
timeline of every SMS/call/visit/notice and payment run against an account.
2026-08-02 11:33:01 +05:30
nitesh 27cdaf7fc2 feat(npa): add Undebited Interest Recovery Report, fix note text width
Adds a 10th NPA report tracking memorandum "undebited interest" per IRAC
norms (accrued vs cash-recovered vs balance), wired into Export to Excel
and the NPA mega-menu. Also fixes a narrow-width text wrap on the report's
description note (new .npa-report-note class overriding pg-sub's 560px cap).
2026-08-02 08:34:03 +05:30
nitesh 90beea64cb feat(npa): add Export to Excel across all 9 NPA reports
Every report screen (Interest, Status, Recovery, Summary, Account Detail,
Movement, Provision, Probable NPA, SMA) now has an Export to Excel button
that builds a workbook from the same derived getters the on-screen tables
use, reusing the shared cashier-export.ts builder.
2026-08-01 20:58:42 +05:30
nitesh 1317a93838 feat(cashier): full double-entry journal view + Excel export for Cash/Clearing/Transfer Summary
Transaction Details now renders each voucher as a paired Dr/Cr journal entry with a
derived contra account and a Balanced status chip, so both sides of a transaction are
visible at a glance for reconciliation. Adds a shared cashier-export.ts (mirrors the
Investment module's exporter) and an Export to Excel button producing a Summary +
Transaction Details workbook, plus a Branch Breakup sheet for Head Office consolidated view.
2026-08-01 20:32:31 +05:30
nitesh 0832017508 feat(investment,reconciliation): add Export to Excel across Investment, fix export popup
Adds a shared Export to Excel utility (investment-export.ts) and wires it
into every listing/report screen in the Investment module — Dashboard
(break-up + allocation), Reports (all ~20 report shapes), Interest (per
active tab), the FD/Bond/Share Holdings registers, and Masters (per active
master tab). Entry/transaction forms intentionally have no export button.
No sign-off is included here, matching the request to keep that feature
reconciliation-only.

Also fixes the Reconciliation export flow: the Prepared/Checked/Approved
sign-off is now an optional one-off popup shown when "Export to Excel" is
clicked (fields are blank by default and downloading works whether or not
they're filled), replacing the earlier always-visible sign-off card. Also
fixes three reconciliation reports (Sundry Dr/Cr, NEFT/RTGS, UDIR) whose
labels contain "/" — an Excel-forbidden worksheet-name character — which
was silently aborting their export.
2026-08-01 19:20:53 +05:30
nitesh 8ac4010967 feat(investment): add portfolio allocation targets and interest receivable/post/receive lifecycle
Adds a Portfolio Allocation (Target vs Actual %) section to the Investment
Dashboard, and reworks Investment Interest into the full accrual lifecycle:
Interest Receivable, FD/Govt./Bond Interest Calculation & Post, and Interest
Receive, plus the existing registers.

Interest Calculation & Post now tracks cumulative posted/received amounts
per holding instead of recomputing full accrued interest on every click
(which previously double-counted on repeat posting). Holdings classified
Non-Performing (Sub-Standard/Doubtful/Loss) are excluded from accrual
posting per RBI norms — their interest accrues in memo/suspense only and is
recognised solely on actual cash receipt via Interest Receive.

Also bumps the production initial-bundle budget in angular.json (13/14mb ->
15/17mb) since the growing set of eagerly-loaded feature modules (Investment,
NPA, Reconciliation, GL Reports, OSS Returns) pushed the build past the old
limit.
2026-08-01 17:56:44 +05:30
nitesh 1c125d97c5 Merge branch 'demo' of https://git.lincpay.tech/CBSNexora/cbsnexora into demo 2026-08-01 13:15:57 +05:30
nitesh c935e2a62a feat(reconciliation): build full 16-screen Reconciliation module
Wires every item in the Reconciliation mega-menu (Core & Books, Bank &
Clearing, Digital & Payments, Instruments & Members, Compliance &
Financials) to a working screen, mirroring the NPA module's pattern: one
route-param-driven component over a shared two-sided (Side A vs Side B)
matching model, with pagination and a "Mark as Reconciled" action on every
screen.

Access is split by real-world scope: activity that happens at a branch
(vouchers, cheques, digital transactions, share members, fixed assets) is
branch-wise with the same Head-Office/branch login behavior as NPA; activity
with no branch dimension in real banking (GL/P&L consolidation, treasury's
own bank accounts, statutory tax filing, vendor procurement, inter-branch
netting) is Head-Office-only, with branch logins shown a restricted notice
instead of the data.

Also adds the .menu-item-live "working" indicator to mat-menu-item buttons
(same convention as .gl-link--live) and applies it across the reconciliation
menu and the pre-existing DD/Pay Order Reconciliation link.
2026-08-01 13:15:17 +05:30
keshav 2a9df828ca fix: update General Ledger toolbar menu links with routerLink 2026-08-01 12:01:55 +05:30
keshav bd753f4983 oss file updated, profitl loss as per the day month and also with date select 2026-08-01 11:46:11 +05:30
nitesh 4261f9659e feat(npa): add branch-wise NPA module with realistic data, pagination and recovery actions
Adds a full NPA (Non-Performing Assets) module mirroring the legacy CBS NPA
mega-menu: NPA Reports, NPA Analysis, and NPA Classification screens over a
640-account loan book classified per RBI IRAC norms (Standard through
Loss). Same Head-Office/branch-wise access pattern as the Cash/Clearing/
Transfer summary, 20-row pagination on every large table, and a Recovery
Action workflow (demand notice, SARFAESI, suit filing, OTS) on the Account
Detail screen.

Fixes several data-generation bugs so every account stays internally
consistent regardless of when it's viewed: disbursement date can no longer
predate the account's own overdue history, last-payment date now reflects
the most recent recovery entry, the quarter-ago snapshot can't imply more
overdue days than the loan's age allowed, and provision held is capped at
the account's outstanding balance.

Also fixes a text-overflow/dropdown-arrow overlap on long select options
(Investment + NPA shared form styles), and marks the GL "Financial
Statements" menu items that are already wired to a working dialog.
2026-08-01 11:18:02 +05:30
nitesh 63ac900e42 feat(investment): add Treasury Investment module (FD, Govt Sec/Non-SLR/Bond/MF, Share)
Adds full frontend-only Investment module mirroring the legacy AutoBank CBS
Investment menu: Dashboard, FD/Bond/Share entry screens (purchase, interest,
sell/redeem, write-off, amortize and more), 10 master screens, an Interest
calculation/register screen, and ~21 reports. All figures are derived from a
single holdings/transactions dataset so entry, interest, and reports can
never drift out of sync. Wires the new "Investment" mega-menu into the shell
and routes the previously inert Investment stub buttons.
2026-08-01 09:17:06 +05:30
niteshandClaude Sonnet 5 fd28788d23 fix(cashier): realistic branch-aware account numbers, dynamic date tags in summary report
Account No now always holds a genuine reference for its transaction type
(customer account, GL/facility code, IFSC, DD/PO/TDS/GST/cheque ref, or
UTR/RRN/UMRN for RTGS/NEFT/UPI/ATM/NACH) instead of a plain description.
Branch 2's view derives its own valid-format account numbers and IFSC
codes by shifting the numeric segment, rather than tagging a "BR2-" prefix
onto Branch 1's values, which looked fake for standardized formats.

Voucher/reference numbers' baked-in "2607" (Jul 2026) tag is now derived
from the real current date at render time, so it won't go stale next month.

feat(clients): auto-calculate Monthly/Annual Income and Turnover

Typing either the monthly or annual figure now fills in the other at a 12x
ratio (rounded to 2 decimals, no trailing ".00" on whole numbers). Guarded
against firing during prefillForEdit()'s initial load of an existing
client's independently-saved values, so editing doesn't silently overwrite
historical data that wasn't an exact 12x match.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 17:24:57 +05:30
keshav b9b37397fe Merge remote-tracking branch 'origin/demo' into demo 2026-07-31 15:10:42 +05:30
keshav f2525080c8 static update 2026-07-31 15:09:18 +05:30
Anshul Rathore a982083b14 chore: stop tracking auto-generated .env.ts file 2026-07-31 15:08:35 +05:30
nitesh 43e3c546a7 Merge remote-tracking branch 'origin/dev' into demo 2026-07-31 14:47:03 +05:30
nitesh b68b25f789 Merge remote-tracking branch 'origin/uate' into demo 2026-07-31 14:46:38 +05:30
Anshul Rathore a560cd6533 feat: add Welcome Kit dispatch dialog and Share Holders view
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
2026-07-31 14:06:27 +05:30
niteshandClaude Sonnet 5 1dc378c2dd feat(cashier): add Cash/Clearing/Transfer summary report with branch-wise drill-down
Adds a dummy-data summary report (Opening/Credit/Debit/Closing) under Sub
Ledger > Cash / Clearing / Transfer, with Cash, Transfer (GL-wise), Clearing
and Digital (RTGS/NEFT/UPI/ATM/NACH) tabs plus a transaction-details drill
down. Credit/Debit/Closing are always derived from the transaction lines so
the summary and detail views can never drift apart.

Head Office logins (officeId 1 or office name containing "head office") get
a branch switcher across two demo branches plus a consolidated view with a
branch-wise break-up; branch-level logins see only their own office's data.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-31 13:39:13 +05:30
keshav 0bf337b962 Merge branch 'uate' of https://git.lincpay.tech/CBSNexora/cbsnexora into uate 2026-07-31 11:00:14 +05:30
keshav 1daa12a117 kyc risk and AML & Compliance Checks automate on client creation 2026-07-31 10:58:58 +05:30
nitesh f687e1808d fix(http): stop surfacing background/enrichment-fetch failures as error toasts
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Two related cases where ErrorHandlerInterceptor's global toast fired even
though the calling component already recovers gracefully on its own:

- GET /kyc/risk-rules 404ing (e.g. not yet deployed on a given backend)
  popped a raw "Http failure response ... 404" toast on the Create Client
  page, even though client-general-step already falls back to an empty
  rule set and a default risk category when this call fails.

- The Clients list page fires several per-row background calls
  (client data/KYC/address, for every visible row) plus the main search —
  each already had its own catchError/error handling, but the
  interceptor's 500 branch had no silencing path at all (only 403/404 did,
  and only for a fixed set of known-optional URLs), so any backend
  hiccup there spammed "Internal Server Error" toasts on top of an
  otherwise-working page.

Added a SILENT_HTTP_ERROR HttpContextToken so a caller can opt a specific
request out of the toast for every status code (not just 403/404) when it
already handles failure itself — threaded as an optional `silent` param
through ClientsService's searchByText/getClientData/getClientKyc/
getClientAddressData (default false, so no other of their ~50+ call sites
change behavior) and set from ClientsComponent's list-page calls. The
risk-rules endpoint was simpler: just added to the interceptor's existing
URL-based silent-request list alongside client images/KYC/pending-edits.
2026-07-30 13:41:28 +05:30
nitesh 186a9057a1 feat(clients): confirm linked Client ID + details after adding a family member
The "Add Member" dialog closed silently on submit, giving no
acknowledgement of what got recorded — most notably the linked client's
own CBS Client ID when the member was linked to an existing client rather
than entered manually. Added a confirmation popup showing Client ID (when
linked), name, relationship, DOB and dependent status right after submit.
2026-07-30 13:38:10 +05:30
nitesh 387bd060e1 feat(clients): draw-signature option for Specimen Signature, drop its webcam capture
DrawSignatureDialogComponent (a mouse/touchpad signature pad) already
existed and was used from the client profile view, but wasn't wired into
the KYC step used during client creation/edit — a stale comment there
even referred to a "draw-pad" option as if it were already present.
Wired it in as a third capture method alongside Choose & Crop, then
removed Use Webcam from the signature box specifically (kept for Client
Photograph) per follow-up feedback — a signature is drawn or scanned, not
photographed.

Refactored the file-picker/webcam/draw-pad paths' duplicated stage+upload
logic into shared applySignatureFile()/uploadSignatureFile() helpers.
2026-07-30 12:28:08 +05:30
nitesh 29f1cdc646 fix(clients): Aadhaar show/hide icon spilling past the field border in KYC step
.toggle-vis-btn shrinks the visible mat-icon-button to 28px, but Material
still reserves its default ~48px invisible touch-target/ripple centered
on the button. Since the suffix container doesn't clip overflow, that
ripple rendered past the input's own border on hover/focus, making the
eye icon look like it was sitting outside/on top of the field edge.
Constrained the touch-target and ripple to match the shrunk button.
2026-07-30 10:32:33 +05:30
nitesh 1efb520009 feat(tasks): backend-driven pagination, search and date filters for Client Approval
Client Approval previously fetched up to 1000 pending clients via a route
resolver and did name-search/sorting client-side (the search box was
actually dead — it set a MatTableDataSource filter that the grouped-table
view never read). Reworked to mirror PendingClientEditsComponent: real
mat-paginator against /clients (offset/limit), server-side displayName
search, orderBy=submittedOnDate for latest-first, and All/Today/Yesterday
presets backed by the new fromDate/toDate params. Dropped the now-unused
GetGroupedClientsData resolver.

Also: Account Number column -> Client ID (element.id), disabled the
Approve button with a "N selected" indicator when nothing's checked, and
a redesigned action bar / empty-state (context-aware message for
zero-results-from-search vs. zero-results-from-date-filter vs. truly
nothing pending) — plus the plain-div search box and matched heights
across chips/search/button, replacing an earlier mat-form-field version
that Material's own outlined-field box model kept misaligning against the
pill buttons.
2026-07-30 10:31:55 +05:30
nitesh 4ea833ff49 feat(clients): cite UAPA Sec. 51-A / RBI KYC Direction and list-currency date in sanctions dialog
The sanctions verification dialog said which lists a client was screened
against but not the regulatory basis for doing so, nor when that list
data was last refreshed. Added a regulatory-basis note and a "List Data
As Of" row (sourced from the backend's newly-exposed listDataAsOf) to
both the cleared and match-found panels.
2026-07-30 10:30:45 +05:30
nitesh 5dc284bd1c fix(clients): address-proof date fields use calendar picker, Pension Payment Order gets one too
Both the address-proof upload dialog and the permanent-address step used a
native `type="date"` input for the issue/statement date, so no calendar
popup was available. Switched both to Angular Material's datepicker, kept
the client-india-address-step round-trip (payload -> saved description ->
re-parsed on edit) working with the Dates util now that the control holds
a Date object instead of a raw string.

Pension Payment Orders was also the only "Financial & Other" address-proof
type missing requiresDate, so selecting it never showed a date field at
all — added the flag and moved Monthly/Yearly Turnover under the "Other
Income" heading alongside Agriculture/Non-Agriculture Income.
2026-07-30 10:30:00 +05:30
niteshandClaude Sonnet 5 56f13ade67 fix(clients): latest-identifier ordering for KYC docs, show client ID in list
Repeat KYC document uploads create a new client_identifier row rather than
updating in place, so loadExistingKycIdentifier() must prefer the newest
matching row instead of the first one returned by the API. Also swap the
Clients list "Account No." column to show the client's numeric ID instead.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-29 11:32:41 +05:30
nitesh dbd160e7e7 Merge remote-tracking branch 'origin/uate' into uate 2026-07-29 10:29:55 +05:30
niteshandClaude Sonnet 5 468eaa96ab feat(clients): maker-checker for client edits (frontend)
- New "Pending Client Edits" screen under Checker Inbox & Tasks: server-driven pagination,
  date range + Today/Yesterday/All presets, status filter (Pending/Approved/Rejected), search —
  mirrors ChequebookRequestsComponent's architecture.
- Compare dialog diffs the maker's proposed values against a point-in-time "before" snapshot
  (client-edit-diff.util.ts) captured when the edit page was opened, so only genuinely changed
  fields show — works correctly for Pending, Approved, and Rejected edits alike, since it no
  longer depends on comparing against the live (possibly already-updated) client record.
- edit-client.component.ts: General tab save now submits for approval instead of applying
  immediately, shows a pending-approval banner, and blocks a second submission while one's
  outstanding.
- error-handler.interceptor.ts: added the new /clients/{id}/edit/pending check to the existing
  "expected 403/404, don't alert" allowlist (same pattern already used for client images/KYC).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-29 10:27:45 +05:30
keshav f682cb17f6 CTR/STR report and Risk Category auto mark on bases of person occupation and anual salary enter 2026-07-29 10:21:02 +05:30
niteshandClaude Sonnet 5 79fedb66e5 fix(clients): minor-age threshold to 18, senior/PWD doc reload, in-app document preview dialog
- Raise isMinor threshold from age <10 to <18 (legal definition), cascading correctly to
  guardian requirement, KYC document filtering, and Education Level/Degree Qualification
  visibility (now shown for all ages, not hidden for minors).
- Load and display previously-uploaded Senior Citizen proof / PWD certificate documents on
  edit (view/replace/remove), instead of always showing an empty upload prompt.
- Fix seniorPwdDocsComplete to accept an existing certificate, not just a freshly-picked file.
- Add DocumentPreviewDialogComponent: a reusable in-app modal (image/PDF/download) used in
  place of window.open() for saved KYC/address/senior-citizen/PWD documents — avoids popup
  blockers (fired only after the async download resolved) and Chrome/Edge's failure to paint
  large base64 data: URLs on first open.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-28 15:49:53 +05:30
niteshandClaude Sonnet 5 c1fc95d9b7 fix(clients): minor-specific KYC document types (Birth Certificate/School ID) never appeared
filterDocTypesForMinor() only ever removes entries. The initial (pre-DOB, isMinor=false) seed
already stripped Birth Certificate/School ID Card out of kycDocumentTypes, so the isMinor
ngOnChanges handler re-filtering that same shortened list could never bring them back once the
client turned out to be a minor. Rebuild from the full defaultDocumentTypes source instead
(matching how the initial seed itself is built) whenever isMinor changes and the backend KYC
template hasn't already taken over. Also gives School ID Card the "Government-issued ID"
category it was missing, so it groups with Aadhaar/Passport/Birth Certificate instead of "Other".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-28 12:56:30 +05:30
nitesh b422ae6600 Merge remote-tracking branch 'origin/uate' into uate 2026-07-28 12:37:59 +05:30
niteshandClaude Sonnet 5 5fd7e1890e feat(clients): require Mother + Father/Caretaker as family members before activation
- Add hasMother/hasFather/hasCaretaker/familyRelationshipRulesMet to
  ClientFamilyMembersStepComponent, matched against the RELATIONSHIP code value label.
- Show two independent inline error banners (never merged into one message) when Mother, or
  both Father and Caretaker, are missing.
- Gate "Save & Next" and final Submit on this rule in both the create and edit client flows —
  the edit flow previously treated the Family tab as unconditionally optional.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-28 12:36:30 +05:30
keshav 0389b1f7c3 aadher edit fild update 2026-07-28 12:32:51 +05:30
nitesh 2e4187c3d2 Merge remote-tracking branch 'origin/uate' into uate 2026-07-28 10:53:26 +05:30
niteshandClaude Sonnet 5 cb4260b7a3 fix(clients): stale signature bug, monthly turnover/annual income fields, senior citizen/PWD classification
- Fix signature-document reads picking the oldest upload instead of the latest across 7 call
  sites (CKYC tab, view/delete-signature dialogs, edit-wizard preview, cashier transaction entry,
  signatory service, record-master) by sorting on document id instead of an unsorted find().
- Add Monthly Turnover and Annual Income fields alongside the renamed Yearly Turnover field.
- Add Senior Citizen (auto-detected from DOB) and Person with Disability classification, with a
  required disability-certificate upload gate before client creation can proceed.
- Add Graduate and Diploma as distinct Education Levels, with diploma-specific degree options.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-28 10:49:28 +05:30
keshav 349dc91951 minor change on client 2026-07-28 10:45:31 +05:30
nitesh a9c60083bf Merge remote-tracking branch 'origin/uate' into dev
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
2026-07-27 14:21:51 +05:30
niteshandClaude Sonnet 5 733d9d22b2 feat(clients): dual-OTP contact-change verification, webcam signature capture, and client history tab
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
Frontend counterpart to the backend dual-OTP contact-change feature:

- New ContactOtpBlockComponent (6-box segmented OTP input) used up to 4x in
  Edit Client (old/new mobile, old/new email — grouped under per-field
  sub-headers) and once each for mobile/email in Create Client, gating
  Save/Save & Next until every required box is verified.
- edit-client.component.ts: detects mobile/email/DOB changes against the
  loaded snapshot using local-date comparison (not `.toISOString()`, which
  false-triggers a day-shift in positive-UTC-offset timezones) and
  trimmed/case-insensitive email comparison (autofill whitespace or re-typed
  casing no longer reads as a change the masked preview can't explain).
- client-kyc-step.component.ts: new `invalidFieldLabels` getter names every
  currently-invalid required KYC field, surfaced via the Save & Next tooltip
  in both create-client and edit-client so a greyed-out button always
  explains what's still missing instead of a generic message.
- CaptureImageDialogComponent generalized for both profile photo and
  signature (photograph-a-paper-signature) capture:
  - Frame aspect now matches the requested getUserMedia resolution
    (4:3 profile / 16:9 signature) with object-fit: cover, eliminating the
    pillarboxing (black bars) a mismatched box previously caused.
  - Suppresses Chromium's auto-injected PiP/cast corner overlay icons.
  - Frame height capped in vh (not just px) so the dialog fits short
    viewports instead of pushing Cancel/Upload below the fold.
- upload-document-dialog.component.ts: generic Documents-tab upload now also
  offers "Capture from Webcam" alongside Browse, reusing the same capture
  dialog.
- New client History tab (reuses the existing Audit Trail data, scoped to
  this client) and dataUrlToFile/dataUrlToBlob util for routing webcam
  captures through the same upload pipelines as a picked file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-26 14:51:04 +05:30
niteshandClaude Sonnet 5 d334dd1669 feat(users): OTP delivery method picker on user creation + post-login agreement
build-run / Run Lint, Build and Deploy (push) Canceled after 0s
Publish Image in Docker Hub / build (push) Canceled after 0s
Playwright E2E Tests / Run Playwright Tests (push) Canceled after 0s
Tests / testRigor (push) Canceled after 0s
Create User dialog now has a mandatory Email/Mobile OTP delivery method
picker (styled as a pill toggle) alongside the existing fields.

Adds a new post-login agreement acceptance dialog: right after the existing
2FA flow (TwoFactorAuthenticationComponent) succeeds, or immediately after
login for users without 2FA, the user must accept the bank's current
agreement/disclaimer at least once before reaching the app.

Also adds a "Manage User Agreement" admin screen (System section) to publish
versioned agreement text without a code deploy.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-24 16:20:46 +05:30
230 changed files with 58420 additions and 1600 deletions
+2 -2
View File
@@ -69,8 +69,8 @@
"budgets": [ "budgets": [
{ {
"type": "initial", "type": "initial",
"maximumWarning": "13mb", "maximumWarning": "15mb",
"maximumError": "14mb" "maximumError": "17mb"
}, },
{ {
"type": "anyComponentStyle", "type": "anyComponentStyle",
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 688 KiB

@@ -0,0 +1,70 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<h2 class="mk-title" [class.mk-title--str]="isEscalation">
<fa-icon [icon]="isEscalation ? 'exclamation-triangle' : 'check-circle'"></fa-icon>
{{ isEscalation ? 'Mark as Suspicious' : 'Mark as Whitelisted' }}
</h2>
<mat-dialog-content>
<div class="mk-entry">
<div>
<label>Journal entry</label><span class="mono">#{{ data.journalEntryId }}</span>
</div>
<div>
<label>Transaction</label><span class="mono">{{ data.transactionId }}</span>
</div>
<div>
<label>Date</label><span>{{ data.transactionDate }}</span>
</div>
<div>
<label>Amount</label><span class="mono">&#8377;{{ data.amount | number: '1.2-2' }}</span>
</div>
<div class="wide">
<label>GL account</label><span>{{ data.glAccountName }}</span>
</div>
</div>
@if (isEscalation) {
<p class="mk-warn">
<fa-icon icon="exclamation-triangle"></fa-icon>
This raises an AML alert against the customer behind this entry and escalates it. An STR case opens for the
Principal Officer with the seven working day FIU-IND clock running. It cannot be undone from this screen.
</p>
} @else {
<p class="mk-note">
Records the entry as reviewed and cleared. No report is filed and the customer's risk rating is untouched.
</p>
}
<label class="mk-field">
<span>Reviewer notes {{ isEscalation ? '(required)' : '(optional)' }}</span>
<textarea
rows="4"
[(ngModel)]="notes"
[placeholder]="
isEscalation
? 'Why is this entry suspicious? What did you check?'
: 'What satisfied you that this entry is in order?'
"
></textarea>
</label>
</mat-dialog-content>
<mat-dialog-actions class="mk-actions">
<button class="mk-btn" (click)="dialogRef.close()">Cancel</button>
<button
class="mk-btn"
[class.mk-btn--str]="isEscalation"
[class.mk-btn--ok]="!isEscalation"
[disabled]="!canSubmit"
(click)="confirm()"
>
{{ isEscalation ? 'Escalate to STR' : 'Whitelist entry' }}
</button>
</mat-dialog-actions>
@@ -0,0 +1,165 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
:host {
--mk-g100: #f1f5f9;
--mk-g200: #e2e8f0;
--mk-g300: #cbd5e1;
--mk-g500: #64748b;
--mk-g700: #334155;
--mk-g900: #0f172a;
--mk-green: #15803d;
--mk-red: #c0392b;
--mk-amber-l: #fef3c7;
display: block;
font-family: 'DM Sans', system-ui, sans-serif;
color: var(--mk-g900);
min-width: 460px;
}
.mk-title {
display: flex;
align-items: center;
gap: 9px;
margin: 0;
padding: 18px 22px 10px;
font-size: 16px;
font-weight: 700;
color: var(--mk-green);
&--str {
color: var(--mk-red);
}
}
.mk-entry {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 18px;
padding: 11px 14px;
background: #fff;
border: 1px solid var(--mk-g200);
border-radius: 8px;
margin-bottom: 12px;
> div {
display: flex;
flex-direction: column;
}
.wide {
grid-column: span 2;
}
label {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--mk-g500);
}
span {
font-size: 12.5px;
}
}
.mk-warn {
display: flex;
align-items: baseline;
gap: 8px;
font-size: 12px;
color: #78350f;
background: var(--mk-amber-l);
border-radius: 7px;
padding: 9px 12px;
margin: 0 0 12px;
}
.mk-note {
font-size: 12px;
color: var(--mk-g500);
margin: 0 0 12px;
}
.mk-field {
display: flex;
flex-direction: column;
gap: 4px;
span {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--mk-g500);
}
textarea {
padding: 9px 11px;
border: 1px solid var(--mk-g300);
border-radius: 7px;
font-size: 13px;
font-family: inherit;
resize: vertical;
&:focus {
outline: none;
border-color: var(--mk-g700);
}
}
}
.mk-actions {
display: flex;
justify-content: flex-end;
gap: 9px;
padding: 8px 22px 18px;
}
.mk-btn {
padding: 8px 16px;
border: 1px solid var(--mk-g300);
background: #fff;
border-radius: 8px;
font-size: 12.5px;
font-weight: 600;
color: var(--mk-g700);
cursor: pointer;
font-family: inherit;
&:hover:not(:disabled) {
background: var(--mk-g100);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&--ok {
background: var(--mk-green);
border-color: var(--mk-green);
color: #fff;
&:hover:not(:disabled) {
background: #12692f;
}
}
&--str {
background: var(--mk-red);
border-color: var(--mk-red);
color: #fff;
&:hover:not(:disabled) {
background: #a5301f;
}
}
}
@@ -0,0 +1,63 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/** Angular Imports */
import { Component, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogContent, MatDialogActions } from '@angular/material/dialog';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
export interface MarkEntryDialogData {
disposition: 'WHITELIST' | 'ESCALATE';
journalEntryId: number;
transactionId: string;
amount: number;
glAccountName: string;
transactionDate: string;
}
/**
* Captures the reviewer's reason before a ledger entry is marked.
*
* Notes are not optional on an escalation: the Principal Officer picks the case up
* with nothing else to go on, and an STR filed on an unexplained referral is not
* defensible. A whitelist may be recorded without them.
*/
@Component({
selector: 'mifosx-mark-entry-dialog',
templateUrl: './mark-entry-dialog.component.html',
styleUrls: ['./mark-entry-dialog.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
FormsModule,
FaIconComponent,
MatDialogContent,
MatDialogActions
]
})
export class MarkEntryDialogComponent {
dialogRef = inject<MatDialogRef<MarkEntryDialogComponent>>(MatDialogRef);
data = inject<MarkEntryDialogData>(MAT_DIALOG_DATA);
notes = '';
get isEscalation(): boolean {
return this.data.disposition === 'ESCALATE';
}
get canSubmit(): boolean {
return !this.isEscalation || this.notes.trim().length > 0;
}
confirm(): void {
if (this.canSubmit) {
this.dialogRef.close(this.notes.trim());
}
}
}
@@ -535,6 +535,14 @@
</div> </div>
</div> </div>
@if (markError) {
<div class="gl-mark-error">
<fa-icon icon="exclamation-triangle"></fa-icon>
<span>{{ markError }}</span>
<button class="gl-mark-error__close" (click)="markError = ''">&times;</button>
</div>
}
<div class="gl-table-shell"> <div class="gl-table-shell">
<mat-table [dataSource]="dataSource" matSort class="gl-mat-table"> <mat-table [dataSource]="dataSource" matSort class="gl-mat-table">
<!-- #ID --> <!-- #ID -->
@@ -692,6 +700,50 @@
</mat-cell> </mat-cell>
</ng-container> </ng-container>
<!-- AML review — whitelist or refer the entry to STR -->
<ng-container matColumnDef="amlMark">
<mat-header-cell *matHeaderCellDef class="gl-th">AML Review</mat-header-cell>
<mat-cell *matCellDef="let e" class="gl-td">
@if (markOf(e); as mark) {
<span
class="gl-mark"
[class.gl-mark--str]="mark.disposition === 'ESCALATE'"
[matTooltip]="
(mark.disposition === 'ESCALATE'
? 'Escalated to STR' + (mark.strCaseId ? ' — case #' + mark.strCaseId : '')
: 'Whitelisted') +
(mark.reviewedBy ? ' by ' + mark.reviewedBy : '') +
(mark.notes ? ' — ' + mark.notes : '')
"
>
<fa-icon [icon]="mark.disposition === 'ESCALATE' ? 'exclamation-triangle' : 'check-circle'"></fa-icon>
{{ mark.disposition === 'ESCALATE' ? 'Suspicious' : 'Whitelisted' }}
</span>
} @else if (isMarking(e)) {
<span class="gl-mark gl-mark--busy">Saving…</span>
} @else if (canMark(e)) {
<span class="gl-mark-actions">
<button
class="gl-mark-btn gl-mark-btn--ok"
matTooltip="Reviewed and in order — clear this entry"
(click)="openMarkDialog(e, 'WHITELIST')"
>
<fa-icon icon="check-circle"></fa-icon> Whitelist
</button>
<button
class="gl-mark-btn gl-mark-btn--str"
matTooltip="Refer to the Principal Officer as an STR case"
(click)="openMarkDialog(e, 'ESCALATE')"
>
<fa-icon icon="exclamation-triangle"></fa-icon> Suspicious
</button>
</span>
} @else {
<span class="gl-mark gl-mark--na" [matTooltip]="markBlockedReason(e)">—</span>
}
</mat-cell>
</ng-container>
<!-- Actions --> <!-- Actions -->
<ng-container matColumnDef="actions"> <ng-container matColumnDef="actions">
<mat-header-cell *matHeaderCellDef class="gl-th"></mat-header-cell> <mat-header-cell *matHeaderCellDef class="gl-th"></mat-header-cell>
@@ -1328,6 +1328,17 @@
flex: 0 0 130px; flex: 0 0 130px;
} }
// Wide enough to hold both action buttons on one line. Every other column
// declares a width; without one this collapsed and clipped its contents.
::ng-deep .mat-column-amlMark {
width: 184px;
min-width: 184px;
flex: 0 0 184px;
// Keeps the "AML REVIEW" heading on one line instead of clipping it.
white-space: nowrap;
overflow: visible;
}
::ng-deep .mat-column-actions { ::ng-deep .mat-column-actions {
width: 50px; width: 50px;
min-width: 50px; min-width: 50px;
@@ -1556,6 +1567,112 @@
} }
} }
// ── AML review column ─────────────────────────────────────────────────────────
// Never wrap — a wrapped second button used to be clipped by the row height.
.gl-mark-actions {
display: flex;
align-items: center;
gap: 5px;
flex-wrap: nowrap;
width: 100%;
}
.gl-mark-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 4px;
padding: 4px 8px;
border: 1px solid var(--c-border);
background: var(--c-surface);
border-radius: 6px;
font-size: 0.62rem;
font-weight: 700;
line-height: 1.2;
color: var(--c-text-2);
cursor: pointer;
font-family: inherit;
white-space: nowrap;
flex: 1 1 auto;
transition: all var(--transition);
// Tinted at rest, not only on hover — these have to be findable in a dense
// table without the reviewer hunting for them.
&--ok {
border-color: rgb(16 185 129 / 45%);
background: var(--c-cr-bg);
color: #047857;
&:hover {
border-color: var(--c-cr);
background: #d1fae5;
}
}
&--str {
border-color: rgb(239 68 68 / 45%);
background: var(--c-dr-bg);
color: #b91c1c;
&:hover {
border-color: var(--c-dr);
background: #fee2e2;
}
}
}
.gl-mark {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 9px;
border-radius: 999px;
font-size: 0.62rem;
font-weight: 700;
white-space: nowrap;
background: var(--c-cr-bg);
color: #047857;
&--str {
background: var(--c-dr-bg);
color: #b91c1c;
}
&--busy {
background: #f1f5f9;
color: var(--c-text-3);
}
&--na {
background: transparent;
color: var(--c-text-3);
cursor: help;
}
}
.gl-mark-error {
display: flex;
align-items: center;
gap: 9px;
margin: 0 0 10px;
padding: 9px 14px;
border: 1px solid #fecaca;
background: var(--c-dr-bg);
border-radius: 8px;
font-size: 0.75rem;
color: #b91c1c;
&__close {
margin-left: auto;
border: 0;
background: transparent;
font-size: 1.1rem;
line-height: 1;
color: inherit;
cursor: pointer;
}
}
// ── Empty state ─────────────────────────────────────────────────────────────── // ── Empty state ───────────────────────────────────────────────────────────────
.gl-empty { .gl-empty {
display: flex; display: flex;
@@ -41,9 +41,20 @@ import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatTooltipModule } from '@angular/material/tooltip'; import { MatTooltipModule } from '@angular/material/tooltip';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatDialog } from '@angular/material/dialog';
import { AmlService } from 'app/aml/aml.service';
import { MarkEntryDialogComponent, MarkEntryDialogData } from './mark-entry-dialog.component';
const STATE_KEY = 'gl_ledger_filter_state'; const STATE_KEY = 'gl_ledger_filter_state';
/** How a ledger entry has been marked by a reviewer, keyed on journal entry id. */
interface EntryMark {
disposition: 'WHITELIST' | 'ESCALATE';
strCaseId: number | null;
reviewedBy: string;
notes: string;
}
@Component({ @Component({
selector: 'mifosx-search-journal-entry', selector: 'mifosx-search-journal-entry',
standalone: true, standalone: true,
@@ -87,6 +98,8 @@ export class SearchJournalEntryComponent implements OnInit, OnDestroy, AfterView
private settingsService = inject(SettingsService); private settingsService = inject(SettingsService);
private dateUtils = inject(Dates); private dateUtils = inject(Dates);
private route = inject(ActivatedRoute); private route = inject(ActivatedRoute);
private amlService = inject(AmlService);
private dialog = inject(MatDialog);
// ── Misc ────────────────────────────────────────────────────────────────── // ── Misc ──────────────────────────────────────────────────────────────────
minDate = new Date(2000, 0, 1); minDate = new Date(2000, 0, 1);
@@ -129,6 +142,7 @@ export class SearchJournalEntryComponent implements OnInit, OnDestroy, AfterView
'manualEntry', 'manualEntry',
'createdByUserName', 'createdByUserName',
'submittedOnDate', 'submittedOnDate',
'amlMark',
'actions' 'actions'
]; ];
dayWiseColumns = [ dayWiseColumns = [
@@ -157,6 +171,14 @@ export class SearchJournalEntryComponent implements OnInit, OnDestroy, AfterView
dayWiseData: any[] = []; dayWiseData: any[] = [];
glAccountInfo: any = null; glAccountInfo: any = null;
// ── AML marking ───────────────────────────────────────────────────────────
/** Marks already recorded, by journal entry id. */
private marks = new Map<number, EntryMark>();
/** Entry ids with a request in flight, so a row cannot be double-submitted. */
private marking = new Set<number>();
markError = '';
// ── UI state ────────────────────────────────────────────────────────────── // ── UI state ──────────────────────────────────────────────────────────────
activeQuickFilter = ''; activeQuickFilter = '';
activeFiltersCount = 0; activeFiltersCount = 0;
@@ -212,6 +234,103 @@ export class SearchJournalEntryComponent implements OnInit, OnDestroy, AfterView
this.setFilteredOffices(); this.setFilteredOffices();
this.getJournalEntries(); this.getJournalEntries();
this.loadLedgerSummary(); this.loadLedgerSummary();
this.loadMarks();
}
// ── AML marking ───────────────────────────────────────────────────────────
/**
* Marks are loaded once for the whole ledger rather than per page, because the
* user pages and re-filters constantly and the set is small — only entries a
* reviewer has actually touched.
*/
private loadMarks(): void {
this.amlService.getManualReferrals().subscribe({
next: (rows) => {
this.marks = new Map(
(rows || []).map((r: any) => [
r.journalEntryId,
{
disposition: r.disposition === 'ESCALATE' ? 'ESCALATE' : 'WHITELIST',
strCaseId: r.strCaseId ?? null,
reviewedBy: r.reviewedByUsername || '',
notes: r.reviewNotes || ''
} as EntryMark
])
);
},
// A ledger that cannot reach the AML service still has to render.
error: () => (this.marks = new Map())
});
}
markOf(entry: any): EntryMark | null {
return this.marks.get(entry?.id) ?? null;
}
isMarking(entry: any): boolean {
return this.marking.has(entry?.id);
}
/**
* An alert needs a customer, and a journal entry only reaches one through the
* savings, loan or client transaction that produced it. A purely manual GL
* posting reaches none, so it cannot be referred — the server enforces this too.
*/
canMark(entry: any): boolean {
return !!entry && !this.markOf(entry) && !!(entry.savingsAccountNo || entry.entityId);
}
markBlockedReason(entry: any): string {
if (this.markOf(entry)) {
return 'Already reviewed — a ledger entry is marked once';
}
return 'No customer behind this entry, so it cannot be referred';
}
openMarkDialog(entry: any, disposition: 'WHITELIST' | 'ESCALATE'): void {
if (!this.canMark(entry) || this.isMarking(entry)) {
return;
}
const data: MarkEntryDialogData = {
disposition,
journalEntryId: entry.id,
transactionId: entry.transactionId,
amount: entry.amount,
glAccountName: `${entry.glAccountCode} — ${entry.glAccountName}`,
transactionDate: this.dateUtils.formatDate(entry.transactionDate, this.settingsService.dateFormat)
};
this.dialog
.open(MarkEntryDialogComponent, { data, width: '520px', autoFocus: false })
.afterClosed()
.subscribe((notes: string | undefined) => {
if (notes !== undefined) {
this.submitMark(entry, disposition, notes);
}
});
}
private submitMark(entry: any, disposition: 'WHITELIST' | 'ESCALATE', notes: string): void {
this.markError = '';
this.marking.add(entry.id);
this.amlService.referJournalEntry(entry.id, disposition, notes).subscribe({
next: (res: any) => {
this.marking.delete(entry.id);
this.marks.set(entry.id, {
disposition,
strCaseId: res?.strCaseId ?? null,
reviewedBy: res?.reviewedByUsername || '',
notes
});
},
error: (err: any) => {
this.marking.delete(entry.id);
this.markError =
err?.error?.defaultUserMessage || err?.error?.errors?.[0]?.defaultUserMessage || 'Could not mark this entry.';
}
});
} }
ngOnDestroy() { ngOnDestroy() {
+111
View File
@@ -0,0 +1,111 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
/**
* AML transaction-monitoring API: live alerts raised by the rule engine, the
* two-tier AML Officer / Principal Officer review workflow, STR cases (with
* their 7-working-day FIU filing deadline), monthly CTR reports, and a
* client's risk-category change history.
*/
@Injectable({
providedIn: 'root'
})
export class AmlService {
private http = inject(HttpClient);
// ═══ Alerts (AML Officer) ═══
getAlerts(status?: string): Observable<any[]> {
const params = status ? new HttpParams().set('status', status) : undefined;
return this.http.get<any[]>('/aml/alerts', { params });
}
/** disposition: 'WHITELIST' | 'ESCALATE' */
reviewAlert(alertId: number, disposition: 'WHITELIST' | 'ESCALATE', notes: string): Observable<any> {
return this.http.post(`/aml/alerts/${alertId}/review`, { disposition, notes });
}
// ═══ Manual referrals from the general ledger ═══
/**
* Ledger entries a user has already marked, keyed on `journalEntryId`.
*
* Separate from `getAlerts()` because these are not engine alerts — they carry the
* journal entry id rather than a savings or loan transaction id, so the ledger
* screen can match them to the rows it is showing.
*/
getManualReferrals(): Observable<any[]> {
return this.http.get<any[]>('/aml/alerts/manual-referrals');
}
/**
* Marks a ledger entry. WHITELIST clears it with no report; ESCALATE opens an STR
* case for the Principal Officer, the same road an escalated engine alert takes.
* The entry must have a customer behind it or the server rejects it.
*/
referJournalEntry(journalEntryId: number, disposition: 'WHITELIST' | 'ESCALATE', notes: string): Observable<any> {
return this.http.post('/aml/alerts/manual-referral', { journalEntryId, disposition, notes });
}
// ═══ STR cases (Principal Officer) ═══
getStrCases(): Observable<any[]> {
return this.http.get<any[]>('/aml/str-cases');
}
getStrCase(strCaseId: number): Observable<any> {
return this.http.get(`/aml/str-cases/${strCaseId}`);
}
getWeeklyDigest(): Observable<any[]> {
return this.http.get<any[]>('/aml/str-cases/weekly-digest');
}
assignPrincipalOfficer(strCaseId: number, principalOfficerUserId: number): Observable<any> {
return this.http.post(`/aml/str-cases/${strCaseId}/assign`, { principalOfficerUserId });
}
/** conclusion: 'NOT_SUSPICIOUS' | 'SUSPICIOUS' */
concludeStrCase(
strCaseId: number,
conclusion: 'NOT_SUSPICIOUS' | 'SUSPICIOUS',
investigationNotes: string,
sourceOfFundsNotes: string
): Observable<any> {
return this.http.post(`/aml/str-cases/${strCaseId}/conclude`, {
conclusion,
investigationNotes,
sourceOfFundsNotes
});
}
fileStr(strCaseId: number, referenceNo: string): Observable<any> {
return this.http.post(`/aml/str-cases/${strCaseId}/file`, { referenceNo });
}
// ═══ CTR reports (mechanical, threshold-based) ═══
getCtrReports(): Observable<any[]> {
return this.http.get<any[]>('/aml/ctr-reports');
}
/** month format: yyyy-MM */
generateCtrReport(month: string): Observable<any> {
return this.http.post('/aml/ctr-reports/generate', { month });
}
// ═══ Client risk-category history ═══
getRiskCategoryHistory(clientId: number): Observable<any[]> {
return this.http.get<any[]>(`/clients/${clientId}/risk-category-history`);
}
}
+10
View File
@@ -64,7 +64,12 @@ import { BankCalendarModule } from './bank-calendar/bank-calendar.module';
import { DeafModule } from './deaf/deaf.module'; import { DeafModule } from './deaf/deaf.module';
import { DicgcModule } from './dicgc/dicgc.module'; import { DicgcModule } from './dicgc/dicgc.module';
import { FiuModule } from './fiu/fiu.module'; import { FiuModule } from './fiu/fiu.module';
import { GlReportsModule } from './gl-reports/gl-reports.module';
import { SftModule } from './sft/sft.module'; import { SftModule } from './sft/sft.module';
import { InvestmentModule } from './investment/investment.module';
import { NpaModule } from './npa/npa.module';
import { ReconciliationModule } from './reconciliation/reconciliation.module';
import { LoanOriginationModule } from './loan-origination/loan-origination.module';
import { DigitalModule } from './digital/digital.module'; import { DigitalModule } from './digital/digital.module';
import { LetterMgmtModule } from './letter-mgmt/letter-mgmt.module'; import { LetterMgmtModule } from './letter-mgmt/letter-mgmt.module';
import { AccountsModule } from './accounts/accounts.module'; import { AccountsModule } from './accounts/accounts.module';
@@ -171,7 +176,12 @@ export function HttpLoaderFactory(http: HttpClient) {
DeafModule, DeafModule,
DicgcModule, DicgcModule,
FiuModule, FiuModule,
GlReportsModule,
SftModule, SftModule,
InvestmentModule,
NpaModule,
ReconciliationModule,
LoanOriginationModule,
DigitalModule, DigitalModule,
LetterMgmtModule, LetterMgmtModule,
AccountsModule, AccountsModule,
@@ -0,0 +1,292 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<div class="pg">
<header class="pg-head">
<div>
<div class="pg-eyebrow">SUB LEDGER · TRANSACTIONS · {{ scopeName | uppercase }}</div>
<h1 class="pg-title">Cash / Clearing / Transfer - Summary Report</h1>
<p class="pg-sub">
Opening, credit, debit and closing position across Cash, Transfer, Clearing and Digital channels as on
{{ asOnDate }}.
</p>
</div>
<div class="pg-toolbar">
@if (isHeadOffice) {
<label class="pg-field">
<span>Branch</span>
<select class="pg-select" [ngModel]="selectedBranchCode" (ngModelChange)="setBranch($event)">
<option value="ALL">All Branches (Consolidated)</option>
@for (b of branches; track b.code) {
<option [value]="b.code">{{ b.name }}</option>
}
</select>
</label>
}
<button type="button" class="pg-btn" [class.pg-btn--active]="showDetails" (click)="toggleDetails()">
{{ showDetails ? 'Summary View' : 'Transaction Details' }}
</button>
<button type="button" class="pg-btn pg-btn--ghost" [disabled]="generating" (click)="exportExcel()">
{{ generating ? 'Exporting…' : 'Export to Excel' }}
</button>
</div>
</header>
<div class="cctr-grand-summary">
<div class="cctr-grand-summary__item">
<span class="cctr-grand-summary__label">Opening</span>
<span class="cctr-grand-summary__value">₹{{ grandOpening | number: '1.2-2' }}</span>
</div>
<div class="cctr-grand-summary__item">
<span class="cctr-grand-summary__label">Credit</span>
<span class="cctr-grand-summary__value col-in">₹{{ grandCredit | number: '1.2-2' }}</span>
</div>
<div class="cctr-grand-summary__item">
<span class="cctr-grand-summary__label">Debit</span>
<span class="cctr-grand-summary__value col-out">₹{{ grandDebit | number: '1.2-2' }}</span>
</div>
<div class="cctr-grand-summary__item">
<span class="cctr-grand-summary__label">Closing</span>
<span class="cctr-grand-summary__value">₹{{ grandClosing | number: '1.2-2' }}</span>
</div>
</div>
@if (isHeadOffice && selectedBranchCode === 'ALL') {
<div class="pg-card">
<div class="pos-section-label">Branch-wise Break-up — click a branch to drill in</div>
<table class="pg-table">
<thead>
<tr>
<th>Branch</th>
<th class="num">Opening</th>
<th class="num col-in">Credit</th>
<th class="num col-out">Debit</th>
<th class="num col-net">Closing</th>
</tr>
</thead>
<tbody>
@for (b of branchBreakup; track b.code) {
<tr class="cctr-branch-row" (click)="setBranch(b.code)">
<td>{{ b.name }}</td>
<td class="num">₹{{ b.opening | number: '1.2-2' }}</td>
<td class="num col-in">₹{{ b.credit | number: '1.2-2' }}</td>
<td class="num col-out">₹{{ b.debit | number: '1.2-2' }}</td>
<td class="num col-net">₹{{ b.closing | number: '1.2-2' }}</td>
</tr>
}
</tbody>
<tfoot>
<tr class="cctr-total-row">
<td>All Branches</td>
<td class="num">₹{{ grandOpening | number: '1.2-2' }}</td>
<td class="num">₹{{ grandCredit | number: '1.2-2' }}</td>
<td class="num">₹{{ grandDebit | number: '1.2-2' }}</td>
<td class="num">₹{{ grandClosing | number: '1.2-2' }}</td>
</tr>
</tfoot>
</table>
</div>
}
<div class="cctr-tabs">
<button
type="button"
class="pg-btn pg-btn--ghost"
[class.pg-btn--active]="activeTab === 'cash'"
(click)="setTab('cash')"
>
Cash
</button>
<button
type="button"
class="pg-btn pg-btn--ghost"
[class.pg-btn--active]="activeTab === 'transfer'"
(click)="setTab('transfer')"
>
Transfer
</button>
<button
type="button"
class="pg-btn pg-btn--ghost"
[class.pg-btn--active]="activeTab === 'clearing'"
(click)="setTab('clearing')"
>
Clearing
</button>
<button
type="button"
class="pg-btn pg-btn--ghost"
[class.pg-btn--active]="activeTab === 'digital'"
(click)="setTab('digital')"
>
Digital
</button>
</div>
<!-- Summary (Opening | Credit | Debit | Closing) -->
@if (!showDetails) {
<div class="pg-card">
@if (activeTab === 'digital') {
<div class="pos-section-label">RTGS · NEFT · UPI · ATM · NACH — Overall Position</div>
}
<table class="pg-table">
<thead>
<tr>
@if (activeTab !== 'digital') {
<th>GL Code</th>
}
<th>Particulars</th>
<th class="num">Opening</th>
<th class="num col-in">Credit</th>
<th class="num col-out">Debit</th>
<th class="num col-net">Closing</th>
</tr>
</thead>
<tbody>
@for (r of rowsForActiveTab; track r.code) {
<tr>
@if (activeTab !== 'digital') {
<td>
<span class="pg-chip">{{ r.code }}</span>
</td>
}
<td>{{ r.name }}</td>
<td class="num">₹{{ r.opening | number: '1.2-2' }}</td>
<td class="num col-in">₹{{ rowCredit(r, txnsForActiveTab) | number: '1.2-2' }}</td>
<td class="num col-out">₹{{ rowDebit(r, txnsForActiveTab) | number: '1.2-2' }}</td>
<td class="num col-net">₹{{ closing(r, txnsForActiveTab) | number: '1.2-2' }}</td>
</tr>
}
</tbody>
<tfoot>
<tr class="cctr-total-row">
<td [attr.colspan]="activeTab !== 'digital' ? 2 : 1">Total</td>
<td class="num">₹{{ total(rowsForActiveTab, txnsForActiveTab, 'opening') | number: '1.2-2' }}</td>
<td class="num">₹{{ total(rowsForActiveTab, txnsForActiveTab, 'credit') | number: '1.2-2' }}</td>
<td class="num">₹{{ total(rowsForActiveTab, txnsForActiveTab, 'debit') | number: '1.2-2' }}</td>
<td class="num">₹{{ totalClosing(rowsForActiveTab, txnsForActiveTab) | number: '1.2-2' }}</td>
</tr>
</tfoot>
</table>
</div>
}
<!-- Transaction Details (all txns for the selected category, optionally filtered by GL/channel) -->
@if (showDetails) {
@if (rowsForActiveTab.length > 1) {
<div class="cctr-tabs">
<button
type="button"
class="pg-btn pg-btn--ghost"
[class.pg-btn--active]="glFilter === null"
(click)="setGlFilter(null)"
>
All
</button>
@for (r of rowsForActiveTab; track r.code) {
<button
type="button"
class="pg-btn pg-btn--ghost"
[class.pg-btn--active]="glFilter === r.code"
(click)="setGlFilter(r.code)"
>
{{ filterLabel(r) }}
</button>
}
</div>
}
<div class="pg-card">
<div class="pos-section-label">
{{
activeTab === 'cash'
? 'Cash'
: activeTab === 'transfer'
? 'Transfer'
: activeTab === 'clearing'
? 'Clearing'
: 'Digital'
}}
— Transaction Details (Full Double Entry)
@if (glFilter !== null) {
· {{ glFilter }}
}
</div>
<table class="pg-table cctr-journal">
<thead>
<tr>
<th>Date</th>
<th>Voucher / Ref No</th>
<th>Dr / Cr</th>
<th>GL / Account</th>
<th class="num col-out">Debit</th>
<th class="num col-in">Credit</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@for (t of filteredTxns; track t.voucherNo) {
<tr class="cctr-journal-row cctr-journal-row--first">
<td>{{ asOnDate }}</td>
<td>
<span class="pg-chip">{{ display(t.voucherNo) }}</span>
</td>
<td><span class="cctr-drcr cctr-drcr--dr">Dr</span></td>
<td>
@if (t.debit > 0) {
<span class="pg-chip">{{ t.glCode }}</span> {{ glName(t.glCode) }} — {{ display(t.accountNo) }} ({{
t.accountName
}})
} @else {
<span class="cctr-contra">{{ contraLabel(t) }}</span>
}
</td>
<td class="num col-out">₹{{ legAmount(t) | number: '1.2-2' }}</td>
<td class="num"></td>
<td rowspan="2">
<span class="cctr-balanced-chip">✓ Balanced</span>
</td>
</tr>
<tr class="cctr-journal-row cctr-journal-row--second">
<td></td>
<td></td>
<td><span class="cctr-drcr cctr-drcr--cr">Cr</span></td>
<td>
@if (t.credit > 0) {
<span class="pg-chip">{{ t.glCode }}</span> {{ glName(t.glCode) }} — {{ display(t.accountNo) }} ({{
t.accountName
}})
} @else {
<span class="cctr-contra">{{ contraLabel(t) }}</span>
}
</td>
<td class="num"></td>
<td class="num col-in">₹{{ legAmount(t) | number: '1.2-2' }}</td>
</tr>
} @empty {
<tr>
<td colspan="7" class="pg-empty">No transactions for this filter.</td>
</tr>
}
</tbody>
<tfoot>
<tr class="cctr-total-row">
<td colspan="4">Total ({{ filteredTxns.length }} vouchers)</td>
<td class="num">
₹{{ txnTotal(filteredTxns, 'debit') + txnTotal(filteredTxns, 'credit') | number: '1.2-2' }}
</td>
<td class="num">
₹{{ txnTotal(filteredTxns, 'debit') + txnTotal(filteredTxns, 'credit') | number: '1.2-2' }}
</td>
<td></td>
</tr>
</tfoot>
</table>
</div>
}
</div>
@@ -0,0 +1,138 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
.cctr-tabs {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.cctr-total-row {
td {
background: #f1f5f9;
font-weight: 800;
border-top: 2px solid #cbd5e1;
border-bottom: none;
color: #0f172a;
}
}
.cctr-grand-summary {
display: flex;
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 12px;
overflow: hidden;
&__item {
flex: 1;
padding: 14px 20px;
display: flex;
flex-direction: column;
gap: 4px;
border-right: 1px solid #e2e8f0;
&:last-child {
border-right: none;
}
}
&__label {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.07em;
color: #64748b;
}
&__value {
font-size: 20px;
font-weight: 800;
font-variant-numeric: tabular-nums;
color: #0f172a;
}
}
.cctr-subtext {
font-size: 11px;
color: #94a3b8;
margin-top: 2px;
}
.cctr-branch-row {
cursor: pointer;
&:hover td {
background: #eff6ff;
}
}
// Both journal lines of one voucher share a tint and sit flush against each other (no dotted
// divider between them) so the pair reads as a single entry; a hairline separates one voucher's
// pair from the next.
.cctr-journal-row {
&--first td {
border-bottom: none;
padding-bottom: 4px;
}
&--second td {
border-top: none;
padding-top: 4px;
border-bottom: 1px solid #e2e8f0;
}
&--first,
&--second {
&:hover td {
background: #f8fafc;
}
}
}
.cctr-drcr {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 28px;
padding: 1px 8px;
border-radius: 6px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.03em;
&--dr {
background: #eff6ff;
color: #1d4ed8;
border: 1px solid #bfdbfe;
}
&--cr {
background: #f0fdf4;
color: #15803d;
border: 1px solid #bbf7d0;
}
}
.cctr-contra {
color: #64748b;
font-style: italic;
}
.cctr-balanced-chip {
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
background: #f0fdf4;
color: #15803d;
border: 1px solid #bbf7d0;
white-space: nowrap;
}
+88
View File
@@ -0,0 +1,88 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// Shared "Export to Excel" builder for Cashier reports (mirrors ../investment/investment-export.ts)
// — centralised so the ExcelJS boilerplate (title/meta/header rows, number formatting, safe sheet
// names, Blob download) is written once and every cashier report's export behaves the same way.
import * as ExcelJS from 'exceljs';
export interface ExportSheetSpec {
/** Worksheet tab name — sanitised for Excel's forbidden characters (\ / ? * [ ]) and length. */
sheetName: string;
/** Bold title row, merged across all columns. */
title: string;
/** Optional italic subtitle row (e.g. scope/date), merged across all columns. */
subtitle?: string;
headers: string[];
rows: (string | number | null)[][];
widths?: number[];
}
/** Excel worksheet names can't contain \ / ? * [ ] or exceed 31 chars. */
function safeSheetName(name: string): string {
return name.replace(/[\\/?*[\]]/g, '-').slice(0, 31);
}
function buildSheet(wb: ExcelJS.Workbook, spec: ExportSheetSpec): void {
const sheet = wb.addWorksheet(safeSheetName(spec.sheetName));
sheet.columns = (spec.widths || spec.headers.map(() => 18)).map((w) => ({ width: w }));
const title = sheet.addRow([spec.title]);
sheet.mergeCells(title.number, 1, title.number, spec.headers.length);
title.font = { bold: true, size: 14, color: { argb: 'FFFFFFFF' } };
title.alignment = { horizontal: 'center', vertical: 'middle' };
title.height = 24;
title.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF0F4F3C' } };
if (spec.subtitle) {
const meta = sheet.addRow([spec.subtitle]);
sheet.mergeCells(meta.number, 1, meta.number, spec.headers.length);
meta.font = { italic: true, size: 10 };
}
sheet.addRow([]);
const head = sheet.addRow(spec.headers);
head.font = { bold: true };
head.alignment = { wrapText: true, horizontal: 'center' };
head.eachCell((c) => {
c.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE2E8F0' } };
c.border = { bottom: { style: 'thin' } };
});
for (const r of spec.rows) {
const row = sheet.addRow(r);
r.forEach((v, idx) => {
if (typeof v === 'number') {
row.getCell(idx + 1).numFmt = '#,##0.00';
}
});
}
sheet.views = [{ state: 'frozen', ySplit: spec.subtitle ? 4 : 3 }];
}
/** Builds a (possibly multi-sheet) workbook and triggers a browser download. */
export async function exportWorkbook(sheets: ExportSheetSpec[], fileName: string): Promise<void> {
const wb = new ExcelJS.Workbook();
wb.creator = 'CBSNexora';
wb.created = new Date();
sheets.forEach((s) => buildSheet(wb, s));
const buffer = await wb.xlsx.writeBuffer();
const blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${fileName.replace(/[^\w]+/g, '-')}.xlsx`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
+11
View File
@@ -179,6 +179,17 @@ const routes: Routes = [
loadComponent: () => loadComponent: () =>
import('./my-deposit-requests/my-deposit-requests.component').then((m) => m.MyDepositRequestsComponent), import('./my-deposit-requests/my-deposit-requests.component').then((m) => m.MyDepositRequestsComponent),
data: { title: 'My Deposit Requests', breadcrumb: 'My Deposit Requests' } data: { title: 'My Deposit Requests', breadcrumb: 'My Deposit Requests' }
},
{
path: 'cash-clearing-transfer-summary',
loadComponent: () =>
import('./cash-clearing-transfer-summary/cash-clearing-transfer-summary.component').then(
(m) => m.CashClearingTransferSummaryComponent
),
data: {
title: 'Cash / Clearing / Transfer - Summary Report',
breadcrumb: 'Cash / Clearing / Transfer - Summary Report'
}
} }
] ]
} }
@@ -394,7 +394,12 @@ export class JointHolderDialogComponent implements OnInit {
this.kyc = kycArr[0] ?? null; this.kyc = kycArr[0] ?? null;
this.photo = photo ?? null; this.photo = photo ?? null;
const docs: any[] = Array.isArray(documents) ? documents : []; const docs: any[] = Array.isArray(documents) ? documents : [];
const sigDoc = docs.find((d: any) => d.name === 'clientSignature' || d.name?.toLowerCase().includes('signature')); // Multiple 'clientSignature' documents can exist for clients who re-cropped/replaced their
// signature before uploads became single-slot, so pick the highest id (latest) rather than
// the first unordered match.
const sigDoc = docs
.filter((d: any) => d.name === 'clientSignature' || d.name?.toLowerCase().includes('signature'))
.sort((a: any, b: any) => b.id - a.id)[0];
this.loading = false; this.loading = false;
if (sigDoc) { if (sigDoc) {
this.http this.http
@@ -1868,7 +1873,12 @@ export class TransactionEntryComponent implements OnInit, OnDestroy {
this.clientAddresses = Array.isArray(r.addresses) ? r.addresses : []; this.clientAddresses = Array.isArray(r.addresses) ? r.addresses : [];
this.clientPhotoUrl = r.photo ?? null; this.clientPhotoUrl = r.photo ?? null;
const docs: any[] = Array.isArray(r.documents) ? r.documents : []; const docs: any[] = Array.isArray(r.documents) ? r.documents : [];
const sigDoc = docs.find((d: any) => d.name === 'clientSignature' || d.name?.toLowerCase().includes('signature')); // Multiple 'clientSignature' documents can exist for clients who re-cropped/replaced their
// signature before uploads became single-slot, so pick the highest id (latest) rather than
// the first unordered match.
const sigDoc = docs
.filter((d: any) => d.name === 'clientSignature' || d.name?.toLowerCase().includes('signature'))
.sort((a: any, b: any) => b.id - a.id)[0];
if (sigDoc) { if (sigDoc) {
this.http this.http
.get(`/clients/${clientId}/documents/${sigDoc.id}/attachment`, { responseType: 'blob' }) .get(`/clients/${clientId}/documents/${sigDoc.id}/attachment`, { responseType: 'blob' })
@@ -12,16 +12,16 @@
* have meaningful variety out of the box. * have meaningful variety out of the box.
*/ */
export const SAMPLE_CKYC_FILE = `10|24401|IN4711|MH|30|31-08-2020|V1.1||||| export const SAMPLE_CKYC_FILE = `10|24401|IN4711|MH|30|31-08-2020|V1.1|||||
20|1|01|01|||||||||||01|||01|10078|MR|RAVI|KUMAR|SHARMA|||||||01|MR|RAJESH|KUMAR|SHARMA||MRS|SUNITA|DEVI|||M|02|IN|B-01|10-08-1985|||||||||01|02|||||02|FLAT 402, SUNRISE TOWERS|MAROL ANDHERI EAST|MUMBAI|MUMBAI|MUMBAI|MH|IN|400069|01||Y|02|FLAT 402, SUNRISE TOWERS|MAROL ANDHERI EAST|MUMBAI|MUMBAI|MUMBAI|MH|IN|400069|01||||||||||||||||9892011001|||||31-08-2020|MUMBAI MAIN|31-08-2020|01|ANJALI MEHTA|ASSISTANT MANAGER|HEAD OFFICE|4|BHARAT URBAN BANK|IN4711|1|0||0|4|||||| 20|1|01|01|||||||||||01|||01|10078|MR|RAVI|KUMAR|SHARMA|||||||01|MR|RAJESH|KUMAR|SHARMA||MRS|SUNITA|DEVI|||M|02|IN|B-01|10-08-1985|||||||||01|02|||||02|FLAT 402, SUNRISE TOWERS|MAROL ANDHERI EAST|MUMBAI|MUMBAI|MUMBAI|MH|IN|400069|01||Y|02|FLAT 402, SUNRISE TOWERS|MAROL ANDHERI EAST|MUMBAI|MUMBAI|MUMBAI|MH|IN|400069|01||||||||||||||||9892011001|||||31-08-2020|MUMBAI MAIN|31-08-2020|01|ANJALI MEHTA|ASSISTANT MANAGER|HEAD OFFICE|4|CBSNEXORA BANK|IN4711|1|0||0|4||||||
30|1|C|AAQPS8560J||01|02||||| 30|1|C|AAQPS8560J||01|02|||||
70|1|10078_Sign.jpeg|09|01|01|||| 70|1|10078_Sign.jpeg|09|01|01||||
70|1|10078_Photo.jpeg|02|01|01|||| 70|1|10078_Photo.jpeg|02|01|01||||
70|1|10078_AP.jpg|04|01|01|||| 70|1|10078_AP.jpg|04|01|01||||
20|2|01|01|||||||||||01|||01|10079|MRS|PRIYA||PATEL|||||||01|MR|HARISH|PATEL|||MRS|MEENA|PATEL|||F|01|IN|O-04|22-03-1990|||||||||01|02|||||02|B-12, SHIVAJI NAGAR|FC ROAD|PUNE|PUNE|PUNE|MH|IN|411005|01||Y|02|B-12, SHIVAJI NAGAR|FC ROAD|PUNE|PUNE|PUNE|MH|IN|411005|01||||||||||||||||9822055002|||||31-08-2020|PUNE FC ROAD|31-08-2020|01|VIKRAM SINGH|BRANCH MANAGER|HEAD OFFICE|4|BHARAT URBAN BANK|IN4711|1|0||0|3|||||| 20|2|01|01|||||||||||01|||01|10079|MRS|PRIYA||PATEL|||||||01|MR|HARISH|PATEL|||MRS|MEENA|PATEL|||F|01|IN|O-04|22-03-1990|||||||||01|02|||||02|B-12, SHIVAJI NAGAR|FC ROAD|PUNE|PUNE|PUNE|MH|IN|411005|01||Y|02|B-12, SHIVAJI NAGAR|FC ROAD|PUNE|PUNE|PUNE|MH|IN|411005|01||||||||||||||||9822055002|||||31-08-2020|PUNE FC ROAD|31-08-2020|01|VIKRAM SINGH|BRANCH MANAGER|HEAD OFFICE|4|CBSNEXORA BANK|IN4711|1|0||0|3||||||
30|2|E|XXXXXXXX2210||01|02||||| 30|2|E|XXXXXXXX2210||01|02|||||
70|2|10079_Sign.jpeg|09|01|01|||| 70|2|10079_Sign.jpeg|09|01|01||||
70|2|10079_Photo.jpeg|02|01|01|||| 70|2|10079_Photo.jpeg|02|01|01||||
20|3|01|01|||||||||||01|||01|10080|MR|ARJUN||DESHMUKH|||||||01|MR|VIJAY|DESHMUKH|||MRS|REKHA|DESHMUKH|||M|01|IN|B-01|15-01-1978|||||||||01|02|||||02|HOUSE NO 7, DHARAMPETH|RAMDASPETH|NAGPUR|NAGPUR|NAGPUR|MH|IN|440010|01||Y|02|HOUSE NO 7, DHARAMPETH|RAMDASPETH|NAGPUR|NAGPUR|NAGPUR|MH|IN|440010|01||||||||||||||||9823033003|||||30-08-2020|NAGPUR DHARAMPETH|30-08-2020|01|RAHUL JOSHI|ASSISTANT MANAGER|HEAD OFFICE|4|BHARAT URBAN BANK|IN4711|1|0||0|3|||||| 20|3|01|01|||||||||||01|||01|10080|MR|ARJUN||DESHMUKH|||||||01|MR|VIJAY|DESHMUKH|||MRS|REKHA|DESHMUKH|||M|01|IN|B-01|15-01-1978|||||||||01|02|||||02|HOUSE NO 7, DHARAMPETH|RAMDASPETH|NAGPUR|NAGPUR|NAGPUR|MH|IN|440010|01||Y|02|HOUSE NO 7, DHARAMPETH|RAMDASPETH|NAGPUR|NAGPUR|NAGPUR|MH|IN|440010|01||||||||||||||||9823033003|||||30-08-2020|NAGPUR DHARAMPETH|30-08-2020|01|RAHUL JOSHI|ASSISTANT MANAGER|HEAD OFFICE|4|CBSNEXORA BANK|IN4711|1|0||0|3||||||
30|3|C|AGTPD1144K||01|02||||| 30|3|C|AGTPD1144K||01|02|||||
70|3|10080_Sign.jpeg|09|01|01|||| 70|3|10080_Sign.jpeg|09|01|01||||
70|3|10080_AP.jpg|04|01|01|||| 70|3|10080_AP.jpg|04|01|01||||
@@ -446,8 +446,12 @@ export class RecordMasterComponent implements OnInit {
}; };
} }
// 2. Signature — client document named 'clientSignature' // 2. Signature — client document named 'clientSignature'. Multiple rows can exist for
const signatureDoc = (documents as any[])?.find((d: any) => d?.name === 'clientSignature'); // clients who re-cropped/replaced their signature before uploads became single-slot, so
// pick the highest id (latest) rather than the first unordered match.
const signatureDoc = (documents as any[])
?.filter((d: any) => d?.name === 'clientSignature')
?.sort((a: any, b: any) => b.id - a.id)?.[0];
if (signatureDoc) { if (signatureDoc) {
this.viewDetails.docs.signature = { this.viewDetails.docs.signature = {
present: true, present: true,
@@ -66,9 +66,12 @@ export class SignatoryService {
fetchClientSignature(clientId: number | string): Observable<string | null> { fetchClientSignature(clientId: number | string): Observable<string | null> {
return this.http.get<any[]>(`/clients/${clientId}/documents`).pipe( return this.http.get<any[]>(`/clients/${clientId}/documents`).pipe(
switchMap((docs: any[]) => { switchMap((docs: any[]) => {
const sigDoc = (docs || []).find( // Multiple 'clientSignature' documents can exist for clients who re-cropped/replaced
(d: any) => d.name === 'clientSignature' || d.name?.toLowerCase().includes('signature') // their signature before uploads became single-slot, so pick the highest id (latest)
); // rather than the first unordered match.
const sigDoc = (docs || [])
.filter((d: any) => d.name === 'clientSignature' || d.name?.toLowerCase().includes('signature'))
.sort((a: any, b: any) => b.id - a.id)[0];
if (!sigDoc) { if (!sigDoc) {
return of(null); return of(null);
} }
@@ -62,6 +62,22 @@
</div> </div>
} }
<!-- Mother requirement — shown independently of the Father/Caretaker check below -->
@if (!nomineeOnly && clientFamilyMembers.length > 0 && !hasMother) {
<div class="fm-step__empty fm-step__empty--required">
<mat-icon class="fm-step__empty-icon">error_outline</mat-icon>
<span class="fm-step__empty-required">Mother is required.</span>
</div>
}
<!-- Father-or-Caretaker requirement — shown independently of the Mother check above -->
@if (!nomineeOnly && clientFamilyMembers.length > 0 && !hasFather && !hasCaretaker) {
<div class="fm-step__empty fm-step__empty--required">
<mat-icon class="fm-step__empty-icon">error_outline</mat-icon>
<span class="fm-step__empty-required">Either Father or a Caretaker is required.</span>
</div>
}
<!-- Spouse hint for married clients --> <!-- Spouse hint for married clients -->
@if (!nomineeOnly && isMarried && !hasSpouse) { @if (!nomineeOnly && isMarried && !hasSpouse) {
<div class="fm-spouse-hint"> <div class="fm-spouse-hint">
@@ -12,6 +12,7 @@ import { TranslateService } from '@ngx-translate/core';
import { DeleteDialogComponent } from 'app/shared/delete-dialog/delete-dialog.component'; import { DeleteDialogComponent } from 'app/shared/delete-dialog/delete-dialog.component';
import { ClientFamilyMemberDialogComponent } from './client-family-member-dialog/client-family-member-dialog.component'; import { ClientFamilyMemberDialogComponent } from './client-family-member-dialog/client-family-member-dialog.component';
import { ImageZoomDialogComponent } from './client-family-member-dialog/client-family-member-dialog.component'; import { ImageZoomDialogComponent } from './client-family-member-dialog/client-family-member-dialog.component';
import { FamilyMemberAddedDialogComponent } from './family-member-added-dialog.component';
import { ClientsService } from '../../clients.service'; import { ClientsService } from '../../clients.service';
import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { MatIcon } from '@angular/material/icon'; import { MatIcon } from '@angular/material/icon';
@@ -152,6 +153,22 @@ export class ClientFamilyMembersStepComponent implements OnInit {
ref.afterClosed().subscribe((response: any) => { ref.afterClosed().subscribe((response: any) => {
if (response?.member) { if (response?.member) {
this.clientFamilyMembers.push(response.member); this.clientFamilyMembers.push(response.member);
this.showFamilyMemberAddedConfirmation(response.member);
}
});
}
/** Confirms what was just recorded — in particular the linked client's own CBS Client ID,
* since the "Add Member" dialog closes silently otherwise and gives no acknowledgement. */
private showFamilyMemberAddedConfirmation(member: any): void {
this.dialog.open(FamilyMemberAddedDialogComponent, {
width: '360px',
data: {
clientId: member._linkedClient?.id ?? member.linkedClientId ?? null,
name: member._linkedClient?.displayName || member.firstName,
relationship: this.getRelName(member.relationshipId),
dateOfBirth: member.dateOfBirth,
isDependent: member.isDependent
} }
}); });
} }
@@ -223,6 +240,33 @@ export class ClientFamilyMembersStepComponent implements OnInit {
return this.clientFamilyMembers.length > 0; return this.clientFamilyMembers.length > 0;
} }
/** True if a family member with the given relationship (case-insensitive) has been added */
private hasRelationship(name: string): boolean {
const target = name.toLowerCase();
return this.clientFamilyMembers.some((m: any) => {
const resolved = this.getRelName(m.relationshipId ?? m.relationship).toLowerCase();
if (resolved === target) return true;
return typeof m.relationship === 'string' && m.relationship.toLowerCase() === target;
});
}
get hasMother(): boolean {
return this.hasRelationship('mother');
}
get hasFather(): boolean {
return this.hasRelationship('father');
}
get hasCaretaker(): boolean {
return this.hasRelationship('caretaker');
}
/** Mother is always required; Father is required unless a Caretaker has been added instead. */
get familyRelationshipRulesMet(): boolean {
return this.hasMother && (this.hasFather || this.hasCaretaker);
}
/** Check if client's marital status is "Married" */ /** Check if client's marital status is "Married" */
get isMarried(): boolean { get isMarried(): boolean {
if (!this.maritalStatusId || !this.maritalStatusOptions?.length) return false; if (!this.maritalStatusId || !this.maritalStatusOptions?.length) return false;
@@ -0,0 +1,145 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Component, inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogTitle, MatDialogActions } from '@angular/material/dialog';
import { MatIcon } from '@angular/material/icon';
import { MatButton } from '@angular/material/button';
/**
* Confirmation popup shown right after a family member is added — surfaces the linked
* client's own CBS Client ID (when the member was linked to an existing client rather than
* entered manually) alongside name/relationship, since the "Add Member" dialog itself just
* closed silently before this with no acknowledgement of what got recorded.
*/
@Component({
selector: 'mifosx-family-member-added-dialog',
imports: [
MatDialogTitle,
MatDialogActions,
MatIcon,
MatButton
],
template: `
<h2 mat-dialog-title class="fma-title">
<mat-icon class="fma-title__icon">check_circle</mat-icon>
Family Member Added
</h2>
<div class="fma-body">
@if (data.clientId) {
<div class="fma-row fma-row--id">
<span class="fma-row__label">Client ID</span>
<span class="fma-row__value fma-row__value--id">{{ data.clientId }}</span>
</div>
}
<div class="fma-row">
<span class="fma-row__label">Name</span>
<span class="fma-row__value">{{ data.name }}</span>
</div>
@if (data.relationship) {
<div class="fma-row">
<span class="fma-row__label">Relationship</span>
<span class="fma-row__value">{{ data.relationship }}</span>
</div>
}
@if (data.dateOfBirth) {
<div class="fma-row">
<span class="fma-row__label">Date of Birth</span>
<span class="fma-row__value">{{ data.dateOfBirth }}</span>
</div>
}
@if (data.isDependent) {
<div class="fma-row">
<span class="fma-row__label">Dependent</span>
<span class="fma-row__value">Yes</span>
</div>
}
</div>
<mat-dialog-actions align="end">
<button mat-flat-button color="primary" (click)="dialogRef.close()">Done</button>
</mat-dialog-actions>
`,
styles: [
`
.fma-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 17px;
font-weight: 700;
color: #0f172a;
margin: 0;
padding: 20px 24px 4px;
}
.fma-title__icon {
color: #059669;
}
.fma-body {
display: flex;
flex-direction: column;
gap: 2px;
padding: 12px 24px 8px;
min-width: 280px;
}
.fma-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 8px 0;
border-bottom: 1px solid #f1f5f9;
&:last-child {
border-bottom: none;
}
}
.fma-row__label {
font-size: 12px;
color: #64748b;
font-weight: 500;
}
.fma-row__value {
font-size: 13px;
color: #0f172a;
font-weight: 600;
text-align: right;
}
.fma-row--id {
background: #eff6ff;
margin: 0 -24px;
padding: 10px 24px;
}
.fma-row__value--id {
font-family: 'Roboto Mono', monospace;
color: #1353a0;
font-size: 14px;
}
mat-dialog-actions {
padding: 8px 24px 16px;
}
`
]
})
export class FamilyMemberAddedDialogComponent {
dialogRef = inject<MatDialogRef<FamilyMemberAddedDialogComponent>>(MatDialogRef);
data: {
clientId?: string | number | null;
name: string;
relationship?: string;
dateOfBirth?: string;
isDependent?: boolean;
} = inject(MAT_DIALOG_DATA);
}
@@ -136,7 +136,7 @@
| translate | translate
}} }}
</mat-label> </mat-label>
<input matInput required formControlName="fullname" /> <input matInput required formControlName="fullname" autocomplete="off" />
@if (createClientForm.controls.fullname.hasError('required')) { @if (createClientForm.controls.fullname.hasError('required')) {
<mat-error>Client name is <strong>required</strong></mat-error> <mat-error>Client name is <strong>required</strong></mat-error>
} @else if (createClientForm.controls.fullname.hasError('pattern')) { } @else if (createClientForm.controls.fullname.hasError('pattern')) {
@@ -214,7 +214,7 @@
<mat-form-field appearance="outline" class="name-field first-name"> <mat-form-field appearance="outline" class="name-field first-name">
<mat-label>{{ 'labels.inputs.First Name' | translate }}</mat-label> <mat-label>{{ 'labels.inputs.First Name' | translate }}</mat-label>
<span matPrefix class="field-prefix-icon"><mat-icon>badge</mat-icon></span> <span matPrefix class="field-prefix-icon"><mat-icon>badge</mat-icon></span>
<input matInput required formControlName="firstname" /> <input matInput required formControlName="firstname" autocomplete="off" />
@if (createClientForm.controls.firstname.hasError('required')) { @if (createClientForm.controls.firstname.hasError('required')) {
<mat-error>First name is <strong>required</strong></mat-error> <mat-error>First name is <strong>required</strong></mat-error>
} @else if (createClientForm.controls.firstname.hasError('pattern')) { } @else if (createClientForm.controls.firstname.hasError('pattern')) {
@@ -228,7 +228,7 @@
<mat-form-field appearance="outline" class="name-field middle-name"> <mat-form-field appearance="outline" class="name-field middle-name">
<mat-label>{{ 'labels.inputs.Middle Name' | translate }}</mat-label> <mat-label>{{ 'labels.inputs.Middle Name' | translate }}</mat-label>
<span matPrefix class="field-prefix-icon"><mat-icon>person_outline</mat-icon></span> <span matPrefix class="field-prefix-icon"><mat-icon>person_outline</mat-icon></span>
<input matInput formControlName="middlename" /> <input matInput formControlName="middlename" autocomplete="off" />
@if ( @if (
createClientForm.controls.middlename?.hasError('pattern') && createClientForm.controls.middlename?.hasError('pattern') &&
createClientForm.controls.middlename?.touched createClientForm.controls.middlename?.touched
@@ -241,7 +241,7 @@
<mat-form-field appearance="outline" class="name-field last-name"> <mat-form-field appearance="outline" class="name-field last-name">
<mat-label>{{ 'labels.inputs.Last Name' | translate }}</mat-label> <mat-label>{{ 'labels.inputs.Last Name' | translate }}</mat-label>
<span matPrefix class="field-prefix-icon"><mat-icon>person</mat-icon></span> <span matPrefix class="field-prefix-icon"><mat-icon>person</mat-icon></span>
<input matInput required formControlName="lastname" /> <input matInput required formControlName="lastname" autocomplete="off" />
@if (createClientForm.controls.lastname.hasError('required')) { @if (createClientForm.controls.lastname.hasError('required')) {
<mat-error>Last name is <strong>required</strong></mat-error> <mat-error>Last name is <strong>required</strong></mat-error>
} @else if (createClientForm.controls.lastname.hasError('pattern')) { } @else if (createClientForm.controls.lastname.hasError('pattern')) {
@@ -358,11 +358,14 @@
@if (isMinor) { @if (isMinor) {
<span class="minor-badge">Minor</span> <span class="minor-badge">Minor</span>
} }
@if (isSeniorCitizen) {
<span class="senior-citizen-badge">Senior Citizen</span>
}
</div> </div>
} }
</div> </div>
<!-- Minor / Guardian Mapping (mandatory if age < 10) --> <!-- Minor / Guardian Mapping (mandatory if age < 18) -->
@if (isMinor && createClientForm.get('legalFormId')?.value === LegalFormId.PERSON) { @if (isMinor && createClientForm.get('legalFormId')?.value === LegalFormId.PERSON) {
<div class="guardian-section"> <div class="guardian-section">
<!-- Header bar --> <!-- Header bar -->
@@ -995,6 +998,32 @@
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
} }
<!-- CLIENT CREATION contact-OTP verification — create mode only. Edit mode already has
its own dual old/new OTP panel in EditClientComponent's template; this single
"new value" block only makes sense for a brand-new client (no "old" destination to
verify against). Each block only appears once its own field passes validation, so
staff enter a plausible-looking number/email before being asked to verify it. -->
@if (!clientData) {
<div class="contact-otp-row">
@if (createClientForm.get('mobileNo')?.valid) {
<mifosx-client-contact-otp-block
channel="MOBILE"
[destination]="createClientForm.get('mobileNo')?.value"
label="Verify Mobile Number"
(stateChange)="onMobileOtpState($event)"
></mifosx-client-contact-otp-block>
}
@if (createClientForm.get('emailAddress')?.valid) {
<mifosx-client-contact-otp-block
channel="EMAIL"
[destination]="createClientForm.get('emailAddress')?.value"
label="Verify Email Address"
(stateChange)="onEmailOtpState($event)"
></mifosx-client-contact-otp-block>
}
</div>
}
</div> </div>
</div> </div>
@@ -1006,69 +1035,67 @@
Education &amp; Social Details Education &amp; Social Details
</h4> </h4>
<div class="form-grid"> <div class="form-grid">
<!-- Education Level (non-minor) --> <!-- Education Level -->
@if (!isMinor) { <mat-form-field appearance="outline" class="form-field">
<mat-form-field appearance="outline" class="form-field"> <mat-label>Education Level</mat-label>
<mat-label>Education Level</mat-label> <mat-select formControlName="educationLevelId">
<mat-select formControlName="educationLevelId"> <mat-select-trigger>
<mat-select-trigger> @if (getSelectedEducationLevel()) {
@if (getSelectedEducationLevel()) { <span class="icon-option">
<span class="icon-option"> <mat-icon class="icon-option-icon">{{
<mat-icon class="icon-option-icon">{{ getEducationLevelIcon(getSelectedEducationLevel().name)
getEducationLevelIcon(getSelectedEducationLevel().name) }}</mat-icon>
}}</mat-icon> {{ getSelectedEducationLevel().name }}
{{ getSelectedEducationLevel().name }} </span>
</span>
}
</mat-select-trigger>
@for (el of educationLevelOptions; track el) {
<mat-option [value]="el.id">
<span class="icon-option">
<mat-icon class="icon-option-icon">{{ getEducationLevelIcon(el.name) }}</mat-icon>
{{ el.name }}
</span>
</mat-option>
} }
</mat-select> </mat-select-trigger>
</mat-form-field> @for (el of educationLevelOptions; track el) {
<mat-option [value]="el.id">
<span class="icon-option">
<mat-icon class="icon-option-icon">{{ getEducationLevelIcon(el.name) }}</mat-icon>
{{ el.name }}
</span>
</mat-option>
}
</mat-select>
</mat-form-field>
<!-- Degree / Qualification (depends on Education Level) --> <!-- Degree / Qualification (depends on Education Level) -->
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
<mat-label>Degree / Qualification</mat-label> <mat-label>Degree / Qualification</mat-label>
<mat-select <mat-select
formControlName="degreeQualificationId" formControlName="degreeQualificationId"
[placeholder]="getSelectedEducationLevel() ? 'Select Degree' : 'Select Education Level first'" [placeholder]="getSelectedEducationLevel() ? 'Select Degree' : 'Select Education Level first'"
> >
<mat-select-trigger> <mat-select-trigger>
@if (getSelectedDegreeQualification()) { @if (getSelectedDegreeQualification()) {
<span class="icon-option"> <span class="icon-option">
<mat-icon class="icon-option-icon">{{ <mat-icon class="icon-option-icon">{{
getDegreeQualificationIcon(getSelectedDegreeQualification().name) getDegreeQualificationIcon(getSelectedDegreeQualification().name)
}}</mat-icon> }}</mat-icon>
{{ getSelectedDegreeQualification().name }} {{ getSelectedDegreeQualification().name }}
</span> </span>
}
</mat-select-trigger>
@for (dq of filteredDegreeQualificationOptions; track dq) {
<mat-option [value]="dq.id">
<span class="icon-option">
<mat-icon class="icon-option-icon">{{ getDegreeQualificationIcon(dq.name) }}</mat-icon>
{{ dq.name }}
</span>
</mat-option>
} }
@if (!getSelectedEducationLevel()) { </mat-select-trigger>
<mat-option disabled> @for (dq of filteredDegreeQualificationOptions; track dq) {
<em>Please select Education Level first</em> <mat-option [value]="dq.id">
</mat-option> <span class="icon-option">
} @else if (filteredDegreeQualificationOptions.length === 0) { <mat-icon class="icon-option-icon">{{ getDegreeQualificationIcon(dq.name) }}</mat-icon>
<mat-option disabled> {{ dq.name }}
<em>No options available</em> </span>
</mat-option> </mat-option>
} }
</mat-select> @if (!getSelectedEducationLevel()) {
</mat-form-field> <mat-option disabled>
} <em>Please select Education Level first</em>
</mat-option>
} @else if (filteredDegreeQualificationOptions.length === 0) {
<mat-option disabled>
<em>No options available</em>
</mat-option>
}
</mat-select>
</mat-form-field>
<!-- Religion --> <!-- Religion -->
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
@@ -1191,21 +1218,25 @@
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
<mat-label>Annual Turnover (Last FY)</mat-label> <mat-label>Annual Income</mat-label>
<span matPrefix class="rupee-prefix">&#8377;</span> <span matPrefix class="rupee-prefix">&#8377;</span>
<input matInput type="number" formControlName="annualTurnover" min="0" /> <input matInput type="number" formControlName="annualIncome" min="0" />
@if ( @if (
createClientForm.get('annualTurnover')?.hasError('pattern') && createClientForm.get('annualIncome')?.hasError('pattern') && createClientForm.get('annualIncome')?.touched
createClientForm.get('annualTurnover')?.touched
) { ) {
<mat-error>Enter a valid amount</mat-error> <mat-error>Enter a valid amount</mat-error>
} @else if ( } @else if (
createClientForm.get('annualTurnover')?.hasError('min') && createClientForm.get('annualTurnover')?.touched createClientForm.get('annualIncome')?.hasError('min') && createClientForm.get('annualIncome')?.touched
) { ) {
<mat-error>Amount cannot be negative</mat-error> <mat-error>Amount cannot be negative</mat-error>
} }
</mat-form-field> </mat-form-field>
<div class="full-width subsection-title">
<fa-icon icon="coins" class="subsection-icon"></fa-icon>
Other Income
</div>
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
<mat-label>Agriculture Income</mat-label> <mat-label>Agriculture Income</mat-label>
<span matPrefix class="rupee-prefix">&#8377;</span> <span matPrefix class="rupee-prefix">&#8377;</span>
@@ -1239,6 +1270,128 @@
<mat-error>Amount cannot be negative</mat-error> <mat-error>Amount cannot be negative</mat-error>
} }
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" class="form-field">
<mat-label>Monthly Turnover</mat-label>
<span matPrefix class="rupee-prefix">&#8377;</span>
<input matInput type="number" formControlName="monthlyTurnover" min="0" />
@if (
createClientForm.get('monthlyTurnover')?.hasError('pattern') &&
createClientForm.get('monthlyTurnover')?.touched
) {
<mat-error>Enter a valid amount</mat-error>
} @else if (
createClientForm.get('monthlyTurnover')?.hasError('min') && createClientForm.get('monthlyTurnover')?.touched
) {
<mat-error>Amount cannot be negative</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline" class="form-field">
<mat-label>Yearly Turnover</mat-label>
<span matPrefix class="rupee-prefix">&#8377;</span>
<input matInput type="number" formControlName="annualTurnover" min="0" />
@if (
createClientForm.get('annualTurnover')?.hasError('pattern') &&
createClientForm.get('annualTurnover')?.touched
) {
<mat-error>Enter a valid amount</mat-error>
} @else if (
createClientForm.get('annualTurnover')?.hasError('min') && createClientForm.get('annualTurnover')?.touched
) {
<mat-error>Amount cannot be negative</mat-error>
}
</mat-form-field>
<div class="full-width subsection-title">
<fa-icon icon="user-shield" class="subsection-icon"></fa-icon>
Senior Citizen / Person with Disability
</div>
@if (isSeniorCitizen) {
<div class="full-width senior-citizen-auto-note">
<fa-icon icon="check-circle"></fa-icon>
Senior Citizen (60+ years) — detected automatically from Date of Birth
</div>
<div class="full-width doc-upload-field">
<label class="doc-upload-label">
<input type="file" accept=".jpg,.jpeg,.png,.pdf" hidden (change)="onSeniorCitizenProofSelected($event)" />
<fa-icon icon="file-upload"></fa-icon>
@if (seniorCitizenProofFile) {
<span>{{ seniorCitizenProofFile.name }}</span>
} @else if (existingSeniorCitizenProofDoc) {
<span>{{ existingSeniorCitizenProofDoc.name }} (uploaded)</span>
} @else {
<span>Upload Senior Citizen Proof (Age / ID Proof) &mdash; optional</span>
}
</label>
@if (seniorCitizenProofFile) {
<button type="button" mat-icon-button (click)="removeSeniorCitizenProof()" matTooltip="Remove">
<mat-icon>close</mat-icon>
</button>
} @else if (existingSeniorCitizenProofDoc) {
<button type="button" mat-icon-button (click)="viewExistingSeniorCitizenProof()" matTooltip="View">
<mat-icon>visibility</mat-icon>
</button>
<button type="button" mat-icon-button (click)="removeExistingSeniorCitizenProof()" matTooltip="Remove">
<mat-icon>close</mat-icon>
</button>
}
</div>
}
<div class="checkbox-field full-width">
<mat-checkbox formControlName="isPwd">Person with Disability (PWD)</mat-checkbox>
</div>
@if (createClientForm.get('isPwd')?.value) {
<mat-form-field appearance="outline" class="form-field">
<mat-label>Disability Type</mat-label>
<mat-select formControlName="pwdCategoryId">
@for (category of pwdCategoryOptions; track category.id) {
<mat-option [value]="category.id">{{ category.name }}</mat-option>
}
</mat-select>
@if (seniorPwdDocsTouched && !createClientForm.get('pwdCategoryId')?.value) {
<mat-error>Disability type is required</mat-error>
}
</mat-form-field>
<div class="full-width doc-upload-field">
<label
class="doc-upload-label"
[class.doc-upload-label--missing]="
seniorPwdDocsTouched && !pwdCertificateFile && !existingPwdCertificateDoc
"
>
<input type="file" accept=".jpg,.jpeg,.png,.pdf" hidden (change)="onPwdCertificateSelected($event)" />
<fa-icon icon="file-upload"></fa-icon>
@if (pwdCertificateFile) {
<span>{{ pwdCertificateFile.name }}</span>
} @else if (existingPwdCertificateDoc) {
<span>{{ existingPwdCertificateDoc.name }} (uploaded)</span>
} @else {
<span>Upload Disability Certificate <span class="doc-upload-req">*</span></span>
}
</label>
@if (pwdCertificateFile) {
<button type="button" mat-icon-button (click)="removePwdCertificate()" matTooltip="Remove">
<mat-icon>close</mat-icon>
</button>
} @else if (existingPwdCertificateDoc) {
<button type="button" mat-icon-button (click)="viewExistingPwdCertificate()" matTooltip="View">
<mat-icon>visibility</mat-icon>
</button>
<button type="button" mat-icon-button (click)="removeExistingPwdCertificate()" matTooltip="Remove">
<mat-icon>close</mat-icon>
</button>
}
@if (seniorPwdDocsTouched && !pwdCertificateFile && !existingPwdCertificateDoc) {
<span class="doc-upload-error">Required when PWD is checked</span>
}
</div>
}
</div> </div>
</div> </div>
} }
@@ -56,6 +56,78 @@ form {
grid-column: 1 / -1; grid-column: 1 / -1;
} }
.senior-citizen-auto-note {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: #1074b9;
background: #eff6ff;
border: 1px solid #bfdbfe;
border-radius: 8px;
padding: 8px 12px;
margin-bottom: 8px;
}
.doc-upload-field {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.doc-upload-label {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
padding: 10px 14px;
border: 1px dashed #cbd5e1;
border-radius: 8px;
font-size: 13px;
color: #475569;
cursor: pointer;
transition: border-color 0.15s;
&:hover {
border-color: #1074b9;
}
&.doc-upload-label--missing {
border-color: #dc2626;
color: #dc2626;
}
}
.doc-upload-req {
color: #dc2626;
font-weight: 700;
}
.doc-upload-error {
font-size: 11px;
color: #dc2626;
}
.subsection-title {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: #6b7280;
margin: 20px 0 4px;
padding-top: 16px;
border-top: 1px solid #e5e7eb;
.subsection-icon {
color: var(--md-sys-color-primary, #1074b9);
font-size: 12px;
}
}
.checkbox-field { .checkbox-field {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -234,6 +306,18 @@ form {
letter-spacing: 0.5px; letter-spacing: 0.5px;
} }
.senior-citizen-badge {
font-size: 10px;
font-weight: 700;
padding: 2px 8px;
border-radius: 10px;
background: #eff6ff;
color: #1074b9;
margin-left: 6px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
/* ═══ Guardian Section (Redesigned) ═══ */ /* ═══ Guardian Section (Redesigned) ═══ */
.guardian-section { .guardian-section {
margin-top: 12px; margin-top: 12px;
@@ -1493,6 +1577,21 @@ form {
} }
} }
/* Create-time mobile/email OTP verification — spans both `.form-grid` columns so the two
* blocks sit on their own full-width row instead of disrupting the field/verify-button pairing
* above them. */
.contact-otp-row {
display: flex;
flex-wrap: wrap;
gap: 16px;
grid-column: 1 / -1;
margin-top: 4px;
mifosx-client-contact-otp-block {
flex: 1 1 260px;
}
}
@media (width <= 768px) { @media (width <= 768px) {
.form-grid { .form-grid {
grid-template-columns: 1fr; grid-template-columns: 1fr;
@@ -1516,6 +1615,10 @@ form {
max-width: none; max-width: none;
} }
} }
.contact-otp-row {
flex-direction: column;
}
} }
.guardian-card__avatar.has-photo { .guardian-card__avatar.has-photo {
@@ -46,10 +46,15 @@ import { MatSelectTrigger } from '@angular/material/select';
import { MatTooltip } from '@angular/material/tooltip'; import { MatTooltip } from '@angular/material/tooltip';
import { MatDialog, MAT_DIALOG_DATA, MatDialogContent, MatDialogClose } from '@angular/material/dialog'; import { MatDialog, MAT_DIALOG_DATA, MatDialogContent, MatDialogClose } from '@angular/material/dialog';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { DocumentPreviewDialogComponent } from '../../shared/document-preview-dialog/document-preview-dialog.component';
import { DateFormatPipe } from '../../../pipes/date-format.pipe'; import { DateFormatPipe } from '../../../pipes/date-format.pipe';
import { SanctionsVerifyDialogComponent } from './sanctions-verify-dialog.component'; import { SanctionsVerifyDialogComponent } from './sanctions-verify-dialog.component';
import { DipVerifyDialogComponent } from './dip-verify-dialog.component'; import { DipVerifyDialogComponent } from './dip-verify-dialog.component';
import { DinVerifyDialogComponent } from './din-verify-dialog.component'; import { DinVerifyDialogComponent } from './din-verify-dialog.component';
import {
ContactOtpBlockComponent,
ContactOtpState
} from 'app/clients/edit-client/contact-otp-block/contact-otp-block.component';
/** /**
* Create Client Component * Create Client Component
@@ -68,7 +73,8 @@ import { DinVerifyDialogComponent } from './din-verify-dialog.component';
MatIcon, MatIcon,
MatTooltip, MatTooltip,
MatSelectTrigger, MatSelectTrigger,
DateFormatPipe DateFormatPipe,
ContactOtpBlockComponent
] ]
}) })
export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges { export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges {
@@ -88,6 +94,148 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
/** Expose enum to template */ /** Expose enum to template */
readonly LegalFormId = LegalFormId; readonly LegalFormId = LegalFormId;
/** Senior Citizen proof is optional; the PWD certificate is mandatory (see seniorPwdDocsComplete). Both, when
* attached, are uploaded after client creation. */
seniorCitizenProofFile: File | null = null;
pwdCertificateFile: File | null = null;
/** Previously-uploaded documents, loaded in edit mode so the certificate doesn't appear to
* "disappear" on reopening — the raw File properties above only ever hold a fresh selection. */
existingSeniorCitizenProofDoc: { id: string; name: string } | null = null;
existingPwdCertificateDoc: { id: string; name: string } | null = null;
/** Disability categories (per the Rights of Persons with Disabilities Act, 2016) — fetched from
* m_code_value (code "PwdCategory") via the client template, same as occupationCategoryOptions.
* Admins can add/reorder/deactivate entries from System -> Manage Codes without a code change. */
pwdCategoryOptions: any[] = [];
riskRules: any[] = [];
/** Set true after a save attempt so the UI can highlight a missing required document */
seniorPwdDocsTouched = false;
/** Senior Citizen proof is optional. The PWD certificate + disability type are mandatory
* whenever the PWD checkbox is set. */
get seniorPwdDocsComplete(): boolean {
const pwdOk =
!this.createClientForm.get('isPwd')?.value ||
((!!this.pwdCertificateFile || !!this.existingPwdCertificateDoc) &&
!!this.createClientForm.get('pwdCategoryId')?.value);
return pwdOk;
}
markSeniorPwdDocsTouched(): void {
this.seniorPwdDocsTouched = true;
}
onSeniorCitizenProofSelected(event: any): void {
const file = event.target?.files?.[0];
if (file) {
this.seniorCitizenProofFile = file;
}
}
removeSeniorCitizenProof(): void {
this.seniorCitizenProofFile = null;
}
onPwdCertificateSelected(event: any): void {
const file = event.target?.files?.[0];
if (file) {
this.pwdCertificateFile = file;
}
}
removePwdCertificate(): void {
this.pwdCertificateFile = null;
}
/** Loads previously-uploaded senior-citizen-proof / PWD-certificate documents in edit mode —
* mirrors the KYC step's loadExistingSignature() pattern so re-opening edit shows what's
* already on file instead of an empty upload prompt. */
private loadExistingSeniorPwdDocuments(): void {
const clientId = this.clientData?.id;
if (!clientId) {
return;
}
this.clientService.getClientDocuments(clientId.toString()).subscribe({
next: (documents: any[]) => {
const seniorDoc = documents
?.filter((d: any) => d.name === 'seniorCitizenProof')
?.sort((a: any, b: any) => b.id - a.id)?.[0];
if (seniorDoc?.id) {
this.existingSeniorCitizenProofDoc = {
id: seniorDoc.id.toString(),
name: seniorDoc.fileName || 'Senior Citizen Proof'
};
}
const pwdDoc = documents
?.filter((d: any) => d.name === 'pwdCertificate')
?.sort((a: any, b: any) => b.id - a.id)?.[0];
if (pwdDoc?.id) {
this.existingPwdCertificateDoc = {
id: pwdDoc.id.toString(),
name: pwdDoc.fileName || 'Disability Certificate'
};
}
},
error: () => {}
});
}
viewExistingSeniorCitizenProof(): void {
const clientId = this.clientData?.id;
if (!clientId || !this.existingSeniorCitizenProofDoc) {
return;
}
this.clientService.downloadClientDocument(clientId.toString(), this.existingSeniorCitizenProofDoc.id).subscribe({
next: (blob: any) =>
this.dialog.open(DocumentPreviewDialogComponent, {
data: {
blob,
title: this.existingSeniorCitizenProofDoc?.name,
fileName: this.existingSeniorCitizenProofDoc?.name
}
}),
error: () => {}
});
}
removeExistingSeniorCitizenProof(): void {
const clientId = this.clientData?.id;
if (!clientId || !this.existingSeniorCitizenProofDoc) {
return;
}
this.clientService.deleteClientDocument(clientId.toString(), this.existingSeniorCitizenProofDoc.id).subscribe({
next: () => (this.existingSeniorCitizenProofDoc = null),
error: () => {}
});
}
viewExistingPwdCertificate(): void {
const clientId = this.clientData?.id;
if (!clientId || !this.existingPwdCertificateDoc) {
return;
}
this.clientService.downloadClientDocument(clientId.toString(), this.existingPwdCertificateDoc.id).subscribe({
next: (blob: any) =>
this.dialog.open(DocumentPreviewDialogComponent, {
data: { blob, title: this.existingPwdCertificateDoc?.name, fileName: this.existingPwdCertificateDoc?.name }
}),
error: () => {}
});
}
removeExistingPwdCertificate(): void {
const clientId = this.clientData?.id;
if (!clientId || !this.existingPwdCertificateDoc) {
return;
}
this.clientService.deleteClientDocument(clientId.toString(), this.existingPwdCertificateDoc.id).subscribe({
next: () => (this.existingPwdCertificateDoc = null),
error: () => {}
});
}
/** Minimum date allowed. */ /** Minimum date allowed. */
minDate = new Date(2000, 0, 1); minDate = new Date(2000, 0, 1);
/** Maximum date allowed. */ /** Maximum date allowed. */
@@ -150,8 +298,10 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
]; ];
/** Calculated age detail string (Y/M/D) */ /** Calculated age detail string (Y/M/D) */
calculatedAgeDetail: string | null = null; calculatedAgeDetail: string | null = null;
/** Whether client is a minor (age < 10) */ /** Whether client is a minor (age < 18) */
isMinor = false; isMinor = false;
/** Whether client is a senior citizen (age >= 60) — auto-detected from Date of Birth */
isSeniorCitizen = false;
/** Age breakdown for DB storage */ /** Age breakdown for DB storage */
ageBreakdown = { years: 0, months: 0, days: 0 }; ageBreakdown = { years: 0, months: 0, days: 0 };
@@ -183,6 +333,45 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
alternateDipLookupLogId: number | null = null; alternateDipLookupLogId: number | null = null;
/** Alternate DIP lookup timestamp from API */ /** Alternate DIP lookup timestamp from API */
alternateDipTimestamp: string | null = null; alternateDipTimestamp: string | null = null;
/**
* CLIENT CREATION contact-OTP verification state (mobileNo / emailAddress). Unlike the
* edit-flow dual old/new OTP panel in `EditClientComponent`, a brand-new client has no "old"
* destination to verify against — so only a single "new value" OTP-verification is needed
* per field here. Sent to the backend as `mobileNewOtpId`/`emailNewOtpId` alongside the rest
* of the create-client payload (see `CreateClientComponent.saveAndProceed()`), which requires
* both whenever `mobileNo`/`emailAddress` are present (and they always are — both are
* `Validators.required` on this form).
*/
mobileOtpVerified = false;
mobileNewOtpId: number | null = null;
emailOtpVerified = false;
emailNewOtpId: number | null = null;
/**
* Whether both mobile and email have been OTP-verified for CLIENT CREATION. Always `true`
* in edit mode (`clientData` set) — edit-time contact verification is gated separately by
* `EditClientComponent.contactVerificationComplete`, not by this component.
*/
get contactVerified(): boolean {
if (this.clientData) {
return true;
}
return this.mobileOtpVerified && this.emailOtpVerified;
}
/** Resets create-time OTP verification for mobileNo — called whenever the field's value
* changes after a prior verification, since that OTP no longer applies to the new value. */
onMobileOtpState(state: ContactOtpState): void {
this.mobileOtpVerified = state.verified;
this.mobileNewOtpId = state.otpId;
}
/** Resets create-time OTP verification for emailAddress — see `onMobileOtpState()`. */
onEmailOtpState(state: ContactOtpState): void {
this.emailOtpVerified = state.verified;
this.emailNewOtpId = state.otpId;
}
/** Constitution Types Master with KYC field metadata */ /** Constitution Types Master with KYC field metadata */
constitutionTypesMaster = [ constitutionTypesMaster = [
{ {
@@ -344,6 +533,8 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
screeningLogId: number | null = null; screeningLogId: number | null = null;
/** Snapshot of the name that was last verified — used to invalidate verification when name changes */ /** Snapshot of the name that was last verified — used to invalidate verification when name changes */
private verifiedName: string = ''; private verifiedName: string = '';
/** True while prefillForEdit() is patching historical monthly/annual values — see linkMonthlyAnnual(). */
private suppressMonthlyAnnualLink = false;
/** /**
* @param {FormBuilder} formBuilder Form Builder * @param {FormBuilder} formBuilder Form Builder
@@ -358,6 +549,18 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
ngOnInit() { ngOnInit() {
this.maxDate = this.settingsService.businessDate; this.maxDate = this.settingsService.businessDate;
this.setOptions(); this.setOptions();
// Risk rules are an enhancement on top of the default low/medium-risk fallback in
// calculatedRisk — if the endpoint isn't available (e.g. not yet deployed on this
// backend), fail silently rather than surfacing a raw HTTP-error toast to the user.
this.clientService.getClientRiskRules().subscribe({
next: (rules) => {
this.riskRules = rules || [];
},
error: () => {
this.riskRules = [];
}
});
// Fetch marital status options from code values // Fetch marital status options from code values
this.clientService.getCodeValuesByName('MaritalStatus').subscribe((options) => { this.clientService.getCodeValuesByName('MaritalStatus').subscribe((options) => {
this.maritalStatusOptions = options || []; this.maritalStatusOptions = options || [];
@@ -422,6 +625,51 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
} }
} }
/**
* Resets transient session state back to a blank-client baseline.
*
* This app's RouteReusableStrategy (core/route/route-reusable-strategy.ts) keeps the SAME
* component instance alive across repeat visits to /clients/create — `ngOnInit`/the
* constructor never re-run for a second "create new client" session. Without this, computed
* state like `isMinor`, the linked guardian, or a prior sanctions/OTP verification would leak
* from whatever client was created in the previous session into the new one. Called by
* CreateClientComponent whenever `route.data` re-emits (which happens on every navigation,
* even a reused one).
*/
resetForNewClient(): void {
this.createClientForm.reset();
// legalFormId's raw FormControl default is '' — the buildDependencies() subscription
// treats any non-PERSON value (including '') as "non-individual" and adds fullname /
// clientNonPersonDetails. Patch it back to the same PERSON default buildDependencies()
// itself applies on first construction, so a reset lands on a blank Individual client
// instead of stuck with leftover Entity-only controls.
this.createClientForm.get('legalFormId')?.setValue(LegalFormId.PERSON);
this.isMinor = false;
this.calculatedAgeDetail = null;
this.ageBreakdown = { years: 0, months: 0, days: 0 };
this.selectedGuardian = null;
this.guardianSearchText = '';
this.guardianSearchResults = [];
this.guardianExpanded = false;
if (this.createClientForm.get('guardianDetails')) {
this.createClientForm.removeControl('guardianDetails');
}
// Verification state must not carry over — a previous client's cleared sanctions
// screening or verified OTP must not silently apply to a different new client.
this.mobileVerified = false;
this.dipLookupLogId = null;
this.dipTimestamp = null;
this.alternateMobileVerified = false;
this.alternateDipLookupLogId = null;
this.alternateDipTimestamp = null;
this.mobileNewOtpId = null;
this.emailNewOtpId = null;
this.sanctionsVerified = false;
this.sanctionsBlocked = false;
this.screeningLogId = null;
this.verifiedName = '';
}
/** /**
* Pre-fills the General step form from a manually-entered family member * Pre-fills the General step form from a manually-entered family member
* when the user clicks "Create as Client" on the family members tab. * when the user clicks "Create as Client" on the family members tab.
@@ -461,6 +709,13 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
*/ */
private prefillForEdit() { private prefillForEdit() {
const data = this.clientData; const data = this.clientData;
this.loadExistingSeniorPwdDocuments();
// Loading an existing client's independently-saved monthly/annual values must not run
// through the auto-calc in linkMonthlyAnnual() — patching monthlyIncome then annualIncome
// (or vice versa) would otherwise have each overwrite the other via its valueChanges,
// instead of keeping the exact historical values as saved.
this.suppressMonthlyAnnualLink = true;
// Patch all base controls that exist on the form // Patch all base controls that exist on the form
this.createClientForm.patchValue({ this.createClientForm.patchValue({
@@ -477,17 +732,26 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
mobileNo: data.mobileNo, mobileNo: data.mobileNo,
alternateMobileNo: data.alternateMobileNo || '', alternateMobileNo: data.alternateMobileNo || '',
emailAddress: data.emailAddress, emailAddress: data.emailAddress,
dateOfBirth: data.dateOfBirth ? new Date(data.dateOfBirth) : '', dateOfBirth: data.dateOfBirth
? Array.isArray(data.dateOfBirth)
? new Date(data.dateOfBirth[0], data.dateOfBirth[1] - 1, data.dateOfBirth[2])
: new Date(data.dateOfBirth)
: '',
occupationCategoryId: data.occupationCategory?.id || data.occupationCategoryId || '', occupationCategoryId: data.occupationCategory?.id || data.occupationCategoryId || '',
occupationId: data.occupation?.id || data.occupationId || '', occupationId: data.occupation?.id || data.occupationId || '',
monthlyIncome: data.monthlyIncome || '', monthlyIncome: data.monthlyIncome || '',
annualIncome: data.annualIncome || '',
annualTurnover: data.annualTurnover || '', annualTurnover: data.annualTurnover || '',
monthlyTurnover: data.monthlyTurnover || '',
isPwd: data.isPwd || false,
pwdCategoryId: data.pwdCategory?.id || '',
agricultureIncome: data.agricultureIncome || '', agricultureIncome: data.agricultureIncome || '',
nonAgricultureIncome: data.nonAgricultureIncome || '', nonAgricultureIncome: data.nonAgricultureIncome || '',
submittedOnDate: data.timeline?.submittedOnDate submittedOnDate: data.timeline?.submittedOnDate
? new Date(data.timeline.submittedOnDate) ? new Date(data.timeline.submittedOnDate)
: this.settingsService.businessDate : this.settingsService.businessDate
}); });
this.suppressMonthlyAnnualLink = false;
// Patch name fields (already created by buildDependencies via legalFormId subscription) // Patch name fields (already created by buildDependencies via legalFormId subscription)
const legalFormId = data.legalForm?.id || LegalFormId.PERSON; const legalFormId = data.legalForm?.id || LegalFormId.PERSON;
@@ -555,6 +819,42 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
} }
}); });
} }
// Restore linked guardian for minor clients. The `guardianDetails` control group above was
// just created synchronously by the dateOfBirth subscription (patched a few lines up), which
// also resets `selectedGuardian` to null — so this has to run after that patch, not before it.
// If a guardian is linked in the database (or the client is marked minor), we force minor state
// and explicitly ensure the form control exists so the guardian details load correctly.
if ((data.isMinor || this.isMinor || data.guardianClientId) && data.guardianClientId) {
this.isMinor = true;
if (!this.createClientForm.get('guardianDetails')) {
this.createClientForm.addControl(
'guardianDetails',
this.formBuilder.group({
guardianClientId: [
'',
Validators.required
],
guardianRelation: [
'',
Validators.required
]
})
);
}
setTimeout(() => {
this.createClientForm.get('guardianDetails')?.patchValue({
guardianClientId: data.guardianClientId,
guardianRelation: data.guardianRelation || ''
});
this.selectedGuardian = {
id: data.guardianClientId,
displayName: data.guardianClientDisplayName || '',
_loading: true
};
this.fetchClientFullDetails(data.guardianClientId, this.selectedGuardian);
});
}
} }
/** /**
@@ -621,6 +921,13 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
Validators.min(0) Validators.min(0)
] ]
], ],
annualIncome: [
'',
[
Validators.pattern(/^\d+(\.\d{1,2})?$/),
Validators.min(0)
]
],
annualTurnover: [ annualTurnover: [
'', '',
[ [
@@ -628,6 +935,15 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
Validators.min(0) Validators.min(0)
] ]
], ],
monthlyTurnover: [
'',
[
Validators.pattern(/^\d+(\.\d{1,2})?$/),
Validators.min(0)
]
],
isPwd: [false],
pwdCategoryId: [''],
agricultureIncome: [ agricultureIncome: [
'', '',
[ [
@@ -647,6 +963,43 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
Validators.required Validators.required
] ]
}); });
this.linkMonthlyAnnual('monthlyIncome', 'annualIncome');
this.linkMonthlyAnnual('monthlyTurnover', 'annualTurnover');
}
/**
* Keeps a Monthly/Annual pair of amount fields in sync at a 12x ratio — typing into either
* one auto-fills the other. Uses { emitEvent: false } on the write side so the two
* subscriptions don't trigger each other back and forth.
*/
/** Rounds to at most 2 decimals without padding whole numbers with a trailing ".00". */
private round2(n: number): string {
return (Math.round(n * 100) / 100).toString();
}
private linkMonthlyAnnual(monthlyControlName: string, annualControlName: string): void {
const monthly = this.createClientForm.get(monthlyControlName);
const annual = this.createClientForm.get(annualControlName);
if (!monthly || !annual) {
return;
}
monthly.valueChanges.subscribe((value) => {
if (this.suppressMonthlyAnnualLink) {
return;
}
const num = parseFloat(value);
annual.setValue(!isNaN(num) && num >= 0 ? this.round2(num * 12) : '', { emitEvent: false });
});
annual.valueChanges.subscribe((value) => {
if (this.suppressMonthlyAnnualLink) {
return;
}
const num = parseFloat(value);
monthly.setValue(!isNaN(num) && num >= 0 ? this.round2(num / 12) : '', { emitEvent: false });
});
} }
/** /**
@@ -665,6 +1018,7 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
this.occupationCategoryOptions = this.clientTemplate.occupationCategoryOptions || []; this.occupationCategoryOptions = this.clientTemplate.occupationCategoryOptions || [];
this.occupationOptions = this.clientTemplate.occupationOptions || []; this.occupationOptions = this.clientTemplate.occupationOptions || [];
this.salutationOptions = this.clientTemplate.salutationOptions || []; this.salutationOptions = this.clientTemplate.salutationOptions || [];
this.pwdCategoryOptions = this.clientTemplate.pwdCategoryOptions || [];
} }
/** /**
@@ -780,7 +1134,8 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
this.calculatedAgeDetail = `${years} yr${years !== 1 ? 's' : ''} ${months} mo${months !== 1 ? 's' : ''} ${days} day${days !== 1 ? 's' : ''}`; this.calculatedAgeDetail = `${years} yr${years !== 1 ? 's' : ''} ${months} mo${months !== 1 ? 's' : ''} ${days} day${days !== 1 ? 's' : ''}`;
this.ageBreakdown = { years, months, days }; this.ageBreakdown = { years, months, days };
const wasMinor = this.isMinor; const wasMinor = this.isMinor;
this.isMinor = years < 10; this.isMinor = years < 18;
this.isSeniorCitizen = years >= 60;
// Add/remove guardian form group based on minor status // Add/remove guardian form group based on minor status
if (this.isMinor && !wasMinor) { if (this.isMinor && !wasMinor) {
this.createClientForm.addControl( this.createClientForm.addControl(
@@ -806,12 +1161,14 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
} else { } else {
this.calculatedAgeDetail = null; this.calculatedAgeDetail = null;
this.isMinor = false; this.isMinor = false;
this.isSeniorCitizen = false;
this.ageBreakdown = { years: 0, months: 0, days: 0 }; this.ageBreakdown = { years: 0, months: 0, days: 0 };
this.createClientForm.removeControl('guardianDetails'); this.createClientForm.removeControl('guardianDetails');
} }
} else { } else {
this.calculatedAgeDetail = null; this.calculatedAgeDetail = null;
this.isMinor = false; this.isMinor = false;
this.isSeniorCitizen = false;
this.ageBreakdown = { years: 0, months: 0, days: 0 }; this.ageBreakdown = { years: 0, months: 0, days: 0 };
this.createClientForm.removeControl('guardianDetails'); this.createClientForm.removeControl('guardianDetails');
} }
@@ -853,6 +1210,13 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
.valueChanges.pipe(takeUntil(this.destroy$)) .valueChanges.pipe(takeUntil(this.destroy$))
.subscribe(() => { .subscribe(() => {
this.mobileVerified = false; this.mobileVerified = false;
// Also reset create-time contact-OTP verification — an OTP verified against a
// previous mobile number no longer applies once the value is edited. Belt-and-braces
// alongside ContactOtpBlockComponent's own destination-change reset: this fires even
// if the OTP block was unmounted (e.g. `*ngIf` hid it while the field was momentarily
// invalid) and its own reset never had a chance to run.
this.mobileOtpVerified = false;
this.mobileNewOtpId = null;
}); });
this.createClientForm this.createClientForm
@@ -861,6 +1225,16 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
.subscribe(() => { .subscribe(() => {
this.alternateMobileVerified = false; this.alternateMobileVerified = false;
}); });
// Reset create-time contact-OTP verification when email address changes — see the
// mobileNo subscription above for the rationale.
this.createClientForm
.get('emailAddress')
.valueChanges.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.emailOtpVerified = false;
this.emailNewOtpId = null;
});
} }
ngOnChanges(changes: SimpleChanges) { ngOnChanges(changes: SimpleChanges) {
@@ -1487,6 +1861,9 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
if (n.includes('postgrad') || n === 'pg' || n.includes('master')) return 'postgraduate'; if (n.includes('postgrad') || n === 'pg' || n.includes('master')) return 'postgraduate';
if (n.includes('undergrad') || n === 'ug' || n.includes('bachelor') || n.includes('graduate')) if (n.includes('undergrad') || n === 'ug' || n.includes('bachelor') || n.includes('graduate'))
return 'undergraduate'; return 'undergraduate';
// Diploma is its own Education Level, distinct from School — checked before the school
// keywords below so it doesn't get swept into that bucket.
if (n.includes('diploma') || n.includes('polytechnic')) return 'diploma';
if ( if (
n.includes('school') || n.includes('school') ||
n.includes('10th') || n.includes('10th') ||
@@ -1495,7 +1872,6 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
n.includes('hsc') || n.includes('hsc') ||
n.includes('matric') || n.includes('matric') ||
n.includes('intermediate') || n.includes('intermediate') ||
n.includes('diploma') ||
n.includes('iti') || n.includes('iti') ||
n.includes('below') n.includes('below')
) )
@@ -1573,8 +1949,12 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
} }
/** /**
* Degrees filtered by the currently selected Education Level. * Degrees filtered by the currently selected Education Level. Each DegreeQualification code
* Returns all degrees if no level is selected, or category can't be determined. * value is tagged with its owning level in `description` (e.g. "Undergraduate") when seeded —
* match on that authoritative field first. Only fall back to the name-keyword heuristic
* (getDegreeQualificationCategory) for older/untagged rows that predate this tagging, so
* degrees never silently disappear because an admin added one without a description.
* Returns all degrees if no level is selected.
*/ */
get filteredDegreeQualificationOptions(): any[] { get filteredDegreeQualificationOptions(): any[] {
const level = this.getSelectedEducationLevel(); const level = this.getSelectedEducationLevel();
@@ -1582,6 +1962,9 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
const category = this.getEducationLevelCategory(level.name); const category = this.getEducationLevelCategory(level.name);
if (!category) return this.degreeQualificationOptions; if (!category) return this.degreeQualificationOptions;
const filtered = this.degreeQualificationOptions.filter((d: any) => { const filtered = this.degreeQualificationOptions.filter((d: any) => {
if (d.description) {
return this.getEducationLevelCategory(d.description) === category;
}
const c = this.getDegreeQualificationCategory(d.name); const c = this.getDegreeQualificationCategory(d.name);
return c === category || c === ''; return c === category || c === '';
}); });
@@ -1744,6 +2127,8 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
// Store extended fields separately (not yet supported by Fineract API) // Store extended fields separately (not yet supported by Fineract API)
// Add isMinor flag // Add isMinor flag
generalDetails.isMinor = this.isMinor; generalDetails.isMinor = this.isMinor;
// isSeniorCitizen is auto-detected from DOB (not a form control) — add it explicitly
generalDetails.isSeniorCitizen = this.isSeniorCitizen;
// Add guardian clientId for minors // Add guardian clientId for minors
if (this.isMinor && generalDetails.guardianDetails) { if (this.isMinor && generalDetails.guardianDetails) {
@@ -1794,6 +2179,121 @@ export class ClientGeneralStepComponent implements OnInit, OnDestroy, OnChanges
return generalDetails; return generalDetails;
} }
get calculatedRisk(): {
category: number;
reason: string;
amlCheckStatus?: string;
bannedEntityMatch?: string;
willfulDefaulter?: string;
ecgcSalFlag?: string;
dormantFlag?: string;
} {
const legalFormId = this.createClientForm.get('legalFormId')?.value || 1; // 1 = Person, 2 = Entity
const occCatId = this.createClientForm.get('occupationCategoryCvId')?.value;
const occId = this.createClientForm.get('occupationCvId')?.value;
const monthlyIncome = parseFloat(this.createClientForm.get('monthlyIncome')?.value) || 0;
const annualIncome = parseFloat(this.createClientForm.get('annualIncome')?.value) || 0;
const monthlyTurnover = parseFloat(this.createClientForm.get('monthlyTurnover')?.value) || 0;
const annualTurnover = parseFloat(this.createClientForm.get('annualTurnover')?.value) || 0;
const agricultureIncome = parseFloat(this.createClientForm.get('agricultureIncome')?.value) || 0;
const nonAgricultureIncome = parseFloat(this.createClientForm.get('nonAgricultureIncome')?.value) || 0;
const totalAnnualIncome = annualIncome + agricultureIncome + nonAgricultureIncome;
// Evaluate rules from DB (ordered by orderPosition ASC)
if (this.riskRules && this.riskRules.length > 0) {
for (const rule of this.riskRules) {
// Skip transaction/AML rules that have no KYC criteria
if (
rule.legalFormId == null &&
rule.occupationCategoryCvId == null &&
rule.occupationCvId == null &&
rule.minMonthlyIncome == null &&
rule.maxMonthlyIncome == null &&
rule.minAnnualIncome == null &&
rule.maxAnnualIncome == null &&
rule.minAnnualTurnover == null &&
rule.maxAnnualTurnover == null
) {
continue;
}
// Match legal form
if (rule.legalFormId != null && rule.legalFormId !== legalFormId) {
continue;
}
// Match occupation category
if (rule.occupationCategoryCvId != null && rule.occupationCategoryCvId !== occCatId) {
continue;
}
// Match occupation
if (rule.occupationCvId != null && rule.occupationCvId !== occId) {
continue;
}
// Match monthly income ranges
if (rule.minMonthlyIncome != null && rule.minMonthlyIncome > 0 && monthlyIncome < rule.minMonthlyIncome) {
continue;
}
if (rule.maxMonthlyIncome != null && rule.maxMonthlyIncome > 0 && monthlyIncome > rule.maxMonthlyIncome) {
continue;
}
// Match annual income ranges (evaluated against totalAnnualIncome)
if (rule.minAnnualIncome != null && rule.minAnnualIncome > 0 && totalAnnualIncome < rule.minAnnualIncome) {
continue;
}
if (rule.maxAnnualIncome != null && rule.maxAnnualIncome > 0 && totalAnnualIncome > rule.maxAnnualIncome) {
continue;
}
// Match turnover ranges
if (rule.minAnnualTurnover != null && rule.minAnnualTurnover > 0 && annualTurnover < rule.minAnnualTurnover) {
continue;
}
if (rule.maxAnnualTurnover != null && rule.maxAnnualTurnover > 0 && annualTurnover > rule.maxAnnualTurnover) {
continue;
}
// All matched!
return {
category: rule.riskCategory,
reason: rule.reason,
amlCheckStatus: rule.amlCheckStatus || (rule.riskCategory === 3 ? 'FLAGGED' : 'CLEAR'),
bannedEntityMatch: rule.bannedEntityMatch || 'NO',
willfulDefaulter: rule.willfulDefaulter || 'NO',
ecgcSalFlag: rule.ecgcSalFlag || 'NO',
dormantFlag: rule.dormantFlag || 'ACTIVE'
};
}
}
// Default Fallbacks
if (legalFormId !== LegalFormId.PERSON) {
return {
category: 2,
reason: 'Non-Individual / Entity profile (Default Medium Risk)',
amlCheckStatus: 'CLEAR',
bannedEntityMatch: 'NO',
willfulDefaulter: 'NO',
ecgcSalFlag: 'NO',
dormantFlag: 'ACTIVE'
};
}
return {
category: 1,
reason: 'Default Low Risk profile (Salary / Service / Agriculture / Others)',
amlCheckStatus: 'CLEAR',
bannedEntityMatch: 'NO',
willfulDefaulter: 'NO',
ecgcSalFlag: 'NO',
dormantFlag: 'ACTIVE'
};
}
} }
/** /**
@@ -42,6 +42,7 @@ import { ClientsService } from 'app/clients/clients.service';
<strong>UN Security Council</strong> &amp; <strong>UN Security Council</strong> &amp;
<strong>Financial Intelligence Unit - India (FIU-IND under UNSC Resolution 2231)</strong> <strong>Financial Intelligence Unit - India (FIU-IND under UNSC Resolution 2231)</strong>
</p> </p>
<p class="regulatory-note">{{ regulatoryBasis }}</p>
</div> </div>
} }
@if (!verifying && !matchFound && !errorOccurred) { @if (!verifying && !matchFound && !errorOccurred) {
@@ -69,7 +70,14 @@ import { ClientsService } from 'app/clients/clients.service';
<span class="meta-label">Database</span> <span class="meta-label">Database</span>
<span class="meta-value">UN SC Consolidated List</span> <span class="meta-value">UN SC Consolidated List</span>
</div> </div>
@if (listDataAsOf) {
<div class="meta-row">
<span class="meta-label">List Data As Of</span>
<span class="meta-value">{{ listDataAsOf }}</span>
</div>
}
</div> </div>
<p class="regulatory-note">{{ regulatoryBasis }}</p>
</div> </div>
} }
@if (!verifying && matchFound) { @if (!verifying && matchFound) {
@@ -96,11 +104,18 @@ import { ClientsService } from 'app/clients/clients.service';
<span class="meta-label">Database</span> <span class="meta-label">Database</span>
<span class="meta-value">UN SC Consolidated List</span> <span class="meta-value">UN SC Consolidated List</span>
</div> </div>
@if (listDataAsOf) {
<div class="meta-row">
<span class="meta-label">List Data As Of</span>
<span class="meta-value">{{ listDataAsOf }}</span>
</div>
}
</div> </div>
<div class="escalate-banner"> <div class="escalate-banner">
<fa-icon icon="exclamation-circle" class="escalate-icon"></fa-icon> <fa-icon icon="exclamation-circle" class="escalate-icon"></fa-icon>
<span><strong>Escalate to Principal Officer immediately.</strong> Account opening blocked.</span> <span><strong>Escalate to Principal Officer immediately.</strong> Account opening blocked.</span>
</div> </div>
<p class="regulatory-note">{{ regulatoryBasis }}</p>
</div> </div>
} }
@if (!verifying && errorOccurred) { @if (!verifying && errorOccurred) {
@@ -207,6 +222,15 @@ import { ClientsService } from 'app/clients/clients.service';
text-align: center; text-align: center;
} }
.regulatory-note {
font-size: 11px;
color: #9ca3af;
line-height: 1.5;
text-align: center;
margin: 8px 0 0;
max-width: 420px;
}
.approve-card { .approve-card {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
@@ -524,6 +548,10 @@ export class SanctionsVerifyDialogComponent implements OnInit, OnDestroy {
errorOccurred = false; errorOccurred = false;
errorMessage = ''; errorMessage = '';
screeningLogId: number | null = null; screeningLogId: number | null = null;
listDataAsOf: string | null = null;
regulatoryBasis =
'Screened as per Section 51-A of the Unlawful Activities (Prevention) Act, 1967 and the RBI Master Direction on KYC.';
screenedDate = new Date().toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' }); screenedDate = new Date().toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
progressValue = 0; progressValue = 0;
@@ -624,6 +652,13 @@ export class SanctionsVerifyDialogComponent implements OnInit, OnDestroy {
'Unable to connect to sanctions screening service.'; 'Unable to connect to sanctions screening service.';
} else { } else {
this.screeningLogId = this.apiResult?.screeningLogId || null; this.screeningLogId = this.apiResult?.screeningLogId || null;
this.listDataAsOf = this.apiResult?.listDataAsOf
? new Date(this.apiResult.listDataAsOf).toLocaleDateString('en-IN', {
day: '2-digit',
month: 'short',
year: 'numeric'
})
: null;
if (this.apiResult?.matchFound) { if (this.apiResult?.matchFound) {
this.matchFound = true; this.matchFound = true;
this.matchCount = this.apiResult.matchCount || 0; this.matchCount = this.apiResult.matchCount || 0;
@@ -173,8 +173,9 @@
@if (selectedAddrProof.requiresDate) { @if (selectedAddrProof.requiresDate) {
<mat-form-field appearance="outline" class="addr-ff"> <mat-form-field appearance="outline" class="addr-ff">
<mat-label>Issue / bill date</mat-label> <mat-label>Issue / bill date</mat-label>
<span matPrefix class="addr-prefix"><mat-icon>event</mat-icon></span> <input matInput [matDatepicker]="addrIssueDatePicker" formControlName="issueDate" />
<input matInput type="date" formControlName="issueDate" /> <mat-datepicker-toggle matSuffix [for]="addrIssueDatePicker"></mat-datepicker-toggle>
<mat-datepicker #addrIssueDatePicker></mat-datepicker>
</mat-form-field> </mat-form-field>
} }
</div> </div>
@@ -15,9 +15,12 @@ import { MatCheckbox } from '@angular/material/checkbox';
import { MatTabsModule } from '@angular/material/tabs'; import { MatTabsModule } from '@angular/material/tabs';
import { MatIcon } from '@angular/material/icon'; import { MatIcon } from '@angular/material/icon';
import { MatIconButton, MatButton } from '@angular/material/button'; import { MatIconButton, MatButton } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { ClientsService } from '../../clients.service'; import { ClientsService } from '../../clients.service';
import { ProofType, normalizeProofType, groupProofsByCategory } from '../../shared/kyc-proof-types'; import { ProofType, normalizeProofType, groupProofsByCategory } from '../../shared/kyc-proof-types';
import { KycUploadHelperService } from '../../shared/kyc-upload-helper.service'; import { KycUploadHelperService } from '../../shared/kyc-upload-helper.service';
import { DocumentPreviewDialogComponent } from '../../shared/document-preview-dialog/document-preview-dialog.component';
import { Dates } from 'app/core/utils/dates';
@Component({ @Component({
selector: 'mifosx-client-india-address-step', selector: 'mifosx-client-india-address-step',
@@ -38,11 +41,20 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
private http = inject(HttpClient); private http = inject(HttpClient);
private clientsService = inject(ClientsService); private clientsService = inject(ClientsService);
private kycUpload = inject(KycUploadHelperService); private kycUpload = inject(KycUploadHelperService);
private dialog = inject(MatDialog);
private dates = inject(Dates);
/** Client ID — when set, loads existing addresses for edit mode */ /** Client ID — when set, loads existing addresses for edit mode */
@Input() clientId: string = ''; @Input() clientId: string = '';
/** Read-only mode — disables form editing until user clicks edit icon */ /** Read-only mode — disables form editing until user clicks edit icon */
@Input() readOnly = false; @Input() readOnly = false;
/** Minor clients can't hold utility bills, bank statements or an adult-only OVD in their own
* name — restricts the address-proof picker to Aadhaar/Passport when true. */
@Input() isMinor = false;
/** Non-individual (entity) clients — hides personal OVDs (Aadhaar/Passport/DL/Voter ID/NREGA/
* NPR/Birth Certificate/School ID) from the proof-of-address picker; a company's registered
* office address is evidenced by utility bills, GST/rent documents etc., not a person's ID. */
@Input() isNonIndividual = false;
activeTab = 0; activeTab = 0;
sameAsPermanent = false; sameAsPermanent = false;
@@ -235,12 +247,50 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
} }
} }
/**
* Resets transient address-tab state for a brand-new client.
*
* This app's RouteReusableStrategy (core/route/route-reusable-strategy.ts) keeps this SAME
* component instance alive across repeat visits to /clients/create, so `ngOnInit` never
* re-runs for a second "create new client" session — the previous client's address forms,
* selected proof-of-address chip and uploaded files would otherwise leak into the new one.
* Called by CreateClientComponent.resetForNewClient() whenever a fresh create session begins.
*/
resetForNewClient(): void {
this.permanentForm.reset({ country: 'India' });
this.currentForm.reset({ country: 'India' });
this.officeForm.reset({ country: 'India' });
this.correspondenceForm.reset({ country: 'India' });
this.activeTab = 0;
this.sameAsPermanent = false;
this.pinStatus = {
permanent: { loading: false, found: false, error: false, message: '' },
current: { loading: false, found: false, error: false, message: '' },
office: { loading: false, found: false, error: false, message: '' },
correspondence: { loading: false, found: false, error: false, message: '' }
};
this.localityOptions = { permanent: [], current: [], office: [], correspondence: [] };
this.selectedAddrProof = null;
this.addrFiles = { front: null, back: null };
this.addrMergedFile = null;
this.addrMergedPreview = null;
this.existingAddressProofIdentifierId = null;
this.existingAddressProofDocuments = [];
this.addressLoaded = false;
// Re-fetch rather than re-filter `addressProofs` in place — if the previous session's
// isMinor filtering already reduced it (e.g. down to Aadhaar/Passport only), filtering
// that reduced list again can never recover the items it already removed.
this.loadProofTypes();
}
private loadProofTypes(): void { private loadProofTypes(): void {
this.loadingProofs = true; this.loadingProofs = true;
this.clientsService.getKycProofTypes().subscribe({ this.clientsService.getKycProofTypes().subscribe({
next: (res: any) => { next: (res: any) => {
const activeFilter = (p: any) => p?.active !== false; const activeFilter = (p: any) => p?.active !== false;
this.addressProofs = (res?.addressProofs || []).filter(activeFilter).map(normalizeProofType); this.addressProofs = this.filterAddressProofsForNonIndividual(
this.filterAddressProofsForMinor((res?.addressProofs || []).filter(activeFilter).map(normalizeProofType))
);
this.addressGroups = groupProofsByCategory(this.addressProofs); this.addressGroups = groupProofsByCategory(this.addressProofs);
this.loadingProofs = false; this.loadingProofs = false;
}, },
@@ -250,6 +300,41 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
}); });
} }
/** Minors don't hold utility bills, bank statements, rent agreements, property tax receipts,
* employer letters or pension orders in their own name, and Voter ID/Driving Licence both
* require adult age — Aadhaar and Passport are the only OVDs left for proof of address. */
private static readonly MINOR_ELIGIBLE_ADDRESS_PROOF_CODES = new Set([
'AADHAAR',
'PASSPORT'
]);
private filterAddressProofsForMinor(proofs: ProofType[]): ProofType[] {
if (!this.isMinor) return proofs;
return proofs.filter((p) =>
ClientIndiaAddressStepComponent.MINOR_ELIGIBLE_ADDRESS_PROOF_CODES.has((p.code || '').toUpperCase())
);
}
/** Personal OVDs — not valid proof of a registered office/entity address. */
private static readonly NON_INDIVIDUAL_EXCLUDED_ADDRESS_PROOF_CODES = new Set([
'AADHAAR',
'PASSPORT',
'VOTER_ID',
'DRIVING_LICENSE',
'NREGA_JOB_CARD',
'NPR_LETTER',
'BIRTH_CERTIFICATE',
'SCHOOL_ID_CARD'
]);
private filterAddressProofsForNonIndividual(proofs: ProofType[]): ProofType[] {
if (!this.isNonIndividual) return proofs;
return proofs.filter(
(p) =>
!ClientIndiaAddressStepComponent.NON_INDIVIDUAL_EXCLUDED_ADDRESS_PROOF_CODES.has((p.code || '').toUpperCase())
);
}
selectAddrProof(proof: ProofType): void { selectAddrProof(proof: ProofType): void {
this.selectedAddrProof = proof; this.selectedAddrProof = proof;
this.permanentForm.get('proofId')?.setValue(proof.id); this.permanentForm.get('proofId')?.setValue(proof.id);
@@ -330,11 +415,12 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
files.push({ slot: 'Back', file: this.addrFiles.back }); files.push({ slot: 'Back', file: this.addrFiles.back });
} }
} }
const rawIssueDate = this.permanentForm.get('issueDate')?.value;
return { return {
proof: this.selectedAddrProof, proof: this.selectedAddrProof,
proofId: this.permanentForm.get('proofId')?.value || '', proofId: this.permanentForm.get('proofId')?.value || '',
documentKey: this.permanentForm.get('documentKey')?.value || '', documentKey: this.permanentForm.get('documentKey')?.value || '',
issueDate: this.permanentForm.get('issueDate')?.value || '', issueDate: rawIssueDate ? this.dates.getDate(rawIssueDate) : '',
files files
}; };
} }
@@ -355,6 +441,25 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
} }
} }
} }
if (changes['isMinor'] && !changes['isMinor'].firstChange && this.addressProofs.length) {
const filtered = this.filterAddressProofsForMinor(this.addressProofs);
if (filtered.length !== this.addressProofs.length) {
this.addressProofs = filtered;
this.addressGroups = groupProofsByCategory(this.addressProofs);
if (this.selectedAddrProof && !filtered.some((p) => p.id === this.selectedAddrProof?.id)) {
this.selectedAddrProof = null;
this.permanentForm.get('proofId')?.setValue('');
}
}
}
// Legal form toggled on an already-initialized instance — re-fetch rather than filter
// `addressProofs` in place, since the non-individual filter only ever removes entries and
// toggling back to individual could never recover what a prior pass had stripped out.
if (changes['isNonIndividual'] && !changes['isNonIndividual'].firstChange) {
this.selectedAddrProof = null;
this.permanentForm.get('proofId')?.setValue('');
this.loadProofTypes();
}
} }
/** /**
@@ -458,13 +563,13 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
proofId: matchedProof.id, proofId: matchedProof.id,
documentKey: identifier.documentKey || '' documentKey: identifier.documentKey || ''
}); });
// The description carries `Issue date: dd/mm/yyyy` when set on create (see // The description carries `Issue date: yyyy-MM-dd` when set on create (see
// create-client.saveAddressProof) — pull it out so the form's issueDate field // create-client.saveAddressProof) — pull it out so the form's issueDate field
// shows what was previously entered. // shows what was previously entered.
const desc: string = identifier.description || ''; const desc: string = identifier.description || '';
const issueMatch = desc.match(/Issue date:\s*(.+)$/i); const issueMatch = desc.match(/Issue date:\s*(.+)$/i);
if (issueMatch) { if (issueMatch) {
this.permanentForm.patchValue({ issueDate: issueMatch[1].trim() }); this.permanentForm.patchValue({ issueDate: this.dates.parseDate(issueMatch[1].trim()) });
} }
} }
@@ -566,33 +671,17 @@ export class ClientIndiaAddressStepComponent implements OnInit, OnChanges {
}); });
} }
/** /** Open the saved address proof in an in-app preview dialog. */
* Open the saved address proof in a new browser tab.
*
* For images we already hold a base64 data URL in `previewUrl` from
* `loadExistingAddressProof`, so we can hand it straight to `window.open`.
* For PDFs / other types we need to fetch the binary blob and create a
* temporary object URL so the browser's PDF viewer can render it.
*/
viewExistingAddressProof(): void { viewExistingAddressProof(): void {
if (!this.existingAddressProofIdentifierId || this.existingAddressProofDocuments.length === 0) { if (!this.existingAddressProofIdentifierId || this.existingAddressProofDocuments.length === 0) {
return; return;
} }
const doc = this.existingAddressProofDocuments[0]; const doc = this.existingAddressProofDocuments[0];
if (doc.previewUrl) {
window.open(doc.previewUrl, '_blank', 'noopener');
return;
}
this.clientsService.downloadClientIdentificationDocument(this.existingAddressProofIdentifierId, doc.id).subscribe({ this.clientsService.downloadClientIdentificationDocument(this.existingAddressProofIdentifierId, doc.id).subscribe({
next: (blob: Blob) => { next: (blob: Blob) =>
const url = URL.createObjectURL(blob); this.dialog.open(DocumentPreviewDialogComponent, {
const w = window.open(url, '_blank', 'noopener'); data: { blob, title: doc.fileName || doc.name, fileName: doc.fileName || doc.name }
// Revoke after the tab has had time to load — browsers vary, so }),
// err on the side of a generous wait.
if (w) {
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
},
error: () => { error: () => {
// Silent fail — UI shows the saved name so user knows it exists. // Silent fail — UI shows the saved name so user knows it exists.
} }
@@ -28,33 +28,36 @@
<div class="form-grid"> <div class="form-grid">
<!-- ══ INDIVIDUAL KYC ══ --> <!-- ══ INDIVIDUAL KYC ══ -->
@if (!isNonIndividual) { @if (!isNonIndividual) {
@if (readOnly) { <!-- Minors don't hold a PAN card — skip the PAN checkbox/section entirely -->
<!-- In view mode the mat-checkbox renders as a faded grey square @if (!isMinor) {
that reads as "blurry". Show a clean Yes/No pill instead. --> @if (readOnly) {
<div class="form-field checkbox-field full-width"> <!-- In view mode the mat-checkbox renders as a faded grey square
<div class="ro-flag"> that reads as "blurry". Show a clean Yes/No pill instead. -->
<span class="ro-flag__label">Client has PAN Card</span> <div class="form-field checkbox-field full-width">
@if (kycForm.get('hasPan')?.value) { <div class="ro-flag">
<span class="ro-flag__chip ro-flag__chip--yes"> <span class="ro-flag__label">Client has PAN Card</span>
<mat-icon>check_circle</mat-icon> @if (kycForm.get('hasPan')?.value) {
Yes <span class="ro-flag__chip ro-flag__chip--yes">
</span> <mat-icon>check_circle</mat-icon>
} @else { Yes
<span class="ro-flag__chip ro-flag__chip--no"> </span>
<mat-icon>cancel</mat-icon> } @else {
No <span class="ro-flag__chip ro-flag__chip--no">
</span> <mat-icon>cancel</mat-icon>
} No
</span>
}
</div>
</div> </div>
</div> } @else {
} @else { <div class="form-field checkbox-field full-width">
<div class="form-field checkbox-field full-width"> <mat-checkbox formControlName="hasPan">Client has PAN Card</mat-checkbox>
<mat-checkbox formControlName="hasPan">Client has PAN Card</mat-checkbox> </div>
</div> }
} }
<!-- Individual PAN with inline verify --> <!-- Individual PAN with inline verify -->
@if (kycForm.get('hasPan')?.value) { @if (!isMinor && kycForm.get('hasPan')?.value) {
<div class="form-field verify-field"> <div class="form-field verify-field">
<mat-form-field appearance="outline" class="verify-input"> <mat-form-field appearance="outline" class="verify-input">
<mat-label>PAN Number</mat-label> <mat-label>PAN Number</mat-label>
@@ -158,6 +161,17 @@
} }
</button> </button>
} }
@if (aadhaarOtpSent && aadhaarVerifyStatus !== 'VERIFIED') {
<button
mat-stroked-button
type="button"
class="change-number-btn"
[disabled]="readOnly"
(click)="changeAadhaarNumber()"
>
<mat-icon>edit</mat-icon> Change Number
</button>
}
@if (aadhaarVerifyStatus === 'VERIFIED') { @if (aadhaarVerifyStatus === 'VERIFIED') {
<span class="verify-chip verified"><fa-icon icon="check-circle"></fa-icon> Verified</span> <span class="verify-chip verified"><fa-icon icon="check-circle"></fa-icon> Verified</span>
} }
@@ -1035,6 +1049,12 @@
</h4> </h4>
<div class="form-grid"> <div class="form-grid">
<div class="checkbox-field override-checkbox-wrapper full-width">
<mat-checkbox formControlName="allowRiskOverride" [disabled]="readOnly">
Override Auto-calculated Risk Category
</mat-checkbox>
</div>
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
<mat-label>Risk Category</mat-label> <mat-label>Risk Category</mat-label>
<mat-select formControlName="riskCategory"> <mat-select formControlName="riskCategory">
@@ -1072,6 +1092,64 @@
<mat-hint>Auto: Low 10yr, Medium 8yr, High 2yr</mat-hint> <mat-hint>Auto: Low 10yr, Medium 8yr, High 2yr</mat-hint>
</mat-form-field> </mat-form-field>
@if (riskCalculationReason && !kycForm.get('allowRiskOverride')?.value && !readOnly) {
<div
class="risk-auto-calc-info full-width"
[class.risk-auto-calc-info--low]="kycForm.get('riskCategory')?.value === 1"
[class.risk-auto-calc-info--medium]="kycForm.get('riskCategory')?.value === 2"
[class.risk-auto-calc-info--high]="kycForm.get('riskCategory')?.value === 3"
>
<mat-icon class="info-icon">info</mat-icon>
<span class="info-text"
>Auto-determined: <strong>{{ riskCalculationReason }}</strong></span
>
</div>
}
<div class="risk-rules-toggle-wrapper full-width">
<button mat-button type="button" class="rules-toggle-btn" (click)="showRiskRulesTable = !showRiskRulesTable">
<mat-icon class="rules-toggle-icon">{{ showRiskRulesTable ? 'expand_less' : 'expand_more' }}</mat-icon>
{{
showRiskRulesTable ? 'Hide Risk Classification Criteria Table' : 'View Risk Classification Criteria Table'
}}
</button>
</div>
@if (showRiskRulesTable) {
<div class="risk-rules-card mat-elevation-z1 full-width">
<table class="risk-rules-table">
<thead>
<tr>
<th>Risk Category</th>
<th>Primary Criteria / Basis</th>
<th>Examples / Thresholds</th>
</tr>
</thead>
<tbody>
<tr class="rule-row rule-row--high">
<td><span class="risk-badge risk-badge--high">High Risk</span></td>
<td>PEPs, High-Risk Industries, High Income / Turnovers</td>
<td>
Politicians; Real Estate, Import/Export; Commission Agents; Income > ₹20L/yr; Turnover > ₹1 Crore
</td>
</tr>
<tr class="rule-row rule-row--medium">
<td><span class="risk-badge risk-badge--medium">Medium Risk</span></td>
<td>Self-Employed, Professionals, Cross-Border, Moderate Income</td>
<td>
Business Owners, Traders; Doctors, Lawyers, CAs; NRI, PIO, OCI; Income > ₹6L/yr; Turnover > ₹20L
</td>
</tr>
<tr class="rule-row rule-row--low">
<td><span class="risk-badge risk-badge--low">Low Risk</span></td>
<td>Non-Earning, Government Employment, Agriculture / Manual</td>
<td>Students, Minors, Homemakers; Govt/PSU Employees; Farmers, Daily Wage; Income <= ₹6L/yr</td>
</tr>
</tbody>
</table>
</div>
}
<mat-form-field appearance="outline" class="form-field full-width"> <mat-form-field appearance="outline" class="form-field full-width">
<mat-label>{{ isKycVerified ? 'Reason for Re-edit *' : 'Remarks' }}</mat-label> <mat-label>{{ isKycVerified ? 'Reason for Re-edit *' : 'Remarks' }}</mat-label>
<textarea <textarea
@@ -1173,6 +1251,12 @@
</h4> </h4>
<div class="form-grid"> <div class="form-grid">
<div class="checkbox-field override-checkbox-wrapper full-width">
<mat-checkbox formControlName="allowAmlOverride" [disabled]="readOnly">
Override Auto-calculated AML &amp; Compliance Checks
</mat-checkbox>
</div>
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
<mat-label>AML Check Status</mat-label> <mat-label>AML Check Status</mat-label>
<mat-select required formControlName="amlCheckStatus"> <mat-select required formControlName="amlCheckStatus">
@@ -1266,11 +1350,11 @@
</div> </div>
</div> </div>
<!-- ═══ SECTION: Form 60/61 ═══ --> <!-- ═══ SECTION: Form 97/98 ═══ -->
<div class="section-block"> <div class="section-block">
<h4 class="section-title"> <h4 class="section-title">
<fa-icon icon="file-invoice" class="section-icon"></fa-icon> <fa-icon icon="file-invoice" class="section-icon"></fa-icon>
Form 60 / 61 Form 97 / 98
@if (!kycForm.get('hasPan')?.value) { @if (!kycForm.get('hasPan')?.value) {
<span class="kyc-badge required-badge">Required — No PAN</span> <span class="kyc-badge required-badge">Required — No PAN</span>
} }
@@ -1278,14 +1362,14 @@
@if (!kycForm.get('hasPan')?.value) { @if (!kycForm.get('hasPan')?.value) {
<div class="kyc-info-hint warning-hint"> <div class="kyc-info-hint warning-hint">
<mat-icon class="kyc-info-hint-icon">warning</mat-icon> <mat-icon class="kyc-info-hint-icon">warning</mat-icon>
<span>Client does not have PAN. Form 60/61 is mandatory.</span> <span>Client does not have PAN. Form 97/98 is mandatory.</span>
</div> </div>
<div class="form-grid"> <div class="form-grid">
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
<mat-label>Form Type</mat-label> <mat-label>Form Type</mat-label>
<mat-select formControlName="form60Type"> <mat-select formControlName="form60Type">
<mat-option value="FORM_60">Form 60</mat-option> <mat-option value="FORM_60">Form 97</mat-option>
<mat-option value="FORM_61">Form 61</mat-option> <mat-option value="FORM_61">Form 98</mat-option>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" class="form-field" (click)="form60DatePicker.open()"> <mat-form-field appearance="outline" class="form-field" (click)="form60DatePicker.open()">
@@ -1296,26 +1380,26 @@
</mat-form-field> </mat-form-field>
</div> </div>
} @else { } @else {
<p class="form60-not-needed">Client has PAN — Form 60/61 not required.</p> <p class="form60-not-needed">Client has PAN — Form 97/98 not required.</p>
} }
</div> </div>
<!-- ═══ SECTION: Form 15G / 15H ═══ --> <!-- ═══ SECTION: Form 121 ═══ -->
<div class="section-block"> <div class="section-block">
<h4 class="section-title"> <h4 class="section-title">
<fa-icon icon="receipt" class="section-icon"></fa-icon> <fa-icon icon="receipt" class="section-icon"></fa-icon>
Form 15G / 15H Form 121
</h4> </h4>
<div class="form-grid"> <div class="form-grid">
<div class="form-field checkbox-field"> <div class="form-field checkbox-field">
<mat-checkbox formControlName="form15Applicable">Form 15G/15H Applicable</mat-checkbox> <mat-checkbox formControlName="form15Applicable">Form 121 Applicable</mat-checkbox>
</div> </div>
@if (kycForm.get('form15Applicable')?.value) { @if (kycForm.get('form15Applicable')?.value) {
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
<mat-label>Form Type</mat-label> <mat-label>Form Type</mat-label>
<mat-select formControlName="form15Type"> <mat-select formControlName="form15Type">
<mat-option value="15G">15G (Below 60 years)</mat-option> <mat-option value="15G">Form 121 (Below 60 years)</mat-option>
<mat-option value="15H">15H (Senior Citizen 60+)</mat-option> <mat-option value="15H">Form 121 (Senior Citizen 60+)</mat-option>
</mat-select> </mat-select>
</mat-form-field> </mat-form-field>
<mat-form-field appearance="outline" class="form-field"> <mat-form-field appearance="outline" class="form-field">
@@ -1359,10 +1443,15 @@
<span class="upload-box__req">*</span> <span class="upload-box__req">*</span>
</span> </span>
<span class="upload-box__hint">JPG / PNG, max 2MB</span> <span class="upload-box__hint">JPG / PNG, max 2MB</span>
<label class="upload-box__btn"> <div class="upload-box__btn-row">
<input type="file" accept="image/*" hidden (change)="onPhotoSelected($event)" /> <label class="upload-box__btn">
<fa-icon icon="camera"></fa-icon> Choose &amp; Crop <input type="file" accept="image/*" hidden (change)="onPhotoSelected($event)" />
</label> <fa-icon icon="camera"></fa-icon> Choose &amp; Crop
</label>
<button type="button" class="upload-box__btn upload-box__btn--secondary" (click)="captureWebcamPhoto()">
<fa-icon icon="video"></fa-icon> Use Webcam
</button>
</div>
@if (photoSigTouched) { @if (photoSigTouched) {
<span class="upload-box__error">Photograph is required</span> <span class="upload-box__error">Photograph is required</span>
} }
@@ -1393,10 +1482,15 @@
<span class="upload-box__req">*</span> <span class="upload-box__req">*</span>
</span> </span>
<span class="upload-box__hint">Scanned image, max 1MB</span> <span class="upload-box__hint">Scanned image, max 1MB</span>
<label class="upload-box__btn"> <div class="upload-box__btn-row">
<input type="file" accept="image/*" hidden (change)="onSignatureSelected($event)" /> <label class="upload-box__btn">
<fa-icon icon="crop"></fa-icon> Choose &amp; Crop <input type="file" accept="image/*" hidden (change)="onSignatureSelected($event)" />
</label> <fa-icon icon="crop"></fa-icon> Choose &amp; Crop
</label>
<button type="button" class="upload-box__btn upload-box__btn--secondary" (click)="drawSignature()">
<fa-icon icon="pen"></fa-icon> Draw Signature
</button>
</div>
@if (photoSigTouched) { @if (photoSigTouched) {
<span class="upload-box__error">Signature is required</span> <span class="upload-box__error">Signature is required</span>
} }
@@ -266,6 +266,23 @@
gap: 6px; gap: 6px;
} }
.change-number-btn {
font-size: 12px !important;
font-weight: 600 !important;
padding: 0 14px !important;
height: 36px !important;
border-radius: 6px !important;
display: flex;
align-items: center;
gap: 6px;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
}
.verify-chip { .verify-chip {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -297,8 +314,24 @@
.toggle-vis-btn { .toggle-vis-btn {
width: 28px !important; width: 28px !important;
height: 28px !important; height: 28px !important;
padding: 0 !important;
font-size: 13px !important; font-size: 13px !important;
color: #64748b; color: #64748b;
/* Material reserves a 48x48 invisible touch-target + ripple around every
mat-icon-button by default. Shrinking the button to 28px above doesn't
shrink that touch-target/ripple with it, so — since the suffix
container doesn't clip overflow — it visually spills out past the
field's own border, making the icon look misplaced/half-outside the box. */
::ng-deep .mat-mdc-button-touch-target {
width: 28px !important;
height: 28px !important;
}
::ng-deep .mat-mdc-button-persistent-ripple,
::ng-deep .mat-ripple {
border-radius: 50%;
}
} }
/* Verification Info Banner */ /* Verification Info Banner */
@@ -1057,9 +1090,17 @@
color: #94a3b8; color: #94a3b8;
} }
&__btn-row {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 8px;
}
&__btn { &__btn {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
gap: 6px;
padding: 6px 16px; padding: 6px 16px;
background: #fff; background: #fff;
border: 1px solid #d0d5dd; border: 1px solid #d0d5dd;
@@ -1074,6 +1115,10 @@
border-color: #1353a0; border-color: #1353a0;
color: #1353a0; color: #1353a0;
} }
&--secondary {
background: #f8fafc;
}
} }
&__status { &__status {
@@ -2228,3 +2273,161 @@
width: 95px; width: 95px;
} }
} }
.override-checkbox-wrapper {
margin-bottom: 8px;
}
.risk-auto-calc-info {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 16px;
border-radius: 8px;
font-size: 13px;
font-weight: 500;
margin-top: -8px;
margin-bottom: 12px;
border: 1px solid transparent;
.info-icon {
font-size: 18px !important;
width: 18px;
height: 18px;
flex-shrink: 0;
}
.info-text strong {
font-weight: 600;
}
&--low {
background: #ecfdf5;
color: #065f46;
border-color: #a7f3d0;
.info-icon {
color: #10b981;
}
}
&--medium {
background: #fffbeb;
color: #92400e;
border-color: #fde68a;
.info-icon {
color: #f59e0b;
}
}
&--high {
background: #fef2f2;
color: #991b1b;
border-color: #fecaca;
.info-icon {
color: #ef4444;
}
}
}
.risk-rules-toggle-wrapper {
margin-top: 4px;
margin-bottom: 12px;
.rules-toggle-btn {
font-size: 13px;
font-weight: 600;
color: #1e6bb8;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border-radius: 20px;
transition: all 0.2s ease-in-out;
background: #f1f5f9;
&:hover {
background: #e2e8f0;
color: #0f172a;
}
}
}
.risk-rules-card {
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 16px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgb(0 0 0 / 5%);
}
.risk-rules-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
text-align: left;
th {
padding: 10px 12px;
font-weight: 600;
color: #475569;
border-bottom: 2px solid #cbd5e1;
background: #f8fafc;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
td {
padding: 12px;
border-bottom: 1px solid #e2e8f0;
color: #334155;
vertical-align: top;
line-height: 1.5;
}
tr:last-child td {
border-bottom: none;
}
.rule-row {
transition: background 0.15s ease-in-out;
&:hover {
background: #f8fafc;
}
}
.risk-badge {
display: inline-block;
padding: 4px 10px;
border-radius: 12px;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.3px;
text-align: center;
width: 80px;
&--high {
background: #fef2f2;
color: #dc2626;
border: 1px solid #fecaca;
}
&--medium {
background: #fffbeb;
color: #d97706;
border: 1px solid #fde68a;
}
&--low {
background: #ecfdf5;
color: #16a34a;
border: 1px solid #a7f3d0;
}
}
}
@@ -30,6 +30,10 @@ import { SettingsService } from 'app/settings/settings.service';
import { Dates } from 'app/core/utils/dates'; import { Dates } from 'app/core/utils/dates';
import { ProofType, normalizeProofType, groupProofsByCategory } from '../../shared/kyc-proof-types'; import { ProofType, normalizeProofType, groupProofsByCategory } from '../../shared/kyc-proof-types';
import { KycUploadHelperService } from '../../shared/kyc-upload-helper.service'; import { KycUploadHelperService } from '../../shared/kyc-upload-helper.service';
import { CaptureImageDialogComponent } from '../../clients-view/custom-dialogs/capture-image-dialog/capture-image-dialog.component';
import { DrawSignatureDialogComponent } from '../../clients-view/custom-dialogs/draw-signature-dialog/draw-signature-dialog.component';
import { dataUrlToFile } from 'app/shared/utils/data-url.util';
import { DocumentPreviewDialogComponent } from '../../shared/document-preview-dialog/document-preview-dialog.component';
@Component({ @Component({
selector: 'mifosx-client-kyc-step', selector: 'mifosx-client-kyc-step',
@@ -59,12 +63,23 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
/** Set by parent after client is created */ /** Set by parent after client is created */
@Input() clientId: string = ''; @Input() clientId: string = '';
@Input() isNonIndividual = false; @Input() isNonIndividual = false;
/** Minor clients don't hold a PAN card — hides the PAN section on the individual KYC form */
@Input() isMinor = false;
/** Constitution metadata (panLabel, showCin, etc.) passed from general step */ /** Constitution metadata (panLabel, showCin, etc.) passed from general step */
@Input() constitutionMeta: any = null; @Input() constitutionMeta: any = null;
/** Entity full name (non-individual) — used for enterprise PAN verification */ /** Entity full name (non-individual) — used for enterprise PAN verification */
@Input() entityName: string = ''; @Input() entityName: string = '';
/** Read-only mode — disables form editing until user clicks edit icon */ /** Read-only mode — disables form editing until user clicks edit icon */
@Input() readOnly = false; @Input() readOnly = false;
@Input() calculatedRisk: {
category: number;
reason: string;
amlCheckStatus?: string;
bannedEntityMatch?: string;
willfulDefaulter?: string;
ecgcSalFlag?: string;
dormantFlag?: string;
} | null = null;
today = new Date(); today = new Date();
kycId: string = ''; kycId: string = '';
@@ -128,6 +143,31 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
markPhotoSigTouched(): void { markPhotoSigTouched(): void {
this.photoSigTouched = true; this.photoSigTouched = true;
} }
/** Human-readable label for each `kycForm` control that can carry a `required` error —
* used to build a specific "why is Save & Next disabled" message instead of a generic one.
* Controls not listed here (e.g. purely pattern-validated ones like panNumber/gstinNumber)
* only block when the user has actually typed something invalid, which is covered separately. */
private static readonly REQUIRED_FIELD_LABELS: Record<string, string> = {
kycDocumentName: 'KYC Document Type',
kycDocumentNumber: 'KYC Document Number',
amlCheckStatus: 'AML Check Status',
bannedEntityMatch: 'Banned Entity List Match'
};
/** Names every currently-invalid `kycForm` control (required-but-empty, or an entered value
* that fails its pattern) in plain English — surfaced via the Save & Next tooltip so staff
* aren't left staring at a greyed-out button with no clue what's still missing. Whether or
* not photo/signature previews are filled has no bearing on this list (they aren't part of
* `kycForm` at all — see `photoSigComplete`). */
get invalidFieldLabels(): string[] {
if (!this.kycForm) {
return [];
}
return Object.keys(this.kycForm.controls)
.filter((key) => this.kycForm.get(key)?.invalid)
.map((key) => ClientKycStepComponent.REQUIRED_FIELD_LABELS[key] || key);
}
/** Fallback document types when template API is unavailable */ /** Fallback document types when template API is unavailable */
private defaultDocumentTypes = [ private defaultDocumentTypes = [
{ name: 'Aadhaar Card', code: 'AADHAAR' }, { name: 'Aadhaar Card', code: 'AADHAAR' },
@@ -136,7 +176,20 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
{ name: 'Driving Licence', code: 'DRIVING_LICENSE' }, { name: 'Driving Licence', code: 'DRIVING_LICENSE' },
{ name: 'Voter ID', code: 'VOTER_ID' }, { name: 'Voter ID', code: 'VOTER_ID' },
{ name: 'NREGA Job Card', code: 'NREGA_JOB_CARD' }, { name: 'NREGA Job Card', code: 'NREGA_JOB_CARD' },
{ name: 'National Population Register Letter', code: 'NPR_LETTER' } { name: 'National Population Register Letter', code: 'NPR_LETTER' },
{ name: 'Birth Certificate', code: 'BIRTH_CERTIFICATE' },
{ name: 'School ID Card', code: 'SCHOOL_ID_CARD' }
];
/** Generic RBI-prescribed KYC documents for legal entities (Master Direction on KYC,
* Annexure I) — shown for non-individual clients before a specific constitution type is
* picked. Individual OVDs (Aadhaar/Passport/DL/Voter ID/NREGA/NPR) don't apply to entities. */
private nonIndividualDefaultDocTypes = [
{ name: 'Certificate of Incorporation / Registration Certificate', code: 'CERT_INCORPORATION' },
{ name: 'PAN Card of Entity', code: 'ENTITY_PAN' },
{ name: 'Memorandum & Articles of Association / Partnership Deed / Trust Deed', code: 'CONSTITUTIVE_DOC' },
{ name: 'Board Resolution / Authorization Letter', code: 'BOARD_RESOLUTION' },
{ name: 'KYC of Authorized Signatory / Power of Attorney Holder', code: 'AUTH_SIGNATORY_KYC' },
{ name: 'GST Registration Certificate', code: 'GST_CERTIFICATE' }
]; ];
/** Constitution-based KYC document types for non-individual clients */ /** Constitution-based KYC document types for non-individual clients */
private constitutionDocTypes: Record<string, { name: string; mandatory: boolean }[]> = { private constitutionDocTypes: Record<string, { name: string; mandatory: boolean }[]> = {
@@ -218,6 +271,9 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
{ value: 3, label: 'High Risk', years: 2, color: 'red' } { value: 3, label: 'High Risk', years: 2, color: 'red' }
]; ];
riskCalculationReason = '';
showRiskRulesTable = false;
/** PAN verification */ /** PAN verification */
panVerifyStatus: 'NONE' | 'VERIFIED' | 'FAILED' = 'NONE'; panVerifyStatus: 'NONE' | 'VERIFIED' | 'FAILED' = 'NONE';
panVerifying = false; panVerifying = false;
@@ -409,6 +465,8 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
kycDocIssueDate: [''], kycDocIssueDate: [''],
kycDocExpiryDate: [''], kycDocExpiryDate: [''],
riskCategory: [1], riskCategory: [1],
allowRiskOverride: [false],
allowAmlOverride: [false],
remarks: [''], remarks: [''],
amlCheckStatus: [ amlCheckStatus: [
'CLEAR', 'CLEAR',
@@ -431,22 +489,177 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
form15FY: [''] form15FY: ['']
}); });
ngOnInit(): void { /** RBI-accepted OVDs for a minor client — mirrors the backend's minor branch in
// Seed defaults immediately so the picker has options before clientId is set * ClientKycApiResource.getRequiredDocuments(). Voter ID, Driving Licence, PAN and NREGA
// (template API requires clientId; user can still pick a type pre-save). * all require adult eligibility; National Population Register Letter is deliberately
if (!this.kycDocumentTypes.length) { * excluded too (not offered as a minor OVD in this system). */
this.kycDocumentTypes = this.defaultDocumentTypes.map((d) => ({ private static readonly MINOR_ELIGIBLE_DOC_CODES = new Set([
name: d.name, 'AADHAAR',
code: d.code, 'PASSPORT',
mandatory: false 'BIRTH_CERTIFICATE',
})); 'SCHOOL_ID_CARD'
this.rebuildKycDocPicker(); ]);
/** Birth Certificate / School ID Card are minor-specific OVDs — not relevant once the
* client is an adult, so they're hidden the other direction. */
private static readonly MINOR_ONLY_DOC_CODES = new Set([
'BIRTH_CERTIFICATE',
'SCHOOL_ID_CARD'
]);
private filterDocTypesForMinor<T extends { name: string; code?: string }>(docs: T[]): T[] {
if (this.isMinor) {
return docs.filter((d) => ClientKycStepComponent.MINOR_ELIGIBLE_DOC_CODES.has((d.code || '').toUpperCase()));
} }
return docs.filter((d) => !ClientKycStepComponent.MINOR_ONLY_DOC_CODES.has((d.code || '').toUpperCase()));
}
/** Individual-only OVDs vs. entity-only RBI docs — never both, and minor filtering only
* ever applies to individuals. */
private getDefaultDocTypes(): { name: string; code: string }[] {
return this.isNonIndividual
? this.nonIndividualDefaultDocTypes
: this.filterDocTypesForMinor(this.defaultDocumentTypes);
}
ngOnInit(): void {
this.seedDefaultDocTypes();
this.loadExistingKycIfNeeded(); this.loadExistingKycIfNeeded();
this.loadKycTemplate(); this.loadKycTemplate();
if (this.isNonIndividual && this.constitutionMeta) { if (this.isNonIndividual && this.constitutionMeta) {
this.updateDocTypesForConstitution(); this.updateDocTypesForConstitution();
} }
this.kycForm.get('allowRiskOverride')?.valueChanges.subscribe((allowed: boolean) => {
const riskControl = this.kycForm.get('riskCategory');
if (allowed) {
if (!this.readOnly) {
riskControl?.enable();
}
} else {
riskControl?.disable();
if (this.calculatedRisk) {
riskControl?.setValue(this.calculatedRisk.category);
}
}
});
this.kycForm.get('allowAmlOverride')?.valueChanges.subscribe((allowed: boolean) => {
const amlControls = [
this.kycForm.get('amlCheckStatus'),
this.kycForm.get('bannedEntityMatch'),
this.kycForm.get('willfulDefaulter'),
this.kycForm.get('ecgcSalFlag'),
this.kycForm.get('dormantFlag')
];
if (allowed) {
if (!this.readOnly) {
amlControls.forEach((ctrl) => ctrl?.enable());
}
} else {
amlControls.forEach((ctrl) => ctrl?.disable());
this.applyAutoCalculatedAmlFlags();
}
});
if (!this.kycForm.get('allowRiskOverride')?.value) {
this.kycForm.get('riskCategory')?.disable();
}
if (!this.kycForm.get('allowAmlOverride')?.value) {
this.kycForm.get('amlCheckStatus')?.disable();
this.kycForm.get('bannedEntityMatch')?.disable();
this.kycForm.get('willfulDefaulter')?.disable();
this.kycForm.get('ecgcSalFlag')?.disable();
this.kycForm.get('dormantFlag')?.disable();
}
}
/** Seed the document-type picker from defaults (entity RBI docs vs. individual OVDs,
* filtered by the current isMinor input for individuals). Only seeds when the list is
* empty — the template API (loadKycTemplate) takes over once a clientId is available. */
private seedDefaultDocTypes(): void {
if (this.kycDocumentTypes.length) return;
this.kycDocumentTypes = this.getDefaultDocTypes().map((d) => ({
name: d.name,
code: d.code,
mandatory: false
}));
this.rebuildKycDocPicker();
}
/**
* Resets transient KYC-tab state for a brand-new client.
*
* This app's RouteReusableStrategy (core/route/route-reusable-strategy.ts) keeps this SAME
* component instance alive across repeat visits to /clients/create, so `ngOnInit` never
* re-runs for a second "create new client" session. Without this, the document-type picker
* (and any PAN/Aadhaar verification state, uploaded photo/signature) would otherwise leak
* from whatever client was created in the previous session into the new one. Called by
* CreateClientComponent.resetForNewClient() whenever a fresh create session begins.
*/
resetForNewClient(): void {
this.kycForm.reset({
hasPan: true,
riskCategory: 1,
allowRiskOverride: false,
amlCheckStatus: 'CLEAR',
bannedEntityMatch: 'NO',
willfulDefaulter: 'NO',
ecgcSalFlag: 'NO',
dormantFlag: 'ACTIVE',
accountStatus: 'ACTIVE',
form60Type: 'FORM_60',
form15Type: '15G'
});
this.kycId = '';
this.kycLoaded = false;
this.kycStatus = 0;
this.kycTemplate = null;
this.kycTemplateLoaded = false;
this.kycDocumentTypes = [];
this.selectedKycDoc = null;
this.kycDocFiles = { front: null, back: null };
this.kycDocMergedFile = null;
this.kycDocMergedPreview = null;
this.existingKycIdentifierId = null;
this.riskCalculationReason = '';
this.showRiskRulesTable = false;
this.existingKycDocuments = [];
this.photoSigTouched = false;
this.panVerifyStatus = 'NONE';
this.panVerifying = false;
this.panVerifyError = '';
this.panVerifyName = '';
this.panVerifiedOn = '';
this.aadhaarVerifyStatus = 'NONE';
this.aadhaarVerifying = false;
this.aadhaarVerifyError = '';
this.aadhaarVerifyName = '';
this.aadhaarVisible = false;
this.aadhaarOtpSent = false;
this.resetOtpDigits();
this.aadhaarOtpReferenceId = '';
this.panAadhaarSeedingStatus = '';
this.entPanVerifyStatus = 'NONE';
this.entPanVerifying = false;
this.entPanVerifyName = '';
this.entPanVerifiedOn = '';
this.gstinVerifyStatus = 'NONE';
this.gstinVerifying = false;
this.gstinVerifyName = '';
this.gstinVerifiedOn = '';
this.gstinVerifyState = '';
this.cinVerifyStatus = 'NONE';
this.cinVerifying = false;
this.cinVerifiedOn = '';
this.cinCompanyName = '';
this.photographFile = null;
this.photographPreview = null;
this.signatureFile = null;
this.signaturePreview = null;
this.existingSignatureDocId = '';
this.seedDefaultDocTypes();
} }
ngOnDestroy(): void { ngOnDestroy(): void {
@@ -464,11 +677,75 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
this.kycForm.disable({ emitEvent: false }); this.kycForm.disable({ emitEvent: false });
} else { } else {
this.kycForm.enable({ emitEvent: false }); this.kycForm.enable({ emitEvent: false });
if (!this.kycForm.get('allowRiskOverride')?.value) {
this.kycForm.get('riskCategory')?.disable({ emitEvent: false });
}
if (!this.kycForm.get('allowAmlOverride')?.value) {
this.kycForm.get('amlCheckStatus')?.disable({ emitEvent: false });
this.kycForm.get('bannedEntityMatch')?.disable({ emitEvent: false });
this.kycForm.get('willfulDefaulter')?.disable({ emitEvent: false });
this.kycForm.get('ecgcSalFlag')?.disable({ emitEvent: false });
this.kycForm.get('dormantFlag')?.disable({ emitEvent: false });
}
}
}
if (changes['calculatedRisk']) {
const newRisk = changes['calculatedRisk'].currentValue;
if (newRisk) {
this.riskCalculationReason = newRisk.reason;
const allowOverride = this.kycForm.get('allowRiskOverride')?.value;
const riskControl = this.kycForm.get('riskCategory');
if (!allowOverride && riskControl && riskControl.value !== newRisk.category) {
riskControl.setValue(newRisk.category);
riskControl.markAsDirty();
}
const allowAmlOverride = this.kycForm.get('allowAmlOverride')?.value;
if (!allowAmlOverride) {
this.applyAutoCalculatedAmlFlags(newRisk);
}
} else {
this.riskCalculationReason = '';
} }
} }
if (changes['constitutionMeta'] && this.isNonIndividual) { if (changes['constitutionMeta'] && this.isNonIndividual) {
this.updateDocTypesForConstitution(); this.updateDocTypesForConstitution();
} }
// Legal form toggled on an already-initialized instance (route-reuse keeps this
// component alive across create sessions) — the individual OVD list and the entity RBI
// doc list are mutually exclusive, so re-seed from scratch rather than filtering in place.
if (changes['isNonIndividual'] && !changes['isNonIndividual'].firstChange && !this.kycTemplateLoaded) {
this.kycDocumentTypes = [];
this.selectedKycDoc = null;
this.kycForm.get('kycDocumentName')?.setValue('');
this.seedDefaultDocTypes();
if (this.isNonIndividual && this.constitutionMeta) {
this.updateDocTypesForConstitution();
}
}
if (changes['isMinor'] && !this.isNonIndividual) {
if (this.isMinor) {
this.kycForm.get('hasPan')?.setValue(false);
this.kycForm.get('panNumber')?.setValue('');
}
// Re-derive from the full default list, not by re-filtering the already-narrowed
// `kycDocumentTypes` — filterDocTypesForMinor() only ever REMOVES entries, so once the
// initial (pre-DOB, isMinor=false) seed has already stripped out Birth Certificate /
// School ID Card, re-filtering that same shortened list can never bring them back once
// the client turns out to be a minor. Once the backend KYC template has loaded
// (kycTemplateLoaded), that list is already minor-aware and authoritative — leave it alone.
if (!this.kycTemplateLoaded) {
const rebuilt = this.filterDocTypesForMinor(
this.defaultDocumentTypes.map((d) => ({ name: d.name, code: d.code, mandatory: false }))
);
this.kycDocumentTypes = rebuilt;
const currentName = this.kycForm.get('kycDocumentName')?.value;
if (currentName && !rebuilt.some((d) => d.name === currentName)) {
this.kycForm.get('kycDocumentName')?.setValue('');
}
this.rebuildKycDocPicker();
}
}
} }
/** Update KYC document types based on selected constitution type */ /** Update KYC document types based on selected constitution type */
@@ -539,30 +816,17 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
this.kycDocMergedPreview = null; this.kycDocMergedPreview = null;
} }
/** /** Open the saved KYC ID-proof document in an in-app preview dialog. */
* Open the saved KYC ID-proof document in a new browser tab.
*
* Same flow as the address-step variant: images use the already-loaded
* base64 data URL; PDFs (or anything without a cached preview) are fetched
* fresh and rendered via a temporary blob URL.
*/
viewExistingKycDoc(): void { viewExistingKycDoc(): void {
if (!this.existingKycIdentifierId || this.existingKycDocuments.length === 0) { if (!this.existingKycIdentifierId || this.existingKycDocuments.length === 0) {
return; return;
} }
const doc = this.existingKycDocuments[0]; const doc = this.existingKycDocuments[0];
if (doc.previewUrl) {
window.open(doc.previewUrl, '_blank', 'noopener');
return;
}
this.clientsService.downloadClientIdentificationDocument(this.existingKycIdentifierId, doc.id).subscribe({ this.clientsService.downloadClientIdentificationDocument(this.existingKycIdentifierId, doc.id).subscribe({
next: (blob: Blob) => { next: (blob: Blob) =>
const url = URL.createObjectURL(blob); this.dialog.open(DocumentPreviewDialogComponent, {
const w = window.open(url, '_blank', 'noopener'); data: { blob, title: doc.fileName || doc.name, fileName: doc.fileName || doc.name }
if (w) { }),
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
},
error: () => { error: () => {
/* silent — UI still shows the saved filename */ /* silent — UI still shows the saved filename */
} }
@@ -653,6 +917,14 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
kycDocExpiryDate: parseDate(data.kycDocExpiryDate), kycDocExpiryDate: parseDate(data.kycDocExpiryDate),
// Risk & Remarks // Risk & Remarks
riskCategory: data.riskCategory || 1, riskCategory: data.riskCategory || 1,
allowRiskOverride: this.calculatedRisk ? this.calculatedRisk.category !== (data.riskCategory || 1) : false,
allowAmlOverride: this.calculatedRisk
? this.calculatedRisk.amlCheckStatus !== (data.amlCheckStatus || 'CLEAR') ||
this.calculatedRisk.bannedEntityMatch !== (data.bannedEntityMatch || 'NO') ||
this.calculatedRisk.willfulDefaulter !== (data.willfulDefaulter || 'NO') ||
this.calculatedRisk.ecgcSalFlag !== (data.ecgcSalFlag || 'NO') ||
this.calculatedRisk.dormantFlag !== (data.dormantFlag || 'ACTIVE')
: false,
remarks: data.remarks || '', remarks: data.remarks || '',
hasPan: !!data.panNumber, hasPan: !!data.panNumber,
// AML & Compliance // AML & Compliance
@@ -738,12 +1010,17 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
const n = i?.documentType?.name?.toLowerCase(); const n = i?.documentType?.name?.toLowerCase();
return !!n && this.kycDocProofs.some((p) => p.name?.toLowerCase() === n); return !!n && this.kycDocProofs.some((p) => p.name?.toLowerCase() === n);
}; };
// Re-uploading a KYC document creates a new identifier row rather than updating the
// old one in place (same pattern as OVD identifiers), so sort newest-first before
// picking — otherwise a repeat upload of the same document type would keep showing
// the ORIGINAL file forever, since .find() would always hit the oldest matching row.
const sorted = [...identifiers].sort((a: any, b: any) => (b?.id ?? 0) - (a?.id ?? 0));
// Pick by document-type name match first; otherwise the first identifier whose // Pick by document-type name match first; otherwise the first identifier whose
// type lives in the KYC proof list (avoid bleeding the address proof in here). // type lives in the KYC proof list (avoid bleeding the address proof in here).
const match = kycDocumentName const match = kycDocumentName
? identifiers.find((i: any) => i?.documentType?.name?.toLowerCase() === kycDocumentName.toLowerCase()) ? sorted.find((i: any) => i?.documentType?.name?.toLowerCase() === kycDocumentName.toLowerCase())
: null; : null;
const identifier = match || identifiers.find(isKycType); const identifier = match || sorted.find(isKycType);
if (!identifier?.id) return; if (!identifier?.id) return;
this.existingKycIdentifierId = identifier.id.toString(); this.existingKycIdentifierId = identifier.id.toString();
@@ -818,7 +1095,12 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
if (!this.clientId) return; if (!this.clientId) return;
this.clientsService.getClientDocuments(this.clientId).subscribe({ this.clientsService.getClientDocuments(this.clientId).subscribe({
next: (documents: any[]) => { next: (documents: any[]) => {
const sigDoc = documents?.find((d: any) => d.name === 'clientSignature'); // Multiple 'clientSignature' documents can exist for clients who re-cropped/replaced
// their signature before uploads became single-slot, so pick the highest id (latest)
// rather than the first unordered match.
const sigDoc = documents
?.filter((d: any) => d.name === 'clientSignature')
?.sort((a: any, b: any) => b.id - a.id)?.[0];
if (sigDoc?.id) { if (sigDoc?.id) {
this.existingSignatureDocId = sigDoc.id.toString(); this.existingSignatureDocId = sigDoc.id.toString();
this.clientsService.getClientSignatureImage(this.clientId, this.existingSignatureDocId).subscribe({ this.clientsService.getClientSignatureImage(this.clientId, this.existingSignatureDocId).subscribe({
@@ -847,11 +1129,13 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
this.kycTemplate = template; this.kycTemplate = template;
this.kycTemplateLoaded = true; this.kycTemplateLoaded = true;
if (template?.requiredDocuments?.length > 0) { if (template?.requiredDocuments?.length > 0) {
this.kycDocumentTypes = template.requiredDocuments.map((doc: any) => ({ this.kycDocumentTypes = this.filterDocTypesForMinor(
name: doc.name, template.requiredDocuments.map((doc: any) => ({
code: doc.code || doc.name, name: doc.name,
mandatory: doc.mandatory ?? false code: doc.code || doc.name,
})); mandatory: doc.mandatory ?? false
}))
);
// Update kycDocumentName validator based on mandatory docs // Update kycDocumentName validator based on mandatory docs
const hasMandatory = this.kycDocumentTypes.some((d) => d.mandatory); const hasMandatory = this.kycDocumentTypes.some((d) => d.mandatory);
if (hasMandatory) { if (hasMandatory) {
@@ -864,7 +1148,7 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
error: () => { error: () => {
// Fallback to defaults if template API unavailable // Fallback to defaults if template API unavailable
this.kycTemplateLoaded = true; this.kycTemplateLoaded = true;
this.kycDocumentTypes = this.defaultDocumentTypes.map((d) => ({ this.kycDocumentTypes = this.getDefaultDocTypes().map((d) => ({
name: d.name, name: d.name,
code: d.code, code: d.code,
mandatory: false mandatory: false
@@ -1291,6 +1575,21 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
); );
} }
/** Lets the user go back and fix a wrong Aadhaar number after an OTP was already sent —
* unlocks the (readonly-while-OTP-pending) input and discards the in-flight OTP session,
* since it was requested for the now-being-corrected number. */
changeAadhaarNumber(): void {
this.aadhaarOtpSent = false;
this.aadhaarVerifyError = '';
this.aadhaarOtpReferenceId = '';
this.resetOtpDigits();
this.resendCountdown = 0;
if (this.resendTimer) {
clearInterval(this.resendTimer);
this.resendTimer = null;
}
}
/** Verify Aadhaar OTP */ /** Verify Aadhaar OTP */
verifyAadhaarOtp() { verifyAadhaarOtp() {
if (!this.aadhaarOtp || !this.clientId || !this.kycId) return; if (!this.aadhaarOtp || !this.clientId || !this.kycId) return;
@@ -1366,6 +1665,25 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
if (!input.files?.length) return; if (!input.files?.length) return;
const file = input.files[0]; const file = input.files[0];
input.value = ''; input.value = '';
await this.openPhotoCropDialog(file);
}
/** Webcam capture entry point for the profile photograph — feeds the captured frame
* through the same crop dialog + staging/upload path as the file-picker flow above,
* so behaviour (immediate upload in edit mode vs staged-until-submit in create mode)
* stays identical regardless of capture source. */
async captureWebcamPhoto(): Promise<void> {
const dialogRef = this.dialog.open(CaptureImageDialogComponent, {
data: { captureTarget: 'profile' }
});
dialogRef.afterClosed().subscribe(async (imageDataUrl: string) => {
if (!imageDataUrl) return;
const file = dataUrlToFile(imageDataUrl, 'webcam-photograph.jpg');
await this.openPhotoCropDialog(file);
});
}
private async openPhotoCropDialog(file: File): Promise<void> {
const { ImageCropDialogComponent } = await import('./image-crop-dialog/image-crop-dialog.component'); const { ImageCropDialogComponent } = await import('./image-crop-dialog/image-crop-dialog.component');
const dialogRef = this.dialog.open(ImageCropDialogComponent, { const dialogRef = this.dialog.open(ImageCropDialogComponent, {
width: '680px', width: '680px',
@@ -1391,6 +1709,10 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
if (!input.files?.length) return; if (!input.files?.length) return;
const file = input.files[0]; const file = input.files[0];
input.value = ''; input.value = '';
await this.openSignatureCropDialog(file);
}
private async openSignatureCropDialog(file: File): Promise<void> {
const { ImageCropDialogComponent } = await import('./image-crop-dialog/image-crop-dialog.component'); const { ImageCropDialogComponent } = await import('./image-crop-dialog/image-crop-dialog.component');
const dialogRef = this.dialog.open(ImageCropDialogComponent, { const dialogRef = this.dialog.open(ImageCropDialogComponent, {
width: '680px', width: '680px',
@@ -1399,42 +1721,51 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
}); });
dialogRef.afterClosed().subscribe((result: any) => { dialogRef.afterClosed().subscribe((result: any) => {
if (result) { if (result) {
this.signatureFile = result.croppedFile; this.applySignatureFile(result.croppedFile, result.previewUrl);
this.signaturePreview = result.previewUrl;
// In edit mode, delete old signature doc then upload new one
if (this.clientId) {
if (this.existingSignatureDocId) {
this.clientsService.deleteClientDocument(this.clientId, this.existingSignatureDocId).subscribe({
next: () => {
this.clientsService.uploadClientSignatureImage(this.clientId, result.croppedFile).subscribe({
next: (res: any) => {
if (res?.resourceId) this.existingSignatureDocId = res.resourceId.toString();
},
error: () => {}
});
},
error: () => {
this.clientsService.uploadClientSignatureImage(this.clientId, result.croppedFile).subscribe({
next: (res: any) => {
if (res?.resourceId) this.existingSignatureDocId = res.resourceId.toString();
},
error: () => {}
});
}
});
} else {
this.clientsService.uploadClientSignatureImage(this.clientId, result.croppedFile).subscribe({
next: (res: any) => {
if (res?.resourceId) this.existingSignatureDocId = res.resourceId.toString();
},
error: () => {}
});
}
}
} }
}); });
} }
/** Draw-with-mouse/touchpad entry point for the specimen signature — same staging/upload
* path as the file-picker and webcam flows, minus the crop step (the pad's canvas is
* already the right shape/size). */
drawSignature(): void {
const dialogRef = this.dialog.open(DrawSignatureDialogComponent);
dialogRef.afterClosed().subscribe((file: File) => {
if (file) {
this.applySignatureFile(file, URL.createObjectURL(file));
}
});
}
/** Stages the signature locally and, in edit mode, persists it — replacing any existing
* signature doc first so a client never ends up with two. Shared by the file-picker, webcam
* and draw-pad entry points. */
private applySignatureFile(file: File, previewUrl: string): void {
this.signatureFile = file;
this.signaturePreview = previewUrl;
if (!this.clientId) {
return;
}
if (this.existingSignatureDocId) {
this.clientsService.deleteClientDocument(this.clientId, this.existingSignatureDocId).subscribe({
next: () => this.uploadSignatureFile(file),
error: () => this.uploadSignatureFile(file)
});
} else {
this.uploadSignatureFile(file);
}
}
private uploadSignatureFile(file: File): void {
this.clientsService.uploadClientSignatureImage(this.clientId, file).subscribe({
next: (res: any) => {
if (res?.resourceId) this.existingSignatureDocId = res.resourceId.toString();
},
error: () => {}
});
}
removePhoto() { removePhoto() {
this.photographFile = null; this.photographFile = null;
this.photographPreview = null; this.photographPreview = null;
@@ -1459,7 +1790,7 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
} }
get kycData(): any { get kycData(): any {
const formVal = this.readOnly ? this.kycForm.getRawValue() : this.kycForm.value; const formVal = this.kycForm.getRawValue();
const aadhaarRaw = formVal.aadhaarNumber || ''; const aadhaarRaw = formVal.aadhaarNumber || '';
const aadhaarMasked = aadhaarRaw.length === 12 ? 'XXXXXXXX' + aadhaarRaw.slice(-4) : null; const aadhaarMasked = aadhaarRaw.length === 12 ? 'XXXXXXXX' + aadhaarRaw.slice(-4) : null;
const dateFormat = this.settingsService.dateFormat; const dateFormat = this.settingsService.dateFormat;
@@ -1528,6 +1859,21 @@ export class ClientKycStepComponent implements OnInit, OnChanges, OnDestroy {
v.form15Applicable v.form15Applicable
); );
} }
private applyAutoCalculatedAmlFlags(risk = this.calculatedRisk): void {
if (!risk) return;
this.kycForm.get('amlCheckStatus')?.setValue(risk.amlCheckStatus || 'CLEAR');
this.kycForm.get('bannedEntityMatch')?.setValue(risk.bannedEntityMatch || 'NO');
this.kycForm.get('willfulDefaulter')?.setValue(risk.willfulDefaulter || 'NO');
this.kycForm.get('ecgcSalFlag')?.setValue(risk.ecgcSalFlag || 'NO');
this.kycForm.get('dormantFlag')?.setValue(risk.dormantFlag || 'ACTIVE');
this.kycForm.get('amlCheckStatus')?.markAsDirty();
this.kycForm.get('bannedEntityMatch')?.markAsDirty();
this.kycForm.get('willfulDefaulter')?.markAsDirty();
this.kycForm.get('ecgcSalFlag')?.markAsDirty();
this.kycForm.get('dormantFlag')?.markAsDirty();
}
} }
/** /**
@@ -195,7 +195,7 @@
client.isMinor ? 'preview-badge preview-badge--danger' : 'preview-badge preview-badge--verified' client.isMinor ? 'preview-badge preview-badge--danger' : 'preview-badge preview-badge--verified'
" "
> >
{{ client.isMinor ? 'Yes (Age < 10)' : 'No' }} {{ client.isMinor ? 'Yes (Age < 18)' : 'No' }}
</span> </span>
</span> </span>
</div> </div>
+7 -1
View File
@@ -22,6 +22,7 @@ import { AddFamilyMemberComponent } from './clients-view/family-members-tab/add-
import { EditFamilyMemberComponent } from './clients-view/family-members-tab/edit-family-member/edit-family-member.component'; import { EditFamilyMemberComponent } from './clients-view/family-members-tab/edit-family-member/edit-family-member.component';
import { IdentitiesTabComponent } from './clients-view/identities-tab/identities-tab.component'; import { IdentitiesTabComponent } from './clients-view/identities-tab/identities-tab.component';
import { NotesTabComponent } from './clients-view/notes-tab/notes-tab.component'; import { NotesTabComponent } from './clients-view/notes-tab/notes-tab.component';
import { HistoryTabComponent } from './clients-view/history-tab/history-tab.component';
import { DocumentsTabComponent } from './clients-view/documents-tab/documents-tab.component'; import { DocumentsTabComponent } from './clients-view/documents-tab/documents-tab.component';
import { DatatableTabComponent } from './clients-view/datatable-tab/datatable-tab.component'; import { DatatableTabComponent } from './clients-view/datatable-tab/datatable-tab.component';
import { AddressTabComponent } from './clients-view/address-tab/address-tab.component'; import { AddressTabComponent } from './clients-view/address-tab/address-tab.component';
@@ -190,7 +191,7 @@ const routes: Routes = [
{ {
path: 'form60', path: 'form60',
component: Form60TabComponent, component: Form60TabComponent,
data: { title: 'Form 60', breadcrumb: 'Form 60', routeParamBreadcrumb: false } data: { title: 'Form 97', breadcrumb: 'Form 97', routeParamBreadcrumb: false }
}, },
{ {
path: 'documents', path: 'documents',
@@ -208,6 +209,11 @@ const routes: Routes = [
clientNotes: ClientNotesResolver clientNotes: ClientNotesResolver
} }
}, },
{
path: 'history',
component: HistoryTabComponent,
data: { title: 'History', breadcrumb: 'History', routeParamBreadcrumb: false }
},
{ {
path: 'datatables', path: 'datatables',
children: [ children: [
@@ -234,8 +234,12 @@ export class CkycTabComponent implements OnInit, OnDestroy {
}; };
} }
// 2. Signature — client document with name='clientSignature' // 2. Signature — client document with name='clientSignature'. Multiple rows can exist
const signatureDoc = (documents as any[])?.find((d: any) => d?.name === 'clientSignature'); // for clients who re-cropped/replaced their signature before uploads became single-slot,
// so pick the highest id (latest) rather than the first unordered match.
const signatureDoc = (documents as any[])
?.filter((d: any) => d?.name === 'clientSignature')
?.sort((a: any, b: any) => b.id - a.id)?.[0];
if (signatureDoc) { if (signatureDoc) {
this.existing.CLIENT_SIGNATURE = { this.existing.CLIENT_SIGNATURE = {
present: true, present: true,
@@ -410,6 +410,9 @@
<button mat-menu-item (click)="doAction('Add Charge')" *mifosxHasPermission="'CREATE_CLIENTCHARGE'"> <button mat-menu-item (click)="doAction('Add Charge')" *mifosxHasPermission="'CREATE_CLIENTCHARGE'">
{{ 'labels.buttons.Add Charge' | translate }} {{ 'labels.buttons.Add Charge' | translate }}
</button> </button>
<button mat-menu-item (click)="doAction('Welcome Kit')" *mifosxHasPermission="'READ_WELCOMEKIT'">
Welcome Kit
</button>
<button mat-menu-item (click)="doAction('Create Collateral')"> <button mat-menu-item (click)="doAction('Create Collateral')">
{{ 'labels.buttons.Create Collateral' | translate }} {{ 'labels.buttons.Create Collateral' | translate }}
</button> </button>
@@ -426,6 +429,9 @@
<button mat-menu-item (click)="doAction('Upload Signature')" *mifosxHasPermission="'CREATE_CLIENTIMAGE'"> <button mat-menu-item (click)="doAction('Upload Signature')" *mifosxHasPermission="'CREATE_CLIENTIMAGE'">
{{ 'labels.buttons.Upload Signature' | translate }} {{ 'labels.buttons.Upload Signature' | translate }}
</button> </button>
<button mat-menu-item (click)="doAction('Capture Signature')" *mifosxHasPermission="'CREATE_CLIENTIMAGE'">
Capture Signature (Webcam)
</button>
<button mat-menu-item (click)="doAction('Delete Signature')" *mifosxHasPermission="'DELETE_CLIENTIMAGE'"> <button mat-menu-item (click)="doAction('Delete Signature')" *mifosxHasPermission="'DELETE_CLIENTIMAGE'">
{{ 'labels.buttons.Delete Signature' | translate }} {{ 'labels.buttons.Delete Signature' | translate }}
</button> </button>
@@ -559,6 +565,15 @@
> >
<i class="fa fa-sticky-note cv-tab-icon"></i> {{ 'labels.inputs.Notes' | translate }} <i class="fa fa-sticky-note cv-tab-icon"></i> {{ 'labels.inputs.Notes' | translate }}
</a> </a>
<a
mat-tab-link
[routerLink]="['./history']"
routerLinkActive
#history="routerLinkActive"
[active]="history.isActive"
>
<i class="fa fa-history cv-tab-icon"></i> History
</a>
@for (clientDatatable of clientDatatables; track clientDatatable) { @for (clientDatatable of clientDatatables; track clientDatatable) {
<a <a
mat-tab-link mat-tab-link
@@ -22,6 +22,7 @@ import { DrawSignatureDialogComponent } from './custom-dialogs/draw-signature-di
import { DeleteDialogComponent } from 'app/shared/delete-dialog/delete-dialog.component'; import { DeleteDialogComponent } from 'app/shared/delete-dialog/delete-dialog.component';
import { UploadImageDialogComponent } from './custom-dialogs/upload-image-dialog/upload-image-dialog.component'; import { UploadImageDialogComponent } from './custom-dialogs/upload-image-dialog/upload-image-dialog.component';
import { CaptureImageDialogComponent } from './custom-dialogs/capture-image-dialog/capture-image-dialog.component'; import { CaptureImageDialogComponent } from './custom-dialogs/capture-image-dialog/capture-image-dialog.component';
import { WelcomeKitDialogComponent } from './custom-dialogs/welcome-kit-dialog/welcome-kit-dialog.component';
/** Custom Services */ /** Custom Services */
import { ClientsService } from '../clients.service'; import { ClientsService } from '../clients.service';
@@ -240,6 +241,9 @@ export class ClientsViewComponent implements OnInit {
case 'Upload Signature': case 'Upload Signature':
this.uploadSignature(); this.uploadSignature();
break; break;
case 'Capture Signature':
this.captureSignatureImage();
break;
case 'Delete Signature': case 'Delete Signature':
this.deleteSignature(); this.deleteSignature();
break; break;
@@ -252,6 +256,9 @@ export class ClientsViewComponent implements OnInit {
case 'Delete Image': case 'Delete Image':
this.deleteProfileImage(); this.deleteProfileImage();
break; break;
case 'Welcome Kit':
this.dispatchWelcomeKit();
break;
case 'Create Standing Instructions': case 'Create Standing Instructions':
const createStandingInstructionsQueryParams: any = { const createStandingInstructionsQueryParams: any = {
officeId: this.clientViewData.officeId, officeId: this.clientViewData.officeId,
@@ -332,6 +339,8 @@ export class ClientsViewComponent implements OnInit {
this.uploadSignature(); this.uploadSignature();
} else if (response.draw) { } else if (response.draw) {
this.drawSignature(); this.drawSignature();
} else if (response.capture) {
this.captureSignatureImage();
} else if (response.delete) { } else if (response.delete) {
this.deleteSignature(); this.deleteSignature();
} }
@@ -391,7 +400,9 @@ export class ClientsViewComponent implements OnInit {
* Captures clients profile image. * Captures clients profile image.
*/ */
private captureProfileImage() { private captureProfileImage() {
const captureImageDialogRef = this.dialog.open(CaptureImageDialogComponent); const captureImageDialogRef = this.dialog.open(CaptureImageDialogComponent, {
data: { captureTarget: 'profile' }
});
captureImageDialogRef.afterClosed().subscribe((imageURL: string) => { captureImageDialogRef.afterClosed().subscribe((imageURL: string) => {
if (imageURL) { if (imageURL) {
this.clientsService.uploadCapturedClientProfileImage(this.clientViewData.id, imageURL).subscribe(() => { this.clientsService.uploadCapturedClientProfileImage(this.clientViewData.id, imageURL).subscribe(() => {
@@ -401,6 +412,24 @@ export class ClientsViewComponent implements OnInit {
}); });
} }
/**
* Captures client signature via webcam (photograph of a paper signature).
* Mirrors `captureProfileImage()` — same dialog, parametrized for signature capture,
* uploaded via `uploadCapturedClientSignature()` instead of the profile-image upload.
*/
private captureSignatureImage() {
const captureImageDialogRef = this.dialog.open(CaptureImageDialogComponent, {
data: { captureTarget: 'signature' }
});
captureImageDialogRef.afterClosed().subscribe((imageURL: string) => {
if (imageURL) {
this.clientsService.uploadCapturedClientSignature(this.clientViewData.id, imageURL).subscribe(() => {
this.reload();
});
}
});
}
/** /**
* Uploads the clients image. * Uploads the clients image.
*/ */
@@ -430,4 +459,20 @@ export class ClientsViewComponent implements OnInit {
} }
}); });
} }
/**
* Opens the Welcome Kit Dispatch dialog.
*/
private dispatchWelcomeKit() {
const welcomeKitDialogRef = this.dialog.open(WelcomeKitDialogComponent, {
data: { clientId: this.clientViewData.id },
width: '600px'
});
welcomeKitDialogRef.afterClosed().subscribe((response: any) => {
if (response) {
// the form was successfully submitted
this.reload();
}
});
}
} }
@@ -6,10 +6,24 @@
file, You can obtain one at http://mozilla.org/MPL/2.0/. file, You can obtain one at http://mozilla.org/MPL/2.0/.
--> -->
<div class="layout-column gap-2px"> <div class="layout-column gap-2px capture-dialog">
<h1 mat-dialog-title align="center">{{ 'labels.heading.Capture Client Image' | translate }}</h1> <h1 mat-dialog-title align="center" class="capture-title">
<fa-icon [icon]="isSignatureCapture ? 'signature' : 'camera'"></fa-icon>
<span>{{ dialogTitle }}</span>
</h1>
<p class="capture-instructions" align="center">{{ dialogInstructions }}</p>
<video #video class="capture-video" autoplay></video> <div class="capture-frame" [class.capture-frame--signature]="isSignatureCapture">
<video
#video
class="capture-video"
autoplay
playsinline
disablepictureinpicture
disableremoteplayback
controlslist="nodownload noremoteplayback nofullscreen"
></video>
</div>
<!-- Using a class will break renderer changes --> <!-- Using a class will break renderer changes -->
<canvas #canvas [ngStyle]="{ display: 'none' }"></canvas> <canvas #canvas [ngStyle]="{ display: 'none' }"></canvas>
@@ -17,20 +31,20 @@
<!-- Using a class will break renderer changes --> <!-- Using a class will break renderer changes -->
<p #fallback [ngStyle]="{ display: 'none' }" align="center"></p> <p #fallback [ngStyle]="{ display: 'none' }" align="center"></p>
<div class="flex-20" align="center"> <div class="capture-actions-row">
@if (!isCaptured) { @if (!isCaptured) {
<button #captureButton mat-stroked-button color="primary" (click)="capture()"> <button #captureButton mat-stroked-button color="primary" class="capture-btn" (click)="capture()">
{{ 'labels.buttons.Capture' | translate }} <fa-icon icon="camera" size="sm" class="m-r-10"></fa-icon>{{ 'labels.buttons.Capture' | translate }}
</button> </button>
} }
@if (isCaptured) { @if (isCaptured) {
<button mat-stroked-button color="primary" (click)="recapture()"> <button mat-stroked-button color="primary" class="capture-btn" (click)="recapture()">
<fa-icon icon="undo" size="sm" class="m-r-10"></fa-icon>{{ 'labels.buttons.Recapture' | translate }} <fa-icon icon="undo" size="sm" class="m-r-10"></fa-icon>{{ 'labels.buttons.Recapture' | translate }}
</button> </button>
} }
</div> </div>
<mat-dialog-actions align="end"> <mat-dialog-actions align="end" class="capture-dialog-footer">
<button mat-raised-button mat-dialog-close>{{ 'labels.buttons.Cancel' | translate }}</button> <button mat-raised-button mat-dialog-close>{{ 'labels.buttons.Cancel' | translate }}</button>
<button [disabled]="!isCaptured" mat-raised-button color="primary" [mat-dialog-close]="clientImageDataURL"> <button [disabled]="!isCaptured" mat-raised-button color="primary" [mat-dialog-close]="clientImageDataURL">
{{ 'labels.buttons.Upload' | translate }} {{ 'labels.buttons.Upload' | translate }}
@@ -6,13 +6,103 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/ */
@use '../../../../../assets/styles/colours' as colors; /* No explicit width/maxHeight is passed at every `dialog.open(CaptureImageDialogComponent)`
call site (there are several, across clients-view/create/edit flows) — capping height and
allowing internal scroll here, once, keeps the Cancel/Upload footer reachable on short
viewports instead of relying on every caller to remember a maxHeight config. */
:host {
display: block;
max-height: 90vh;
overflow-y: auto;
}
.capture-dialog {
padding: 4px 4px 8px;
}
.capture-title {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
margin: 0;
fa-icon {
color: #1074b9;
font-size: 18px;
}
}
.capture-instructions {
margin: 4px 0 14px;
padding: 0 16px;
font-size: 13px;
color: rgb(0 0 0 / 60%);
}
.capture-frame {
width: 100%;
max-width: 640px;
/* Capped in vh, not just px, so the frame shrinks on short viewports (laptop screens with
browser chrome eating into the visible height) instead of pushing the Capture/Cancel/
Upload buttons below the fold — `object-fit: cover` on the video means shrinking this box
never reintroduces pillarboxing, it just changes how much of the live frame is visible. */
max-height: 42vh;
margin: 0 auto;
border-radius: 14px;
overflow: hidden;
background: #111;
box-shadow: 0 8px 24px -8px rgb(15 23 42 / 25%);
border: 1px solid rgb(255 255 255 / 8%);
/* Default (profile) frame follows the requested 4:3 capture stream. */
aspect-ratio: 4 / 3;
/* Signature capture uses a shorter, wider (16:9) frame — paper signatures are landscape-ish
and this matches the wider resolution requested from getUserMedia, so the live preview
fills the frame edge-to-edge instead of pillarboxing (black bars) inside a mismatched box. */
&--signature {
aspect-ratio: 16 / 9;
max-height: 36vh;
}
}
.capture-video { .capture-video {
width: 100%; width: 100%;
max-width: 640px; height: 100%;
height: auto; object-fit: cover;
object-fit: contain; display: block;
border-radius: 4px;
background-color: colors.$black; /* Chromium auto-injects a Picture-in-Picture toggle (and sometimes a cast button) as small
square overlay icons in a bare <video>'s corners on hover — the `disablepictureinpicture`/
`disableremoteplayback` attributes stop the *feature*, but these pseudo-elements are the
belt-and-braces way to make sure the icons themselves never render. */
&::-webkit-media-controls,
&::-webkit-media-controls-panel,
&::-internal-media-controls-overlay-cast-button {
display: none !important;
}
}
.capture-actions-row {
display: flex;
justify-content: center;
margin: 16px 0 4px;
}
.capture-btn {
border-radius: 999px !important;
padding: 0 20px !important;
height: 42px;
font-weight: 600 !important;
}
.capture-dialog-footer {
padding: 8px 4px 0 !important;
.mat-mdc-raised-button {
border-radius: 999px !important;
font-weight: 600 !important;
}
} }
@@ -8,11 +8,23 @@
/** Angular Imports */ /** Angular Imports */
import { Component, ViewChild, ElementRef, AfterViewInit, Renderer2, OnDestroy, inject } from '@angular/core'; import { Component, ViewChild, ElementRef, AfterViewInit, Renderer2, OnDestroy, inject } from '@angular/core';
import { MatDialogRef, MatDialogTitle, MatDialogActions, MatDialogClose } from '@angular/material/dialog'; import {
MatDialogRef,
MAT_DIALOG_DATA,
MatDialogTitle,
MatDialogActions,
MatDialogClose
} from '@angular/material/dialog';
import { NgStyle } from '@angular/common'; import { NgStyle } from '@angular/common';
import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/** What the captured image is for — drives the dialog's title/instructions and lets the
* caller decide (based on how it opened the dialog) which upload method to invoke on the
* resulting data URL. Defaults to 'profile' so existing callers that don't pass `data`
* keep working unchanged. */
export type CaptureImageTarget = 'profile' | 'signature';
/** /**
* Capture image dialog component * Capture image dialog component
*/ */
@@ -32,6 +44,24 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export class CaptureImageDialogComponent implements AfterViewInit, OnDestroy { export class CaptureImageDialogComponent implements AfterViewInit, OnDestroy {
dialogRef = inject<MatDialogRef<CaptureImageDialogComponent>>(MatDialogRef); dialogRef = inject<MatDialogRef<CaptureImageDialogComponent>>(MatDialogRef);
private renderer = inject(Renderer2); private renderer = inject(Renderer2);
private data = inject<{ captureTarget?: CaptureImageTarget } | null>(MAT_DIALOG_DATA, { optional: true });
/** 'profile' (default, unchanged behaviour) or 'signature' — photographing a paper signature. */
captureTarget: CaptureImageTarget = this.data?.captureTarget || 'profile';
get isSignatureCapture(): boolean {
return this.captureTarget === 'signature';
}
get dialogTitle(): string {
return this.isSignatureCapture ? 'Capture Client Signature' : 'Capture Client Image';
}
get dialogInstructions(): string {
return this.isSignatureCapture
? 'Photograph the customer’s signed paper — line up the signature within the frame before capturing.'
: 'Line up the customer’s face within the frame before capturing.';
}
/** Video element reference */ /** Video element reference */
@ViewChild('video', { static: true }) video: ElementRef; @ViewChild('video', { static: true }) video: ElementRef;
@@ -62,11 +92,12 @@ export class CaptureImageDialogComponent implements AfterViewInit, OnDestroy {
*/ */
startCamera() { startCamera() {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
const videoConstraints: MediaTrackConstraints = { // Signature capture asks for a wide/short (16:9) stream to match the frame it's shown
width: { ideal: 640 }, // in — requesting an aspect ratio close to what the CSS box actually renders avoids the
height: { ideal: 480 }, // camera negotiating a 4:3 stream that then gets pillarboxed (black bars) inside a 16:9 box.
facingMode: 'user' const videoConstraints: MediaTrackConstraints = this.isSignatureCapture
}; ? { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' }
: { width: { ideal: 640 }, height: { ideal: 480 }, facingMode: 'user' };
navigator.mediaDevices navigator.mediaDevices
.getUserMedia({ video: videoConstraints }) .getUserMedia({ video: videoConstraints })
.then((stream: MediaStream) => { .then((stream: MediaStream) => {
@@ -47,7 +47,13 @@ export class DeleteSignatureDialogComponent {
* @param {any} data Documents data * @param {any} data Documents data
*/ */
constructor() { constructor() {
const signature = this.data.find((document: any) => document.name === 'clientSignature') || {}; // Multiple 'clientSignature' documents can exist for clients who re-cropped/replaced their
// signature before uploads became single-slot, so pick the highest id (latest) rather than
// the first unordered match.
const signature =
this.data
.filter((document: any) => document.name === 'clientSignature')
.sort((a: any, b: any) => b.id - a.id)[0] || {};
this.signatureId = signature.id; this.signatureId = signature.id;
} }
} }
@@ -347,9 +347,18 @@
<i class="fa fa-calendar"></i> Issue / statement date <i class="fa fa-calendar"></i> Issue / statement date
<span class="kyc-opt">(not older than 3 months)</span> <span class="kyc-opt">(not older than 3 months)</span>
</label> </label>
<div class="kyc-input-wrap kyc-input-wrap--date"> <div class="kyc-input-wrap kyc-input-wrap--date" (click)="uploadIssueDatePicker.open()">
<i class="fa fa-calendar-o kyc-input-wrap__icon"></i> <input
<input type="date" class="kyc-input kyc-input--date" formControlName="issueDate" /> class="kyc-input kyc-input--date"
[matDatepicker]="uploadIssueDatePicker"
formControlName="issueDate"
readonly
/>
<mat-datepicker-toggle
class="kyc-input-wrap__calendar-toggle"
[for]="uploadIssueDatePicker"
></mat-datepicker-toggle>
<mat-datepicker #uploadIssueDatePicker></mat-datepicker>
</div> </div>
</div> </div>
} }
@@ -438,6 +447,15 @@
<div class="fd-field fd-field--file"> <div class="fd-field fd-field--file">
<mifosx-file-upload flex="100%" (change)="onFileSelect($event)"></mifosx-file-upload> <mifosx-file-upload flex="100%" (change)="onFileSelect($event)"></mifosx-file-upload>
</div> </div>
<div class="fd-webcam-row">
<span class="fd-webcam-divider">or</span>
<button type="button" mat-stroked-button color="primary" class="fd-webcam-btn" (click)="captureFromWebcam()">
<i class="fa fa-camera"></i> Capture from Webcam
</button>
@if (capturedFileName) {
<span class="fd-webcam-confirm"><i class="fa fa-check-circle"></i> {{ capturedFileName }}</span>
}
</div>
</form> </form>
} }
</div> </div>
@@ -130,6 +130,41 @@ $white: #fff;
} }
} }
.fd-webcam-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 8px;
}
.fd-webcam-divider {
font-size: 12px;
color: $gray-500;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.fd-webcam-btn {
border-radius: 8px !important;
font-weight: 500 !important;
i {
margin-right: 6px;
}
}
.fd-webcam-confirm {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: #1e8e3e;
i {
color: #1e8e3e;
}
}
.fd-section-divider { .fd-section-divider {
margin: 8px 0 12px; margin: 8px 0 12px;
border-bottom: 1px solid $gray-200; border-bottom: 1px solid $gray-200;
@@ -353,42 +388,32 @@ $red-900: #993c1d;
padding-left: 38px; padding-left: 38px;
} }
/* Date input — match styling of other kyc inputs */ /* Date input — opens the Material calendar picker; styled to match other kyc inputs */
.kyc-input--date { .kyc-input--date {
font-family: inherit; font-family: inherit;
color: $gray-900; color: $gray-900;
cursor: pointer; cursor: pointer;
min-height: 40px; min-height: 40px;
padding-right: 14px !important; padding-left: 12px !important;
padding-right: 40px !important;
}
&::-webkit-calendar-picker-indicator { .kyc-input-wrap--date .kyc-input-wrap__calendar-toggle {
opacity: 0.55; position: absolute;
cursor: pointer; right: 2px;
filter: grayscale(1); top: 50%;
transition: opacity 0.15s; transform: translateY(-50%);
color: $gray-500;
::ng-deep .mat-mdc-icon-button {
width: 32px;
height: 32px;
padding: 4px;
} }
&:hover::-webkit-calendar-picker-indicator { ::ng-deep .mat-mdc-icon-button svg {
opacity: 0.9; width: 18px;
} height: 18px;
&::-webkit-datetime-edit {
color: $gray-900;
padding-top: 1px;
}
&::-webkit-datetime-edit-fields-wrapper {
color: $gray-900;
}
&::-webkit-datetime-edit-text {
color: $gray-500;
padding: 0 2px;
}
&:invalid::-webkit-datetime-edit,
&:not(:focus):placeholder-shown::-webkit-datetime-edit {
color: $gray-500;
} }
} }
@@ -16,12 +16,14 @@ import {
MatDialogClose MatDialogClose
} from '@angular/material/dialog'; } from '@angular/material/dialog';
import { ImageCropperDialogComponent } from '../image-cropper-dialog/image-cropper-dialog.component'; import { ImageCropperDialogComponent } from '../image-cropper-dialog/image-cropper-dialog.component';
import { CaptureImageDialogComponent } from '../capture-image-dialog/capture-image-dialog.component';
import { UntypedFormGroup, UntypedFormBuilder, Validators, ReactiveFormsModule } from '@angular/forms'; import { UntypedFormGroup, UntypedFormBuilder, Validators, ReactiveFormsModule } from '@angular/forms';
import { FileUploadComponent } from '../../../../shared/file-upload/file-upload.component'; import { FileUploadComponent } from '../../../../shared/file-upload/file-upload.component';
import { MatIconButton } from '@angular/material/button'; import { MatIconButton } from '@angular/material/button';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { ClientsService } from '../../../clients.service'; import { ClientsService } from '../../../clients.service';
import { ProofType, normalizeProofType, groupProofsByCategory } from '../../../shared/kyc-proof-types'; import { ProofType, normalizeProofType, groupProofsByCategory } from '../../../shared/kyc-proof-types';
import { dataUrlToFile } from '../../../../shared/utils/data-url.util';
type SectionKey = 'id' | 'address'; type SectionKey = 'id' | 'address';
@@ -72,6 +74,12 @@ export class UploadDocumentDialogComponent implements OnInit {
addrMergedFile: File | null = null; addrMergedFile: File | null = null;
addrMergedPreview: string | null = null; addrMergedPreview: string | null = null;
/** Non-identifier (generic) mode only — set after a webcam capture, since
* `FileUploadComponent` only reflects files picked through its own native input and has
* no input for one supplied programmatically. Cleared if the user then picks a file via
* Browse instead, so only one confirmation shows at a time. */
capturedFileName: string | null = null;
constructor() { constructor() {
const data = this.data; const data = this.data;
this.documentIdentifier = !!data?.documentIdentifier; this.documentIdentifier = !!data?.documentIdentifier;
@@ -390,6 +398,24 @@ export class UploadDocumentDialogComponent implements OnInit {
if ($event.target.files.length > 0) { if ($event.target.files.length > 0) {
const file = $event.target.files[0]; const file = $event.target.files[0];
this.uploadDocumentForm.get('file').setValue(file); this.uploadDocumentForm.get('file').setValue(file);
this.capturedFileName = null;
} }
} }
/** Non-identifier (generic Documents tab) mode only — lets staff photograph a document
* with the webcam instead of only being able to browse for an existing file. Reuses the
* same capture dialog as the profile-photo/signature flows. */
captureFromWebcam(): void {
const ref = this.dialog.open(CaptureImageDialogComponent, {
width: '720px',
maxWidth: '95vw',
data: { captureTarget: 'profile' }
});
ref.afterClosed().subscribe((dataUrl: string | null) => {
if (!dataUrl) return;
const file = dataUrlToFile(dataUrl, `webcam-capture-${Date.now()}.jpg`);
this.uploadDocumentForm.get('file').setValue(file);
this.capturedFileName = file.name;
});
}
} }
@@ -34,5 +34,8 @@
<button mat-raised-button color="primary" [mat-dialog-close]="{ draw: true }"> <button mat-raised-button color="primary" [mat-dialog-close]="{ draw: true }">
{{ 'labels.buttons.Draw' | translate }} {{ 'labels.buttons.Draw' | translate }}
</button> </button>
<button mat-raised-button color="primary" [mat-dialog-close]="{ capture: true }">
<fa-icon icon="camera"></fa-icon> Webcam
</button>
} }
</mat-dialog-actions> </mat-dialog-actions>
@@ -24,6 +24,7 @@ import { ClientsService } from 'app/clients/clients.service';
/** Node Types */ /** Node Types */
import { Buffer } from 'buffer'; import { Buffer } from 'buffer';
import { CdkScrollable } from '@angular/cdk/scrolling'; import { CdkScrollable } from '@angular/cdk/scrolling';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/** /**
@@ -39,7 +40,8 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
CdkScrollable, CdkScrollable,
MatDialogContent, MatDialogContent,
MatDialogActions, MatDialogActions,
MatDialogClose MatDialogClose,
FaIconComponent
] ]
}) })
export class ViewSignatureDialogComponent implements OnInit { export class ViewSignatureDialogComponent implements OnInit {
@@ -63,7 +65,13 @@ export class ViewSignatureDialogComponent implements OnInit {
* @param {any} data Documents data * @param {any} data Documents data
*/ */
constructor() { constructor() {
const signature = this.data.documents.find((document: any) => document.name === 'clientSignature') || {}; // Multiple 'clientSignature' documents can exist for clients who re-cropped/replaced their
// signature before uploads became single-slot, so pick the highest id (latest) rather than
// the first unordered match.
const signature =
this.data.documents
.filter((document: any) => document.name === 'clientSignature')
.sort((a: any, b: any) => b.id - a.id)[0] || {};
this.signatureId = signature.id; this.signatureId = signature.id;
this.clientId = this.data.id; this.clientId = this.data.id;
} }
@@ -0,0 +1,94 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<h2 mat-dialog-title>Welcome Kit Dispatch</h2>
<mat-dialog-content class="mat-typography">
<div fxLayout="row" fxLayoutAlign="center center" style="padding: 2rem" *ngIf="isLoading">
<mat-spinner diameter="40"></mat-spinner>
</div>
<ng-container *ngIf="!isLoading">
<!-- Tracking view if dispatches already exist -->
<div
class="dispatch-tracking-panel"
*ngFor="let dispatch of activeDispatches; let i = index"
style="margin-bottom: 16px; padding: 16px; border: 1px solid #e0e0e0; border-radius: 4px; background: #fafafa"
>
<div fxLayout="row" fxLayoutAlign="space-between start" style="margin-bottom: 8px">
<h3 style="margin: 0">{{ i === 0 ? 'Current' : 'Previous' }} Welcome Kit Status</h3>
<button mat-stroked-button color="primary" type="button" (click)="downloadPdf(dispatch)">
Download Details
</button>
</div>
<p style="margin: 4px 0"><strong>Delivery Address:</strong> {{ getDisplayAddress(dispatch) }}</p>
<p style="margin: 4px 0"><strong>Tracking ID:</strong> {{ dispatch.trackingId }}</p>
<p style="margin: 4px 0">
<strong>Delivery Mode:</strong> {{ dispatch.deliveryMode }}
<ng-container *ngIf="dispatch.deliveryMode === 'OTHER'">({{ dispatch.deliveryModeOtherText }})</ng-container>
</p>
<p style="margin: 4px 0"><strong>Dispatched On:</strong> {{ dispatch.dispatchedOnDate | date: 'mediumDate' }}</p>
<p style="margin: 4px 0">
<strong>Status:</strong>
<span class="status-badge status-{{ dispatch.status | lowercase }}">{{ dispatch.status }}</span>
</p>
</div>
<hr *ngIf="activeDispatches.length > 0 && welcomeKitsData?.canDispatchNew" />
<!-- Create form if they can dispatch a new one -->
<div class="dispatch-create-form" [formGroup]="dispatchForm" *ngIf="welcomeKitsData?.canDispatchNew">
<h3>Create New Dispatch</h3>
<div fxLayout="column" fxLayoutGap="16px">
<mat-form-field appearance="outline" class="full-width">
<mat-label>Delivery Address</mat-label>
<textarea matInput formControlName="deliveryAddress" rows="3" required></textarea>
<mat-error *ngIf="dispatchForm.get('deliveryAddress')?.hasError('required')">
Delivery Address is required
</mat-error>
</mat-form-field>
<mat-form-field appearance="outline" class="full-width">
<mat-label>Delivery Mode</mat-label>
<mat-select formControlName="deliveryMode" required>
<mat-option *ngFor="let mode of deliveryModes" [value]="mode">
{{ mode }}
</mat-option>
</mat-select>
<mat-error *ngIf="dispatchForm.get('deliveryMode')?.hasError('required')">
Delivery Mode is required
</mat-error>
</mat-form-field>
<mat-form-field
appearance="outline"
class="full-width"
*ngIf="dispatchForm.get('deliveryMode')?.value === 'OTHER'"
>
<mat-label>Specify Other Mode</mat-label>
<input matInput formControlName="deliveryModeOtherText" required />
<mat-error *ngIf="dispatchForm.get('deliveryModeOtherText')?.hasError('required')">
Please specify the delivery mode
</mat-error>
</mat-form-field>
</div>
</div>
</ng-container>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button mat-dialog-close>Close</button>
<button
mat-raised-button
color="primary"
*ngIf="welcomeKitsData?.canDispatchNew && !isLoading"
(click)="submit()"
[disabled]="dispatchForm.invalid || isLoading"
>
Dispatch
</button>
</mat-dialog-actions>
@@ -0,0 +1,59 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
.dispatch-tracking-panel {
background-color: #f5f5f5;
border-radius: 8px;
padding: 16px;
margin-bottom: 16px;
h3 {
margin-top: 0;
margin-bottom: 12px;
font-size: 1.1rem;
}
p {
margin: 6px 0;
}
.status-badge {
padding: 4px 8px;
border-radius: 4px;
font-size: 0.85rem;
font-weight: 500;
color: white;
&.status-dispatched {
background-color: #1976d2;
}
&.status-in_transit {
background-color: #f57c00;
}
&.status-delivered {
background-color: #388e3c;
}
&.status-returned {
background-color: #d32f2f;
}
}
}
.dispatch-create-form {
h3 {
margin-top: 0;
margin-bottom: 12px;
font-size: 1.1rem;
}
}
.full-width {
width: 100%;
}
@@ -0,0 +1,347 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Component, OnInit, inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {
MAT_DIALOG_DATA,
MatDialogRef,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialogClose
} from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { ClientsService } from '../../../clients.service';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { DatePipe } from '@angular/common';
import { jsPDF } from 'jspdf';
import autoTable from 'jspdf-autotable';
@Component({
selector: 'mifosx-welcome-kit-dialog',
templateUrl: './welcome-kit-dialog.component.html',
styleUrls: ['./welcome-kit-dialog.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialogClose,
MatProgressSpinnerModule
],
providers: [DatePipe]
})
export class WelcomeKitDialogComponent implements OnInit {
private dialogRef = inject(MatDialogRef<WelcomeKitDialogComponent>);
data: { clientId: string } = inject(MAT_DIALOG_DATA);
private clientsService = inject(ClientsService);
private formBuilder = inject(FormBuilder);
private snackBar = inject(MatSnackBar);
private datePipe = inject(DatePipe);
isLoading = true;
welcomeKitsData: any = null;
dispatchForm: FormGroup = this.formBuilder.group({
deliveryAddress: [
'',
Validators.required
],
deliveryMode: [
'POSTMAN',
Validators.required
],
deliveryModeOtherText: ['']
});
deliveryModes = [
'POSTMAN',
'COURIER',
'OTHER'
];
constructor() {
this.dispatchForm.get('deliveryMode')?.valueChanges.subscribe((mode) => {
const otherControl = this.dispatchForm.get('deliveryModeOtherText');
if (mode === 'OTHER') {
otherControl?.setValidators([Validators.required]);
} else {
otherControl?.clearValidators();
}
otherControl?.updateValueAndValidity();
});
}
ngOnInit(): void {
this.fetchData();
}
fetchData() {
this.isLoading = true;
this.clientsService.getWelcomeKits(this.data.clientId).subscribe({
next: (response: any) => {
this.welcomeKitsData = response;
if (this.welcomeKitsData && this.welcomeKitsData.canDispatchNew) {
this.fetchPrimaryAddress();
} else {
this.isLoading = false;
}
},
error: () => {
this.isLoading = false;
this.snackBar.open('Failed to load welcome kits data', 'Close', { duration: 3000 });
}
});
}
fetchPrimaryAddress() {
this.clientsService.getClientAddressData(this.data.clientId).subscribe({
next: (addresses: any) => {
this.isLoading = false;
if (addresses && addresses.length > 0) {
// Attempt to build a readable address from the first address returned
const primary = addresses[0];
const parts = [];
if (primary.addressLine1) parts.push(primary.addressLine1);
if (primary.addressLine2) parts.push(primary.addressLine2);
if (primary.city) parts.push(primary.city);
if (primary.stateName) parts.push(primary.stateName);
if (primary.postalCode) parts.push(primary.postalCode);
if (primary.countryName) parts.push(primary.countryName);
const clientNameStr = this.welcomeKitsData?.clientName ? this.welcomeKitsData.clientName + ' — ' : '';
this.dispatchForm.patchValue({
deliveryAddress: clientNameStr + parts.join(', ')
});
}
},
error: () => {
this.isLoading = false;
}
});
}
get activeDispatches() {
if (this.welcomeKitsData && this.welcomeKitsData.dispatches && this.welcomeKitsData.dispatches.length > 0) {
return this.welcomeKitsData.dispatches;
}
return [];
}
submit() {
if (this.dispatchForm.invalid) {
this.dispatchForm.markAllAsTouched();
return;
}
this.isLoading = true;
const formValue = this.dispatchForm.value;
const today = new Date();
const formattedDate = this.datePipe.transform(today, 'dd MMMM yyyy');
const payload = {
deliveryAddress: formValue.deliveryAddress,
deliveryMode: formValue.deliveryMode,
deliveryModeOtherText: formValue.deliveryMode === 'OTHER' ? formValue.deliveryModeOtherText : null,
dispatchedOnDate: formattedDate,
locale: 'en',
dateFormat: 'dd MMMM yyyy'
};
this.clientsService.dispatchWelcomeKit(this.data.clientId, payload).subscribe({
next: () => {
this.snackBar.open('Welcome Kit Dispatched successfully', 'Close', { duration: 3000 });
this.fetchData();
},
error: () => {
this.isLoading = false;
this.snackBar.open('Failed to dispatch welcome kit', 'Close', { duration: 3000 });
}
});
}
getDisplayAddress(dispatch: any): string {
const address = dispatch.deliveryAddress || '';
const name = this.welcomeKitsData?.clientName || '';
if (name && !address.startsWith(name)) {
return `${name} — ${address}`;
}
return address;
}
downloadPdf(dispatch: any) {
const doc = new jsPDF();
const clientName = this.welcomeKitsData?.clientName || dispatch.clientName || 'N/A';
const address = this.getDisplayAddress(dispatch);
const mode =
dispatch.deliveryMode === 'OTHER'
? `${dispatch.deliveryMode} (${dispatch.deliveryModeOtherText || ''})`
: dispatch.deliveryMode;
const trackingId = dispatch.trackingId || 'N/A';
const status = dispatch.status || 'N/A';
const dispatchedOn = this.datePipe.transform(dispatch.dispatchedOnDate, 'mediumDate') || 'N/A';
const primaryColor: [number, number, number] = [
31,
73,
125
]; // Navy Blue
const grayColor: [number, number, number] = [
100,
100,
100
];
const lightGray: [number, number, number] = [
230,
230,
230
];
const pageWidth = doc.internal.pageSize.getWidth();
const pageHeight = doc.internal.pageSize.getHeight();
// --- 1. Header Banner ---
doc.setFillColor(...primaryColor);
doc.rect(0, 0, pageWidth, 40, 'F');
// Decorative circles
doc.setFillColor(255, 255, 255);
doc.circle(pageWidth - 20, 15, 3, 'F');
doc.circle(pageWidth - 30, 25, 2, 'F');
doc.circle(pageWidth - 10, 30, 1.5, 'F');
doc.setFontSize(28);
doc.setFont('helvetica', 'bold');
doc.setTextColor(255, 255, 255);
doc.text('CBSNexora', 20, 22);
doc.setFontSize(11);
doc.setFont('helvetica', 'normal');
doc.text('Core Banking Solution', 22, 30);
// --- 2. Title ---
let currentY = 55;
doc.setFontSize(16);
doc.setFont('helvetica', 'bold');
doc.setTextColor(...primaryColor);
doc.text('Welcome Kit Dispatch Confirmation', pageWidth / 2, currentY, { align: 'center' });
currentY += 12;
// --- 3. Date Line ---
doc.setFontSize(11);
doc.setFont('helvetica', 'normal');
doc.setTextColor(0, 0, 0);
const today = this.datePipe.transform(new Date(), 'longDate');
doc.text(`Date: ${today}`, pageWidth - 20, currentY, { align: 'right' });
currentY += 15;
// --- 4. Greeting ---
doc.text(`Dear ${clientName},`, 20, currentY);
currentY += 10;
// --- 5. Opening welcome paragraph ---
const p1 =
'Welcome to the CBSNexora family! We are delighted to have you on board as a valued client. As part of our onboarding process, we have dispatched your Welcome Kit to your registered address, which includes your account documentation and essential banking materials to help you get started with us.';
const splitP1 = doc.splitTextToSize(p1, pageWidth - 40);
doc.text(splitP1, 20, currentY);
currentY += splitP1.length * 6 + 8;
// --- 6. Short paragraph about the company ---
const p2 =
'CBSNexora is committed to providing secure, reliable, and customer-first banking services. Our team is always available to assist you with any banking needs, from account management to digital services, ensuring a seamless banking experience.';
const splitP2 = doc.splitTextToSize(p2, pageWidth - 40);
doc.text(splitP2, 20, currentY);
currentY += splitP2.length * 6 + 8;
// --- 7. Transition line before details ---
doc.text('Please find your Welcome Kit dispatch details below for your reference:', 20, currentY);
currentY += 8;
// --- 8. Details Section ---
autoTable(doc, {
startY: currentY,
theme: 'plain',
margin: { left: 20, right: 20 },
styles: { fontSize: 11, cellPadding: 6, textColor: [
0,
0,
0
] },
columnStyles: {
0: { fontStyle: 'bold', cellWidth: 50 },
1: { cellWidth: 'auto' }
},
didDrawCell: (data) => {
if (data.row.index >= 0) {
doc.setDrawColor(...lightGray);
doc.setLineWidth(0.2);
doc.line(
data.cell.x,
data.cell.y + data.cell.height,
data.cell.x + data.cell.width,
data.cell.y + data.cell.height
);
}
},
body: [
[
'Delivery Address',
address
],
[
'Delivery Mode',
mode
],
[
'Tracking ID',
trackingId
],
[
'Status',
status
],
[
'Dispatched On',
dispatchedOn
]
]
});
// --- 9. Closing paragraph ---
currentY = (doc as any).lastAutoTable.finalY + 12;
const p3 =
'Should you have any questions about your Welcome Kit or need any assistance, please do not hesitate to reach out to our support team. We look forward to serving you and building a long-term relationship with you.';
const splitP3 = doc.splitTextToSize(p3, pageWidth - 40);
doc.text(splitP3, 20, currentY);
currentY += splitP3.length * 6 + 12;
// --- 10. Sign-off ---
doc.text('Warm regards,', 20, currentY);
currentY += 7;
doc.setFont('helvetica', 'bold');
doc.text('CBSNexora Operations Team', 20, currentY);
// --- 11. Footer ---
// Ensure footer doesn't float too high on short pages, but pushes down if content goes long
let footerY = currentY + 30;
if (footerY < pageHeight - 30) {
footerY = pageHeight - 30;
}
doc.setDrawColor(...primaryColor);
doc.setLineWidth(0.3);
doc.line(20, footerY - 5, pageWidth - 20, footerY - 5);
doc.setFontSize(9);
doc.setFont('helvetica', 'italic');
doc.setTextColor(...grayColor);
const timestamp = this.datePipe.transform(new Date(), 'medium');
doc.text(`This is a system-generated document. Generated on: ${timestamp}`, 20, footerY + 2);
doc.save(`WelcomeKit_Dispatch_${trackingId !== 'N/A' ? trackingId : new Date().getTime()}.pdf`);
}
}
@@ -19,14 +19,14 @@
<div class="f60-pan-ok__icon-wrap"> <div class="f60-pan-ok__icon-wrap">
<mat-icon class="f60-pan-ok__icon">verified</mat-icon> <mat-icon class="f60-pan-ok__icon">verified</mat-icon>
</div> </div>
<h3 class="f60-pan-ok__title">Form 60 Not Required</h3> <h3 class="f60-pan-ok__title">Form 97 Not Required</h3>
<p class="f60-pan-ok__desc"> <p class="f60-pan-ok__desc">
PAN <strong>{{ panNumber }}</strong> is attached to this client. PAN <strong>{{ panNumber }}</strong> is attached to this client.
@if (panVerified) { @if (panVerified) {
<mat-icon class="f60-pan-ok__tick">check_circle</mat-icon> <span class="f60-pan-ok__verified">Verified</span> <mat-icon class="f60-pan-ok__tick">check_circle</mat-icon> <span class="f60-pan-ok__verified">Verified</span>
} }
</p> </p>
<p class="f60-pan-ok__rule">As per Income Tax Rule 114B, Form 60 is only required when PAN is not available.</p> <p class="f60-pan-ok__rule">As per Income Tax Rule 114B, Form 97 is only required when PAN is not available.</p>
</div> </div>
} }
@@ -36,7 +36,7 @@
<div class="f60-warning"> <div class="f60-warning">
<mat-icon class="f60-warning__icon">warning_amber</mat-icon> <mat-icon class="f60-warning__icon">warning_amber</mat-icon>
<div class="f60-warning__text"> <div class="f60-warning__text">
<strong>PAN not provided</strong> — Form 60 declaration is mandatory as per Income Tax Rule 114B. <strong>PAN not provided</strong> — Form 97 declaration is mandatory as per Income Tax Rule 114B.
</div> </div>
</div> </div>
@@ -45,7 +45,7 @@
<div class="f60-card"> <div class="f60-card">
<div class="f60-card__header"> <div class="f60-card__header">
<mat-icon class="f60-card__header-icon">description</mat-icon> <mat-icon class="f60-card__header-icon">description</mat-icon>
<h3>Form 60 Declaration</h3> <h3>Form 97 Declaration</h3>
<span class="f60-card__status">Submitted</span> <span class="f60-card__status">Submitted</span>
<button mat-stroked-button color="primary" (click)="toggleEditMode()" class="f60-card__edit"> <button mat-stroked-button color="primary" (click)="toggleEditMode()" class="f60-card__edit">
<mat-icon>edit</mat-icon> Edit <mat-icon>edit</mat-icon> Edit
@@ -123,7 +123,7 @@
<div class="f60-card"> <div class="f60-card">
<div class="f60-card__header"> <div class="f60-card__header">
<mat-icon class="f60-card__header-icon">edit_note</mat-icon> <mat-icon class="f60-card__header-icon">edit_note</mat-icon>
<h3>Form 60 Declaration</h3> <h3>Form 97 Declaration</h3>
</div> </div>
<div class="f60-card__body"> <div class="f60-card__body">
<form [formGroup]="form60Form" (ngSubmit)="submit()"> <form [formGroup]="form60Form" (ngSubmit)="submit()">
@@ -204,7 +204,7 @@
<button type="button" mat-stroked-button (click)="toggleEditMode()">Cancel</button> <button type="button" mat-stroked-button (click)="toggleEditMode()">Cancel</button>
} }
<button type="submit" mat-flat-button color="primary" [disabled]="!form60Form.valid"> <button type="submit" mat-flat-button color="primary" [disabled]="!form60Form.valid">
<mat-icon>check</mat-icon> Submit Form 60 <mat-icon>check</mat-icon> Submit Form 97
</button> </button>
</div> </div>
</form> </form>
@@ -224,14 +224,14 @@ export class Form60TabComponent implements OnInit, OnDestroy {
this.isEditMode = false; this.isEditMode = false;
this.alertService.alert({ this.alertService.alert({
type: 'success', type: 'success',
message: 'Form 60 submitted successfully.' message: 'Form 97 submitted successfully.'
}); });
this.loadForm60Data(); this.loadForm60Data();
}, },
error: (err: any) => { error: (err: any) => {
this.alertService.alert({ this.alertService.alert({
type: 'error', type: 'error',
message: err?.error?.developerMessage || err?.error?.defaultUserMessage || 'Failed to submit Form 60.' message: err?.error?.developerMessage || err?.error?.defaultUserMessage || 'Failed to submit Form 97.'
}); });
} }
}); });
@@ -0,0 +1,79 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<div class="history-tab">
<div class="history-tab__header">
<h3>Change History</h3>
<p>Past changes to this client's details and address, pulled from the system Audit Trail.</p>
</div>
<div class="history-tab__table-container">
@if (isLoading) {
<mat-progress-bar mode="indeterminate" class="history-tab__loader"></mat-progress-bar>
}
@if (!isLoading && dataSource.data.length === 0) {
<div class="history-tab__empty">No recorded changes for this client yet.</div>
}
@if (!isLoading && dataSource.data.length > 0) {
<table mat-table [dataSource]="dataSource" class="history-tab__table">
<ng-container matColumnDef="entityName">
<th mat-header-cell *matHeaderCellDef>Entity</th>
<td mat-cell *matCellDef="let row">{{ row.entityName | translateKey: 'auditTrail.entities' }}</td>
</ng-container>
<ng-container matColumnDef="actionName">
<th mat-header-cell *matHeaderCellDef>Action</th>
<td mat-cell *matCellDef="let row">
<span class="history-tab__action-badge">{{ row.actionName | translateKey: 'auditTrail.actions' }}</span>
</td>
</ng-container>
<ng-container matColumnDef="fieldsChanged">
<th mat-header-cell *matHeaderCellDef>Fields Changed</th>
<td mat-cell *matCellDef="let row" class="history-tab__fields">{{ fieldsChanged(row) || '—' }}</td>
</ng-container>
<ng-container matColumnDef="maker">
<th mat-header-cell *matHeaderCellDef>Made By</th>
<td mat-cell *matCellDef="let row">{{ row.maker }}</td>
</ng-container>
<ng-container matColumnDef="madeOnDate">
<th mat-header-cell *matHeaderCellDef>Made On</th>
<td mat-cell *matCellDef="let row" class="history-tab__mono">{{ row.madeOnDate | datetimeFormat }}</td>
</ng-container>
<ng-container matColumnDef="processingResult">
<th mat-header-cell *matHeaderCellDef>Status</th>
<td mat-cell *matCellDef="let row">
<span
class="history-tab__status"
[class.history-tab__status--success]="row.processingResult === 'SUCCESS'"
[class.history-tab__status--failure]="row.processingResult === 'FAILURE'"
[class.history-tab__status--awaiting]="row.processingResult === 'AWAITING_APPROVAL'"
>
{{ row.processingResult }}
</span>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr
mat-row
*matRowDef="let row; columns: displayedColumns"
class="history-tab__row"
[routerLink]="['/system', 'audit-trails', row.id]"
></tr>
</table>
<mat-paginator [pageSize]="10" [pageSizeOptions]="[10, 25, 50]" showFirstLastButtons></mat-paginator>
}
</div>
</div>
@@ -0,0 +1,108 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
.history-tab {
padding: 16px 0;
}
.history-tab__header {
margin-bottom: 16px;
h3 {
margin: 0 0 4px;
font-size: 18px;
font-weight: 600;
}
p {
margin: 0;
font-size: 13px;
color: rgb(0 0 0 / 60%);
}
}
.history-tab__table-container {
position: relative;
background: #fff;
border-radius: 8px;
box-shadow: 0 1px 4px rgb(0 0 0 / 8%);
overflow-x: auto;
}
.history-tab__loader {
position: absolute;
top: 0;
left: 0;
right: 0;
}
.history-tab__empty {
padding: 32px 16px;
text-align: center;
color: rgb(0 0 0 / 55%);
font-size: 13.5px;
}
.history-tab__table {
width: 100%;
}
.history-tab__row {
cursor: pointer;
&:hover {
background: #f8fafc;
}
}
.history-tab__fields {
max-width: 320px;
white-space: normal;
font-size: 12.5px;
color: #475569;
}
.history-tab__mono {
font-family: 'Roboto Mono', monospace;
font-size: 12.5px;
}
.history-tab__action-badge {
display: inline-block;
padding: 2px 10px;
border-radius: 999px;
background: #eff6ff;
color: #1074b9;
font-size: 11.5px;
font-weight: 600;
}
.history-tab__status {
display: inline-block;
padding: 2px 10px;
border-radius: 999px;
font-size: 11.5px;
font-weight: 700;
background: #f1f5f9;
color: #475569;
&--success {
background: #dcfce7;
color: #15803d;
}
&--failure {
background: #fee2e2;
color: #b91c1c;
}
&--awaiting {
background: #fef3c7;
color: #92400e;
}
}
@@ -0,0 +1,150 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/** Angular Imports */
import { Component, OnInit, ViewChild, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatPaginator } from '@angular/material/paginator';
import {
MatTableDataSource,
MatTable,
MatColumnDef,
MatHeaderCellDef,
MatHeaderCell,
MatCellDef,
MatCell,
MatHeaderRowDef,
MatHeaderRow,
MatRowDef,
MatRow
} from '@angular/material/table';
import { MatProgressBar } from '@angular/material/progress-bar';
/** rxjs Imports */
import { forkJoin } from 'rxjs';
/** Custom Services */
import { SystemService } from 'app/system/system.service';
import { DatetimeFormatPipe } from '../../../pipes/datetime-format.pipe';
import { TranslatePipe } from '../../../pipes/translate.pipe';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/**
* Client "History" tab — a read-only, client-scoped view over the EXISTING system-wide
* Audit Trail data (no new backend endpoint). Reuses `SystemService.getAuditTrails()`
* exactly as `AuditTrailsComponent` does, pre-filtered to `entityName IN (CLIENT, ADDRESS)`
* + `resourceId = clientId` — two calls (the underlying `filterBy` shape only carries one
* `entityName` value at a time) merged and sorted client-side.
*/
@Component({
selector: 'mifosx-clients-history-tab',
templateUrl: './history-tab.component.html',
styleUrls: ['./history-tab.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatProgressBar,
MatTable,
MatColumnDef,
MatHeaderCellDef,
MatHeaderCell,
MatCellDef,
MatCell,
MatHeaderRowDef,
MatHeaderRow,
MatRowDef,
MatRow,
MatPaginator,
DatetimeFormatPipe,
TranslatePipe
]
})
export class HistoryTabComponent implements OnInit {
private route = inject(ActivatedRoute);
private systemService = inject(SystemService);
/** Client ID (from the parent `:clientId` route param, same pattern as notes-tab). */
clientId: string;
isLoading = false;
displayedColumns: string[] = [
'entityName',
'actionName',
'fieldsChanged',
'maker',
'madeOnDate',
'processingResult'
];
dataSource: MatTableDataSource<any> = new MatTableDataSource<any>([]);
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor() {
this.clientId = this.route.parent.snapshot.params['clientId'];
}
ngOnInit(): void {
this.loadHistory();
}
private auditFilterFor(entityName: string): { type: string; value: string }[] {
return [
{ type: 'entityName', value: entityName },
{ type: 'resourceId', value: this.clientId }
];
}
private loadHistory(): void {
this.isLoading = true;
forkJoin({
client: this.systemService.getAuditTrails(this.auditFilterFor('CLIENT'), '', '', 0, 200),
address: this.systemService.getAuditTrails(this.auditFilterFor('ADDRESS'), '', '', 0, 200)
}).subscribe({
next: ({ client, address }: { client: any; address: any }) => {
const merged = [
...(client?.pageItems || []),
...(address?.pageItems || [])
];
// Most recent first — audit trail ids are monotonically increasing.
merged.sort((a, b) => (b?.id ?? 0) - (a?.id ?? 0));
this.dataSource = new MatTableDataSource(merged);
this.dataSource.paginator = this.paginator;
this.isLoading = false;
},
error: () => {
this.isLoading = false;
}
});
}
/**
* Summarises which fields a row changed, parsed from `commandAsJson` — same source
* `ViewAuditComponent` parses for its command/value table, just condensed to a
* comma-separated field list for this compact history view. Boilerplate command
* params (locale/dateFormat) are excluded as noise.
*/
fieldsChanged(row: any): string {
if (!row?.commandAsJson) {
return '';
}
try {
const parsed = JSON.parse(row.commandAsJson);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
const ignore = new Set([
'locale',
'dateFormat'
]);
return Object.keys(parsed)
.filter((key) => !ignore.has(key))
.join(', ');
}
} catch {
// Malformed/absent commandAsJson — leave blank rather than throw.
}
return '';
}
}
@@ -105,7 +105,7 @@
[class.pd-verify-badge--verified]="!clientViewData.isMinor" [class.pd-verify-badge--verified]="!clientViewData.isMinor"
[class.pd-verify-badge--pending]="clientViewData.isMinor" [class.pd-verify-badge--pending]="clientViewData.isMinor"
> >
{{ clientViewData.isMinor ? 'Yes (Age < 10)' : 'No' }} {{ clientViewData.isMinor ? 'Yes (Age < 18)' : 'No' }}
</span> </span>
</div> </div>
</div> </div>
+3 -5
View File
@@ -98,12 +98,10 @@
</td> </td>
</ng-container> </ng-container>
<!-- Account no Column --> <!-- Client ID Column -->
<ng-container matColumnDef="accountNumber"> <ng-container matColumnDef="accountNumber">
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{ 'labels.inputs.Account No' | translate }}</th> <th mat-header-cell *matHeaderCellDef mat-sort-header>Client ID</th>
<td mat-cell *matCellDef="let row" class="cell-mono"> <td mat-cell *matCellDef="let row" class="cell-mono">{{ row.id }}</td>
<mifosx-account-number display="left" accountNo="{{ row.accountNumber }}"></mifosx-account-number>
</td>
</ng-container> </ng-container>
<!-- CIF Number Column --> <!-- CIF Number Column -->
+13 -4
View File
@@ -137,7 +137,16 @@ export class ClientsComponent implements OnInit {
private getClients() { private getClients() {
this.isLoading = true; this.isLoading = true;
this.clientService this.clientService
.searchByText(this.filterText, this.currentPage, this.pageSize, this.sortAttribute, this.sortDirection) .searchByText(
this.filterText,
this.currentPage,
this.pageSize,
this.sortAttribute,
this.sortDirection,
false,
'',
true
)
.subscribe( .subscribe(
(data: any) => { (data: any) => {
this.allRows = data.content || []; this.allRows = data.content || [];
@@ -166,7 +175,7 @@ export class ClientsComponent implements OnInit {
// Use individual subscriptions instead of forkJoin to avoid EMPTY observable issues // Use individual subscriptions instead of forkJoin to avoid EMPTY observable issues
clients.forEach((client, i) => { clients.forEach((client, i) => {
this.clientService this.clientService
.getClientData(client.id?.toString()) .getClientData(client.id?.toString(), true)
.pipe(catchError(() => of(null))) .pipe(catchError(() => of(null)))
.subscribe((data: any) => { .subscribe((data: any) => {
if (data?.legalForm) { if (data?.legalForm) {
@@ -176,7 +185,7 @@ export class ClientsComponent implements OnInit {
}); });
this.clientService this.clientService
.getClientKyc(client.id?.toString()) .getClientKyc(client.id?.toString(), true)
.pipe(catchError(() => of(null))) .pipe(catchError(() => of(null)))
.subscribe((kyc: any) => { .subscribe((kyc: any) => {
if (kyc) { if (kyc) {
@@ -188,7 +197,7 @@ export class ClientsComponent implements OnInit {
}); });
this.clientService this.clientService
.getClientAddressData(client.id?.toString()) .getClientAddressData(client.id?.toString(), true)
.pipe(catchError(() => of(null))) .pipe(catchError(() => of(null)))
.subscribe((addr: any) => { .subscribe((addr: any) => {
if (addr && Array.isArray(addr) && addr.length > 0) { if (addr && Array.isArray(addr) && addr.length > 0) {
+131 -9
View File
@@ -8,7 +8,8 @@
/** Angular Imports */ /** Angular Imports */
import { Injectable, inject } from '@angular/core'; import { Injectable, inject } from '@angular/core';
import { HttpClient, HttpParams, HttpBackend, HttpHeaders } from '@angular/common/http'; import { HttpClient, HttpParams, HttpBackend, HttpHeaders, HttpContext } from '@angular/common/http';
import { SILENT_HTTP_ERROR } from 'app/core/http/silent-error.token';
/** rxjs Imports */ /** rxjs Imports */
import { Observable, of, throwError } from 'rxjs'; import { Observable, of, throwError } from 'rxjs';
@@ -16,6 +17,7 @@ import { switchMap } from 'rxjs/operators';
import { map, catchError } from 'rxjs/operators'; import { map, catchError } from 'rxjs/operators';
import { environment } from 'environments/environment'; import { environment } from 'environments/environment';
import { dataUrlToFile } from 'app/shared/utils/data-url.util';
/** /**
* Clients service. * Clients service.
@@ -65,8 +67,11 @@ export class ClientsService {
return this.http.get(`/clients/template?officeId=${officeId}&staffInSelectedOfficeOnly=true`); return this.http.get(`/clients/template?officeId=${officeId}&staffInSelectedOfficeOnly=true`);
} }
getClientData(clientId: string) { getClientData(clientId: string, silent = false) {
return this.http.get(`/clients/${clientId}`); return this.http.get(
`/clients/${clientId}`,
silent ? { context: new HttpContext().set(SILENT_HTTP_ERROR, true) } : {}
);
} }
createClient(client: any) { createClient(client: any) {
@@ -81,6 +86,43 @@ export class ClientsService {
return this.http.delete(`/clients/${clientId}`); return this.http.delete(`/clients/${clientId}`);
} }
/**
* Maker-checker for Client edits — stages the change in m_client_pending_edit instead of
* applying it immediately; a different user must call approveClientEdit() before it takes
* effect. See ClientEditApiResource on the backend.
*/
submitClientEdit(clientId: string, client: any) {
return this.http.post(`/clients/${clientId}/edit`, client);
}
getPendingClientEdit(clientId: string) {
return this.http.get(`/clients/${clientId}/edit/pending`);
}
getAllPendingClientEdits(
status?: string,
clientName?: string,
fromDate?: string,
toDate?: string,
offset = 0,
limit = 20
): Observable<any> {
let params = new HttpParams().set('offset', offset).set('limit', limit);
if (status) params = params.set('status', status);
if (clientName) params = params.set('clientName', clientName);
if (fromDate) params = params.set('fromDate', fromDate);
if (toDate) params = params.set('toDate', toDate);
return this.http.get(`/clients/edit/pending`, { params });
}
approveClientEdit(clientId: string) {
return this.http.post(`/clients/${clientId}/edit/approve`, {});
}
rejectClientEdit(clientId: string, rejectReason?: string) {
return this.http.post(`/clients/${clientId}/edit/reject`, { rejectReason: rejectReason || '' });
}
getClientDataAndTemplate(clientId: string) { getClientDataAndTemplate(clientId: string) {
const httpParams = new HttpParams().set('template', 'true').set('staffInSelectedOfficeOnly', 'true'); const httpParams = new HttpParams().set('template', 'true').set('staffInSelectedOfficeOnly', 'true');
return this.http.get(`/clients/${clientId}`, { params: httpParams }); return this.http.get(`/clients/${clientId}`, { params: httpParams });
@@ -115,8 +157,11 @@ export class ClientsService {
return this.http.get(`/clients/${clientId}/accounts`); return this.http.get(`/clients/${clientId}/accounts`);
} }
getClientAddressData(clientId: string) { getClientAddressData(clientId: string, silent = false) {
return this.http.get(`/client/${clientId}/addresses`); return this.http.get(
`/client/${clientId}/addresses`,
silent ? { context: new HttpContext().set(SILENT_HTTP_ERROR, true) } : {}
);
} }
getClientChargesData(clientId: string) { getClientChargesData(clientId: string) {
@@ -230,6 +275,63 @@ export class ClientsService {
return this.http.get(`/clients/${clientId}/documents/${documentId}/attachment`, { responseType: 'blob' }); return this.http.get(`/clients/${clientId}/documents/${documentId}/attachment`, { responseType: 'blob' });
} }
/**
* Uploads a webcam-captured signature (photograph of a paper signature).
* Mirrors `uploadClientSignatureImage()`'s multipart shape (name=clientSignature)
* exactly, but the source is a captured `data:` URL rather than a picked `File`.
*/
uploadCapturedClientSignature(clientId: string, imageDataUrl: string) {
const formData = new FormData();
formData.append('file', dataUrlToFile(imageDataUrl, 'clientSignature.jpg'));
formData.append('name', 'clientSignature');
formData.append('description', 'Client signature (captured via webcam)');
return this.http.post(`/clients/${clientId}/documents`, formData);
}
/**
* Generates an OTP against a client's OLD or NEW mobile/email destination, ahead of a
* sensitive contact-detail change. Dual-OTP verification (old + new) is required before
* the mobileNo/emailAddress change is accepted by the backend — see `verifyClientContactOtp()`.
* @param clientId Client ID
* @param channel 'MOBILE' | 'EMAIL'
* @param destination Raw mobile number or email address to send the OTP to
*/
sendClientContactOtp(clientId: string, channel: 'MOBILE' | 'EMAIL', destination: string): Observable<any> {
return this.http.post(`/clients/${clientId}/contact-verification/otp`, { channel, destination });
}
/**
* Verifies an OTP previously generated via `sendClientContactOtp()`.
* @param clientId Client ID
* @param otpId ID returned by the generate call
* @param otp 6-digit code entered by staff on the customer's behalf
*/
verifyClientContactOtp(clientId: string, otpId: number, otp: string): Observable<any> {
return this.http.post(`/clients/${clientId}/contact-verification/otp/verify`, { otpId, otp });
}
/**
* Generates an OTP against a NOT-YET-CREATED client's mobile/email, ahead of the initial
* `POST /clients` call. There is no clientId yet, so this hits the clientId-less sibling
* endpoint (`ClientCreationContactVerificationApiResource`) rather than
* `sendClientContactOtp()`'s `/clients/{clientId}/...` shape. The returned otpId is sent
* back as `mobileNewOtpId`/`emailNewOtpId` on `createClient()`.
* @param channel 'MOBILE' | 'EMAIL'
* @param destination Raw mobile number or email address to send the OTP to
*/
sendClientCreationContactOtp(channel: 'MOBILE' | 'EMAIL', destination: string): Observable<any> {
return this.http.post(`/clients/contact-verification/otp`, { channel, destination });
}
/**
* Verifies an OTP previously generated via `sendClientCreationContactOtp()`.
* @param otpId ID returned by the generate call
* @param otp 6-digit code entered by staff on the customer's behalf
*/
verifyClientCreationContactOtp(otpId: number, otp: string): Observable<any> {
return this.http.post(`/clients/contact-verification/otp/verify`, { otpId, otp });
}
getClientFamilyMembers(clientId: string) { getClientFamilyMembers(clientId: string) {
return this.http.get(`/clients/${clientId}/familymembers`); return this.http.get(`/clients/${clientId}/familymembers`);
} }
@@ -603,7 +705,8 @@ export class ClientsService {
sortAttribute: string = '', sortAttribute: string = '',
sortDirection: string = '', sortDirection: string = '',
activeOnly: boolean = false, activeOnly: boolean = false,
legalFormType: string = '' legalFormType: string = '',
silent: boolean = false
) { ) {
const innerRequest: any = { text }; const innerRequest: any = { text };
if (activeOnly) { if (activeOnly) {
@@ -632,7 +735,11 @@ export class ClientsService {
] ]
}; };
} }
return this.http.post(`/v2/clients/search`, request); return this.http.post(
`/v2/clients/search`,
request,
silent ? { context: new HttpContext().set(SILENT_HTTP_ERROR, true) } : {}
);
} }
/** /**
@@ -669,8 +776,11 @@ export class ClientsService {
* Gets KYC details for a client. * Gets KYC details for a client.
* @param clientId Client ID * @param clientId Client ID
*/ */
getClientKyc(clientId: string): Observable<any> { getClientKyc(clientId: string, silent = false): Observable<any> {
return this.http.get(`/clients/${clientId}/kyc`); return this.http.get(
`/clients/${clientId}/kyc`,
silent ? { context: new HttpContext().set(SILENT_HTTP_ERROR, true) } : {}
);
} }
/** /**
@@ -681,6 +791,10 @@ export class ClientsService {
return this.http.get(`/clients/${clientId}/kyc/template`); return this.http.get(`/clients/${clientId}/kyc/template`);
} }
getClientRiskRules(): Observable<any[]> {
return this.http.get<any[]>('/kyc/risk-rules');
}
/** Fetch code values by code ID */ /** Fetch code values by code ID */
getCodeValuesById(codeId: number): Observable<any[]> { getCodeValuesById(codeId: number): Observable<any[]> {
return this.http.get<any[]>(`/codes/${codeId}/codevalues`).pipe(catchError(() => of([]))); return this.http.get<any[]>(`/codes/${codeId}/codevalues`).pipe(catchError(() => of([])));
@@ -836,4 +950,12 @@ export class ClientsService {
submitClientForm60(clientId: string, data: any): Observable<any> { submitClientForm60(clientId: string, data: any): Observable<any> {
return this.http.post(`/clients/${clientId}/form60`, data); return this.http.post(`/clients/${clientId}/form60`, data);
} }
getWelcomeKits(clientId: string | number): Observable<any> {
return this.http.get(`/clients/${clientId}/welcomekit`);
}
dispatchWelcomeKit(clientId: string | number, data: any): Observable<any> {
return this.http.post(`/clients/${clientId}/welcomekit`, data);
}
} }
@@ -71,10 +71,12 @@
<mifosx-client-kyc-step <mifosx-client-kyc-step
#clientKyc #clientKyc
[isNonIndividual]="legalFormType === 2" [isNonIndividual]="legalFormType === 2"
[isMinor]="clientGeneralStep?.isMinor || false"
[clientId]="createdClientId" [clientId]="createdClientId"
[constitutionMeta]="clientGeneralStep?.selectedConstitution" [constitutionMeta]="clientGeneralStep?.selectedConstitution"
[entityName]="clientGeneralStep?.createClientForm?.get('fullname')?.value || ''" [entityName]="clientGeneralStep?.createClientForm?.get('fullname')?.value || ''"
[readOnly]="isTabReadOnly(1)" [readOnly]="isTabReadOnly(1)"
[calculatedRisk]="clientGeneralStep?.calculatedRisk"
></mifosx-client-kyc-step> ></mifosx-client-kyc-step>
</div> </div>
@@ -146,6 +148,8 @@
} }
<mifosx-client-india-address-step <mifosx-client-india-address-step
#clientIndiaAddress #clientIndiaAddress
[isMinor]="clientGeneralStep?.isMinor || false"
[isNonIndividual]="legalFormType === 2"
[readOnly]="isTabReadOnly(addressTabIdx)" [readOnly]="isTabReadOnly(addressTabIdx)"
></mifosx-client-india-address-step> ></mifosx-client-india-address-step>
</div> </div>
@@ -111,6 +111,12 @@ export class CreateClientComponent {
this.route.data.subscribe((data: { clientTemplate: any; clientAddressFieldConfig: any }) => { this.route.data.subscribe((data: { clientTemplate: any; clientAddressFieldConfig: any }) => {
this.clientTemplate = data.clientTemplate; this.clientTemplate = data.clientTemplate;
this.clientAddressFieldConfig = data.clientAddressFieldConfig; this.clientAddressFieldConfig = data.clientAddressFieldConfig;
// This app's RouteReusableStrategy keeps this SAME component instance alive across
// repeat visits to /clients/create, so ngOnInit/constructor won't re-run for a second
// "create new client" session — reset transient state here instead, since `route.data`
// re-emits on every navigation regardless of whether the component was reused. Must run
// BEFORE setDatatables(), which reads legalFormType to filter clientTemplate.datatables.
this.resetForNewClient();
this.setDatatables(); this.setDatatables();
}); });
// Read pre-fill data set by "Create as Client" from a manual family member // Read pre-fill data set by "Create as Client" from a manual family member
@@ -121,6 +127,22 @@ export class CreateClientComponent {
} }
} }
/** Resets session state that could otherwise leak between clients when the route is reused. */
private resetForNewClient(): void {
this.legalFormType = 1;
this.selectedTabIndex = 0;
this.createdClientId = '';
this.savingClient = false;
this.saveProgress = 0;
this.tabEditMode = {};
this.highestTabReached = 0;
this.validationError = '';
this.prefillData = null;
this.clientGeneralStep?.resetForNewClient();
this.clientKycStep?.resetForNewClient();
this.clientIndiaAddressStep?.resetForNewClient();
}
/** Check if a tab is in read-only mode (completed tab navigated back to) */ /** Check if a tab is in read-only mode (completed tab navigated back to) */
isTabReadOnly(tabIndex: number): boolean { isTabReadOnly(tabIndex: number): boolean {
// Only tabs that have been passed (below highest reached) AND not explicitly set to edit mode // Only tabs that have been passed (below highest reached) AND not explicitly set to edit mode
@@ -192,7 +214,10 @@ export class CreateClientComponent {
if (idx === 0) { if (idx === 0) {
if (!this.clientGeneralStep || !this.clientGeneralForm) return false; if (!this.clientGeneralStep || !this.clientGeneralForm) return false;
if (this.clientGeneralStep.sanctionsBlocked) return false; if (this.clientGeneralStep.sanctionsBlocked) return false;
return this.clientGeneralForm.valid; if (!this.clientGeneralForm.valid) return false;
// Contact-OTP gate: mobileNo/emailAddress must each be OTP-verified before a brand-new
// client can be created — mirrors the edit flow's dual-OTP gate in EditClientComponent.
return this.clientGeneralStep.contactVerified;
} }
if (idx === 1) { if (idx === 1) {
// KYC tab — block when the kyc form has unfilled required fields // KYC tab — block when the kyc form has unfilled required fields
@@ -215,8 +240,8 @@ export class CreateClientComponent {
return this.isAddressStepValid(); return this.isAddressStepValid();
} }
if (idx === 3) { if (idx === 3) {
// Family tab — relations are optional, always allow. // Family tab — Mother is required, and either Father or a Caretaker.
return true; return !this.clientFamilyMembersStep || this.clientFamilyMembersStep.familyRelationshipRulesMet;
} }
} }
return true; return true;
@@ -241,6 +266,20 @@ export class CreateClientComponent {
if (idx === 0 && this.clientGeneralStep?.sanctionsBlocked) { if (idx === 0 && this.clientGeneralStep?.sanctionsBlocked) {
return 'Client failed sanctions screening — cannot proceed.'; return 'Client failed sanctions screening — cannot proceed.';
} }
if (idx === 0 && this.clientGeneralForm?.valid && !this.clientGeneralStep?.contactVerified) {
return 'Verify the OTP sent to both the mobile number and email address before proceeding.';
}
if (idx === 1) {
const labels = this.clientKycStep?.invalidFieldLabels || [];
if (labels.length) {
return `Please fill/correct: ${labels.join(', ')}.`;
}
}
if (idx === 3 && this.legalFormType === 1 && this.clientFamilyMembersStep) {
const step = this.clientFamilyMembersStep;
if (!step.hasMother) return 'Mother is required as a family member.';
if (!step.hasFather && !step.hasCaretaker) return 'Either Father or a Caretaker is required as a family member.';
}
return 'Please fill all mandatory fields on this tab to continue.'; return 'Please fill all mandatory fields on this tab to continue.';
} }
@@ -309,6 +348,28 @@ export class CreateClientComponent {
return; return;
} }
// Contact-OTP gate — defensive re-check. The Save & Next button is already disabled via
// `currentStepValid` while this is incomplete, but don't rely on that alone (mirrors the
// same defensive re-check in EditClientComponent.confirmAndSaveTab()).
if (!this.clientGeneralStep?.contactVerified) {
this.snackBar.open('Verify the OTP sent to both the mobile number and email address before saving.', 'Close', {
duration: 5000
});
return;
}
// PWD gate — disability type + certificate are mandatory when PWD is checked
// (Senior Citizen proof upload is optional, not gated here)
if (!this.clientGeneralStep?.seniorPwdDocsComplete) {
this.clientGeneralStep?.markSeniorPwdDocsTouched();
this.snackBar.open(
'Select the disability type and upload the Disability Certificate before continuing.',
'Close',
{ duration: 5000 }
);
return;
}
// Sanctions verification gate — Verify Client must be clicked before save // Sanctions verification gate — Verify Client must be clicked before save
if (!this.clientGeneralStep?.sanctionsVerified) { if (!this.clientGeneralStep?.sanctionsVerified) {
this.dialog this.dialog
@@ -426,6 +487,12 @@ export class CreateClientComponent {
const dateFormat = this.settingsService.dateFormat; const dateFormat = this.settingsService.dateFormat;
const clientData = { ...this.client, dateFormat, locale }; const clientData = { ...this.client, dateFormat, locale };
// Mandatory contact-OTP references — required by POST /clients whenever mobileNo/
// emailAddress are present (they always are, both are Validators.required on this form).
// Gated by `contactVerified` above, so these are guaranteed non-null at this point.
clientData.mobileNewOtpId = this.clientGeneralStep?.mobileNewOtpId;
clientData.emailNewOtpId = this.clientGeneralStep?.emailNewOtpId;
if (this.clientTemplate.datatables && this.clientTemplate.datatables.length > 0) { if (this.clientTemplate.datatables && this.clientTemplate.datatables.length > 0) {
const datatables: any[] = []; const datatables: any[] = [];
this.clientDatatables?.forEach((clientDatatable: ClientDatatableStepComponent) => { this.clientDatatables?.forEach((clientDatatable: ClientDatatableStepComponent) => {
@@ -441,6 +508,29 @@ export class CreateClientComponent {
clearInterval(progressInterval); clearInterval(progressInterval);
this.saveProgress = 100; this.saveProgress = 100;
this.createdClientId = response.resourceId; this.createdClientId = response.resourceId;
// Senior Citizen / PWD supporting documents — uploaded after creation, same pattern as
// the KYC step's photo/signature uploads (the generic /clients/{id}/documents endpoint
// needs a real clientId, which only exists once createClient() has returned).
if (this.clientGeneralStep?.seniorCitizenProofFile) {
const seniorCitizenProofForm = new FormData();
seniorCitizenProofForm.append('file', this.clientGeneralStep.seniorCitizenProofFile);
seniorCitizenProofForm.append('name', 'seniorCitizenProof');
seniorCitizenProofForm.append('description', 'Senior Citizen Proof (Age/ID Proof)');
this.clientsService
.uploadClientDocument(this.createdClientId, seniorCitizenProofForm)
.subscribe({ error: () => {} });
}
if (this.clientGeneralStep?.pwdCertificateFile) {
const pwdCertificateForm = new FormData();
pwdCertificateForm.append('file', this.clientGeneralStep.pwdCertificateFile);
pwdCertificateForm.append('name', 'pwdCertificate');
pwdCertificateForm.append('description', 'Disability Certificate');
this.clientsService
.uploadClientDocument(this.createdClientId, pwdCertificateForm)
.subscribe({ error: () => {} });
}
// Brief delay to show 100% before transitioning // Brief delay to show 100% before transitioning
setTimeout(() => { setTimeout(() => {
this.savingClient = false; this.savingClient = false;
@@ -486,6 +576,21 @@ export class CreateClientComponent {
this.selectedTabIndex = 3; this.selectedTabIndex = 3;
return; return;
} }
// Validate: Mother required, and either Father or a Caretaker (Individual clients)
if (
this.legalFormType === 1 &&
this.clientFamilyMembersStep &&
!this.clientFamilyMembersStep.familyRelationshipRulesMet
) {
const step = this.clientFamilyMembersStep;
if (!step.hasMother) {
this.validationError = 'Mother is required as a family member.';
} else {
this.validationError = 'Either Father or a Caretaker is required as a family member.';
}
this.selectedTabIndex = 3;
return;
}
this.validationError = ''; this.validationError = '';
if (this.createdClientId) { if (this.createdClientId) {
@@ -493,12 +598,19 @@ export class CreateClientComponent {
this.finalizeClient(this.createdClientId); this.finalizeClient(this.createdClientId);
} else { } else {
// Fallback: create client now (shouldn't happen in normal flow) // Fallback: create client now (shouldn't happen in normal flow)
if (!this.clientGeneralStep?.contactVerified) {
this.validationError = 'Verify the OTP sent to both the mobile number and email address before submitting.';
this.selectedTabIndex = 0;
return;
}
const locale = this.settingsService.language.code; const locale = this.settingsService.language.code;
const dateFormat = this.settingsService.dateFormat; const dateFormat = this.settingsService.dateFormat;
const clientData = { const clientData = {
...this.client, ...this.client,
dateFormat, dateFormat,
locale locale,
mobileNewOtpId: this.clientGeneralStep?.mobileNewOtpId,
emailNewOtpId: this.clientGeneralStep?.emailNewOtpId
}; };
if (this.clientTemplate.datatables && this.clientTemplate.datatables.length > 0) { if (this.clientTemplate.datatables && this.clientTemplate.datatables.length > 0) {
@@ -0,0 +1,76 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<div class="cotp-block" [class.cotp-block--verified]="verified">
<div class="cotp-block__header">
<span class="cotp-block__label">{{ label }}</span>
<span class="cotp-block__target">{{ maskedDestination }}</span>
</div>
@if (verified) {
<div class="cotp-block__verified">
<fa-icon icon="check-circle"></fa-icon>
<span>Verified</span>
</div>
} @else if (!otpSent) {
<button type="button" class="cotp-btn cotp-btn--primary" (click)="sendOtp()" [disabled]="sending || !destination">
@if (sending) {
<mat-progress-spinner diameter="16" mode="indeterminate"></mat-progress-spinner>
<span>Sending…</span>
} @else {
<fa-icon icon="paper-plane"></fa-icon>
<span>Send OTP</span>
}
</button>
} @else {
<div class="cotp-otp">
@for (i of digitIndexes; track i) {
<input
#digitBox
type="text"
inputmode="numeric"
maxlength="1"
class="cotp-otp__box"
[value]="digitControls[i].value"
[attr.autocomplete]="i === 0 ? 'one-time-code' : 'off'"
(input)="onDigitInput(i, $any($event.target).value)"
(keydown)="onDigitKeydown(i, $event)"
(paste)="onDigitPaste($event)"
/>
}
</div>
<div class="cotp-block__actions">
<button
type="button"
class="cotp-btn cotp-btn--primary"
(click)="verifyOtp()"
[disabled]="!codeValid || verifying"
>
@if (verifying) {
<mat-progress-spinner diameter="16" mode="indeterminate"></mat-progress-spinner>
<span>Verifying…</span>
} @else {
<fa-icon icon="check-circle"></fa-icon>
<span>Verify</span>
}
</button>
<button type="button" class="cotp-btn cotp-btn--ghost" (click)="resendOtp()" [disabled]="resendCountdown > 0">
<fa-icon icon="redo"></fa-icon>
<span>{{ resendCountdown > 0 ? 'Resend (' + resendCountdown + 's)' : 'Resend OTP' }}</span>
</button>
</div>
}
@if (errorMessage) {
<div class="cotp-error">
<fa-icon icon="exclamation-circle"></fa-icon>
{{ errorMessage }}
</div>
}
</div>
@@ -0,0 +1,177 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* Card with 6 individually-bordered digit boxes (not the single-input/background-gradient
* trick used elsewhere in this app) — each box is its own <input>, so focus/border state is
* per-digit rather than shared across the whole code. */
:host {
display: block;
}
.cotp-block {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
padding: 28px 24px;
border: 1px solid #e7ecf3;
border-radius: 18px;
background: #fff;
box-shadow: 0 8px 24px -8px rgb(15 23 42 / 10%);
text-align: center;
&--verified {
border-color: #86efac;
background: #f7fdf9;
}
}
.cotp-block__header {
display: flex;
flex-direction: column;
gap: 6px;
}
.cotp-block__label {
font-size: 15px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.4px;
color: #1e293b;
}
.cotp-block__target {
font-size: 15px;
font-weight: 700;
color: #1074b9;
word-break: break-all;
}
.cotp-block__verified {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 16px;
border-radius: 999px;
background: #dcfce7;
color: #15803d;
font-size: 13px;
font-weight: 700;
}
.cotp-block__actions {
display: flex;
justify-content: center;
gap: 12px;
width: 100%;
}
.cotp-otp {
display: flex;
justify-content: center;
gap: 10px;
}
.cotp-otp__box {
box-sizing: border-box;
width: 46px;
height: 52px;
border: 1.5px solid #dde3ec;
border-radius: 12px;
background: #fff;
color: #0f172a;
font-family: 'SF Mono', 'Cascadia Code', Consolas, monospace;
font-size: 22px;
font-weight: 700;
text-align: center;
caret-color: #1074b9;
outline: none;
transition:
border-color 0.15s,
box-shadow 0.15s;
&:hover {
border-color: #b7c2d0;
}
&:focus {
border-color: #1074b9;
box-shadow: 0 0 0 3px rgb(16 116 185 / 15%);
}
}
.cotp-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
flex: 1 1 0;
height: 48px;
padding: 0 20px;
border-radius: 999px;
font-size: 14px;
font-weight: 700;
cursor: pointer;
border: 1.5px solid transparent;
transition:
background 0.15s,
border-color 0.15s,
color 0.15s,
opacity 0.15s;
&:disabled {
cursor: not-allowed;
opacity: 0.55;
}
&--primary {
background: #1074b9;
color: #fff;
box-shadow: 0 6px 16px -4px rgb(16 116 185 / 45%);
&:hover:not(:disabled) {
background: #0d5f96;
}
}
&--ghost {
background: #fff;
color: #1074b9;
border-color: #cfe0ee;
&:hover:not(:disabled) {
border-color: #1074b9;
background: #f0f7fc;
}
}
mat-progress-spinner ::ng-deep circle {
stroke: currentcolor !important;
}
}
.cotp-error {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 14px;
border-radius: 10px;
background: #fef2f2;
border: 1px solid #fecaca;
color: #b91c1c;
font-size: 12.5px;
}
@media (width <= 420px) {
.cotp-otp__box {
width: 38px;
height: 46px;
font-size: 18px;
}
}
@@ -0,0 +1,307 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/** Angular Imports */
import {
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Output,
QueryList,
SimpleChanges,
ViewChildren,
inject
} from '@angular/core';
import { UntypedFormControl } from '@angular/forms';
import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
/** Custom Services */
import { ClientsService } from '../../clients.service';
/** Emitted every time this block's verification result changes — including a reset back
* to `{ otpId: null, verified: false }` when the destination it was verifying no longer
* matches (e.g. staff kept editing the mobile number after verifying an earlier value). */
export interface ContactOtpState {
otpId: number | null;
verified: boolean;
}
/**
* Small presentational OTP-entry block reused up to four times inside the Edit Client
* "Verify Contact Change" panel (old mobile / new mobile / old email / new email — see
* `EditClientComponent`), and once each for mobile/email in the Create Client flow (see
* `ClientGeneralStepComponent`). Renders as 6 individually-bordered digit boxes (one real
* `<input>` each, auto-advancing focus) rather than the single-input/background-gradient trick
* used elsewhere in this app — each box needs its own focus/border state, which a shared input
* can't express.
*/
@Component({
selector: 'mifosx-client-contact-otp-block',
templateUrl: './contact-otp-block.component.html',
styleUrls: ['./contact-otp-block.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
FaIconComponent,
MatProgressSpinner
]
})
export class ContactOtpBlockComponent implements OnChanges, OnDestroy {
private clientsService = inject(ClientsService);
/** The 6 individual digit-box <input> elements, in order — used to move focus between them. */
@ViewChildren('digitBox') digitBoxes: QueryList<ElementRef<HTMLInputElement>>;
/** One independent control per box — NOT a single 6-char string sliced up. Editing box 0
* can never disturb box 3's value this way. (An earlier version kept one shared string and
* rebuilt it via `chars.join('')` on every keystroke — `['', '2', '3'].join('') === '23'`
* silently drops empty slots instead of preserving them as gaps, so deleting an early digit
* collapsed/shifted every digit after it. Per-box controls sidestep that class of bug
* entirely — there's no string to rebuild until the moment we actually submit.) */
readonly digitControls: UntypedFormControl[] = Array.from({ length: 6 }, () => new UntypedFormControl(''));
/** Fixed-length array so the template can `*ngFor` over exactly 6 boxes. */
readonly digitIndexes = [
0,
1,
2,
3,
4,
5
];
/** Client whose mobileNo/emailAddress is being changed. Omit this input entirely for the
* CLIENT CREATION flow — there is no client id yet, so the block falls back to the
* clientId-less creation-time OTP endpoints (`ClientsService.sendClientCreationContactOtp()` /
* `verifyClientCreationContactOtp()`) instead of the edit-flow `/clients/{clientId}/...` ones. */
@Input() clientId?: string;
/** Which LincPay OTP channel to use. */
@Input() channel: 'MOBILE' | 'EMAIL';
/** Raw destination (old or new mobile number / email address) this block verifies. */
@Input() destination = '';
/** Display label, e.g. "Old Mobile Number" / "New Email Address". */
@Input() label = '';
/** Fires whenever `{ otpId, verified }` changes — including resets. */
@Output() stateChange = new EventEmitter<ContactOtpState>();
otpId: number | null = null;
otpSent = false;
verified = false;
sending = false;
verifying = false;
errorMessage = '';
resendCountdown = 0;
private resendTimer: ReturnType<typeof setInterval> | null = null;
/** The full 6-digit code, assembled fresh from the 6 independent box controls only when
* actually needed (display never needs this — each box renders its own control's value). */
get code(): string {
return this.digitControls.map((c) => c.value || '').join('');
}
get codeValid(): boolean {
return /^\d{6}$/.test(this.code);
}
ngOnChanges(changes: SimpleChanges): void {
// If the value being verified changes after the fact (staff kept typing), any
// previously-sent/verified OTP no longer applies to the current destination.
if (changes['destination'] && !changes['destination'].firstChange && this.otpSent) {
this.resetState();
}
}
ngOnDestroy(): void {
if (this.resendTimer) {
clearInterval(this.resendTimer);
}
}
/** Masks the destination so only a few characters are visible, mirroring the masking
* convention already used on the login 2FA screen (`maskTarget()`). */
get maskedDestination(): string {
const value = this.destination || '';
if (!value) {
return '';
}
if (this.channel === 'MOBILE') {
const digits = value.replace(/\D/g, '');
if (digits.length <= 4) {
return value;
}
return 'X'.repeat(digits.length - 4) + digits.slice(-4);
}
const at = value.indexOf('@');
if (at <= 0) {
return value;
}
const local = value.substring(0, at);
const domain = value.substring(at);
const visible = local.substring(0, Math.min(2, local.length));
const hidden = 'X'.repeat(Math.max(0, local.length - visible.length));
return visible + hidden + domain;
}
sendOtp(): void {
if (!this.destination || this.sending) {
return;
}
this.sending = true;
this.errorMessage = '';
const request$ = this.clientId
? this.clientsService.sendClientContactOtp(this.clientId, this.channel, this.destination)
: this.clientsService.sendClientCreationContactOtp(this.channel, this.destination);
request$.subscribe({
next: (res: any) => {
this.sending = false;
this.otpId = res?.otpId ?? res?.resourceId ?? null;
this.otpSent = true;
this.clearAllDigits();
this.startResendCountdown();
// The 6 digit boxes only render once otpSent flips true — defer the focus call to the
// next tick so they exist in the DOM (and in `digitBoxes`) by the time it runs.
setTimeout(() => this.focusBox(0));
if (this.otpId == null) {
this.errorMessage = 'OTP sent, but no reference id was returned. Please contact support.';
}
},
error: (err: any) => {
this.sending = false;
this.errorMessage = err?.error?.defaultUserMessage || err?.error?.message || 'Could not send OTP.';
}
});
}
/** Typing a digit in box `index`: this box's own control gets exactly that digit — every
* other box's control is untouched, so there's nothing to shift or collapse. Moves focus to
* the next box unless this was the last one. */
onDigitInput(index: number, rawValue: string): void {
const digit = (rawValue || '').replace(/\D/g, '').slice(-1);
this.digitControls[index].setValue(digit);
if (digit && index < 5) {
this.focusBox(index + 1);
}
}
/** Backspace in an empty box clears the PREVIOUS box and moves focus there, matching the
* usual "segmented OTP input" keyboard feel — again, only ever touching one control at a
* time. Arrow keys move focus without altering any box's value. */
onDigitKeydown(index: number, event: KeyboardEvent): void {
if (event.key === 'Backspace') {
if (!this.digitControls[index].value && index > 0) {
this.digitControls[index - 1].setValue('');
this.focusBox(index - 1);
event.preventDefault();
}
return;
}
if (event.key === 'ArrowLeft' && index > 0) {
this.focusBox(index - 1);
event.preventDefault();
} else if (event.key === 'ArrowRight' && index < 5) {
this.focusBox(index + 1);
event.preventDefault();
}
}
/** Pasting a full code into any box fills all 6 boxes at once (one control per digit) and
* focuses the last filled one. */
onDigitPaste(event: ClipboardEvent): void {
const pasted = event.clipboardData?.getData('text') || '';
const digits = pasted.replace(/\D/g, '').slice(0, 6);
if (!digits) {
return;
}
event.preventDefault();
digits.split('').forEach((d, i) => this.digitControls[i].setValue(d));
for (let i = digits.length; i < 6; i++) {
this.digitControls[i].setValue('');
}
this.focusBox(Math.min(digits.length, 6) - 1);
}
private clearAllDigits(): void {
this.digitControls.forEach((c) => c.setValue(''));
}
private focusBox(index: number): void {
const box = this.digitBoxes?.toArray()[index];
box?.nativeElement.focus();
}
resendOtp(): void {
if (this.resendCountdown > 0 || this.sending) {
return;
}
this.sendOtp();
}
verifyOtp(): void {
if (this.otpId == null || !this.codeValid || this.verifying) {
this.digitControls.forEach((c) => c.markAsTouched());
return;
}
this.verifying = true;
this.errorMessage = '';
const request$ = this.clientId
? this.clientsService.verifyClientContactOtp(this.clientId, this.otpId, this.code)
: this.clientsService.verifyClientCreationContactOtp(this.otpId, this.code);
request$.subscribe({
next: (res: any) => {
this.verifying = false;
// Defensive shape-tolerance: treat an explicit `verified: false` as failure,
// anything else (2xx with `verified: true`, or no `verified` field at all) as success.
const ok = res?.verified !== false;
if (ok) {
this.verified = true;
this.stateChange.emit({ otpId: this.otpId, verified: true });
} else {
this.errorMessage = res?.message || 'Incorrect OTP — please try again.';
}
},
error: (err: any) => {
this.verifying = false;
this.errorMessage = err?.error?.defaultUserMessage || err?.error?.message || 'OTP verification failed.';
}
});
}
private resetState(): void {
this.otpId = null;
this.otpSent = false;
this.verified = false;
this.errorMessage = '';
this.clearAllDigits();
if (this.resendTimer) {
clearInterval(this.resendTimer);
this.resendTimer = null;
}
this.resendCountdown = 0;
this.stateChange.emit({ otpId: null, verified: false });
}
private startResendCountdown(): void {
this.resendCountdown = 30;
if (this.resendTimer) {
clearInterval(this.resendTimer);
}
this.resendTimer = setInterval(() => {
this.resendCountdown--;
if (this.resendCountdown <= 0 && this.resendTimer) {
clearInterval(this.resendTimer);
this.resendTimer = null;
}
}, 1000);
}
}
@@ -25,9 +25,22 @@
{{ 'labels.inputs.GENERAL' | translate }} {{ 'labels.inputs.GENERAL' | translate }}
</ng-template> </ng-template>
<div class="tab-content" [class.tab-content--readonly]="isTabReadOnly(0)"> <div class="tab-content" [class.tab-content--readonly]="isTabReadOnly(0)">
@if (hasPendingGeneralEdit) {
<div class="pending-edit-banner">
<mat-icon>hourglass_top</mat-icon>
<span
>An edit is awaiting approval from another user. You can't submit another edit until it's resolved.</span
>
</div>
}
<div class="tab-mode-bar"> <div class="tab-mode-bar">
@if (isTabReadOnly(0)) { @if (isTabReadOnly(0)) {
<button mat-flat-button class="tab-mode-btn tab-mode-btn--edit" (click)="enableTabEdit(0)"> <button
mat-flat-button
class="tab-mode-btn tab-mode-btn--edit"
[disabled]="hasPendingGeneralEdit"
(click)="enableTabEdit(0)"
>
<mat-icon>edit</mat-icon> Edit <mat-icon>edit</mat-icon> Edit
</button> </button>
} @else { } @else {
@@ -42,6 +55,79 @@
[readOnly]="isTabReadOnly(0)" [readOnly]="isTabReadOnly(0)"
(legalFormChangeEvent)="legalFormChange($event)" (legalFormChangeEvent)="legalFormChange($event)"
></mifosx-client-general-step> ></mifosx-client-general-step>
<!-- Dual-OTP contact-change verification panel — appears only once the mobile
number and/or email address differ from the loaded snapshot. Save stays
gated (see currentStepValid) until every required block below is verified. -->
@if (!isTabReadOnly(0) && (contactChanges.mobileChanged || contactChanges.emailChanged)) {
<div class="contact-verify-panel">
<div class="contact-verify-panel__header">
<mat-icon>verified_user</mat-icon>
<div class="contact-verify-panel__header-text">
<strong>Verify Contact Change</strong>
<span
>An OTP must be verified on both the old and new
{{
contactChanges.mobileChanged && contactChanges.emailChanged
? 'mobile number and email address'
: contactChanges.mobileChanged
? 'mobile number'
: 'email address'
}}
before this change can be saved.</span
>
</div>
</div>
@if (contactChanges.mobileChanged) {
<div class="contact-verify-panel__field-group">
<div class="contact-verify-panel__field-title">
<mat-icon>phone_iphone</mat-icon>
<span>Mobile Number</span>
</div>
<div class="contact-verify-panel__grid">
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="MOBILE"
[destination]="contactChanges.oldMobile"
label="Old Mobile Number"
(stateChange)="onOldMobileOtpState($event)"
></mifosx-client-contact-otp-block>
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="MOBILE"
[destination]="contactChanges.newMobile"
label="New Mobile Number"
(stateChange)="onNewMobileOtpState($event)"
></mifosx-client-contact-otp-block>
</div>
</div>
}
@if (contactChanges.emailChanged) {
<div class="contact-verify-panel__field-group">
<div class="contact-verify-panel__field-title">
<mat-icon>email</mat-icon>
<span>Email Address</span>
</div>
<div class="contact-verify-panel__grid">
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="EMAIL"
[destination]="contactChanges.oldEmail"
label="Old Email Address"
(stateChange)="onOldEmailOtpState($event)"
></mifosx-client-contact-otp-block>
<mifosx-client-contact-otp-block
[clientId]="clientId"
channel="EMAIL"
[destination]="contactChanges.newEmail"
label="New Email Address"
(stateChange)="onNewEmailOtpState($event)"
></mifosx-client-contact-otp-block>
</div>
</div>
}
</div>
}
</div> </div>
</mat-tab> </mat-tab>
@@ -76,8 +162,10 @@
<mifosx-client-kyc-step <mifosx-client-kyc-step
#clientKyc #clientKyc
[isNonIndividual]="legalFormType === 2" [isNonIndividual]="legalFormType === 2"
[isMinor]="clientGeneralStep?.isMinor || false"
[clientId]="clientId" [clientId]="clientId"
[readOnly]="isTabReadOnly(1)" [readOnly]="isTabReadOnly(1)"
[calculatedRisk]="clientGeneralStep?.calculatedRisk"
></mifosx-client-kyc-step> ></mifosx-client-kyc-step>
</div> </div>
</div> </div>
@@ -133,6 +221,8 @@
<mifosx-client-india-address-step <mifosx-client-india-address-step
#clientIndiaAddress #clientIndiaAddress
[clientId]="clientId" [clientId]="clientId"
[isMinor]="clientGeneralStep?.isMinor || false"
[isNonIndividual]="legalFormType === 2"
[readOnly]="isTabReadOnly(addressTabIdx)" [readOnly]="isTabReadOnly(addressTabIdx)"
></mifosx-client-india-address-step> ></mifosx-client-india-address-step>
</div> </div>
@@ -150,6 +150,93 @@
border: 1px solid #fca5a5 !important; border: 1px solid #fca5a5 !important;
} }
/* ─── Dual-OTP "Verify Contact Change" panel ─── */
.contact-verify-panel {
margin-top: 20px;
padding: 16px 18px;
border: 1px solid #bfdbfe;
border-radius: 8px;
background: #eff6ff;
&__header {
display: flex;
align-items: flex-start;
gap: 12px;
margin-bottom: 14px;
color: #1074b9;
mat-icon {
margin-top: 1px;
flex-shrink: 0;
}
}
&__header-text {
display: flex;
flex-direction: column;
gap: 2px;
font-size: 13.5px;
line-height: 1.5;
color: #1e3a5f;
strong {
font-size: 14px;
font-weight: 700;
}
}
&__field-group {
&:not(:last-child) {
margin-bottom: 18px;
padding-bottom: 18px;
border-bottom: 1px dashed #bfdbfe;
}
}
&__field-title {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 8px;
font-size: 13px;
font-weight: 700;
color: #1e3a5f;
mat-icon {
font-size: 17px;
width: 17px;
height: 17px;
color: #1074b9;
}
}
&__grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
}
}
/* ─── Pending Edit Approval Banner ─── */
.pending-edit-banner {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 16px;
margin: 0 0 16px;
background: #eff6ff;
border: 1px solid #93c5fd;
border-radius: 8px;
color: #1e40af;
font-size: 13px;
font-weight: 500;
mat-icon {
color: #2563eb;
flex-shrink: 0;
}
}
/* ─── Re-KYC Alert Banner ─── */ /* ─── Re-KYC Alert Banner ─── */
.rekyc-alert { .rekyc-alert {
display: flex; display: flex;
@@ -10,6 +10,7 @@
import { Component, QueryList, ViewChild, ViewChildren, inject } from '@angular/core'; import { Component, QueryList, ViewChild, ViewChildren, inject } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'; import { Router, ActivatedRoute } from '@angular/router';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Observable, of } from 'rxjs'; import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators'; import { map } from 'rxjs/operators';
@@ -28,6 +29,7 @@ import { ClientDatatableStepComponent } from '../client-stepper/client-datatable
import { ClientKycStepComponent } from '../client-stepper/client-kyc-step/client-kyc-step.component'; import { ClientKycStepComponent } from '../client-stepper/client-kyc-step/client-kyc-step.component';
import { ClientPreviewStepComponent } from '../client-stepper/client-preview-step/client-preview-step.component'; import { ClientPreviewStepComponent } from '../client-stepper/client-preview-step/client-preview-step.component';
import { ClientFamilyMembersStepComponent } from '../client-stepper/client-family-members-step/client-family-members-step.component'; import { ClientFamilyMembersStepComponent } from '../client-stepper/client-family-members-step/client-family-members-step.component';
import { ContactOtpBlockComponent, ContactOtpState } from './contact-otp-block/contact-otp-block.component';
import { MatTabsModule } from '@angular/material/tabs'; import { MatTabsModule } from '@angular/material/tabs';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
@@ -36,6 +38,7 @@ import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import { MatProgressSpinner } from '@angular/material/progress-spinner'; import { MatProgressSpinner } from '@angular/material/progress-spinner';
import { MatTooltip } from '@angular/material/tooltip'; import { MatTooltip } from '@angular/material/tooltip';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module'; import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { ORIGINAL_VALUES_PAYLOAD_KEY, buildOriginalValuesSnapshot } from '../shared/client-edit-diff.util';
/** /**
* Edit Client Component — uses the same wizard/stepper layout as Create Client. * Edit Client Component — uses the same wizard/stepper layout as Create Client.
@@ -59,7 +62,8 @@ import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
ClientDatatableStepComponent, ClientDatatableStepComponent,
ClientKycStepComponent, ClientKycStepComponent,
ClientPreviewStepComponent, ClientPreviewStepComponent,
ClientFamilyMembersStepComponent ClientFamilyMembersStepComponent,
ContactOtpBlockComponent
] ]
}) })
export class EditClientComponent { export class EditClientComponent {
@@ -68,6 +72,7 @@ export class EditClientComponent {
private dialog = inject(MatDialog); private dialog = inject(MatDialog);
private clientsService = inject(ClientsService); private clientsService = inject(ClientsService);
private settingsService = inject(SettingsService); private settingsService = inject(SettingsService);
private snackBar = inject(MatSnackBar);
@ViewChild(ClientGeneralStepComponent) clientGeneralStep: ClientGeneralStepComponent; @ViewChild(ClientGeneralStepComponent) clientGeneralStep: ClientGeneralStepComponent;
@ViewChild('clientAddress') clientAddressStep: ClientAddressStepComponent; @ViewChild('clientAddress') clientAddressStep: ClientAddressStepComponent;
@@ -88,10 +93,33 @@ export class EditClientComponent {
/** Flag: DOB was changed — requires re-KYC (PAN re-verification) */ /** Flag: DOB was changed — requires re-KYC (PAN re-verification) */
dobChanged = false; dobChanged = false;
/**
* Dual-OTP contact-change verification state (mobileNo / emailAddress). Mirrors the
* name/DOB "detect change against snapshot, gate the save" pattern already established
* in this component (see `detectSensitiveFieldChanges()` / `flagReKycRequired()`) —
* extended here so a changed mobile/email must be OTP-verified on BOTH the old and new
* destination before Save is allowed. Payload param names sent to the backend PUT are
* `mobileOldOtpId` / `mobileNewOtpId` / `emailOldOtpId` / `emailNewOtpId` (added onto
* `clientData` in `saveCurrentTab()`'s General-tab branch) — kept per-field rather than
* one generic old/new pair so mobile AND email can both be changed (and independently
* OTP-verified) in a single save.
*/
oldMobileOtpId: number | null = null;
newMobileOtpId: number | null = null;
oldMobileVerified = false;
newMobileVerified = false;
oldEmailOtpId: number | null = null;
newEmailOtpId: number | null = null;
oldEmailVerified = false;
newEmailVerified = false;
/** Client data and template (merged object from resolver) */ /** Client data and template (merged object from resolver) */
clientDataAndTemplate: any; clientDataAndTemplate: any;
/** Client ID */ /** Client ID */
clientId: string; clientId: string;
/** True while a General-tab edit is staged awaiting checker approval — blocks submitting
* another one (the backend enforces this too; this just avoids a round-trip error toast). */
hasPendingGeneralEdit = false;
constructor() { constructor() {
this.route.data.subscribe((data: { clientDataAndTemplate: any }) => { this.route.data.subscribe((data: { clientDataAndTemplate: any }) => {
@@ -100,6 +128,15 @@ export class EditClientComponent {
if (this.clientDataAndTemplate.legalForm) { if (this.clientDataAndTemplate.legalForm) {
this.legalFormType = this.clientDataAndTemplate.legalForm.id; this.legalFormType = this.clientDataAndTemplate.legalForm.id;
} }
this.loadPendingGeneralEdit();
});
}
private loadPendingGeneralEdit(): void {
if (!this.clientId) return;
this.clientsService.getPendingClientEdit(this.clientId).subscribe({
next: (edit: any) => (this.hasPendingGeneralEdit = !!edit && edit.status === 'PENDING'),
error: () => (this.hasPendingGeneralEdit = false)
}); });
} }
@@ -168,6 +205,61 @@ export class EditClientComponent {
return { ...general }; return { ...general };
} }
/**
* Live view of `detectSensitiveFieldChanges()` against the loaded snapshot — drives the
* "Verify Contact Change" OTP panel in the General tab template. Re-evaluated on every
* change-detection pass (cheap: a handful of form-control reads), so the panel appears/
* disappears as the user types, same as the existing re-KYC name/DOB detection.
*/
get contactChanges() {
return this.detectSensitiveFieldChanges(this.clientDataAndTemplate);
}
/** Whether every OTP block required by the fields that actually changed has been verified. */
get contactVerificationComplete(): boolean {
const changes = this.contactChanges;
if (changes.mobileChanged && !(this.oldMobileVerified && this.newMobileVerified)) {
return false;
}
if (changes.emailChanged && !(this.oldEmailVerified && this.newEmailVerified)) {
return false;
}
return true;
}
onOldMobileOtpState(state: ContactOtpState): void {
this.oldMobileOtpId = state.otpId;
this.oldMobileVerified = state.verified;
}
onNewMobileOtpState(state: ContactOtpState): void {
this.newMobileOtpId = state.otpId;
this.newMobileVerified = state.verified;
}
onOldEmailOtpState(state: ContactOtpState): void {
this.oldEmailOtpId = state.otpId;
this.oldEmailVerified = state.verified;
}
onNewEmailOtpState(state: ContactOtpState): void {
this.newEmailOtpId = state.otpId;
this.newEmailVerified = state.verified;
}
/** Reset all dual-OTP state — called once a General-tab save succeeds (the snapshot is
* updated to match, so the "Verify Contact Change" panel naturally disappears too). */
private resetContactVerificationState(): void {
this.oldMobileOtpId = null;
this.newMobileOtpId = null;
this.oldMobileVerified = false;
this.newMobileVerified = false;
this.oldEmailOtpId = null;
this.newEmailOtpId = null;
this.oldEmailVerified = false;
this.newEmailVerified = false;
}
areFormvalids(): boolean { areFormvalids(): boolean {
if (!this.clientGeneralStep || !this.clientGeneralForm) { if (!this.clientGeneralStep || !this.clientGeneralForm) {
return false; return false;
@@ -196,7 +288,10 @@ export class EditClientComponent {
if (idx === 0) { if (idx === 0) {
if (!this.clientGeneralStep || !this.clientGeneralForm) return false; if (!this.clientGeneralStep || !this.clientGeneralForm) return false;
if (this.clientGeneralStep.sanctionsBlocked) return false; if (this.clientGeneralStep.sanctionsBlocked) return false;
return this.clientGeneralForm.valid; if (!this.clientGeneralForm.valid) return false;
// Dual-OTP gate: a changed mobile/email must be verified on both old & new
// destinations before Save is allowed — mirrors the re-KYC gate below it.
return this.contactVerificationComplete;
} }
if (idx === 1) { if (idx === 1) {
const kf = this.clientKycStep?.kycForm; const kf = this.clientKycStep?.kycForm;
@@ -205,14 +300,20 @@ export class EditClientComponent {
if (this.legalFormType === 2) { if (this.legalFormType === 2) {
if (idx === 2) return true; // Scheme & Sector — opt-in if (idx === 2) return true; // Scheme & Sector — opt-in
if (idx === 3) return this.isAddressStepValid(); if (idx === 3) return this.isAddressStepValid();
if (idx === 4) return true; // Family — optional if (idx === 4) return true; // Family — not applicable to non-individual entities
} else { } else {
if (idx === 2) return this.isAddressStepValid(); if (idx === 2) return this.isAddressStepValid();
if (idx === 3) return true; // Family — optional if (idx === 3) return this.isFamilyStepValid(); // Mother required, plus Father or a Caretaker
} }
return true; return true;
} }
/** Mother is required, and either Father or a Caretaker, for individual clients. */
private isFamilyStepValid(): boolean {
const step = this.clientFamilyMembersStep;
return !step || step.familyRelationshipRulesMet;
}
private isAddressStepValid(): boolean { private isAddressStepValid(): boolean {
const step = this.clientIndiaAddressStep; const step = this.clientIndiaAddressStep;
if (!step) return true; if (!step) return true;
@@ -227,6 +328,21 @@ export class EditClientComponent {
if (this.selectedTabIndex === 0 && this.clientGeneralStep?.sanctionsBlocked) { if (this.selectedTabIndex === 0 && this.clientGeneralStep?.sanctionsBlocked) {
return 'Client failed sanctions screening — cannot proceed.'; return 'Client failed sanctions screening — cannot proceed.';
} }
if (this.selectedTabIndex === 0 && this.clientGeneralForm?.valid && !this.contactVerificationComplete) {
return 'Verify the OTP sent to both the old and new mobile number/email before saving.';
}
if (this.selectedTabIndex === 1) {
const labels = this.clientKycStep?.invalidFieldLabels || [];
if (labels.length) {
return `Please fill/correct: ${labels.join(', ')}.`;
}
}
const familyTabIndex = this.legalFormType === 2 ? 4 : 3;
if (this.selectedTabIndex === familyTabIndex && this.legalFormType !== 2 && this.clientFamilyMembersStep) {
const step = this.clientFamilyMembersStep;
if (!step.hasMother) return 'Mother is required as a family member.';
if (!step.hasFather && !step.hasCaretaker) return 'Either Father or a Caretaker is required as a family member.';
}
return 'Please fill all mandatory fields on this tab to continue.'; return 'Please fill all mandatory fields on this tab to continue.';
} }
@@ -272,6 +388,16 @@ export class EditClientComponent {
// Check if name or DOB changed on the General tab — warn about re-KYC // Check if name or DOB changed on the General tab — warn about re-KYC
if (this.selectedTabIndex === 0) { if (this.selectedTabIndex === 0) {
const changes = this.detectSensitiveFieldChanges(this.clientDataAndTemplate); const changes = this.detectSensitiveFieldChanges(this.clientDataAndTemplate);
// Dual-OTP gate — defensive re-check. The "Save & Next" button is already disabled
// via `currentStepValid` while this is incomplete, but don't rely on that alone.
if (!this.contactVerificationComplete) {
this.snackBar.open('Verify the OTP sent to both the old and new mobile number/email before saving.', 'Close', {
duration: 5000
});
return;
}
if (changes.nameChanged || changes.dobChanged) { if (changes.nameChanged || changes.dobChanged) {
heading = 'Re-KYC Required'; heading = 'Re-KYC Required';
dialogContext = dialogContext =
@@ -308,39 +434,65 @@ export class EditClientComponent {
const originalData = this.clientDataAndTemplate; const originalData = this.clientDataAndTemplate;
const changedFields = this.detectSensitiveFieldChanges(originalData); const changedFields = this.detectSensitiveFieldChanges(originalData);
// Dual-OTP verified ids — sent only for the field(s) that actually changed, per-field
// (not a single generic old/new pair) so the backend can tell mobile's OTPs apart from
// email's when BOTH changed in the same save. See the class-level JSDoc above the OTP
// state fields for the full naming rationale.
if (changedFields.mobileChanged) {
clientData.mobileOldOtpId = this.oldMobileOtpId;
clientData.mobileNewOtpId = this.newMobileOtpId;
}
if (changedFields.emailChanged) {
clientData.emailOldOtpId = this.oldEmailOtpId;
clientData.emailNewOtpId = this.newEmailOtpId;
}
// Point-in-time "before" snapshot for the checker's diff view — captured now, from the
// client record loaded when this edit page opened, rather than relying on comparing against
// the LIVE client later (which would show nothing changed once a checker approves the edit,
// since by then current == proposed).
clientData[ORIGINAL_VALUES_PAYLOAD_KEY] = buildOriginalValuesSnapshot(originalData);
this.savingClient = true; this.savingClient = true;
this.clientsService.updateClient(this.clientId, clientData).subscribe({ // Maker-checker: stage the edit instead of applying it immediately. The customer-facing
// side effects that a direct update would have had immediately — SMS/Email contact-change
// notification, re-KYC flagging, PAN re-verification reset — are all deferred until a
// different user actually approves the edit (approval replays this exact payload through
// the same updateClient() the direct PUT used to call, so the backend-driven notification
// still fires correctly, just at approval time instead of now).
this.clientsService.submitClientEdit(this.clientId, clientData).subscribe({
next: () => { next: () => {
this.savingClient = false; this.savingClient = false;
this.tabEditMode[tabIndex] = false; this.tabEditMode[tabIndex] = false;
this.hasPendingGeneralEdit = true;
// Log mobile/email changes as client notes for risk audit // Senior Citizen / PWD supporting documents — separate upload endpoints, not part of
this.logFieldChangeNotes(changedFields); // the staged JSON edit, so these still apply immediately as before.
if (this.clientGeneralStep?.seniorCitizenProofFile) {
// If name or DOB changed, flag re-KYC requirement and reset PAN verification const seniorCitizenProofForm = new FormData();
if (changedFields.nameChanged || changedFields.dobChanged) { seniorCitizenProofForm.append('file', this.clientGeneralStep.seniorCitizenProofFile);
this.dobChanged = true; seniorCitizenProofForm.append('name', 'seniorCitizenProof');
this.tabEditMode[1] = true; // auto-enable KYC tab for re-verification seniorCitizenProofForm.append('description', 'Senior Citizen Proof (Age/ID Proof)');
this.flagReKycRequired(changedFields); this.clientsService
.uploadClientDocument(this.clientId, seniorCitizenProofForm)
.subscribe({ error: () => {} });
}
if (this.clientGeneralStep?.pwdCertificateFile) {
const pwdCertificateForm = new FormData();
pwdCertificateForm.append('file', this.clientGeneralStep.pwdCertificateFile);
pwdCertificateForm.append('name', 'pwdCertificate');
pwdCertificateForm.append('description', 'Disability Certificate');
this.clientsService.uploadClientDocument(this.clientId, pwdCertificateForm).subscribe({ error: () => {} });
} }
// Update original data snapshot so subsequent edits compare against latest this.snackBar.open(
if (changedFields.mobileChanged) { 'Edit submitted for approval — a different user must review it before it takes effect.',
originalData.mobileNo = changedFields.newMobile; 'Close',
} {
if (changedFields.emailChanged) { duration: 5000
originalData.emailAddress = changedFields.newEmail; }
} );
if (changedFields.dobChanged) { this.resetContactVerificationState();
originalData.dateOfBirth = changedFields.newDob;
}
if (changedFields.nameChanged) {
const form = this.clientGeneralForm;
originalData.firstname = form?.get('firstname')?.value ?? originalData.firstname;
originalData.middlename = form?.get('middlename')?.value ?? originalData.middlename;
originalData.lastname = form?.get('lastname')?.value ?? originalData.lastname;
originalData.fullname = form?.get('fullname')?.value ?? originalData.fullname;
}
this.selectedTabIndex = this.selectedTabIndex + 1; this.selectedTabIndex = this.selectedTabIndex + 1;
}, },
@@ -430,12 +582,14 @@ export class EditClientComponent {
return; return;
} }
// Address tab // Address tab — no OTP gate (an address has no "old/new channel" to verify an OTP
// against); notification-only, per the plan. Save proceeds normally.
const addressTabIdx = this.legalFormType === 2 ? 3 : 2; const addressTabIdx = this.legalFormType === 2 ? 3 : 2;
if (tabIndex === addressTabIdx) { if (tabIndex === addressTabIdx) {
this.savingClient = true; this.savingClient = true;
if (this.clientIndiaAddressStep?.hasAddressData) { if (this.clientIndiaAddressStep?.hasAddressData) {
this.saveClientAddresses(this.clientId); this.saveClientAddresses(this.clientId);
this.snackBar.open('Customer notified via SMS/Email of the address change.', 'Close', { duration: 4000 });
} }
this.savingClient = false; this.savingClient = false;
this.tabEditMode[tabIndex] = false; this.tabEditMode[tabIndex] = false;
@@ -465,20 +619,41 @@ export class EditClientComponent {
/** /**
* Compare current form values with original data to detect changes in name, DOB, mobile, email. * Compare current form values with original data to detect changes in name, DOB, mobile, email.
*/ */
/** "YYYY-MM-DD" built from a Date's LOCAL components — see the timezone-safety note where
* this is called from `detectSensitiveFieldChanges()`. */
private toLocalDateString(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
private detectSensitiveFieldChanges(originalData: any) { private detectSensitiveFieldChanges(originalData: any) {
const form = this.clientGeneralForm; const form = this.clientGeneralForm;
const newMobile = form?.get('mobileNo')?.value || ''; // Trimmed so browser autofill adding invisible leading/trailing whitespace never reads as
const newEmail = form?.get('emailAddress')?.value || ''; // a "change" — the masked preview shown in the Verify Contact Change panel only reveals the
// first couple of characters, so a whitespace-only difference is otherwise invisible to the
// user and just looks like the panel appeared for no reason. These trimmed-but-original-case
// values are what get returned/sent as the actual OTP destination and saved value — only the
// *comparison* (below) is further case-normalized for email, so we never silently rewrite the
// customer's email casing into the saved record or the OTP destination.
const newMobile = (form?.get('mobileNo')?.value || '').trim();
const newEmail = (form?.get('emailAddress')?.value || '').trim();
const newDobRaw = form?.get('dateOfBirth')?.value; const newDobRaw = form?.get('dateOfBirth')?.value;
const newDob = newDobRaw instanceof Date ? newDobRaw.toISOString().split('T')[0] : newDobRaw || ''; // Local calendar date, NOT `.toISOString()` — that converts to UTC first, which silently
// shifts the date by a day in any positive-UTC-offset timezone (e.g. India, UTC+5:30:
// midnight local on the 15th becomes 18:30 UTC on the 14th). That made this comparison
// report a DOB "change" — falsely triggering the Re-KYC dialog — even when the user never
// touched the date field, purely because the Date object round-tripped through the picker.
const newDob = newDobRaw instanceof Date ? this.toLocalDateString(newDobRaw) : newDobRaw || '';
const oldMobile = originalData.mobileNo || ''; const oldMobile = (originalData.mobileNo || '').trim();
const oldEmail = originalData.emailAddress || ''; const oldEmail = (originalData.emailAddress || '').trim();
const oldDobRaw = originalData.dateOfBirth; const oldDobRaw = originalData.dateOfBirth;
const oldDob = Array.isArray(oldDobRaw) const oldDob = Array.isArray(oldDobRaw)
? `${oldDobRaw[0]}-${String(oldDobRaw[1]).padStart(2, '0')}-${String(oldDobRaw[2]).padStart(2, '0')}` ? `${oldDobRaw[0]}-${String(oldDobRaw[1]).padStart(2, '0')}-${String(oldDobRaw[2]).padStart(2, '0')}`
: oldDobRaw instanceof Date : oldDobRaw instanceof Date
? oldDobRaw.toISOString().split('T')[0] ? this.toLocalDateString(oldDobRaw)
: oldDobRaw || ''; : oldDobRaw || '';
const buildName = (parts: { firstname?: string; middlename?: string; lastname?: string; fullname?: string }) => const buildName = (parts: { firstname?: string; middlename?: string; lastname?: string; fullname?: string }) =>
@@ -509,7 +684,9 @@ export class EditClientComponent {
return { return {
nameChanged: newName !== oldName, nameChanged: newName !== oldName,
mobileChanged: newMobile !== oldMobile, mobileChanged: newMobile !== oldMobile,
emailChanged: newEmail !== oldEmail, // Case-insensitive: emails are not case-sensitive in practice, and comparing raw case
// would flag a change (surfacing the dual-OTP panel) even when nothing meaningful changed.
emailChanged: newEmail.toLowerCase() !== oldEmail.toLowerCase(),
dobChanged: newDob !== oldDob, dobChanged: newDob !== oldDob,
oldName, oldName,
newName, newName,
@@ -0,0 +1,149 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* Shared between the maker side (edit-client, which captures a point-in-time snapshot of the
* client's current values right before staging an edit) and the checker side (pending-client-edits,
* which diffs the staged payload against that snapshot). Keeping both in one place means the two
* sides can never drift out of sync on which fields are captured/compared/labelled.
*
* Extracts a payload key's CURRENT value from a client record (as returned by GET /clients/{id}) —
* CodeValue fields come back as nested {id, name} objects, so most extractors pull the nested .id
* to compare against the payload's raw id.
*/
export const PENDING_EDIT_FIELD_EXTRACTORS: Record<string, (c: any) => any> = {
officeId: (c) => c.officeId,
legalFormId: (c) => c.legalForm?.id,
nationalityId: (c) => c.nationality,
isStaff: (c) => c.isStaff,
active: (c) => c.active,
accountNo: (c) => c.accountNo,
salutationId: (c) => c.salutation?.id,
firstname: (c) => c.firstname,
middlename: (c) => c.middlename,
lastname: (c) => c.lastname,
fullname: (c) => c.fullname,
genderId: (c) => c.gender?.id,
maritalStatusId: (c) => c.maritalStatus?.id,
educationLevelId: (c) => c.educationLevel?.id,
degreeQualificationId: (c) => c.degreeQualification?.id,
religionId: (c) => c.religion?.id,
socialCategoryId: (c) => c.socialCategory?.id,
mobileNo: (c) => c.mobileNo,
alternateMobileNo: (c) => c.alternateMobileNo,
emailAddress: (c) => c.emailAddress,
dateOfBirth: (c) => c.dateOfBirth,
occupationCategoryId: (c) => c.occupationCategory?.id,
occupationId: (c) => c.occupation?.id,
monthlyIncome: (c) => c.monthlyIncome,
annualIncome: (c) => c.annualIncome,
annualTurnover: (c) => c.annualTurnover,
monthlyTurnover: (c) => c.monthlyTurnover,
isPwd: (c) => c.isPwd,
pwdCategoryId: (c) => c.pwdCategory?.id,
isSeniorCitizen: (c) => c.isSeniorCitizen,
agricultureIncome: (c) => c.agricultureIncome,
nonAgricultureIncome: (c) => c.nonAgricultureIncome,
savingsProductId: (c) => c.savingsProductId,
staffId: (c) => c.staffId,
guardianClientId: (c) => c.guardianClientId,
guardianRelation: (c) => c.guardianRelation
};
/** Payload keys that are computed, internal, or otherwise never meaningfully "changed" from a
* checker's point of view — always sent by the form (age breakdown, OTP tracking ids, the
* business-date default on submittedOnDate) but with no comparable "current" value. */
export const NON_COMPARABLE_KEYS = new Set([
'dateFormat',
'locale',
'ageYears',
'ageMonths',
'ageDays',
'isMinor',
'addSavings',
'submittedOnDate',
'activationDate',
// Flattened onto top-level guardianClientId/guardianRelation right after this in the payload —
// that flattened pair already has real comparators above, so the nested group is redundant.
'guardianDetails',
// Mobile/email DIP verification + name-match + sanctions-screening results — carried along on
// every save to re-affirm the client's EXISTING verification state, not something the maker
// edited on this pass. dipTimestamp especially would almost never string-match exactly even
// when functionally unchanged, so these were never real "proposed changes" to review.
'dipVerified',
'dipLookupLogId',
'dipTimestamp',
'alternateDipVerified',
'alternateDipLookupLogId',
'alternateDipTimestamp',
'nameVerified',
'screeningLogId',
'mobileNewOtpId',
'mobileOldOtpId',
'emailNewOtpId',
'emailOldOtpId'
]);
export const PENDING_EDIT_FIELD_LABELS: Record<string, string> = {
officeId: 'Office',
legalFormId: 'Legal Form',
nationalityId: 'Nationality',
isStaff: 'Is Staff',
active: 'Active',
accountNo: 'Account Number',
salutationId: 'Salutation',
firstname: 'First Name',
middlename: 'Middle Name',
lastname: 'Last Name',
fullname: 'Full Name',
genderId: 'Gender',
maritalStatusId: 'Marital Status',
educationLevelId: 'Education Level',
degreeQualificationId: 'Degree / Qualification',
religionId: 'Religion',
socialCategoryId: 'Social Category',
mobileNo: 'Mobile Number',
alternateMobileNo: 'Alternate Mobile Number',
emailAddress: 'Email Address',
dateOfBirth: 'Date of Birth',
occupationCategoryId: 'Occupation Category',
occupationId: 'Occupation',
monthlyIncome: 'Monthly Income',
annualIncome: 'Annual Income',
annualTurnover: 'Yearly Turnover',
monthlyTurnover: 'Monthly Turnover',
isPwd: 'Person with Disability',
pwdCategoryId: 'Disability Type',
isSeniorCitizen: 'Senior Citizen',
agricultureIncome: 'Agriculture Income',
nonAgricultureIncome: 'Non-Agriculture Income',
submittedOnDate: 'Submitted On',
savingsProductId: 'Linked Savings Product',
staffId: 'Staff'
};
/** Key under which the maker's point-in-time "before" snapshot rides along in the submit payload —
* stripped out by the backend before replaying the rest through updateClient(), and stored
* separately as original_json for the checker's diff. Never a real Client field name, so it can't
* collide with anything ClientDataValidator actually expects. */
export const ORIGINAL_VALUES_PAYLOAD_KEY = '_originalValues';
/** Builds the maker-side "before" snapshot from the client record loaded when the edit page
* opened — flat key names matching the payload's own, so the checker side can diff two plain
* objects directly without needing to know Client's nested response shape at all. */
export function buildOriginalValuesSnapshot(clientData: any): Record<string, any> {
const snapshot: Record<string, any> = {};
if (!clientData) return snapshot;
for (const key of Object.keys(PENDING_EDIT_FIELD_EXTRACTORS)) {
const value = PENDING_EDIT_FIELD_EXTRACTORS[key](clientData);
if (value !== undefined) {
snapshot[key] = value;
}
}
return snapshot;
}
@@ -0,0 +1,24 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<h1 mat-dialog-title>{{ data.title || data.fileName || 'Document Preview' }}</h1>
<div mat-dialog-content class="doc-preview-content">
@if (isImage) {
<img [src]="previewUrl" [alt]="data.fileName || 'Document'" class="doc-preview-image" />
} @else if (isPdf) {
<iframe [src]="safeUrl" class="doc-preview-pdf" title="Document preview"></iframe>
} @else {
<p>Preview isn't available for this file type — use Download to view it.</p>
}
</div>
<mat-dialog-actions align="end">
<button mat-raised-button (click)="download()">Download</button>
<button mat-raised-button mat-dialog-close color="primary">Close</button>
</mat-dialog-actions>
@@ -0,0 +1,27 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
.doc-preview-content {
display: flex;
justify-content: center;
align-items: center;
min-width: 320px;
max-width: 80vw;
}
.doc-preview-image {
max-width: 100%;
max-height: 70vh;
object-fit: contain;
}
.doc-preview-pdf {
width: 70vw;
height: 70vh;
border: none;
}
@@ -0,0 +1,81 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/** Angular Imports */
import { Component, OnDestroy, inject } from '@angular/core';
import {
MatDialogRef,
MAT_DIALOG_DATA,
MatDialogTitle,
MatDialogContent,
MatDialogActions,
MatDialogClose
} from '@angular/material/dialog';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { CdkScrollable } from '@angular/cdk/scrolling';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
export interface DocumentPreviewDialogData {
blob: Blob;
title?: string;
fileName?: string;
}
/**
* Generic in-app document preview dialog — shows an image inline or a PDF in an embedded
* viewer, with a Download fallback for anything else. Used in place of window.open() for
* saved KYC/address/senior-citizen/PWD documents: opening a new browser tab is subject to
* popup blockers (fires only after the async download resolves) and, for images, Chrome/Edge
* frequently fail to paint a huge base64 data: URL until the tab is manually refreshed.
*/
@Component({
selector: 'mifosx-document-preview-dialog',
templateUrl: './document-preview-dialog.component.html',
styleUrls: ['./document-preview-dialog.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
MatDialogTitle,
CdkScrollable,
MatDialogContent,
MatDialogActions,
MatDialogClose
]
})
export class DocumentPreviewDialogComponent implements OnDestroy {
dialogRef = inject<MatDialogRef<DocumentPreviewDialogComponent>>(MatDialogRef);
private sanitizer = inject(DomSanitizer);
data = inject<DocumentPreviewDialogData>(MAT_DIALOG_DATA);
private readonly objectUrl: string;
readonly safeUrl: SafeResourceUrl;
readonly isImage: boolean;
readonly isPdf: boolean;
constructor() {
this.objectUrl = URL.createObjectURL(this.data.blob);
this.safeUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.objectUrl);
const type = this.data.blob.type || '';
this.isImage = type.startsWith('image/');
this.isPdf = type === 'application/pdf';
}
ngOnDestroy(): void {
URL.revokeObjectURL(this.objectUrl);
}
get previewUrl(): string {
return this.objectUrl;
}
download(): void {
const a = document.createElement('a');
a.href = this.objectUrl;
a.download = this.data.fileName || 'document';
a.click();
}
}
+53
View File
@@ -70,6 +70,20 @@ export const PROOF_META: Record<string, Partial<ProofType>> = {
documentKeyPlaceholder: 'NPR reference number', documentKeyPlaceholder: 'NPR reference number',
info: 'NPR letter — upload full document.' info: 'NPR letter — upload full document.'
}, },
BIRTH_CERTIFICATE: {
sides: 1,
documentKeyLabel: 'Birth certificate registration number',
documentKeyPlaceholder: 'Registration / certificate number',
category: 'Government-issued ID',
info: 'Birth certificate issued by the Municipal Corporation / Registrar of Births & Deaths — accepted proof of identity for minor clients as per RBI KYC norms.'
},
SCHOOL_ID_CARD: {
sides: 1,
documentKeyLabel: 'School ID / admission number',
documentKeyPlaceholder: 'Student ID number',
category: 'Government-issued ID',
info: 'School identity card bearing photograph — accepted proof of identity for minor clients as per RBI KYC norms.'
},
UTILITY_BILL: { UTILITY_BILL: {
sides: 1, sides: 1,
category: 'Utility bills', category: 'Utility bills',
@@ -131,7 +145,46 @@ export const PROOF_META: Record<string, Partial<ProofType>> = {
PENSION_PAYMENT_ORDER: { PENSION_PAYMENT_ORDER: {
sides: 1, sides: 1,
category: 'Financial & other', category: 'Financial & other',
requiresDate: true,
info: 'Pension payment order — upload full document issued by pension authority.' info: 'Pension payment order — upload full document issued by pension authority.'
},
CERT_INCORPORATION: {
sides: 1,
category: 'Entity KYC documents',
documentKeyLabel: 'Registration / incorporation number',
documentKeyPlaceholder: 'CIN / registration number',
info: 'Certificate of Incorporation (companies/LLPs) or Registration Certificate (firms/trusts/societies) — as prescribed under the RBI Master Direction on KYC, Annexure I.'
},
ENTITY_PAN: {
sides: 1,
category: 'Entity KYC documents',
documentKeyLabel: 'PAN of entity',
documentKeyPlaceholder: 'e.g. ABCDE1234F',
info: 'PAN card issued in the name of the entity.'
},
CONSTITUTIVE_DOC: {
sides: 1,
category: 'Entity KYC documents',
documentKeyLabel: 'Document reference number',
documentKeyPlaceholder: 'Reference / registration number',
info: 'Constitutive document — Memorandum & Articles of Association (companies), Partnership Deed (firms), Trust Deed (trusts), or By-laws (societies) — as prescribed under the RBI Master Direction on KYC.'
},
BOARD_RESOLUTION: {
sides: 1,
category: 'Entity KYC documents',
info: 'Board Resolution / Authorization Letter naming the officers, managers or employees authorised to transact on the entity’s behalf.'
},
AUTH_SIGNATORY_KYC: {
sides: 1,
category: 'Entity KYC documents',
info: 'OVD-based KYC of the person(s) holding Power of Attorney / authorised to transact on the entity’s behalf.'
},
GST_CERTIFICATE: {
sides: 1,
category: 'Entity KYC documents',
documentKeyLabel: 'GSTIN',
documentKeyPlaceholder: 'e.g. 22AAAAA0000A1Z5',
info: 'GST Registration Certificate, where the entity is GST-registered.'
} }
}; };
@@ -281,12 +281,8 @@ export class AuthenticationService {
message: 'Your password has expired, please reset your password!' message: 'Your password has expired, please reset your password!'
}); });
} else { } else {
this.setCredentials(credentials); this.credentials = credentials;
this.alertService.alert({ this.finalizeLogin();
type: 'Authentication Success',
message: `${credentials.username} successfully logged in!`
});
delete this.credentials;
} }
} }
} }
@@ -396,6 +392,22 @@ export class AuthenticationService {
return roleNames.some((n) => n === 'clerk'); return roleNames.some((n) => n === 'clerk');
} }
/** Returns true when the logged-in user has the "Principal Officer" role (STR conclusion/filing authority). */
isPrincipalOfficerUser(): boolean {
const creds = this.getCredentials();
if (!creds || !creds.roles) return false;
const roleNames: string[] = (creds.roles as any[]).map((r) => (r.name || r.role || '').toLowerCase().trim());
return roleNames.some((n) => n === 'principal officer');
}
/** Returns true when the logged-in user has the "AML Officer" role (first-level alert review). */
isAmlOfficerUser(): boolean {
const creds = this.getCredentials();
if (!creds || !creds.roles) return false;
const roleNames: string[] = (creds.roles as any[]).map((r) => (r.name || r.role || '').toLowerCase().trim());
return roleNames.some((n) => n === 'aml officer');
}
/** /**
* Returns true ONLY for regular cashier role (not Head Cashier). * Returns true ONLY for regular cashier role (not Head Cashier).
* Regular cashier → full-screen transaction entry, no nav. * Regular cashier → full-screen transaction entry, no nav.
@@ -428,6 +440,18 @@ export class AuthenticationService {
return roleNames.some((n) => n === 'cashier'); return roleNames.some((n) => n === 'cashier');
} }
/**
* Returns true when the logged-in user belongs to the Head Office.
* Fineract seeds Head Office as officeId 1 with hierarchy "."; office name is
* checked too since some deployments rename/reseed the root office.
*/
isHeadOfficeUser(): boolean {
const creds = this.getCredentials();
if (!creds) return false;
if (creds.officeId === 1) return true;
return (creds.officeName || '').toLowerCase().includes('head office');
}
/** /**
* Sets the user credentials. * Sets the user credentials.
* *
@@ -554,16 +578,60 @@ export class AuthenticationService {
message: 'Your password has expired, please reset your password!' message: 'Your password has expired, please reset your password!'
}); });
} else { } else {
this.setCredentials(this.credentials);
this.alertService.alert({
type: 'Authentication Success',
message: `${this.credentials.username} successfully logged in!`
});
delete this.credentials;
this.storage.setItem(this.twoFactorAuthenticationTokenStorageKey, JSON.stringify(response)); this.storage.setItem(this.twoFactorAuthenticationTokenStorageKey, JSON.stringify(response));
this.finalizeLogin();
} }
} }
/**
* Runs after primary login (and 2FA, if the account has it enrolled) succeeds. Every user must
* accept the bank's current agreement/disclaimer at least once — checks that here and either
* finishes the login immediately (already accepted, or nothing published yet) or fires an alert
* so `login.component.ts` can show the accept dialog.
*/
private finalizeLogin(): void {
this.http.get<{ accepted: boolean }>('/useragreements/active/status').subscribe({
next: (status) => {
if (status?.accepted) {
this.completeAuthentication();
} else {
this.alertService.alert({
type: 'Agreement Acceptance Required',
message: 'Please review and accept the agreement to continue.'
});
}
},
// Don't let an agreement-status hiccup block login entirely.
error: () => this.completeAuthentication()
});
}
/** Finishes the login: persists credentials and fires the existing 'Authentication Success' alert. */
private completeAuthentication(): void {
this.setCredentials(this.credentials);
this.alertService.alert({
type: 'Authentication Success',
message: `${this.credentials.username} successfully logged in!`
});
delete this.credentials;
}
/** Fetches the active agreement's text for display, when the current user hasn't accepted it yet. */
getAgreementStatus(): Observable<{
accepted: boolean;
id?: number;
version?: number;
title?: string;
body?: string;
}> {
return this.http.get<any>('/useragreements/active/status');
}
/** Records the current user's acceptance of the active agreement, then finishes the login. */
acceptActiveAgreement(): Observable<void> {
return this.http.post<any>('/useragreements/active/accept', {}).pipe(map(() => this.completeAuthentication()));
}
/** /**
* Resets the user's password and authenticates the user. * Resets the user's password and authenticates the user.
* @param {any} passwordDetails New password. * @param {any} passwordDetails New password.
+98
View File
@@ -0,0 +1,98 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Injectable, inject } from '@angular/core';
import { AuthenticationService } from './authentication/authentication.service';
import { GL_BRANCHES, GlBranch } from 'app/gl-reports/gl-reports-data';
/**
* Resolves what branch data the logged-in user is allowed to see.
*
* Head Office sees every branch and can drill into any one of them; a branch login is
* locked to its own book. Previously this logic was copy-pasted into the Cash/Clearing
* Summary and the NPA report with slightly different branch code lists; this service is
* the single place it lives so new reports cannot drift.
*
* The logged-in office is matched to a branch by name, since session credentials carry
* only officeId and officeName. Office names are seeded to match the GL branch names
* exactly (see Liquibase 0442).
*/
@Injectable({ providedIn: 'root' })
export class BranchScopeService {
private auth = inject(AuthenticationService);
/** Sentinel used when a branch login cannot be matched to a known branch. */
static readonly UNRESOLVED = '__unresolved__';
get isHeadOffice(): boolean {
return this.auth.isHeadOfficeUser();
}
/** The office name on the session, for labelling the scope in report headers. */
get officeName(): string {
return this.auth.getCredentials()?.officeName || 'Branch Office';
}
/**
* Branch code the user is confined to, or null for Head Office.
*
* Deliberately returns the UNRESOLVED sentinel rather than falling back to the first
* branch when the office cannot be matched: showing an unrecognised branch someone
* else's figures would be worse than showing them nothing.
*/
get ownBranchCode(): string | null {
if (this.isHeadOffice) {
return null;
}
const name = this.officeName.toLowerCase().trim();
const match = GL_BRANCHES.find((b) => b.code !== 'HO' && name === b.name.toLowerCase());
// Fall back to a substring match for offices named e.g. "Andheri (E) Branch".
const loose = match ?? GL_BRANCHES.find((b) => b.code !== 'HO' && name.includes(b.name.toLowerCase()));
return loose?.code ?? BranchScopeService.UNRESOLVED;
}
/** True when the user may choose which branch to view. */
get canSelectBranch(): boolean {
return this.isHeadOffice;
}
/** Branches offered in a selector — everything for Head Office, nothing for a branch login. */
get selectableBranches(): GlBranch[] {
return this.isHeadOffice ? GL_BRANCHES : [];
}
/** Branch code a report should start on. '' means all branches consolidated. */
get defaultBranchCode(): string {
return this.isHeadOffice ? '' : (this.ownBranchCode ?? '');
}
/**
* Forces a requested branch code into what the user is actually allowed to see.
* Call this wherever a branch code reaches a data query, so a stale or hand-edited
* selection cannot widen the user's scope.
*/
enforce(requested: string): string {
return this.isHeadOffice ? requested : (this.ownBranchCode ?? BranchScopeService.UNRESOLVED);
}
/** True when a branch login's office matched no known branch, so it sees no data. */
get isUnresolved(): boolean {
return this.ownBranchCode === BranchScopeService.UNRESOLVED;
}
/** Human label for the current scope, for report headers. */
scopeLabel(selectedCode: string): string {
if (!this.isHeadOffice) {
return this.officeName;
}
if (!selectedCode) {
return 'All Branches (Consolidated)';
}
return GL_BRANCHES.find((b) => b.code === selectedCode)?.name ?? selectedCode;
}
}
+24 -2
View File
@@ -21,6 +21,7 @@ import { environment } from '../../../environments/environment';
import { Logger } from '../logger/logger.service'; import { Logger } from '../logger/logger.service';
import { AlertService } from '../alert/alert.service'; import { AlertService } from '../alert/alert.service';
import { TranslateService } from '@ngx-translate/core'; // Added import for TranslateService import { TranslateService } from '@ngx-translate/core'; // Added import for TranslateService
import { SILENT_HTTP_ERROR } from './silent-error.token';
/** Initialize Logger */ /** Initialize Logger */
const log = new Logger('ErrorHandlerInterceptor'); const log = new Logger('ErrorHandlerInterceptor');
@@ -54,12 +55,33 @@ export class ErrorHandlerInterceptor implements HttpInterceptor {
const isClientImageRequest = request.url.includes('/clients/') && request.url.includes('/images'); const isClientImageRequest = request.url.includes('/clients/') && request.url.includes('/images');
const isClientKycRequest = request.url.match(/\/clients\/\d+\/kyc$/); const isClientKycRequest = request.url.match(/\/clients\/\d+\/kyc$/);
const isDirectorRequest = request.url.includes('/election/directors'); const isDirectorRequest = request.url.includes('/election/directors');
const isSilentRequest = isClientImageRequest || isClientKycRequest || isDirectorRequest; // "No pending edit for this client" is the normal/expected state — checked on every edit-page
// load, not a real error the user needs to see.
const isClientPendingEditRequest = request.url.match(/\/clients\/\d+\/edit\/pending$/);
// Risk rules are an enhancement on top of a default risk-category fallback — if this
// endpoint isn't available on a given backend deployment, the client-general-step
// component already falls back to riskRules = [] silently; no toast needed here either.
const isKycRiskRulesRequest = request.url.includes('/kyc/risk-rules');
const isSilentRequest =
isClientImageRequest ||
isClientKycRequest ||
isDirectorRequest ||
isClientPendingEditRequest ||
isKycRiskRulesRequest;
if (!environment.production && !isSilentRequest) { // Explicit per-request opt-out (e.g. per-row enrichment fetches on a list page whose
// component already recovers via its own catchError) — silenced for every status, since
// the caller took responsibility for handling failure when it set this.
const isSilentOverride = request.context.get(SILENT_HTTP_ERROR);
if (!environment.production && !isSilentRequest && !isSilentOverride) {
log.error(`Request Error: ${errorMessage}`); log.error(`Request Error: ${errorMessage}`);
} }
if (isSilentOverride) {
throw response;
}
// Silently handle expected 403/404 errors (no image, no KYC record) // Silently handle expected 403/404 errors (no image, no KYC record)
// Throw instead of EMPTY so component-level catchError can handle it // Throw instead of EMPTY so component-level catchError can handle it
if (isSilentRequest && (status === 403 || status === 404)) { if (isSilentRequest && (status === 403 || status === 404)) {
+17
View File
@@ -0,0 +1,17 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { HttpContextToken } from '@angular/common/http';
/**
* Per-request opt-out of ErrorHandlerInterceptor's toast. Set via
* `{ context: new HttpContext().set(SILENT_HTTP_ERROR, true) }` on calls whose caller already
* handles failures itself (e.g. per-row enrichment fetches on a list page) — the interceptor
* still throws so the caller's own catchError/error callback runs, it just skips the alert.
*/
export const SILENT_HTTP_ERROR = new HttpContextToken<boolean>(() => false);
+386 -79
View File
@@ -350,6 +350,10 @@
<fa-icon icon="exclamation-triangle" class="ni-ico"></fa-icon>NPA <fa-icon icon="exclamation-triangle" class="ni-ico"></fa-icon>NPA
<fa-icon icon="caret-down" class="ni-caret"></fa-icon> <fa-icon icon="caret-down" class="ni-caret"></fa-icon>
</a> </a>
<a class="ni" tabindex="0" [matMenuTriggerFor]="loanOriginationMenu" *mifosxHasPermission="'MENU_ADVANCES'">
<fa-icon icon="clipboard-check" class="ni-ico"></fa-icon>Loan Origination
<fa-icon icon="caret-down" class="ni-caret"></fa-icon>
</a>
<a class="ni" tabindex="0" [matMenuTriggerFor]="advancesMenu" *mifosxHasPermission="'MENU_ADVANCES'"> <a class="ni" tabindex="0" [matMenuTriggerFor]="advancesMenu" *mifosxHasPermission="'MENU_ADVANCES'">
<fa-icon icon="hand-holding-usd" class="ni-ico"></fa-icon>Advances <fa-icon icon="hand-holding-usd" class="ni-ico"></fa-icon>Advances
<fa-icon icon="caret-down" class="ni-caret"></fa-icon> <fa-icon icon="caret-down" class="ni-caret"></fa-icon>
@@ -362,6 +366,10 @@
<fa-icon icon="university" class="ni-ico"></fa-icon>RBI <fa-icon icon="university" class="ni-ico"></fa-icon>RBI
<fa-icon [icon]="rbiMenuOpen ? 'caret-up' : 'caret-down'" class="ni-caret"></fa-icon> <fa-icon [icon]="rbiMenuOpen ? 'caret-up' : 'caret-down'" class="ni-caret"></fa-icon>
</a> </a>
<a class="ni" tabindex="0" (click)="investmentMenuOpen = !investmentMenuOpen; rbiMenuOpen = false; glMenuOpen = false" *mifosxHasPermission="'MENU_RBI'">
<fa-icon icon="chart-line" class="ni-ico"></fa-icon>Investment
<fa-icon [icon]="investmentMenuOpen ? 'caret-up' : 'caret-down'" class="ni-caret"></fa-icon>
</a>
<a class="ni" tabindex="0" [matMenuTriggerFor]="digitalMenu" *mifosxHasPermission="'MENU_DIGITAL'"> <a class="ni" tabindex="0" [matMenuTriggerFor]="digitalMenu" *mifosxHasPermission="'MENU_DIGITAL'">
<fa-icon icon="mobile-alt" class="ni-ico"></fa-icon>Digital <fa-icon icon="mobile-alt" class="ni-ico"></fa-icon>Digital
<fa-icon icon="caret-down" class="ni-caret"></fa-icon> <fa-icon icon="caret-down" class="ni-caret"></fa-icon>
@@ -438,6 +446,10 @@
<fa-icon icon="exclamation-triangle" class="ni-ico"></fa-icon>NPA <fa-icon icon="exclamation-triangle" class="ni-ico"></fa-icon>NPA
<fa-icon icon="caret-down" class="ni-caret"></fa-icon> <fa-icon icon="caret-down" class="ni-caret"></fa-icon>
</a> </a>
<a class="ni" tabindex="0" [matMenuTriggerFor]="loanOriginationMenu" *mifosxHasPermission="'MENU_ADVANCES'">
<fa-icon icon="clipboard-check" class="ni-ico"></fa-icon>Loan Origination
<fa-icon icon="caret-down" class="ni-caret"></fa-icon>
</a>
<a <a
class="ni" class="ni"
tabindex="0" tabindex="0"
@@ -492,6 +504,15 @@
<fa-icon icon="university" class="ni-ico"></fa-icon>RBI <fa-icon icon="university" class="ni-ico"></fa-icon>RBI
<fa-icon [icon]="rbiMenuOpen ? 'caret-up' : 'caret-down'" class="ni-caret"></fa-icon> <fa-icon [icon]="rbiMenuOpen ? 'caret-up' : 'caret-down'" class="ni-caret"></fa-icon>
</a> </a>
<a
class="ni"
tabindex="0"
(click)="investmentMenuOpen = !investmentMenuOpen; rbiMenuOpen = false; glMenuOpen = false"
*mifosxHasPermission="'MENU_RBI'"
>
<fa-icon icon="chart-line" class="ni-ico"></fa-icon>Investment
<fa-icon [icon]="investmentMenuOpen ? 'caret-up' : 'caret-down'" class="ni-caret"></fa-icon>
</a>
<a class="ni" tabindex="0" [matMenuTriggerFor]="reportsMenu" *mifosxHasPermission="'MENU_REPORTS'"> <a class="ni" tabindex="0" [matMenuTriggerFor]="reportsMenu" *mifosxHasPermission="'MENU_REPORTS'">
<fa-icon icon="chart-bar" class="ni-ico"></fa-icon>Reports <fa-icon icon="chart-bar" class="ni-ico"></fa-icon>Reports
<fa-icon icon="caret-down" class="ni-caret"></fa-icon> <fa-icon icon="caret-down" class="ni-caret"></fa-icon>
@@ -566,6 +587,13 @@
<button mat-menu-item [routerLink]="['/reports', 'Accounting']" tabindex="0"> <button mat-menu-item [routerLink]="['/reports', 'Accounting']" tabindex="0">
<i class="fa fa-calculator menu-item-icon"></i> Accounting <i class="fa fa-calculator menu-item-icon"></i> Accounting
</button> </button>
<mat-divider></mat-divider>
<button mat-menu-item routerLink="/reports/form-97-98" tabindex="0">
<i class="fa fa-file-invoice menu-item-icon"></i> Form 97/98 Transaction Report
</button>
<button mat-menu-item routerLink="/reports/risk-review" tabindex="0">
<i class="fa fa-user-shield menu-item-icon"></i> Risk Review Report
</button>
</mat-menu> </mat-menu>
<!-- Admin Mega Menu — 3-column rectangular panel grouping Setup, <!-- Admin Mega Menu — 3-column rectangular panel grouping Setup,
@@ -653,6 +681,7 @@
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesSubLedgerSearch('Cash / Clearing / Transfer')" [class.hidden]="!matchesSubLedgerSearch('Cash / Clearing / Transfer')"
routerLink="/cashier/cash-clearing-transfer-summary"
(click)="subLedgerOpen = false" (click)="subLedgerOpen = false"
><fa-icon icon="money-bill" class="gl-icon"></fa-icon> Cash / Clearing / Transfer</a ><fa-icon icon="money-bill" class="gl-icon"></fa-icon> Cash / Clearing / Transfer</a
> >
@@ -701,8 +730,11 @@
</div> </div>
<div class="gl-group"> <div class="gl-group">
<div class="gl-group-title">Deposits</div> <div class="gl-group-title">Deposits</div>
<a class="gl-link" [class.hidden]="!matchesSubLedgerSearch('FD / RD Entry')" (click)="subLedgerOpen = false" <a
><fa-icon icon="piggy-bank" class="gl-icon"></fa-icon> FD / RD Entry</a class="gl-link"
[class.hidden]="!matchesSubLedgerSearch('FD / RD Entry')"
(click)="subLedgerOpen = false; openFdRdEntryDialog()"
><fa-icon icon="piggy-bank" class="gl-icon" style="color: #0f766e"></fa-icon> FD / RD Entry</a
> >
<a class="gl-link" [class.hidden]="!matchesSubLedgerSearch('DDS Entry')" (click)="subLedgerOpen = false" <a class="gl-link" [class.hidden]="!matchesSubLedgerSearch('DDS Entry')" (click)="subLedgerOpen = false"
><fa-icon icon="coins" class="gl-icon"></fa-icon> DDS Entry</a ><fa-icon icon="coins" class="gl-icon"></fa-icon> DDS Entry</a
@@ -808,50 +840,72 @@
<div class="gl-columns"> <div class="gl-columns">
<div class="gl-group"> <div class="gl-group">
<div class="gl-group-title">Financial Statements</div> <div class="gl-group-title">Financial Statements</div>
<a class="gl-link" [class.hidden]="!matchesGlSearch('Trial Balance')" (click)="glMenuOpen = false" <a
><fa-icon icon="balance-scale" class="gl-icon"></fa-icon> Trial Balance</a class="gl-link"
[class.hidden]="!matchesGlSearch('Trial Balance')"
routerLink="/gl/reports/trial-balance"
(click)="glMenuOpen = false"
><fa-icon icon="balance-scale" class="gl-icon" style="color: #b45309"></fa-icon> Trial Balance</a
> >
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesGlSearch('Profit and Loss')" [class.hidden]="!matchesGlSearch('Profit and Loss')"
(click)="glMenuOpen = false; openAccountingReportsDialog('PNL')" routerLink="/gl/reports/profit-and-loss"
(click)="glMenuOpen = false"
><fa-icon icon="chart-line" class="gl-icon" style="color: #b45309"></fa-icon> Profit and Loss</a ><fa-icon icon="chart-line" class="gl-icon" style="color: #b45309"></fa-icon> Profit and Loss</a
> >
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesGlSearch('Consolidate Balance Sheet')" [class.hidden]="!matchesGlSearch('Consolidate Balance Sheet')"
(click)="glMenuOpen = false; openAccountingReportsDialog('BALANCE-SHEET')" routerLink="/gl/reports/balance-sheet"
><fa-icon icon="file-alt" class="gl-icon" style="color: #b45309"></fa-icon> Consolidate Balance Sheet</a (click)="glMenuOpen = false"
><fa-icon icon="file-alt" class="gl-icon" style="color: #b45309"></fa-icon> Consolidated Balance Sheet</a
> >
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesGlSearch('Comparative Balance Sheet')" [class.hidden]="!matchesGlSearch('Comparative Balance Sheet')"
(click)="glMenuOpen = false; openAccountingReportsDialog('COMPARATIVE-BS')" routerLink="/gl/reports/comparative-balance-sheet"
(click)="glMenuOpen = false"
><fa-icon icon="balance-scale" class="gl-icon" style="color: #b45309"></fa-icon> Comparative Balance ><fa-icon icon="balance-scale" class="gl-icon" style="color: #b45309"></fa-icon> Comparative Balance
Sheet</a Sheet</a
> >
</div> </div>
<div class="gl-group"> <div class="gl-group">
<div class="gl-group-title">GL Reports</div> <div class="gl-group-title">GL Reports</div>
<a class="gl-link" [class.hidden]="!matchesGlSearch('GL Average Balance')" (click)="glMenuOpen = false" <a
><fa-icon icon="calculator" class="gl-icon"></fa-icon> GL Average Balance</a class="gl-link"
[class.hidden]="!matchesGlSearch('GL Average Balance')"
routerLink="/gl/reports/gl-average-balance"
(click)="glMenuOpen = false"
><fa-icon icon="calculator" class="gl-icon" style="color: #b45309"></fa-icon> GL Average Balance</a
> >
<a class="gl-link" [class.hidden]="!matchesGlSearch('GL Mapping for Report')" (click)="glMenuOpen = false" <a
><fa-icon icon="project-diagram" class="gl-icon"></fa-icon> GL Mapping for Report</a class="gl-link"
[class.hidden]="!matchesGlSearch('GL Mapping for Report')"
routerLink="/gl/reports/gl-mapping"
(click)="glMenuOpen = false"
><fa-icon icon="project-diagram" class="gl-icon" style="color: #b45309"></fa-icon> GL Mapping for
Report</a
> >
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesGlSearch('Account wise Balance List')" [class.hidden]="!matchesGlSearch('Account wise Balance List')"
routerLink="/gl/reports/account-wise-balance"
(click)="glMenuOpen = false" (click)="glMenuOpen = false"
><fa-icon icon="list" class="gl-icon"></fa-icon> Account wise Balance List</a ><fa-icon icon="list" class="gl-icon" style="color: #b45309"></fa-icon> Account wise Balance List</a
> >
<a class="gl-link" [class.hidden]="!matchesGlSearch('Distribution of Balance')" (click)="glMenuOpen = false" <a
><fa-icon icon="chart-pie" class="gl-icon"></fa-icon> Distribution of Balance</a class="gl-link"
[class.hidden]="!matchesGlSearch('Distribution of Balance')"
routerLink="/gl/reports/distribution-of-balance"
(click)="glMenuOpen = false"
><fa-icon icon="chart-pie" class="gl-icon" style="color: #b45309"></fa-icon> Distribution of Balance</a
> >
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesGlSearch('GL Wise DR CR')" [class.hidden]="!matchesGlSearch('GL Wise DR CR')"
(click)="glMenuOpen = false; openAccountingReportsDialog('GL-DR-CR')" routerLink="/gl/reports/gl-wise-dr-cr"
(click)="glMenuOpen = false"
><fa-icon icon="project-diagram" class="gl-icon" style="color: #b45309"></fa-icon> GL Wise DR / CR ><fa-icon icon="project-diagram" class="gl-icon" style="color: #b45309"></fa-icon> GL Wise DR / CR
Report</a Report</a
> >
@@ -861,28 +915,47 @@
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesGlSearch('Client wise Balance Report')" [class.hidden]="!matchesGlSearch('Client wise Balance Report')"
routerLink="/gl/reports/client-wise-balance"
(click)="glMenuOpen = false" (click)="glMenuOpen = false"
><fa-icon icon="users" class="gl-icon"></fa-icon> Client wise Balance Report</a ><fa-icon icon="users" class="gl-icon" style="color: #b45309"></fa-icon> Client wise Balance Report</a
> >
<a class="gl-link" [class.hidden]="!matchesGlSearch('Contingent Expense')" (click)="glMenuOpen = false" <a
><fa-icon icon="exclamation-circle" class="gl-icon"></fa-icon> Contingent Expense</a class="gl-link"
[class.hidden]="!matchesGlSearch('Contingent Liabilities')"
routerLink="/gl/reports/contingent-liabilities"
(click)="glMenuOpen = false"
><fa-icon icon="exclamation-circle" class="gl-icon" style="color: #b45309"></fa-icon> Contingent
Liabilities</a
> >
<a class="gl-link" [class.hidden]="!matchesGlSearch('Banker Head Report')" (click)="glMenuOpen = false" <a
><fa-icon icon="university" class="gl-icon"></fa-icon> Banker Head Report</a class="gl-link"
[class.hidden]="!matchesGlSearch('Banker Head Report')"
routerLink="/gl/reports/banker-head"
(click)="glMenuOpen = false"
><fa-icon icon="university" class="gl-icon" style="color: #b45309"></fa-icon> Banker Head Report</a
> >
</div> </div>
<div class="gl-group"> <div class="gl-group">
<div class="gl-group-title">Registers</div> <div class="gl-group-title">Registers</div>
<a class="gl-link" [class.hidden]="!matchesGlSearch('Sundry Register')" (click)="glMenuOpen = false" <a
><fa-icon icon="clipboard-list" class="gl-icon"></fa-icon> Sundry Register</a class="gl-link"
[class.hidden]="!matchesGlSearch('Sundry Register')"
routerLink="/gl/reports/sundry-register"
(click)="glMenuOpen = false"
><fa-icon icon="clipboard-list" class="gl-icon" style="color: #b45309"></fa-icon> Sundry Register</a
> >
<a class="gl-link" [class.hidden]="!matchesGlSearch('Voucher Register')" (click)="glMenuOpen = false" <a
><fa-icon icon="receipt" class="gl-icon"></fa-icon> Voucher Register</a class="gl-link"
[class.hidden]="!matchesGlSearch('Voucher Register')"
routerLink="/gl/reports/voucher-register"
(click)="glMenuOpen = false"
><fa-icon icon="receipt" class="gl-icon" style="color: #b45309"></fa-icon> Voucher Register</a
> >
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesGlSearch('Misc Expense Ledger')" [class.hidden]="!matchesGlSearch('Misc Expense Ledger')"
(click)="glMenuOpen = false; openAccountingReportsDialog('MISC-EXP')" routerLink="/gl/reports/misc-expense-ledger"
(click)="glMenuOpen = false"
><fa-icon icon="receipt" class="gl-icon" style="color: #b45309"></fa-icon> Misc Expense Ledger</a ><fa-icon icon="receipt" class="gl-icon" style="color: #b45309"></fa-icon> Misc Expense Ledger</a
> >
</div> </div>
@@ -1121,7 +1194,7 @@
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0">
<fa-icon icon="check-circle" class="menu-item-icon"></fa-icon> Share Issued <fa-icon icon="check-circle" class="menu-item-icon"></fa-icon> Share Issued
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" [routerLink]="['/shares/share-holders']">
<fa-icon icon="users" class="menu-item-icon"></fa-icon> Share Holder <fa-icon icon="users" class="menu-item-icon"></fa-icon> Share Holder
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0">
@@ -1155,7 +1228,7 @@
<fa-icon icon="user-slash" class="menu-item-icon" style="color: #c2410c"></fa-icon> Non-Customer Entry <fa-icon icon="user-slash" class="menu-item-icon" style="color: #c2410c"></fa-icon> Non-Customer Entry
</button> </button>
<button mat-menu-item tabindex="0"><fa-icon icon="lock" class="menu-item-icon"></fa-icon> Locker</button> <button mat-menu-item tabindex="0"><fa-icon icon="lock" class="menu-item-icon"></fa-icon> Locker</button>
<button mat-menu-item tabindex="0"> <button mat-menu-item routerLink="/investment/bonds" tabindex="0">
<fa-icon icon="chart-line" class="menu-item-icon"></fa-icon> SLR and Non SLR Investment Report <fa-icon icon="chart-line" class="menu-item-icon"></fa-icon> SLR and Non SLR Investment Report
</button> </button>
<button mat-menu-item tabindex="0" (click)="openCicReportingDialog()"> <button mat-menu-item tabindex="0" (click)="openCicReportingDialog()">
@@ -1167,21 +1240,17 @@
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0">
<fa-icon icon="chart-bar" class="menu-item-icon"></fa-icon> Depreciation Register <fa-icon icon="chart-bar" class="menu-item-icon"></fa-icon> Depreciation Register
</button> </button>
<button mat-menu-item routerLink="/fiu" tabindex="0">
<fa-icon icon="shield-alt" class="menu-item-icon" style="color: #dc2626"></fa-icon> Financial Intelligence
Unit (FIU-IND)
</button>
</div> </div>
<!-- Investment --> <!-- Investment -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">Investment</div> <div class="deposit-group-title">Investment</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item routerLink="/investment/dashboard" tabindex="0">
<fa-icon icon="calendar-alt" class="menu-item-icon"></fa-icon> Due Date Diary for All Investment <fa-icon icon="calendar-alt" class="menu-item-icon"></fa-icon> Due Date Diary for All Investment
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item routerLink="/investment/reports" tabindex="0">
<fa-icon icon="dollar-sign" class="menu-item-icon"></fa-icon> Total Int Received &amp; Receivable Report <fa-icon icon="dollar-sign" class="menu-item-icon"></fa-icon> Total Int Received &amp; Receivable Report
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item routerLink="/investment/reports" tabindex="0">
<fa-icon icon="piggy-bank" class="menu-item-icon"></fa-icon> Bucket Wise Investment <fa-icon icon="piggy-bank" class="menu-item-icon"></fa-icon> Bucket Wise Investment
</button> </button>
<button mat-menu-item routerLink="/deaf" tabindex="0"> <button mat-menu-item routerLink="/deaf" tabindex="0">
@@ -1212,39 +1281,96 @@
<!-- NPA Reports --> <!-- NPA Reports -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">NPA Reports</div> <div class="deposit-group-title">NPA Reports</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/interest">
<fa-icon icon="chart-line" class="menu-item-icon"></fa-icon> NPA Interest <fa-icon icon="chart-line" class="menu-item-icon"></fa-icon> NPA Report
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/status">
<fa-icon icon="file-alt" class="menu-item-icon"></fa-icon> NPA Status Report <fa-icon icon="file-alt" class="menu-item-icon"></fa-icon> NPA Status Report
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/recovery">
<fa-icon icon="undo" class="menu-item-icon"></fa-icon> NPA Recovery Report <fa-icon icon="undo" class="menu-item-icon"></fa-icon> NPA Recovery Report
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/summary">
<fa-icon icon="clipboard-list" class="menu-item-icon"></fa-icon> NPA Summary Report <fa-icon icon="clipboard-list" class="menu-item-icon"></fa-icon> NPA Summary Report
</button> </button>
</div> </div>
<!-- NPA Analysis --> <!-- NPA Analysis -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">NPA Analysis</div> <div class="deposit-group-title">NPA Analysis</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/account-detail">
<fa-icon icon="list-alt" class="menu-item-icon"></fa-icon> NPA Account Detail Report <fa-icon icon="list-alt" class="menu-item-icon"></fa-icon> NPA Account Detail Report
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/movement">
<fa-icon icon="exchange" class="menu-item-icon"></fa-icon> NPA Movement Report <fa-icon icon="exchange" class="menu-item-icon"></fa-icon> NPA Movement Report
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/provision">
<fa-icon icon="hand-holding-usd" class="menu-item-icon"></fa-icon> NPA with Provision and Required Provision <fa-icon icon="hand-holding-usd" class="menu-item-icon"></fa-icon> NPA with Provision and Required Provision
</button> </button>
<button mat-menu-item tabindex="0" routerLink="/npa/reports/undebited-interest">
<fa-icon icon="coins" class="menu-item-icon"></fa-icon> Undebited Interest Recovery Report
</button>
</div> </div>
<!-- NPA Classification --> <!-- NPA Classification -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">NPA Classification</div> <div class="deposit-group-title">NPA Classification</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/npa/reports/probable">
<fa-icon icon="exclamation-circle" class="menu-item-icon"></fa-icon> Probable NPA <fa-icon icon="exclamation-circle" class="menu-item-icon"></fa-icon> Probable NPA
</button> </button>
<button mat-menu-item tabindex="0"><fa-icon icon="flag" class="menu-item-icon"></fa-icon> SMA Report</button> <button mat-menu-item tabindex="0" routerLink="/npa/reports/sma">
<fa-icon icon="flag" class="menu-item-icon"></fa-icon> SMA Report
</button>
</div>
<!-- Recovery Management -->
<div class="deposit-menu-group">
<div class="deposit-group-title">Recovery Management</div>
<button mat-menu-item tabindex="0" routerLink="/npa/reports/recovery-dashboard">
<fa-icon icon="tachometer-alt" class="menu-item-icon"></fa-icon> Recovery Management Dashboard
</button>
<button mat-menu-item tabindex="0" routerLink="/npa/reports/daywise-overdue">
<fa-icon icon="calendar-alt" class="menu-item-icon"></fa-icon> Day-wise Overdue Report
</button>
<button mat-menu-item tabindex="0" routerLink="/npa/reports/daywise-overdrawn">
<fa-icon icon="credit-card" class="menu-item-icon"></fa-icon> Day-wise Overdrawn Report
</button>
<button mat-menu-item tabindex="0" routerLink="/npa/reports/agri-gold-value">
<fa-icon icon="crop" class="menu-item-icon"></fa-icon> Agriculture / Gold Market Value Report
</button>
<button mat-menu-item tabindex="0" routerLink="/npa/reports/exception-check">
<fa-icon icon="balance-scale" class="menu-item-icon"></fa-icon> Exception Check — Security Value vs Loan
</button>
</div>
</div>
</mat-menu>
<mat-menu #loanOriginationMenu="matMenu" class="npa-mega-panel" [overlapTrigger]="false">
<div class="deposit-menu-grid npa-grid" (click)="$event.stopPropagation()">
<!-- Loan Origination -->
<div class="deposit-menu-group">
<div class="deposit-group-title">Loan Origination</div>
<button mat-menu-item tabindex="0" routerLink="/loan-origination/pipeline">
<fa-icon icon="stream" class="menu-item-icon"></fa-icon> Application Pipeline
</button>
</div>
<!-- Reports -->
<div class="deposit-menu-group">
<div class="deposit-group-title">Reports</div>
<button
mat-menu-item
tabindex="0"
routerLink="/loan-origination/pipeline"
[queryParams]="{ view: 'channel' }"
>
<fa-icon icon="chart-pie" class="menu-item-icon"></fa-icon> Channel-wise Report
</button>
<button mat-menu-item tabindex="0" routerLink="/loan-origination/pipeline" [queryParams]="{ view: 'bc' }">
<fa-icon icon="mobile-alt" class="menu-item-icon"></fa-icon> BC-wise Report
</button>
<button mat-menu-item tabindex="0" routerLink="/loan-origination/pipeline" [queryParams]="{ view: 'share' }">
<fa-icon icon="coins" class="menu-item-icon"></fa-icon> Share Member Report
</button>
<button mat-menu-item tabindex="0" routerLink="/loan-origination/pipeline" [queryParams]="{ view: 'target' }">
<fa-icon icon="chart-column" class="menu-item-icon"></fa-icon> Target vs Actual
</button>
</div> </div>
</div> </div>
</mat-menu> </mat-menu>
@@ -1277,27 +1403,27 @@
<!-- Core / Books --> <!-- Core / Books -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">Core &amp; Books</div> <div class="deposit-group-title">Core &amp; Books</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/voucher">
<fa-icon icon="receipt" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="receipt" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Voucher Reconciliation Voucher Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/sundry-dr-cr">
<fa-icon icon="random" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="random" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Sundry Dr / Cr Reconciliation Sundry Dr / Cr Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/pnl-impact">
<fa-icon icon="chart-line" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="chart-line" class="menu-item-icon" style="color: #0d9488"></fa-icon>
P&amp;L Impact Reconciliation P&amp;L Impact Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/gl-reconciliation">
<fa-icon icon="book-open" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="book-open" class="menu-item-icon" style="color: #0d9488"></fa-icon>
GL Reconciliation GL Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/fixed-assets">
<fa-icon icon="cube" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="cube" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Fixed Assets Reconciliation Fixed Assets Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/inter-company">
<fa-icon icon="sitemap" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="sitemap" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Inter-Company Reconciliation Inter-Company Reconciliation
</button> </button>
@@ -1306,19 +1432,19 @@
<!-- Bank & Clearing --> <!-- Bank & Clearing -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">Bank &amp; Clearing</div> <div class="deposit-group-title">Bank &amp; Clearing</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/bank-reco">
<fa-icon icon="university" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="university" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Bank Reconciliation Bank Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/api-bank-reco">
<fa-icon icon="code-branch" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="code-branch" class="menu-item-icon" style="color: #0d9488"></fa-icon>
API Based Bank Reconciliation API Based Bank Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/neft-rtgs">
<fa-icon icon="exchange" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="exchange" class="menu-item-icon" style="color: #0d9488"></fa-icon>
NEFT / RTGS Reconciliation NEFT / RTGS Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/clearing-reco">
<fa-icon icon="hand-holding-usd" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="hand-holding-usd" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Clearing Reconciliation Clearing Reconciliation
</button> </button>
@@ -1327,15 +1453,15 @@
<!-- Digital / Payments --> <!-- Digital / Payments -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">Digital &amp; Payments</div> <div class="deposit-group-title">Digital &amp; Payments</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/udir">
<fa-icon icon="mobile-alt" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="mobile-alt" class="menu-item-icon" style="color: #0d9488"></fa-icon>
UDIR (IMPS / UPI / ATM) UDIR (IMPS / UPI / ATM)
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/three-way-digital">
<fa-icon icon="project-diagram" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="project-diagram" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Three-way Digital Reconciliation Three-way Digital Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/nach-reco">
<fa-icon icon="sync-alt" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="sync-alt" class="menu-item-icon" style="color: #0d9488"></fa-icon>
NACH Reconciliation NACH Reconciliation
</button> </button>
@@ -1348,7 +1474,7 @@
<fa-icon icon="money-check-alt" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="money-check-alt" class="menu-item-icon" style="color: #0d9488"></fa-icon>
DD / Pay Order Reconciliation DD / Pay Order Reconciliation
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/share-member">
<fa-icon icon="coins" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="coins" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Share Member Reconciliation Share Member Reconciliation
</button> </button>
@@ -1357,11 +1483,11 @@
<!-- Compliance & Financials --> <!-- Compliance & Financials -->
<div class="deposit-menu-group"> <div class="deposit-menu-group">
<div class="deposit-group-title">Compliance &amp; Financials</div> <div class="deposit-group-title">Compliance &amp; Financials</div>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/invoice-payment">
<fa-icon icon="file-invoice" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="file-invoice" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Invoice Payment Invoice Payment
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0" routerLink="/reconciliation/tax-reco">
<fa-icon icon="percentage" class="menu-item-icon" style="color: #0d9488"></fa-icon> <fa-icon icon="percentage" class="menu-item-icon" style="color: #0d9488"></fa-icon>
Tax Reconciliation Tax Reconciliation
</button> </button>
@@ -1468,13 +1594,16 @@
Balance Certificate Balance Certificate
</button> </button>
<button mat-menu-item routerLink="/letter-mgmt/form-60" tabindex="0"> <button mat-menu-item routerLink="/letter-mgmt/form-60" tabindex="0">
<fa-icon icon="file-signature" class="menu-item-icon" style="color: #15803d"></fa-icon> Form 60 <fa-icon icon="file-signature" class="menu-item-icon" style="color: #15803d"></fa-icon> Form 97
</button> </button>
<button mat-menu-item tabindex="0"> <button mat-menu-item tabindex="0">
<fa-icon icon="file-signature" class="menu-item-icon" style="color: #15803d"></fa-icon> Form 61 <fa-icon icon="file-signature" class="menu-item-icon" style="color: #15803d"></fa-icon> Form 98
</button>
<button mat-menu-item routerLink="/reports/form-97-98" tabindex="0">
<fa-icon icon="file-invoice" class="menu-item-icon" style="color: #15803d"></fa-icon> Form 97/98 Txn Report
</button> </button>
<button mat-menu-item routerLink="/letter-mgmt/form-15gh" tabindex="0"> <button mat-menu-item routerLink="/letter-mgmt/form-15gh" tabindex="0">
<fa-icon icon="file-signature" class="menu-item-icon" style="color: #15803d"></fa-icon> Form 15G and H <fa-icon icon="file-signature" class="menu-item-icon" style="color: #15803d"></fa-icon> Form 121
</button> </button>
<button mat-menu-item routerLink="/letter-mgmt/hypothecation-certificate" tabindex="0"> <button mat-menu-item routerLink="/letter-mgmt/hypothecation-certificate" tabindex="0">
<fa-icon icon="file-alt" class="menu-item-icon" style="color: #15803d"></fa-icon> <fa-icon icon="file-alt" class="menu-item-icon" style="color: #15803d"></fa-icon>
@@ -1568,8 +1697,13 @@
<a class="gl-link" [class.hidden]="!matchesRbiSearch('Balance Sheet')" (click)="rbiMenuOpen = false"> <a class="gl-link" [class.hidden]="!matchesRbiSearch('Balance Sheet')" (click)="rbiMenuOpen = false">
<fa-icon icon="file-alt" class="gl-icon"></fa-icon> Balance Sheet (BR Act & Others) <fa-icon icon="file-alt" class="gl-icon"></fa-icon> Balance Sheet (BR Act & Others)
</a> </a>
<a class="gl-link" [class.hidden]="!matchesRbiSearch('CRR / SLR')" (click)="rbiMenuOpen = false"> <a
<fa-icon icon="calculator" class="gl-icon"></fa-icon> CRR / SLR class="gl-link"
[class.hidden]="!matchesRbiSearch('CTR / STR')"
routerLink="/fiu"
(click)="rbiMenuOpen = false"
>
<fa-icon icon="calculator" class="gl-icon"></fa-icon> CTR / STR
</a> </a>
<a class="gl-link" [class.hidden]="!matchesRbiSearch('Annexure')" (click)="rbiMenuOpen = false"> <a class="gl-link" [class.hidden]="!matchesRbiSearch('Annexure')" (click)="rbiMenuOpen = false">
<fa-icon icon="paperclip" class="gl-icon"></fa-icon> Annexure <fa-icon icon="paperclip" class="gl-icon"></fa-icon> Annexure
@@ -1664,31 +1798,49 @@
> >
<fa-icon icon="bell" class="gl-icon"></fa-icon> Daily Position Notice <fa-icon icon="bell" class="gl-icon"></fa-icon> Daily Position Notice
</a> </a>
<a class="gl-link" [class.hidden]="!matchesRbiSearch('R/SLR')" (click)="rbiMenuOpen = false"> <a
<fa-icon icon="lock" class="gl-icon"></fa-icon> R/SLR class="gl-link"
[class.hidden]="!matchesRbiSearch('AML')"
routerLink="/rbi/aml"
(click)="rbiMenuOpen = false"
>
<fa-icon icon="shield-alt" class="gl-icon"></fa-icon> AML
</a>
<a
class="gl-link"
[class.hidden]="!matchesRbiSearch('Risk Review Report')"
routerLink="/reports/risk-review"
(click)="rbiMenuOpen = false"
>
<fa-icon icon="user-shield" class="gl-icon"></fa-icon> Risk Review Report
</a> </a>
</div> </div>
<!-- OSS Reports --> <!-- OSS Reports -->
<div class="gl-group"> <div class="gl-group">
<div class="gl-group-title">OSS Reports</div> <div class="gl-group-title">OSS Reports</div>
<a class="gl-link" [class.hidden]="!matchesRbiSearch('OSS 1 XBRL/CIMS')" (click)="rbiMenuOpen = false"> <a
<fa-icon icon="file-alt" class="gl-icon"></fa-icon> OSS 1 XBRL/CIMS class="gl-link"
[class.hidden]="!matchesRbiSearch('OSS 1 XBRL/CIMS')"
routerLink="/rbi/oss1"
(click)="rbiMenuOpen = false"
>
<fa-icon icon="file-alt" class="gl-icon" style="color: #0891b2"></fa-icon> OSS 1 XBRL/CIMS
</a> </a>
<a <a
class="gl-link" class="gl-link"
[class.hidden]="!matchesRbiSearch('OSS 2 XBRL')" [class.hidden]="!matchesRbiSearch('OSS 2 XBRL')"
(click)="rbiMenuOpen = false; openCimsXbrlDialog('OSS-2')" routerLink="/rbi/oss2"
(click)="rbiMenuOpen = false"
> >
<fa-icon icon="file-alt" class="gl-icon" style="color: #0891b2"></fa-icon> OSS 2 XBRL <fa-icon icon="file-alt" class="gl-icon" style="color: #0891b2"></fa-icon> OSS 2 XBRL
</a> </a>
<a class="gl-link" [class.hidden]="!matchesRbiSearch('OSS 3 XBRL/CIMS')" (click)="rbiMenuOpen = false"> <a
<fa-icon icon="file-alt" class="gl-icon"></fa-icon> OSS 3 XBRL/CIMS class="gl-link"
</a> [class.hidden]="!matchesRbiSearch('OSS 3 XBRL/CIMS')"
<a class="gl-link" [class.hidden]="!matchesRbiSearch('OSS 4/OSS 5/OSS 6')" (click)="rbiMenuOpen = false"> routerLink="/rbi/oss3"
<fa-icon icon="file-alt" class="gl-icon"></fa-icon> OSS 4 / OSS 5 / OSS 6 (click)="rbiMenuOpen = false"
</a> >
<a class="gl-link" [class.hidden]="!matchesRbiSearch('OSS 7')" (click)="rbiMenuOpen = false"> <fa-icon icon="file-alt" class="gl-icon" style="color: #0891b2"></fa-icon> OSS 3 XBRL/CIMS
<fa-icon icon="file-alt" class="gl-icon"></fa-icon> OSS 7
</a> </a>
</div> </div>
<!-- CIMS / XBRL Returns --> <!-- CIMS / XBRL Returns -->
@@ -1819,6 +1971,161 @@
</div> </div>
} }
<!-- Investment (Treasury) Mega Menu -->
@if (investmentMenuOpen) {
<div class="gl-backdrop" (click)="investmentMenuOpen = false"></div>
<div class="gl-mega-menu rbi-mega-menu">
<div class="gl-mega-menu-header">
<fa-icon icon="chart-line" class="gl-mega-menu-header-icon"></fa-icon>
<span>Investment</span>
</div>
<input
type="text"
class="gl-search"
placeholder="Search Investment..."
(input)="investmentSearch = $any($event.target).value"
/>
<div class="rbi-columns">
<!-- Dashboard -->
<div class="gl-group">
<div class="gl-group-title">Dashboard</div>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Investment Dashboard')"
routerLink="/investment/dashboard"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="chart-pie" class="gl-icon"></fa-icon> Portfolio Dashboard
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Due Date Diary for All Investment')"
routerLink="/investment/dashboard"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="calendar-check" class="gl-icon"></fa-icon> Due Date Diary for All Investment
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Bucket Wise Investment')"
routerLink="/investment/reports"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="layer-group" class="gl-icon"></fa-icon> Bucket Wise Investment
</a>
</div>
<!-- Entry -->
<div class="gl-group">
<div class="gl-group-title">Entry</div>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('FD Investment')"
routerLink="/investment/fd"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="piggy-bank" class="gl-icon"></fa-icon> FD Investment
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Govt Security / Non-SLR / Bond / Mutual Fund')"
routerLink="/investment/bonds"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="university" class="gl-icon"></fa-icon> Govt Security / Non-SLR / Bond / Mutual Fund
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('SLR and Non SLR Investment Report')"
routerLink="/investment/bonds"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="balance-scale" class="gl-icon"></fa-icon> SLR and Non SLR Investment Report
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Share Entry')"
routerLink="/investment/share"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="chart-line" class="gl-icon"></fa-icon> Share Entry
</a>
</div>
<!-- Masters -->
<div class="gl-group">
<div class="gl-group-title">Masters</div>
<a
class="gl-link"
[class.hidden]="
!matchesInvestmentSearch(
'Bank Party Script Broker SubType Control Parameter Daily Script LIEN Reason Mutual Fund Product SGL Bank Script Market Detail Masters'
)
"
routerLink="/investment/masters"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="cogs" class="gl-icon"></fa-icon> Bank/Party, Script, Broker &amp; Other Masters
</a>
</div>
<!-- Interest -->
<div class="gl-group">
<div class="gl-group-title">Interest</div>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('FD Interest Calculation')"
routerLink="/investment/interest"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="calculator" class="gl-icon"></fa-icon> FD Interest Calculation
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Govt Bond Interest Calculation')"
routerLink="/investment/interest"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="calculator" class="gl-icon"></fa-icon> Govt./Bond Int. Calculation
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Government Bond Int Register FD Interest Register FD Register')"
routerLink="/investment/interest"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="list-alt" class="gl-icon"></fa-icon> Bond Int / FD Int / FD Registers
</a>
</div>
<!-- Reports -->
<div class="gl-group">
<div class="gl-group-title">Reports</div>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Balance Ledger Maturity Investment Reports')"
routerLink="/investment/reports"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="file-invoice" class="gl-icon"></fa-icon> Balance / Ledger / Maturity Reports
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Total Int Received & Receivable Report')"
routerLink="/investment/reports"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="hand-holding-usd" class="gl-icon"></fa-icon> Total Int Received &amp; Receivable Report
</a>
<a
class="gl-link"
[class.hidden]="!matchesInvestmentSearch('Investment Portfolio')"
routerLink="/investment/reports"
(click)="investmentMenuOpen = false"
>
<fa-icon icon="briefcase" class="gl-icon"></fa-icon> Investment Portfolio
</a>
</div>
</div>
</div>
}
<!-- Progress Bar --> <!-- Progress Bar -->
@if (progressBarMode !== 'none') { @if (progressBarMode !== 'none') {
<div> <div>
+41
View File
@@ -677,6 +677,26 @@ $gray-700: #334155;
opacity: 0.7; opacity: 0.7;
} }
// Marks a `mat-menu-item` as actually wired to a working screen/dialog (vs a still-unwired
// placeholder) — same "green dot" convention as .gl-link--live, positioned absolutely since
// mat-menu-item's internal layout isn't a plain flex row we control directly.
[mat-menu-item].menu-item-live {
position: relative;
&::after {
content: '';
position: absolute;
right: 14px;
top: 50%;
transform: translateY(-50%);
width: 6px;
height: 6px;
border-radius: 50%;
background: #16a34a;
box-shadow: 0 0 0 2px rgb(22 163 74 / 15%);
}
}
// ===== Nav Dropdown Menus ===== // ===== Nav Dropdown Menus =====
::ng-deep .nav-dropdown { ::ng-deep .nav-dropdown {
border-radius: 8px !important; border-radius: 8px !important;
@@ -729,6 +749,13 @@ $gray-700: #334155;
} }
} }
/* NPA Mega Panel — 4 columns (Reports / Analysis / Classification / Recovery Management) */
.npa-grid {
grid-template-columns: repeat(4, minmax(200px, 1fr));
min-width: 880px;
max-width: 96vw;
}
/* Reconciliation Mega Panel — 5 columns, teal accent to match the icon palette */ /* Reconciliation Mega Panel — 5 columns, teal accent to match the icon palette */
.reconciliation-grid { .reconciliation-grid {
grid-template-columns: repeat(5, minmax(190px, 1fr)); grid-template-columns: repeat(5, minmax(190px, 1fr));
@@ -856,6 +883,20 @@ $gray-700: #334155;
} }
} }
// Marks a menu link as actually wired to a working screen/dialog (vs a still-unwired
// placeholder) — a small green dot at the end of the row, so a reviewer can tell at a glance
// which items in a mega-menu are functional without having to click every one of them.
.gl-link--live::after {
content: '';
width: 6px;
height: 6px;
margin-left: auto;
flex-shrink: 0;
border-radius: 50%;
background: #16a34a;
box-shadow: 0 0 0 2px rgb(22 163 74 / 15%);
}
/* RBI Mega Menu */ /* RBI Mega Menu */
.rbi-mega-menu { .rbi-mega-menu {
width: 1100px; width: 1100px;
+33 -2
View File
@@ -98,6 +98,10 @@ export class ShellComponent implements OnInit, OnDestroy {
rbiMenuOpen = false; rbiMenuOpen = false;
rbiSearch = ''; rbiSearch = '';
/** Investment (Treasury) mega menu state */
investmentMenuOpen = false;
investmentSearch = '';
/* Live KPI ticker — markup is static inside the template; the marquee /* Live KPI ticker — markup is static inside the template; the marquee
animation, LIVE badge, and pause-on-hover handle the live feel. */ animation, LIVE badge, and pause-on-hover handle the live feel. */
@@ -116,6 +120,11 @@ export class ShellComponent implements OnInit, OnDestroy {
return label.toLowerCase().includes(this.rbiSearch.toLowerCase()); return label.toLowerCase().includes(this.rbiSearch.toLowerCase());
} }
matchesInvestmentSearch(label: string): boolean {
if (!this.investmentSearch) return true;
return label.toLowerCase().includes(this.investmentSearch.toLowerCase());
}
/** Route for a facility entry in the Account Facilities hover dropdown — only "Cheque Book" has a /** Route for a facility entry in the Account Facilities hover dropdown — only "Cheque Book" has a
* dedicated action page today; every other facility falls back to the existing overview page. */ * dedicated action page today; every other facility falls back to the existing overview page. */
facilityRoute(label: string): string[] { facilityRoute(label: string): string[] {
@@ -242,7 +251,7 @@ export class ShellComponent implements OnInit, OnDestroy {
* GL Wise DR/CR / Misc Expense Ledger). Initial report selected via menu link. * GL Wise DR/CR / Misc Expense Ledger). Initial report selected via menu link.
*/ */
async openAccountingReportsDialog( async openAccountingReportsDialog(
initialReport: 'PNL' | 'BALANCE-SHEET' | 'COMPARATIVE-BS' | 'GL-DR-CR' | 'MISC-EXP' = 'PNL' initialReport: 'PNL' | 'BALANCE-SHEET' | 'COMPARATIVE-BS' | 'CONTINGENT-LIAB' | 'GL-DR-CR' | 'MISC-EXP' = 'PNL'
): Promise<void> { ): Promise<void> {
const { AccountingReportsDialogComponent } = const { AccountingReportsDialogComponent } =
await import('../../home/dashboard/accounting-reports-dialog/accounting-reports-dialog.component'); await import('../../home/dashboard/accounting-reports-dialog/accounting-reports-dialog.component');
@@ -285,7 +294,9 @@ export class ShellComponent implements OnInit, OnDestroy {
* is selected based on the menu link the user clicked; user can switch between * is selected based on the menu link the user clicked; user can switch between
* forms via the form-pill selector inside the dialog. * forms via the form-pill selector inside the dialog.
*/ */
async openCimsXbrlDialog(initialForm: 'OSS-2' | 'PSA' | 'RAL' | 'RCP-UCB' = 'OSS-2'): Promise<void> { async openCimsXbrlDialog(
initialForm: 'OSS-2' | 'PSA' | 'RAL' | 'RCP-UCB' | 'OSS-4' | 'OSS-5' | 'OSS-6' | 'OSS-7' = 'OSS-2'
): Promise<void> {
const { CimsXbrlDialogComponent } = const { CimsXbrlDialogComponent } =
await import('../../home/dashboard/cims-xbrl-dialog/cims-xbrl-dialog.component'); await import('../../home/dashboard/cims-xbrl-dialog/cims-xbrl-dialog.component');
this.dialog.open(CimsXbrlDialogComponent, { this.dialog.open(CimsXbrlDialogComponent, {
@@ -301,6 +312,26 @@ export class ShellComponent implements OnInit, OnDestroy {
}); });
} }
/** Opens the FD / RD Entry dialog under Sub Ledger → Deposits. */
async openFdRdEntryDialog(): Promise<void> {
const { FdRdEntryDialogComponent } =
await import('../../home/dashboard/fd-rd-entry-dialog/fd-rd-entry-dialog.component');
this.dialog.open(FdRdEntryDialogComponent, {
width: '100vw',
height: '100vh',
maxWidth: '100vw',
maxHeight: '100vh',
panelClass: [
'crr-slr-dialog-panel',
'fdrd-fullscreen-panel'
],
autoFocus: false,
disableClose: false,
hasBackdrop: true,
backdropClass: 'fdrd-dlg-backdrop'
});
}
/** /**
* Opens the Asset Liability Management dialog (Form ALM-1). * Opens the Asset Liability Management dialog (Form ALM-1).
* Covers maturity ladder, monthly snapshot, and structural liquidity returns. * Covers maturity ladder, monthly snapshot, and structural liquidity returns.
@@ -266,7 +266,7 @@
<a <a
class="subledger-link" class="subledger-link"
[class.hidden]="!matchesSearch('Cash / Clearing / Transfer')" [class.hidden]="!matchesSearch('Cash / Clearing / Transfer')"
(click)="subLedgerOpen = false" (click)="navigateMenu('/cashier/cash-clearing-transfer-summary'); subLedgerOpen = false"
> >
<fa-icon icon="money-bill" class="subledger-icon"></fa-icon> Cash / Clearing / Transfer <fa-icon icon="money-bill" class="subledger-icon"></fa-icon> Cash / Clearing / Transfer
</a> </a>
@@ -403,17 +403,26 @@
<div class="subledger-columns"> <div class="subledger-columns">
<div class="subledger-group"> <div class="subledger-group">
<div class="subledger-group-title">Financial Statements</div> <div class="subledger-group-title">Financial Statements</div>
<a class="subledger-link" [class.hidden]="!matchesGlSearch('Trial Balance')" (click)="glMenuOpen = false" <a
class="subledger-link"
[class.hidden]="!matchesGlSearch('Trial Balance')"
routerLink="/gl/reports/trial-balance"
(click)="glMenuOpen = false"
><fa-icon icon="balance-scale" class="subledger-icon"></fa-icon> Trial Balance</a ><fa-icon icon="balance-scale" class="subledger-icon"></fa-icon> Trial Balance</a
> >
<a class="subledger-link" [class.hidden]="!matchesGlSearch('Profit and Loss')" (click)="glMenuOpen = false" <a
class="subledger-link"
[class.hidden]="!matchesGlSearch('Profit and Loss')"
routerLink="/gl/reports/profit-and-loss"
(click)="glMenuOpen = false"
><fa-icon icon="chart-line" class="subledger-icon"></fa-icon> Profit and Loss</a ><fa-icon icon="chart-line" class="subledger-icon"></fa-icon> Profit and Loss</a
> >
<a <a
class="subledger-link" class="subledger-link"
[class.hidden]="!matchesGlSearch('Consolidate Balance Sheet')" [class.hidden]="!matchesGlSearch('Consolidated Balance Sheet')"
routerLink="/gl/reports/balance-sheet"
(click)="glMenuOpen = false" (click)="glMenuOpen = false"
><fa-icon icon="file-alt" class="subledger-icon"></fa-icon> Consolidate Balance Sheet</a ><fa-icon icon="file-alt" class="subledger-icon"></fa-icon> Consolidated Balance Sheet</a
> >
</div> </div>
<div class="subledger-group"> <div class="subledger-group">
@@ -448,8 +457,12 @@
(click)="glMenuOpen = false" (click)="glMenuOpen = false"
><fa-icon icon="users" class="subledger-icon"></fa-icon> Client wise Balance Report</a ><fa-icon icon="users" class="subledger-icon"></fa-icon> Client wise Balance Report</a
> >
<a class="subledger-link" [class.hidden]="!matchesGlSearch('Contingent Expense')" (click)="glMenuOpen = false" <a
><fa-icon icon="exclamation-circle" class="subledger-icon"></fa-icon> Contingent Expense</a class="subledger-link"
[class.hidden]="!matchesGlSearch('Contingent Liabilities')"
routerLink="/gl/reports/contingent-liabilities"
(click)="glMenuOpen = false"
><fa-icon icon="exclamation-circle" class="subledger-icon"></fa-icon> Contingent Liabilities</a
> >
<a class="subledger-link" [class.hidden]="!matchesGlSearch('Banker Head Report')" (click)="glMenuOpen = false" <a class="subledger-link" [class.hidden]="!matchesGlSearch('Banker Head Report')" (click)="glMenuOpen = false"
><fa-icon icon="university" class="subledger-icon"></fa-icon> Banker Head Report</a ><fa-icon icon="university" class="subledger-icon"></fa-icon> Banker Head Report</a
@@ -365,6 +365,21 @@
</mat-form-field> </mat-form-field>
</form> </form>
} }
<!-- Compliance / AML Action Triage -->
<div class="compliance-triage" style="margin-top: 16px; padding: 12px; background: #fff8f8; border: 1px dashed #f5c2c2; border-radius: 8px;">
<h4 style="margin: 0 0 8px; font-weight: 600; color: #b91c1c; display: flex; align-items: center; gap: 6px;">
Compliance & AML Triage
</h4>
<div style="display: flex; flex-direction: column; gap: 8px;">
<mat-checkbox [(ngModel)]="flagAsSuspicious" [ngModelOptions]="{standalone: true}">
Flag as suspicious (escalate to STR cases under RBI compliance)
</mat-checkbox>
<mat-checkbox [(ngModel)]="markAsWhitelisted" [ngModelOptions]="{standalone: true}">
Mark as whitelisted (prevent future AML alerts for this account)
</mat-checkbox>
</div>
</div>
} }
<div #lightboxRoot style="display: none"></div> <div #lightboxRoot style="display: none"></div>
@@ -131,6 +131,90 @@ export class ItemDecisionDialogComponent implements OnInit, OnDestroy {
/** 'any' = mode of operation lets any one signer sign (Either/Anyone or Survivor); 'all' = every mandatory signer must sign. */ /** 'any' = mode of operation lets any one signer sign (Either/Anyone or Survivor); 'all' = every mandatory signer must sign. */
signerSelectionMode: 'any' | 'all' = 'any'; signerSelectionMode: 'any' | 'all' = 'any';
manualOverrideChecked = false; manualOverrideChecked = false;
flagAsSuspicious = false;
markAsWhitelisted = false;
handleComplianceActions(): void {
if (this.flagAsSuspicious) {
const existingStrData = localStorage.getItem('fiu_str_cases');
let cases: any[] = [];
if (existingStrData) {
try {
cases = JSON.parse(existingStrData);
} catch (e) {
cases = [];
}
}
const newRef = 101 + cases.length;
const newCase: any = {
reportType: 'STR',
reportRefNo: newRef,
branchCode: this.item.presentingBranchCode || '1',
accountNumber: this.item.accountNo || this.item.accountId || '110001101000838',
txnBranchCode: this.item.presentingBranchCode || '1',
depositOrWithdrawal: 'Withdrawal',
txnId: this.item.id,
txnDate: new Date().toLocaleDateString('en-GB').replace(/\//g, '-'),
txnTime: new Date().toLocaleTimeString('en-US', { hour12: false }),
txnAmount: this.item.amount,
instrumentType: 'Cheque',
instrumentId: this.item.chequeNumber,
nonCustomerRef: '',
relationshipFlag: 'Customer',
thirdPartyPan: '',
declaration: 'NA',
customerName: this.item.clientName || 'UNKNOWN CLIENT',
detectedOn: new Date().toLocaleDateString('en-GB').replace(/\//g, '-'),
flaggedBy: 'CTS Clearing Officer',
riskCategory: 'unusual-pattern',
narrative: `CTS Cheque #${this.item.chequeNumber} for amount ₹${this.item.amount} flagged as suspicious by Clearing Officer during inward presentment review. Action: ${this.mode}. Reason/Notes: ${this.mode === 'RETURN' ? this.returnForm.value.reason : this.passForm.value.note || 'Manual compliance escalation'}`,
status: 'po-review'
};
cases.unshift(newCase);
localStorage.setItem('fiu_str_cases', JSON.stringify(cases));
const storedCtr = localStorage.getItem('fiu_ctr_txns');
if (storedCtr) {
try {
const ctrList = JSON.parse(storedCtr);
const matching = ctrList.find((t: any) => t.accountNumber === newCase.accountNumber);
if (matching) {
matching.complianceStatus = 'SUSPICIOUS';
localStorage.setItem('fiu_ctr_txns', JSON.stringify(ctrList));
}
} catch (e) {}
}
} else if (this.markAsWhitelisted) {
const existingWhitelist = localStorage.getItem('compliance_whitelisted_accounts');
let whitelisted: string[] = [];
if (existingWhitelist) {
try {
whitelisted = JSON.parse(existingWhitelist);
} catch (e) {
whitelisted = [];
}
}
const account = this.item.accountNo || this.item.accountId;
if (account && !whitelisted.includes(account.toString())) {
whitelisted.push(account.toString());
localStorage.setItem('compliance_whitelisted_accounts', JSON.stringify(whitelisted));
}
const storedCtr = localStorage.getItem('fiu_ctr_txns');
if (storedCtr) {
try {
const ctrList = JSON.parse(storedCtr);
const matching = ctrList.find((t: any) => t.accountNumber === (account ? account.toString() : ''));
if (matching) {
matching.complianceStatus = 'WHITELISTED';
localStorage.setItem('fiu_ctr_txns', JSON.stringify(ctrList));
}
} catch (e) {}
}
}
}
/** Every automatic validation rule InwardClearingValidationService already computes, shown so the clerk sees WHY, not just a decision. */ /** Every automatic validation rule InwardClearingValidationService already computes, shown so the clerk sees WHY, not just a decision. */
readonly validationRules: { key: string; label: string; goodWhenTrue: boolean }[] = [ readonly validationRules: { key: string; label: string; goodWhenTrue: boolean }[] = [
@@ -652,6 +736,7 @@ export class ItemDecisionDialogComponent implements OnInit, OnDestroy {
this.ctsService.passInwardItem(this.item.id, payload).subscribe({ this.ctsService.passInwardItem(this.item.id, payload).subscribe({
next: () => { next: () => {
this.busy = false; this.busy = false;
this.handleComplianceActions();
this.notify('Cheque passed'); this.notify('Cheque passed');
this.dialogRef.close({ actioned: true }); this.dialogRef.close({ actioned: true });
}, },
@@ -676,6 +761,7 @@ export class ItemDecisionDialogComponent implements OnInit, OnDestroy {
this.ctsService.returnInwardItem(this.item.id, payload).subscribe({ this.ctsService.returnInwardItem(this.item.id, payload).subscribe({
next: () => { next: () => {
this.busy = false; this.busy = false;
this.handleComplianceActions();
this.notify('Cheque returned'); this.notify('Cheque returned');
this.dialogRef.close({ actioned: true }); this.dialogRef.close({ actioned: true });
}, },
+3 -3
View File
@@ -81,7 +81,7 @@ export interface DeafEligibleAccount {
/** Form I — Dec 2025 cycle */ /** Form I — Dec 2025 cycle */
export const FORM_I: DeafForm = { export const FORM_I: DeafForm = {
bankName: 'Bharat Urban Bank Ltd, Mumbai Main Branch', bankName: 'CBSNexora Bank Ltd, Mumbai Main Branch',
bankDeafCode: '1100', bankDeafCode: '1100',
remittedThroughSponsor: 'Y', remittedThroughSponsor: 'Y',
sponsorBankName: 'State Bank of India', sponsorBankName: 'State Bank of India',
@@ -170,7 +170,7 @@ export const FORM_I: DeafForm = {
/** Form II — Jan 2026 (head office consolidated) */ /** Form II — Jan 2026 (head office consolidated) */
export const FORM_II: DeafForm = { export const FORM_II: DeafForm = {
bankName: 'Bharat Urban Bank Ltd, Head Office', bankName: 'CBSNexora Bank Ltd, Head Office',
bankDeafCode: '1100', bankDeafCode: '1100',
remittedThroughSponsor: 'Y', remittedThroughSponsor: 'Y',
sponsorBankName: 'State Bank of India', sponsorBankName: 'State Bank of India',
@@ -271,7 +271,7 @@ export const REFUND_CLAIMS: {
auditor: string; auditor: string;
rows: DeafClaim[]; rows: DeafClaim[];
} = { } = {
bankName: 'Bharat Urban Bank Ltd', bankName: 'CBSNexora Bank Ltd',
bankDeafCode: '1100', bankDeafCode: '1100',
currentAcWithRbi: '03010200099001', currentAcWithRbi: '03010200099001',
sponsorBank: 'State Bank of India', sponsorBank: 'State Bank of India',
+1 -1
View File
@@ -53,7 +53,7 @@ export interface SahayDepositor {
} }
export const DICGC_BANK = { export const DICGC_BANK = {
name: 'Bharat Urban Bank Ltd', name: 'CBSNexora Bank Ltd',
branch: 'Head Office', branch: 'Head Office',
reportAsOn: '29-01-2026', reportAsOn: '29-01-2026',
printDate: '29-01-2026 04:19 PM', printDate: '29-01-2026 04:19 PM',
+732 -300
View File
File diff suppressed because it is too large Load Diff
+653 -93
View File
@@ -14,12 +14,25 @@
<div> <div>
<h2 class="fiu-head-t">Financial Intelligence Unit – India (FIU-IND)</h2> <h2 class="fiu-head-t">Financial Intelligence Unit – India (FIU-IND)</h2>
<div class="fiu-head-s"> <div class="fiu-head-s">
{{ bank.name }} &middot; {{ bank.branch }} &middot; Reporting Month <strong>{{ bank.reportingMonth }}</strong> {{ bank.name }} &middot; {{ scopeName }} &middot; Reporting Month <strong>{{ bank.reportingMonth }}</strong>
&middot; PMLA 2002 / FINnet 2.0 &middot; PMLA 2002 / FINnet 2.0
</div> </div>
</div> </div>
</div> </div>
<div class="fiu-head-meta"> <div class="fiu-head-meta">
<div>
<span class="fiu-meta-l">Branch</span>
@if (isHeadOffice) {
<select class="fiu-inp" [ngModel]="branchFilter" (ngModelChange)="setBranch($event)">
<option value="">All Branches</option>
@for (b of branches; track b.code) {
<option [value]="b.code">{{ b.name }}</option>
}
</select>
} @else {
<span class="fiu-meta-v">{{ scopeName }}</span>
}
</div>
<div> <div>
<span class="fiu-meta-l">Principal Officer</span><span class="fiu-meta-v">{{ bank.principalOfficer }}</span> <span class="fiu-meta-l">Principal Officer</span><span class="fiu-meta-v">{{ bank.principalOfficer }}</span>
</div> </div>
@@ -71,17 +84,19 @@
<div class="fiu-kpi fiu-kpi--amber"> <div class="fiu-kpi fiu-kpi--amber">
<div class="fiu-kpi-ic"><fa-icon icon="exclamation-triangle"></fa-icon></div> <div class="fiu-kpi-ic"><fa-icon icon="exclamation-triangle"></fa-icon></div>
<div> <div>
<div class="fiu-kpi-n">{{ pendingStr | number }}</div> <div class="fiu-kpi-n">{{ liveStrPending | number }}</div>
<div class="fiu-kpi-l">STR Pending</div> <div class="fiu-kpi-l">STR Pending</div>
<div class="fiu-kpi-sub">draft / PO review</div> <div class="fiu-kpi-sub">
{{ liveStrOpen }} to investigate &middot; {{ liveStrAwaitingFiling }} awaiting filing
</div>
</div> </div>
</div> </div>
<div class="fiu-kpi fiu-kpi--green"> <div class="fiu-kpi fiu-kpi--green">
<div class="fiu-kpi-ic"><fa-icon icon="check-circle"></fa-icon></div> <div class="fiu-kpi-ic"><fa-icon icon="check-circle"></fa-icon></div>
<div> <div>
<div class="fiu-kpi-n">{{ filedStr | number }}</div> <div class="fiu-kpi-n">{{ liveStrFiled | number }}</div>
<div class="fiu-kpi-l">STR Filed</div> <div class="fiu-kpi-l">STR Filed</div>
<div class="fiu-kpi-sub">acknowledged by FIU</div> <div class="fiu-kpi-sub">{{ liveStrCleared }} concluded clear</div>
</div> </div>
</div> </div>
<div class="fiu-kpi fiu-kpi--purple"> <div class="fiu-kpi fiu-kpi--purple">
@@ -94,6 +109,52 @@
</div> </div>
</div> </div>
<!-- WHEN TO REPORT — the five PMLA obligations -->
<div class="ob-block">
<div class="ob-head">
<div>
<h3 class="ob-title"><fa-icon icon="gavel"></fa-icon> When to report to FIU-IND</h3>
<p class="ob-sub">
The five reports a reporting entity owes under the Prevention of Money Laundering Act. All are filed
electronically through the FINnet 2.0 portal.
</p>
</div>
</div>
<div class="ob-grid">
@for (o of obligations; track o.code) {
<div class="ob-card" [class.ob-card--off]="!o.handled">
<div class="ob-card-h">
<fa-icon [icon]="o.icon" class="ob-ic"></fa-icon>
<span class="ob-code">{{ o.code }}</span>
<span class="ob-name">{{ o.name }}</span>
@if (o.handled) {
<span class="ob-flag ob-flag--on">Filed here</span>
} @else {
<span class="ob-flag">Tracked</span>
}
</div>
<div class="ob-row">
<label>Report when</label><span>{{ o.trigger }}</span>
</div>
<div class="ob-row">
<label>Deadline</label><span class="ob-due">{{ o.deadline }}</span>
</div>
<div class="ob-note">{{ o.note }}</div>
@if (o.code === 'CTR') {
<button class="dc-btn" (click)="showTab('ctr')">
<fa-icon icon="external-link-alt"></fa-icon> Open CTR
</button>
} @else if (o.code === 'STR') {
<button class="dc-btn" (click)="showTab('str')">
<fa-icon icon="external-link-alt"></fa-icon> Open STR
</button>
}
</div>
}
</div>
</div>
<!-- Compliance cards --> <!-- Compliance cards -->
<div class="fiu-compliance"> <div class="fiu-compliance">
<div class="dc-card"> <div class="dc-card">
@@ -112,7 +173,12 @@
</div> </div>
<div class="dc-meta">Filing window: <strong>within 7 days of detection</strong></div> <div class="dc-meta">Filing window: <strong>within 7 days of detection</strong></div>
<div class="dc-meta"> <div class="dc-meta">
Pending: <strong>{{ pendingStr }}</strong> &middot; Filed: <strong>{{ filedStr }}</strong> To investigate: <strong>{{ liveStrOpen }}</strong> &middot; Awaiting filing:
<strong>{{ liveStrAwaitingFiling }}</strong>
</div>
<div class="dc-meta">
Filed: <strong>{{ liveStrFiled }}</strong> &middot; Concluded clear:
<strong>{{ liveStrCleared }}</strong>
</div> </div>
<button class="dc-btn" (click)="showTab('str')"><fa-icon icon="external-link-alt"></fa-icon> Open</button> <button class="dc-btn" (click)="showTab('str')"><fa-icon icon="external-link-alt"></fa-icon> Open</button>
</div> </div>
@@ -129,91 +195,105 @@
<!-- CTR --> <!-- CTR -->
@if (activeTab === 'ctr') { @if (activeTab === 'ctr') {
<div class="fiu-section"> <div class="fiu-section">
<div class="fiu-form-meta"> <!-- FINNET FILE SEQUENCE — the CTR submission, in prescribed order -->
<div class="fiu-form-title"> <div class="seq-block">
<h3>CTR — Cash Transaction Report</h3> <div class="fiu-form-meta">
<p> <div class="fiu-form-title">
All cash transactions ≥ &#8377;{{ bank.cashThreshold | number }} (single or aggregate per month per account) <h3>CTR Submission Files — FINnet 2.0</h3>
</p> <p>
The CTR is built in this order: the account is described first, then who is behind it, then the two
transaction files. Every grid below is the exact content of its CSV. The customer cards (KC1 / KC2) travel
with the same bundle and are worked on the Customer Cards tab.
</p>
</div>
<button class="fiu-btn fiu-btn-xls" (click)="exportAll()">
<fa-icon icon="file-csv"></fa-icon> Download full bundle
</button>
</div> </div>
<button class="fiu-btn fiu-btn-csv" (click)="exportTc2()">
<fa-icon icon="file-csv"></fa-icon> Download TC2.csv
</button>
</div>
<div class="fiu-filters"> <!-- Scope: these controls decide which transactions the six files carry. -->
<div class="fiu-filter"> <div class="fiu-filters">
<label>Type</label> <div class="fiu-filter">
<select class="fiu-inp" [(ngModel)]="ctrFilterMode"> <label>Type</label>
<option value="">All</option> <select class="fiu-inp" [(ngModel)]="ctrFilterMode">
<option value="Deposit">Deposit</option> <option value="">All</option>
<option value="Withdrawal">Withdrawal</option> <option value="Deposit">Deposit</option>
</select> <option value="Withdrawal">Withdrawal</option>
</select>
</div>
<div class="fiu-filter">
<label>Account contains</label>
<input class="fiu-inp" type="text" [(ngModel)]="ctrFilterAccount" placeholder="A/c partial" />
</div>
<div class="fiu-filter">
<label>Min Amount (&#8377;)</label>
<input class="fiu-inp" type="number" [(ngModel)]="ctrFilterMinAmount" placeholder="0" />
</div>
<button class="fiu-btn fiu-btn-g" (click)="resetCtrFilters()">Reset</button>
</div> </div>
<div class="fiu-filter">
<label>Account contains</label>
<input class="fiu-inp" type="text" [(ngModel)]="ctrFilterAccount" placeholder="A/c partial" />
</div>
<div class="fiu-filter">
<label>Min Amount (&#8377;)</label>
<input class="fiu-inp" type="number" [(ngModel)]="ctrFilterMinAmount" placeholder="0" />
</div>
<button class="fiu-btn fiu-btn-g" (click)="resetCtrFilters()">Reset</button>
</div>
<div class="fiu-tbl-wrap"> <!-- Step rail -->
<table class="fiu-tbl"> <div class="seq-rail">
<thead> @for (f of finnetSequence; track f.key) {
<tr> <button class="seq-step" [class.active]="activeFinnetFile === f.key" (click)="showFinnetFile(f.key)">
<th class="ta-c">Ref</th> <span class="seq-n">{{ f.step }}</span>
<th>Account</th> <span class="seq-txt">
<th>Customer</th> <strong>{{ f.name }}</strong>
<th class="ta-c">Type</th> <em>{{ f.table.rows.length }} {{ f.table.rows.length === 1 ? 'row' : 'rows' }}</em>
<th>Date / Time</th> </span>
<th class="ta-r">Amount</th> </button>
<th>Instrument</th> @if (!$last) {
<th>Branch</th> <fa-icon icon="chevron-right" class="seq-arrow"></fa-icon>
<th class="ta-c">Relationship</th>
</tr>
</thead>
<tbody>
@for (t of filteredCtr; track t.txnId) {
<tr>
<td class="ta-c">{{ t.reportRefNo }}</td>
<td class="mono">{{ t.accountNumber }}</td>
<td>{{ t.customerName }}</td>
<td class="ta-c">
<span
class="dir-pill"
[class.deposit]="t.depositOrWithdrawal === 'Deposit'"
[class.withdrawal]="t.depositOrWithdrawal === 'Withdrawal'"
>
{{ t.depositOrWithdrawal }}
</span>
</td>
<td>
{{ t.txnDate }} <span class="muted">{{ t.txnTime }}</span>
</td>
<td class="ta-r mono">
<strong>&#8377;{{ t.txnAmount | number: '1.0-0' }}</strong>
</td>
<td>
{{ t.instrumentType }} <span class="muted">{{ t.instrumentId }}</span>
</td>
<td class="mono">{{ t.branchCode }}</td>
<td class="ta-c">
<span class="rel-pill" [class.non-cust]="t.relationshipFlag === 'Non-Customer'">{{
t.relationshipFlag
}}</span>
</td>
</tr>
} @empty {
<tr>
<td colspan="9" class="fiu-empty">No transactions match the filters.</td>
</tr>
} }
</tbody> }
</table> </div>
<!-- Open file -->
<div class="seq-panel">
<div class="seq-panel-h">
<div>
<h4>Step {{ openFinnetFile.step }} — {{ openFinnetFile.title }}</h4>
<p>{{ openFinnetFile.purpose }}</p>
</div>
<button class="fiu-btn fiu-btn-csv" (click)="downloadOpenFinnetFile()">
<fa-icon icon="file-csv"></fa-icon> {{ openFinnetFile.name }}.csv
</button>
</div>
<div class="seq-tbl-wrap">
<table class="seq-tbl">
<thead>
<tr>
<th class="seq-rownum">#</th>
@for (h of openFinnetFile.table.headers; track $index) {
<th>{{ h }}</th>
}
</tr>
</thead>
<tbody>
@for (r of openFinnetFile.table.rows; track $index) {
<tr>
<td class="seq-rownum">{{ $index + 1 }}</td>
@for (c of r; track $index) {
<td>{{ c }}</td>
}
</tr>
} @empty {
<tr>
<td [attr.colspan]="openFinnetFile.table.headers.length + 1" class="seq-empty">
@if (openFinnetFile.key === 'tc1') {
No ATM or card transactions match the current scope. When the bank books none at all, TC1 is
still submitted as a header-only file — that is what FIU-IND expects.
} @else {
No rows for the current filters.
}
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div> </div>
</div> </div>
} }
@@ -221,9 +301,275 @@
<!-- STR --> <!-- STR -->
@if (activeTab === 'str') { @if (activeTab === 'str') {
<div class="fiu-section"> <div class="fiu-section">
<!-- LIVE: suspicious AML alerts awaiting AML Officer review (Structuring, PEP, etc.) -->
<div class="fiu-form-meta"> <div class="fiu-form-meta">
<div class="fiu-form-title"> <div class="fiu-form-title">
<h3>STR — Suspicious Transaction Report</h3> <h3>Live AML Alerts (Awaiting Triage)</h3>
<p>Flagged by the monitoring engine for suspicious behavioral patterns — triage and whitelist or escalate</p>
</div>
</div>
<div class="fiu-tbl-wrap">
<table class="fiu-tbl">
<thead>
<tr>
<th>ID</th>
<th>Client</th>
<th>Type</th>
<th>Rule</th>
<th class="ta-r">Amount</th>
<th>Raised On</th>
<th>Status</th>
<th class="ta-c">Routes To</th>
<th>Notes</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@for (alert of amlSuspiciousAlerts; track alert.id) {
<tr>
<td>{{ alert.id }}</td>
<td>{{ alert.clientDisplayName }}</td>
<td>{{ alert.transactionType }}</td>
<td>{{ alert.ruleCode }} &mdash; {{ alert.ruleDescription }}</td>
<td class="ta-r mono">&#8377;{{ alert.amount | number: '1.0-0' }}</td>
<td>{{ alert.raisedOn | date: 'medium' }}</td>
<td>
<span [class]="amlStatusClass(alert.status)">{{ alert.status }}</span>
</td>
<td class="ta-c">
<span [class]="alertRouteClass(alert.status, false)">{{ alertRouteLabel(alert.status, false) }}</span>
</td>
<td>
@if (alert.status === 'RAISED' || alert.status === 'UNDER_REVIEW') {
<input
type="text"
class="fiu-inp"
placeholder="Review notes"
[(ngModel)]="amlReviewNotes[alert.id]"
/>
} @else {
<span class="muted">{{ alert.reviewNotes }}</span>
}
</td>
<td>
@if (alert.status === 'RAISED' || alert.status === 'UNDER_REVIEW') {
<div class="fiu-action-group" *mifosxHasPermission="'REVIEW_AML_ALERT'">
<button class="fiu-btn fiu-btn-g" (click)="whitelistAlert(alert)">Whitelist</button>
<button class="fiu-btn fiu-btn-xml" (click)="escalateAlert(alert)">Escalate</button>
</div>
}
</td>
</tr>
} @empty {
<tr>
<td colspan="10" class="fiu-empty">No suspicious behavioral alerts.</td>
</tr>
}
</tbody>
</table>
</div>
<p class="fiu-tbl-legend">
<span class="report-pill report-pending">Pending</span> awaiting Whitelist/Escalate decision &middot;
<span class="report-pill report-cleared">Cleared</span> whitelisted — no report filed &middot;
<span class="report-pill report-str">→ STR</span> escalated to Principal Officer as an STR case
</p>
<hr style="border: 0; border-top: 1px solid var(--f-g200); margin: 8px 0" />
<!-- LIVE: STR cases with full Principal Officer actions -->
<div class="fiu-form-meta">
<div class="fiu-form-title">
<h3>Live STR Cases</h3>
<p>
Escalated by an AML Officer; Principal Officer investigates, concludes and files with FIU-IND within 7
working days
</p>
</div>
</div>
<div class="fiu-tbl-wrap">
<table class="fiu-tbl">
<thead>
<tr>
<th>ID</th>
<th>Client</th>
<th class="ta-c">Cumulative Cases</th>
<th>Assigned PO</th>
<th>Conclusion</th>
<th>FIU Due Date</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@for (sc of amlStrCases; track sc.id) {
<tr [class.selected-row]="selectedStrCase?.id === sc.id">
<td>{{ sc.id }}</td>
<td>{{ sc.clientDisplayName }}</td>
<td class="ta-c" [class.escalation-warning]="sc.cumulativeStrCaseCountForClient >= 3">
{{ sc.cumulativeStrCaseCountForClient }}
</td>
<td>{{ sc.assignedPoUsername || '—' }}</td>
<td>{{ sc.conclusion || '—' }}</td>
<td>{{ sc.fiuDueDate || '—' }}</td>
<td>
<span [class]="amlStatusClass(sc.status)">{{ sc.status }}</span>
</td>
<td><button class="fiu-btn fiu-btn-g" (click)="selectStrCase(sc)">Investigate</button></td>
</tr>
} @empty {
<tr>
<td colspan="8" class="fiu-empty">No STR cases yet.</td>
</tr>
}
</tbody>
</table>
</div>
@if (selectedStrCase) {
<div class="str-case-detail">
<div class="fiu-form-meta">
<div class="fiu-form-title">
<h3>STR Case #{{ selectedStrCase.id }} — {{ selectedStrCase.clientDisplayName }}</h3>
<p>
Alert #{{ selectedStrCase.alertId }} &middot;
{{ selectedStrCase.cumulativeStrCaseCountForClient }} cumulative STR case(s) for this client
@if (selectedStrCase.cumulativeStrCaseCountForClient >= 3) {
<span class="escalation-badge">Risk category auto-escalated</span>
}
</p>
</div>
<button class="fiu-btn fiu-btn-g" (click)="closeStrCaseDetail()">Close</button>
</div>
<div
class="case-outcome"
[class.case-outcome--clear]="selectedStrCase.status === 'CONCLUDED_CLEAR'"
[class.case-outcome--suspicious]="
selectedStrCase.status === 'CONCLUDED_SUSPICIOUS' || selectedStrCase.status === 'FILED'
"
>
<span [class]="amlStatusClass(selectedStrCase.status)">{{ selectedStrCase.status }}</span>
<span>{{ strCaseOutcome(selectedStrCase) }}</span>
</div>
<div class="case-form" *mifosxHasPermission="'CONCLUDE_AML_STR'">
<div class="form-row">
<label for="fiuInvestigationNotes">Investigation notes (source-of-transaction history reviewed)</label>
<textarea id="fiuInvestigationNotes" rows="3" [(ngModel)]="concludeInvestigationNotes"></textarea>
</div>
<div class="form-row">
<label for="fiuSourceOfFundsNotes">Source-of-funds notes</label>
<textarea id="fiuSourceOfFundsNotes" rows="2" [(ngModel)]="concludeSourceOfFundsNotes"></textarea>
</div>
<!-- Verification checklist — the verdict is derived, not chosen. -->
<div class="checklist">
<div class="checklist-head">
<span>Principal Officer verification — mark each point as found</span>
<span class="checklist-progress" [class.done]="allAnswered">
{{ answeredCount }} / {{ strChecklist.length }} answered
</span>
</div>
<table class="checklist-tbl">
<thead>
<tr>
<th>Verification point</th>
<th class="ta-c col-yes">Genuine</th>
<th class="ta-c col-no">Not satisfied</th>
</tr>
</thead>
<tbody>
@for (item of strChecklist; track item.key) {
<tr
[class.row-yes]="strFindings[item.key] === true"
[class.row-no]="strFindings[item.key] === false"
[class.row-pending]="strFindings[item.key] === null"
>
<td>
<div class="chk-label">{{ item.label }}</div>
<div class="chk-hint">{{ item.hint }}</div>
</td>
<td class="ta-c">
<button
type="button"
class="chk-box chk-box--yes"
[class.on]="strFindings[item.key] === true"
[attr.aria-pressed]="strFindings[item.key] === true"
[attr.aria-label]="'Mark ' + item.label + ' as genuine'"
(click)="setFinding(item.key, true)"
>
<fa-icon icon="check-circle"></fa-icon>
</button>
</td>
<td class="ta-c">
<button
type="button"
class="chk-box chk-box--no"
[class.on]="strFindings[item.key] === false"
[attr.aria-pressed]="strFindings[item.key] === false"
[attr.aria-label]="'Mark ' + item.label + ' as not satisfied'"
(click)="setFinding(item.key, false)"
>
<fa-icon icon="exclamation-triangle"></fa-icon>
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
<!-- Derived verdict -->
<div
class="verdict"
[class.verdict--clear]="allAnswered && derivedConclusion === 'NOT_SUSPICIOUS'"
[class.verdict--suspicious]="allAnswered && derivedConclusion === 'SUSPICIOUS'"
>
@if (!allAnswered) {
<fa-icon icon="info-circle"></fa-icon>
<span>
Answer every verification point to determine the outcome —
{{ strChecklist.length - answeredCount }} still pending.
</span>
} @else if (derivedConclusion === 'NOT_SUSPICIOUS') {
<fa-icon icon="check-circle"></fa-icon>
<span>
<strong>Not suspicious.</strong> All {{ strChecklist.length }} points found genuine — the case will be
closed and nothing filed with FIU-IND.
</span>
} @else {
<fa-icon icon="exclamation-triangle"></fa-icon>
<span>
<strong>Suspicious — STR must be filed.</strong>
{{ failedFindings.length }} of {{ strChecklist.length }} points not satisfied:
{{ failedFindings[0].label }}
@if (failedFindings.length > 1) {
<span> and {{ failedFindings.length - 1 }} more</span>
}
.
</span>
}
</div>
<button class="fiu-btn fiu-btn-xml" [disabled]="!allAnswered" (click)="concludeStrCase()">
Conclude as
{{ allAnswered ? (derivedConclusion === 'SUSPICIOUS' ? 'Suspicious' : 'Not Suspicious') : '…' }}
</button>
@if (selectedStrCase.status === 'CONCLUDED_SUSPICIOUS') {
<div class="file-str-row">
<label for="fiuFileReferenceNo">FIU-IND acknowledgement / reference number</label>
<input id="fiuFileReferenceNo" class="fiu-inp" type="text" [(ngModel)]="fileReferenceNo" />
<button class="fiu-btn fiu-btn-xml" (click)="fileStrCase()">Mark STR Filed</button>
</div>
}
</div>
</div>
}
<!-- FINnet export template (separate concern — STR XML file-format generation) -->
<div class="fiu-form-meta">
<div class="fiu-form-title">
<h3>FINnet STR XML Export Template</h3>
<p>Detected by AML rules engine + branch compliance officers; filed within 7 days</p> <p>Detected by AML rules engine + branch compliance officers; filed within 7 days</p>
</div> </div>
<button class="fiu-btn fiu-btn-xml" (click)="exportStrXml()"> <button class="fiu-btn fiu-btn-xml" (click)="exportStrXml()">
@@ -238,8 +584,9 @@
<option value="">All</option> <option value="">All</option>
<option value="draft">Draft</option> <option value="draft">Draft</option>
<option value="po-review">PO Review</option> <option value="po-review">PO Review</option>
<option value="awaiting-filing">Awaiting Filing</option>
<option value="filed">Filed</option> <option value="filed">Filed</option>
<option value="rejected">Rejected</option> <option value="rejected">Closed — Clean</option>
</select> </select>
</div> </div>
<div class="fiu-filter"> <div class="fiu-filter">
@@ -259,7 +606,12 @@
<div class="fiu-str-list"> <div class="fiu-str-list">
@for (s of filteredStr; track s.reportRefNo) { @for (s of filteredStr; track s.reportRefNo) {
<div class="str-card" [class.str-card--filed]="s.status === 'filed'"> <div
class="str-card"
[id]="'str-card-' + s.reportRefNo"
[class.str-card--filed]="s.status === 'filed'"
[class.str-card--highlight]="highlightedStrRef === s.reportRefNo"
>
<div class="str-card-h"> <div class="str-card-h">
<div class="str-card-id"> <div class="str-card-id">
<span class="str-ref">STR-{{ s.reportRefNo }}</span> <span class="str-ref">STR-{{ s.reportRefNo }}</span>
@@ -291,6 +643,9 @@
<div> <div>
<label>Instrument</label><span>{{ s.instrumentType }} {{ s.instrumentId }}</span> <label>Instrument</label><span>{{ s.instrumentType }} {{ s.instrumentId }}</span>
</div> </div>
<div>
<label>Branch</label><span class="mono">{{ s.branchCode }} {{ branchNameFor(s.branchCode) }}</span>
</div>
</div> </div>
<div class="str-narrative"> <div class="str-narrative">
<label>Narrative</label> <label>Narrative</label>
@@ -302,6 +657,208 @@
<p>{{ s.poRemarks }}</p> <p>{{ s.poRemarks }}</p>
</div> </div>
} }
@if (s.poFinding) {
<div class="str-finding" [class.str-finding--suspicious]="s.poFinding === 'SUSPICIOUS'">
<label>
<fa-icon [icon]="s.poFinding === 'CLEAN' ? 'check-circle' : 'exclamation-triangle'"></fa-icon>
Principal Officer Finding
</label>
<p>{{ poFindingLabel(s.poFinding) }}</p>
</div>
}
<!-- Concluded suspicious but not yet submitted to FIU-IND -->
@if (s.status === 'awaiting-filing') {
<div class="str-filing" *mifosxHasPermission="'CONCLUDE_AML_STR'">
<label>
<fa-icon icon="exclamation-triangle"></fa-icon> Awaiting submission to FIU-IND — due within 7 days
of {{ s.detectedOn }}
</label>
<p class="filing-hint">
Generate the FINnet STR XML, upload it on the FIU-IND portal under
{{ bank.principalOfficer }}'s digital signature, then record the acknowledgement number here.
</p>
<div class="filing-row">
<button class="fiu-btn" (click)="exportSingleStrXml(s)">
<fa-icon icon="file-alt"></fa-icon> Generate STR XML
</button>
<input
class="fiu-inp"
type="text"
placeholder="FIU-IND acknowledgement no."
[(ngModel)]="localFileRefs[s.reportRefNo]"
/>
<button class="fiu-btn fiu-btn-xml" (click)="fileLocalStr(s)">Mark STR Filed</button>
</div>
</div>
}
@if (s.status === 'filed' && s.fiuReferenceNo) {
<div class="str-filed-ack">
<fa-icon icon="check-circle"></fa-icon>
<span>
Filed with FIU-IND on <strong>{{ s.filedOn }}</strong> &middot; acknowledgement
<strong class="mono">{{ s.fiuReferenceNo }}</strong>
</span>
</div>
}
@if (!s.poFinding && investigatingStr?.reportRefNo !== s.reportRefNo) {
<div class="str-po-action" *mifosxHasPermission="'CONCLUDE_AML_STR'">
<label>Principal Officer investigation — is the source of funds legitimate?</label>
<button class="fiu-btn fiu-btn-xml" (click)="investigateLocalStr(s)">
<fa-icon icon="search"></fa-icon> Investigate this case
</button>
</div>
}
<!-- Investigation workspace for this case -->
@if (investigatingStr?.reportRefNo === s.reportRefNo) {
<div class="str-investigation" *mifosxHasPermission="'CONCLUDE_AML_STR'">
<div class="inv-head">
<span>Principal Officer investigation — STR-{{ s.reportRefNo }}</span>
<button class="fiu-link-btn fiu-link-btn--muted" (click)="closeLocalStrInvestigation()">
Cancel
</button>
</div>
<!-- Step 1 — call for evidence -->
<div class="inv-step">
<div class="inv-step-t"><span class="inv-num">1</span> Documentary evidence called for</div>
<div class="inv-grid">
<div class="form-row">
<label for="invDocType">Document requested from the customer</label>
<select id="invDocType" class="fiu-inp" [(ngModel)]="evidenceDocType">
<option value="">Select document…</option>
@for (d of evidenceDocTypes; track d) {
<option [value]="d">{{ d }}</option>
}
</select>
</div>
<div class="form-row">
<label for="invReceived">Was it produced?</label>
<select id="invReceived" class="fiu-inp" [(ngModel)]="evidenceReceived">
<option value="">Select…</option>
<option value="YES">Yes — complete</option>
<option value="PARTIAL">Partially — incomplete</option>
<option value="NO">No — not produced</option>
</select>
</div>
<div class="form-row">
<label for="invRef">Document / reference number</label>
<input id="invRef" class="fiu-inp" type="text" [(ngModel)]="evidenceReference" />
</div>
</div>
</div>
<!-- Step 2 — customer's account of the funds -->
<div class="inv-step">
<div class="inv-step-t"><span class="inv-num">2</span> Customer’s explanation of the source</div>
<textarea
rows="2"
[(ngModel)]="customerExplanation"
placeholder="e.g. Proceeds of a flat sold in June; sale deed produced and matched to the deposit amount and date."
></textarea>
</div>
<!-- Step 3 — verification checklist -->
<div class="inv-step">
<div class="inv-step-t">
<span class="inv-num">3</span> Verification checklist
<span class="checklist-progress" [class.done]="allAnswered">
{{ answeredCount }} / {{ strChecklist.length }} answered
</span>
</div>
<table class="checklist-tbl">
<thead>
<tr>
<th>Verification point</th>
<th class="ta-c col-yes">Genuine</th>
<th class="ta-c col-no">Not satisfied</th>
</tr>
</thead>
<tbody>
@for (item of strChecklist; track item.key) {
<tr
[class.row-yes]="strFindings[item.key] === true"
[class.row-no]="strFindings[item.key] === false"
[class.row-pending]="strFindings[item.key] === null"
>
<td>
<div class="chk-label">{{ item.label }}</div>
<div class="chk-hint">{{ item.hint }}</div>
</td>
<td class="ta-c">
<button
type="button"
class="chk-box chk-box--yes"
[class.on]="strFindings[item.key] === true"
[attr.aria-label]="'Mark ' + item.label + ' as genuine'"
(click)="setFinding(item.key, true)"
>
<fa-icon icon="check-circle"></fa-icon>
</button>
</td>
<td class="ta-c">
<button
type="button"
class="chk-box chk-box--no"
[class.on]="strFindings[item.key] === false"
[attr.aria-label]="'Mark ' + item.label + ' as not satisfied'"
(click)="setFinding(item.key, false)"
>
<fa-icon icon="exclamation-triangle"></fa-icon>
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
<!-- Derived outcome -->
<div
class="verdict"
[class.verdict--clear]="canConcludeLocal && derivedConclusion === 'NOT_SUSPICIOUS'"
[class.verdict--suspicious]="canConcludeLocal && derivedConclusion === 'SUSPICIOUS'"
>
@if (!canConcludeLocal) {
<fa-icon icon="info-circle"></fa-icon>
<span>
Complete all three steps to determine the outcome.
@if (!evidenceRecorded) {
<span> Evidence not yet recorded.</span>
}
@if (!allAnswered) {
<span> {{ strChecklist.length - answeredCount }} verification point(s) pending.</span>
}
</span>
} @else if (derivedConclusion === 'NOT_SUSPICIOUS') {
<fa-icon icon="check-circle"></fa-icon>
<span>
<strong>Source of funds established.</strong> Case closes as clean — the transaction stays in
the CTR report and no STR is filed with FIU-IND.
</span>
} @else {
<fa-icon icon="exclamation-triangle"></fa-icon>
<span>
<strong>Source of funds not established.</strong> {{ failedFindings.length }} point(s)
unsatisfied — an STR will be filed with FIU-IND in addition to the CTR.
</span>
}
</div>
<button class="fiu-btn fiu-btn-xml" [disabled]="!canConcludeLocal" (click)="concludeLocalStr()">
{{
canConcludeLocal
? derivedConclusion === 'SUSPICIOUS'
? 'Conclude — file STR with FIU-IND'
: 'Conclude — close as clean (CTR only)'
: 'Conclude'
}}
</button>
</div>
}
</div> </div>
</div> </div>
} @empty { } @empty {
@@ -407,10 +964,13 @@
<div class="fiu-form-meta"> <div class="fiu-form-meta">
<div class="fiu-form-title"> <div class="fiu-form-title">
<h3>FINnet 2.0 Submission Files</h3> <h3>FINnet 2.0 Submission Files</h3>
<p>6 CSV files in FIU-IND prescribed schema, plus STR XML</p> <p>
6 CSV files in FIU-IND prescribed schema, plus STR XML. Counts reflect any filters set on the CTR and STR
tabs, so every file in the bundle covers the same transactions.
</p>
</div> </div>
<button class="fiu-btn fiu-btn-xls" (click)="exportAll()"> <button class="fiu-btn fiu-btn-xls" (click)="exportAll()">
<fa-icon icon="file-csv"></fa-icon> Download All <fa-icon icon="file-csv"></fa-icon> Download All 7
</button> </button>
</div> </div>
@@ -422,7 +982,7 @@
</div> </div>
<div class="file-card"> <div class="file-card">
<div class="file-card-h"><fa-icon icon="file-csv"></fa-icon>TC2.csv</div> <div class="file-card-h"><fa-icon icon="file-csv"></fa-icon>TC2.csv</div>
<p>Branch / cash transactions ({{ ctrTxns.length }} rows)</p> <p>Branch / cash transactions ({{ filteredCtr.length }} rows)</p>
<button class="fiu-btn fiu-btn-csv" (click)="exportTc2()"> <button class="fiu-btn fiu-btn-csv" (click)="exportTc2()">
<fa-icon icon="file-csv"></fa-icon> Download <fa-icon icon="file-csv"></fa-icon> Download
</button> </button>
@@ -457,7 +1017,7 @@
</div> </div>
<div class="file-card file-card--xml"> <div class="file-card file-card--xml">
<div class="file-card-h"><fa-icon icon="file-alt"></fa-icon>STR.xml</div> <div class="file-card-h"><fa-icon icon="file-alt"></fa-icon>STR.xml</div>
<p>Suspicious Transaction Report ({{ filedStr + pendingStr }} suspects)</p> <p>Suspicious Transaction Report ({{ strSuspects.length }} suspects — cases concluded clean are excluded)</p>
<button class="fiu-btn fiu-btn-xml" (click)="exportStrXml()"> <button class="fiu-btn fiu-btn-xml" (click)="exportStrXml()">
<fa-icon icon="file-alt"></fa-icon> Download XML <fa-icon icon="file-alt"></fa-icon> Download XML
</button> </button>
+955
View File
@@ -386,6 +386,172 @@
align-self: end; align-self: end;
} }
/* CTR outcome 1: source of funds evidenced at the counter — CTR only. */
.fiu-btn-evidence {
padding: 5px 10px;
font-size: 11px;
font-weight: 600;
color: var(--f-green);
border-color: var(--f-green);
background: var(--f-green-l);
&:hover {
background: var(--f-green);
border-color: var(--f-green);
color: #fff;
}
}
/* Inline evidence capture row inside the TC2 table. */
.evidence-row td {
background: var(--f-green-l) !important;
padding: 0 !important;
}
.evidence-panel {
padding: 12px 16px;
border-left: 3px solid var(--f-green);
}
.evidence-t {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 700;
color: #14532d;
margin-bottom: 10px;
}
.evidence-grid {
display: grid;
grid-template-columns: 2fr 1fr auto;
gap: 12px;
align-items: end;
}
.evidence-note {
margin: 8px 0 0;
font-size: 11px;
color: var(--f-g700);
}
@media (width <= 900px) {
.evidence-grid {
grid-template-columns: 1fr;
}
}
/* CTR outcome 2: evidence unavailable — refer the transaction onward to STR. */
.fiu-btn-refer {
padding: 5px 10px;
font-size: 11px;
font-weight: 600;
color: var(--f-red);
border-color: var(--f-red);
background: var(--f-red-l);
&:hover {
background: var(--f-red);
border-color: var(--f-red);
color: #fff;
}
}
.fiu-link-btn {
display: inline-block;
margin-top: 3px;
padding: 0;
border: none;
background: none;
font-family: inherit;
font-size: 11px;
font-weight: 600;
color: var(--f-red);
cursor: pointer;
text-decoration: underline;
&:hover {
color: #9a2f22;
}
&--muted {
color: var(--f-g500);
&:hover {
color: var(--f-red);
}
}
}
/* PRINCIPAL OFFICER INVESTIGATION */
.str-po-action {
background: var(--f-amber-l);
border: 1px dashed #fcd34d;
border-radius: 8px;
padding: 10px 14px;
display: flex;
flex-direction: column;
gap: 8px;
> label {
font-size: 10px;
font-weight: 700;
color: #92400e;
text-transform: uppercase;
letter-spacing: 0.05em;
}
}
.fiu-btn-clean {
background: var(--f-green);
border-color: var(--f-green);
color: #fff;
&:hover {
background: #166534;
border-color: #166534;
color: #fff;
}
}
.str-finding {
background: var(--f-green-l);
border-radius: 8px;
padding: 10px 14px;
label {
font-size: 10px;
font-weight: 700;
color: var(--f-green);
text-transform: uppercase;
letter-spacing: 0.05em;
display: flex;
align-items: center;
gap: 5px;
margin-bottom: 4px;
}
p {
margin: 0;
font-size: 13px;
color: #14532d;
line-height: 1.5;
}
&--suspicious {
background: var(--f-red-l);
label {
color: var(--f-red);
}
p {
color: #7f1d1d;
}
}
}
/* INPUTS */ /* INPUTS */
.fiu-inp { .fiu-inp {
width: 100%; width: 100%;
@@ -538,6 +704,50 @@
} }
} }
.report-pill {
display: inline-block;
padding: 2px 9px;
border-radius: 999px;
font-size: 11px;
font-weight: 700;
white-space: nowrap;
&.report-ctr {
background: var(--f-blue-l);
color: var(--f-blue);
}
&.report-str {
background: var(--f-red-l);
color: var(--f-red);
margin-left: 4px;
}
&.report-pending {
background: var(--f-amber-l);
color: var(--f-amber);
}
&.report-cleared {
background: var(--f-green-l);
color: var(--f-green);
}
}
.fiu-tbl-legend {
margin: -6px 2px 0;
font-size: 11px;
color: var(--f-g500);
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
.report-pill {
margin-left: 0;
}
}
.rel-pill { .rel-pill {
display: inline-block; display: inline-block;
padding: 2px 9px; padding: 2px 9px;
@@ -570,6 +780,11 @@
color: var(--f-amber); color: var(--f-amber);
} }
&.st-awaiting-filing {
background: #ffedd5;
color: #9a3412;
}
&.st-filed { &.st-filed {
background: var(--f-green-l); background: var(--f-green-l);
color: var(--f-green); color: var(--f-green);
@@ -579,6 +794,41 @@
background: var(--f-red-l); background: var(--f-red-l);
color: var(--f-red); color: var(--f-red);
} }
&.status-raised {
background: var(--f-amber-l);
color: var(--f-amber);
}
&.status-under-review {
background: var(--f-blue-l);
color: var(--f-blue);
}
&.status-whitelisted,
&.status-concluded-clear,
&.status-generated,
&.status-submitted {
background: var(--f-green-l);
color: var(--f-green);
}
&.status-escalated,
&.status-open,
&.status-concluded-suspicious {
background: var(--f-red-l);
color: var(--f-red);
}
&.status-filed {
background: var(--f-purple-l);
color: var(--f-purple);
}
&.status-draft {
background: var(--f-g100);
color: var(--f-g500);
}
} }
.risk-pill { .risk-pill {
@@ -662,6 +912,11 @@
&--filed { &--filed {
border-color: #86efac; border-color: #86efac;
} }
&--highlight {
border-color: var(--f-red);
box-shadow: 0 0 0 3px rgb(192 57 43 / 20%);
}
} }
.str-card-h { .str-card-h {
@@ -892,3 +1147,703 @@
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
} }
.selected-row {
background: var(--f-blue-l);
}
.escalation-warning {
color: var(--f-red);
font-weight: 700;
}
.escalation-badge {
display: inline-block;
margin-left: 8px;
padding: 2px 8px;
border-radius: 10px;
background: var(--f-amber-l);
color: var(--f-amber);
font-size: 11px;
font-weight: 600;
}
.str-case-detail {
border: 1px solid var(--f-g200);
border-radius: 10px;
padding: 16px;
background: #fff;
margin-bottom: 16px;
}
.case-outcome {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
margin: 12px 0;
padding: 10px 14px;
border-radius: 8px;
background: var(--f-g100);
font-size: 13px;
color: var(--f-g700);
&--clear {
background: var(--f-green-l);
color: #14532d;
}
&--suspicious {
background: var(--f-red-l);
color: #7f1d1d;
}
}
.case-form {
display: flex;
flex-direction: column;
gap: 12px;
textarea {
width: 100%;
padding: 8px 10px;
border-radius: 6px;
border: 1px solid var(--f-g300);
font-family: inherit;
font-size: 13px;
}
}
.form-row {
display: flex;
flex-direction: column;
gap: 4px;
label {
font-size: 12px;
font-weight: 600;
color: var(--f-g500);
}
}
.conclusion-row {
flex-direction: row;
gap: 24px;
label {
display: flex;
align-items: center;
gap: 6px;
font-weight: 500;
}
}
/* ── Principal Officer verification checklist ───────────────────────────── */
.checklist {
border: 1px solid var(--f-g200);
border-radius: 10px;
overflow: hidden;
background: #fff;
}
.checklist-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
padding: 10px 14px;
background: var(--f-g50);
border-bottom: 1px solid var(--f-g200);
font-size: 12px;
font-weight: 700;
color: var(--f-g700);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.checklist-progress {
font-size: 11px;
font-weight: 700;
padding: 2px 10px;
border-radius: 999px;
background: var(--f-amber-l);
color: var(--f-amber);
text-transform: none;
letter-spacing: 0;
white-space: nowrap;
&.done {
background: var(--f-green-l);
color: var(--f-green);
}
}
.checklist-tbl {
width: 100%;
border-collapse: collapse;
th {
padding: 8px 12px;
font-size: 10px;
font-weight: 700;
color: var(--f-g500);
text-transform: uppercase;
letter-spacing: 0.05em;
background: var(--f-g50);
border-bottom: 1px solid var(--f-g200);
text-align: left;
white-space: nowrap;
}
th.col-yes {
color: var(--f-green);
width: 96px;
}
th.col-no {
color: var(--f-red);
width: 112px;
}
td {
padding: 9px 12px;
border-bottom: 1px solid var(--f-g100);
vertical-align: middle;
}
tr:last-child td {
border-bottom: none;
}
}
/* Answered rows tint so an unresolved finding is obvious at a glance. */
.row-yes td {
background: rgb(220 252 231 / 45%);
}
.row-no td {
background: rgb(253 236 234 / 60%);
}
.row-pending td {
background: #fff;
}
.chk-label {
font-size: 13px;
font-weight: 600;
color: var(--f-g900);
}
.chk-hint {
font-size: 11px;
color: var(--f-g500);
margin-top: 1px;
}
/* Two-sided toggle: one box on the genuine side, one on the not-satisfied side. */
.chk-box {
width: 30px;
height: 30px;
border-radius: 7px;
border: 2px solid var(--f-g300);
background: #fff;
color: var(--f-g300);
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 14px;
transition: all 0.15s;
&:hover {
transform: scale(1.08);
}
&--yes:hover {
border-color: var(--f-green);
color: var(--f-green);
}
&--no:hover {
border-color: var(--f-red);
color: var(--f-red);
}
&--yes.on {
border-color: var(--f-green);
background: var(--f-green);
color: #fff;
}
&--no.on {
border-color: var(--f-red);
background: var(--f-red);
color: #fff;
}
}
/* Concluded suspicious, still to be submitted on the FINnet portal. */
.str-filing {
background: #fff7ed;
border: 1px solid #fdba74;
border-radius: 8px;
padding: 10px 14px;
label {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-weight: 700;
color: #9a3412;
text-transform: uppercase;
letter-spacing: 0.04em;
}
}
.filing-hint {
margin: 4px 0 8px;
font-size: 12px;
color: var(--f-g700);
}
.filing-row {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
.fiu-inp {
max-width: 260px;
}
}
.str-filed-ack {
display: flex;
align-items: center;
gap: 8px;
background: var(--f-green-l);
border: 1px solid #86efac;
border-radius: 8px;
padding: 9px 14px;
font-size: 12px;
color: #14532d;
}
/* ── CTR-referred case: Principal Officer investigation workspace ───────── */
.str-investigation {
margin-top: 12px;
border: 1px solid var(--f-purple);
border-radius: 10px;
background: #fdfcff;
display: flex;
flex-direction: column;
gap: 12px;
padding: 14px;
}
.inv-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
font-size: 12px;
font-weight: 700;
color: var(--f-purple);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.inv-step {
display: flex;
flex-direction: column;
gap: 8px;
textarea {
width: 100%;
padding: 8px 10px;
border-radius: 6px;
border: 1px solid var(--f-g300);
font-family: inherit;
font-size: 13px;
}
}
.inv-step-t {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 700;
color: var(--f-g900);
}
.inv-num {
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
border-radius: 50%;
background: var(--f-purple);
color: #fff;
font-size: 11px;
font-weight: 700;
flex-shrink: 0;
}
.inv-grid {
display: grid;
grid-template-columns: 2fr 1fr 1fr;
gap: 12px;
}
@media (width <= 900px) {
.inv-grid {
grid-template-columns: 1fr;
}
}
/* Derived verdict banner */
.verdict {
display: flex;
align-items: center;
gap: 10px;
padding: 11px 15px;
border-radius: 9px;
font-size: 13px;
background: var(--f-g100);
border: 1px solid var(--f-g200);
color: var(--f-g700);
&--clear {
background: var(--f-green-l);
border-color: #86efac;
color: #14532d;
}
&--suspicious {
background: var(--f-red-l);
border-color: #fca5a5;
color: #7f1d1d;
}
}
.case-form .fiu-btn-xml:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.file-str-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 8px;
padding-top: 12px;
border-top: 1px dashed var(--f-g300);
label {
font-size: 12px;
font-weight: 600;
color: var(--f-g500);
}
}
/* ═══ WHEN TO REPORT — the five PMLA obligations ═══ */
.ob-block {
margin: 18px 0 20px;
}
.ob-head {
margin-bottom: 12px;
}
.ob-title {
margin: 0;
font-size: 15px;
font-weight: 700;
display: flex;
align-items: center;
gap: 8px;
}
.ob-sub {
margin: 3px 0 0;
font-size: 12px;
color: #64748b;
max-width: 860px;
}
.ob-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 12px;
}
.ob-card {
background: #fff;
border: 1px solid #e2e8f0;
border-left: 4px solid #1a237e;
border-radius: 11px;
padding: 13px 15px;
display: flex;
flex-direction: column;
gap: 7px;
/* Obligations the module only tracks read back a shade quieter than the
two it actually files, so the distinction is visible at a glance. */
&--off {
border-left-color: #cbd5e1;
background: #fcfcfd;
}
}
.ob-card-h {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.ob-ic {
color: #1a237e;
font-size: 15px;
}
.ob-code {
font-weight: 800;
font-size: 13px;
letter-spacing: 0.02em;
}
.ob-name {
font-size: 12px;
color: #334155;
font-weight: 600;
}
.ob-flag {
margin-left: auto;
font-size: 10px;
font-weight: 700;
padding: 1px 8px;
border-radius: 999px;
background: #f1f5f9;
color: #64748b;
white-space: nowrap;
&--on {
background: #dcfce7;
color: #15803d;
}
}
.ob-row {
display: flex;
flex-direction: column;
gap: 1px;
label {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #94a3b8;
}
span {
font-size: 12.5px;
color: #0f172a;
line-height: 1.45;
}
}
.ob-due {
font-weight: 700;
color: #b45309 !important;
}
.ob-note {
font-size: 11.5px;
color: #64748b;
font-style: italic;
border-top: 1px dashed #e2e8f0;
padding-top: 6px;
}
/* ═══ FINNET FILE SEQUENCE ═══ */
.seq-block {
margin-top: 26px;
padding-top: 18px;
border-top: 2px solid #e2e8f0;
}
.seq-rail {
display: flex;
align-items: center;
gap: 4px;
flex-wrap: wrap;
margin-bottom: 14px;
}
.seq-step {
display: inline-flex;
align-items: center;
gap: 9px;
padding: 7px 13px;
border: 1px solid #cbd5e1;
background: #fff;
border-radius: 9px;
cursor: pointer;
font-family: inherit;
text-align: left;
transition: all 0.15s;
&:hover {
border-color: #1a237e;
}
&.active {
background: #1a237e;
border-color: #1a237e;
.seq-n {
background: #fff;
color: #1a237e;
}
.seq-txt strong,
.seq-txt em {
color: #fff;
}
}
}
.seq-n {
display: inline-flex;
align-items: center;
justify-content: center;
width: 21px;
height: 21px;
border-radius: 50%;
background: #1a237e;
color: #fff;
font-size: 11px;
font-weight: 800;
flex: 0 0 21px;
}
.seq-txt {
display: flex;
flex-direction: column;
line-height: 1.25;
strong {
font-size: 12.5px;
color: #0f172a;
font-weight: 700;
}
em {
font-size: 10.5px;
color: #64748b;
font-style: normal;
}
}
.seq-arrow {
color: #cbd5e1;
font-size: 11px;
}
.seq-panel {
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 11px;
overflow: hidden;
}
.seq-panel-h {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
padding: 12px 16px;
background: #f8fafc;
border-bottom: 1px solid #e2e8f0;
flex-wrap: wrap;
h4 {
margin: 0;
font-size: 13.5px;
font-weight: 700;
}
p {
margin: 2px 0 0;
font-size: 12px;
color: #64748b;
max-width: 780px;
}
}
.seq-tbl-wrap {
max-height: 460px;
overflow: auto;
}
.seq-tbl {
width: 100%;
border-collapse: collapse;
font-size: 11.5px;
white-space: nowrap;
th {
position: sticky;
top: 0;
z-index: 1;
text-align: left;
padding: 8px 10px;
background: #eef2f7;
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.03em;
color: #334155;
border-bottom: 1px solid #cbd5e1;
}
td {
padding: 6px 10px;
border-bottom: 1px solid #f1f5f9;
font-family: 'DM Mono', monospace;
color: #0f172a;
}
tbody tr:hover td {
background: #f8fafc;
}
}
.seq-rownum {
color: #94a3b8 !important;
font-weight: 700;
text-align: right;
position: sticky;
left: 0;
background: #fff;
}
.seq-tbl thead .seq-rownum {
background: #eef2f7;
}
.seq-empty {
padding: 36px !important;
text-align: center;
color: #64748b;
font-family: inherit !important;
white-space: normal;
font-size: 12.5px;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,638 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { GL_BRANCHES, GL_PERIOD } from '../gl-reports/gl-reports-data';
/**
* Transactions of customers who banked on a Form 97 / Form 98 declaration.
*
* Rule 114B of the Income-tax Rules lists transactions where quoting PAN is
* mandatory. A customer who has no PAN gives a declaration instead:
*
* Form 97 — person with no PAN (income may be taxable).
* Form 98 — person whose only income is agricultural and who has no PAN.
*
* The bank must be able to produce, for any period, every transaction put
* through on the strength of such a declaration. That is what this report is.
*/
export type FormType = 'FORM_60' | 'FORM_61';
/** Screen and workbook labels — this bank numbers the declarations 97 and 98. */
export const FORM_LABEL: Record<FormType, string> = {
FORM_60: 'Form 97',
FORM_61: 'Form 98'
};
export interface FormDeclarant {
/** Declaration acknowledgement number, as issued by the branch. */
ackNo: string;
formType: FormType;
name: string;
fatherName: string;
dateOfBirth: string;
address: string;
branchCode: string;
accountNo: string;
/** Why the customer has no PAN — printed on the declaration. */
reasonForNoPan: string;
estimatedIncome: number;
declaredOn: string;
aadhaarLast4: string;
}
export type TxnMode = 'CASH' | 'TRANSFER' | 'CLEARING' | 'NEFT' | 'RTGS' | 'UPI' | 'ATM';
export interface FormDeclarantTxn {
txnId: string;
ackNo: string;
date: string;
branchCode: string;
accountNo: string;
mode: TxnMode;
drCr: 'DR' | 'CR';
amount: number;
/** What the transaction was — a Rule 114B category or ordinary activity. */
nature: string;
/** Coarse bucket the nature belongs to, e.g. Cash, Clearing, Loan. */
group: string;
/** True when the nature is one of the categories listed in Rule 114B. */
rule114B: boolean;
particulars: string;
voucherNo: string;
}
/** Deterministic linear congruential generator — same figures on every load. */
function lcg(seed: number): () => number {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 4294967296;
};
}
function pick<T>(rand: () => number, list: T[]): T {
return list[Math.floor(rand() * list.length)];
}
function isoDate(d: Date): string {
const y = d.getUTCFullYear();
const m = `${d.getUTCMonth() + 1}`.padStart(2, '0');
const day = `${d.getUTCDate()}`.padStart(2, '0');
return `${y}-${m}-${day}`;
}
/**
* Thresholds that make a row worth a second look.
*
* `RULE_114B_CASH` is the cash-deposit limit above which a declaration is
* required at all; `CTR` is the aggregate cash figure that puts the customer
* into the monthly Cash Transaction Report.
*/
export const FORM_THRESHOLD = {
RULE_114B_CASH: 50_000,
CTR: 1_000_000
};
const FIRST_NAMES = [
'Ramesh',
'Sunita',
'Vitthal',
'Kamala',
'Ganpat',
'Shobha',
'Dnyaneshwar',
'Mangala',
'Bhaskar',
'Anita',
'Tukaram',
'Sarika',
'Nivrutti',
'Rekha',
'Popat',
'Chhaya',
'Ashok',
'Vaishali',
'Bapu',
'Nanda',
'Sitaram',
'Jayshree',
'Madhukar',
'Pushpa',
'Eknath',
'Sulochana',
'Baban',
'Indubai',
'Hanumant',
'Kalpana'
];
const SURNAMES = [
'Jadhav',
'Pawar',
'Shinde',
'Gaikwad',
'More',
'Kadam',
'Bhosale',
'Patil',
'Sawant',
'Chavan',
'Salunkhe',
'Mane',
'Deshmukh',
'Thorat',
'Nikam',
'Wagh',
'Kale',
'Ghadge',
'Bhoir',
'Tandel'
];
const VILLAGES = [
'Wadgaon',
'Kolhewadi',
'Shirgaon',
'Nandgaon',
'Pimpalgaon',
'Bhosari',
'Rajgurunagar',
'Talegaon',
'Karjat',
'Murbad',
'Shahapur',
'Vasind'
];
/** Reasons a Form 97 declarant gives — Form 98 has its own single reason. */
const NO_PAN_REASONS = [
'Applied for PAN, allotment awaited',
'Total income below taxable limit',
'Not required to file return of income',
'First-time account holder, PAN not yet obtained'
];
/**
* Every kind of transaction one of these customers puts through — not only the
* ones that triggered a declaration.
*
* `rule114B` marks the categories listed in Rule 114B, where quoting PAN (and
* therefore the Form 97/98 declaration) is mandatory above the limit. The rest
* are ordinary account activity, which the report still has to show: the point
* is the customer's whole picture, not just the declared slice.
*
* `drCr` is fixed where the category only goes one way; 'EITHER' lets the
* generator choose. `cashOnly` forces counter cash, `nonCash` excludes it.
*/
interface TxnKind {
nature: string;
group: string;
rule114B: boolean;
drCr: 'DR' | 'CR' | 'EITHER';
cashOnly?: boolean;
nonCash?: boolean;
/** Relative frequency — small routine postings outnumber big declared ones. */
weight: number;
/** Typical value band, before the occasional large-value tail. */
min: number;
max: number;
}
const TXN_KINDS: TxnKind[] = [
// ── Rule 114B categories: the transactions the declaration was taken for ──
{
nature: 'Cash deposit exceeding ₹50,000 in a day',
group: 'Cash',
rule114B: true,
drCr: 'CR',
cashOnly: true,
weight: 14,
min: 50_000,
max: 470_000
},
{
nature: 'Cash withdrawal exceeding ₹50,000',
group: 'Cash',
rule114B: true,
drCr: 'DR',
cashOnly: true,
weight: 8,
min: 50_000,
max: 380_000
},
{
nature: 'Opening of deposit account',
group: 'Account',
rule114B: true,
drCr: 'CR',
cashOnly: true,
weight: 3,
min: 5_000,
max: 50_000
},
{
nature: 'Term deposit exceeding ₹50,000',
group: 'Deposit',
rule114B: true,
drCr: 'DR',
weight: 5,
min: 50_000,
max: 900_000
},
{
nature: 'Purchase of demand draft in cash',
group: 'Remittance',
rule114B: true,
drCr: 'DR',
cashOnly: true,
weight: 4,
min: 50_000,
max: 260_000
},
{
nature: 'Sale/purchase of goods or services above ₹2,00,000',
group: 'Trade',
rule114B: true,
drCr: 'EITHER',
weight: 3,
min: 200_000,
max: 850_000
},
// ── Ordinary account activity ────────────────────────────────────────────
{
nature: 'Cash deposit',
group: 'Cash',
rule114B: false,
drCr: 'CR',
cashOnly: true,
weight: 16,
min: 500,
max: 49_900
},
{
nature: 'Cash withdrawal',
group: 'Cash',
rule114B: false,
drCr: 'DR',
cashOnly: true,
weight: 15,
min: 500,
max: 49_900
},
{
nature: 'Cheque deposit — outward clearing',
group: 'Clearing',
rule114B: false,
drCr: 'CR',
nonCash: true,
weight: 7,
min: 2_000,
max: 180_000
},
{
nature: 'Cheque paid — inward clearing',
group: 'Clearing',
rule114B: false,
drCr: 'DR',
nonCash: true,
weight: 6,
min: 2_000,
max: 160_000
},
{
nature: 'NEFT inward credit',
group: 'Remittance',
rule114B: false,
drCr: 'CR',
nonCash: true,
weight: 6,
min: 1_000,
max: 220_000
},
{
nature: 'NEFT outward remittance',
group: 'Remittance',
rule114B: false,
drCr: 'DR',
nonCash: true,
weight: 5,
min: 1_000,
max: 200_000
},
{
nature: 'RTGS inward credit',
group: 'Remittance',
rule114B: false,
drCr: 'CR',
nonCash: true,
weight: 2,
min: 200_000,
max: 1_200_000
},
{
nature: 'UPI / mobile banking transfer',
group: 'Digital',
rule114B: false,
drCr: 'EITHER',
nonCash: true,
weight: 10,
min: 100,
max: 24_000
},
{
nature: 'ATM cash withdrawal',
group: 'Digital',
rule114B: false,
drCr: 'DR',
cashOnly: true,
weight: 9,
min: 500,
max: 20_000
},
{
nature: 'Transfer between own accounts',
group: 'Transfer',
rule114B: false,
drCr: 'EITHER',
nonCash: true,
weight: 5,
min: 1_000,
max: 120_000
},
{
nature: 'Loan instalment (EMI) recovery',
group: 'Loan',
rule114B: false,
drCr: 'DR',
weight: 7,
min: 2_500,
max: 42_000
},
{
nature: 'Loan disbursement credited',
group: 'Loan',
rule114B: false,
drCr: 'CR',
nonCash: true,
weight: 2,
min: 50_000,
max: 700_000
},
{
nature: 'Interest credited on deposit',
group: 'Interest',
rule114B: false,
drCr: 'CR',
nonCash: true,
weight: 6,
min: 120,
max: 14_000
},
{
nature: 'Interest debited on loan',
group: 'Interest',
rule114B: false,
drCr: 'DR',
nonCash: true,
weight: 4,
min: 200,
max: 11_000
},
{
nature: 'Term deposit matured and credited',
group: 'Deposit',
rule114B: false,
drCr: 'CR',
nonCash: true,
weight: 3,
min: 25_000,
max: 620_000
},
{
nature: 'Recurring deposit instalment',
group: 'Deposit',
rule114B: false,
drCr: 'DR',
weight: 5,
min: 500,
max: 12_000
},
{
nature: 'Service charges / commission recovered',
group: 'Charges',
rule114B: false,
drCr: 'DR',
nonCash: true,
weight: 6,
min: 25,
max: 2_400
},
{
nature: 'Cheque return charges',
group: 'Charges',
rule114B: false,
drCr: 'DR',
nonCash: true,
weight: 2,
min: 100,
max: 900
},
{
nature: 'Locker rent recovered',
group: 'Charges',
rule114B: false,
drCr: 'DR',
nonCash: true,
weight: 1,
min: 800,
max: 4_500
},
{
nature: 'Dividend credited on shares',
group: 'Shares',
rule114B: false,
drCr: 'CR',
nonCash: true,
weight: 2,
min: 200,
max: 9_000
},
{
nature: 'Share capital subscription',
group: 'Shares',
rule114B: false,
drCr: 'DR',
weight: 2,
min: 500,
max: 25_000
}
];
/** Flattened by weight so a single draw picks a category at the right rate. */
const KIND_POOL: TxnKind[] = TXN_KINDS.flatMap((k) => Array<TxnKind>(k.weight).fill(k));
/** The distinct groups, for the report's category filter. */
export const TXN_GROUPS: string[] = [...new Set(TXN_KINDS.map((k) => k.group))].sort();
let declarantCache: FormDeclarant[] | null = null;
let txnCache: FormDeclarantTxn[] | null = null;
/**
* The customers who filed a declaration. Roughly one in five is a Form 98
* (agricultural income only), which matches the mix a semi-urban co-operative
* bank sees — the rural branches carry most of them.
*/
export function formDeclarants(): FormDeclarant[] {
if (declarantCache) {
return declarantCache;
}
const rand = lcg(31071998);
const branches = GL_BRANCHES.filter((b) => b.code !== 'HO');
const out: FormDeclarant[] = [];
for (let i = 0; i < 148; i++) {
const branch = branches[i % branches.length];
// Form 98 is the agricultural-income declaration, so it clusters in the
// outlying branches rather than being spread evenly.
const rural = branch.code === '0004' || branch.code === '0006';
const formType: FormType = rand() < (rural ? 0.42 : 0.08) ? 'FORM_61' : 'FORM_60';
const first = pick(rand, FIRST_NAMES);
const last = pick(rand, SURNAMES);
const seq = `${i + 1}`.padStart(3, '0');
// Declarations are taken in the run-up to and during the ledger period.
const declOffset = Math.floor(rand() * 150);
const declDate = new Date(`${GL_PERIOD.fyStart}T00:00:00Z`);
declDate.setUTCDate(declDate.getUTCDate() - 60 + declOffset);
const birthYear = 1955 + Math.floor(rand() * 45);
const birthMonth = 1 + Math.floor(rand() * 12);
const birthDay = 1 + Math.floor(rand() * 28);
out.push({
ackNo: `${branch.code}/F${formType === 'FORM_60' ? '97' : '98'}/${seq}`,
formType,
name: `${first} ${last}`,
fatherName: `${pick(rand, FIRST_NAMES)} ${last}`,
dateOfBirth: `${birthYear}-${`${birthMonth}`.padStart(2, '0')}-${`${birthDay}`.padStart(2, '0')}`,
address: `${pick(rand, VILLAGES)}, Tal. ${pick(rand, VILLAGES)}, Dist. Thane`,
branchCode: branch.code,
accountNo: `${branch.code}${(4100000 + i * 137).toString().padStart(8, '0')}`,
reasonForNoPan:
formType === 'FORM_61' ? 'Income consists only of agricultural income' : pick(rand, NO_PAN_REASONS),
// Form 98 declarants report agricultural income, which the Act exempts, so
// their declared figures sit below the Form 97 band.
estimatedIncome:
formType === 'FORM_61' ? 90_000 + Math.floor(rand() * 160_000) : 140_000 + Math.floor(rand() * 380_000),
declaredOn: isoDate(declDate),
aadhaarLast4: `${1000 + Math.floor(rand() * 9000)}`
});
}
declarantCache = out;
return out;
}
/**
* Every transaction these customers put through inside the ledger period.
*
* A declaration is taken per transaction category, so an active customer shows
* several rows; a customer who only opened an account shows one.
*/
export function formDeclarantTxns(): FormDeclarantTxn[] {
if (txnCache) {
return txnCache;
}
const rand = lcg(19980731);
const start = new Date(`${GL_PERIOD.fyStart}T00:00:00Z`);
const end = new Date(`${GL_PERIOD.fyEnd}T00:00:00Z`);
const span = Math.round((end.getTime() - start.getTime()) / 86_400_000);
const out: FormDeclarantTxn[] = [];
let voucher = 1;
for (const d of formDeclarants()) {
// Weighted low — most declarants are occasional users and a handful bank
// every week. Squaring the draw gives that long tail rather than a flat
// spread, while still leaving enough volume for a day-wise filter to show.
const count = 1 + Math.floor(rand() * rand() * 22);
for (let n = 0; n < count; n++) {
const day = new Date(start.getTime());
day.setUTCDate(day.getUTCDate() + Math.floor(rand() * span));
if (day.getUTCDay() === 0) {
day.setUTCDate(day.getUTCDate() + 1); // Sunday — no counter business.
}
const kind = pick(rand, KIND_POOL);
const drCr: 'DR' | 'CR' = kind.drCr === 'EITHER' ? (rand() < 0.5 ? 'DR' : 'CR') : kind.drCr;
// The channel follows the category: cash categories go over the counter,
// clearing goes through the house, and the rest split across the
// electronic rails a co-operative bank offers.
let mode: TxnMode;
if (kind.cashOnly) {
mode = kind.nature.startsWith('ATM') ? 'ATM' : 'CASH';
} else if (kind.nonCash) {
mode =
kind.group === 'Clearing'
? 'CLEARING'
: kind.nature.startsWith('RTGS')
? 'RTGS'
: kind.nature.startsWith('NEFT')
? 'NEFT'
: kind.group === 'Digital'
? 'UPI'
: 'TRANSFER';
} else {
// Categories that can go either way — a term deposit or an EMI is paid
// in cash as often as it is transferred at this kind of bank.
mode = rand() < 0.55 ? 'CASH' : 'TRANSFER';
}
// Inside the category's own band, with a thin large-value tail on the
// Rule 114B rows so the report has CTR-sized entries to flag.
let amount = kind.min + Math.floor(rand() * (kind.max - kind.min));
if (kind.rule114B && kind.cashOnly && rand() < 0.09) {
amount = FORM_THRESHOLD.CTR + Math.floor(rand() * 1_400_000);
}
amount = Math.round(amount / 100) * 100 || 100;
const cashWord = mode === 'CASH' || mode === 'ATM';
out.push({
txnId: `TXN${`${out.length + 1}`.padStart(5, '0')}`,
ackNo: d.ackNo,
date: isoDate(day),
branchCode: d.branchCode,
accountNo: d.accountNo,
mode,
drCr,
amount,
nature: kind.nature,
group: kind.group,
rule114B: kind.rule114B,
particulars:
drCr === 'DR'
? `${cashWord ? 'Cash paid to' : 'Debit to account of'} ${d.name} — ${kind.nature.toLowerCase()}`
: `${cashWord ? 'Cash received from' : 'Credit to account of'} ${d.name} — ${kind.nature.toLowerCase()}`,
voucherNo: `${d.branchCode}/V/${`${voucher++}`.padStart(5, '0')}`
});
}
}
out.sort((a, b) => (a.date === b.date ? a.txnId.localeCompare(b.txnId) : a.date.localeCompare(b.date)));
txnCache = out;
return out;
}
export function declarantByAck(ackNo: string): FormDeclarant | undefined {
return formDeclarants().find((d) => d.ackNo === ackNo);
}
@@ -0,0 +1,370 @@
<!--
Copyright since 2025 Mifos Initiative
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-->
<div class="fd-root">
<!-- HEADER -->
<div class="fd-head">
<div class="fd-head-left">
<fa-icon icon="file-signature" class="fd-head-ic"></fa-icon>
<div>
<h2 class="fd-head-t">Form 97 / 98 Transaction Report</h2>
<div class="fd-head-s">
Every transaction put through on a declaration under Rule 114B, for customers who have no PAN. Form 97 is the
general declaration; Form 98 is for a person whose only income is agricultural.
</div>
</div>
</div>
<button class="fd-btn fd-btn--primary" [disabled]="generating" (click)="exportExcel()">
<fa-icon icon="file-excel"></fa-icon> {{ generating ? 'Generating…' : 'Download Excel' }}
</button>
</div>
<!-- FILTERS -->
<div class="fd-filters">
<div class="fd-filter-row">
<div class="fd-modes">
@for (m of periodModes; track m.key) {
<button class="fd-chip" [class.active]="periodMode === m.key" (click)="periodMode = m.key">
{{ m.label }}
</button>
}
</div>
@switch (periodMode) {
@case ('day') {
<label class="fd-field">
<span>Date</span>
<input type="date" [(ngModel)]="filterDay" [min]="period.fyStart" [max]="period.fyEnd" />
</label>
}
@case ('week') {
<label class="fd-field">
<span>Any date in week</span>
<input type="date" [(ngModel)]="filterWeek" [min]="period.fyStart" [max]="period.fyEnd" />
</label>
<span class="fd-resolved">Week: {{ rangeLabel }}</span>
}
@case ('month') {
<label class="fd-field">
<span>Month</span>
<input type="month" [(ngModel)]="filterMonth" min="2026-04" max="2026-07" />
</label>
}
@default {
<label class="fd-field">
<span>From</span>
<input type="date" [(ngModel)]="filterFrom" [min]="period.fyStart" [max]="period.fyEnd" />
</label>
<label class="fd-field">
<span>To</span>
<input type="date" [(ngModel)]="filterTo" [min]="period.fyStart" [max]="period.fyEnd" />
</label>
}
}
</div>
<div class="fd-filter-row">
<label class="fd-field">
<span>Branch</span>
<select [(ngModel)]="branchCode" [disabled]="!canSelectBranch">
@if (canSelectBranch) {
<option value="">All Branches</option>
}
@for (b of branches; track b.code) {
<option [value]="b.code">{{ b.code }} — {{ b.name }}</option>
}
</select>
</label>
<label class="fd-field">
<span>Declaration</span>
<select [(ngModel)]="formType">
<option value="">Both</option>
<option value="FORM_60">Form 97 — no PAN</option>
<option value="FORM_61">Form 98 — agricultural income</option>
</select>
</label>
<label class="fd-field">
<span>Transaction type</span>
<select [(ngModel)]="group">
<option value="">All types</option>
@for (g of txnGroups; track g) {
<option [value]="g">{{ g }}</option>
}
</select>
</label>
<label class="fd-field fd-field--grow">
<span>Search</span>
<input type="text" [(ngModel)]="search" placeholder="Name, account number or acknowledgement no…" />
</label>
<label class="fd-check">
<input type="checkbox" [(ngModel)]="flaggedOnly" />
Only CTR reportable
</label>
<button class="fd-btn" (click)="resetFilters()"><fa-icon icon="undo"></fa-icon> Reset</button>
</div>
@if (!canSelectBranch) {
<div class="fd-scope-note">
<fa-icon icon="lock"></fa-icon>
Showing {{ branchLabel }} only. Head Office logins can select any branch.
</div>
}
</div>
<!-- SUMMARY -->
<div class="fd-kpis">
<div class="fd-kpi">
<div class="fd-kpi-n">{{ summary.persons }}</div>
<div class="fd-kpi-l">Declarants</div>
<div class="fd-kpi-sub">{{ summary.form60Persons }} on Form 97 · {{ summary.form61Persons }} on Form 98</div>
</div>
<div class="fd-kpi fd-kpi--blue">
<div class="fd-kpi-n">{{ summary.txnCount }}</div>
<div class="fd-kpi-l">Transactions — all types</div>
<div class="fd-kpi-sub">{{ summary.declarationRequired }} in a Rule 114B category</div>
</div>
<div class="fd-kpi fd-kpi--amber">
<div class="fd-kpi-n">{{ summary.cashTotal | number: '1.0-0' }}</div>
<div class="fd-kpi-l">Cash turnover (₹)</div>
<div class="fd-kpi-sub">{{ summary.cashCount }} cash transactions</div>
</div>
<div class="fd-kpi" [class.fd-kpi--red]="summary.ctrReportable > 0">
<div class="fd-kpi-n">{{ summary.ctrReportable }}</div>
<div class="fd-kpi-l">CTR reportable</div>
<div class="fd-kpi-sub">cash at or above ₹10,00,000</div>
</div>
</div>
<!-- CATEGORY MIX — what these customers actually do, beyond the declared rows -->
@if (summary.byGroup.length) {
<div class="fd-mix">
<span class="fd-mix-t">Transaction mix</span>
@for (g of summary.byGroup; track g.group) {
<button
class="fd-mix-item"
[class.active]="group === g.group"
(click)="group = group === g.group ? '' : g.group"
>
{{ g.group }} <strong>{{ g.count }}</strong>
</button>
}
</div>
}
<!-- VIEW SWITCH -->
<div class="fd-views">
<button class="fd-chip" [class.active]="view === 'person'" (click)="view = 'person'">
<fa-icon icon="users"></fa-icon> Person wise
</button>
<button class="fd-chip" [class.active]="view === 'transaction'" (click)="view = 'transaction'">
<fa-icon icon="list"></fa-icon> Transaction wise
</button>
<span class="fd-spacer"></span>
<span class="fd-count">
{{ view === 'person' ? personRows.length + ' declarants' : txnRows.length + ' transactions' }}
</span>
</div>
<!-- PERSON WISE -->
@if (view === 'person') {
<div class="fd-table-wrap">
<table class="fd-table">
<thead>
<tr>
<th></th>
<th>Acknowledgement</th>
<th>Form</th>
<th>Name of declarant</th>
<th>Account No</th>
<th>Branch</th>
<th class="num">Txns</th>
<th class="num">Rule 114B</th>
<th class="num">Cash turnover</th>
<th class="num">Credit</th>
<th class="num">Debit</th>
<th class="num">Declared income</th>
<th class="num">Cash ÷ income</th>
</tr>
</thead>
<tbody>
@for (p of personRows; track p.declarant.ackNo) {
<tr class="fd-person" [class.open]="expanded === p.declarant.ackNo" (click)="toggle(p.declarant.ackNo)">
<td>
<fa-icon [icon]="expanded === p.declarant.ackNo ? 'caret-down' : 'caret-right'"></fa-icon>
</td>
<td class="mono">{{ p.declarant.ackNo }}</td>
<td>
<span class="fd-form" [class.fd-form--61]="p.declarant.formType === 'FORM_61'">
{{ formLabel[p.declarant.formType] }}
</span>
</td>
<td>
<strong>{{ p.declarant.name }}</strong>
@if (p.ctrCount > 0) {
<span class="fd-tag fd-tag--ctr">{{ p.ctrCount }} CTR</span>
}
</td>
<td class="mono">{{ p.declarant.accountNo }}</td>
<td>{{ p.declarant.branchCode }}</td>
<td class="num">{{ p.txnCount }}</td>
<td class="num">{{ p.declaredCount }}</td>
<td class="num strong">{{ p.cashTotal | number: '1.0-0' }}</td>
<td class="num">{{ p.totalCredit | number: '1.0-0' }}</td>
<td class="num">{{ p.totalDebit | number: '1.0-0' }}</td>
<td class="num">{{ p.declarant.estimatedIncome | number: '1.0-0' }}</td>
<td class="num">
<span [class]="ratioClass(p.incomeRatio)">{{ p.incomeRatio | number: '1.1-1' }}×</span>
</td>
</tr>
@if (expanded === p.declarant.ackNo) {
<tr class="fd-detail">
<td colspan="13">
<div class="fd-decl">
<div>
<label>Father's name</label><span>{{ p.declarant.fatherName }}</span>
</div>
<div>
<label>Date of birth</label><span>{{ p.declarant.dateOfBirth }}</span>
</div>
<div>
<label>Aadhaar</label><span class="mono">XXXX XXXX {{ p.declarant.aadhaarLast4 }}</span>
</div>
<div>
<label>Declared on</label><span>{{ p.declarant.declaredOn }}</span>
</div>
<div class="wide">
<label>Address</label><span>{{ p.declarant.address }}</span>
</div>
<div class="wide">
<label>Reason for no PAN</label><span>{{ p.declarant.reasonForNoPan }}</span>
</div>
</div>
<table class="fd-subtable">
<thead>
<tr>
<th>Date</th>
<th>Txn ID</th>
<th>Mode</th>
<th>Dr/Cr</th>
<th class="num">Amount</th>
<th>Nature of transaction (Rule 114B)</th>
<th>Voucher</th>
<th>Flag</th>
</tr>
</thead>
<tbody>
@for (t of p.txns; track t.txnId) {
<tr>
<td class="mono">{{ t.date }}</td>
<td class="mono">{{ t.txnId }}</td>
<td>
<span class="fd-mode">{{ t.mode }}</span>
</td>
<td [class.cr]="t.drCr === 'CR'" [class.dr]="t.drCr === 'DR'">{{ t.drCr }}</td>
<td class="num strong">{{ t.amount | number: '1.0-0' }}</td>
<td>{{ t.nature }}</td>
<td class="mono">{{ t.voucherNo }}</td>
<td>
@if (t.ctrReportable) {
<span class="fd-tag fd-tag--ctr">CTR</span>
} @else if (t.declarationRequired) {
<span class="fd-tag">Rule 114B</span>
}
</td>
</tr>
}
</tbody>
</table>
</td>
</tr>
}
} @empty {
<tr>
<td colspan="13" class="fd-empty">
No Form 97 or Form 98 transactions for {{ rangeLabel }} at {{ branchLabel }}.
</td>
</tr>
}
</tbody>
</table>
</div>
}
<!-- TRANSACTION WISE -->
@if (view === 'transaction') {
<div class="fd-table-wrap">
<table class="fd-table">
<thead>
<tr>
<th>Date</th>
<th>Txn ID</th>
<th>Acknowledgement</th>
<th>Form</th>
<th>Name of declarant</th>
<th>Account No</th>
<th>Branch</th>
<th>Category</th>
<th>Mode</th>
<th>Dr/Cr</th>
<th class="num">Amount</th>
<th>Nature of transaction</th>
<th>Voucher</th>
<th>Flag</th>
</tr>
</thead>
<tbody>
@for (t of txnRows; track t.txnId) {
<tr [class.fd-row--ctr]="t.ctrReportable">
<td class="mono">{{ t.date }}</td>
<td class="mono">{{ t.txnId }}</td>
<td class="mono">{{ t.ackNo }}</td>
<td>
<span class="fd-form" [class.fd-form--61]="t.formType === 'FORM_61'">{{ formLabel[t.formType] }}</span>
</td>
<td>{{ t.declarantName }}</td>
<td class="mono">{{ t.accountNo }}</td>
<td>{{ t.branchCode }}</td>
<td>
<span class="fd-group">{{ t.group }}</span>
</td>
<td>
<span class="fd-mode">{{ t.mode }}</span>
</td>
<td [class.cr]="t.drCr === 'CR'" [class.dr]="t.drCr === 'DR'">{{ t.drCr }}</td>
<td class="num strong">{{ t.amount | number: '1.0-0' }}</td>
<td>{{ t.nature }}</td>
<td class="mono">{{ t.voucherNo }}</td>
<td>
@if (t.ctrReportable) {
<span class="fd-tag fd-tag--ctr">CTR</span>
} @else if (t.declarationRequired) {
<span class="fd-tag">Rule 114B</span>
}
</td>
</tr>
} @empty {
<tr>
<td colspan="14" class="fd-empty">
No Form 97 or Form 98 transactions for {{ rangeLabel }} at {{ branchLabel }}.
</td>
</tr>
}
</tbody>
</table>
</div>
}
<div class="fd-toast" [class.show]="toastVisible">{{ toastMsg }}</div>
</div>
@@ -0,0 +1,608 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
:host {
--f-navy: #1a237e;
--f-blue: #1d4ed8;
--f-blue-l: #eff6ff;
--f-green: #15803d;
--f-green-l: #dcfce7;
--f-amber: #b45309;
--f-amber-l: #fef3c7;
--f-red: #c0392b;
--f-red-l: #fdecea;
--f-g50: #f8fafc;
--f-g100: #f1f5f9;
--f-g200: #e2e8f0;
--f-g300: #cbd5e1;
--f-g500: #64748b;
--f-g700: #334155;
--f-g900: #0f172a;
display: block;
font-family: 'DM Sans', system-ui, sans-serif;
background: var(--f-g50);
color: var(--f-g900);
font-size: 14px;
line-height: 1.5;
}
.fd-root {
padding: 18px 22px;
max-width: 1700px;
margin: 0 auto;
}
/* HEADER */
.fd-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 14px;
}
.fd-head-left {
display: flex;
align-items: flex-start;
gap: 14px;
}
.fd-head-ic {
font-size: 26px;
color: var(--f-navy);
margin-top: 3px;
}
.fd-head-t {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.fd-head-s {
font-size: 12px;
color: var(--f-g500);
max-width: 820px;
}
/* BUTTONS */
.fd-btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 15px;
border: 1px solid var(--f-g300);
background: #fff;
border-radius: 8px;
font-size: 12.5px;
font-weight: 600;
color: var(--f-g700);
cursor: pointer;
font-family: inherit;
transition: all 0.15s;
&:hover:not(:disabled) {
background: var(--f-g50);
border-color: var(--f-g500);
}
&:disabled {
opacity: 0.55;
cursor: not-allowed;
}
&--primary {
background: var(--f-green);
border-color: var(--f-green);
color: #fff;
&:hover:not(:disabled) {
background: #12692f;
border-color: #12692f;
color: #fff;
}
}
}
/* FILTERS */
.fd-filters {
background: #fff;
border: 1px solid var(--f-g200);
border-radius: 11px;
padding: 12px 16px;
margin-bottom: 14px;
display: flex;
flex-direction: column;
gap: 10px;
}
.fd-filter-row {
display: flex;
align-items: flex-end;
gap: 12px;
flex-wrap: wrap;
}
.fd-modes {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.fd-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border: 1px solid var(--f-g300);
background: #fff;
border-radius: 999px;
font-size: 12.5px;
font-weight: 600;
color: var(--f-g700);
cursor: pointer;
font-family: inherit;
&:hover {
border-color: var(--f-navy);
}
&.active {
background: var(--f-navy);
border-color: var(--f-navy);
color: #fff;
}
}
.fd-field {
display: flex;
flex-direction: column;
gap: 3px;
span {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--f-g500);
}
input,
select {
padding: 7px 10px;
border: 1px solid var(--f-g300);
border-radius: 7px;
font-size: 13px;
font-family: inherit;
background: #fff;
color: var(--f-g900);
&:focus {
outline: none;
border-color: var(--f-navy);
}
&:disabled {
background: var(--f-g100);
color: var(--f-g500);
}
}
&--grow {
flex: 1;
min-width: 240px;
input {
width: 100%;
}
}
}
.fd-resolved {
font-size: 12px;
color: var(--f-g500);
padding-bottom: 8px;
}
.fd-check {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
font-weight: 600;
color: var(--f-g700);
padding-bottom: 8px;
cursor: pointer;
}
.fd-scope-note {
display: flex;
align-items: center;
gap: 7px;
font-size: 12px;
color: var(--f-amber);
background: var(--f-amber-l);
border: 1px solid #fcd34d;
border-radius: 7px;
padding: 6px 11px;
}
/* KPIs */
.fd-kpis {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 14px;
}
.fd-kpi {
background: #fff;
border: 1px solid var(--f-g200);
border-left: 4px solid var(--f-navy);
border-radius: 11px;
padding: 12px 16px;
&--blue {
border-left-color: var(--f-blue);
}
&--amber {
border-left-color: var(--f-amber);
}
&--red {
border-left-color: var(--f-red);
}
}
.fd-kpi-n {
font-size: 22px;
font-weight: 700;
font-family: 'DM Mono', monospace;
}
.fd-kpi-l {
font-size: 12px;
font-weight: 600;
color: var(--f-g700);
}
.fd-kpi-sub {
font-size: 11px;
color: var(--f-g500);
}
/* VIEW SWITCH */
.fd-views {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
}
.fd-spacer {
flex: 1;
}
.fd-count {
font-size: 12px;
color: var(--f-g500);
font-weight: 600;
}
/* TABLE */
.fd-table-wrap {
background: #fff;
border: 1px solid var(--f-g200);
border-radius: 11px;
overflow-x: auto;
}
.fd-table {
width: 100%;
border-collapse: collapse;
font-size: 12.5px;
th {
text-align: left;
padding: 9px 10px;
background: var(--f-g100);
font-size: 10.5px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--f-g700);
white-space: nowrap;
border-bottom: 1px solid var(--f-g200);
}
td {
padding: 8px 10px;
border-bottom: 1px solid var(--f-g100);
vertical-align: top;
}
.num {
text-align: right;
font-family: 'DM Mono', monospace;
}
.strong {
font-weight: 700;
}
tbody tr:hover:not(.fd-detail) {
background: var(--f-g50);
}
}
.fd-person {
cursor: pointer;
&.open {
background: var(--f-blue-l);
}
}
.fd-row--ctr {
background: var(--f-red-l);
}
.fd-detail {
background: #fcfcfe;
td {
padding: 12px 16px 16px;
}
}
.fd-decl {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 8px 18px;
margin-bottom: 12px;
padding: 10px 14px;
background: #fff;
border: 1px solid var(--f-g200);
border-radius: 8px;
> div {
display: flex;
flex-direction: column;
}
.wide {
grid-column: span 2;
}
label {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--f-g500);
}
span {
font-size: 12.5px;
}
}
.fd-subtable {
width: 100%;
border-collapse: collapse;
font-size: 12px;
background: #fff;
border: 1px solid var(--f-g200);
border-radius: 8px;
overflow: hidden;
th {
text-align: left;
padding: 7px 10px;
background: var(--f-g50);
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--f-g500);
white-space: nowrap;
}
td {
padding: 6px 10px;
border-top: 1px solid var(--f-g100);
}
.num {
text-align: right;
font-family: 'DM Mono', monospace;
}
.strong {
font-weight: 700;
}
}
/* Badges */
.fd-form {
display: inline-block;
padding: 1px 8px;
border-radius: 999px;
font-size: 10.5px;
font-weight: 700;
background: var(--f-blue-l);
color: var(--f-blue);
white-space: nowrap;
&--61 {
background: var(--f-green-l);
color: var(--f-green);
}
}
.fd-mode {
display: inline-block;
padding: 1px 7px;
border-radius: 5px;
font-size: 10.5px;
font-weight: 700;
background: var(--f-g100);
color: var(--f-g700);
}
.fd-group {
display: inline-block;
padding: 1px 8px;
border-radius: 999px;
font-size: 10.5px;
font-weight: 600;
background: #fff;
border: 1px solid var(--f-g300);
color: var(--f-g700);
white-space: nowrap;
}
/* Category mix — doubles as a one-click filter. */
.fd-mix {
display: flex;
align-items: center;
gap: 7px;
flex-wrap: wrap;
margin-bottom: 12px;
}
.fd-mix-t {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--f-g500);
margin-right: 2px;
}
.fd-mix-item {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 4px 11px;
border: 1px solid var(--f-g200);
background: #fff;
border-radius: 7px;
font-size: 11.5px;
font-weight: 600;
color: var(--f-g700);
cursor: pointer;
font-family: inherit;
strong {
font-family: 'DM Mono', monospace;
color: var(--f-navy);
}
&:hover {
border-color: var(--f-navy);
}
&.active {
background: var(--f-navy);
border-color: var(--f-navy);
color: #fff;
strong {
color: #fff;
}
}
}
.fd-tag {
display: inline-block;
margin-left: 6px;
padding: 1px 7px;
border-radius: 999px;
font-size: 10px;
font-weight: 700;
background: var(--f-amber-l);
color: var(--f-amber);
white-space: nowrap;
&--ctr {
background: var(--f-red-l);
color: var(--f-red);
}
}
.fd-ratio {
font-weight: 600;
&--mid {
color: var(--f-amber);
}
&--high {
color: var(--f-red);
font-weight: 700;
}
}
.cr {
color: var(--f-green);
font-weight: 700;
}
.dr {
color: var(--f-red);
font-weight: 700;
}
.mono {
font-family: 'DM Mono', monospace;
font-size: 11.5px;
}
.fd-empty {
padding: 44px;
text-align: center;
color: var(--f-g500);
font-size: 13px;
}
/* TOAST */
.fd-toast {
position: fixed;
bottom: 32px;
left: 50%;
transform: translateX(-50%) translateY(20px);
background: var(--f-navy);
color: #fff;
padding: 12px 22px;
border-radius: 10px;
font-size: 13px;
box-shadow: 0 6px 20px rgb(0 0 0 / 25%);
opacity: 0;
pointer-events: none;
transition: all 0.25s;
z-index: 1500;
&.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@media (width <= 1200px) {
.fd-kpis {
grid-template-columns: 1fr 1fr;
}
.fd-decl {
grid-template-columns: 1fr 1fr;
}
}
@@ -0,0 +1,474 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { STANDALONE_SHARED_IMPORTS } from 'app/standalone-shared.module';
import { FaIconComponent } from '@fortawesome/angular-fontawesome';
import * as ExcelJS from 'exceljs';
import { BranchScopeService } from '../core/branch-scope.service';
import { GL_BRANCHES, GL_PERIOD, glBranchName } from '../gl-reports/gl-reports-data';
import { FORM_LABEL, FORM_THRESHOLD, FormType, TXN_GROUPS } from './form-declaration-data';
import {
DateRange,
FormPersonRow,
FormReportFilter,
FormReportSummary,
FormTxnRow,
formPersonRows,
formReportSummary,
formTxnRows,
monthRange,
weekRange
} from './form-declaration.compute';
type PeriodMode = 'day' | 'week' | 'month' | 'range';
type ViewMode = 'person' | 'transaction';
@Component({
selector: 'mifosx-form-declaration-report',
templateUrl: './form-declaration-report.component.html',
styleUrls: ['./form-declaration-report.component.scss'],
imports: [
...STANDALONE_SHARED_IMPORTS,
FaIconComponent,
FormsModule
]
})
export class FormDeclarationReportComponent implements OnInit {
private scope = inject(BranchScopeService);
readonly period = GL_PERIOD;
readonly branches = GL_BRANCHES;
readonly formLabel = FORM_LABEL;
readonly threshold = FORM_THRESHOLD;
readonly txnGroups = TXN_GROUPS;
readonly periodModes: { key: PeriodMode; label: string }[] = [
{ key: 'day', label: 'Day wise' },
{ key: 'week', label: 'Week wise' },
{ key: 'month', label: 'Month wise' },
{ key: 'range', label: 'Between dates' }
];
// ── Filter state ───────────────────────────────────────────────────────────
periodMode: PeriodMode = 'month';
filterDay = '2026-07-31';
/** Any date inside the wanted week; resolved to Mon–Sat. */
filterWeek = '2026-07-27';
filterMonth = '2026-07';
filterFrom = GL_PERIOD.fyStart;
filterTo = GL_PERIOD.fyEnd;
branchCode = '';
formType: FormType | '' = '';
group = '';
search = '';
flaggedOnly = false;
view: ViewMode = 'person';
/** Acknowledgement number of the person row currently expanded. */
expanded: string | null = null;
generating = false;
toastMsg = '';
toastVisible = false;
private toastTimer: any;
ngOnInit(): void {
// A branch login opens on its own book and cannot move off it.
this.branchCode = this.scope.defaultBranchCode;
}
// ── Filter resolution ──────────────────────────────────────────────────────
get range(): DateRange {
if (this.periodMode === 'day') {
return { from: this.filterDay, to: this.filterDay };
}
if (this.periodMode === 'week') {
return weekRange(this.filterWeek);
}
if (this.periodMode === 'month') {
return monthRange(this.filterMonth);
}
return { from: this.filterFrom, to: this.filterTo };
}
get rangeLabel(): string {
const r = this.range;
return r.from === r.to ? r.from : `${r.from} to ${r.to}`;
}
get canSelectBranch(): boolean {
return this.scope.canSelectBranch;
}
get branchLabel(): string {
if (!this.canSelectBranch) {
return this.scope.officeName;
}
return this.branchCode ? glBranchName(this.branchCode) : 'All Branches (Consolidated)';
}
/**
* Applied at the data boundary rather than only in the UI, so a branch login
* cannot widen its own scope by tampering with component state.
*/
private get effectiveBranch(): string {
return this.scope.enforce(this.branchCode);
}
private get filter(): FormReportFilter {
return {
range: this.range,
branchCode: this.effectiveBranch,
formType: this.formType,
group: this.group,
search: this.search,
flaggedOnly: this.flaggedOnly
};
}
resetFilters(): void {
this.periodMode = 'month';
this.filterDay = '2026-07-31';
this.filterWeek = '2026-07-27';
this.filterMonth = '2026-07';
this.filterFrom = GL_PERIOD.fyStart;
this.filterTo = GL_PERIOD.fyEnd;
this.formType = '';
this.group = '';
this.search = '';
this.flaggedOnly = false;
this.expanded = null;
// Reset returns a branch login to its own branch, never to "all".
this.branchCode = this.scope.defaultBranchCode;
}
// ── Data ───────────────────────────────────────────────────────────────────
get summary(): FormReportSummary {
return formReportSummary(this.filter);
}
get personRows(): FormPersonRow[] {
return formPersonRows(this.filter);
}
get txnRows(): FormTxnRow[] {
return formTxnRows(this.filter);
}
toggle(ackNo: string): void {
this.expanded = this.expanded === ackNo ? null : ackNo;
}
/** Cash turnover far above declared income is the point of the report. */
ratioClass(ratio: number): string {
if (ratio >= 5) {
return 'fd-ratio fd-ratio--high';
}
if (ratio >= 2) {
return 'fd-ratio fd-ratio--mid';
}
return 'fd-ratio';
}
// ── Excel ──────────────────────────────────────────────────────────────────
async exportExcel(): Promise<void> {
this.generating = true;
try {
const wb = new ExcelJS.Workbook();
wb.creator = 'CBSNexora';
wb.created = new Date();
this.writeSummarySheet(wb);
this.writePersonSheet(wb);
this.writeTransactionSheet(wb);
const buffer = await wb.xlsx.writeBuffer();
const blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `Form-97-98-Transaction-Report-${this.range.from}-to-${this.range.to}.xlsx`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
this.toast(`Exported ${this.summary.txnCount} transactions for ${this.rangeLabel}`);
} catch {
this.toast('Could not generate the workbook — please retry');
} finally {
this.generating = false;
}
}
/** Title band + filter caption, repeated on every sheet so pages stand alone. */
private banner(sheet: ExcelJS.Worksheet, title: string, cols: number): void {
const t = sheet.addRow([title]);
sheet.mergeCells(t.number, 1, t.number, cols);
t.font = { bold: true, size: 14, color: { argb: 'FFFFFFFF' } };
t.alignment = { horizontal: 'center', vertical: 'middle' };
t.height = 24;
t.getCell(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF1A237E' } };
const formCaption = this.formType ? FORM_LABEL[this.formType] : 'Form 97 and Form 98';
const meta = sheet.addRow([
`Period: ${this.rangeLabel} · Branch: ${this.branchLabel} · Declaration: ${formCaption}` +
` · Category: ${this.group || 'All transaction types'}`
]);
sheet.mergeCells(meta.number, 1, meta.number, cols);
meta.font = { italic: true, size: 10 };
sheet.addRow([]);
}
private headerRow(sheet: ExcelJS.Worksheet, headers: string[]): void {
const head = sheet.addRow(headers);
head.font = { bold: true };
head.alignment = { wrapText: true, horizontal: 'center' };
head.eachCell((c) => {
c.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE2E8F0' } };
c.border = { bottom: { style: 'thin' } };
});
}
private writeSummarySheet(wb: ExcelJS.Workbook): void {
const s = this.summary;
const sheet = wb.addWorksheet('Summary');
sheet.columns = [
{ width: 52 },
{ width: 24 }];
this.banner(sheet, 'Form 97 / 98 Transaction Report — Summary', 2);
this.headerRow(sheet, [
'Particulars',
'Value'
]);
const money = new Set([
'Total cash turnover',
'Total credits',
'Total debits'
]);
const lines: [string, string | number][] = [
[
'Declarants transacting in the period',
s.persons
],
[
' of which Form 97 (no PAN)',
s.form60Persons
],
[
' of which Form 98 (agricultural income only)',
s.form61Persons
],
[
'Total transactions — all types',
s.txnCount
],
[
' of which cash (counter and ATM)',
s.cashCount
],
[
' of which in a Rule 114B category',
s.declarationRequired
],
[
'Total cash turnover',
s.cashTotal
],
[
'Total credits',
s.totalCredit
],
[
'Total debits',
s.totalDebit
],
[
`Cash transactions at or above ₹${FORM_THRESHOLD.CTR.toLocaleString('en-IN')} (CTR reportable)`,
s.ctrReportable
]
];
for (const [
label,
value
] of lines) {
const row = sheet.addRow([
label,
value
]);
if (money.has(label)) {
row.getCell(2).numFmt = '#,##0.00';
}
}
// Category mix — what the customer group actually does, beyond the
// declared transactions.
sheet.addRow([]);
this.headerRow(sheet, [
'Transaction category',
'Count'
]);
for (const g of s.byGroup) {
sheet.addRow([
g.group,
g.count
]);
}
sheet.views = [{ state: 'frozen', ySplit: 4 }];
}
private writePersonSheet(wb: ExcelJS.Workbook): void {
const sheet = wb.addWorksheet('Person wise');
const widths = [
18,
12,
26,
24,
18,
14,
10,
10,
10,
16,
16,
16,
14,
10,
34
];
sheet.columns = widths.map((w) => ({ width: w }));
this.banner(sheet, 'Form 97 / 98 Transaction Report — Person wise', widths.length);
this.headerRow(sheet, [
'Acknowledgement',
'Form',
'Name of declarant',
"Father's name",
'Account No',
'Branch',
'Total txns',
'Cash txns',
'Rule 114B txns',
'Cash turnover',
'Total credit',
'Total debit',
'Declared income',
'CTR rows',
'Categories transacted'
]);
for (const p of this.personRows) {
const row = sheet.addRow([
p.declarant.ackNo,
FORM_LABEL[p.declarant.formType],
p.declarant.name,
p.declarant.fatherName,
p.declarant.accountNo,
glBranchName(p.declarant.branchCode),
p.txnCount,
p.cashCount,
p.declaredCount,
p.cashTotal,
p.totalCredit,
p.totalDebit,
p.declarant.estimatedIncome,
p.ctrCount,
p.groups.join(', ')
]);
for (const c of [
10,
11,
12,
13
]) {
row.getCell(c).numFmt = '#,##0.00';
}
}
sheet.views = [{ state: 'frozen', ySplit: 4 }];
}
private writeTransactionSheet(wb: ExcelJS.Workbook): void {
const sheet = wb.addWorksheet('Transactions');
const widths = [
12,
12,
18,
12,
26,
18,
14,
12,
10,
6,
16,
46,
16,
12
];
sheet.columns = widths.map((w) => ({ width: w }));
this.banner(sheet, 'Form 97 / 98 Transaction Report — Transaction wise', widths.length);
this.headerRow(sheet, [
'Date',
'Txn ID',
'Acknowledgement',
'Form',
'Name of declarant',
'Account No',
'Branch',
'Category',
'Mode',
'Dr/Cr',
'Amount',
'Nature of transaction',
'Voucher No',
'Flag'
]);
for (const t of this.txnRows) {
const row = sheet.addRow([
t.date,
t.txnId,
t.ackNo,
FORM_LABEL[t.formType],
t.declarantName,
t.accountNo,
glBranchName(t.branchCode),
t.group,
t.mode,
t.drCr,
t.amount,
t.nature,
t.voucherNo,
t.ctrReportable ? 'CTR' : t.declarationRequired ? 'Rule 114B' : ''
]);
row.getCell(11).numFmt = '#,##0.00';
if (t.ctrReportable) {
row.getCell(14).font = { bold: true, color: { argb: 'FFC0392B' } };
}
}
sheet.views = [{ state: 'frozen', ySplit: 4 }];
}
private toast(msg: string): void {
this.toastMsg = msg;
this.toastVisible = true;
if (this.toastTimer) {
clearTimeout(this.toastTimer);
}
this.toastTimer = setTimeout(() => (this.toastVisible = false), 3200);
}
}
@@ -0,0 +1,296 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { GL_PERIOD } from '../gl-reports/gl-reports-data';
import {
FORM_THRESHOLD,
FormDeclarant,
FormDeclarantTxn,
FormType,
formDeclarants,
formDeclarantTxns
} from './form-declaration-data';
export interface DateRange {
from: string;
to: string;
}
export interface FormReportFilter {
range: DateRange;
/** '' means every branch. */
branchCode: string;
/** '' means both declaration types. */
formType: FormType | '';
/** '' means every transaction category (Cash, Clearing, Loan, …). */
group: string;
/** Free text over name, account number and acknowledgement number. */
search: string;
/** Show only rows a compliance officer would need to look at. */
flaggedOnly: boolean;
}
/** One transaction, joined to the declarant who filed for it. */
export interface FormTxnRow extends FormDeclarantTxn {
declarantName: string;
formType: FormType;
fatherName: string;
declaredOn: string;
reasonForNoPan: string;
estimatedIncome: number;
/** Counter or ATM cash, as opposed to a book or electronic entry. */
isCash: boolean;
/**
* The transaction is one of the categories in Rule 114B, so PAN — and in its
* absence the Form 97/98 declaration — was mandatory for it.
*/
declarationRequired: boolean;
/** Cash at or above the CTR limit — also lands in the monthly CTR. */
ctrReportable: boolean;
}
/** A declarant with their totals for the period. */
export interface FormPersonRow {
declarant: FormDeclarant;
txns: FormTxnRow[];
txnCount: number;
cashCount: number;
totalCredit: number;
totalDebit: number;
cashTotal: number;
/** Largest single transaction, used to sort the riskiest to the top. */
maxAmount: number;
/** How many of the period's transactions needed the declaration. */
declaredCount: number;
ctrCount: number;
/** Distinct categories the customer transacted in during the period. */
groups: string[];
/**
* Aggregate cash for the period against the income the customer declared.
* A ratio well above 1 is the classic "turnover inconsistent with declared
* income" flag, which is why the declaration is collected in the first place.
*/
incomeRatio: number;
}
export interface FormReportSummary {
persons: number;
form60Persons: number;
form61Persons: number;
txnCount: number;
cashTotal: number;
cashCount: number;
totalCredit: number;
totalDebit: number;
/** Transactions falling in a Rule 114B category. */
declarationRequired: number;
ctrReportable: number;
/** Transaction count by category, largest first — drives the mix panel. */
byGroup: { group: string; count: number; amount: number }[];
}
function clamp(range: DateRange): DateRange {
const from = range.from < GL_PERIOD.fyStart ? GL_PERIOD.fyStart : range.from;
const to = range.to > GL_PERIOD.fyEnd ? GL_PERIOD.fyEnd : range.to;
// A backwards range would silently return nothing; collapse it to a single day.
return from > to ? { from: to, to: to } : { from, to };
}
/** Monday-to-Saturday banking week containing the given date. */
export function weekRange(anchor: string): DateRange {
const d = new Date(`${anchor}T00:00:00Z`);
const dow = d.getUTCDay(); // 0 = Sunday
const monday = new Date(d.getTime());
monday.setUTCDate(d.getUTCDate() - (dow === 0 ? 6 : dow - 1));
const saturday = new Date(monday.getTime());
saturday.setUTCDate(monday.getUTCDate() + 5);
const iso = (x: Date) => x.toISOString().slice(0, 10);
return { from: iso(monday), to: iso(saturday) };
}
export function monthRange(month: string): DateRange {
const [
y,
m
] = month.split('-').map(Number);
const last = new Date(Date.UTC(y, m, 0)).getUTCDate();
return { from: `${month}-01`, to: `${month}-${`${last}`.padStart(2, '0')}` };
}
/**
* Transactions matching the filter, each joined to its declarant.
*
* Memoised on the filter signature: the getters that feed the template are read
* many times per change-detection pass, and re-scanning several hundred rows on
* every read is what made the GL reports stall.
*/
let rowCacheKey = '';
let rowCache: FormTxnRow[] = [];
export function formTxnRows(filter: FormReportFilter): FormTxnRow[] {
const range = clamp(filter.range);
const key = [
range.from,
range.to,
filter.branchCode,
filter.formType,
filter.group,
filter.search.trim().toLowerCase(),
filter.flaggedOnly ? '1' : '0'
].join('|');
if (key === rowCacheKey) {
return rowCache;
}
const byAck = new Map(
formDeclarants().map((d) => [
d.ackNo,
d
])
);
const needle = filter.search.trim().toLowerCase();
const rows: FormTxnRow[] = [];
for (const t of formDeclarantTxns()) {
if (t.date < range.from || t.date > range.to) {
continue;
}
if (filter.branchCode && t.branchCode !== filter.branchCode) {
continue;
}
if (filter.group && t.group !== filter.group) {
continue;
}
const d = byAck.get(t.ackNo);
if (!d) {
continue;
}
if (filter.formType && d.formType !== filter.formType) {
continue;
}
if (
needle &&
!d.name.toLowerCase().includes(needle) &&
!t.accountNo.toLowerCase().includes(needle) &&
!d.ackNo.toLowerCase().includes(needle)
) {
continue;
}
// ATM dispensing is cash in the customer's hands, so it counts towards the
// cash view even though it never crossed the counter.
const isCash = t.mode === 'CASH' || t.mode === 'ATM';
const ctrReportable = isCash && t.amount >= FORM_THRESHOLD.CTR;
if (filter.flaggedOnly && !ctrReportable) {
continue;
}
rows.push({
...t,
declarantName: d.name,
formType: d.formType,
fatherName: d.fatherName,
declaredOn: d.declaredOn,
reasonForNoPan: d.reasonForNoPan,
estimatedIncome: d.estimatedIncome,
isCash,
declarationRequired: t.rule114B,
ctrReportable
});
}
rowCacheKey = key;
rowCache = rows;
return rows;
}
/** The same rows grouped by declarant, heaviest customer first. */
export function formPersonRows(filter: FormReportFilter): FormPersonRow[] {
const byAck = new Map(
formDeclarants().map((d) => [
d.ackNo,
d
])
);
const grouped = new Map<string, FormTxnRow[]>();
for (const r of formTxnRows(filter)) {
const list = grouped.get(r.ackNo);
if (list) {
list.push(r);
} else {
grouped.set(r.ackNo, [r]);
}
}
const out: FormPersonRow[] = [];
for (const [
ackNo,
txns
] of grouped) {
const declarant = byAck.get(ackNo);
if (!declarant) {
continue;
}
const cash = txns.filter((t) => t.isCash);
const cashTotal = cash.reduce((s, t) => s + t.amount, 0);
out.push({
declarant,
txns,
txnCount: txns.length,
cashCount: cash.length,
totalCredit: txns.filter((t) => t.drCr === 'CR').reduce((s, t) => s + t.amount, 0),
totalDebit: txns.filter((t) => t.drCr === 'DR').reduce((s, t) => s + t.amount, 0),
cashTotal,
maxAmount: txns.reduce((m, t) => Math.max(m, t.amount), 0),
declaredCount: txns.filter((t) => t.declarationRequired).length,
ctrCount: txns.filter((t) => t.ctrReportable).length,
groups: [...new Set(txns.map((t) => t.group))].sort(),
incomeRatio: declarant.estimatedIncome > 0 ? cashTotal / declarant.estimatedIncome : 0
});
}
out.sort((a, b) => b.cashTotal - a.cashTotal);
return out;
}
export function formReportSummary(filter: FormReportFilter): FormReportSummary {
const rows = formTxnRows(filter);
const acks = new Set(rows.map((r) => r.ackNo));
const form61 = new Set(rows.filter((r) => r.formType === 'FORM_61').map((r) => r.ackNo));
const form60 = new Set(rows.filter((r) => r.formType === 'FORM_60').map((r) => r.ackNo));
const groupMap = new Map<string, { group: string; count: number; amount: number }>();
for (const r of rows) {
const g = groupMap.get(r.group);
if (g) {
g.count++;
g.amount += r.amount;
} else {
groupMap.set(r.group, { group: r.group, count: 1, amount: r.amount });
}
}
const cash = rows.filter((r) => r.isCash);
return {
persons: acks.size,
form60Persons: form60.size,
form61Persons: form61.size,
txnCount: rows.length,
cashTotal: cash.reduce((s, r) => s + r.amount, 0),
cashCount: cash.length,
totalCredit: rows.filter((r) => r.drCr === 'CR').reduce((s, r) => s + r.amount, 0),
totalDebit: rows.filter((r) => r.drCr === 'DR').reduce((s, r) => s + r.amount, 0),
declarationRequired: rows.filter((r) => r.declarationRequired).length,
ctrReportable: rows.filter((r) => r.ctrReportable).length,
byGroup: [...groupMap.values()].sort((a, b) => b.count - a.count)
};
}
+723
View File
@@ -0,0 +1,723 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* Data layer for the General Ledger report suite.
*
* Rather than hard-coding seven finished reports, this file holds a chart of
* accounts plus a generated ledger of double-entry postings. Every report is
* then computed from those postings, which is what makes the day / month /
* branch filters genuinely recompute instead of just re-labelling a static table.
*
* The generator is deterministic — a fixed-seed LCG, never Math.random — so the
* figures are identical on every reload and across users. Amounts are in rupees.
*/
export type GlAccountType = 'ASSET' | 'LIABILITY' | 'INCOME' | 'EXPENSE' | 'CONTINGENT';
export interface GlAccount {
code: string;
name: string;
type: GlAccountType;
/** Balance-sheet / P&L grouping used as a sub-heading in the reports. */
group: string;
/** Included in the Misc Expense Ledger report. */
miscExpense?: boolean;
}
export interface GlBranch {
code: string;
name: string;
}
/** One side of a double-entry voucher. */
export interface GlPosting {
/** ISO yyyy-MM-dd — the posting (value) date. */
date: string;
branchCode: string;
accountCode: string;
debit: number;
credit: number;
voucherNo: string;
narration: string;
}
export const GL_BRANCHES: GlBranch[] = [
{ code: 'HO', name: 'Head Office' },
{ code: '0002', name: 'Andheri (E)' },
{ code: '0003', name: 'Bandra (W)' },
{ code: '0004', name: 'Borivali' },
{ code: '0005', name: 'Dadar' },
{ code: '0006', name: 'Thane' }
];
export const GL_ACCOUNTS: GlAccount[] = [
// ── Assets ────────────────────────────────────────────────────────────────
{ code: '110101', name: 'Cash in Hand', type: 'ASSET', group: 'Cash & Bank Balances' },
{ code: '110102', name: 'Balance with RBI', type: 'ASSET', group: 'Cash & Bank Balances' },
{ code: '110103', name: 'Balance with Other Banks — Current', type: 'ASSET', group: 'Cash & Bank Balances' },
{ code: '110104', name: 'Balance with Other Banks — Fixed', type: 'ASSET', group: 'Cash & Bank Balances' },
{ code: '120101', name: 'SLR Investments — Govt Securities', type: 'ASSET', group: 'Investments' },
{ code: '120102', name: 'SLR Investments — State Govt Securities', type: 'ASSET', group: 'Investments' },
{ code: '120201', name: 'Non-SLR Investments — Bonds', type: 'ASSET', group: 'Investments' },
{ code: '120202', name: 'Non-SLR Investments — Mutual Funds', type: 'ASSET', group: 'Investments' },
{ code: '130101', name: 'Cash Credit & Overdrafts', type: 'ASSET', group: 'Loans & Advances' },
{ code: '130102', name: 'Term Loans — Short Term', type: 'ASSET', group: 'Loans & Advances' },
{ code: '130103', name: 'Term Loans — Medium Term', type: 'ASSET', group: 'Loans & Advances' },
{ code: '130104', name: 'Term Loans — Long Term', type: 'ASSET', group: 'Loans & Advances' },
{ code: '130105', name: 'Housing Loans', type: 'ASSET', group: 'Loans & Advances' },
{ code: '130106', name: 'Gold Loans', type: 'ASSET', group: 'Loans & Advances' },
{ code: '140101', name: 'Interest Receivable', type: 'ASSET', group: 'Other Assets' },
{ code: '140102', name: 'Premises (net of depreciation)', type: 'ASSET', group: 'Fixed Assets' },
{ code: '140103', name: 'Furniture & Fixtures (net)', type: 'ASSET', group: 'Fixed Assets' },
{ code: '140104', name: 'Sundry Debtors', type: 'ASSET', group: 'Other Assets' },
{ code: '140105', name: 'Advance Tax & TDS', type: 'ASSET', group: 'Other Assets' },
{ code: '140199', name: 'Opening Balance Suspense (unreconciled)', type: 'ASSET', group: 'Other Assets' },
// ── Liabilities & Capital ─────────────────────────────────────────────────
{ code: '210101', name: 'Share Capital — Individuals', type: 'LIABILITY', group: 'Capital & Reserves' },
{ code: '210201', name: 'Statutory Reserve Fund', type: 'LIABILITY', group: 'Capital & Reserves' },
{ code: '210202', name: 'Building Fund', type: 'LIABILITY', group: 'Capital & Reserves' },
{ code: '210203', name: 'Investment Depreciation Reserve', type: 'LIABILITY', group: 'Capital & Reserves' },
{ code: '210204', name: 'BDDR / Special BDDR', type: 'LIABILITY', group: 'Capital & Reserves' },
{ code: '220101', name: 'Savings Bank Deposits', type: 'LIABILITY', group: 'Deposits' },
{ code: '220102', name: 'Current Deposits', type: 'LIABILITY', group: 'Deposits' },
{ code: '220103', name: 'Term Deposits', type: 'LIABILITY', group: 'Deposits' },
{ code: '220104', name: 'Recurring Deposits', type: 'LIABILITY', group: 'Deposits' },
{ code: '230101', name: 'Interest Payable on Deposits', type: 'LIABILITY', group: 'Other Liabilities' },
{ code: '230102', name: 'Bills Payable', type: 'LIABILITY', group: 'Other Liabilities' },
{ code: '230103', name: 'Sundry Creditors', type: 'LIABILITY', group: 'Other Liabilities' },
{ code: '230104', name: 'TDS / GST Payable', type: 'LIABILITY', group: 'Other Liabilities' },
{ code: '230105', name: 'Overdue Interest Reserve', type: 'LIABILITY', group: 'Other Liabilities' },
// ── Income ────────────────────────────────────────────────────────────────
{ code: '310101', name: 'Interest on Loans & Advances', type: 'INCOME', group: 'Interest Income' },
{ code: '310102', name: 'Interest on Investments', type: 'INCOME', group: 'Interest Income' },
{ code: '310103', name: 'Interest on Inter-bank Deposits', type: 'INCOME', group: 'Interest Income' },
{ code: '320101', name: 'Commission & Exchange', type: 'INCOME', group: 'Other Income' },
{ code: '320102', name: 'Locker Rent', type: 'INCOME', group: 'Other Income' },
{ code: '320103', name: 'Processing Fees', type: 'INCOME', group: 'Other Income' },
{ code: '320104', name: 'Profit on Sale of Securities', type: 'INCOME', group: 'Other Income' },
{ code: '320105', name: 'Miscellaneous Income', type: 'INCOME', group: 'Other Income' },
// ── Expenditure ───────────────────────────────────────────────────────────
{ code: '410101', name: 'Interest on Savings Deposits', type: 'EXPENSE', group: 'Interest Expended' },
{ code: '410102', name: 'Interest on Term Deposits', type: 'EXPENSE', group: 'Interest Expended' },
{ code: '410103', name: 'Interest on Borrowings', type: 'EXPENSE', group: 'Interest Expended' },
{ code: '420101', name: 'Salaries & Allowances', type: 'EXPENSE', group: 'Operating Expenses' },
{ code: '420102', name: "Directors' Fees", type: 'EXPENSE', group: 'Operating Expenses' },
{ code: '420103', name: "Auditors' Fees", type: 'EXPENSE', group: 'Operating Expenses' },
{ code: '420104', name: 'Rent, Taxes & Lighting', type: 'EXPENSE', group: 'Operating Expenses' },
{ code: '420105', name: 'Depreciation on Bank Property', type: 'EXPENSE', group: 'Operating Expenses' },
{
code: '430101',
name: 'Printing & Stationery',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430102',
name: 'Postage, Telegram & Telephone',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430103',
name: 'Advertisement & Publicity',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430104',
name: 'Repairs & Maintenance',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430105',
name: 'Travelling & Conveyance',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430106',
name: 'Computer & Software Expenses',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430107',
name: 'Legal & Professional Charges',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430108',
name: 'Insurance (DICGC & Other)',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430109',
name: 'Bank Charges & Commission Paid',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{
code: '430110',
name: 'AGM & Meeting Expenses',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
{ code: '430111', name: 'Electricity Charges', type: 'EXPENSE', group: 'Miscellaneous Expenses', miscExpense: true },
{
code: '430112',
name: 'Other Miscellaneous Expenses',
type: 'EXPENSE',
group: 'Miscellaneous Expenses',
miscExpense: true
},
// ── Contingent (memoranda, not part of the balance sheet totals) ──────────
{ code: '910101', name: 'Guarantees Issued — Financial', type: 'CONTINGENT', group: 'Guarantees' },
{ code: '910102', name: 'Guarantees Issued — Performance', type: 'CONTINGENT', group: 'Guarantees' },
{ code: '910103', name: 'Letters of Credit Outstanding', type: 'CONTINGENT', group: 'Letters of Credit' },
{ code: '910104', name: 'Bills for Collection', type: 'CONTINGENT', group: 'Bills & Claims' },
{ code: '910105', name: 'Claims Against Bank Not Acknowledged as Debt', type: 'CONTINGENT', group: 'Bills & Claims' },
{ code: '910106', name: 'Forward Exchange Contracts', type: 'CONTINGENT', group: 'Other Commitments' },
{ code: '910107', name: 'Capital Commitments Not Provided For', type: 'CONTINGENT', group: 'Other Commitments' }
];
/** Financial year covered by the generated ledger. */
export const GL_PERIOD = {
/** FY 2026-27 opens here. */
fyStart: '2026-04-01',
/** Postings run to the day before the app's "today" (01 Aug 2026). */
fyEnd: '2026-07-31',
label: 'FY 2026-27'
};
/**
* Opening balances as at 01-Apr-2026, keyed by account code. Positive means the
* account opens on its natural side (debit for assets/expenses, credit for the
* rest). Head Office carries the investments and reserves; branches carry the
* customer-facing book.
*/
const OPENING_BALANCES: Record<string, number> = {
'110101': 9_996_000,
'110102': 12_400_000,
'110103': 13_667_000,
// Surplus deposits parked with correspondent banks. Sized so the opening
// balance sheet tallies exactly — see the assertion in glPostings().
'110104': 54_206_000,
'120101': 63_839_000,
'120102': 147_895_000,
'120201': 22_500_000,
'120202': 24_234_000,
'130101': 166_614_000,
'130102': 125_082_000,
'130103': 70_236_000,
'130104': 29_356_000,
'130105': 10_241_000,
'130106': 8_450_000,
'140101': 33_541_000,
'140102': 3_185_000,
'140103': 1_763_000,
'140104': 1_240_000,
'140105': 657_000,
'210101': 27_278_000,
'210201': 31_149_000,
'210202': 13_642_000,
'210203': 3_750_000,
'210204': 24_341_000,
'220101': 208_116_000,
'220102': 19_592_000,
'220103': 406_601_000,
'220104': 24_880_000,
'230101': 731_000,
'230102': 291_000,
'230103': 5_515_000,
'230104': 1_120_000,
'230105': 32_096_000,
'910101': 1_450_000,
'910102': 980_000,
'910103': 620_000,
'910104': 1_180_000,
'910105': 2_638_000,
'910106': 0,
'910107': 340_000
};
/** Deterministic linear congruential generator — same figures on every load. */
function lcg(seed: number): () => number {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 4294967296;
};
}
function isoDate(d: Date): string {
const y = d.getUTCFullYear();
const m = `${d.getUTCMonth() + 1}`.padStart(2, '0');
const day = `${d.getUTCDate()}`.padStart(2, '0');
return `${y}-${m}-${day}`;
}
/** Every posting date in the ledger period, Sundays excluded (bank holiday). */
export function ledgerDates(): string[] {
const out: string[] = [];
const cur = new Date(`${GL_PERIOD.fyStart}T00:00:00Z`);
const end = new Date(`${GL_PERIOD.fyEnd}T00:00:00Z`);
while (cur <= end) {
if (cur.getUTCDay() !== 0) {
out.push(isoDate(cur));
}
cur.setUTCDate(cur.getUTCDate() + 1);
}
return out;
}
/** Templates for the vouchers the generator posts each day. */
const VOUCHER_TEMPLATES: {
debit: string;
credit: string;
narration: string;
/** Rough rupee scale of the voucher. */
scale: number;
/** Chance the voucher is raised on any given branch-day. */
frequency: number;
}[] = [
{ debit: '110101', credit: '220101', narration: 'Cash deposit — savings accounts', scale: 900_000, frequency: 1 },
{ debit: '220101', credit: '110101', narration: 'Cash withdrawal — savings accounts', scale: 780_000, frequency: 1 },
{ debit: '110101', credit: '220103', narration: 'Term deposit received', scale: 1_400_000, frequency: 0.75 },
{ debit: '220103', credit: '110101', narration: 'Term deposit matured and paid', scale: 1_150_000, frequency: 0.6 },
{ debit: '110101', credit: '220102', narration: 'Current account deposit', scale: 620_000, frequency: 0.8 },
{ debit: '220102', credit: '110101', narration: 'Current account withdrawal', scale: 560_000, frequency: 0.8 },
{ debit: '110101', credit: '220104', narration: 'Recurring deposit instalment', scale: 180_000, frequency: 0.7 },
{ debit: '130101', credit: '110101', narration: 'Cash credit disbursed', scale: 1_250_000, frequency: 0.55 },
{ debit: '110101', credit: '130101', narration: 'Cash credit repayment', scale: 1_100_000, frequency: 0.6 },
{ debit: '130102', credit: '110101', narration: 'Short term loan disbursed', scale: 850_000, frequency: 0.4 },
{ debit: '110101', credit: '130102', narration: 'Short term loan repayment', scale: 760_000, frequency: 0.5 },
{ debit: '130103', credit: '110101', narration: 'Medium term loan disbursed', scale: 640_000, frequency: 0.3 },
{ debit: '110101', credit: '130104', narration: 'Long term loan repayment', scale: 410_000, frequency: 0.35 },
{ debit: '130105', credit: '110101', narration: 'Housing loan disbursed', scale: 520_000, frequency: 0.2 },
{ debit: '130106', credit: '110101', narration: 'Gold loan disbursed', scale: 260_000, frequency: 0.4 },
// Interest on advances is the dominant earning line — sized so the bank runs a
// ~13% net margin rather than the loss the first-cut figures produced.
{ debit: '110101', credit: '310101', narration: 'Interest recovered on advances', scale: 430_000, frequency: 1 },
{ debit: '140101', credit: '310102', narration: 'Interest accrued on investments', scale: 148_000, frequency: 0.5 },
{ debit: '110103', credit: '310103', narration: 'Interest on inter-bank deposits', scale: 42_000, frequency: 0.25 },
{ debit: '110101', credit: '320101', narration: 'Commission and exchange collected', scale: 26_000, frequency: 0.9 },
{ debit: '110101', credit: '320102', narration: 'Locker rent collected', scale: 9_000, frequency: 0.3 },
{ debit: '110101', credit: '320103', narration: 'Loan processing fees', scale: 18_000, frequency: 0.5 },
{ debit: '110101', credit: '320105', narration: 'Miscellaneous income', scale: 7_500, frequency: 0.4 },
{
debit: '410101',
credit: '230101',
narration: 'Interest provided on savings deposits',
scale: 128_000,
frequency: 0.8
},
{
debit: '410102',
credit: '230101',
narration: 'Interest provided on term deposits',
scale: 265_000,
frequency: 0.9
},
{ debit: '420101', credit: '110101', narration: 'Salaries and allowances paid', scale: 210_000, frequency: 0.35 },
{ debit: '420104', credit: '110101', narration: 'Rent, taxes and lighting', scale: 46_000, frequency: 0.3 },
{ debit: '430101', credit: '110101', narration: 'Printing and stationery purchased', scale: 9_400, frequency: 0.3 },
{ debit: '430102', credit: '110101', narration: 'Postage and telephone charges', scale: 6_200, frequency: 0.35 },
{ debit: '430103', credit: '110101', narration: 'Advertisement and publicity', scale: 12_500, frequency: 0.15 },
{ debit: '430104', credit: '110101', narration: 'Repairs and maintenance', scale: 15_800, frequency: 0.25 },
{ debit: '430105', credit: '110101', narration: 'Travelling and conveyance', scale: 7_100, frequency: 0.3 },
{ debit: '430106', credit: '110101', narration: 'Computer and software expenses', scale: 22_400, frequency: 0.2 },
{ debit: '430107', credit: '110101', narration: 'Legal and professional charges', scale: 11_300, frequency: 0.15 },
{ debit: '430109', credit: '110101', narration: 'Bank charges and commission paid', scale: 4_800, frequency: 0.3 },
{ debit: '430111', credit: '110101', narration: 'Electricity charges', scale: 13_600, frequency: 0.25 },
{ debit: '430112', credit: '110101', narration: 'Other miscellaneous expenses', scale: 8_900, frequency: 0.3 },
{
debit: '110102',
credit: '110101',
narration: 'Cash remitted to RBI currency chest',
scale: 1_800_000,
frequency: 0.2
},
{
debit: '110101',
credit: '110103',
narration: 'Funds drawn from correspondent bank',
scale: 1_400_000,
frequency: 0.2
}
];
/** Head-Office-only vouchers — investments, reserves and centralised charges. */
const HO_TEMPLATES: typeof VOUCHER_TEMPLATES = [
{ debit: '120101', credit: '110102', narration: 'Purchase of Govt securities', scale: 2_400_000, frequency: 0.12 },
{
debit: '120102',
credit: '110102',
narration: 'Purchase of State Govt securities',
scale: 1_900_000,
frequency: 0.12
},
{ debit: '110102', credit: '320104', narration: 'Profit on sale of securities', scale: 78_000, frequency: 0.1 },
{ debit: '420102', credit: '110101', narration: "Directors' sitting fees", scale: 32_000, frequency: 0.08 },
{ debit: '420103', credit: '110101', narration: "Statutory auditors' fees", scale: 45_000, frequency: 0.06 },
{ debit: '420105', credit: '140103', narration: 'Depreciation charged on assets', scale: 64_000, frequency: 0.12 },
{ debit: '430108', credit: '110101', narration: 'DICGC premium and other insurance', scale: 38_000, frequency: 0.1 },
{ debit: '430110', credit: '110101', narration: 'AGM and meeting expenses', scale: 26_000, frequency: 0.06 },
{ debit: '410103', credit: '230101', narration: 'Interest on borrowings', scale: 54_000, frequency: 0.1 },
{ debit: '230104', credit: '110102', narration: 'TDS and GST remitted', scale: 145_000, frequency: 0.15 }
];
/**
* Contingent-account movements are memoranda, each posted single-sided.
* Guarantees, LCs and collection bills are raised at the counter, so these run
* at every branch — not just Head Office.
*/
const CONTINGENT_TEMPLATES: { account: string; narration: string; scale: number; frequency: number }[] = [
{ account: '910101', narration: 'Financial guarantee issued', scale: 320_000, frequency: 0.1 },
{ account: '910102', narration: 'Performance guarantee issued', scale: 240_000, frequency: 0.08 },
{ account: '910103', narration: 'Letter of credit opened', scale: 180_000, frequency: 0.07 },
{ account: '910104', narration: 'Bills lodged for collection', scale: 95_000, frequency: 0.12 },
{ account: '910105', narration: 'Claim lodged against the bank', scale: 140_000, frequency: 0.03 },
{ account: '910107', narration: 'Capital commitment contracted', scale: 85_000, frequency: 0.04 }
];
/**
* How the opening contingent book is spread across the network. Head Office
* carries the capital commitments and large claims; the branches carry the
* counter-issued guarantees. Weights are applied per account and the rounding
* remainder is absorbed by Head Office so each account's total stays exact.
*/
const CONTINGENT_BRANCH_WEIGHTS: Record<string, number> = {
HO: 0.2,
'0002': 0.18,
'0003': 0.16,
'0004': 0.16,
'0005': 0.15,
'0006': 0.15
};
let cachedPostings: GlPosting[] | null = null;
/**
* The full generated ledger. Built once and memoised — every report reads from
* this array, so the reports can never disagree with one another.
*/
export function glPostings(): GlPosting[] {
if (cachedPostings) {
return cachedPostings;
}
const rand = lcg(20260401);
const out: GlPosting[] = [];
const dates = ledgerDates();
let voucherSeq = 1;
// Opening entries, posted at Head Office on day one so the books start in balance.
const openingVoucher = `OB/${GL_PERIOD.label.replace(/\s/g, '')}`;
let openingDebit = 0;
let openingCredit = 0;
for (const [
code,
amount
] of Object.entries(OPENING_BALANCES)) {
if (!amount) {
continue;
}
const account = GL_ACCOUNTS.find((a) => a.code === code);
if (!account) {
continue;
}
const debitSide = account.type === 'ASSET' || account.type === 'EXPENSE' || account.type === 'CONTINGENT';
// Contingent accounts are single-sided memoranda held at the issuing branch,
// so their opening book is spread across the network rather than sat at HO.
if (account.type === 'CONTINGENT') {
let allocated = 0;
for (const branch of GL_BRANCHES) {
if (branch.code === 'HO') {
continue;
}
const share = Math.round((amount * (CONTINGENT_BRANCH_WEIGHTS[branch.code] ?? 0)) / 100) * 100;
if (!share) {
continue;
}
allocated += share;
out.push({
date: GL_PERIOD.fyStart,
branchCode: branch.code,
accountCode: code,
debit: share,
credit: 0,
voucherNo: openingVoucher,
narration: 'Opening balance brought forward'
});
}
// Head Office takes its own share plus whatever rounding left behind.
out.push({
date: GL_PERIOD.fyStart,
branchCode: 'HO',
accountCode: code,
debit: amount - allocated,
credit: 0,
voucherNo: openingVoucher,
narration: 'Opening balance brought forward'
});
continue;
}
out.push({
date: GL_PERIOD.fyStart,
branchCode: 'HO',
accountCode: code,
debit: debitSide ? amount : 0,
credit: debitSide ? 0 : amount,
voucherNo: openingVoucher,
narration: 'Opening balance brought forward'
});
if (debitSide) {
openingDebit += amount;
} else {
openingCredit += amount;
}
}
// If OPENING_BALANCES is ever edited so the two sides diverge, park the residual
// in a visibly-named suspense account rather than letting the trial balance drift.
const openingResidual = openingCredit - openingDebit;
if (openingResidual !== 0) {
out.push({
date: GL_PERIOD.fyStart,
branchCode: 'HO',
accountCode: '140199',
debit: openingResidual > 0 ? openingResidual : 0,
credit: openingResidual < 0 ? -openingResidual : 0,
voucherNo: openingVoucher,
narration: 'Unreconciled opening balance difference'
});
}
const round = (n: number): number => Math.round(n / 100) * 100;
for (const date of dates) {
for (const branch of GL_BRANCHES) {
// Head Office posts fewer counter transactions than the branches.
const weight = branch.code === 'HO' ? 0.45 : 1;
const templates = branch.code === 'HO' ? [
...VOUCHER_TEMPLATES,
...HO_TEMPLATES
] : VOUCHER_TEMPLATES;
for (const tpl of templates) {
if (rand() > tpl.frequency * weight) {
continue;
}
// 0.55x .. 1.45x of the template scale keeps daily figures varied but plausible.
const amount = round(tpl.scale * (0.55 + rand() * 0.9));
if (amount <= 0) {
continue;
}
const voucherNo = `${branch.code}/${date.slice(5, 7)}/${`${voucherSeq++}`.padStart(5, '0')}`;
out.push({
date,
branchCode: branch.code,
accountCode: tpl.debit,
debit: amount,
credit: 0,
voucherNo,
narration: tpl.narration
});
out.push({
date,
branchCode: branch.code,
accountCode: tpl.credit,
debit: 0,
credit: amount,
voucherNo,
narration: tpl.narration
});
}
// Contingent memoranda are raised at every branch, weighted by its size.
const contingentWeight = CONTINGENT_BRANCH_WEIGHTS[branch.code] ?? 0.15;
for (const tpl of CONTINGENT_TEMPLATES) {
// Claims against the bank and capital commitments are Head Office matters.
const headOfficeOnly = tpl.account === '910105' || tpl.account === '910107';
if (headOfficeOnly && branch.code !== 'HO') {
continue;
}
const frequency = headOfficeOnly ? tpl.frequency : tpl.frequency * (contingentWeight / 0.2);
if (rand() > frequency) {
continue;
}
const amount = round(tpl.scale * (0.55 + rand() * 0.9));
out.push({
date,
branchCode: branch.code,
accountCode: tpl.account,
debit: amount,
credit: 0,
voucherNo: `CNT/${branch.code}/${date.slice(5, 7)}/${`${voucherSeq++}`.padStart(5, '0')}`,
narration: tpl.narration
});
}
}
}
cachedPostings = out;
return out;
}
/**
* Customer sub-ledger.
*
* The GL is account-level, so a client-wise report needs a customer dimension on top.
* Each customer holds a share of one GL head at one branch; balances are not stored,
* they are derived at query time as `share x that head's GL balance`. That way the
* client-wise report always reconciles to the General Ledger exactly, whatever period
* or branch is selected, instead of drifting as a second source of truth.
*/
export interface GlCustomer {
cif: string;
name: string;
branchCode: string;
/** GL head this relationship sits under. */
accountCode: string;
accountNo: string;
/** Fraction of the branch's balance in that head. Shares per (branch, head) sum to 1. */
share: number;
}
const FIRST_NAMES = [
'Ravi',
'Priya',
'Vikram',
'Nirav',
'Kavita',
'Arjun',
'Lakshmi',
'Sameer',
'Anjali',
'Rohan',
'Meera',
'Karan',
'Divya',
'Sanjay',
'Pooja',
'Amit',
'Sneha',
'Manish',
'Rekha',
'Deepak'
];
const LAST_NAMES = [
'Sharma',
'Patel',
'Reddy',
'Shah',
'Verma',
'Deshmukh',
'Iyer',
'Kapoor',
'Nair',
'Joshi',
'Mehta',
'Gupta',
'Rao',
'Bhatt',
'Chauhan'
];
const FIRMS = [
'Traders',
'Enterprises',
'Agencies',
'& Sons',
'Industries',
'Stores',
'Corporation'
];
/** Customer-facing heads a client relationship can sit under. */
const CUSTOMER_HEADS = [
'220101',
'220102',
'220103',
'220104',
'130101',
'130102',
'130103',
'130104',
'130105',
'130106'
];
let cachedCustomers: GlCustomer[] | null = null;
export function glCustomers(): GlCustomer[] {
if (cachedCustomers) {
return cachedCustomers;
}
const rand = lcg(76543210);
const out: GlCustomer[] = [];
let seq = 1;
for (const branch of GL_BRANCHES) {
for (const head of CUSTOMER_HEADS) {
// Deposits are held by many customers; advances by fewer, larger ones.
const isAdvance = head.startsWith('13');
const count = isAdvance ? 2 + Math.floor(rand() * 3) : 3 + Math.floor(rand() * 4);
const weights: number[] = [];
for (let i = 0; i < count; i++) {
weights.push(0.35 + rand() * 0.65);
}
const weightTotal = weights.reduce((a, b) => a + b, 0);
for (let i = 0; i < count; i++) {
const corporate = isAdvance && rand() > 0.55;
const name = corporate
? `${LAST_NAMES[Math.floor(rand() * LAST_NAMES.length)]} ${FIRMS[Math.floor(rand() * FIRMS.length)]}`
: `${FIRST_NAMES[Math.floor(rand() * FIRST_NAMES.length)]} ${LAST_NAMES[Math.floor(rand() * LAST_NAMES.length)]}`;
out.push({
cif: `CIF${`${100000 + seq}`}`,
name,
branchCode: branch.code,
accountCode: head,
accountNo: `${branch.code === 'HO' ? '0001' : branch.code}${head}${`${seq}`.padStart(4, '0')}`,
share: weights[i] / weightTotal
});
seq++;
}
}
}
cachedCustomers = out;
return out;
}
export function glAccount(code: string): GlAccount | undefined {
return GL_ACCOUNTS.find((a) => a.code === code);
}
export function glBranchName(code: string): string {
return GL_BRANCHES.find((b) => b.code === code)?.name ?? code;
}
@@ -0,0 +1,34 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Route } from '../core/route/route.service';
const routes: Routes = [
Route.withShell([
{
path: 'gl/reports',
// Lazy — the generated ledger and ExcelJS should not weigh down the eager bundle.
loadComponent: () => import('./gl-reports.component').then((m) => m.GlReportsComponent),
data: { title: 'General Ledger Reports', breadcrumb: 'GL Reports' }
},
{
path: 'gl/reports/:report',
loadComponent: () => import('./gl-reports.component').then((m) => m.GlReportsComponent),
data: { title: 'General Ledger Reports', breadcrumb: 'GL Reports' }
}
])
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class GlReportsRoutingModule {}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,560 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
:host {
--g-navy: #1a237e;
--g-blue: #1d4ed8;
--g-blue-l: #eff6ff;
--g-teal: #0e7e6b;
--g-teal-l: #e0f4f0;
--g-green: #15803d;
--g-green-l: #dcfce7;
--g-amber: #b45309;
--g-amber-l: #fef3c7;
--g-red: #c0392b;
--g-red-l: #fdecea;
--g-g50: #f8fafc;
--g-g100: #f1f5f9;
--g-g200: #e2e8f0;
--g-g300: #cbd5e1;
--g-g500: #64748b;
--g-g700: #334155;
--g-g900: #0f172a;
display: block;
font-family:
'DM Sans',
system-ui,
-apple-system,
sans-serif;
background: var(--g-g50);
color: var(--g-g900);
font-size: 14px;
line-height: 1.5;
}
.glr-root {
padding: 18px 22px;
max-width: 1700px;
margin: 0 auto;
}
/* HEADER */
.glr-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 14px;
}
.glr-head-left {
display: flex;
align-items: center;
gap: 14px;
}
.glr-head-ic {
font-size: 28px;
color: var(--g-navy);
}
.glr-head-t {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.glr-head-s {
font-size: 12px;
color: var(--g-g500);
}
/* BUTTONS */
.glr-btn {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 9px 16px;
border: 1px solid var(--g-g300);
background: #fff;
border-radius: 8px;
font-size: 13px;
font-weight: 600;
color: var(--g-g700);
cursor: pointer;
font-family: inherit;
transition: all 0.15s;
white-space: nowrap;
&:hover:not(:disabled) {
background: var(--g-g50);
border-color: var(--g-g500);
}
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
}
.glr-btn-xls {
background: #16a34a;
border-color: #16a34a;
color: #fff;
&:hover:not(:disabled) {
background: #15803d;
border-color: #15803d;
color: #fff;
}
}
/* FILTER BAR */
.glr-filters {
background: #fff;
border: 1px solid var(--g-g200);
border-radius: 12px;
padding: 14px;
display: flex;
align-items: flex-end;
gap: 14px;
flex-wrap: wrap;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgb(0 0 0 / 4%);
}
.glr-filter {
display: flex;
flex-direction: column;
gap: 5px;
label {
font-size: 11px;
font-weight: 700;
color: var(--g-g500);
text-transform: uppercase;
letter-spacing: 0.05em;
}
}
.glr-inp {
padding: 8px 12px;
border: 1px solid var(--g-g200);
border-radius: 8px;
font-size: 13px;
background: #fff;
font-family: inherit;
min-width: 190px;
&:focus {
outline: none;
border-color: var(--g-navy);
box-shadow: 0 0 0 3px rgb(26 35 126 / 12%);
}
}
/* Read-only branch shown to a branch-level login in place of the selector. */
.glr-chip {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 8px 14px;
min-width: 190px;
border: 1px solid var(--g-g200);
border-radius: 8px;
background: var(--g-g100);
font-size: 13px;
font-weight: 600;
color: var(--g-g700);
}
/* Day / Month / Range segmented control */
.glr-seg {
display: inline-flex;
border: 1px solid var(--g-g200);
border-radius: 8px;
overflow: hidden;
button {
padding: 8px 14px;
border: none;
background: #fff;
font-size: 13px;
font-weight: 600;
color: var(--g-g500);
cursor: pointer;
font-family: inherit;
transition: all 0.15s;
+ button {
border-left: 1px solid var(--g-g200);
}
&:hover {
background: var(--g-g50);
}
&.active {
background: var(--g-navy);
color: #fff;
}
}
}
/* REPORT SELECTOR */
.glr-tabs {
display: flex;
gap: 4px;
background: #fff;
border: 1px solid var(--g-g200);
border-radius: 10px;
padding: 4px;
margin-bottom: 16px;
overflow-x: auto;
}
.glr-tab {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 9px 14px;
border: none;
background: transparent;
font-size: 13px;
font-weight: 500;
color: var(--g-g500);
cursor: pointer;
border-radius: 7px;
white-space: nowrap;
transition: all 0.15s;
font-family: inherit;
&:hover {
color: var(--g-g900);
}
&.active {
background: var(--g-navy);
color: #fff;
box-shadow: 0 2px 6px rgb(26 35 126 / 25%);
}
}
.glr-section {
display: flex;
flex-direction: column;
gap: 16px;
}
/* BALANCE BANNER */
.glr-balance {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
border-radius: 10px;
background: var(--g-green-l);
border: 1px solid #86efac;
color: #14532d;
font-size: 13px;
&--bad {
background: var(--g-red-l);
border-color: #fca5a5;
color: #7f1d1d;
}
}
.glr-note {
margin: 0;
font-size: 12px;
color: var(--g-g500);
}
/* KPIs */
.glr-kpis {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
}
.glr-kpi {
background: #fff;
border: 1px solid var(--g-g200);
border-left: 4px solid var(--g-g300);
border-radius: 12px;
padding: 14px 18px;
box-shadow: 0 1px 3px rgb(0 0 0 / 5%);
&--teal {
border-left-color: var(--g-teal);
}
&--amber {
border-left-color: var(--g-amber);
}
&--green {
border-left-color: var(--g-green);
}
&--red {
border-left-color: var(--g-red);
}
}
.glr-kpi-n {
font-size: 20px;
font-weight: 700;
font-family: 'DM Mono', monospace;
color: var(--g-g900);
}
.glr-kpi-l {
font-size: 12px;
color: var(--g-g700);
font-weight: 600;
margin-top: 2px;
}
.glr-kpi-sub {
font-size: 11px;
color: var(--g-g500);
}
/* TABLES */
.glr-two-col {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
align-items: start;
}
.glr-tbl-wrap {
background: #fff;
border: 1px solid var(--g-g200);
border-radius: 12px;
overflow: auto;
box-shadow: 0 1px 3px rgb(0 0 0 / 4%);
&--tall {
max-height: 70vh;
}
}
.glr-tbl-h {
background: var(--g-blue-l);
color: var(--g-navy);
padding: 10px 16px;
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
border-bottom: 1px solid var(--g-g200);
position: sticky;
top: 0;
z-index: 2;
}
.glr-tbl {
width: 100%;
border-collapse: collapse;
th {
text-align: left;
padding: 9px 12px;
font-size: 11px;
font-weight: 700;
color: var(--g-g500);
text-transform: uppercase;
letter-spacing: 0.04em;
background: var(--g-g50);
border-bottom: 1px solid var(--g-g200);
white-space: nowrap;
}
td {
padding: 8px 12px;
border-bottom: 1px solid var(--g-g100);
font-size: 13px;
color: var(--g-g700);
}
tbody tr:hover td {
background: var(--g-g50);
}
tfoot td {
position: sticky;
bottom: 0;
}
}
.total-row td {
background: var(--g-g100) !important;
font-weight: 700;
color: var(--g-g900);
border-top: 2px solid var(--g-g300);
}
.glr-profit-row td {
background: var(--g-green-l) !important;
color: #14532d;
}
.glr-loss-row td {
background: var(--g-red-l) !important;
color: #7f1d1d;
}
.ta-c {
text-align: center;
}
.ta-r {
text-align: right;
}
.mono {
font-family: 'DM Mono', monospace;
font-size: 12px;
}
.muted {
color: var(--g-g500);
font-size: 11px;
}
.var-up {
color: var(--g-green);
font-weight: 600;
}
.var-down {
color: var(--g-red);
font-weight: 600;
}
.glr-empty {
text-align: center;
padding: 34px;
color: var(--g-g500);
font-style: italic;
}
/* A voucher whose debits and credits disagree. */
.glr-unbalanced td {
background: var(--g-red-l) !important;
color: #7f1d1d;
font-weight: 600;
}
/* GL code chips on the mapping report */
.glr-gl-chip {
display: inline-block;
padding: 1px 8px;
margin: 1px 3px 1px 0;
border-radius: 999px;
background: #e0f2fe;
color: #075985;
font-size: 11px;
font-weight: 600;
}
/* Share bars on the distribution report */
.glr-bar-col {
width: 150px;
}
.glr-bar {
height: 9px;
border-radius: 999px;
background: var(--g-g100);
overflow: hidden;
min-width: 110px;
}
.glr-bar-fill {
height: 100%;
border-radius: 999px;
background: linear-gradient(90deg, var(--g-navy), var(--g-blue));
transition: width 0.25s;
}
/* Account-type pills on the GL Wise report */
.type-pill {
display: inline-block;
padding: 2px 9px;
border-radius: 999px;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
background: var(--g-g100);
color: var(--g-g700);
&.type-asset {
background: var(--g-blue-l);
color: var(--g-blue);
}
&.type-liability {
background: var(--g-teal-l);
color: var(--g-teal);
}
&.type-income {
background: var(--g-green-l);
color: var(--g-green);
}
&.type-expense {
background: var(--g-amber-l);
color: var(--g-amber);
}
&.type-contingent {
background: var(--g-red-l);
color: var(--g-red);
}
}
/* TOAST */
.glr-toast {
position: fixed;
bottom: 32px;
left: 50%;
transform: translateX(-50%) translateY(20px);
background: var(--g-navy);
color: #fff;
padding: 12px 22px;
border-radius: 10px;
font-size: 13px;
font-weight: 500;
box-shadow: 0 6px 20px rgb(0 0 0 / 25%);
opacity: 0;
pointer-events: none;
transition: all 0.25s;
z-index: 1500;
&.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@media (width <= 1200px) {
.glr-two-col {
grid-template-columns: 1fr;
}
.glr-kpis {
grid-template-columns: 1fr;
}
}
File diff suppressed because it is too large Load Diff
+843
View File
@@ -0,0 +1,843 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/**
* Derives all seven General Ledger reports from the posting ledger.
*
* Each report is a pure function of (postings, date range, branch), so changing
* the day / month / branch filter genuinely recomputes the figures. Results are
* memoised per filter key because the ledger runs to roughly twenty thousand
* postings and Angular re-evaluates template getters on every change detection.
*/
import { GL_ACCOUNTS, GL_PERIOD, GlAccount, GlPosting, glAccount, glCustomers, glPostings } from './gl-reports-data';
export interface GlDateRange {
from: string;
to: string;
}
export interface TrialBalanceRow {
code: string;
name: string;
group: string;
openingDebit: number;
openingCredit: number;
periodDebit: number;
periodCredit: number;
closingDebit: number;
closingCredit: number;
}
export interface PnlRow {
code: string;
name: string;
group: string;
amount: number;
}
export interface BalanceSheetRow {
code: string;
name: string;
group: string;
amount: number;
}
export interface ComparativeRow {
code: string;
name: string;
group: string;
side: 'ASSET' | 'LIABILITY';
current: number;
previous: number;
variance: number;
variancePct: number | null;
}
export interface GlWiseRow {
code: string;
name: string;
group: string;
type: string;
debit: number;
credit: number;
net: number;
vouchers: number;
}
export interface MiscExpenseRow {
date: string;
voucherNo: string;
branchCode: string;
code: string;
name: string;
narration: string;
amount: number;
}
/** Natural side of an account — assets and expenses sit on the debit side. */
function isDebitSide(account: GlAccount): boolean {
return account.type === 'ASSET' || account.type === 'EXPENSE' || account.type === 'CONTINGENT';
}
function matchesBranch(p: GlPosting, branchCode: string): boolean {
return !branchCode || p.branchCode === branchCode;
}
/**
* Both scans below walk the whole ~21k-posting ledger, so their results are cached
* per (date, branch). Angular re-evaluates template getters on every change-detection
* pass; without this a screen with a few hundred mapped lines would spend seconds per
* click rescanning the ledger and appear frozen.
*/
const balanceCache = new Map<string, Map<string, number>>();
const turnoverCache = new Map<string, Map<string, { debit: number; credit: number; vouchers: Set<string> }>>();
/** Signed balance on the account's natural side, for postings up to and including `to`. */
function cumulativeBalances(to: string, branchCode: string): Map<string, number> {
const key = `${to}|${branchCode}`;
const hit = balanceCache.get(key);
if (hit) {
return hit;
}
const out = new Map<string, number>();
for (const p of glPostings()) {
if (p.date > to || !matchesBranch(p, branchCode)) {
continue;
}
const account = glAccount(p.accountCode);
if (!account) {
continue;
}
const delta = isDebitSide(account) ? p.debit - p.credit : p.credit - p.debit;
out.set(p.accountCode, (out.get(p.accountCode) ?? 0) + delta);
}
balanceCache.set(key, out);
return out;
}
/** Debit and credit turnover strictly inside the range. */
function periodTurnover(
range: GlDateRange,
branchCode: string
): Map<string, { debit: number; credit: number; vouchers: Set<string> }> {
const key = `${range.from}|${range.to}|${branchCode}`;
const hit = turnoverCache.get(key);
if (hit) {
return hit;
}
const out = new Map<string, { debit: number; credit: number; vouchers: Set<string> }>();
for (const p of glPostings()) {
if (p.date < range.from || p.date > range.to || !matchesBranch(p, branchCode)) {
continue;
}
let entry = out.get(p.accountCode);
if (!entry) {
entry = { debit: 0, credit: 0, vouchers: new Set<string>() };
out.set(p.accountCode, entry);
}
entry.debit += p.debit;
entry.credit += p.credit;
entry.vouchers.add(p.voucherNo);
}
turnoverCache.set(key, out);
return out;
}
/** The day before `date`, ISO formatted — used for opening balances. */
function previousDay(date: string): string {
const d = new Date(`${date}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() - 1);
return d.toISOString().slice(0, 10);
}
// ── Reports ──────────────────────────────────────────────────────────────────
export function trialBalance(range: GlDateRange, branchCode: string): TrialBalanceRow[] {
const opening = cumulativeBalances(previousDay(range.from), branchCode);
const turnover = periodTurnover(range, branchCode);
const rows: TrialBalanceRow[] = [];
for (const account of GL_ACCOUNTS) {
// Contingent accounts are memoranda and never appear in the trial balance.
if (account.type === 'CONTINGENT') {
continue;
}
const open = opening.get(account.code) ?? 0;
const move = turnover.get(account.code);
const periodDebit = move?.debit ?? 0;
const periodCredit = move?.credit ?? 0;
if (!open && !periodDebit && !periodCredit) {
continue;
}
const debitSide = isDebitSide(account);
const closingNatural = open + (debitSide ? periodDebit - periodCredit : periodCredit - periodDebit);
const closingSigned = debitSide ? closingNatural : -closingNatural;
rows.push({
code: account.code,
name: account.name,
group: account.group,
openingDebit: debitSide && open > 0 ? open : !debitSide && open < 0 ? -open : 0,
openingCredit: !debitSide && open > 0 ? open : debitSide && open < 0 ? -open : 0,
periodDebit,
periodCredit,
closingDebit: closingSigned > 0 ? closingSigned : 0,
closingCredit: closingSigned < 0 ? -closingSigned : 0
});
}
return rows;
}
export function profitAndLoss(range: GlDateRange, branchCode: string): { income: PnlRow[]; expense: PnlRow[] } {
const turnover = periodTurnover(range, branchCode);
const income: PnlRow[] = [];
const expense: PnlRow[] = [];
for (const account of GL_ACCOUNTS) {
if (account.type !== 'INCOME' && account.type !== 'EXPENSE') {
continue;
}
const move = turnover.get(account.code);
if (!move) {
continue;
}
const amount = account.type === 'INCOME' ? move.credit - move.debit : move.debit - move.credit;
if (!amount) {
continue;
}
const row: PnlRow = { code: account.code, name: account.name, group: account.group, amount };
(account.type === 'INCOME' ? income : expense).push(row);
}
return { income, expense };
}
/**
* Balance sheet as at the period end. The current-period surplus is folded in as
* a liability line so the two sides tally the way the printed statement does.
*/
export function balanceSheet(
range: GlDateRange,
branchCode: string
): {
assets: BalanceSheetRow[];
liabilities: BalanceSheetRow[];
surplus: number;
} {
const closing = cumulativeBalances(range.to, branchCode);
const assets: BalanceSheetRow[] = [];
const liabilities: BalanceSheetRow[] = [];
let income = 0;
let expense = 0;
for (const account of GL_ACCOUNTS) {
const bal = closing.get(account.code) ?? 0;
if (account.type === 'INCOME') {
income += bal;
continue;
}
if (account.type === 'EXPENSE') {
expense += bal;
continue;
}
if (account.type === 'CONTINGENT' || !bal) {
continue;
}
const row: BalanceSheetRow = { code: account.code, name: account.name, group: account.group, amount: bal };
(account.type === 'ASSET' ? assets : liabilities).push(row);
}
return { assets, liabilities, surplus: income - expense };
}
/** Current period against the equivalent span immediately before it. */
export function comparativeBalanceSheet(range: GlDateRange, branchCode: string): ComparativeRow[] {
const priorTo = previousDay(range.from);
const current = cumulativeBalances(range.to, branchCode);
const previous = cumulativeBalances(priorTo, branchCode);
const rows: ComparativeRow[] = [];
for (const account of GL_ACCOUNTS) {
if (account.type !== 'ASSET' && account.type !== 'LIABILITY') {
continue;
}
const cur = current.get(account.code) ?? 0;
const prev = previous.get(account.code) ?? 0;
if (!cur && !prev) {
continue;
}
const variance = cur - prev;
rows.push({
code: account.code,
name: account.name,
group: account.group,
side: account.type,
current: cur,
previous: prev,
variance,
variancePct: prev ? (variance / Math.abs(prev)) * 100 : null
});
}
return rows;
}
export function contingentLiabilities(range: GlDateRange, branchCode: string): BalanceSheetRow[] {
const closing = cumulativeBalances(range.to, branchCode);
return GL_ACCOUNTS.filter((a) => a.type === 'CONTINGENT')
.map((a) => ({ code: a.code, name: a.name, group: a.group, amount: closing.get(a.code) ?? 0 }))
.filter((r) => r.amount !== 0);
}
export function glWiseDrCr(range: GlDateRange, branchCode: string): GlWiseRow[] {
const turnover = periodTurnover(range, branchCode);
const rows: GlWiseRow[] = [];
for (const account of GL_ACCOUNTS) {
const move = turnover.get(account.code);
if (!move || (!move.debit && !move.credit)) {
continue;
}
rows.push({
code: account.code,
name: account.name,
group: account.group,
type: account.type,
debit: move.debit,
credit: move.credit,
net: move.debit - move.credit,
vouchers: move.vouchers.size
});
}
return rows;
}
export function miscExpenseLedger(range: GlDateRange, branchCode: string): MiscExpenseRow[] {
const miscCodes = new Set(GL_ACCOUNTS.filter((a) => a.miscExpense).map((a) => a.code));
const rows: MiscExpenseRow[] = [];
for (const p of glPostings()) {
if (p.date < range.from || p.date > range.to || !matchesBranch(p, branchCode)) {
continue;
}
if (!miscCodes.has(p.accountCode) || !p.debit) {
continue;
}
rows.push({
date: p.date,
voucherNo: p.voucherNo,
branchCode: p.branchCode,
code: p.accountCode,
name: glAccount(p.accountCode)?.name ?? p.accountCode,
narration: p.narration,
amount: p.debit
});
}
return rows.sort((a, b) =>
a.date === b.date ? a.voucherNo.localeCompare(b.voucherNo) : a.date.localeCompare(b.date)
);
}
export interface AverageBalanceRow {
code: string;
name: string;
group: string;
type: string;
opening: number;
closing: number;
average: number;
peak: number;
lowest: number;
/** Days on which the account moved. */
activeDays: number;
}
export interface AccountBranchRow {
code: string;
name: string;
group: string;
/** Closing balance per branch code, plus a `total`. */
byBranch: Record<string, number>;
total: number;
}
export interface DistributionRow {
group: string;
amount: number;
share: number;
accounts: number;
}
/** Calendar days in the range, inclusive. */
function daysInRange(range: GlDateRange): string[] {
const out: string[] = [];
const cur = new Date(`${range.from}T00:00:00Z`);
const end = new Date(`${range.to}T00:00:00Z`);
while (cur <= end) {
out.push(cur.toISOString().slice(0, 10));
cur.setUTCDate(cur.getUTCDate() + 1);
}
return out;
}
/**
* Average daily balance per account across the period, plus the peak and lowest
* balance touched. Banks use average balances rather than closing snapshots for
* interest, CRR/SLR and profitability work, because a closing figure can be
* window-dressed on the last day.
*
* Computed by carrying a running balance forward day by day rather than
* recomputing a cumulative balance per day, which would be quadratic.
*/
export function averageBalances(range: GlDateRange, branchCode: string): AverageBalanceRow[] {
const opening = cumulativeBalances(previousDay(range.from), branchCode);
const days = daysInRange(range);
// Net movement per account per day, on the account's natural side.
const dailyDelta = new Map<string, Map<string, number>>();
const movedOn = new Map<string, Set<string>>();
for (const p of glPostings()) {
if (p.date < range.from || p.date > range.to || !matchesBranch(p, branchCode)) {
continue;
}
const account = glAccount(p.accountCode);
if (!account) {
continue;
}
const delta = isDebitSide(account) ? p.debit - p.credit : p.credit - p.debit;
let perDay = dailyDelta.get(p.accountCode);
if (!perDay) {
perDay = new Map<string, number>();
dailyDelta.set(p.accountCode, perDay);
}
perDay.set(p.date, (perDay.get(p.date) ?? 0) + delta);
let seen = movedOn.get(p.accountCode);
if (!seen) {
seen = new Set<string>();
movedOn.set(p.accountCode, seen);
}
seen.add(p.date);
}
const rows: AverageBalanceRow[] = [];
for (const account of GL_ACCOUNTS) {
const open = opening.get(account.code) ?? 0;
const perDay = dailyDelta.get(account.code);
if (!open && !perDay) {
continue;
}
let running = open;
let total = 0;
let peak = open;
let lowest = open;
for (const d of days) {
running += perDay?.get(d) ?? 0;
total += running;
peak = Math.max(peak, running);
lowest = Math.min(lowest, running);
}
rows.push({
code: account.code,
name: account.name,
group: account.group,
type: account.type,
opening: open,
closing: running,
average: days.length ? total / days.length : 0,
peak,
lowest,
activeDays: movedOn.get(account.code)?.size ?? 0
});
}
return rows;
}
/**
* Closing balance of every account broken out by branch. Answers "which branch is
* carrying this balance", which a single consolidated column cannot.
*/
export function accountWiseByBranch(range: GlDateRange, branchCodes: string[]): AccountBranchRow[] {
const perBranch = new Map<string, Map<string, number>>();
for (const b of branchCodes) {
perBranch.set(b, cumulativeBalances(range.to, b));
}
const rows: AccountBranchRow[] = [];
for (const account of GL_ACCOUNTS) {
const byBranch: Record<string, number> = {};
let total = 0;
let any = false;
for (const b of branchCodes) {
const v = perBranch.get(b)?.get(account.code) ?? 0;
byBranch[b] = v;
total += v;
if (v) {
any = true;
}
}
if (!any) {
continue;
}
rows.push({ code: account.code, name: account.name, group: account.group, byBranch, total });
}
return rows;
}
/**
* Share of the closing book held by each account group, for one side of the
* balance sheet. Used to see concentration at a glance.
*/
export function balanceDistribution(
range: GlDateRange,
branchCode: string,
side: 'ASSET' | 'LIABILITY'
): DistributionRow[] {
const closing = cumulativeBalances(range.to, branchCode);
const byGroup = new Map<string, { amount: number; accounts: number }>();
let grand = 0;
for (const account of GL_ACCOUNTS) {
if (account.type !== side) {
continue;
}
const v = closing.get(account.code) ?? 0;
if (!v) {
continue;
}
const entry = byGroup.get(account.group) ?? { amount: 0, accounts: 0 };
entry.amount += v;
entry.accounts += 1;
byGroup.set(account.group, entry);
grand += v;
}
return [...byGroup.entries()]
.map(
([
group,
e
]) => ({
group,
amount: e.amount,
accounts: e.accounts,
share: grand ? (e.amount / grand) * 100 : 0
})
)
.sort((a, b) => b.amount - a.amount);
}
export interface ClientBalanceRow {
cif: string;
name: string;
branchCode: string;
accountNo: string;
accountCode: string;
product: string;
/** DEPOSIT or ADVANCE — which side of the relationship this is. */
side: 'DEPOSIT' | 'ADVANCE';
balance: number;
}
export interface BankerHeadRow {
head: string;
opening: number;
debit: number;
credit: number;
closing: number;
accounts: number;
}
export interface SundryItemRow {
date: string;
voucherNo: string;
branchCode: string;
code: string;
name: string;
narration: string;
amount: number;
/** Days outstanding as at the period end. */
ageDays: number;
bucket: string;
}
export interface VoucherRow {
voucherNo: string;
date: string;
branchCode: string;
narration: string;
debitAccounts: string;
creditAccounts: string;
amount: number;
legs: number;
/** False when debits and credits on the voucher do not agree. */
balanced: boolean;
}
/**
* Client-wise balances, derived from the GL rather than stored separately so the two
* can never disagree. Each customer's balance is its share of the branch's closing
* balance in the head it sits under.
*/
export function clientWiseBalances(range: GlDateRange, branchCode: string): ClientBalanceRow[] {
const rows: ClientBalanceRow[] = [];
const branchClosings = new Map<string, Map<string, number>>();
for (const c of glCustomers()) {
if (branchCode && c.branchCode !== branchCode) {
continue;
}
let closing = branchClosings.get(c.branchCode);
if (!closing) {
closing = cumulativeBalances(range.to, c.branchCode);
branchClosings.set(c.branchCode, closing);
}
const headBalance = closing.get(c.accountCode) ?? 0;
const balance = headBalance * c.share;
if (Math.abs(balance) < 0.005) {
continue;
}
const account = glAccount(c.accountCode);
rows.push({
cif: c.cif,
name: c.name,
branchCode: c.branchCode,
accountNo: c.accountNo,
accountCode: c.accountCode,
product: account?.name ?? c.accountCode,
side: c.accountCode.startsWith('13') ? 'ADVANCE' : 'DEPOSIT',
balance
});
}
return rows.sort((a, b) => b.balance - a.balance);
}
/**
* Head-wise abstract: the trial balance rolled up to principal heads, the summary a
* banker reads before the detail. Opening, turnover and closing per head.
*/
export function bankerHeadSummary(range: GlDateRange, branchCode: string): BankerHeadRow[] {
const opening = cumulativeBalances(previousDay(range.from), branchCode);
const turnover = periodTurnover(range, branchCode);
const byHead = new Map<string, BankerHeadRow>();
for (const account of GL_ACCOUNTS) {
// Contingents are single-sided off-balance-sheet memoranda. Including them would
// make the abstract's debit and credit turnover disagree and stop it reconciling
// to the trial balance, which also excludes them. They have their own report.
if (account.type === 'CONTINGENT') {
continue;
}
const open = opening.get(account.code) ?? 0;
const move = turnover.get(account.code);
if (!open && !move) {
continue;
}
const debit = move?.debit ?? 0;
const credit = move?.credit ?? 0;
const closing = open + (isDebitSide(account) ? debit - credit : credit - debit);
const row = byHead.get(account.group) ?? {
head: account.group,
opening: 0,
debit: 0,
credit: 0,
closing: 0,
accounts: 0
};
row.opening += open;
row.debit += debit;
row.credit += credit;
row.closing += closing;
row.accounts += 1;
byHead.set(account.group, row);
}
return [...byHead.values()];
}
const SUNDRY_CODES = [
'140104',
'230103',
'140199',
'230102'
];
/**
* Outstanding items in the sundry and suspense heads, aged from the posting date.
* These accounts are where unreconciled entries accumulate, so ageing is the point
* of the register.
*/
export function sundryRegister(range: GlDateRange, branchCode: string): SundryItemRow[] {
const wanted = new Set(SUNDRY_CODES);
const end = new Date(`${range.to}T00:00:00Z`).getTime();
const rows: SundryItemRow[] = [];
for (const p of glPostings()) {
if (p.date > range.to || !matchesBranch(p, branchCode) || !wanted.has(p.accountCode)) {
continue;
}
const ageDays = Math.max(0, Math.round((end - new Date(`${p.date}T00:00:00Z`).getTime()) / 86400000));
const bucket =
ageDays <= 30
? 'Up to 30 days'
: ageDays <= 90
? '31 to 90 days'
: ageDays <= 180
? '91 to 180 days'
: 'Over 180 days';
rows.push({
date: p.date,
voucherNo: p.voucherNo,
branchCode: p.branchCode,
code: p.accountCode,
name: glAccount(p.accountCode)?.name ?? p.accountCode,
narration: p.narration,
amount: p.debit || p.credit,
ageDays,
bucket
});
}
return rows.sort((a, b) => b.ageDays - a.ageDays);
}
/**
* Every voucher raised in the period with its debit and credit legs collapsed onto
* one line, plus a per-voucher double-entry check.
*/
export function voucherRegister(range: GlDateRange, branchCode: string): VoucherRow[] {
const grouped = new Map<string, GlPosting[]>();
for (const p of glPostings()) {
if (p.date < range.from || p.date > range.to || !matchesBranch(p, branchCode)) {
continue;
}
const list = grouped.get(p.voucherNo);
if (list) {
list.push(p);
} else {
grouped.set(p.voucherNo, [p]);
}
}
const rows: VoucherRow[] = [];
for (const [
voucherNo,
legs
] of grouped) {
const debits = legs.filter((l) => l.debit > 0);
const credits = legs.filter((l) => l.credit > 0);
const drTotal = debits.reduce((s, l) => s + l.debit, 0);
const crTotal = credits.reduce((s, l) => s + l.credit, 0);
const nameOf = (codes: GlPosting[], side: 'debit' | 'credit') =>
[...new Set(codes.map((l) => `${l.accountCode} ${glAccount(l.accountCode)?.name ?? ''}`.trim()))].join(', ');
rows.push({
voucherNo,
date: legs[0].date,
branchCode: legs[0].branchCode,
narration: legs[0].narration,
debitAccounts: nameOf(debits, 'debit') || '—',
creditAccounts: nameOf(credits, 'credit') || '—',
amount: Math.max(drTotal, crTotal),
legs: legs.length,
// Contingent and opening memoranda are single-sided by design.
balanced: voucherNo.startsWith('CNT/') || voucherNo.startsWith('OB/') || Math.round(drTotal - crTotal) === 0
});
}
return rows.sort((a, b) =>
a.date === b.date ? a.voucherNo.localeCompare(b.voucherNo) : a.date.localeCompare(b.date)
);
}
// ── Memoisation ──────────────────────────────────────────────────────────────
export interface GlReportSet {
trialBalance: TrialBalanceRow[];
pnl: { income: PnlRow[]; expense: PnlRow[] };
balanceSheet: { assets: BalanceSheetRow[]; liabilities: BalanceSheetRow[]; surplus: number };
comparative: ComparativeRow[];
contingent: BalanceSheetRow[];
glWise: GlWiseRow[];
miscExpense: MiscExpenseRow[];
}
let cacheKey = '';
let cached: GlReportSet | null = null;
/** All seven reports for one filter selection, computed once per selection. */
export function buildReports(range: GlDateRange, branchCode: string): GlReportSet {
const key = `${range.from}|${range.to}|${branchCode}`;
if (cached && cacheKey === key) {
return cached;
}
cached = {
trialBalance: trialBalance(range, branchCode),
pnl: profitAndLoss(range, branchCode),
balanceSheet: balanceSheet(range, branchCode),
comparative: comparativeBalanceSheet(range, branchCode),
contingent: contingentLiabilities(range, branchCode),
glWise: glWiseDrCr(range, branchCode),
miscExpense: miscExpenseLedger(range, branchCode)
};
cacheKey = key;
return cached;
}
/** Clamp a range to the generated ledger so filters cannot query empty space. */
export function clampToLedger(range: GlDateRange): GlDateRange {
return {
from: range.from < GL_PERIOD.fyStart ? GL_PERIOD.fyStart : range.from,
to: range.to > GL_PERIOD.fyEnd ? GL_PERIOD.fyEnd : range.to
};
}
/**
* Value of a set of GL accounts for a period, used when an RBI return line item is
* mapped to the chart of accounts.
*
* Balance-sheet accounts contribute their closing balance as at the period end;
* income and expenditure accounts contribute their movement within the period.
* That mirrors how the two kinds of figure are read on a return.
*/
export function glValueForCodes(codes: string[], range: GlDateRange, branchCode = ''): number {
if (!codes.length) {
return 0;
}
const wanted = new Set(codes);
const closing = cumulativeBalances(range.to, branchCode);
const movement = periodTurnover(range, branchCode);
let total = 0;
for (const code of wanted) {
const account = glAccount(code);
if (!account) {
continue;
}
if (account.type === 'INCOME' || account.type === 'EXPENSE') {
const move = movement.get(code);
if (!move) {
continue;
}
total += account.type === 'INCOME' ? move.credit - move.debit : move.debit - move.credit;
} else {
total += closing.get(code) ?? 0;
}
}
return total;
}
export function sum<T>(rows: T[], pick: (row: T) => number): number {
return rows.reduce((acc, r) => acc + pick(r), 0);
}
/** Groups rows by their `group` field, preserving chart-of-accounts order. */
export function groupBy<T extends { group: string }>(rows: T[]): { group: string; rows: T[]; total: number }[] {
const order: string[] = [];
const map = new Map<string, T[]>();
for (const r of rows) {
if (!map.has(r.group)) {
map.set(r.group, []);
order.push(r.group);
}
map.get(r.group)!.push(r);
}
return order.map((g) => ({ group: g, rows: map.get(g)!, total: 0 }));
}
+20
View File
@@ -0,0 +1,20 @@
/**
* Copyright since 2025 Mifos Initiative
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { GlReportsRoutingModule } from './gl-reports-routing.module';
@NgModule({
imports: [
SharedModule,
GlReportsRoutingModule
]
})
export class GlReportsModule {}
@@ -397,6 +397,64 @@
</div> </div>
</ng-container> </ng-container>
<!-- ════════════ CONTINGENT LIABILITIES ════════════ -->
<ng-container *ngIf="activeReport === 'CONTINGENT-LIAB'">
<div class="acr-stats">
<div class="acr-stat-card alert">
<div class="acr-stat-l">Total Contingent Liabilities — {{ bank.fiscalYear }}</div>
<div class="acr-stat-v">&#8377; {{ contingentLiab.current | number: '1.2-2' }} Lakh</div>
<div class="acr-stat-meta">vs {{ contingentLiab.previous | number: '1.2-2' }} Lakh (PY)</div>
</div>
<div class="acr-stat-card" [ngClass]="clVariation <= 0 ? 'good' : 'alert'">
<div class="acr-stat-l">Variation over Previous Year</div>
<div class="acr-stat-v">{{ clVariation >= 0 ? '+' : '' }}{{ clVariation | number: '1.2-2' }} Lakh</div>
<div class="acr-stat-meta">{{ clVariationPct >= 0 ? '+' : '' }}{{ clVariationPct.toFixed(2) }}%</div>
</div>
<div class="acr-stat-card">
<div class="acr-stat-l">As On Date</div>
<div class="acr-stat-v" style="font-size: 16px">{{ bank.asOnDate }}</div>
<div class="acr-stat-meta">Schedule 12</div>
</div>
</div>
<div class="acr-section">
<div class="acr-sec-h">
<h3 class="acr-sec-t">Contingent Liabilities &mdash; As on {{ bank.asOnDate }} (₹ in Lakhs)</h3>
<button mat-stroked-button class="acr-btn-xls" (click)="exportContingentLiabCsv()">
<fa-icon icon="file-csv"></fa-icon>&nbsp; Export CSV
</button>
</div>
<div class="acr-tbl-wrap">
<table class="acr-tbl">
<thead>
<tr>
<th colspan="2" class="acr-sub-h">Items Covered Under This Schedule</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of contingentLiabItems">
<td class="mono">{{ item.code }}</td>
<td>{{ item.label }}</td>
</tr>
</tbody>
<tfoot>
<tr class="row-total expense">
<td colspan="2">
<strong>Total Contingent Liabilities: &#8377; {{ contingentLiab.current | number: '1.2-2' }} Lakh</strong>
</td>
</tr>
</tfoot>
</table>
</div>
<p class="acr-note">
<fa-icon icon="info-circle"></fa-icon>&nbsp; Individual item-wise figures for this schedule are not broken
out here — only the audited total is shown, to avoid presenting a sub-item split that could not be
independently verified against the source statement.
</p>
</div>
</ng-container>
<!-- ════════════ GL DR/CR ════════════ --> <!-- ════════════ GL DR/CR ════════════ -->
<ng-container *ngIf="activeReport === 'GL-DR-CR'"> <ng-container *ngIf="activeReport === 'GL-DR-CR'">
<div class="acr-stats"> <div class="acr-stats">
@@ -318,6 +318,16 @@
border-bottom: 1px dashed var(--acr-g200); border-bottom: 1px dashed var(--acr-g200);
} }
.acr-note {
margin: 12px 0 0;
font-size: 12px;
font-style: italic;
color: var(--acr-g500);
display: flex;
align-items: flex-start;
gap: 6px;
}
.acr-btn-xls { .acr-btn-xls {
font-size: 12px !important; font-size: 12px !important;
height: 34px !important; height: 34px !important;

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