Skip to content

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

fix: require account on recurring transactions (#64)

Tássio Noronha45c7bb2341e5
diff --git a/backend/app/api/recurring_transactions.py b/backend/app/api/recurring_transactions.py
index 83a1e008..663ffb0d 100644
--- a/backend/app/api/recurring_transactions.py
+++ b/backend/app/api/recurring_transactions.py
@@ -30,7 +30,10 @@ async def create_recurring_transaction(
session: AsyncSession = Depends(get_async_session),
user: User = Depends(current_active_user),
):
- return await recurring_transaction_service.create_recurring_transaction(session, user.id, data)
+ try:
+ return await recurring_transaction_service.create_recurring_transaction(session, user.id, data)
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
@router.patch("/{recurring_id}", response_model=RecurringTransactionRead)
@@ -40,9 +43,12 @@ async def update_recurring_transaction(
session: AsyncSession = Depends(get_async_session),
user: User = Depends(current_active_user),
):
- recurring = await recurring_transaction_service.update_recurring_transaction(
- session, recurring_id, user.id, data
- )
+ try:
+ recurring = await recurring_transaction_service.update_recurring_transaction(
+ session, recurring_id, user.id, data
+ )
+ except ValueError as e:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
if not recurring:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Recurring transaction not found")
return recurring
diff --git a/backend/app/schemas/recurring_transaction.py b/backend/app/schemas/recurring_transaction.py
index e7e2e674..c79726c8 100644
--- a/backend/app/schemas/recurring_transaction.py
+++ b/backend/app/schemas/recurring_transaction.py
@@ -15,7 +15,7 @@ class RecurringTransactionCreate(BaseModel):
day_of_month: Optional[int] = None
start_date: _Date
end_date: Optional[_Date] = None
- account_id: Optional[uuid.UUID] = None
+ account_id: uuid.UUID
category_id: Optional[uuid.UUID] = None
skip_first: bool = False # Set true when first occurrence already created as a transaction
diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.py
index 80c586c3..2d9ae672 100644
--- a/backend/app/services/recurring_transaction_service.py
+++ b/backend/app/services/recurring_transaction_service.py
@@ -3,15 +3,36 @@ import uuid
from datetime import date, timedelta
from typing import Optional
-from sqlalchemy import select
+from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.models.account import Account
+from app.models.bank_connection import BankConnection
from app.models.recurring_transaction import RecurringTransaction
from app.models.transaction import Transaction
from app.schemas.recurring_transaction import RecurringTransactionCreate, RecurringTransactionUpdate
from app.services.fx_rate_service import stamp_primary_amount
+async def _verify_account_owned(
+ session: AsyncSession, user_id: uuid.UUID, account_id: uuid.UUID
+) -> None:
+ """Raise ValueError if the account does not belong to the user (directly or via a bank connection)."""
+ result = await session.execute(
+ select(Account)
+ .outerjoin(BankConnection)
+ .where(
+ Account.id == account_id,
+ or_(
+ Account.user_id == user_id,
+ BankConnection.user_id == user_id,
+ ),
+ )
+ )
+ if result.scalar_one_or_none() is None:
+ raise ValueError("Account not found")
+
+
async def get_recurring_transactions(
session: AsyncSession, user_id: uuid.UUID
) -> list[RecurringTransaction]:
@@ -36,6 +57,7 @@ async def get_recurring_transaction(
async def create_recurring_transaction(
session: AsyncSession, user_id: uuid.UUID, data: RecurringTransactionCreate
) -> RecurringTransaction:
+ await _verify_account_owned(session, user_id, data.account_id)
next_occ = data.start_date
if data.skip_first:
next_occ = _advance_date(data.start_date, data.frequency)
@@ -71,7 +93,18 @@ async def update_recurring_transaction(
if not recurring:
return None
- for key, value in data.model_dump(exclude_unset=True).items():
+ update_data = data.model_dump(exclude_unset=True)
+
+ # A recurring transaction must always have an account — reject an explicit
+ # null, and verify ownership of any new account_id.
+ if "account_id" in update_data:
+ new_account_id = update_data["account_id"]
+ if new_account_id is None:
+ raise ValueError("account_id is required")
+ if new_account_id != recurring.account_id:
+ await _verify_account_owned(session, user_id, new_account_id)
+
+ for key, value in update_data.items():
setattr(recurring, key, value)
await session.commit()
@@ -162,6 +195,11 @@ async def generate_pending(
count = 0
for recurring in recurring_list:
+ # Legacy rows may exist with a null account_id from before account_id
+ # was required. Skip them rather than crashing on Transaction's NOT NULL
+ # constraint — the user should edit the recurring to fix it.
+ if recurring.account_id is None:
+ continue
# Generate transactions until next_occurrence is past the cutoff
while recurring.next_occurrence <= cutoff:
# Check if past end_date
diff --git a/backend/tests/test_api_extended.py b/backend/tests/test_api_extended.py
index 9fbc23f3..9d9b9e3a 100644
--- a/backend/tests/test_api_extended.py
+++ b/backend/tests/test_api_extended.py
@@ -468,7 +468,7 @@ async def test_reconnect_token_no_item_id(
@pytest.mark.asyncio
async def test_dashboard_projected_transactions(
- client: AsyncClient, auth_headers, test_categories,
+ client: AsyncClient, auth_headers, test_categories, test_account,
):
"""GET /api/dashboard/projected-transactions returns projections."""
# Create a recurring transaction
@@ -488,6 +488,7 @@ async def test_dashboard_projected_transactions(
"frequency": "monthly",
"start_date": next_month.isoformat(),
"category_id": str(test_categories[0].id),
+ "account_id": str(test_account.id),
},
)
diff --git a/backend/tests/test_dashboard_api.py b/backend/tests/test_dashboard_api.py
index afbb481f..23ba3cb7 100644
--- a/backend/tests/test_dashboard_api.py
+++ b/backend/tests/test_dashboard_api.py
@@ -97,7 +97,7 @@ async def test_summary_numeric_fields(client, auth_headers, test_transactions):
@pytest.mark.asyncio
async def test_dashboard_virtual_recurring_projection(
- client, auth_headers, test_categories
+ client, auth_headers, test_categories, test_account
):
"""Dashboard includes recurring projections via virtual computation — no DB writes."""
# Use a future month so projections always apply regardless of today's date.
@@ -115,6 +115,7 @@ async def test_dashboard_virtual_recurring_projection(
"frequency": "weekly",
"start_date": next_month,
"category_id": str(test_categories[0].id),
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -164,7 +165,7 @@ async def test_dashboard_virtual_recurring_projection(
@pytest.mark.asyncio
async def test_dashboard_no_duplicates_on_concurrent_calls(
- client, auth_headers, test_categories
+ client, auth_headers, test_categories, test_account
):
"""Calling summary and spending concurrently does NOT create duplicates."""
import asyncio
@@ -182,6 +183,7 @@ async def test_dashboard_no_duplicates_on_concurrent_calls(
"frequency": "monthly",
"start_date": next_month,
"category_id": str(test_categories[1].id),
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -225,7 +227,7 @@ async def test_dashboard_no_duplicates_on_concurrent_calls(
@pytest.mark.asyncio
async def test_recurring_projection_respects_end_date(
- client, auth_headers, test_categories
+ client, auth_headers, test_categories, test_account
):
"""Recurring with end_date stops projecting after that date."""
next_month = _next_month_str()
@@ -242,6 +244,7 @@ async def test_recurring_projection_respects_end_date(
"start_date": next_month,
"end_date": end_date,
"category_id": str(test_categories[0].id),
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -365,6 +368,7 @@ async def test_future_month_balance_includes_recurring_projections(
headers=auth_headers,
)
assert acc_resp.status_code == 201
+ acc_id = acc_resp.json()["id"]
# Create a monthly recurring expense of 500 starting next month
rec_resp = await client.post(
@@ -377,6 +381,7 @@ async def test_future_month_balance_includes_recurring_projections(
"frequency": "monthly",
"start_date": next_month,
"category_id": str(test_categories[1].id),
+ "account_id": acc_id,
},
headers=auth_headers,
)
diff --git a/backend/tests/test_recurring_api.py b/backend/tests/test_recurring_api.py
index 1d055898..32d28146 100644
--- a/backend/tests/test_recurring_api.py
+++ b/backend/tests/test_recurring_api.py
@@ -5,7 +5,7 @@ import pytest
@pytest.mark.asyncio
-async def test_create_recurring_transaction(client, auth_headers, test_categories):
+async def test_create_recurring_transaction(client, auth_headers, test_categories, test_account):
"""Creating a recurring transaction sets next_occurrence to start_date."""
response = await client.post(
"/api/recurring-transactions",
@@ -17,6 +17,7 @@ async def test_create_recurring_transaction(client, auth_headers, test_categorie
"frequency": "monthly",
"start_date": "2026-03-01",
"category_id": str(test_categories[0].id),
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -30,7 +31,7 @@ async def test_create_recurring_transaction(client, auth_headers, test_categorie
@pytest.mark.asyncio
-async def test_create_recurring_with_skip_first(client, auth_headers, test_categories):
+async def test_create_recurring_with_skip_first(client, auth_headers, test_categories, test_account):
"""skip_first=true advances next_occurrence by one frequency period."""
response = await client.post(
"/api/recurring-transactions",
@@ -43,6 +44,7 @@ async def test_create_recurring_with_skip_first(client, auth_headers, test_categ
"start_date": "2026-02-25",
"skip_first": True,
"category_id": str(test_categories[0].id),
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -55,7 +57,7 @@ async def test_create_recurring_with_skip_first(client, auth_headers, test_categ
@pytest.mark.asyncio
-async def test_create_recurring_skip_first_monthly(client, auth_headers):
+async def test_create_recurring_skip_first_monthly(client, auth_headers, test_account):
"""skip_first with monthly frequency advances by one month."""
response = await client.post(
"/api/recurring-transactions",
@@ -67,6 +69,7 @@ async def test_create_recurring_skip_first_monthly(client, auth_headers):
"frequency": "monthly",
"start_date": "2026-01-15",
"skip_first": True,
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -185,7 +188,7 @@ async def test_generate_no_duplicate_with_skip_first(client, auth_headers, test_
@pytest.mark.asyncio
-async def test_list_recurring_transactions(client, auth_headers):
+async def test_list_recurring_transactions(client, auth_headers, test_account):
"""List returns all recurring transactions for the user."""
# Create two
for desc in ["Sub A", "Sub B"]:
@@ -197,6 +200,7 @@ async def test_list_recurring_transactions(client, auth_headers):
"type": "debit",
"frequency": "monthly",
"start_date": "2026-03-01",
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -209,7 +213,7 @@ async def test_list_recurring_transactions(client, auth_headers):
@pytest.mark.asyncio
-async def test_delete_recurring_transaction(client, auth_headers):
+async def test_delete_recurring_transaction(client, auth_headers, test_account):
"""Delete removes a recurring transaction."""
create_resp = await client.post(
"/api/recurring-transactions",
@@ -219,6 +223,7 @@ async def test_delete_recurring_transaction(client, auth_headers):
"type": "debit",
"frequency": "weekly",
"start_date": "2026-03-01",
+ "account_id": str(test_account.id),
},
headers=auth_headers,
)
@@ -229,3 +234,59 @@ async def test_delete_recurring_transaction(client, auth_headers):
headers=auth_headers,
)
assert del_resp.status_code == 204
+
+
+# ---------------------------------------------------------------------------
+# Regression tests for #64 — account_id is required
+# ---------------------------------------------------------------------------
+
+
+async def test_create_recurring_without_account_rejected(client, auth_headers):
+ """Omitting account_id should return a validation error, not a 500 later."""
+ response = await client.post(
+ "/api/recurring-transactions",
+ json={
+ "description": "No account",
+ "amount": 10.00,
+ "type": "debit",
+ "frequency": "monthly",
+ "start_date": "2026-03-01",
+ },
+ headers=auth_headers,
+ )
+ assert response.status_code == 422
+
+
+async def test_generate_pending_skips_legacy_null_account(
+ session, test_user, test_account
+):
+ """Legacy rows with account_id=None (predating the schema fix) must not crash
+ generate_pending — they are skipped instead."""
+ import uuid as _uuid
+ from datetime import date as _date
+ from decimal import Decimal as _Decimal
+ from app.models.recurring_transaction import RecurringTransaction
+ from app.services.recurring_transaction_service import generate_pending
+
+ # Bypass the schema by creating the row directly.
+ legacy = RecurringTransaction(
+ id=_uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=None,
+ description="Legacy",
+ amount=_Decimal("10"),
+ currency="BRL",
+ type="debit",
+ frequency="monthly",
+ start_date=_date(2026, 1, 1),
+ next_occurrence=_date(2026, 1, 1),
+ is_active=True,
+ )
+ session.add(legacy)
+ await session.commit()
+
+ # Should not raise; should report 0 generated for the legacy row.
+ count = await generate_pending(session, test_user.id, up_to=_date(2026, 4, 1))
+ assert count == 0
diff --git a/frontend/src/pages/recurring.tsx b/frontend/src/pages/recurring.tsx
index 61c72f62..6f652566 100644
--- a/frontend/src/pages/recurring.tsx
+++ b/frontend/src/pages/recurring.tsx
@@ -277,7 +277,7 @@ function RecurringForm({
const [startDate, setStartDate] = useState(recurring?.start_date ?? new Date().toISOString().split('T')[0])
const [endDate, setEndDate] = useState(recurring?.end_date ?? '')
const [categoryId, setCategoryId] = useState(recurring?.category_id ?? '')
- const [accountId, setAccountId] = useState(recurring?.account_id ?? '')
+ const [accountId, setAccountId] = useState(recurring?.account_id ?? accounts[0]?.id ?? '')
const [isActive, setIsActive] = useState(recurring?.is_active ?? true)
const selectClass = 'w-full border border-border rounded-lg px-3 py-2 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'
@@ -365,8 +365,13 @@ function RecurringForm({
</div>
<div className="space-y-2">
<Label>{t('recurring.account')}</Label>
- <select className={selectClass} value={accountId} onChange={(e) => setAccountId(e.target.value)}>
- <option value="">{t('recurring.noAccount')}</option>
+ <select
+ className={selectClass}
+ value={accountId}
+ onChange={(e) => setAccountId(e.target.value)}
+ required
+ >
+ {!accountId && <option value="" disabled>{t('recurring.noAccount')}</option>}
{accounts.map((acc) => (
<option key={acc.id} value={acc.id}>{acc.name}</option>
))}