Add account balance enquiry via GET /accounts/balance

The CBS API now exposes a balance endpoint, which it previously did not.
Several comments in the codebase asserted that no such endpoint existed
anywhere in the API; those are corrected here rather than left to mislead.

Balance is fetched lazily, per account, from the Account Details card:

- `accounts.balance` endpoint, `CbsAccountBalance` type, and a
  `getAccountBalance` query with `keepUnusedDataFor: 0` — a balance is the
  most perishable figure in the app and must not outlive its screen.
- The call is triggered by the customer, not by render. Every call reaches
  the core banking system, and a balance should not appear over someone's
  shoulder just for opening a screen.
- `supportsBalanceEnquiry` gates the control by account type only, with no
  status check: a dormant savings account cannot be debited but still has a
  balance. Deposits are excluded because the endpoint does not serve them.
- `ACCOUNT_BALANCE_NOT_AVAILABLE` added to the error catalogue as a
  non-retryable refusal, so the card states it instead of inviting a tap
  that gets the identical answer.

Also carries in-progress work already present in the tree: customer-facing
account type labels (`accountTypeLabel`) applied across the account card,
selector, mini statement, balance enquiry and MMID screens.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Abin Toppo
2026-09-21 15:27:50 +05:30
co-authored by Claude Opus 5
parent 2dcb10775c
commit 86f9647437
13 changed files with 341 additions and 27 deletions
@@ -1,4 +1,4 @@
import React, { useState, useRef } from 'react';
import React, { useCallback, useState, useRef } from 'react';
import { StyleSheet, Text, View, Dimensions, Animated } from 'react-native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import Ionicons from '@react-native-vector-icons/ionicons';
@@ -13,6 +13,10 @@ import { useTheme, fontFamily } from '../../../theme';
import { FeatureKey } from '../../../constants/featureKeys';
import { useFeature } from '../../../features';
import { formatDate } from '../../../utils/formatters';
import { accountTypeLabel, supportsBalanceEnquiry } from '../utils/accountRules';
import { useLazyGetAccountBalanceQuery } from '../services/accountsApi';
import { describeError, isRetryableError } from '../../../services/api/cbsErrors';
import type { ApiError } from '../../../types/api';
const { width: SCREEN_WIDTH } = Dimensions.get('window');
const SPACING = 16;
@@ -28,6 +32,20 @@ type DetailItem = {
icon: IconName;
};
/**
* What one card knows about its account's balance. Keyed per account rather
* than held as a single value, because the carousel has every account mounted
* at once and a shared slot would paint one account's figure onto another's
* card mid-swipe.
*/
type BalanceState = {
value?: number;
loading?: boolean;
/** Resolved copy, not a code — the card renders it verbatim. */
error?: string;
retryable?: boolean;
};
export default function AccountDetailsScreen({ route, navigation }: Props) {
const theme = useTheme();
const canToggleBalance = useFeature(FeatureKey.HOME_ACCOUNTS_BALANCE_TOGGLE);
@@ -37,6 +55,49 @@ export default function AccountDetailsScreen({ route, navigation }: Props) {
const profile = useAppSelector((state) => state.user.profile);
const [selectedNumber, setSelectedNumber] = useState(route.params?.accountNumber);
const scrollX = useRef(new Animated.Value(0)).current;
/**
* Balances are fetched on demand, one account at a time, and kept only in
* this screen's state — never in the account list, which would let a figure
* outlive the moment it was true for.
*/
const [fetchBalance] = useLazyGetAccountBalanceQuery();
const [balances, setBalances] = useState<Record<string, BalanceState>>({});
const handleCheckBalance = useCallback(
async (accountNumber: string) => {
setBalances((current) => ({
...current,
// The previous error is cleared on the way in, so a retry does not sit
// under the spinner that is already answering it.
[accountNumber]: { ...current[accountNumber], loading: true, error: undefined },
}));
try {
const result = await fetchBalance(accountNumber).unwrap();
setBalances((current) => ({
...current,
[accountNumber]: { value: result.balance, loading: false },
}));
} catch (error) {
const apiError = error as ApiError | undefined;
const copy = describeError(apiError?.code);
setBalances((current) => ({
...current,
[accountNumber]: {
loading: false,
error: copy.title,
// A refusal the bank will repeat must not offer a tap that gets
// the identical answer.
retryable: isRetryableError(apiError?.code),
},
}));
}
},
[fetchBalance],
);
const account =
accounts.find((item) => item.accountNumber === selectedNumber) ?? accounts[0];
const activeIndex = accounts.findIndex(
@@ -83,7 +144,7 @@ export default function AccountDetailsScreen({ route, navigation }: Props) {
{
id: 'type',
label: 'Account type',
value: account.accountType,
value: accountTypeLabel(account.accountType),
icon: 'layers-outline',
},
{
@@ -148,7 +209,7 @@ export default function AccountDetailsScreen({ route, navigation }: Props) {
return (
<ScreenShell
title="Account details"
subtitle={`${account.accountType} account overview`}
subtitle={`${accountTypeLabel(account.accountType)} overview`}
contentContainerStyle={styles.contentContainer}
>
<View style={styles.carouselSection}>
@@ -174,6 +235,7 @@ export default function AccountDetailsScreen({ route, navigation }: Props) {
scrollEventThrottle={16}
keyExtractor={(item) => item.accountNumber}
renderItem={({ item, index }) => {
const balanceState = balances[item.accountNumber];
const inputRange = [
(index - 1) * (CARD_WIDTH + SPACING),
index * (CARD_WIDTH + SPACING),
@@ -191,6 +253,18 @@ export default function AccountDetailsScreen({ route, navigation }: Props) {
account={item}
accountHolder={customerName || undefined}
canRevealNumber={canToggleBalance}
onCheckBalance={
// Undefined for a deposit, which the balance endpoint does
// not serve — the card then draws no control at all rather
// than one that always fails.
supportsBalanceEnquiry(item)
? () => void handleCheckBalance(item.accountNumber)
: undefined
}
balance={balanceState?.value}
balanceLoading={balanceState?.loading}
balanceError={balanceState?.error}
balanceRetryable={balanceState?.retryable ?? true}
/>
</Animated.View>
);
@@ -64,7 +64,7 @@ export default function AccountsMmidScreen(_props: Props) {
// Masked numbers repeat across accounts on this profile, so they cannot key
// the list. The MMID is unique per account where the bank has allocated
// one; the type disambiguates the deposits that have none.
<Card
( account.mmid ? <Card
key={account.mmid ?? `${account.accountType}-${account.accountNumberMasked}`}
style={styles.accountCard}
>
@@ -104,7 +104,7 @@ export default function AccountsMmidScreen(_props: Props) {
{account.ifsc}
</Text>
</View>
</Card>
</Card>:null)
);
const apiError = error as ApiError | undefined;
@@ -29,6 +29,7 @@ import type { CbsStatementTransaction } from '../../../types/cbs';
import { describeError, isRetryableError } from '../../../services/api/cbsErrors';
import { useApiErrorToast } from '../../../hooks/useApiErrorToast';
import { useAccounts } from '../hooks/useAccounts';
import { accountTypeLabel } from '../utils/accountRules';
import { toStatementDate, useStatement } from '../hooks/useStatement';
import {
counterpartyDirection,
@@ -369,7 +370,7 @@ export default function MiniStatementScreen({ route }: Props) {
]}
>
<Text style={[styles.accountChipText, { color: theme.colors.onBrandPrimary }]}>
{`${account.accountType} · XXXX ${account.accountNumber.slice(-4)}`}
{`${accountTypeLabel(account.accountType)} · XXXX ${account.accountNumber.slice(-4)}`}
</Text>
</View>
</View>
+33
View File
@@ -5,6 +5,7 @@ import { resolveLive } from '../../../services/api/serviceHelpers';
import { downloadPdf } from '../../../services/files/pdfDownload';
import type {
CbsAccount,
CbsAccountBalance,
CbsPdfDocument,
CbsStatementExportQuery,
CbsStatementPage,
@@ -107,6 +108,37 @@ export const accountsApi = baseApi.injectEndpoints({
keepUnusedDataFor: 0,
}),
/**
* One account's balance, read live from the bank.
*
* `keepUnusedDataFor: 0` for the same reason as `getAccounts`, only more
* so: a balance is the most perishable figure in the app. The moment the
* card showing it unmounts the entry is dropped, so nothing can come back
* to a screen and find yesterday's number waiting for it.
*
* Fetched lazily — the screens use `useLazyGetAccountBalanceQuery` — so
* the call happens when the customer asks for it, not on render. That is
* partly a cost decision, since every call reaches the core banking
* system, and partly a privacy one: a balance should not appear over
* someone's shoulder because they opened a details screen.
*
* SAVINGS and CURRENT only; see `supportsBalanceEnquiry`. A deposit sent
* here answers `ACCOUNT_BALANCE_NOT_AVAILABLE`, which is a refusal rather
* than a fault, and the card says so instead of offering a retry.
*/
getAccountBalance: builder.query<CbsAccountBalance, string>({
queryFn: (accountNumber) =>
resolveLive(async () => {
const response = await apiClient.get<CbsAccountBalance>(
endpoints.accounts.balance,
{ params: { accountNumber } },
);
return response.data;
}),
keepUnusedDataFor: 0,
}),
/**
* The statement for a range, as a PDF on disk.
*
@@ -155,6 +187,7 @@ export const accountsApi = baseApi.injectEndpoints({
export const {
useGetAccountsQuery,
useGetMmidAccountsQuery,
useLazyGetAccountBalanceQuery,
useGetStatementQuery,
useExportStatementMutation,
useDownloadMiniStatementMutation,
+5 -4
View File
@@ -83,10 +83,11 @@ describe('isOperativeAccount', () => {
});
describe('accountTypeLabel', () => {
it('turns the API_SHAPE into something readable', () => {
expect(accountTypeLabel('FIXED_DEPOSIT')).toBe('Fixed deposit');
expect(accountTypeLabel('RECURRING_DEPOSIT')).toBe('Recurring deposit');
expect(accountTypeLabel('SAVINGS')).toBe('Savings');
it('turns the API shape into something readable for customers', () => {
expect(accountTypeLabel('FIXED_DEPOSIT')).toBe('Deposit account');
expect(accountTypeLabel('RECURRING_DEPOSIT')).toBe('Deposit account');
expect(accountTypeLabel('SAVINGS')).toBe('Savings account');
expect(accountTypeLabel('CURRENT')).toBe('Current account');
});
});
+31 -3
View File
@@ -22,6 +22,19 @@ export const OPERATIVE_ACCOUNT_TYPES: readonly CbsAccountType[] = ['SAVINGS', 'C
export const isOperativeAccount = (account: CbsAccount) =>
account.status === 'ACTIVE' && OPERATIVE_ACCOUNT_TYPES.includes(account.accountType);
/**
* True when `GET /accounts/balance` will answer for this account.
*
* Type only, with no status check — unlike `isOperativeAccount` above. A
* dormant savings account cannot be the debit side of a transfer but it still
* has a balance, and refusing to show it would be the app inventing a
* restriction the bank does not have. A deposit is excluded because the
* endpoint genuinely does not serve one: its balance lives on
* `GET /accounts/deposits/detail`.
*/
export const supportsBalanceEnquiry = (account: CbsAccount) =>
OPERATIVE_ACCOUNT_TYPES.includes(account.accountType);
/**
* Masked form of a full account number, in the shape the rest of the app uses.
*
@@ -35,11 +48,26 @@ export const maskAccountNumber = (accountNumber: string) =>
/**
* Readable label for an account type.
*
* The API returns SCREAMING_SNAKE, so `FIXED_DEPOSIT` has to become "Fixed
* deposit" rather than "Fixed_deposit" — the underscore is what a naive
* title-case leaves behind.
* The API returns SCREAMING_SNAKE, but we show the customer a friendly label
* rather than the raw backend nomenclature. Deposit accounts are intentionally
* genericised because "RECURRING_DEPOSIT" is a bank-internal code, not a user
* facing account title.
*/
export const accountTypeLabel = (accountType: string) => {
const upper = accountType.trim().toUpperCase();
if (upper === 'FIXED_DEPOSIT' || upper === 'RECURRING_DEPOSIT') {
return 'Deposit account';
}
if (upper === 'SAVINGS') {
return 'Savings account';
}
if (upper === 'CURRENT') {
return 'Current account';
}
const [first = '', ...rest] = accountType.toLowerCase().split('_');
return [first.charAt(0).toUpperCase() + first.slice(1), ...rest].join(' ');
@@ -5,6 +5,7 @@ import Ionicons from '@react-native-vector-icons/ionicons';
import { Card, EmptyState, InfoBanner, Loader, ScreenShell } from '../../../components';
import { useAccounts } from '../../home/hooks/useAccounts';
import { accountTypeLabel } from '../../home/utils/accountRules';
import { useTheme, fontFamily } from '../../../theme';
import type { CbsAccount } from '../../../types/cbs';
import type { ServicesStackParamList } from '../../../navigation/types';
@@ -38,7 +39,7 @@ export default function BalanceEnquiryScreen(_props: Props) {
</View>
<View style={styles.accountCopy}>
<Text style={[styles.accountType, { color: theme.colors.primary }]}>
{`${account.accountType.toUpperCase()} ACCOUNT`}
{accountTypeLabel(account.accountType).toUpperCase()}
</Text>
<Text style={[styles.accountNumber, { color: theme.colors.textPrimary }]}>
{`XXXX ${account.accountNumber.slice(-4)}`}