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.
This commit is contained in:
2026-08-01 11:18:02 +05:30
parent 63ac900e42
commit 4261f9659e
10 changed files with 2312 additions and 9 deletions
+619
View File
@@ -0,0 +1,619 @@
/**
* 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/.
*/
// Dummy NPA (Non-Performing Asset) data layer for the NPA Reports / Analysis / Classification
// screens. Everything downstream — classification, provisioning, interest reversal, GNPA/NNPA —
// is *derived* from LOAN_ACCOUNTS via pure functions below, so no two reports can ever disagree
// on the same account's numbers.
//
// The book is generated with a seeded RNG (not Math.random()) so the "large, real-world-CBS"
// dataset stays identical across reloads instead of reshuffling every time the page opens.
export type NpaStage =
| 'STANDARD'
| 'SMA0'
| 'SMA1'
| 'SMA2'
| 'SUBSTANDARD'
| 'DOUBTFUL1'
| 'DOUBTFUL2'
| 'DOUBTFUL3'
| 'LOSS';
export const STAGE_ORDER: NpaStage[] = [
'STANDARD',
'SMA0',
'SMA1',
'SMA2',
'SUBSTANDARD',
'DOUBTFUL1',
'DOUBTFUL2',
'DOUBTFUL3',
'LOSS'
];
export const STAGE_LABELS: Record<NpaStage, string> = {
STANDARD: 'Standard',
SMA0: 'SMA-0',
SMA1: 'SMA-1',
SMA2: 'SMA-2',
SUBSTANDARD: 'Sub-Standard',
DOUBTFUL1: 'Doubtful-1',
DOUBTFUL2: 'Doubtful-2',
DOUBTFUL3: 'Doubtful-3',
LOSS: 'Loss Asset'
};
export function isNpaStage(stage: NpaStage): boolean {
return stage !== 'STANDARD' && stage !== 'SMA0' && stage !== 'SMA1' && stage !== 'SMA2';
}
export function isSmaStage(stage: NpaStage): boolean {
return stage === 'SMA0' || stage === 'SMA1' || stage === 'SMA2';
}
export function stageBadgeClass(stage: NpaStage): string {
return `npa-badge npa-badge--${stage.toLowerCase()}`;
}
/** Recovery-workflow stage tracked separately from IRAC classification — a Doubtful/Loss
* account can sit at any of these while its classification stays driven purely by overdueDays. */
export type LegalActionStatus = 'NONE' | 'NOTICE_ISSUED' | 'SARFAESI_INITIATED' | 'SUIT_FILED' | 'OTS_NEGOTIATION';
export const LEGAL_ACTION_LABELS: Record<LegalActionStatus, string> = {
NONE: 'No Action Yet',
NOTICE_ISSUED: 'Demand Notice Issued',
SARFAESI_INITIATED: 'SARFAESI Action Initiated',
SUIT_FILED: 'Recovery Suit Filed',
OTS_NEGOTIATION: 'One-Time Settlement Under Negotiation'
};
export interface RecoveryTxn {
date: string;
amount: number;
mode: string;
}
export interface LoanAccount {
accountNo: string;
customerName: string;
guarantorName: string;
branchCode: string;
branchName: string;
productCode: string;
productName: string;
secured: boolean;
sanctionedAmount: number;
disbursementDate: string;
interestRate: number;
outstandingBalance: number;
overdueAmount: number;
overdueDays: number;
overdueDaysQuarterAgo: number;
collateralValue: number;
lastPaymentDate: string;
isLossAsset: boolean;
isRestructured: boolean;
provisionCoverageRatio: number;
recoveries: RecoveryTxn[];
/** '—' for Standard/SMA accounts — only NPA accounts are actually assigned a reason. */
npaReason: string;
/** '—' for Standard accounts — SMA and NPA accounts get a recovery officer assigned for follow-up. */
recoveryOfficer: string;
legalActionStatus: LegalActionStatus;
}
// -------------------------------------------------------------------------
// Date helpers
// -------------------------------------------------------------------------
function fmt(d: Date): string {
return `${String(d.getDate()).padStart(2, '0')}-${String(d.getMonth() + 1).padStart(2, '0')}-${d.getFullYear()}`;
}
function addDays(d: Date, days: number): Date {
const r = new Date(d);
r.setDate(r.getDate() + days);
return r;
}
/** Parses a "DD-MM-YYYY" string back into a Date, so generated dates can be compared/ordered
* against each other (e.g. "is this recovery more recent than the last-payment estimate?"). */
function parseDMY(s: string): Date {
const [
d,
m,
y
] = s.split('-').map(Number);
return new Date(y, m - 1, d);
}
export function todayDDMMYYYY(): string {
return fmt(new Date());
}
// -------------------------------------------------------------------------
// Seeded RNG — keeps the generated book stable across reloads
// -------------------------------------------------------------------------
function mulberry32(seed: number): () => number {
return function random(): number {
seed |= 0;
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rng = mulberry32(19870614);
const pick = <T>(arr: T[]): T => arr[Math.floor(rng() * arr.length)];
const between = (min: number, max: number): number => min + rng() * (max - min);
const round = (n: number): number => Math.round(n);
// -------------------------------------------------------------------------
// Masters
// -------------------------------------------------------------------------
export interface BranchMaster {
code: string;
name: string;
}
// BR01/BR02 are deliberately named "Branch 1"/"Branch 2" — identical to the two branches in
// cash-clearing-transfer-summary.component.ts — so a single pair of real office names in the DB
// gets recognised by BOTH reports instead of each module expecting a different branch name.
export const BRANCHES: BranchMaster[] = [
{ code: 'BR01', name: 'Branch 1' },
{ code: 'BR02', name: 'Branch 2' },
{ code: 'BR03', name: 'Borivali Branch' },
{ code: 'BR04', name: 'Thane Branch' },
{ code: 'BR05', name: 'Pune Branch' },
{ code: 'BR06', name: 'Nashik Branch' },
{ code: 'BR07', name: 'Nagpur Branch' },
{ code: 'BR08', name: 'Kolhapur Branch' }
];
interface ProductMaster {
code: string;
name: string;
secured: boolean;
minAmt: number;
maxAmt: number;
minRate: number;
maxRate: number;
}
export const LOAN_PRODUCTS: ProductMaster[] = [
{
code: '01',
name: 'Cash Credit (MSME)',
secured: true,
minAmt: 500000,
maxAmt: 5000000,
minRate: 11,
maxRate: 13.5
},
{ code: '02', name: 'Term Loan - MSME', secured: true, minAmt: 300000, maxAmt: 3000000, minRate: 11, maxRate: 14 },
{ code: '03', name: 'Housing Loan', secured: true, minAmt: 1000000, maxAmt: 4000000, minRate: 8.5, maxRate: 10.5 },
{ code: '04', name: 'Vehicle Loan', secured: true, minAmt: 300000, maxAmt: 1500000, minRate: 9, maxRate: 11.5 },
{ code: '05', name: 'Gold Loan', secured: true, minAmt: 50000, maxAmt: 1000000, minRate: 9, maxRate: 12 },
{ code: '06', name: 'Kisan Credit Card', secured: true, minAmt: 100000, maxAmt: 500000, minRate: 7, maxRate: 9 },
{ code: '07', name: 'Personal Loan', secured: false, minAmt: 50000, maxAmt: 500000, minRate: 13, maxRate: 16 },
{ code: '08', name: 'Education Loan', secured: false, minAmt: 200000, maxAmt: 1500000, minRate: 10, maxRate: 12 },
{
code: '09',
name: 'SHG / Micro Finance Loan',
secured: false,
minAmt: 20000,
maxAmt: 200000,
minRate: 12,
maxRate: 14
},
{
code: '10',
name: 'Overdraft Against Property',
secured: true,
minAmt: 500000,
maxAmt: 2500000,
minRate: 11,
maxRate: 13
}
];
const FIRST_NAMES = [
'Ramesh',
'Suresh',
'Mahesh',
'Ganesh',
'Dinesh',
'Vijay',
'Sanjay',
'Ajay',
'Prakash',
'Vinod',
'Sunita',
'Anita',
'Kavita',
'Savita',
'Rekha',
'Meena',
'Pooja',
'Sangita',
'Nirmala',
'Usha',
'Ravindra',
'Mahendra',
'Narendra',
'Jitendra',
'Rajendra',
'Bhagwan',
'Balasaheb',
'Vasant',
'Shivaji',
'Yogesh',
'Kiran',
'Manisha',
'Deepak',
'Sandeep',
'Pradeep',
'Ashok',
'Vishal',
'Nitin',
'Amol',
'Santosh'
];
const LAST_NAMES = [
'Patil',
'More',
'Jadhav',
'Deshmukh',
'Pawar',
'Kulkarni',
'Shinde',
'Gaikwad',
'Chavan',
'Bhosale',
'Kale',
'Salunkhe',
'Sawant',
'Kadam',
'Joshi',
'Wagh',
'Thorat',
'Waghmare',
'Mane',
'Shaikh'
];
const NPA_REASONS = [
'Crop Failure / Agri Distress',
'Business Loss',
'Health Issue / Death of Borrower',
'Diversion of Funds',
'Wilful Default',
'Natural Calamity',
'Loss of Employment',
'Family Dispute / Litigation',
'Delayed Receivables from Debtors',
'Unit Closure'
];
/** Recovery officers are bank staff, kept distinct from the FIRST_NAMES/LAST_NAMES pool used for
* customers so a name never accidentally reads as "the officer is also the borrower". */
const RECOVERY_OFFICERS = [
'Anil Deshpande',
'Sunil Kadam',
'Vikas Pathak',
'Rajendra More',
'Sachin Bhagat',
'Prashant Jagtap',
'Milind Kulkarni',
'Ravi Ghadge'
];
// -------------------------------------------------------------------------
// Weighted stage buckets — used only to seed a realistic distribution of
// overdue-day counts; the actual classification is always re-derived from
// `overdueDays` via classifyDays(), never stored directly.
// -------------------------------------------------------------------------
interface StageBucket {
weight: number;
minDays: number;
maxDays: number;
isLossPool: boolean;
}
const BUCKETS: StageBucket[] = [
{ weight: 60, minDays: 0, maxDays: 0, isLossPool: false },
{ weight: 10, minDays: 1, maxDays: 30, isLossPool: false },
{ weight: 7, minDays: 31, maxDays: 60, isLossPool: false },
{ weight: 6, minDays: 61, maxDays: 90, isLossPool: false },
{ weight: 9, minDays: 91, maxDays: 365, isLossPool: false },
{ weight: 4, minDays: 366, maxDays: 730, isLossPool: false },
{ weight: 2.5, minDays: 731, maxDays: 1095, isLossPool: false },
{ weight: 1.5, minDays: 1096, maxDays: 1900, isLossPool: true }
];
const TOTAL_WEIGHT = BUCKETS.reduce((s, b) => s + b.weight, 0);
function pickBucket(): StageBucket {
let r = rng() * TOTAL_WEIGHT;
for (const b of BUCKETS) {
if (r < b.weight) {
return b;
}
r -= b.weight;
}
return BUCKETS[0];
}
/** Recovery-workflow progression — only NPA accounts get any legal action, and the more
* advanced/stressed the classification, the more likely the bank has already escalated. */
function legalActionFor(stage: NpaStage): LegalActionStatus {
if (!isNpaStage(stage)) {
return 'NONE';
}
const r = rng();
if (stage === 'SUBSTANDARD') {
return r < 0.2 ? 'NOTICE_ISSUED' : 'NONE';
}
if (stage === 'DOUBTFUL1') {
if (r < 0.15) return 'OTS_NEGOTIATION';
if (r < 0.45) return 'SARFAESI_INITIATED';
if (r < 0.65) return 'NOTICE_ISSUED';
return 'NONE';
}
// DOUBTFUL2, DOUBTFUL3, LOSS
if (r < 0.1) return 'OTS_NEGOTIATION';
if (r < 0.55) return 'SUIT_FILED';
if (r < 0.8) return 'SARFAESI_INITIATED';
if (r < 0.9) return 'NOTICE_ISSUED';
return 'NONE';
}
function generateAccounts(count: number): LoanAccount[] {
const today = new Date();
const accounts: LoanAccount[] = [];
for (let i = 0; i < count; i++) {
const branch = pick(BRANCHES);
const product = pick(LOAN_PRODUCTS);
const bucket = pickBucket();
const overdueDays = bucket.maxDays === 0 ? 0 : round(between(bucket.minDays, bucket.maxDays));
const isLossAsset = bucket.isLossPool && rng() < 0.4;
// Restructured accounts skew towards the already-stressed buckets (SMA-2 and worse),
// matching how RBI restructuring relief is actually used in practice.
const stressed = classifyDays(overdueDays, isLossAsset);
const isRestructured =
rng() < (stressed === 'STANDARD' || stressed === 'SMA0' || stressed === 'SMA1' ? 0.04 : 0.18);
const sanctionedAmount = round(between(product.minAmt, product.maxAmt) / 1000) * 1000;
// The loan must be old enough to have actually accrued `overdueDays` of delinquency, plus a
// minimum "good" performing stretch beforehand — otherwise a badly-overdue account could end
// up with a disbursement date that falls AFTER its own last-payment/NPA date, which would look
// wrong no matter what day this report is viewed on.
const minGoodPeriodDays = round(between(30, 180));
const loanAgeDays = Math.max(round(between(0.5, 8) * 365), overdueDays + minGoodPeriodDays);
const disbursementDate = fmt(addDays(today, -loanAgeDays));
const interestRate = +between(product.minRate, product.maxRate).toFixed(2);
const outstandingBalance = round(sanctionedAmount * between(0.25, 0.9));
const overdueFrac = overdueDays === 0 ? 0 : Math.min(0.85, overdueDays / 1200 + between(0, 0.15));
const overdueAmount = round(outstandingBalance * overdueFrac);
const collateralValue = product.secured ? round(sanctionedAmount * between(0.85, 1.25)) : 0;
const npaReason = isNpaStage(stressed) ? pick(NPA_REASONS) : '—';
const recoveryOfficer = isNpaStage(stressed) || isSmaStage(stressed) ? pick(RECOVERY_OFFICERS) : '—';
const legalActionStatus = legalActionFor(stressed);
// Quarter-ago overdue count is capped at how old the loan actually was 90 days back — a loan
// can't have been overdue for longer than it had existed at that point in time.
const drift = round((rng() - 0.4) * 130);
const maxQuarterAgoOverdueDays = Math.max(0, loanAgeDays - 90);
const overdueDaysQuarterAgo = Math.min(Math.max(0, overdueDays - drift), maxQuarterAgoOverdueDays);
const recoveries: RecoveryTxn[] = [];
if (overdueDays > 90 && rng() < 0.5) {
const numRecoveries = 1 + Math.floor(rng() * 3);
for (let r = 0; r < numRecoveries; r++) {
recoveries.push({
date: fmt(addDays(today, -round(between(10, Math.min(overdueDays, 400))))),
amount: round(outstandingBalance * between(0.02, 0.12)),
mode: pick([
'Cash Deposit',
'Cheque',
'NEFT/RTGS',
'Auction / SARFAESI',
'One-Time Settlement'
])
});
}
}
// A recorded recovery IS a payment — if one landed more recently than the formula-based
// last-payment estimate, the account's "last payment" must reflect that, otherwise the two
// fields on the Account Detail screen would visibly contradict each other.
const formulaLastPaymentDate = fmt(addDays(today, -Math.max(5, overdueDays - round(between(0, 20)))));
const latestRecoveryDate = recoveries.reduce<Date | null>((latest, r) => {
const d = parseDMY(r.date);
return !latest || d > latest ? d : latest;
}, null);
const lastPaymentDate =
latestRecoveryDate && latestRecoveryDate > parseDMY(formulaLastPaymentDate)
? fmt(latestRecoveryDate)
: formulaLastPaymentDate;
const seq = String(1000 + i).padStart(6, '0');
accounts.push({
accountNo: `1${branch.code.slice(2)}${product.code}${seq}`,
customerName: `${pick(FIRST_NAMES)} ${pick(LAST_NAMES)}`,
guarantorName: `${pick(FIRST_NAMES)} ${pick(LAST_NAMES)}`,
branchCode: branch.code,
branchName: branch.name,
productCode: product.code,
productName: product.name,
secured: product.secured,
sanctionedAmount,
disbursementDate,
interestRate,
outstandingBalance,
overdueAmount,
overdueDays,
overdueDaysQuarterAgo,
collateralValue,
lastPaymentDate,
isLossAsset,
isRestructured,
provisionCoverageRatio: +between(0.75, 1.1).toFixed(2),
recoveries,
npaReason,
recoveryOfficer,
legalActionStatus
});
}
return accounts;
}
// 8 branches x ~80 accounts/branch on average — sized to look like a real cooperative bank's
// loan book rather than a token demo sample. Pagination in the reports UI is what makes a book
// this size usable, not a smaller dataset.
export const LOAN_ACCOUNTS: LoanAccount[] = generateAccounts(640);
// -------------------------------------------------------------------------
// Classification & provisioning (RBI IRAC norms, simplified for a demo book)
// -------------------------------------------------------------------------
export function classifyDays(days: number, isLossAsset: boolean): NpaStage {
if (isLossAsset && days > 1095) {
return 'LOSS';
}
if (days <= 0) {
return 'STANDARD';
}
if (days <= 30) {
return 'SMA0';
}
if (days <= 60) {
return 'SMA1';
}
if (days <= 90) {
return 'SMA2';
}
if (days <= 365) {
return 'SUBSTANDARD';
}
if (days <= 730) {
return 'DOUBTFUL1';
}
if (days <= 1095) {
return 'DOUBTFUL2';
}
return 'DOUBTFUL3';
}
export function currentStage(a: LoanAccount): NpaStage {
return classifyDays(a.overdueDays, a.isLossAsset);
}
export function previousStage(a: LoanAccount): NpaStage {
return classifyDays(a.overdueDaysQuarterAgo, a.isLossAsset && a.overdueDaysQuarterAgo > 1095);
}
export function provisionRatePct(stage: NpaStage, secured: boolean): number {
switch (stage) {
case 'STANDARD':
case 'SMA0':
case 'SMA1':
return 0.4;
case 'SMA2':
return 0.75;
case 'SUBSTANDARD':
return secured ? 15 : 25;
case 'DOUBTFUL1':
return secured ? 25 : 100;
case 'DOUBTFUL2':
return secured ? 40 : 100;
case 'DOUBTFUL3':
case 'LOSS':
return 100;
}
}
export function provisionRequired(a: LoanAccount): number {
const stage = currentStage(a);
if (!isNpaStage(stage)) {
return round(a.outstandingBalance * (provisionRatePct(stage, a.secured) / 100));
}
const securedPortion = Math.min(a.outstandingBalance, a.collateralValue);
const unsecuredPortion = Math.max(0, a.outstandingBalance - a.collateralValue);
const securedRate = provisionRatePct(stage, true) / 100;
const unsecuredRate = provisionRatePct(stage, false) / 100;
return round(securedPortion * securedRate + unsecuredPortion * unsecuredRate);
}
/** Provision held can run a little above or below what's required (over/under-provisioning
* happens in real banks) — but it can never exceed the account's own outstanding balance, since
* a bank cannot hold more provision than the money actually at risk on that one loan. */
export function provisionHeld(a: LoanAccount): number {
return Math.min(a.outstandingBalance, round(provisionRequired(a) * a.provisionCoverageRatio));
}
/** Interest income de-recognised because the account has been NPA for longer than 90 days. */
export function interestReversed(a: LoanAccount): number {
const stage = currentStage(a);
if (!isNpaStage(stage)) {
return 0;
}
const daysSinceNpa = Math.max(0, a.overdueDays - 90);
return round(a.outstandingBalance * (a.interestRate / 100) * (daysSinceNpa / 365));
}
/** Date the account first crossed 90 days overdue (i.e. became NPA) — derived from overdueDays,
* never stored separately, so it always agrees with the account's current classification. */
export function npaSinceDate(a: LoanAccount): string {
if (!isNpaStage(currentStage(a))) {
return '—';
}
const daysSinceNpa = Math.max(0, a.overdueDays - 90);
return fmt(addDays(new Date(), -daysSinceNpa));
}
export function totalRecovered(a: LoanAccount): number {
return a.recoveries.reduce((s, r) => s + r.amount, 0);
}
export function movementLabel(prev: NpaStage, curr: NpaStage): string {
if (prev === curr) {
return 'No Change';
}
const prevIdx = STAGE_ORDER.indexOf(prev);
const currIdx = STAGE_ORDER.indexOf(curr);
if (currIdx > prevIdx) {
return !isNpaStage(prev) && isNpaStage(curr) ? 'Fresh Slippage to NPA' : 'Downgraded';
}
return isNpaStage(prev) && !isNpaStage(curr) ? 'Upgraded to Standard' : 'Improved';
}
// -------------------------------------------------------------------------
// Report menu metadata — drives both the shell mega-menu routerLinks and the
// in-page group/report tab rows, so a menu item and its screen can never
// point at different labels.
// -------------------------------------------------------------------------
export type ReportGroupId = 'reports' | 'analysis' | 'classification';
export interface ReportMeta {
id: string;
group: ReportGroupId;
label: string;
}
export const REPORT_META: ReportMeta[] = [
{ id: 'interest', group: 'reports', label: 'NPA Interest' },
{ id: 'status', group: 'reports', label: 'NPA Status Report' },
{ id: 'recovery', group: 'reports', label: 'NPA Recovery Report' },
{ id: 'summary', group: 'reports', label: 'NPA Summary Report' },
{ id: 'account-detail', group: 'analysis', label: 'NPA Account Detail Report' },
{ id: 'movement', group: 'analysis', label: 'NPA Movement Report' },
{ id: 'provision', group: 'analysis', label: 'NPA with Provision and Required Provision' },
{ id: 'probable', group: 'classification', label: 'Probable NPA' },
{ id: 'sma', group: 'classification', label: 'SMA Report' }
];
export const GROUP_LABELS: Record<ReportGroupId, string> = {
reports: 'NPA Reports',
analysis: 'NPA Analysis',
classification: 'NPA Classification'
};
export const DEFAULT_REPORT_ID = 'summary';