Skip to content

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

fix: preserve manual account opening balances (#14) (#377)

Albert Dolkunb41d66127609
diff --git a/backend/app/services/account_service.py b/backend/app/services/account_service.py
index face8210..187fd542 100644
--- a/backend/app/services/account_service.py
+++ b/backend/app/services/account_service.py
@@ -36,6 +36,12 @@ def _simplefin_to_internal_balance(provider: str, account_type: str, balance: De
return balance
+def _opening_balance_values(account_type: str, balance: Decimal) -> tuple[Decimal, str]:
+ amount = abs(balance)
+ is_credit = (balance > 0) == (account_type != "credit_card")
+ return amount, "credit" if is_credit else "debit"
+
+
async def get_accounts(session: AsyncSession, workspace_id: uuid.UUID, include_closed: bool = False) -> list[dict]:
# Subquery: compute current_balance per account from transactions in one pass
# Use amount_primary only when tx currency differs from account currency
@@ -242,16 +248,14 @@ async def create_account(
session.add(account)
await session.flush() # get account.id without committing
- if data.balance > Decimal("0.00"):
- # Credit cards: opening balance represents debt → record as debit.
- # Other accounts: opening balance represents assets → record as credit.
- opening_type = "debit" if data.type == "credit_card" else "credit"
+ if data.balance != Decimal("0.00"):
+ amount, opening_type = _opening_balance_values(data.type, data.balance)
opening_tx = Transaction(
user_id=user_id,
workspace_id=workspace_id,
account_id=account.id,
description="Saldo inicial",
- amount=data.balance,
+ amount=amount,
currency=data.currency,
date=data.balance_date or _Date.today(),
type=opening_type,
@@ -363,11 +367,11 @@ async def update_account(
)
)
opening_tx = existing_opening.scalar_one_or_none()
- opening_type = "debit" if account.type == "credit_card" else "credit"
- if new_balance > Decimal("0.00"):
+ if new_balance != Decimal("0.00"):
+ amount, opening_type = _opening_balance_values(account.type, new_balance)
if opening_tx:
- opening_tx.amount = new_balance
+ opening_tx.amount = amount
opening_tx.type = opening_type
if balance_date:
opening_tx.date = balance_date
@@ -378,7 +382,7 @@ async def update_account(
workspace_id=account.workspace_id,
account_id=account_id,
description="Saldo inicial",
- amount=new_balance,
+ amount=amount,
currency=account.currency,
date=balance_date or _Date.today(),
type=opening_type,
@@ -388,6 +392,17 @@ async def update_account(
session.add(opening_tx)
elif opening_tx:
await session.delete(opening_tx)
+ elif balance_date:
+ existing_opening = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account_id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening_tx = existing_opening.scalar_one_or_none()
+ if opening_tx:
+ opening_tx.date = balance_date
+ apply_effective_date(opening_tx, account)
if cycle_fields_changed:
await _recompute_effective_dates(session, account)
diff --git a/backend/tests/test_account_service.py b/backend/tests/test_account_service.py
index 46589142..8672fabd 100644
--- a/backend/tests/test_account_service.py
+++ b/backend/tests/test_account_service.py
@@ -117,6 +117,27 @@ async def test_create_account_with_balance(session: AsyncSession, test_user, tes
assert opening.type == "credit"
+async def test_create_account_with_negative_balance(session: AsyncSession, test_user, test_workspace):
+ """Negative manual opening balance is recorded as a debit."""
+ data = AccountCreate(name="Overdrawn", type="checking", balance=Decimal("-250.00"), currency="BRL")
+ account = await create_account(session, test_workspace.id, test_user.id, data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.amount == Decimal("250.00")
+ assert opening.type == "debit"
+
+ [serialized] = await get_accounts(session, test_workspace.id)
+ assert serialized["current_balance"] == -250.0
+
+
@pytest.mark.asyncio
async def test_create_credit_card_account_opening_is_debit(session: AsyncSession, test_user, test_workspace):
"""Credit card opening balance is recorded as debit (represents debt)."""
@@ -208,6 +229,26 @@ async def test_update_account_balance_creates_opening(session: AsyncSession, tes
assert opening.type == "credit"
+async def test_update_account_balance_creates_negative_opening(session: AsyncSession, test_user, test_workspace):
+ """Updating a manual account to a negative balance creates a debit opening."""
+ account = await _make_account(session, test_user.id, "No Balance", balance="0.00")
+ data = AccountUpdate(balance=Decimal("-500.00"))
+ updated = await update_account(session, account.id, test_workspace.id, data)
+
+ assert updated is not None
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.amount == Decimal("500.00")
+ assert opening.type == "debit"
+
+
@pytest.mark.asyncio
async def test_update_account_balance_updates_existing_opening(session: AsyncSession, test_user, test_workspace):
"""Updating balance when opening_balance exists updates it."""
@@ -269,6 +310,28 @@ async def test_update_account_balance_with_date(session: AsyncSession, test_user
assert opening.amount == Decimal("1500.00")
+async def test_update_account_balance_date_only_updates_opening(session: AsyncSession, test_user, test_workspace):
+ """Updating only balance_date moves the existing opening transaction."""
+ data = AccountCreate(name="Date Only Test", type="checking", balance=Decimal("1000.00"), currency="BRL")
+ account = await create_account(session, test_workspace.id, test_user.id, data)
+
+ new_date = date(2025, 7, 20)
+ update_data = AccountUpdate(balance_date=new_date)
+ await update_account(session, account.id, test_workspace.id, update_data)
+
+ from sqlalchemy import select
+ result = await session.execute(
+ select(Transaction).where(
+ Transaction.account_id == account.id,
+ Transaction.source == "opening_balance",
+ )
+ )
+ opening = result.scalar_one()
+ assert opening.date == new_date
+ assert opening.amount == Decimal("1000.00")
+
+
@pytest.mark.asyncio
async def test_update_bank_connected_raises(session: AsyncSession, test_user, test_workspace, test_connection):
"""Updating a bank-connected account raises ValueError."""