Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

fix(accounts): keep the opening balance date when editing an account (#1226)

Shayn Hornik0a2e371585be
diff --git a/backend/app/schemas/account.py b/backend/app/schemas/account.py
index 5ea2d0d0..d46e949a 100644
--- a/backend/app/schemas/account.py
+++ b/backend/app/schemas/account.py
@@ -61,6 +61,8 @@ class AccountRead(AccountBase):
institution_logo_url: Optional[str] = None
current_balance: float = 0.0
previous_balance: Optional[float] = None
+ # Date of the opening-balance transaction; null when there is none.
+ balance_date: Optional[date] = None
balance_primary: Optional[float] = None
# True when the account is in a foreign currency and no real FX rate is
# available, so balance_primary is left unset rather than a 1:1 guess.
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index 5a94779c..2bc474a2 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -154,6 +154,16 @@ def _accounts_with_balances_query(
func.coalesce(balance_sq.c.current_balance, 0).label("current_balance"),
func.coalesce(prev_balance_sq.c.previous_balance, 0).label("previous_balance"),
func.coalesce(future_charges_sq.c.future_charges, 0).label("future_charges"),
+ # The opening balance's date, so the edit form can show it and
+ # leave it alone (issue #1204).
+ select(func.min(Transaction.date))
+ .where(
+ Transaction.account_id == Account.id,
+ Transaction.source == "opening_balance",
+ )
+ .correlate(Account)
+ .scalar_subquery()
+ .label("balance_date"),
)
.outerjoin(BankConnection)
.outerjoin(balance_sq, Account.id == balance_sq.c.account_id)
@@ -176,9 +186,21 @@ async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_c
result = await session.execute(query)
return [
serialize_account(
- acc, current_balance, previous_balance, connection, future_charges=future_charges
+ acc,
+ current_balance,
+ previous_balance,
+ connection,
+ future_charges=future_charges,
+ balance_date=balance_date,
)
- for acc, connection, current_balance, previous_balance, future_charges in result.all()
+ for (
+ acc,
+ connection,
+ current_balance,
+ previous_balance,
+ future_charges,
+ balance_date,
+ ) in result.all()
]
@@ -192,9 +214,14 @@ async def get_account_with_balances(
row = (await session.execute(query)).first()
if row is None:
return None
- acc, connection, current_balance, previous_balance, future_charges = row
+ acc, connection, current_balance, previous_balance, future_charges, balance_date = row
return serialize_account(
- acc, current_balance, previous_balance, connection, future_charges=future_charges
+ acc,
+ current_balance,
+ previous_balance,
+ connection,
+ future_charges=future_charges,
+ balance_date=balance_date,
)
@@ -227,6 +254,7 @@ def serialize_account(
connection: Optional[BankConnection] = None,
*,
future_charges: Optional[Decimal] = None,
+ balance_date: Optional[_Date] = None,
) -> dict:
# Connected CC: provider stores positive for debt → negate.
# Manual accounts: transaction math already gives correct sign.
@@ -261,6 +289,7 @@ def serialize_account(
"shared_balance_group": acc.shared_balance_group,
"institution_name": institution_name,
"institution_logo_url": institution_logo_url,
+ "balance_date": balance_date,
"available_credit": None,
"next_close_date": None,
"next_due_date": None,
diff --git a/backend/tests/test_accounts_api.py b/backend/tests/test_accounts_api.py
index baeb631d..85dc4b99 100644
--- a/backend/tests/test_accounts_api.py
+++ b/backend/tests/test_accounts_api.py
@@ -914,3 +914,51 @@ async def test_available_credit_of_connected_card_ignores_future_rows(
detail = (await client.get(f"/api/accounts/{card.id}", headers=auth_headers)).json()
assert detail["available_credit"] == pytest.approx(700.0)
+
+
+async def test_account_reports_its_opening_balance_date(client: AsyncClient, auth_headers):
+ """Issue #1204: the payload carries the opening balance's date, and an
+ edit that leaves `balance_date` out keeps it."""
+ created = await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={
+ "name": "Checking",
+ "type": "checking",
+ "balance": "1000.00",
+ "balance_date": "2026-08-01",
+ "currency": "USD",
+ },
+ )
+ assert created.status_code == 201
+ account_id = created.json()["id"]
+
+ listed = await client.get("/api/accounts", headers=auth_headers)
+ assert [a["balance_date"] for a in listed.json()] == ["2026-08-01"]
+
+ renamed = await client.patch(
+ f"/api/accounts/{account_id}",
+ headers=auth_headers,
+ json={"name": "Main checking", "balance": "1000.00", "currency": "USD"},
+ )
+ assert renamed.status_code == 200
+ assert renamed.json()["balance_date"] == "2026-08-01"
+
+ moved = await client.patch(
+ f"/api/accounts/{account_id}", headers=auth_headers, json={"balance_date": "2026-07-15"}
+ )
+ assert moved.json()["balance_date"] == "2026-07-15"
+
+
+async def test_account_without_opening_balance_has_no_balance_date(
+ client: AsyncClient, auth_headers
+):
+ created = await client.post(
+ "/api/accounts",
+ headers=auth_headers,
+ json={"name": "Empty", "type": "checking", "balance": "0", "currency": "USD"},
+ )
+ fetched = await client.get(f"/api/accounts/{created.json()['id']}", headers=auth_headers)
+ assert fetched.json()["balance_date"] is None
diff --git a/frontend/src/pages/accounts-dialog-balance-date.test.tsx b/frontend/src/pages/accounts-dialog-balance-date.test.tsx
new file mode 100644
index 00000000..fdbfc5c9
--- /dev/null
+++ b/frontend/src/pages/accounts-dialog-balance-date.test.tsx
@@ -0,0 +1,70 @@
+import { fireEvent, screen } from '@testing-library/react'
+import { expect, it, vi } from 'vitest'
+import { renderWithProviders, t } from '@/test/utils'
+import type { Account } from '@/types'
+
+vi.mock('@/contexts/auth-context', () => ({ useAuth: () => ({ user: null }) }))
+vi.mock('@/lib/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/api')>()),
+ currencies: { list: vi.fn().mockResolvedValue([]) },
+}))
+// A plain input stands in for the calendar popover.
+vi.mock('@/components/ui/date-picker-input', () => ({
+ DatePickerInput: ({ value, onChange }: { value: string; onChange: (v: string) => void }) => (
+ <input aria-label="balance date" value={value} onChange={(e) => onChange(e.target.value)} />
+ ),
+}))
+
+import { AccountDialog } from './accounts'
+
+const manual = {
+ id: 'acc-1',
+ connection_id: null,
+ name: 'Checking',
+ display_name: null,
+ type: 'checking',
+ balance: 1000,
+ currency: 'USD',
+ balance_date: '2026-08-01',
+ credit_limit: null,
+ statement_close_day: null,
+ payment_due_day: null,
+} as Account
+
+function renderDialog(account: Account | null) {
+ const onSave = vi.fn()
+ renderWithProviders(
+ <AccountDialog open onClose={vi.fn()} account={account} onSave={onSave} loading={false} />,
+ )
+ return onSave
+}
+
+it('opens with the opening balance date and keeps it on an unrelated edit (#1204)', () => {
+ const onSave = renderDialog(manual)
+
+ expect(screen.getByLabelText('balance date')).toHaveValue('2026-08-01')
+ fireEvent.change(screen.getAllByRole('textbox')[0], { target: { value: 'Main checking' } })
+ fireEvent.click(screen.getByRole('button', { name: t('common.save') }))
+
+ expect(onSave).toHaveBeenCalledTimes(1)
+ expect(onSave.mock.calls[0][0]).toMatchObject({ name: 'Main checking' })
+ expect(onSave.mock.calls[0][0]).not.toHaveProperty('balance_date')
+})
+
+it('sends the date when the user changes it', () => {
+ const onSave = renderDialog(manual)
+
+ fireEvent.change(screen.getByLabelText('balance date'), { target: { value: '2026-07-15' } })
+ fireEvent.click(screen.getByRole('button', { name: t('common.save') }))
+
+ expect(onSave.mock.calls[0][0]).toMatchObject({ balance_date: '2026-07-15' })
+})
+
+it('always sends the date for a new account', () => {
+ const onSave = renderDialog(null)
+
+ fireEvent.change(screen.getAllByRole('textbox')[0], { target: { value: 'Savings' } })
+ fireEvent.click(screen.getByRole('button', { name: t('common.save') }))
+
+ expect(onSave.mock.calls[0][0]).toHaveProperty('balance_date')
+})
diff --git a/frontend/src/pages/accounts.tsx b/frontend/src/pages/accounts.tsx
index 09a38fda..a704b642 100644
--- a/frontend/src/pages/accounts.tsx
+++ b/frontend/src/pages/accounts.tsx
@@ -695,7 +695,7 @@ export default function AccountsPage() {
)
}
-function AccountDialog({
+export function AccountDialog({
open,
onClose,
account,
@@ -737,7 +737,10 @@ function AccountDialog({
const [type, setType] = useState(account?.type ?? 'checking')
const [balance, setBalance] = useState(account?.balance?.toString() ?? '0')
const [currency, setCurrency] = useState(account?.currency ?? userCurrency)
- const [balanceDate, setBalanceDate] = useState(localDateString)
+ // The opening balance's own date (issue #1204); today for a new account
+ // or one without an opening balance.
+ const initialBalanceDate = () => account?.balance_date ?? localDateString()
+ const [balanceDate, setBalanceDate] = useState(initialBalanceDate)
const [creditLimit, setCreditLimit] = useState(account?.credit_limit?.toString() ?? '')
const [statementCloseDay, setStatementCloseDay] = useState(account?.statement_close_day?.toString() ?? '')
const [paymentDueDay, setPaymentDueDay] = useState(account?.payment_due_day?.toString() ?? '')
@@ -747,15 +750,19 @@ function AccountDialog({
// Send the link the select shows: a saved id that is no longer a listed
// property (it changed type) would otherwise be resent and rejected.
const securedAssetIsListed = !!securedAssetId && (!assetsList || properties.some((asset) => asset.id === securedAssetId))
- const [formSource, setFormSource] = useState<{ account: typeof account } | null>(null)
+ const [formSource, setFormSource] = useState<{
+ account: typeof account
+ balanceDate: string
+ } | null>(null)
if (!formSource || formSource.account !== account) {
- setFormSource({ account })
+ const date = initialBalanceDate()
+ setFormSource({ account, balanceDate: date })
setName(account?.name ?? '')
setDisplayName(account?.display_name ?? '')
setType(account?.type ?? 'checking')
setBalance(account?.balance?.toString() ?? '0')
setCurrency(account?.currency ?? userCurrency)
- setBalanceDate(localDateString())
+ setBalanceDate(date)
setCreditLimit(account?.credit_limit?.toString() ?? '')
setStatementCloseDay(account?.statement_close_day?.toString() ?? '')
setPaymentDueDay(account?.payment_due_day?.toString() ?? '')
@@ -780,8 +787,15 @@ function AccountDialog({
return Number.isFinite(n) && n >= 1 && n <= 31 ? n : null
}
const isConnected = !!account?.connection_id
+ // Editing: only move the opening balance when the date was changed.
+ const dateChanged = !account || balanceDate !== formSource?.balanceDate
onSave({
- ...(!isConnected && { name, balance: parseFloat(balance), balance_date: balanceDate, currency }),
+ ...(!isConnected && {
+ name,
+ balance: parseFloat(balance),
+ ...(dateChanged && { balance_date: balanceDate }),
+ currency,
+ }),
type,
...(type === 'loan' && { secured_asset_id: securedAssetIsListed ? securedAssetId : null }),
display_name: displayName.trim() || null,
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 3f9628a8..bbc6db21 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -182,6 +182,8 @@ export interface Account {
balance: number
current_balance: number
previous_balance: number | null
+ // Date of the opening-balance transaction; null when there is none.
+ balance_date?: string | null
balance_primary: number | null
// No real FX rate: balance_primary is unset and totals use the native amount.
fx_fallback?: boolean