Open-source personal finance manager. Self-hosted, privacy-first.
feat(accounts): allow loan type overrides for connected accounts (#1286)
Paul Loeb302d4059ee81
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.pyindex cc9a4c62..35d20fe5 100644--- a/backend/app/services/account_service.py+++ b/backend/app/services/account_service.py@@ -67,9 +67,10 @@ LIABILITY_ACCOUNT_TYPES = frozenset({"credit_card", "loan"})def _provider_to_internal_balance(provider: str, account_type: str, balance: Decimal) -> Decimal:"""Normalize provider balances to positive-for-debt for liabilities.- A loan's balance is always debt. SimpleFIN reports credit card debt as a- negative value and exposes no account type, so only that combination needs- a sign flip.+ A loan's balance is always debt, whichever type the provider reported and+ whatever sign it used, so the magnitude is the whole answer. SimpleFIN+ reports credit card debt as a negative value and exposes no account type,+ so only that combination needs a sign flip."""if account_type == "loan":return abs(balance)@@ -487,14 +488,18 @@ async def update_account(update_data = data.model_dump(exclude_unset=True)balance_date = update_data.pop("balance_date", None)new_type = update_data.get("type", account.type)- if account.connection_id is not None and new_type == "loan":- raise ValueError("Bank-connected accounts cannot be loans yet")if account.type == "loan" and new_type != "loan" and await _has_mortgage_allocations(session, account):raise ValueError("Remove this loan's mortgage payment breakdowns before changing its type")- # Switching between a loan and any other type flips what the balance means+ # Switching a manual account to or from a loan flips what the balance means# (money held vs. money owed). That is safe for an account that only has# its opening balance; with real history it would silently reinterpret it.- if new_type != account.type and "loan" in {account.type, new_type}:+ # A connected account keeps its provider balance and history: the sync+ # renormalizes the balance to the new type on its next run.+ if (+ account.connection_id is None+ and new_type != account.type+ and "loan" in {account.type, new_type}+ ):has_history = await session.scalar(select(Transaction.id).where(@@ -532,42 +537,54 @@ async def update_account(# account creation and never overwrites it afterwards, so the override# survives subsequent syncs without a separate field.if account.connection_id is not None:+ # The contract terms describe the agreement with the lender, not+ # anything the provider reports, so a connected loan can carry them+ # and the sync has nothing to say about them.editable_fields = {"display_name","type",+ "secured_asset_id","credit_limit","statement_close_day","payment_due_day","minimum_payment","card_brand","card_level",+ *LOAN_TERM_FIELDS,}disallowed = set(update_data.keys()) - editable_fieldsif disallowed:raise ValueError("Cannot edit bank-connected accounts")old_type = account.typenew_type = update_data.get("type", account.type)- cc_fields = editable_fields - {"display_name", "type"}+ cc_fields = editable_fields - {"display_name", "type", "secured_asset_id", *LOAN_TERM_FIELDS}cc_update = {k: v for k, v in update_data.items() if k in cc_fields}if cc_update and new_type != "credit_card":raise ValueError("Credit card fields can only be set on credit card accounts")+ loan_update = {k: v for k, v in update_data.items() if k in LOAN_TERM_FIELDS}+ if loan_update and new_type != "loan":+ raise ValueError("Loan contract terms can only be set on loan accounts")for key, value in update_data.items():setattr(account, key, value)# SimpleFIN stores a card's balance with the raw provider sign (negative# for debt) under type="checking". When the user flips the type across# a liability boundary, the downstream display sites start (or stop)# applying the positive-for-debt negation, so the stored value must flip- # too — otherwise the card double-counts. Mirror the ingestion-time+ # too, otherwise the card double-counts. Mirror the ingestion-time# normalization (_provider_to_internal_balance) here so the correction# is immediate, not deferred to the next sync. Load the provider via# session.get (identity-map hit, never a lazy-load that throws).+ #+ # Leaving a loan needs that flip for every provider, so the debt the+ # account showed survives the way back. Entering one does not: the+ # normalization below takes the magnitude, which makes the flip moot.if (old_type in LIABILITY_ACCOUNT_TYPES) != (new_type in LIABILITY_ACCOUNT_TYPES):conn = (await session.get(BankConnection, account.connection_id)if account.connection_id is not Noneelse None)- if conn is not None and conn.provider == "simplefin":+ if "loan" in (old_type, new_type) or (conn is not None and conn.provider == "simplefin"):account.balance = -account.balanceif new_type == "loan":account.balance = _provider_to_internal_balance("", "loan", account.balance)@@ -580,6 +597,8 @@ async def update_account(account.minimum_payment = Noneaccount.card_brand = Noneaccount.card_level = None+ if new_type != "loan":+ account.secured_asset_id = Noneif cycle_fields_changed:await _recompute_effective_dates(session, account)await session.commit()@@ -1350,7 +1369,13 @@ async def get_period_opening_balance(is_inside_provider_snapshot(),))- opening_balance = float(account.balance) - float(posted_result.scalar() or 0)+ # The snapshot stores a liability's debt positive, while the walk this+ # seeds is signed like every other balance on screen. Only a loan+ # reaches this: a connected card returns 0.0 above.+ snapshot = float(account.balance)+ if account.type in LIABILITY_ACCOUNT_TYPES:+ snapshot = -snapshot+ opening_balance = snapshot - float(posted_result.scalar() or 0)opening_balance -= float(pending_result.scalar() or 0)if date_from > today:diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.pyindex 9eb16d3e..5c3a5986 100644--- a/backend/app/services/connection_service.py+++ b/backend/app/services/connection_service.py@@ -2406,7 +2406,8 @@ async def sync_connection(# SimpleFIN reports card debt as negative under a "checking"# label; once the user overrides the type to credit_card the# downstream sites negate it, so store positive-for-debt to keep- # them provider-agnostic and avoid double-counting.+ # them provider-agnostic and avoid double-counting. A loan reads+ # the same way whatever the provider called the account.account.balance = _provider_to_internal_balance(connection.provider,account.type,diff --git a/backend/app/services/reconciliation_rule_service.py b/backend/app/services/reconciliation_rule_service.pyindex fd9aa4d6..94e69c88 100644--- a/backend/app/services/reconciliation_rule_service.py+++ b/backend/app/services/reconciliation_rule_service.py@@ -630,7 +630,7 @@ _TIE_BREAKS = ("closest_date",)#: The kinds of account a rule may name. Closed rather than free text:#: a typo in a condition is a rule that silently never fires, and the one#: place that is unforgivable is matching, where nobody is watching.-_ACCOUNT_TYPES = ("checking", "savings", "credit_card", "investment", "wallet")+_ACCOUNT_TYPES = ("checking", "savings", "credit_card", "loan", "investment", "wallet")def _validate_account_types(rule: Any) -> list[str]:diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.pyindex 082b8518..f460d103 100644--- a/backend/tests/test_connection_service.py+++ b/backend/tests/test_connection_service.py@@ -4842,14 +4842,27 @@ async def test_sync_normalizes_simplefin_card_balance_to_positive_for_debt(@pytest.mark.asyncio-async def test_sync_leaves_simplefin_checking_balance_unchanged(- session: AsyncSession, test_user, test_workspace,[email protected]("provider", ["simplefin", "pluggy", "enable_banking"])[email protected]("account_type,provider_type,reported,stored", [+ # No override: a checking account keeps the provider's balance verbatim.+ ("checking", "checking", "1234.56", "1234.56"),+ # A loan the bank labels "checking" is debt whichever sign it reports.+ ("loan", "checking", "-650.00", "650.00"),+ ("loan", "checking", "650.00", "650.00"),+ # A loan the bank labels a card, signed either way by the provider.+ ("loan", "credit_card", "-650.00", "650.00"),+ ("loan", "credit_card", "25.00", "25.00"),+])+async def test_sync_preserves_overridden_type_and_normalizes_debt(+ session: AsyncSession, test_user, test_workspace, provider, account_type, provider_type, reported, stored,):- """A SimpleFIN non-card account (no override) keeps the provider's balance- verbatim — the normalization only applies to credit_card."""+ """An override survives sync, and a loan always stores its debt positive."""from app.models.account import Account+ from app.schemas.account import AccountUpdate+ from app.services.account_service import get_account_with_balances, update_accountconn = await _make_simplefin_connection(session, test_user.id, "SF Checking")+ conn.provider = provideraccount = Account(id=uuid.uuid4(), user_id=test_user.id, connection_id=conn.id,external_id="sf-chk-1", name="SimpleFIN Checking", type="checking",@@ -4857,13 +4870,16 @@ async def test_sync_leaves_simplefin_checking_balance_unchanged()session.add(account)await session.commit()+ await update_account(session, account.id, test_workspace.id, AccountUpdate(type=account_type))mock_provider = AsyncMock()mock_provider.refresh_credentials = AsyncMock(return_value={"token": "t"})mock_provider.get_accounts = AsyncMock(return_value=[AccountData(external_id="sf-chk-1", name="SimpleFIN Checking",- type="checking", balance=Decimal("1234.56"), currency="USD",+ type=provider_type,+ balance=Decimal(reported),+ currency="USD",),])mock_provider.get_transactions = AsyncMock(return_value=[])@@ -4876,7 +4892,13 @@ async def test_sync_leaves_simplefin_checking_balance_unchanged(await sync_connection(session, conn.id, test_workspace.id, test_user.id)await session.refresh(account)- assert account.balance == Decimal("1234.56")+ assert account.type == account_type+ assert account.balance == Decimal(stored)+ payload = await get_account_with_balances(session, account.id, test_workspace.id)+ assert payload is not None+ # A liability reads as negative money, so the stored debt is positive.+ expected = -float(stored) if account_type == "loan" else float(stored)+ assert payload["current_balance"] == expected# ---------------------------------------------------------------------------diff --git a/backend/tests/test_loan_accounts.py b/backend/tests/test_loan_accounts.pyindex 7276538a..1f3719b8 100644--- a/backend/tests/test_loan_accounts.py+++ b/backend/tests/test_loan_accounts.py@@ -193,23 +193,30 @@ async def test_retyping_account_to_loan_resigns_opening_balance_without_balance_@pytest.mark.asyncio-async def test_a_bank_connected_account_cannot_become_a_loan([email protected]("provider", ["enable_banking", "simplefin", "pluggy"])[email protected]("source_type", ["checking", "credit_card"])+async def test_a_bank_connected_account_can_become_a_loan_with_history(client: AsyncClient,auth_headers,session: AsyncSession,test_user: User,test_workspace: Workspace,+ provider: str,+ source_type: str,):from datetime import datetime, timezonefrom app.models.account import Accountfrom app.models.bank_connection import BankConnection+ from app.services.account_service import sync_opening_balance_for_connected_account++ home = await _asset(session, test_user, test_workspace, "real_estate")connection = BankConnection(id=uuid.uuid4(),user_id=test_user.id,workspace_id=test_workspace.id,- provider="enable_banking",+ provider=provider,external_id=f"ext-{uuid.uuid4().hex[:8]}",institution_name="Lender",credentials={"token": "fake"},@@ -226,6 +233,178 @@ async def test_a_bank_connected_account_cannot_become_a_loan(connection_id=connection.id,external_id="acc-1",name="Lender account",+ type=source_type,+ balance=1000 if source_type == "credit_card" else -1000,+ currency="EUR",+ )+ session.add(account)+ await session.flush()+ payment = Transaction(+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ account_id=account.id,+ external_id="payment-1",+ description="Loan repayment",+ amount=100,+ currency="EUR",+ date=app_today(),+ type="credit",+ source="sync",+ )+ session.add(payment)+ await session.flush()+ await sync_opening_balance_for_connected_account(session, account)+ await session.commit()+ before = list((await session.scalars(+ select(Transaction).where(Transaction.account_id == account.id).order_by(Transaction.id)+ )).all())+ history = [(tx.id, tx.amount, tx.type, tx.date, tx.source) for tx in before]++ response = await client.patch(+ f"/api/accounts/{account.id}",+ headers=auth_headers,+ json={"type": "loan", "secured_asset_id": str(home.id), "display_name": "Home loan"},+ )++ assert response.status_code == 200, response.text+ assert response.json()["type"] == "loan"+ assert response.json()["secured_asset_id"] == str(home.id)+ assert response.json()["current_balance"] == -1000+ assert response.json()["connection_id"] == str(connection.id)+ summary = await client.get(f"/api/accounts/{account.id}/summary", headers=auth_headers)+ assert summary.status_code == 200, summary.text+ assert summary.json()["current_balance"] == -1000+ after = (await session.scalars(+ select(Transaction).where(Transaction.account_id == account.id).order_by(Transaction.id)+ )).all()+ assert [(tx.id, tx.amount, tx.type, tx.date, tx.source) for tx in after] == history++ renamed = await client.patch(+ f"/api/accounts/{account.id}", headers=auth_headers, json={"display_name": "Mortgage"}+ )+ assert renamed.status_code == 200, renamed.text+ assert renamed.json()["type"] == "loan"+ retyped = await client.patch(+ f"/api/accounts/{account.id}", headers=auth_headers, json={"type": source_type}+ )+ assert retyped.status_code == 200, retyped.text+ assert retyped.json()["secured_asset_id"] is None+ assert retyped.json()["current_balance"] == -1000+++async def test_a_connected_loan_takes_its_contract_terms(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ """The terms come from the agreement, not the provider, so a connected+ loan can carry them: without them the type override buys a loan account+ that can never show a schedule."""+ from datetime import datetime, timezone++ from app.models.account import Account+ from app.models.bank_connection import BankConnection++ connection = BankConnection(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ provider="enable_banking",+ external_id=f"ext-{uuid.uuid4().hex[:8]}",+ institution_name="Lender",+ credentials={"token": "fake"},+ status="active",+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(connection)+ await session.flush()+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ connection_id=connection.id,+ external_id="acc-terms-1",+ name="Lender account",+ type="checking",+ balance=-60000,+ currency="EUR",+ )+ session.add(account)+ await session.commit()++ terms = {+ "loan_kind": "mortgage",+ "loan_original_amount": 60000,+ "loan_interest_rate": 0.8,+ "loan_rate_period": "monthly",+ "loan_term_months": 120,+ "loan_first_payment_date": "2026-01-10",+ "loan_amortization": "price",+ }++ # They belong to a loan, so they are refused while the account is checking.+ rejected = await client.patch(+ f"/api/accounts/{account.id}", headers=auth_headers, json=terms+ )+ assert rejected.status_code == 400++ assert (await client.patch(+ f"/api/accounts/{account.id}", headers=auth_headers, json={"type": "loan"}+ )).status_code == 200+ saved = await client.patch(+ f"/api/accounts/{account.id}", headers=auth_headers, json=terms+ )+ assert saved.status_code == 200, saved.text+ assert saved.json()["loan_term_months"] == 120++ schedule = await client.get(f"/api/accounts/{account.id}/loan-schedule", headers=auth_headers)+ assert schedule.status_code == 200, schedule.text+ assert schedule.json()["configured"] is True+ assert len(schedule.json()["installments"]) == 120+++async def test_a_connected_loan_opens_the_period_on_a_signed_balance(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ """The provider snapshot stores a loan's debt positive, but the summary's+ opening balance seeds the running-balance walk, which is signed. A card+ returns 0.0 there, so a loan is the first connected liability to reach it:+ left unsigned, the projected balance read as money held."""+ from datetime import datetime, timezone++ from app.models.account import Account+ from app.models.bank_connection import BankConnection++ connection = BankConnection(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ provider="enable_banking",+ external_id=f"ext-{uuid.uuid4().hex[:8]}",+ institution_name="Lender",+ credentials={"token": "fake"},+ status="active",+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(connection)+ await session.flush()+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ connection_id=connection.id,+ external_id="acc-signed-1",+ name="Lender account",type="checking",balance=-1000,currency="EUR",@@ -233,12 +412,15 @@ async def test_a_bank_connected_account_cannot_become_a_loan(session.add(account)await session.commit()- response = await client.patch(+ retyped = await client.patch(f"/api/accounts/{account.id}", headers=auth_headers, json={"type": "loan"})+ assert retyped.status_code == 200, retyped.text- assert response.status_code == 400- assert "cannot be loans" in response.json()["detail"]+ summary = await client.get(f"/api/accounts/{account.id}/summary", headers=auth_headers)+ assert summary.status_code == 200, summary.text+ assert summary.json()["current_balance"] == -1000+ assert summary.json()["opening_balance"] == -1000@pytest.mark.asynciodiff --git a/backend/tests/test_mortgage_payments_api.py b/backend/tests/test_mortgage_payments_api.pyindex c36af588..9a33977b 100644--- a/backend/tests/test_mortgage_payments_api.py+++ b/backend/tests/test_mortgage_payments_api.py@@ -654,6 +654,55 @@ async def test_bank_connected_loan_keeps_split_without_posting_principal(assert entries == []+async def test_a_connected_loan_with_breakdowns_cannot_be_retyped(+ client: AsyncClient,+ auth_headers,+ session: AsyncSession,+ test_user: User,+ test_workspace: Workspace,+):+ """A connected account skips the history check that stops a manual one, so+ the breakdown guard is the only thing left holding the type in place."""+ from datetime import datetime, timezone++ payment, loan = await _make_payment_and_loan(+ session, test_user, test_workspace, snapshot_date=date(2026, 5, 31)+ )+ connection = BankConnection(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=test_workspace.id,+ provider="enable_banking",+ external_id=f"ext-{uuid.uuid4().hex[:8]}",+ institution_name="Lender",+ credentials={"token": "fake"},+ status="active",+ last_sync_at=datetime.now(timezone.utc),+ created_at=datetime.now(timezone.utc),+ )+ session.add(connection)+ await session.flush()+ loan.connection_id = connection.id+ await session.commit()++ await _post_breakdown(client, auth_headers, payment, loan)++ retyped = await client.patch(+ f"/api/accounts/{loan.id}", headers=auth_headers, json={"type": "checking"}+ )+ assert retyped.status_code == 400+ assert "mortgage payment breakdowns" in retyped.json()["detail"]++ removed = await client.delete(f"/api/mortgage-payments/{payment.id}", headers=auth_headers)+ assert removed.status_code == 204+ assert (+ await client.patch(+ f"/api/accounts/{loan.id}", headers=auth_headers, json={"type": "checking"}+ )+ ).status_code == 200++@pytest.mark.asyncioasync def test_loan_with_breakdowns_cannot_be_deleted_or_retyped(client: AsyncClient,diff --git a/backend/tests/test_reconciliation_rules.py b/backend/tests/test_reconciliation_rules.pyindex 49fc672b..49a82516 100644--- a/backend/tests/test_reconciliation_rules.py+++ b/backend/tests/test_reconciliation_rules.py@@ -816,6 +816,10 @@ class TestConditionValidation:def test_something_that_is_not_an_account_is_refused(self):assert self.refused({"accounts": {"in": ["the checking one"]}}) == "bad_accounts"+ # -- account types ------------------------------------------------------+ def test_loan_is_an_account_type(self):+ assert self.check({"account_types": ["loan"]}) == {"account_types": ["loan"]}+def test_an_empty_account_list_is_refused_rather_than_ignored(self):"""An empty list reads as "no accounts", which would silentlydisable the rule. Leaving the condition out is how you say "any"."""diff --git a/frontend/src/lib/account-type-config.ts b/frontend/src/lib/account-type-config.tsindex a93d754f..ae0a06ba 100644--- a/frontend/src/lib/account-type-config.ts+++ b/frontend/src/lib/account-type-config.ts@@ -1,10 +1,11 @@import type { ElementType } from 'react'import { Building2, PiggyBank, CreditCard, TrendingUp, Wallet, Landmark } from 'lucide-react'+import type { AccountType } from '@/types'// Account-type → icon/color, the fallback shown when an account has no bank// logo (manual accounts, and connected accounts whose provider exposes none).export const ACCOUNT_TYPE_CONFIG: Record<- string,+ AccountType,{ icon: ElementType; color: string; bg: string; label: string }> = {checking: { icon: Building2, color: 'text-indigo-600', bg: 'bg-indigo-100', label: 'accounts.typeChecking' },@@ -16,5 +17,5 @@ export const ACCOUNT_TYPE_CONFIG: Record<}export function getAccountTypeConfig(type: string) {- return ACCOUNT_TYPE_CONFIG[type] ?? ACCOUNT_TYPE_CONFIG['checking']+ return ACCOUNT_TYPE_CONFIG[type as AccountType] ?? ACCOUNT_TYPE_CONFIG.checking}diff --git a/frontend/src/pages/accounts.test.tsx b/frontend/src/pages/accounts.test.tsxindex 6fc45a44..3c88c4e0 100644--- a/frontend/src/pages/accounts.test.tsx+++ b/frontend/src/pages/accounts.test.tsx@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import { screen } from '@testing-library/react'-import AccountsPage from '@/pages/accounts'+import AccountsPage, { AccountDialog } from '@/pages/accounts'import { renderWithProviders, t } from '@/test/utils'import type { Account, BankConnection } from '@/types'@@ -13,6 +13,7 @@ const api = vi.hoisted(() => ({vi.mock('@/lib/api', () => ({accounts: { list: api.accountsList },+ assets: { list: vi.fn().mockResolvedValue([]) },connections: {list: api.connectionsList,getProviders: vi.fn().mockResolvedValue([]),@@ -144,3 +145,24 @@ describe('AccountsPage connection row actions', () => {expect(api.sync).toHaveBeenCalledWith('conn-err')})})++describe('AccountDialog account types', () => {+ it.each([+ { kind: 'manual', connectionId: null },+ { kind: 'bank-connected', connectionId: 'conn-1' },+ ])('saves Loan when editing an existing $kind checking account', async ({ connectionId }) => {+ const account = { ...makeAccount('conn-1'), connection_id: connectionId }+ const onSave = vi.fn()+ const { user } = renderWithProviders(+ <AccountDialog open account={account} onClose={vi.fn()} onSave={onSave} loading={false} />,+ )++ expect(screen.getByRole('heading', { name: t('accounts.editAccount') })).toBeInTheDocument()+ const [accountType] = screen.getAllByRole('combobox')+ expect(accountType).toHaveValue('checking')+ await user.selectOptions(accountType, 'loan')+ await user.click(screen.getByRole('button', { name: t('common.save') }))++ expect(onSave).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ type: 'loan' }))+ })+})diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsxindex 8b648512..490a58f3 100644--- a/frontend/src/pages/accounts.tsx+++ b/frontend/src/pages/accounts.tsx@@ -898,8 +898,7 @@ export function AccountDialog({value={type}onChange={(e) => setType(e.target.value)}>- {/* A bank-connected account cannot be a loan yet. */}- {ACCOUNT_TYPE_OPTIONS.filter((o) => o.value !== 'loan').map((o) => (+ {ACCOUNT_TYPE_OPTIONS.map((o) => (<option key={o.value} value={o.value}>{t(o.labelKey)}</option>))}</select>diff --git a/frontend/src/pages/import.tsx b/frontend/src/pages/import.tsxindex cbb02e81..7ca31222 100644--- a/frontend/src/pages/import.tsx+++ b/frontend/src/pages/import.tsx@@ -9,7 +9,12 @@ import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import { Label } from '@/components/ui/label'-import type { ImportPreviewTransaction, ImportReviewTransaction, FailedRow } from '@/types'+import type {+ AccountType,+ ImportPreviewTransaction,+ ImportReviewTransaction,+ FailedRow,+} from '@/types'import { Upload, FileText, X, CheckCircle2, AlertCircle, Settings2, Download } from 'lucide-react'import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog'import { PageHeader } from '@/components/page-header'@@ -20,11 +25,13 @@ import { ImportHistory } from '@/components/import-history'import { useAuth } from '@/contexts/auth-context'import { useWorkspace } from '@/contexts/workspace-context'-const TYPE_LABELS: Record<string, string> = {+const TYPE_LABELS: Record<AccountType, string> = {checking: 'accounts.typeChecking',savings: 'accounts.typeSavings',credit_card: 'accounts.typeCreditCard',+ loan: 'accounts.typeLoan',investment: 'accounts.typeInvestment',+ wallet: 'accounts.typeWallet',}// Securo fields a CSV column can be mapped to, in display order.@@ -387,7 +394,7 @@ function TransactionImportPanel() {><option value="">{t('import.selectAccount')}</option>{sortAccountsByDisplayName(accountsList ?? []).map((acc) => (- <option key={acc.id} value={acc.id}>{getAccountName(acc)} ({t(TYPE_LABELS[acc.type] || acc.type)})</option>+ <option key={acc.id} value={acc.id}>{getAccountName(acc)} ({t(TYPE_LABELS[acc.type as AccountType] || acc.type)})</option>))}</select>{!selectedAccount && (diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex f1a0729d..7d829b7d 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -163,6 +163,8 @@ export interface SyncResult extends BankConnection {sync_outcome: 'refreshed' | 'rate_limited'}+export type AccountType = 'checking' | 'savings' | 'credit_card' | 'loan' | 'investment' | 'wallet'+export interface Account {id: stringuser_id: string@@ -1728,7 +1730,7 @@ export interface ReconciliationConditions {/** Only pairs where one of the two legs sits on an account of this* kind. Either leg is enough: a rule that exists to be careful about* credit cards has to fire whichever end the card is on. */- account_types?: ('checking' | 'savings' | 'credit_card' | 'investment' | 'wallet')[]+ account_types?: AccountType[]/** One side's statement text has to name the other side's account. The* signal that tells two same-day transfers of the same amount apart,* when one line reads "To FORTUNEO ACCOUNT" and the other does not. */