Open-source personal finance manager. Self-hosted, privacy-first.
fix(invoices): use workspace dates for recurring billing (#1090)
Albert Dolkun620150fa47b7
diff --git a/backend/app/services/invoice_schedule_service.py b/backend/app/services/invoice_schedule_service.pyindex c73119f7..a8feae08 100644--- a/backend/app/services/invoice_schedule_service.py+++ b/backend/app/services/invoice_schedule_service.py@@ -14,9 +14,8 @@ the frequency, day of month clamped in shorter months and recoveredafterwards, and ends the day before period `n + 1` starts. That is allthe calendar there is: no separate "next run" date to drift, notimezone column to disagree with the anchor. The job compares period-starts against the UTC date; a retainer due on the 1st is emitted on-the 1st UTC, which is the same day everywhere that matters for a-document dated by the day.+starts against the workspace's calendar, using the same timezone as+invoice dates and the rest of its books.## Terms@@ -49,6 +48,7 @@ from sqlalchemy import func, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession+from app.core.app_clock import app_todayfrom app.models.invoice import (Invoice,InvoiceAllocation,@@ -87,7 +87,7 @@ _MAX_WALK = 1000def _today() -> _date:- return datetime.now(timezone.utc).date()+ return app_today()# ---------------------------------------------------------------------------diff --git a/backend/app/tasks/invoice_schedule_tasks.py b/backend/app/tasks/invoice_schedule_tasks.pyindex fc728283..00b937f3 100644--- a/backend/app/tasks/invoice_schedule_tasks.py+++ b/backend/app/tasks/invoice_schedule_tasks.py@@ -9,6 +9,7 @@ import loggingfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine+from app.core.app_clock import use_timezonefrom app.core.config import get_settingsfrom app.models.workspace import Workspacefrom app.services import invoice_schedule_service, invoice_service@@ -31,37 +32,38 @@ async def _generate_one(session_maker, schedule_id) -> int:schedule = await session.get(invoice_schedule_service.InvoiceSchedule, schedule_id)if schedule is None:return 0- try:- emitted = await invoice_schedule_service.generate_due(session, schedule)- except Exception as exc:- if isinstance(exc, InvoiceError) and exc.code == "period_already_issued":- # Another run emitted the period first. Nothing failed,- # and `generate_due` already rolled back.+ async with use_timezone(session, schedule.workspace_id, fresh=True):+ try:+ emitted = await invoice_schedule_service.generate_due(session, schedule)+ except Exception as exc:+ if isinstance(exc, InvoiceError) and exc.code == "period_already_issued":+ # Another run emitted the period first. Nothing failed,+ # and `generate_due` already rolled back.+ return 0+ # `generate_due` already counted the failure on the row and+ # may have paused the schedule; what it did not do is commit.+ # Anything half-written for the invoice is rolled back, then+ # the count is written on its own.+ logger.exception("Failed to emit invoices for schedule %s", schedule_id)+ failures = schedule.consecutive_failures+ status = schedule.status+ pause_reason = schedule.pause_reason+ await session.rollback()+ fresh = await session.get(invoice_schedule_service.InvoiceSchedule, schedule_id)+ if fresh is not None:+ fresh.consecutive_failures = failures+ fresh.status = status+ fresh.pause_reason = pause_reason+ await session.commit()return 0- # `generate_due` already counted the failure on the row and- # may have paused the schedule; what it did not do is commit.- # Anything half-written for the invoice is rolled back, then- # the count is written on its own.- logger.exception("Failed to emit invoices for schedule %s", schedule_id)- failures = schedule.consecutive_failures- status = schedule.status- pause_reason = schedule.pause_reason- await session.rollback()- fresh = await session.get(invoice_schedule_service.InvoiceSchedule, schedule_id)- if fresh is not None:- fresh.consecutive_failures = failures- fresh.status = status- fresh.pause_reason = pause_reason- await session.commit()- return 0- await session.commit()+ await session.commit()- workspace = await session.get(Workspace, schedule.workspace_id)- for invoice in emitted:- loaded = await invoice_service.get_invoice(session, invoice.id, schedule.workspace_id)- if loaded is not None and workspace is not None:- await invoice_schedule_service.after_generation(session, loaded, workspace)- return len(emitted)+ workspace = await session.get(Workspace, schedule.workspace_id)+ for invoice in emitted:+ loaded = await invoice_service.get_invoice(session, invoice.id, schedule.workspace_id)+ if loaded is not None and workspace is not None:+ await invoice_schedule_service.after_generation(session, loaded, workspace)+ return len(emitted)async def _generate_all() -> int:diff --git a/backend/tests/test_invoice_schedule_timezone.py b/backend/tests/test_invoice_schedule_timezone.pynew file mode 100644index 00000000..ebee0305--- /dev/null+++ b/backend/tests/test_invoice_schedule_timezone.py@@ -0,0 +1,115 @@+"""Recurring invoices follow the workspace calendar in requests and background jobs."""+from datetime import date, datetime, timezone++import pytest+from sqlalchemy.ext.asyncio import async_sessionmaker++from app.core import app_clock+from app.models.app_settings import AppSetting+from app.services import invoice_schedule_service as schedules+from app.tasks import invoice_schedule_tasks+++def frozen_clock(monkeypatch):+ class FixedDatetime(datetime):+ instant = datetime(2026, 10, 5, 1, tzinfo=timezone.utc)++ @classmethod+ def now(cls, tz=None):+ return cls.instant.astimezone(tz)++ monkeypatch.setattr(app_clock, "datetime", FixedDatetime)+ monkeypatch.setattr(schedules, "datetime", FixedDatetime)+ return FixedDatetime+++ "zone,instant,local_day",+ [+ ("America/Los_Angeles", datetime(2026, 10, 5, 1, tzinfo=timezone.utc), date(2026, 10, 4)),+ ("Asia/Tokyo", datetime(2026, 10, 4, 23, tzinfo=timezone.utc), date(2026, 10, 5)),+ ],+)+async def test_schedule_creation_keeps_the_workspace_first_period(+ client, auth_headers, session, test_workspace, frozen_clock, zone, instant, local_day+):+ frozen_clock.instant = instant+ test_workspace.kind = "business"+ test_workspace.timezone = zone+ session.add(AppSetting(key="timezone", value="UTC"))+ await session.commit()+ headers = {**auth_headers, "X-Workspace-Id": str(test_workspace.id)}++ # Both choosing "today" and leaving the default must keep period one.+ for dates in ({"start_date": local_day.isoformat()}, {}):+ response = await client.post(+ "/api/invoice-schedules",+ headers=headers,+ json={+ "name": "Monthly retainer", "frequency": "monthly", **dates,+ "lines": [{"description": "Service", "unit_price": "100"}],+ },+ )+ assert response.status_code == 201, response.text+ assert response.json()["start_date"] == local_day.isoformat()+ assert response.json()["next_sequence"] == 1+ assert response.json()["next_period_start"] == local_day.isoformat()+++ "zone,instant,expected_count",+ [+ ("America/Los_Angeles", datetime(2026, 10, 5, 1, tzinfo=timezone.utc), 0),+ ("Asia/Tokyo", datetime(2026, 10, 4, 23, tzinfo=timezone.utc), 1),+ ],+)+async def test_schedule_worker_uses_each_workspace_calendar(+ session, test_user, test_workspace, frozen_clock, zone, instant, expected_count+):+ frozen_clock.instant = instant+ test_workspace.timezone = zone+ session.add(AppSetting(key="timezone", value="UTC"))+ schedule = await schedules.create_schedule(+ session, test_workspace.id, test_user.id,+ {"name": "Retainer", "frequency": "monthly", "start_date": date(2026, 10, 5),+ "lines": [{"description": "Service", "unit_price": "100"}]},+ today=date(2026, 10, 1),+ )+ await session.commit()+ maker = async_sessionmaker(session.bind, expire_on_commit=False)++ assert await invoice_schedule_tasks._generate_one(maker, schedule.id) == expected_count+ # The next hourly pass cannot bill the same period twice.+ assert await invoice_schedule_tasks._generate_one(maker, schedule.id) == 0+ await session.refresh(schedule)+ assert schedule.next_sequence == 1 + expected_count+++ "cached_zone,saved_zone,expected_count",+ [("UTC", "America/Los_Angeles", 0), ("America/Los_Angeles", "UTC", 1)],+)+async def test_schedule_worker_reads_past_a_stale_application_timezone(+ session, test_user, test_workspace, frozen_clock, cached_zone, saved_zone, expected_count+):+ setting = AppSetting(key="timezone", value=cached_zone)+ session.add(setting)+ schedule = await schedules.create_schedule(+ session, test_workspace.id, test_user.id,+ {"name": "Retainer", "frequency": "monthly", "start_date": date(2026, 10, 5),+ "lines": [{"description": "Service", "unit_price": "100"}]},+ today=date(2026, 10, 1),+ )+ await session.commit()+ assert str(await app_clock.get_timezone(session)) == cached_zone+ # A different process saves the setting without invalidating this cache.+ setting.value = saved_zone+ await session.commit()+ assert str(await app_clock.get_timezone(session)) == cached_zone+ maker = async_sessionmaker(session.bind, expire_on_commit=False)++ assert await invoice_schedule_tasks._generate_one(maker, schedule.id) == expected_count+ await session.refresh(schedule)+ assert schedule.next_sequence == 1 + expected_count+