Open-source personal finance manager. Self-hosted, privacy-first.
fix: localize account opening-balance descriptions (#1067)
Juizc93249d7ffdf
diff --git a/backend/app/services/search_service.py b/backend/app/services/search_service.pyindex 82954230..930aa5fb 100644--- a/backend/app/services/search_service.py+++ b/backend/app/services/search_service.py@@ -137,6 +137,7 @@ async def search_all("account_id": str(tx.account_id),"category_id": str(tx.category_id) if tx.category_id else None,"tx_type": tx.type,+ "source": tx.source,},))diff --git a/backend/tests/test_opening_balance_locale_api.py b/backend/tests/test_opening_balance_locale_api.pynew file mode 100644index 00000000..ae179ce7--- /dev/null+++ b/backend/tests/test_opening_balance_locale_api.py@@ -0,0 +1,142 @@+"""Backend-to-wire proof; UI translation is covered separately by Vitest."""++import json+import os+import uuid+from datetime import date+from decimal import Decimal+from pathlib import Path++import pytest+from httpx import AsyncClient+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.transaction import Transaction+++async def test_opening_balance_source_and_raw_description_survive_locale_changes(+ client: AsyncClient, auth_headers, session: AsyncSession+):+ response = await client.post(+ "/api/accounts",+ headers=auth_headers,+ json={+ "name": "Synthetic locale regression",+ "type": "checking",+ "balance": "100.00",+ "balance_date": "2026-09-12",+ "currency": "BRL",+ },+ )+ assert response.status_code == 201+ account = response.json()+ account_id = account["id"]++ response = await client.post(+ "/api/transactions",+ headers=auth_headers,+ json={+ "account_id": account_id,+ "description": "Saldo inicial",+ "amount": "50.00",+ "currency": "BRL",+ "date": "2026-09-11",+ "type": "credit",+ },+ )+ assert response.status_code == 201+ manual = response.json()+ assert manual["source"] == "manual"+ assert manual["description"] == "Saldo inicial"++ async def reread():+ # Evict identities before every SELECT: never compare a stale ORM cache.+ session.expunge_all()+ rows = (+ await session.scalars(+ select(Transaction).where(Transaction.account_id == uuid.UUID(account_id))+ )+ ).all()+ snapshot = {+ str(row.id): {+ column.key: getattr(row, column.key) for column in Transaction.__table__.columns+ }+ for row in rows+ }+ await session.rollback()+ return snapshot++ before = await reread()+ assert len(before) == 2+ assert before[manual["id"]]["source"] == "manual"+ opening_id = next(row_id for row_id in before if row_id != manual["id"])+ assert before[opening_id]["source"] == "opening_balance"+ assert before[opening_id]["amount"] == Decimal("100.00")+ assert before[opening_id]["date"] == date(2026, 9, 12)+ assert before[manual["id"]]["amount"] == Decimal("50.00")+ assert before[manual["id"]]["date"] == date(2026, 9, 11)+ assert all(row["description"] == "Saldo inicial" for row in before.values())++ locale_responses = {}+ for language in ("en", "pt-BR", "en"):+ response = await client.patch(+ "/api/users/me",+ headers=auth_headers,+ json={"preferences": {"language": language}},+ )+ assert response.status_code == 200+ assert response.json()["preferences"]["language"] == language+ response = await client.get("/api/users/me", headers=auth_headers)+ assert response.status_code == 200+ assert response.json()["preferences"]["language"] == language++ response = await client.get(+ "/api/transactions",+ headers=auth_headers,+ params={"account_id": account_id, "include_opening_balance": "true"},+ )+ assert response.status_code == 200+ payload = response.json()+ assert payload["total"] == 2+ assert len(payload["items"]) == 2+ wire = {row["id"]: row for row in payload["items"]}+ locale_responses[language] = payload+ assert set(wire) == set(before)+ assert wire[opening_id]["source"] == "opening_balance"+ assert wire[manual["id"]]["source"] == "manual"+ for row_id, row in wire.items():+ assert row["description"] == "Saldo inicial"+ assert row["account_id"] == account_id+ assert Decimal(str(row["amount"])) == before[row_id]["amount"]+ assert row["date"] == before[row_id]["date"].isoformat()++ # Both the omitted default and explicit false exclude only the synthetic row.+ for inclusion in ({}, {"include_opening_balance": "false"}):+ response = await client.get(+ "/api/transactions",+ headers=auth_headers,+ params={"account_id": account_id, **inclusion},+ )+ assert response.status_code == 200+ payload = response.json()+ assert payload["total"] == 1+ assert len(payload["items"]) == 1+ assert payload["items"][0]["id"] == manual["id"]+ assert payload["items"][0]["source"] == "manual"+ assert payload["items"][0]["description"] == "Saldo inicial"++ # Includes every persisted column, not just source/description.+ assert await reread() == before++ fixture_path = os.environ.get("SECURO_1022_WIRE_FIXTURE_OUT")+ if fixture_path:+ Path(fixture_path).write_text(+ json.dumps(+ {"account": account, "responses": locale_responses, "persisted_rows": before},+ indent=2,+ default=str,+ ),+ encoding="utf-8",+ )diff --git a/backend/tests/test_search_opening_balance_api.py b/backend/tests/test_search_opening_balance_api.pynew file mode 100644index 00000000..cb60c1a5--- /dev/null+++ b/backend/tests/test_search_opening_balance_api.py@@ -0,0 +1,87 @@+"""Search carries provenance without translating or mutating stored descriptions."""++import uuid+from datetime import date, datetime, timezone+from decimal import Decimal++import pytest+from sqlalchemy import select++from app.models.account import Account+from app.models.transaction import Transaction+from app.models.user import User+from app.services.workspace_service import create_personal_workspace_for_user++[email protected]("language", ["en", "pt-BR", "nl"])+async def test_search_exposes_source_preserves_raw_fields_and_workspace_scope(+ client, auth_headers, session, test_user, test_account, language+):+ rows = []+ for source in ["opening_balance", "manual"]:+ tx = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, account_id=test_account.id,+ description="Saldo inicial", source=source, amount=Decimal("100.25"),+ currency="BRL", type="credit", date=date(2026, 9, 12),+ created_at=datetime(2026, 9, 12, tzinfo=timezone.utc),+ )+ session.add(tx)+ rows.append(tx)++ other = User(+ id=uuid.uuid4(), email="[email protected]",+ hashed_password="synthetic-unused", is_active=True, is_verified=True,+ )+ session.add(other)+ await session.flush()+ workspace = await create_personal_workspace_for_user(session, other)+ account = Account(+ id=uuid.uuid4(), user_id=other.id, workspace_id=workspace.id,+ name="Private", type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add(account)+ await session.flush()+ foreign = Transaction(+ id=uuid.uuid4(), user_id=other.id, workspace_id=workspace.id,+ account_id=account.id, description="Saldo inicial", source="opening_balance",+ amount=Decimal("999"), currency="BRL", type="credit", date=date(2026, 9, 12),+ )+ session.add(foreign)+ await session.commit()+ before = [(tx.id, tx.description, tx.source, tx.amount, tx.date) for tx in rows]++ response = await client.get(+ "/api/search", params={"q": "saldo"},+ headers={**auth_headers, "Accept-Language": language},+ )+ assert response.status_code == 200+ hits = [hit for hit in response.json()["results"] if hit["type"] == "transaction"]+ assert {hit["id"] for hit in hits} == {str(tx.id) for tx in rows}+ by_id = {hit["id"]: hit for hit in hits}+ for tx in rows:+ hit = by_id[str(tx.id)]+ assert hit["label"] == "Saldo inicial"+ assert hit["amount"] == 100.25+ assert hit["currency"] == "BRL"+ assert hit["date"] == "2026-09-12"+ assert hit["meta"] == {+ "account_id": str(test_account.id), "category_id": None,+ "tx_type": "credit", "source": tx.source,+ }+ session.expire_all()+ persisted = (await session.execute(select(Transaction).where(+ Transaction.id.in_([row[0] for row in before])+ ))).scalars().all()+ assert sorted((tx.id, tx.description, tx.source, tx.amount, tx.date) for tx in persisted) == sorted(before)+ # Characterize the deferred query-policy decision: display localization+ # does not make an English phrase match raw Portuguese stored fields.+ english_query = await client.get(+ "/api/search", params={"q": "opening balance"}, headers=auth_headers,+ )+ assert english_query.status_code == 200+ assert english_query.json()["results"] == []+++async def test_search_still_requires_authentication(client):+ response = await client.get("/api/search", params={"q": "saldo"})+ assert response.status_code == 401\ No newline at end of filediff --git a/frontend/src/components/command-palette-opening-balance.test.tsx b/frontend/src/components/command-palette-opening-balance.test.tsxnew file mode 100644index 00000000..9e69528d--- /dev/null+++ b/frontend/src/components/command-palette-opening-balance.test.tsx@@ -0,0 +1,99 @@+import { useState } from 'react'+import { act, screen, waitFor, within } from '@testing-library/react'+import { beforeEach, expect, it, vi } from 'vitest'+import { CommandPalette } from '@/components/command-palette'+import { i18n, renderWithProviders } from '@/test/utils'+import type { SearchHit } from '@/lib/api'+import { transactionDescription } from '@/lib/transaction-description'+import { SUPPORTED_LANGS } from '@/lib/i18n'++const api = vi.hoisted(() => ({ query: vi.fn() }))+vi.mock('@/lib/api', () => ({ search: api }))+vi.mock('@/contexts/workspace-context', () => ({ useWorkspace: () => ({ hasModule: () => true }) }))+vi.mock('@/hooks/use-display-locale', () => ({ useDisplayLocale: () => 'en-US' }))++const opening: SearchHit = {+ type: 'transaction', id: 'opening', label: 'Saldo inicial', subtitle: 'Synthetic',+ amount: 100, currency: 'BRL', date: '2026-09-12', icon: null, color: null,+ meta: { source: 'opening_balance', account_id: 'acc-1', tx_type: 'credit' },+}+const hits: SearchHit[] = [+ opening,+ { ...opening, id: 'manual', subtitle: 'Manual', meta: { source: 'manual' } },+ { ...opening, id: 'legacy', subtitle: 'Legacy', meta: {} },+ { ...opening, id: 'account', type: 'account', subtitle: 'Account' },+ { ...opening, id: 'null', subtitle: 'Null source', meta: { source: null } },+]++function Harness() {+ const [open, setOpen] = useState(true)+ return <><button onClick={() => setOpen(true)}>Open palette</button><CommandPalette open={open} onOpenChange={setOpen} /></>+}++beforeEach(async () => {+ vi.clearAllMocks()+ await i18n.changeLanguage('en')+ api.query.mockResolvedValue(hits)+})++it('translates only source-qualified transaction hits and keeps future recents live across locales', async () => {+ const original = structuredClone(hits)+ const { user } = renderWithProviders(<Harness />)+ await user.type(screen.getByRole('combobox'), 'saldo')+ await waitFor(() => expect(api.query).toHaveBeenCalledWith('saldo', 5))+ await waitFor(() => expect(screen.getByText('Synthetic', { exact: false })).toBeVisible())+ const option = (subtitle: string) => screen.getByRole('option', { name: new RegExp(subtitle) })+ expect(within(option('Synthetic')).getByText('Opening balance')).toBeVisible()+ for (const subtitle of ['Manual', 'Legacy', 'Account', 'Null source']) {+ expect(within(option(subtitle)).getByText('Saldo inicial')).toBeVisible()+ }+ const amount = within(option('Synthetic')).getByText(/100\.00/).textContent+ await act(async () => { await i18n.changeLanguage('pt-BR') })+ expect(within(option('Synthetic')).getByText('Saldo inicial')).toBeVisible()+ await act(async () => { await i18n.changeLanguage('nl') })+ expect(within(option('Synthetic')).getByText('Openingsbalans')).toBeVisible()+ expect(within(option('Synthetic')).getByText(/100\.00/).textContent).toBe(amount)+ await user.click(option('Synthetic'))+ await waitFor(() => expect(screen.queryByRole('combobox')).not.toBeInTheDocument())+ const recent = JSON.parse(localStorage.getItem('securo.cmdk.recent')!)[0]+ expect(recent).toMatchObject({ label: 'Saldo inicial', source: 'opening_balance', icon: 'transaction' })+ await user.click(screen.getByRole('button', { name: 'Open palette' }))+ expect(screen.getByText('Openingsbalans')).toBeVisible()+ await act(async () => { await i18n.changeLanguage('en') })+ expect(screen.getByText('Opening balance')).toBeVisible()+ // Re-selecting a recent must not lose its provenance or freeze its translation.+ await user.click(screen.getByText('Opening balance'))+ await user.click(screen.getByRole('button', { name: 'Open palette' }))+ await act(async () => { await i18n.changeLanguage('pt-BR') })+ expect(screen.getByText('Saldo inicial')).toBeVisible()+ // A legacy result with no provenance remains raw when saved as a recent.+ await user.type(screen.getByRole('combobox'), 'saldo')+ await waitFor(() => expect(screen.getByRole('option', { name: /Legacy/ })).toBeVisible())+ await user.click(screen.getByRole('option', { name: /Legacy/ }))+ await user.click(screen.getByRole('button', { name: 'Open palette' }))+ await act(async () => { await i18n.changeLanguage('nl') })+ expect(within(screen.getByRole('option', { name: /Legacy/ })).getByText('Saldo inicial')).toBeVisible()+ expect(screen.getByText('Openingsbalans')).toBeVisible()+ await user.type(screen.getByRole('combobox'), 'saldo')+ await waitFor(() => expect(screen.getByRole('option', { name: /Account/ })).toBeVisible())+ await user.click(screen.getByRole('option', { name: /Account/ }))+ await user.click(screen.getByRole('button', { name: 'Open palette' }))+ expect(within(screen.getByRole('option', { name: /Account/ })).getByText('Saldo inicial')).toBeVisible()+ expect(hits).toEqual(original)+})++// Characterization of the shared display contract across every shipped bundle.+it.each(SUPPORTED_LANGS)('ships dedicated primary copy without changing badge copy ($code)', async ({ code }) => {+ await i18n.changeLanguage(code)+ const title = i18n.getResource(code, 'translation', 'accounts.openingBalanceDescription')+ const badge = i18n.getResource(code, 'translation', 'accounts.openingBalance')+ expect(typeof title).toBe('string')+ expect(title).not.toBe('accounts.openingBalanceDescription')+ expect(transactionDescription('raw API text', 'opening_balance', i18n.t)).toBe(title)+ expect(badge).toBeTruthy()+ for (const text of ['Saldo inicial', 'opening balance', 'Opening balance', 'Grocery store', 'lowercase user text']) {+ for (const source of ['manual', 'import', undefined, null, { source: 'opening_balance' }]) {+ expect(transactionDescription(text, source, i18n.t)).toBe(text)+ }+ }+})\ No newline at end of filediff --git a/frontend/src/components/command-palette.tsx b/frontend/src/components/command-palette.tsxindex 369f717c..dd5b469a 100644--- a/frontend/src/components/command-palette.tsx+++ b/frontend/src/components/command-palette.tsx@@ -36,6 +36,7 @@ import {import { search as searchApi, type SearchHit, type SearchHitType } from '@/lib/api'import { cn, normalizeText } from '@/lib/utils'+import { transactionDescription } from '@/lib/transaction-description'// ---------------------------------------------------------------------------// Static actions & navigation registry@@ -170,6 +171,7 @@ type RecentItem = {path: stringicon: string // lucide name, stored as string; resolved via fallback iconsublabel?: string | null+ source?: 'opening_balance'}const RECENT_KEY = 'securo.cmdk.recent'@@ -335,13 +337,14 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {}, [debounced, t])const runAndClose = useCallback(- (item: { id: string; label: string; path: string; iconName: string; sublabel?: string | null }) => {+ (item: { id: string; label: string; path: string; iconName: string; sublabel?: string | null; source?: RecentItem['source'] }) => {saveRecent({id: item.id,label: item.label,path: item.path,icon: item.iconName,sublabel: item.sublabel,+ source: item.source,})handleOpenChange(false)// Slight delay so dialog closes before navigation animation@@ -434,7 +437,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {{recents.map((r) => (<Command.Itemkey={`recent-${r.id}`}- value={`recent ${r.label}`}+ value={`recent ${transactionDescription(r.label, r.icon === 'transaction' ? r.source : undefined, t)}`}onSelect={() =>runAndClose({id: r.id,@@ -442,6 +445,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {path: r.path,iconName: r.icon,sublabel: r.sublabel,+ source: r.source,})}className={itemClasses()}@@ -450,7 +454,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {<Compass size={14} /></ItemIcon><div className="min-w-0 flex-1">- <div className="truncate text-[13.5px] text-foreground">{r.label}</div>+ <div className="truncate text-[13.5px] text-foreground">{transactionDescription(r.label, r.icon === 'transaction' ? r.source : undefined, t)}</div>{r.sublabel && (<div className="truncate text-[11.5px] text-muted-foreground">{r.sublabel}</div>)}@@ -549,6 +553,9 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {labelKey={meta.labelKey}>{items.map((hit) => {+ const source = hit.type === 'transaction' && hit.meta?.source === 'opening_balance'+ ? 'opening_balance' : undefined+ const label = transactionDescription(hit.label, source, t)const amount = formatHitAmount(hit.amount, hit.currency, locale)const dateLabel = formatHitDate(hit.date, locale)const isPositive = (hit.amount ?? 0) > 0 && hit.type === 'transaction' && (hit.meta?.tx_type === 'credit' || hit.amount! > 0)@@ -556,7 +563,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {return (<Command.Itemkey={`${hit.type}-${hit.id}`}- value={`${hit.type} ${hit.label} ${hit.subtitle ?? ''}`}+ value={`${hit.type} ${label} ${hit.subtitle ?? ''}`}onSelect={() =>runAndClose({id: `${hit.type}-${hit.id}`,@@ -564,6 +571,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {path: meta.pathFor(hit),iconName: hit.type,sublabel: hit.subtitle,+ source,})}className={itemClasses()}@@ -572,7 +580,7 @@ export function CommandPalette({ open, onOpenChange }: CommandPaletteProps) {<GroupIcon size={14} /></ItemIcon><div className="min-w-0 flex-1">- <div className="truncate text-[13.5px] text-foreground">{hit.label}</div>+ <div className="truncate text-[13.5px] text-foreground">{label}</div>{hit.subtitle && (<div className="truncate text-[11.5px] text-muted-foreground/90">{hit.subtitle}diff --git a/frontend/src/components/mobile-transaction-row.tsx b/frontend/src/components/mobile-transaction-row.tsxindex 05cee746..4e92ed5b 100644--- a/frontend/src/components/mobile-transaction-row.tsx+++ b/frontend/src/components/mobile-transaction-row.tsx@@ -7,6 +7,7 @@ import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { useTranslation } from 'react-i18next'import { formatCurrency } from '@/lib/format'import { shouldShowPendingBadge } from '@/lib/transaction-status'+import { transactionDescription } from '@/lib/transaction-description'/** Keep long merchant references on one line when there are no word breaks. */function hasWordBreaks(text: string): boolean {@@ -28,6 +29,8 @@ interface MobileTransactionRowProps {onClick: (tx: Transaction) => void/** Show the payee instead of the account name in an account-scoped view. */showPayee?: boolean+ /** Localize synthetic opening-balance descriptions only in account detail. */+ localizeOpeningBalance?: boolean}export function MobileTransactionRow({@@ -44,9 +47,13 @@ export function MobileTransactionRow({onSelect,onClick,showPayee = false,+ localizeOpeningBalance = false,}: MobileTransactionRowProps) {const { mask } = usePrivacyMode()const { t } = useTranslation()+ const description = localizeOpeningBalance+ ? transactionDescription(tx.description, tx.source, t)+ : tx.descriptionconst displayAmount = tx.is_shared && tx.viewer_share != null? Number(tx.viewer_share)@@ -102,8 +109,8 @@ export function MobileTransactionRow({<div className="min-w-0 flex-1">{/* Description row */}<div className="flex items-center gap-1.5">- <p className={`text-sm font-semibold text-foreground leading-tight min-w-0 ${hasWordBreaks(tx.description) ? 'break-words whitespace-normal' : 'truncate'}`}>- {tx.description}+ <p className={`text-sm font-semibold text-foreground leading-tight min-w-0 ${hasWordBreaks(description) ? 'break-words whitespace-normal' : 'truncate'}`}>+ {description}</p>{tx.group_id && (<span className="inline-flex items-center text-[9px] font-semibold uppercase tracking-wide text-violet-700 bg-violet-50 border border-violet-200 dark:bg-violet-950/40 dark:text-violet-300 dark:border-violet-900 px-1 py-0.5 rounded-full shrink-0">diff --git a/frontend/src/lib/transaction-description.ts b/frontend/src/lib/transaction-description.tsnew file mode 100644index 00000000..6d399e8e--- /dev/null+++ b/frontend/src/lib/transaction-description.ts@@ -0,0 +1,6 @@+import type { TFunction } from 'i18next'++/** Translate synthetic rows by provenance, never by user-authored text. */+export function transactionDescription(description: string, source: unknown, t: TFunction): string {+ return source === 'opening_balance' ? t('accounts.openingBalanceDescription') : description+}\ No newline at end of filediff --git a/frontend/src/locales/cs.json b/frontend/src/locales/cs.jsonindex 0c55839f..3c8ca1cc 100644--- a/frontend/src/locales/cs.json+++ b/frontend/src/locales/cs.json@@ -1224,6 +1224,7 @@"confirmDeleteTitle": "Smazat účet?","confirmDeleteDesc": "Tuto akci nelze vrátit. Smaže také všechny transakce, záznamy o importech a opakované transakce přiřazené k tomuto účtu a odpojí všechny cíle, které ho sledovaly.","openingBalance": "počáteční zůstatek",+ "openingBalanceDescription": "Počáteční zůstatek","notFound": "Účet nebyl nalezen.","balance": "Zůstatek","balanceCreditCard": "Dlužná částka",diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex ef2e06d9..d37e7845 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -1156,6 +1156,7 @@"confirmDeleteTitle": "Konto löschen?","confirmDeleteDesc": "Diese Aktion kann nicht rückgängig gemacht werden. Es werden auch alle Transaktionen, Importdatensätze und wiederkehrenden Transaktionen gelöscht, die mit diesem Konto verknüpft sind, und alle Ziele, die dieses Konto verfolgt haben, werden getrennt.","openingBalance": "Eröffnungssaldo",+ "openingBalanceDescription": "Eröffnungssaldo","notFound": "Konto nicht gefunden.","balance": "Saldo","balanceCreditCard": "Geschuldeter Betrag",diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex c9523230..5137c70d 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -886,6 +886,7 @@"confirmDeleteTitle": "Διαγραφή λογαριασμού;","confirmDeleteDesc": "Αυτή η ενέργεια είναι μη αναστρέψιμη. Θα διαγράψει επίσης κάθε συναλλαγή, εγγραφή εισαγωγής και επαναλαμβανόμενη συναλλαγή που συνδέεται με αυτόν τον λογαριασμό, και θα αποσυνδέσει τυχόν στόχους που τον παρακολουθούσαν.","openingBalance": "αρχικό υπόλοιπο",+ "openingBalanceDescription": "Αρχικό υπόλοιπο","notFound": "Ο λογαριασμός δεν βρέθηκε.","balance": "Υπόλοιπο","balanceCreditCard": "Οφειλόμενο ποσό",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex e9ec2c48..64c066d4 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -1156,6 +1156,7 @@"confirmDeleteTitle": "Delete account?","confirmDeleteDesc": "This action is irreversible. It will also delete every transaction, import record and recurring transaction attached to this account, and unlink any goals that were tracking it.","openingBalance": "opening balance",+ "openingBalanceDescription": "Opening balance","notFound": "Account not found.","balance": "Balance","balanceCreditCard": "Amount owed",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 0d306358..fb4f1669 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -1158,6 +1158,7 @@"confirmDeleteTitle": "¿Eliminar cuenta?","confirmDeleteDesc": "Esta acción es irreversible. También eliminará todas las transacciones, registros de importación y transacciones recurrentes adjuntas a esta cuenta, y desvinculará cualquier objetivo que la estuviera siguiendo.","openingBalance": "saldo inicial",+ "openingBalanceDescription": "Saldo inicial","notFound": "Cuenta no encontrada.","balance": "Saldo","balanceCreditCard": "Importe adeudado",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 867d76f5..ca972640 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -1158,6 +1158,7 @@"confirmDeleteTitle": "Supprimer le compte ?","confirmDeleteDesc": "Cette action est irréversible. Elle supprimera également toutes les transactions, enregistrements d'import et transactions récurrentes attachés à ce compte, et dissociera tous les objectifs qui le suivaient.","openingBalance": "solde d'ouverture",+ "openingBalanceDescription": "Solde d'ouverture","notFound": "Compte introuvable.","balance": "Solde","balanceCreditCard": "Montant dû",diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex c6cbe771..69e7614c 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -1156,6 +1156,7 @@"confirmDeleteTitle": "खाता हटाएँ?","confirmDeleteDesc": "यह कार्रवाई वापस नहीं ली जा सकती। यह इस खाते से जुड़े हर लेन-देन, इंपोर्ट रिकॉर्ड और आवर्ती लेन-देन को भी हटा देगी, और इसे ट्रैक कर रहे किसी भी लक्ष्य को अलग कर देगी।","openingBalance": "आरंभिक शेष",+ "openingBalanceDescription": "आरंभिक शेष","notFound": "खाता नहीं मिला।","balance": "शेष राशि","balanceCreditCard": "बकाया राशि",diff --git a/frontend/src/locales/hu.json b/frontend/src/locales/hu.jsonindex 6f3822c4..d21b338d 100644--- a/frontend/src/locales/hu.json+++ b/frontend/src/locales/hu.json@@ -1156,6 +1156,7 @@"confirmDeleteTitle": "Törlöd a számlát?","confirmDeleteDesc": "Ez a művelet nem vonható vissza. A számlához tartozó összes tranzakció, importálási rekord és ismétlődő tranzakció is törlődik, és az ezt követő célok kapcsolata megszűnik.","openingBalance": "nyitó egyenleg",+ "openingBalanceDescription": "Nyitó egyenleg","notFound": "A számla nem található.","balance": "Egyenleg","balanceCreditCard": "Tartozás",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 76eef661..0b5e0d61 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -1158,6 +1158,7 @@"confirmDeleteTitle": "Eliminare il conto?","confirmDeleteDesc": "Questa azione è irreversibile. Eliminerà anche ogni transazione, record di importazione e transazione ricorrente collegati a questo conto, e scollegherà gli obiettivi che lo tracciavano.","openingBalance": "saldo iniziale",+ "openingBalanceDescription": "Saldo iniziale","notFound": "Conto non trovato.","balance": "Saldo","balanceCreditCard": "Importo dovuto",diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex d073cae9..0a1a359d 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -1156,6 +1156,7 @@"confirmDeleteTitle": "口座を削除しますか?","confirmDeleteDesc": "この操作は取り消せません。この口座に関連するすべての取引、インポート記録、定期取引も削除され、この口座を追跡していた目標の紐付けが解除されます。","openingBalance": "期首残高",+ "openingBalanceDescription": "期首残高","notFound": "口座が見つかりません。","balance": "残高","balanceCreditCard": "未払い金額",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 28773f87..4d9a466e 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -1156,6 +1156,7 @@"confirmDeleteTitle": "Account verwijderen?","confirmDeleteDesc": "Deze actie is onomkeerbaar. Het verwijdert ook elke transactie, importrecord en terugkerende transactie die aan dit account is gekoppeld, en ontkoppelt alle doelen die het bijhielden.","openingBalance": "openingsbalans",+ "openingBalanceDescription": "Openingsbalans","notFound": "Account niet gevonden.","balance": "Balans","balanceCreditCard": "Verschuldigd bedrag",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 2fb47210..4119c8cd 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -1197,6 +1197,7 @@"confirmDeleteTitle": "Usunąć konto?","confirmDeleteDesc": "Ta operacja jest nieodwracalna. Usunie również każdą transakcję, rekord importu i transakcję cykliczną powiązaną z tym kontem oraz odłączy wszelkie cele, które je śledziły.","openingBalance": "saldo początkowe",+ "openingBalanceDescription": "Saldo początkowe","notFound": "Nie znaleziono konta.","balance": "Saldo","balanceCreditCard": "Kwota zadłużenia",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex ed107360..f2742aed 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -1158,6 +1158,7 @@"confirmDeleteTitle": "Excluir conta?","confirmDeleteDesc": "Esta ação é irreversível. Também excluirá todas as transações, registros de importação e transações recorrentes vinculadas a esta conta, e desvinculará qualquer meta que estivesse acompanhando-a.","openingBalance": "saldo inicial",+ "openingBalanceDescription": "Saldo inicial","notFound": "Conta não encontrada.","balance": "Saldo","balanceCreditCard": "Valor devido",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex a300a462..94e3ee95 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -1158,6 +1158,7 @@"confirmDeleteTitle": "Eliminar conta?","confirmDeleteDesc": "Esta ação é irreversível. Também eliminará todas as transações, registos de importação e transações recorrentes vinculadas a esta conta, e desvinculará qualquer objetivo que a estivesse a acompanhar.","openingBalance": "saldo inicial",+ "openingBalanceDescription": "Saldo inicial","notFound": "Conta não encontrada.","balance": "Saldo","balanceCreditCard": "Valor devido",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex d9d2d3fc..b3ca250c 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -1170,6 +1170,7 @@"confirmDeleteTitle": "Удалить счёт?","confirmDeleteDesc": "Это действие необратимо. Оно также удалит все транзакции, записи импорта и регулярные транзакции, привязанные к этому счёту, и отвяжет цели, которые отслеживали его.","openingBalance": "начальный баланс",+ "openingBalanceDescription": "Начальный баланс","notFound": "Счёт не найден.","balance": "Баланс","balanceCreditCard": "Задолженность",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex b90b7d6f..568a4e80 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -1208,6 +1208,7 @@"confirmDeleteTitle": "Vymazať účet?","confirmDeleteDesc": "Táto akcia je nezvratná. Vymaže aj všetky transakcie, záznamy o importoch a opakované transakcie priradené k tomuto účtu a odpojí všetky ciele, ktoré ho sledovali.","openingBalance": "počiatočný zostatok",+ "openingBalanceDescription": "Počiatočný zostatok","notFound": "Účet sa nenašiel.","balance": "Zostatok","balanceCreditCard": "Dlžná suma",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex b6385335..bace692f 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -1170,6 +1170,7 @@"confirmDeleteTitle": "Видалити рахунок?","confirmDeleteDesc": "Ця дія незворотна. Вона також видалить усі транзакції, записи імпорту та регулярні транзакції, прив'язані до цього рахунку, і відв'яже цілі, які відстежували його.","openingBalance": "початковий баланс",+ "openingBalanceDescription": "Початковий баланс","notFound": "Рахунок не знайдено.","balance": "Баланс","balanceCreditCard": "Заборгованість",diff --git a/frontend/src/pages/account-detail-opening-balance.test.tsx b/frontend/src/pages/account-detail-opening-balance.test.tsxnew file mode 100644index 00000000..08a01e14--- /dev/null+++ b/frontend/src/pages/account-detail-opening-balance.test.tsx@@ -0,0 +1,158 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { act, screen, waitFor } from '@testing-library/react'+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'++import AccountDetailPage from '@/pages/account-detail'+import { MobileTransactionRow } from '@/components/mobile-transaction-row'+import { i18n, renderWithProviders } from '@/test/utils'+import type { Transaction } from '@/types'++type AsgiFixture = {+ account: { id: string; name: string; type: string; currency: string; balance: string | number }+ responses: Record<string, { items: Transaction[]; total: number; [key: string]: unknown }>+}++const asgiFixturePath = process.env.SECURO_1022_ASGI_FIXTURE+const asgiFixture = asgiFixturePath+ ? JSON.parse(readFileSync(asgiFixturePath, 'utf8')) as AsgiFixture+ : null++const api = vi.hoisted(() => ({+ accounts: { get: vi.fn(), bills: vi.fn(), summary: vi.fn(), list: vi.fn(), update: vi.fn() },+ transactions: { list: vi.fn(), update: vi.fn(), delete: vi.fn(), create: vi.fn() },+ dashboard: { projectedTransactions: vi.fn() },+ categories: { list: vi.fn() },+ categoryGroups: { list: vi.fn() },+}))+const viewport = vi.hoisted(() => ({ mobile: false }))++vi.mock('@/lib/api', () => ({+ accounts: api.accounts,+ transactions: api.transactions,+ dashboard: api.dashboard,+ categories: api.categories,+ categoryGroups: api.categoryGroups,+}))+vi.mock('@/hooks/use-mobile', () => ({ useIsMobile: () => viewport.mobile }))+vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))+vi.mock('@/hooks/use-privacy-mode', () => ({+ usePrivacyMode: () => ({ mask: (value: string) => value, privacyMode: false, MASK: '***' }),+}))+vi.mock('@/contexts/auth-context', () => ({+ useAuth: () => ({ user: { preferences: { currency_display: 'BRL' } } }),+}))+vi.mock('@/contexts/workspace-context', () => ({+ useWorkspace: () => ({ canWrite: true }),+}))++const account = {+ id: asgiFixture?.account.id ?? 'acc-1',+ name: asgiFixture?.account.name ?? 'Checking',+ type: asgiFixture?.account.type ?? 'checking',+ currency: asgiFixture?.account.currency ?? 'BRL',+ balance: Number(asgiFixture?.account.balance ?? 150),+ current_balance: 150, is_active: true,+}+const opening = {+ id: 'opening', user_id: 'user-1', account_id: 'acc-1', category_id: null,+ category: null, external_id: null, description: 'Saldo inicial', original_description: null,+ amount: 100, currency: 'BRL', date: '2026-09-12', type: 'credit',+ source: 'opening_balance', status: 'posted', payee: null, payee_id: null,+ payee_name: null, notes: null, transfer_pair_id: null, amount_primary: null,+ fx_rate_used: null, fx_fallback: false, installment_number: null,+ total_installments: null, installment_total_amount: null,+ installment_purchase_date: null, installment_series_id: null, bill_id: null,+ effective_bill_date: null, splits: [], is_ignored: false,+} satisfies Transaction+const manual = {+ ...opening, id: 'manual', source: 'manual', amount: 50, date: '2026-09-11',+} satisfies Transaction+const items: Transaction[] = asgiFixture?.responses.en.items ?? [opening, manual]++function captureAsgiRender(locale: string) {+ const directory = process.env.SECURO_1022_RENDERED_DOM_DIR+ if (!asgiFixture || !directory) return+ mkdirSync(directory, { recursive: true })+ const device = viewport.mobile ? 'mobile' : 'desktop'+ writeFileSync(join(directory, `${device}-${locale}.html`), document.body.innerHTML)+}++beforeEach(async () => {+ vi.clearAllMocks()+ viewport.mobile = false+ await i18n.changeLanguage('en')+ api.accounts.get.mockResolvedValue(account)+ api.accounts.list.mockResolvedValue([account])+ api.accounts.summary.mockResolvedValue({+ opening_balance: 0, current_balance: 150, monthly_income: 0, monthly_expenses: 0,+ projected_income: 0, projected_expenses: 0,+ })+ api.transactions.list.mockResolvedValue(+ asgiFixture?.responses.en ?? { items, total: items.length },+ )+ api.dashboard.projectedTransactions.mockResolvedValue([])+ api.categories.list.mockResolvedValue([])+ api.categoryGroups.list.mockResolvedValue([])+})++function description(text: string, mobile: boolean) {+ return screen.getByText(text, {+ selector: mobile ? 'p.font-semibold' : 'span.font-semibold',+ })+}++describe.each([false, true])('account-detail opening-balance description (mobile=%s)', (mobile) => {+ it('uses only the UI locale for the synthetic description and never rewrites an ordinary row', async () => {+ viewport.mobile = mobile+ const originalItems = structuredClone(items)+ renderWithProviders(<AccountDetailPage />, {+ route: `/accounts/${account.id}`, path: '/accounts/:id',+ })+ await waitFor(() => expect(api.transactions.list).toHaveBeenCalled())+ await waitFor(() => expect(screen.queryAllByText('Saldo inicial', {+ selector: mobile ? 'p.font-semibold' : 'span.font-semibold',+ }).length).toBeGreaterThan(0))++ // The translated badge alone must not satisfy this: check the description element.+ expect(description('Opening balance', mobile)).toBeVisible()+ expect(screen.getAllByText('Opening balance')).toHaveLength(1)+ expect(description('Saldo inicial', mobile)).toBeVisible() // manual row, same stored text+ expect(api.transactions.list).toHaveBeenCalledWith(expect.objectContaining({ include_opening_balance: true }))+ expect(items).toEqual(originalItems)+ captureAsgiRender('en')++ await act(async () => { await i18n.changeLanguage('pt-BR') })+ expect(screen.getAllByText('Saldo inicial', {+ selector: mobile ? 'p.font-semibold' : 'span.font-semibold',+ exact: true,+ })).toHaveLength(2)+ captureAsgiRender('pt-BR')+ await act(async () => { await i18n.changeLanguage('nl') })+ expect(description('Openingsbalans', mobile)).toBeVisible()+ expect(description('Saldo inicial', mobile)).toBeVisible()+ await act(async () => { await i18n.changeLanguage('en') })+ expect(description('Opening balance', mobile)).toBeVisible()+ expect(description('Saldo inicial', mobile)).toBeVisible()+ expect(opening.description).toBe('Saldo inicial')+ expect(manual.description).toBe('Saldo inicial')+ expect(items).toEqual(originalItems) // amount, date, source and API data stay unchanged+ expect(api.transactions.update).not.toHaveBeenCalled()+ captureAsgiRender('en-restored')+ })+})++it('leaves the shared mobile row unchanged for other callers', async () => {+ renderWithProviders(+ <MobileTransactionRow+ tx={opening} account={undefined} groupName={undefined} selected={false}+ selectable={false} canWrite={false} highlighted={false} locale="en-US"+ userCurrency="BRL" onSelect={() => {}} onClick={() => {}}+ />,+ )+ expect(screen.getByText('Saldo inicial', { selector: 'p.font-semibold' })).toBeVisible()+ expect(screen.queryByText('opening balance')).not.toBeInTheDocument()+})diff --git a/frontend/src/pages/account-detail.tsx b/frontend/src/pages/account-detail.tsxindex 019cf190..ff57968a 100644--- a/frontend/src/pages/account-detail.tsx+++ b/frontend/src/pages/account-detail.tsx@@ -17,6 +17,7 @@ import { Skeleton } from '@/components/ui/skeleton'import { Button } from '@/components/ui/button'import { ArrowLeft, ArrowLeftRight, CalendarClock, ChevronLeft, ChevronRight, Clock, EyeClosed, HelpCircle, Paperclip, Pencil, Plus, X } from 'lucide-react'import { MobileTransactionRow } from '@/components/mobile-transaction-row'+import { transactionDescription } from '@/lib/transaction-description'import { CategoryIcon } from '@/components/category-icon'import { ProjectedTransactionBadge } from '@/components/projected-transaction-badge'import { TransactionDialog, type TransactionSavePayload } from '@/components/transaction-dialog'@@ -1575,6 +1576,7 @@ export default function AccountDetailPage() {userCurrency={userCurrency}onSelect={() => {}}showPayee+ localizeOpeningBalanceonClick={(clickedTx) => {// The opening-balance row is synthetic; the desktop// table makes it non-clickable and mobile must match.@@ -1623,13 +1625,8 @@ export default function AccountDetailPage() {</td><td className="px-3 sm:px-4 py-3 w-full max-w-0"><div className="flex items-center gap-1.5 min-w-0">- <span className="font-semibold text-foreground text-sm truncate">{tx.description}</span>+ <span className="font-semibold text-foreground text-sm truncate">{transactionDescription(tx.description, tx.source, t)}</span><div className="flex items-center gap-1 shrink-0">- {isOpening && (- <span className="ml-2 text-xs text-muted-foreground font-normal border border-border rounded px-1.5 py-0.5">- {t('accounts.openingBalance')}- </span>- )}{isTransfer && (<span className="ml-2 inline-flex items-center gap-1 text-xs text-blue-600 font-normal bg-blue-50 border border-blue-200 rounded px-1.5 py-0.5"><ArrowLeftRight className="h-3 w-3" />