Open-source personal finance manager. Self-hosted, privacy-first.
fix(recurring): let Generate Pending cover schedules with auto-generate off (#1168)
Shayn Hornik6ce55d920f50
diff --git a/backend/app/api/recurring_transactions.py b/backend/app/api/recurring_transactions.pyindex 9a61df33..0bf04d07 100644--- a/backend/app/api/recurring_transactions.py+++ b/backend/app/api/recurring_transactions.py@@ -77,5 +77,10 @@ async def generate_recurring_transactions(ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):- count = await recurring_transaction_service.generate_pending(session, ctx.user_id)+ # The button is an explicit request, so it also covers schedules whose+ # auto-generate toggle is off; the hourly task skips those. It is scoped+ # to the workspace this request was authorized to write to.+ count = await recurring_transaction_service.generate_pending(+ session, ctx.user_id, include_manual=True, workspace_id=ctx.workspace.id+ )return {"generated": count}diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.pyindex 406dca53..c2809cff 100644--- a/backend/app/services/recurring_transaction_service.py+++ b/backend/app/services/recurring_transaction_service.py@@ -3,7 +3,7 @@ import uuidfrom datetime import date, timedeltafrom typing import Optional-from sqlalchemy import and_, or_, select+from sqlalchemy import and_, or_, select, truefrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.app_clock import app_today, get_workspace_timezone, today_in@@ -265,12 +265,33 @@ def get_occurrences_in_range(async def generate_pending(- session: AsyncSession, user_id: uuid.UUID, up_to: Optional[date] = None+ session: AsyncSession,+ user_id: uuid.UUID,+ up_to: Optional[date] = None,+ include_manual: bool = False,+ workspace_id: Optional[uuid.UUID] = None,) -> int:"""Generate transactions for all pending recurring transactions up to a given date.If up_to is None, defaults to today. This allows the dashboard to pre-generatetransactions for future months when the user navigates ahead.++ Schedules with auto_generate off are left alone unless include_manual is+ set: the hourly task must never materialize them, while the Generate+ Pending button is the user asking for exactly that.++ workspace_id narrows the run to one workspace. The button passes the+ workspace it was authorized for, so a click there cannot write into+ another workspace the user merely belongs to; unattended runs leave it+ unset and cover all of them.Returns the count of transactions generated."""+ # Unattended runs only touch schedules that opted in to auto-generation.+ generation_filter = (+ true() if include_manual else RecurringTransaction.auto_generate == True+ )+ if workspace_id is not None:+ generation_filter = and_(+ generation_filter, RecurringTransaction.workspace_id == workspace_id+ )# A person's recurring rows may live in several workspaces, and each# workspace keeps its own calendar, so "today" is resolved per workspace.# The query is bounded by the latest of those days and the loop below@@ -283,7 +304,7 @@ async def generate_pending(.where(RecurringTransaction.user_id == user_id,RecurringTransaction.is_active == True,- RecurringTransaction.auto_generate == True,+ generation_filter,).distinct())@@ -301,7 +322,7 @@ async def generate_pending(.where(RecurringTransaction.user_id == user_id,RecurringTransaction.is_active == True,- RecurringTransaction.auto_generate == True,+ generation_filter,or_(and_(RecurringTransaction.weekend_adjustment == "previous_friday",diff --git a/backend/tests/test_recurring_api.py b/backend/tests/test_recurring_api.pyindex e82e70c2..5e2d3412 100644--- a/backend/tests/test_recurring_api.py+++ b/backend/tests/test_recurring_api.py@@ -142,6 +142,35 @@ async def test_create_recurring_skip_first_new_frequencies(assert data["next_occurrence"] == expected_next+async def test_generate_pending_button_covers_auto_generate_off(client, auth_headers, test_account):+ """The endpoint behind Generate Pending also creates schedules whose+ auto-generate toggle is off (issue #1145)."""+ create_resp = await client.post(+ "/api/recurring-transactions",+ json={+ "description": "Manual rent",+ "amount": 900.00,+ "currency": "BRL",+ "type": "debit",+ "frequency": "monthly",+ "start_date": "2026-02-01",+ "account_id": str(test_account.id),+ "auto_generate": False,+ },+ headers=auth_headers,+ )+ assert create_resp.status_code == 201+ assert create_resp.json()["auto_generate"] is False++ gen_resp = await client.post(+ "/api/recurring-transactions/generate",+ headers=auth_headers,+ )+ assert gen_resp.status_code == 200+ assert gen_resp.json()["generated"] >= 1++@pytest.mark.asyncioasync def test_generate_pending_creates_transactions(client, auth_headers, test_account):"""Generate pending creates transactions and advances next_occurrence."""diff --git a/backend/tests/test_recurring_match.py b/backend/tests/test_recurring_match.pyindex de105bbd..eea5a13c 100644--- a/backend/tests/test_recurring_match.py+++ b/backend/tests/test_recurring_match.py@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Accountfrom app.models.transaction import Transaction+from app.models.workspace import Workspace, WorkspaceMemberfrom app.schemas.recurring_transaction import RecurringTransactionCreatefrom app.services import recurring_match_service as rmsfrom app.services.text_similarity import token_overlap@@ -407,6 +408,86 @@ async def test_generate_pending_skips_auto_generate_off(session, test_user, testassert result.scalars().all() == []+async def test_generate_pending_include_manual_covers_auto_generate_off(+ session, test_user, test_workspace, account+):+ """The Generate Pending button asks for schedules the hourly task skips."""+ bill = await _make_bill(session, test_workspace, test_user, account, auto_generate=False)+ count = await generate_pending(+ session, test_user.id, up_to=date(2025, 1, 20), include_manual=True+ )+ assert count == 1+ result = await session.execute(+ select(Transaction).where(Transaction.account_id == account.id)+ )+ txs = result.scalars().all()+ assert len(txs) == 1+ assert txs[0].recurring_transaction_id == bill.id+ assert txs[0].date == date(2025, 1, 10)+++async def test_generate_pending_include_manual_links_real_tx_instead_of_duplicating(+ session, test_user, test_workspace, account+):+ bill = await _make_bill(session, test_workspace, test_user, account, auto_generate=False)+ real = await _add_tx(session, test_user, test_workspace, account, date=date(2025, 1, 10))+ count = await generate_pending(+ session, test_user.id, up_to=date(2025, 1, 20), include_manual=True+ )+ assert count == 0+ await session.refresh(real)+ assert real.recurring_transaction_id == bill.id+++async def test_generate_pending_workspace_scope_leaves_other_workspaces_alone(+ session, test_user, test_workspace, account+):+ """Generate Pending is authorized for one workspace, so it must not+ materialize or advance a schedule that lives in another."""+ other_ws = Workspace(+ id=uuid.uuid4(), name="Other", kind="personal",+ created_by_user_id=test_user.id, default_currency="BRL",+ )+ session.add(other_ws)+ await session.flush()+ session.add(+ WorkspaceMember(+ id=uuid.uuid4(), workspace_id=other_ws.id, user_id=test_user.id, role="owner",+ )+ )+ other_account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=other_ws.id,+ name="OtherAcc", type="checking", balance=Decimal("0"), currency="BRL",+ )+ session.add(other_account)+ await session.commit()++ await _make_bill(session, test_workspace, test_user, account, auto_generate=False)+ other_bill = await _make_bill(+ session, other_ws, test_user, other_account,+ description="Gym Membership", auto_generate=False,+ )++ count = await generate_pending(+ session,+ test_user.id,+ up_to=date(2025, 1, 20),+ include_manual=True,+ workspace_id=test_workspace.id,+ )++ assert count == 1+ result = await session.execute(+ select(Transaction).where(Transaction.account_id == other_account.id)+ )+ assert result.scalars().all() == []+ await session.refresh(other_bill)+ assert other_bill.next_occurrence == date(2025, 1, 10)++@pytest.mark.asyncioasync def test_generate_pending_description_mismatch_creates_placeholder(session, test_user, test_workspace, account