Skip to content

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

fix(recurring): recompute next_occurrence when the schedule is edited (#943)

Rhuan Barretodba6121c0e87
diff --git a/backend/app/schemas/recurring_transaction.py b/backend/app/schemas/recurring_transaction.py
index 686c1d61..61d151d1 100644
--- a/backend/app/schemas/recurring_transaction.py
+++ b/backend/app/schemas/recurring_transaction.py
@@ -1,11 +1,13 @@
import uuid
from datetime import date as _Date
from decimal import Decimal
-from typing import Literal, Optional
+from typing import Annotated, Literal, Optional
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
WeekendAdjustment = Literal["none", "previous_friday", "next_monday"]
+RecurringFrequency = Literal["weekly", "biweekly", "monthly", "quarterly", "semiannual", "yearly"]
+DayOfMonth = Annotated[int, Field(ge=1, le=31)]
class RecurringTransactionCreate(BaseModel):
@@ -15,7 +17,7 @@ class RecurringTransactionCreate(BaseModel):
type: str # debit, credit
frequency: str # weekly, biweekly, monthly, quarterly, semiannual, yearly
weekend_adjustment: WeekendAdjustment = "none"
- day_of_month: Optional[int] = None
+ day_of_month: Optional[DayOfMonth] = None
start_date: _Date
end_date: Optional[_Date] = None
account_id: uuid.UUID
@@ -29,9 +31,9 @@ class RecurringTransactionUpdate(BaseModel):
amount: Optional[Decimal] = None
currency: Optional[str] = None
type: Optional[str] = None
- frequency: Optional[str] = None # weekly, biweekly, monthly, quarterly, semiannual, yearly
+ frequency: Optional[RecurringFrequency] = None
weekend_adjustment: Optional[WeekendAdjustment] = None
- day_of_month: Optional[int] = None
+ day_of_month: Optional[DayOfMonth] = None
start_date: Optional[_Date] = None
end_date: Optional[_Date] = None
account_id: Optional[uuid.UUID] = None
diff --git a/backend/app/services/recurring_transaction_service.py b/backend/app/services/recurring_transaction_service.py
index 77bef087..c74e8d28 100644
--- a/backend/app/services/recurring_transaction_service.py
+++ b/backend/app/services/recurring_transaction_service.py
@@ -106,11 +106,9 @@ async def update_recurring_transaction(
update_data = data.model_dump(exclude_unset=True)
- if (
- "weekend_adjustment" in update_data
- and update_data["weekend_adjustment"] is None
- ):
- raise ValueError("weekend_adjustment is required")
+ for required in ("weekend_adjustment", "start_date", "frequency"):
+ if required in update_data and update_data[required] is None:
+ raise ValueError(f"{required} is required")
# A recurring transaction must always have an account — reject an explicit
# null, and verify ownership of any new account_id.
@@ -121,9 +119,23 @@ async def update_recurring_transaction(
if new_account_id != recurring.account_id:
await _verify_account_in_workspace(session, workspace_id, new_account_id)
+ schedule_changed = any(
+ key in update_data and update_data[key] != getattr(recurring, key)
+ for key in _SCHEDULE_FIELDS
+ )
+ previous_next_occurrence = recurring.next_occurrence
+
for key, value in update_data.items():
setattr(recurring, key, value)
+ if schedule_changed:
+ recurring.next_occurrence = _first_occurrence_on_or_after(
+ recurring.start_date,
+ recurring.frequency,
+ intended_day=recurring.day_of_month or recurring.start_date.day,
+ floor=previous_next_occurrence,
+ )
+
await session.commit()
await session.refresh(recurring)
return recurring
@@ -181,6 +193,28 @@ def _advance_date(
return _advance_months(current, 1, target_day)
+# Fields the occurrence schedule is derived from; changing any of them moves
+# the next_occurrence pointer.
+_SCHEDULE_FIELDS = ("start_date", "day_of_month", "frequency")
+
+
+def _first_occurrence_on_or_after(
+ start: date, frequency: str, intended_day: Optional[int], floor: date,
+) -> date:
+ """Return the first occurrence of the schedule on or after ``floor``.
+
+ The schedule starts at ``start``, as on creation. ``floor`` is the pointer
+ before the edit: every occurrence before it was already generated or
+ matched, so the new pointer never moves behind it. That keeps an edit from
+ backfilling past periods or repeating one that was already charged, while a
+ ``start`` later than ``floor`` still defers the rule to ``start``.
+ """
+ current = start
+ while current < floor:
+ current = _advance_date(current, frequency, intended_day=intended_day)
+ return current
+
+
def adjust_weekend_date(
nominal_date: date, weekend_adjustment: str = "none"
) -> date:
diff --git a/backend/tests/test_recurring_transaction_service.py b/backend/tests/test_recurring_transaction_service.py
index 7f888f34..d477a6ea 100644
--- a/backend/tests/test_recurring_transaction_service.py
+++ b/backend/tests/test_recurring_transaction_service.py
@@ -4,6 +4,7 @@ from decimal import Decimal
import pytest
import pytest_asyncio
+from pydantic import ValidationError
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -162,6 +163,136 @@ async def test_update_recurring_transaction(
assert updated is not None
assert updated.description == "Updated"
assert updated.amount == Decimal("150")
+ assert updated.next_occurrence == date(2025, 1, 1)
+
+
+async def _monthly_rule(
+ session, test_workspace, test_user, account,
+ start_date: date = date(2026, 1, 5), day_of_month: int | None = None,
+):
+ return await create_recurring_transaction(
+ session, test_workspace.id, test_user.id,
+ RecurringTransactionCreate(
+ description="Rule",
+ amount=Decimal("100"),
+ type="debit",
+ frequency="monthly",
+ start_date=start_date,
+ day_of_month=day_of_month,
+ account_id=account.id,
+ ),
+ )
+
+
+async def test_update_later_start_date_defers_next_occurrence(
+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring
+):
+ rec = await _monthly_rule(
+ session, test_workspace, test_user, test_account_for_recurring,
+ start_date=date(2026, 8, 31), day_of_month=31,
+ )
+ rec.next_occurrence = date(2026, 9, 30)
+ await session.commit()
+
+ updated = await update_recurring_transaction(
+ session, rec.id, test_workspace.id,
+ RecurringTransactionUpdate(start_date=date(2026, 10, 22), day_of_month=22),
+ )
+
+ assert updated is not None
+ assert updated.next_occurrence == date(2026, 10, 22)
+
+
+async def test_update_day_of_month_keeps_pointer_ahead_of_processed_periods(
+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring
+):
+ # September's occurrence on the 5th was already generated.
+ rec = await _monthly_rule(
+ session, test_workspace, test_user, test_account_for_recurring, day_of_month=5,
+ )
+ rec.next_occurrence = date(2026, 10, 5)
+ await session.commit()
+
+ updated = await update_recurring_transaction(
+ session, rec.id, test_workspace.id, RecurringTransactionUpdate(day_of_month=25),
+ )
+
+ assert updated is not None
+ assert updated.next_occurrence == date(2026, 10, 25)
+
+
+async def test_update_frequency_realigns_next_occurrence(
+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring
+):
+ rec = await _monthly_rule(
+ session, test_workspace, test_user, test_account_for_recurring,
+ start_date=date(2026, 1, 1),
+ )
+ rec.next_occurrence = date(2026, 3, 1)
+ await session.commit()
+
+ updated = await update_recurring_transaction(
+ session, rec.id, test_workspace.id, RecurringTransactionUpdate(frequency="weekly"),
+ )
+
+ assert updated is not None
+ assert updated.next_occurrence == date(2026, 3, 5)
+
+
[email protected]("field", ["start_date", "frequency"])
+async def test_update_rejects_null_schedule_field(
+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring, field
+):
+ rec = await _monthly_rule(session, test_workspace, test_user, test_account_for_recurring)
+
+ with pytest.raises(ValueError, match=f"{field} is required"):
+ await update_recurring_transaction(
+ session, rec.id, test_workspace.id, RecurringTransactionUpdate(**{field: None}),
+ )
+
+
[email protected]("day", [0, -1, 32])
+def test_schemas_reject_day_of_month_outside_calendar(day):
+ with pytest.raises(ValidationError):
+ RecurringTransactionUpdate(day_of_month=day)
+ with pytest.raises(ValidationError):
+ RecurringTransactionCreate(
+ description="Rule", amount=Decimal("1"), type="debit", frequency="monthly",
+ start_date=date(2026, 1, 1), account_id=uuid.uuid4(), day_of_month=day,
+ )
+
+
+def test_update_rejects_unsupported_frequency():
+ # An unknown cadence would reach _advance_date's monthly fallback and
+ # silently turn the rule monthly when the pointer is recomputed.
+ with pytest.raises(ValidationError):
+ RecurringTransactionUpdate(frequency="daily") # ty: ignore[invalid-argument-type]
+
+
+async def test_update_resending_schedule_keeps_next_occurrence(
+ session: AsyncSession, test_user, test_workspace, test_account_for_recurring
+):
+ rec = await _monthly_rule(
+ session, test_workspace, test_user, test_account_for_recurring, day_of_month=5,
+ )
+ rec.next_occurrence = date(2026, 10, 5)
+ await session.commit()
+
+ updated = await update_recurring_transaction(
+ session, rec.id, test_workspace.id,
+ RecurringTransactionUpdate(
+ start_date=date(2026, 1, 5), day_of_month=5, frequency="monthly",
+ description="Renamed",
+ ),
+ )
+
+ assert updated is not None
+ assert updated.next_occurrence == date(2026, 10, 5)
@pytest.mark.asyncio