Open-source personal finance manager. Self-hosted, privacy-first.
feat(accounts): show a masked account number to tell same-named accounts apart (#415)
Tássio Noronha9d77be02d79d
diff --git a/backend/alembic/versions/065_account_masked_number.py b/backend/alembic/versions/065_account_masked_number.pynew file mode 100644index 00000000..22c5df8f--- /dev/null+++ b/backend/alembic/versions/065_account_masked_number.py@@ -0,0 +1,34 @@+"""add masked_number to accounts (issue #408)++Revision ID: 065+Revises: 064+Create Date: 2026-07-14++Banks often report every account under the same label (typically the account+holder's name), leaving two accounts at one bank indistinguishable in the UI.+Store the last 4 characters of the bank's own identifier for the account so the+accounts list can tell them apart without the user renaming each one by hand.++Only the last 4 characters are kept, never the full IBAN/account number.++Additive and nullable: existing rows are unaffected and backfill themselves on+the next sync, since `masked_number` is provider-owned and refreshed alongside+`name`.+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op++revision: str = "065"+down_revision: Union[str, None] = "064"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.add_column("accounts", sa.Column("masked_number", sa.String(4), nullable=True))+++def downgrade() -> None:+ op.drop_column("accounts", "masked_number")diff --git a/backend/app/models/account.py b/backend/app/models/account.pyindex 31e51b5d..6f3f64ce 100644--- a/backend/app/models/account.py+++ b/backend/app/models/account.py@@ -26,6 +26,10 @@ class Account(Base):external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)name: Mapped[str] = mapped_column(String(255))display_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ # Last 4 chars of the bank's identifier (IBAN, account or card number), when+ # the provider exposes one. Provider-owned like `name`: refreshed on sync,+ # not user-editable. Never holds the full identifier.+ masked_number: Mapped[Optional[str]] = mapped_column(String(4), nullable=True)type: Mapped[str] = mapped_column(String(50)) # checking, savings, credit_cardbalance: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0.00"))currency: Mapped[str] = mapped_column(String(3), default="USD")diff --git a/backend/app/providers/base.py b/backend/app/providers/base.pyindex e926a93c..8872acdd 100644--- a/backend/app/providers/base.py+++ b/backend/app/providers/base.py@@ -18,6 +18,27 @@ from typing import Literal, OptionalRefreshOutcome = Literal["refreshed", "skipped", "needs_user_action", "failed"]+def mask_last4(value: Optional[str]) -> Optional[str]:+ """Reduce a bank-assigned account identifier to its last four characters.++ Providers expose different identifiers for the same purpose: an IBAN+ (Enable Banking), a branch/account number (Pluggy), a card number. They all+ serve one job here, telling two same-named accounts apart, so we normalize+ them to a single shape and deliberately keep only the tail. Storing the full+ identifier would put a payable bank reference in the database for no gain.++ Separators (spaces, dashes) are stripped first, since IBANs are commonly+ formatted in groups of four. Returns None when the source is missing or too+ short to mask, so callers never render a partial identifier.+ """+ if not value:+ return None+ cleaned = "".join(ch for ch in str(value) if ch.isalnum())+ if len(cleaned) < 4:+ return None+ return cleaned[-4:]++@dataclassclass AccountData:external_id: str@@ -31,6 +52,10 @@ class AccountData:minimum_payment: Optional[Decimal] = Nonecard_brand: Optional[str] = Nonecard_level: Optional[str] = None+ # Last 4 chars of the bank's own identifier for the account, when the+ # provider exposes one. Disambiguates accounts a bank reports under an+ # identical name (issue #408). Never the full identifier — see mask_last4.+ masked_number: Optional[str] = None@dataclassdiff --git a/backend/app/providers/enable_banking.py b/backend/app/providers/enable_banking.pyindex cbe48502..2f7c2c13 100644--- a/backend/app/providers/enable_banking.py+++ b/backend/app/providers/enable_banking.py@@ -34,6 +34,7 @@ from app.providers.base import (ProviderUserActionRequired,SessionExpiredError,TransactionData,+ mask_last4,)logger = logging.getLogger(__name__)@@ -64,6 +65,28 @@ def _map_cash_account_type(eb_type: Optional[str]) -> str:return mapping.get(eb_type.upper(), "checking")+def _account_identifier(raw: dict) -> Optional[str]:+ """Pull the bank's own identifier for an account out of an EB details payload.++ EB reports it in three places, in descending order of usefulness: the IBAN+ on `account_id`, a non-IBAN scheme (BBAN, sort-code-and-account) on+ `account_id.other`, and the `all_account_ids` list. Banks outside SEPA only+ populate the latter two, so we fall through rather than assuming an IBAN.+ """+ account_id = raw.get("account_id") or {}+ if isinstance(account_id, dict):+ iban = account_id.get("iban")+ if iban:+ return str(iban)+ other = account_id.get("other") or {}+ if isinstance(other, dict) and other.get("identification"):+ return str(other["identification"])+ for entry in raw.get("all_account_ids") or []:+ if isinstance(entry, dict) and entry.get("identification"):+ return str(entry["identification"])+ return None++def _pick_balance(balances: list[dict]) -> Optional[dict]:"""Pick the most useful balance from EB's list (prefer closing booked)."""if not balances:@@ -448,6 +471,7 @@ class EnableBankingProvider(BankProvider):type=_map_cash_account_type(raw.get("cash_account_type")),balance=balance,currency=currency,+ masked_number=mask_last4(_account_identifier(raw)),)# ----- account / transaction fetches -----diff --git a/backend/app/providers/pluggy.py b/backend/app/providers/pluggy.pyindex 152fc2cd..d7b81d8b 100644--- a/backend/app/providers/pluggy.py+++ b/backend/app/providers/pluggy.py@@ -18,6 +18,7 @@ from app.providers.base import (HoldingData,RefreshOutcome,TransactionData,+ mask_last4,)from app.providers.pluggy_constants import pluggy_icon_for_compe@@ -227,6 +228,9 @@ def _build_account_data(acc: dict, type_mapper) -> AccountData:minimum_payment=minimum_payment,card_brand=card_brand,card_level=card_level,+ # Brazil has no IBAN; Pluggy's `number` is the branch/account number+ # (or the card number for credit cards), which serves the same purpose.+ masked_number=mask_last4(acc.get("number")),)diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.pyindex 38b5df95..798fa39e 100644--- a/backend/app/schemas/account.py+++ b/backend/app/schemas/account.py@@ -47,6 +47,9 @@ class AccountRead(AccountBase):connection_id: Optional[uuid.UUID] = Noneexternal_id: Optional[str] = Nonedisplay_name: Optional[str] = None+ # Last 4 chars of the bank's identifier, when the provider exposes one.+ # Read-only: absent from AccountUpdate because sync owns it.+ masked_number: Optional[str] = None# Denormalized from the linked BankConnection so every surface that shows# an account (transactions list, accounts page, dashboard) can render the# bank identity without a separate join. Null for manual accounts.diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex 187fd542..a036cb7c 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -150,6 +150,7 @@ def serialize_account("external_id": acc.external_id,"name": acc.name,"display_name": acc.display_name,+ "masked_number": acc.masked_number,"type": acc.type,"balance": acc.balance,"currency": acc.currency,diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 07fbecb6..4e436cf8 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -584,6 +584,7 @@ async def handle_oauth_callback(connection_id=connection.id,external_id=acc_data.external_id,name=acc_data.name,+ masked_number=acc_data.masked_number,type=acc_data.type,balance=acc_data.balance,currency=acc_data.currency,@@ -1209,6 +1210,11 @@ async def sync_connection(connection.provider, account.type, acc_data.balance)account.name = acc_data.name+ # Backfills existing accounts on their next sync. Only written+ # when the provider actually returns an identifier, so a payload+ # that intermittently omits it can't blank out a known mask.+ if acc_data.masked_number is not None:+ account.masked_number = acc_data.masked_numberif acc_data.type == "credit_card":# Preserve existing CC metadata when the provider doesn't# expose it. Pluggy's creditData fields (limit, close/due@@ -1236,6 +1242,7 @@ async def sync_connection(connection_id=connection.id,external_id=acc_data.external_id,name=acc_data.name,+ masked_number=acc_data.masked_number,type=acc_data.type,balance=acc_data.balance,currency=acc_data.currency,diff --git a/backend/tests/test_providers_enable_banking.py b/backend/tests/test_providers_enable_banking.pyindex 9710be78..492d4cb8 100644--- a/backend/tests/test_providers_enable_banking.py+++ b/backend/tests/test_providers_enable_banking.py@@ -16,9 +16,14 @@ from cryptography.hazmat.primitives import serializationfrom cryptography.hazmat.primitives.asymmetric import rsafrom jose import jwt-from app.providers.base import ProviderUserActionRequired, SessionExpiredError+from app.providers.base import (+ ProviderUserActionRequired,+ SessionExpiredError,+ mask_last4,+)from app.providers.enable_banking import (EnableBankingProvider,+ _account_identifier,_map_cash_account_type,_txn_fingerprint,)@@ -394,3 +399,53 @@ async def test_refresh_credentials_valid_passes(eb_keys):creds = {"valid_until": future, "session_id_enc": "enc"}out = await provider.refresh_credentials(creds)assert out is creds+++# ----- account identifier / masking (issue #408) -----+++def test_account_identifier_prefers_iban():+ raw = {+ "account_id": {"iban": "NL91ABNA0417164300", "other": {"identification": "999"}},+ "all_account_ids": [{"identification": "888", "scheme_name": "BBAN"}],+ }+ assert _account_identifier(raw) == "NL91ABNA0417164300"+++def test_account_identifier_falls_back_to_other_scheme():+ """Banks outside SEPA report no IBAN; we must still find an identifier."""+ raw = {"account_id": {"other": {"identification": "12345678", "scheme_name": "BBAN"}}}+ assert _account_identifier(raw) == "12345678"+++def test_account_identifier_falls_back_to_all_account_ids():+ raw = {"all_account_ids": [{"identification": "87654321", "scheme_name": "BBAN"}]}+ assert _account_identifier(raw) == "87654321"+++def test_account_identifier_returns_none_when_absent():+ assert _account_identifier({"uid": "abc", "product": "Girokonto"}) is None+ assert _account_identifier({"account_id": {}, "all_account_ids": []}) is None+++def test_mask_last4_keeps_only_the_tail():+ # The whole point: the full IBAN never reaches the database.+ assert mask_last4("NL91ABNA0417164300") == "4300"+++def test_mask_last4_ignores_separators():+ """IBANs are commonly formatted in groups of four."""+ assert mask_last4("NL91 ABNA 0417 1643 00") == "4300"+ assert mask_last4("1234-5678") == "5678"+++def test_mask_last4_returns_none_when_unusable():+ assert mask_last4(None) is None+ assert mask_last4("") is None+ # Too short to mask: render nothing rather than a partial identifier.+ assert mask_last4("12") is None+ assert mask_last4("- -") is None+++def test_mask_last4_handles_exactly_four():+ assert mask_last4("1234") == "1234"diff --git a/backend/tests/test_providers_pluggy.py b/backend/tests/test_providers_pluggy.pyindex ec5ca96e..eee61ecc 100644--- a/backend/tests/test_providers_pluggy.py+++ b/backend/tests/test_providers_pluggy.py@@ -345,3 +345,30 @@ async def test_get_transactions_follows_cursor_until_next_is_null():assert first.kwargs["params"]["createdAtFrom"] == "2026-01-01"assert "after" not in first.kwargs["params"]assert client.get.await_args_list[1].kwargs["params"]["after"] == "CUR2"+++# ----- masked account number (issue #408) -----+++def test_build_account_data_masks_account_number():+ """Brazil has no IBAN; Pluggy's `number` is the branch/account number."""+ from app.providers.pluggy import _build_account_data++ acc = {+ "id": "acc-1",+ "name": "Conta Corrente",+ "type": "BANK",+ "number": "1234-56789",+ "balance": 100,+ "currencyCode": "BRL",+ }+ out = _build_account_data(acc, PluggyProvider._map_account_type)+ assert out.masked_number == "6789"+++def test_build_account_data_without_number_leaves_mask_none():+ from app.providers.pluggy import _build_account_data++ acc = {"id": "acc-2", "name": "Conta", "type": "BANK", "balance": 0}+ out = _build_account_data(acc, PluggyProvider._map_account_type)+ assert out.masked_number is Nonediff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex c5f14fa5..f4690afe 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback, useMemo, useRef } from 'react'-import { getAccountName } from '@/lib/account-utils'+import { getAccountLabel } from '@/lib/account-utils'import { useTranslation } from 'react-i18next'import { useDateLocale } from '@/hooks/use-display-locale'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'@@ -915,7 +915,7 @@ function TransactionForm({required>{accounts.map((acc) => (- <option key={acc.id} value={acc.id}>{getAccountName(acc)}</option>+ <option key={acc.id} value={acc.id}>{getAccountLabel(acc)}</option>))}</select></div>diff --git a/frontend/src/components/transfer-dialog.tsx b/frontend/src/components/transfer-dialog.tsxindex ba0afb2f..8b75b1e2 100644--- a/frontend/src/components/transfer-dialog.tsx+++ b/frontend/src/components/transfer-dialog.tsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback } from 'react'-import { getAccountName } from '@/lib/account-utils'+import { getAccountLabel } from '@/lib/account-utils'import { useTranslation } from 'react-i18next'import { Button } from '@/components/ui/button'import { Input } from '@/components/ui/input'@@ -137,7 +137,7 @@ export function TransferDialog({<option value="" disabled>{t('transactions.account')}</option>{accounts.map((acc) => (<option key={acc.id} value={acc.id}>- {getAccountName(acc)} ({acc.currency})+ {getAccountLabel(acc)} ({acc.currency})</option>))}</select>@@ -160,7 +160,7 @@ export function TransferDialog({<option value="" disabled>{t('transactions.account')}</option>{availableToAccounts.map((acc) => (<option key={acc.id} value={acc.id}>- {getAccountName(acc)} ({acc.currency})+ {getAccountLabel(acc)} ({acc.currency})</option>))}</select>diff --git a/frontend/src/lib/account-utils.ts b/frontend/src/lib/account-utils.tsindex cca21d1f..7efcf07b 100644--- a/frontend/src/lib/account-utils.ts+++ b/frontend/src/lib/account-utils.ts@@ -1,3 +1,32 @@export function getAccountName(account: { name: string; display_name?: string | null }): string {return account.display_name ?? account.name}++/**+ * The bank's identifier for an account, masked to its last 4 chars, e.g. "•••• 1234".+ *+ * Banks commonly report every account under the same label (often the holder's+ * name), so this is what tells two of them apart. Null when the provider gave us+ * no identifier, so callers render nothing rather than an empty mask. Locale-neutral+ * by construction: dots and the bank's own digits, nothing to translate.+ */+export function formatAccountMask(account: { masked_number?: string | null }): string | null {+ return account.masked_number ? `•••• ${account.masked_number}` : null+}++/**+ * Account name with its mask appended, e.g. "Checking •••• 1234", for compact+ * single-line surfaces such as the account <select> options, where there is no+ * room for a secondary line. Unparenthesized so callers that already append+ * their own parenthetical (the transfer dialog appends the currency) don't end+ * up with two of them.+ */+export function getAccountLabel(account: {+ name: string+ display_name?: string | null+ masked_number?: string | null+}): string {+ const mask = formatAccountMask(account)+ const name = getAccountName(account)+ return mask ? `${name} ${mask}` : name+}diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex 64f21bda..5cf17ffe 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -1,5 +1,5 @@import { useEffect, useMemo, useState } from 'react'-import { getAccountName } from '@/lib/account-utils'+import { formatAccountMask, getAccountLabel, getAccountName } from '@/lib/account-utils'import { getConnectionName } from '@/lib/connection-utils'import { Link, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'@@ -281,6 +281,7 @@ export default function AccountsPage() {: dueIn === 0 ? t('accounts.dueToday'): t('accounts.dueIn', { count: dueIn })const dueClass = dueIn != null && dueIn <= 3 ? 'text-amber-600' : 'text-muted-foreground'+ const accountMask = formatAccountMask(acc)return (<div key={acc.id} className="group flex items-center px-5 py-3 hover:bg-muted/50 transition-colors"><Link to={`/accounts/${acc.id}`} className="flex items-center gap-3 flex-1 min-w-0">@@ -289,6 +290,7 @@ export default function AccountsPage() {<p className="text-sm font-medium text-foreground truncate">{getAccountName(acc)}</p><p className="text-xs text-muted-foreground">{t(cfg.label)}+ {accountMask && <> · <span className="tabular-nums">{accountMask}</span></>}{dueText && <> · <span className={dueClass}>{dueText}</span></>}</p></div>@@ -439,6 +441,7 @@ export default function AccountsPage() {: dueIn === 0 ? t('accounts.dueToday'): t('accounts.dueIn', { count: dueIn })const dueClass = dueIn != null && dueIn <= 3 ? 'text-amber-600' : 'text-muted-foreground'+ const accountMask = formatAccountMask(acc)return (<div key={acc.id} className="group flex items-center px-5 py-3 hover:bg-muted/50 transition-colors"><Link to={`/accounts/${acc.id}`} className="flex items-center gap-3 flex-1 min-w-0">@@ -447,6 +450,7 @@ export default function AccountsPage() {<p className="text-sm font-medium text-foreground truncate">{getAccountName(acc)}</p><p className="text-xs text-muted-foreground">{t(cfg.label)}+ {accountMask && <> · <span className="tabular-nums">{accountMask}</span></>}{dueText && <> · <span className={dueClass}>{dueText}</span></>}</p></div>@@ -514,7 +518,7 @@ export default function AccountsPage() {<div key={acc.id} className="flex items-center px-5 py-3"><div className="flex items-center gap-3 flex-1 min-w-0"><AccountIcon account={acc} />- <p className="text-sm font-medium text-muted-foreground truncate">{getAccountName(acc)}</p>+ <p className="text-sm font-medium text-muted-foreground truncate">{getAccountLabel(acc)}</p></div>{canWrite && (<Buttondiff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 344c35f5..9155604b 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -128,6 +128,9 @@ export interface Account {external_id: string | nullname: stringdisplay_name: string | null+ // Last 4 chars of the bank's identifier for the account, when the provider+ // exposes one. Tells apart accounts a bank reports under an identical name.+ masked_number: string | null// Denormalized bank identity from the linked connection (null for manual// accounts). Used to render the institution logo next to the account.institution_name: string | null