Open-source personal finance manager. Self-hosted, privacy-first.
feat(invoices): recurring invoices with price terms (#988)
Tássio Noronhaeade430db23d
diff --git a/backend/alembic/versions/092_invoice_schedules.py b/backend/alembic/versions/092_invoice_schedules.pynew file mode 100644index 00000000..3c6304a4--- /dev/null+++ b/backend/alembic/versions/092_invoice_schedules.py@@ -0,0 +1,198 @@+"""recurring invoices: schedules, their terms, and the link from an invoice++Two tables and four columns, all saying the same thing: an invoice may+answer for one period of an agreement.++ - `invoice_schedules` is the agreement: a client, a frequency, an+ anchor date, an end condition, and a status that records decisions+ only (`active`, `paused`, `ended`). Recurring revenue, what a+ client paid under it and whether it is behind are derived from its+ invoices, never stored.+ - `invoice_schedule_terms` is the price over time: one row per change,+ each saying from when it applies. A raise recorded today for January+ changes nothing until January.+ - `invoices.schedule_id` / `sequence` / `period_start` / `period_end`+ point an invoice at its agreement and period. The unique+ `(schedule_id, sequence)` is what makes the generation job+ idempotent: a retry hits the index instead of emitting twice.++Revision ID: 092+Revises: 091+"""+from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects import postgresql++revision = "092"+down_revision = "091"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.create_table(+ "invoice_schedules",+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("payee_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("name", sa.String(length=200), nullable=False),+ sa.Column("origin", sa.String(length=20), server_default="local", nullable=False),+ sa.Column("external_source", sa.String(length=50), nullable=True),+ sa.Column("external_id", sa.String(length=255), nullable=True),+ sa.Column("status", sa.String(length=20), server_default="active", nullable=False),+ sa.Column("pause_reason", sa.String(length=20), nullable=True),+ sa.Column("ended_at", sa.Date(), nullable=True),+ sa.Column("end_reason", sa.String(length=30), nullable=True),+ sa.Column("frequency", sa.String(length=20), nullable=False),+ sa.Column("start_date", sa.Date(), nullable=False),+ sa.Column("end_type", sa.String(length=20), server_default="never", nullable=False),+ sa.Column("end_date", sa.Date(), nullable=True),+ sa.Column("end_count", sa.Integer(), nullable=True),+ sa.Column("payment_terms_days", sa.Integer(), nullable=True),+ sa.Column("currency", sa.String(length=3), nullable=False),+ sa.Column("notes", sa.Text(), nullable=True),+ sa.Column("custom_fields", sa.JSON(), nullable=True),+ sa.Column("next_sequence", sa.Integer(), server_default="1", nullable=False),+ sa.Column("last_generated_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("consecutive_failures", sa.Integer(), server_default="0", nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),+ sa.ForeignKeyConstraint(["payee_id"], ["payees.id"], ondelete="RESTRICT"),+ sa.PrimaryKeyConstraint("id"),+ sa.UniqueConstraint(+ "workspace_id",+ "external_source",+ "external_id",+ name="uq_invoice_schedules_workspace_external",+ ),+ sa.CheckConstraint(+ "status IN ('active', 'paused', 'ended')", name="ck_invoice_schedules_status"+ ),+ sa.CheckConstraint(+ "origin IN ('local', 'imported')", name="ck_invoice_schedules_origin"+ ),+ sa.CheckConstraint(+ "frequency IN ('weekly', 'biweekly', 'monthly', 'quarterly', 'semiannual', 'yearly')",+ name="ck_invoice_schedules_frequency",+ ),+ sa.CheckConstraint(+ "end_type IN ('never', 'on_date', 'after_count')",+ name="ck_invoice_schedules_end_type",+ ),+ sa.CheckConstraint(+ "(end_type = 'never')"+ " OR (end_type = 'on_date' AND end_date IS NOT NULL)"+ " OR (end_type = 'after_count' AND end_count IS NOT NULL AND end_count > 0)",+ name="ck_invoice_schedules_end_condition",+ ),+ sa.CheckConstraint(+ "end_reason IS NULL OR end_reason IN"+ " ('canceled_by_client', 'canceled_by_us', 'completed', 'unpaid', 'other')",+ name="ck_invoice_schedules_end_reason",+ ),+ sa.CheckConstraint(+ "pause_reason IS NULL OR pause_reason IN ('manual', 'failures')",+ name="ck_invoice_schedules_pause_reason",+ ),+ sa.CheckConstraint(+ "(status = 'ended' AND ended_at IS NOT NULL AND end_reason IS NOT NULL)"+ " OR (status <> 'ended' AND ended_at IS NULL AND end_reason IS NULL)",+ name="ck_invoice_schedules_ended_fields",+ ),+ sa.CheckConstraint("next_sequence >= 1", name="ck_invoice_schedules_next_sequence"),+ sa.CheckConstraint(+ "payment_terms_days IS NULL OR payment_terms_days >= 0",+ name="ck_invoice_schedules_payment_terms",+ ),+ )+ op.create_index(+ "ix_invoice_schedules_workspace_id", "invoice_schedules", ["workspace_id"]+ )+ op.create_index("ix_invoice_schedules_payee_id", "invoice_schedules", ["payee_id"])+ op.create_index(+ "ix_invoice_schedules_workspace_status",+ "invoice_schedules",+ ["workspace_id", "status"],+ )++ op.create_table(+ "invoice_schedule_terms",+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("schedule_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("effective_from", sa.Date(), nullable=False),+ sa.Column("lines", sa.JSON(), nullable=False),+ sa.Column("discount", sa.Numeric(precision=15, scale=2), nullable=False),+ sa.Column("subtotal", sa.Numeric(precision=15, scale=2), nullable=False),+ sa.Column("tax_total", sa.Numeric(precision=15, scale=2), nullable=False),+ sa.Column("total", sa.Numeric(precision=15, scale=2), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(+ ["schedule_id"], ["invoice_schedules.id"], ondelete="CASCADE"+ ),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ sa.UniqueConstraint(+ "schedule_id", "effective_from", name="uq_invoice_schedule_terms_effective_from"+ ),+ sa.CheckConstraint("discount >= 0", name="ck_invoice_schedule_terms_discount"),+ sa.CheckConstraint("total >= 0", name="ck_invoice_schedule_terms_total"),+ )+ op.create_index(+ "ix_invoice_schedule_terms_schedule", "invoice_schedule_terms", ["schedule_id"]+ )+ op.create_index(+ "ix_invoice_schedule_terms_workspace_id", "invoice_schedule_terms", ["workspace_id"]+ )++ op.add_column(+ "invoices", sa.Column("schedule_id", postgresql.UUID(as_uuid=True), nullable=True)+ )+ op.add_column("invoices", sa.Column("sequence", sa.Integer(), nullable=True))+ op.add_column("invoices", sa.Column("period_start", sa.Date(), nullable=True))+ op.add_column("invoices", sa.Column("period_end", sa.Date(), nullable=True))+ op.create_foreign_key(+ "fk_invoices_schedule_id",+ "invoices",+ "invoice_schedules",+ ["schedule_id"],+ ["id"],+ ondelete="SET NULL",+ )+ op.create_index("ix_invoices_schedule_id", "invoices", ["schedule_id"])+ op.create_unique_constraint(+ "uq_invoices_schedule_sequence", "invoices", ["schedule_id", "sequence"]+ )+ op.create_check_constraint(+ "ck_invoices_schedule_fields",+ "invoices",+ "(schedule_id IS NULL AND sequence IS NULL"+ " AND period_start IS NULL AND period_end IS NULL)"+ " OR (schedule_id IS NOT NULL AND sequence IS NOT NULL"+ " AND period_start IS NOT NULL AND period_end IS NOT NULL)",+ )+++def downgrade() -> None:+ # The invoices stay: they are money, and only the memory of which+ # agreement they answered for is lost.+ op.drop_constraint("ck_invoices_schedule_fields", "invoices", type_="check")+ op.drop_constraint("uq_invoices_schedule_sequence", "invoices", type_="unique")+ op.drop_index("ix_invoices_schedule_id", table_name="invoices")+ op.drop_constraint("fk_invoices_schedule_id", "invoices", type_="foreignkey")+ op.drop_column("invoices", "period_end")+ op.drop_column("invoices", "period_start")+ op.drop_column("invoices", "sequence")+ op.drop_column("invoices", "schedule_id")++ op.drop_index("ix_invoice_schedule_terms_workspace_id", table_name="invoice_schedule_terms")+ op.drop_index("ix_invoice_schedule_terms_schedule", table_name="invoice_schedule_terms")+ op.drop_table("invoice_schedule_terms")++ op.drop_index("ix_invoice_schedules_workspace_status", table_name="invoice_schedules")+ op.drop_index("ix_invoice_schedules_payee_id", table_name="invoice_schedules")+ op.drop_index("ix_invoice_schedules_workspace_id", table_name="invoice_schedules")+ op.drop_table("invoice_schedules")diff --git a/backend/app/api/invoice_schedules.py b/backend/app/api/invoice_schedules.pynew file mode 100644index 00000000..85428112--- /dev/null+++ b/backend/app/api/invoice_schedules.py@@ -0,0 +1,390 @@+"""Recurring invoice routes.++Gated exactly like `/api/invoices`: `require_module(INVOICES)` for reads,+the write variant for anything that changes an agreement. A personal+workspace gets a 404 from all of them.++Mounted under its own prefix rather than `/api/invoices/schedules`,+because `/api/invoices/{invoice_id}` is declared with a UUID path+parameter and would answer `schedules` with a 422 before this router+was consulted.+"""+import uuid+from datetime import date as _date+from typing import Optional++from fastapi import APIRouter, Depends, HTTPException, Query, status+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.invoices import _http, _serialize as _serialize_invoice+from app.core.database import get_async_session+from app.core.module_gate import require_module, require_module_write+from app.core.workspace_context import WorkspaceContext+from app.models.invoice import Invoice+from app.models.invoice_schedule import InvoiceSchedule+from app.schemas.invoice import InvoiceRead+from app.schemas.invoice_schedule import (+ ScheduleCreate,+ ScheduleEnd,+ ScheduleLinkInvoice,+ SchedulePeriodRead,+ ScheduleRead,+ ScheduleSummaryRead,+ ScheduleTermInput,+ ScheduleTermRead,+ ScheduleTermUpdate,+ ScheduleUpdate,+)+from app.services import invoice_schedule_service as svc+from app.services import invoice_service+from app.services.invoice_service import InvoiceError+from app.services.module_service import ModuleId++router = APIRouter(prefix="/api/invoice-schedules", tags=["invoice-schedules"])++read_ctx = require_module(ModuleId.INVOICES)+write_ctx = require_module_write(ModuleId.INVOICES)+++def _serialize(+ schedule: InvoiceSchedule,+ figures: Optional[svc.ScheduleFigures] = None,+ today: Optional[_date] = None,+) -> ScheduleRead:+ """Attach the derived answers to the stored row. The only place that+ builds a `ScheduleRead`, so every figure comes from one definition."""+ payload = ScheduleRead.model_validate(schedule, from_attributes=True)+ today = today or svc._today()+ current = svc.term_for(schedule, today)+ payload.current_term = ScheduleTermRead.model_validate(current) if current else None+ upcoming = svc.next_period_start(schedule)+ payload.next_period_start = upcoming+ next_term = svc.term_for(schedule, upcoming) if upcoming else current+ payload.next_term = ScheduleTermRead.model_validate(next_term) if next_term else None+ payload.monthly_amount = svc.monthly_amount(schedule, current)+ if figures is not None:+ payload.invoice_count = figures.invoice_count+ payload.amount_invoiced = figures.amount_invoiced+ payload.amount_paid = figures.amount_paid+ payload.past_due_count = figures.past_due_count+ return payload+++async def _load(session: AsyncSession, schedule_id: uuid.UUID, workspace_id: uuid.UUID):+ schedule = await svc.get_schedule(session, schedule_id, workspace_id)+ if schedule is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Schedule not found")+ return schedule+++async def _load_invoice(session: AsyncSession, invoice_id: uuid.UUID, workspace_id: uuid.UUID) -> Invoice:+ invoice = await invoice_service.get_invoice(session, invoice_id, workspace_id)+ if invoice is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invoice not found")+ return invoice+++async def _read(session: AsyncSession, schedule_id: uuid.UUID, workspace_id: uuid.UUID) -> ScheduleRead:+ schedule = await _load(session, schedule_id, workspace_id)+ figures = await svc.figures_for(session, workspace_id, [schedule.id])+ return _serialize(schedule, figures.get(schedule.id))+++# ---------------------------------------------------------------------------+# Reading+# ---------------------------------------------------------------------------[email protected]("/summary", response_model=ScheduleSummaryRead)+async def summary(+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ return await svc.summary(session, ctx.workspace.id)++[email protected]("", response_model=list[ScheduleRead])+async def list_schedules(+ status_: Optional[str] = Query(None, alias="status"),+ payee_id: Optional[uuid.UUID] = Query(None),+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedules = await svc.list_schedules(session, ctx.workspace.id, status=status_, payee_id=payee_id)+ figures = await svc.figures_for(session, ctx.workspace.id, [s.id for s in schedules])+ return [_serialize(s, figures.get(s.id)) for s in schedules]++[email protected]("/{schedule_id}", response_model=ScheduleRead)+async def get_schedule(+ schedule_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ return await _read(session, schedule_id, ctx.workspace.id)++[email protected]("/{schedule_id}/invoices", response_model=list[InvoiceRead])+async def list_schedule_invoices(+ schedule_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ invoices = await invoice_service.list_invoices(+ session, ctx.workspace.id, schedule_id=schedule.id, limit=500+ )+ return [_serialize_invoice(inv) for inv in invoices]++[email protected]("/{schedule_id}/periods", response_model=list[SchedulePeriodRead])+async def list_periods(+ schedule_id: uuid.UUID,+ ahead: int = Query(3, ge=0, le=24, description="Periods past the cursor to include"),+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """The agreement's periods as labels, from the first to a few past+ the cursor, each saying whether an invoice already answers for it.+ What the "which period is this invoice for" picker lists."""+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ taken = {+ row[0]+ for row in (+ await session.execute(+ select(Invoice.sequence).where(Invoice.schedule_id == schedule.id)+ )+ ).all()+ }+ last = schedule.next_sequence + ahead+ out = []+ for sequence in range(1, last + 1):+ if not svc.period_within_end(schedule, sequence):+ break+ start, end = svc.period_bounds(schedule, sequence)+ out.append(+ SchedulePeriodRead(+ sequence=sequence, period_start=start, period_end=end, taken=sequence in taken+ )+ )+ return out+++# ---------------------------------------------------------------------------+# Writing+# ---------------------------------------------------------------------------[email protected]("", response_model=ScheduleRead, status_code=status.HTTP_201_CREATED)+async def create_schedule(+ payload: ScheduleCreate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ data = payload.model_dump(exclude_unset=True)+ data["lines"] = [dict(line) for line in data["lines"]]+ try:+ schedule = await svc.create_schedule(session, ctx.workspace.id, ctx.user_id, data)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule.id, ctx.workspace.id)++[email protected]("/{schedule_id}", response_model=ScheduleRead)+async def update_schedule(+ schedule_id: uuid.UUID,+ payload: ScheduleUpdate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ try:+ await svc.update_schedule(session, schedule, payload.model_dump(exclude_unset=True))+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule_id, ctx.workspace.id)++[email protected]("/{schedule_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_schedule(+ schedule_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ try:+ await svc.delete_schedule(session, schedule)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()++[email protected]("/{schedule_id}/pause", response_model=ScheduleRead)+async def pause_schedule(+ schedule_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ try:+ await svc.pause_schedule(session, schedule)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule_id, ctx.workspace.id)++[email protected]("/{schedule_id}/resume", response_model=ScheduleRead)+async def resume_schedule(+ schedule_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ try:+ await svc.resume_schedule(session, schedule)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule_id, ctx.workspace.id)++[email protected]("/{schedule_id}/end", response_model=ScheduleRead)+async def end_schedule(+ schedule_id: uuid.UUID,+ payload: ScheduleEnd,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ try:+ await svc.end_schedule(session, schedule, reason=payload.reason, ended_at=payload.ended_at)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule_id, ctx.workspace.id)++[email protected]("/{schedule_id}/generate", response_model=list[InvoiceRead], status_code=status.HTTP_201_CREATED)+async def generate_now(+ schedule_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """Emit the next period now, whether or not its date has come."""+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ if schedule.status != "active":+ raise HTTPException(+ status_code=400,+ detail={"code": "schedule_not_active", "message": "Only an active agreement emits invoices"},+ )+ try:+ emitted = await svc.generate_due(session, schedule, force_next=True)+ except InvoiceError as exc:+ # The failure count is worth keeping. A 409 already rolled back:+ # the period exists, and there is nothing to record.+ if exc.status_code != 409:+ await session.commit()+ raise _http(exc)+ await session.commit()+ out = []+ for emitted_invoice in emitted:+ loaded = await invoice_service.get_invoice(session, emitted_invoice.id, ctx.workspace.id)+ if loaded is None:+ continue+ await svc.after_generation(session, loaded, ctx.workspace)+ out.append(_serialize_invoice(await _load_invoice(session, loaded.id, ctx.workspace.id)))+ return out+++# ---------------------------------------------------------------------------+# Terms+# ---------------------------------------------------------------------------[email protected]("/{schedule_id}/terms", response_model=ScheduleRead, status_code=status.HTTP_201_CREATED)+async def add_term(+ schedule_id: uuid.UUID,+ payload: ScheduleTermInput,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ try:+ await svc.add_term(+ session,+ schedule,+ effective_from=payload.effective_from,+ lines=[dict(line) for line in payload.lines],+ discount=payload.discount,+ )+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule_id, ctx.workspace.id)++[email protected]("/{schedule_id}/terms/{term_id}", response_model=ScheduleRead)+async def update_term(+ schedule_id: uuid.UUID,+ term_id: uuid.UUID,+ payload: ScheduleTermUpdate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ term = next((t for t in schedule.terms if t.id == term_id), None)+ if term is None:+ raise HTTPException(status_code=404, detail="Term not found")+ data = payload.model_dump(exclude_unset=True)+ try:+ await svc.update_term(+ session,+ schedule,+ term,+ lines=[dict(line) for line in data["lines"]] if data.get("lines") is not None else None,+ discount=data.get("discount"),+ effective_from=data.get("effective_from"),+ )+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule_id, ctx.workspace.id)++[email protected]("/{schedule_id}/terms/{term_id}", response_model=ScheduleRead)+async def delete_term(+ schedule_id: uuid.UUID,+ term_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ term = next((t for t in schedule.terms if t.id == term_id), None)+ if term is None:+ raise HTTPException(status_code=404, detail="Term not found")+ try:+ await svc.delete_term(session, schedule, term)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read(session, schedule_id, ctx.workspace.id)+++# ---------------------------------------------------------------------------+# Linking+# ---------------------------------------------------------------------------[email protected]("/{schedule_id}/link", response_model=InvoiceRead)+async def link_invoice(+ schedule_id: uuid.UUID,+ payload: ScheduleLinkInvoice,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ schedule = await _load(session, schedule_id, ctx.workspace.id)+ invoice = await invoice_service.get_invoice(session, payload.invoice_id, ctx.workspace.id)+ if invoice is None:+ raise HTTPException(status_code=404, detail="Invoice not found")+ try:+ await svc.link_invoice(session, schedule, invoice, payload.period_start)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize_invoice(await _load_invoice(session, invoice.id, ctx.workspace.id))diff --git a/backend/app/api/invoices.py b/backend/app/api/invoices.pyindex 5931ef49..49b693b7 100644--- a/backend/app/api/invoices.py+++ b/backend/app/api/invoices.py@@ -33,12 +33,14 @@ from app.schemas.invoice import (IssuerProfileUpdate,ShareLinkRead,)+from app.schemas.invoice_schedule import MakeRecurring, ScheduleReadfrom app.services import (invoice_archive,invoice_attachment_service,invoice_logo_service,invoice_document,invoice_pdf,+ invoice_schedule_service,invoice_service,reconciliation_history_service,reconciliation_service,@@ -202,6 +204,7 @@ async def list_invoices(year: Optional[int] = Query(None, ge=1970, le=2200, description="Filter by issue year"),direction: InvoiceDirection = DirectionParam,payee_id: Optional[uuid.UUID] = Query(None),+ schedule_id: Optional[uuid.UUID] = Query(None, description="Only invoices of this agreement"),q: Optional[str] = Query(None),limit: int = Query(100, ge=1, le=500),offset: int = Query(0, ge=0),@@ -210,7 +213,7 @@ async def list_invoices():invoices = await invoice_service.list_invoices(session, ctx.workspace.id, state=state, year=year, direction=direction,- payee_id=payee_id, q=q, limit=limit, offset=offset,+ payee_id=payee_id, schedule_id=schedule_id, q=q, limit=limit, offset=offset,)return [_serialize(inv) for inv in invoices]@@ -388,6 +391,40 @@ async def reopen_invoice(# ---------------------------------------------------------------------------# Allocations — money bound to debt# ---------------------------------------------------------------------------[email protected]("/{invoice_id}/make-recurring", response_model=ScheduleRead, status_code=status.HTTP_201_CREATED)+async def make_recurring(+ invoice_id: uuid.UUID,+ payload: MakeRecurring,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """Turn this invoice into period one of a new agreement that repeats it."""+ from app.api.invoice_schedules import _read as _read_schedule++ invoice = await _load(session, invoice_id, ctx.workspace.id)+ try:+ schedule = await invoice_schedule_service.make_recurring(+ session, invoice, ctx.user_id, payload.model_dump(exclude_unset=True)+ )+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return await _read_schedule(session, schedule.id, ctx.workspace.id)++[email protected]("/{invoice_id}/schedule", response_model=InvoiceRead)+async def unlink_schedule(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """The invoice stops answering for a period. It stays as it is."""+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ await invoice_schedule_service.unlink_invoice(session, invoice)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++@router.post("/{invoice_id}/allocations", response_model=InvoiceRead, status_code=status.HTTP_201_CREATED)async def create_allocation(invoice_id: uuid.UUID,diff --git a/backend/app/main.py b/backend/app/main.pyindex 215161c4..3b27dc90 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -35,6 +35,7 @@ from app.api.fx_rates import router as fx_rates_routerfrom app.api.attachments import router as attachments_routerfrom app.api.fiscal import router as fiscal_routerfrom app.api.invoice_attachments import router as invoice_attachments_router+from app.api.invoice_schedules import router as invoice_schedules_routerfrom app.api.invoices import router as invoices_routerfrom app.api.public_invoices import router as public_invoices_routerfrom app.api.payees import router as payees_router@@ -192,6 +193,7 @@ app.include_router(fiscal_router)app.include_router(payees_router)app.include_router(invoices_router)app.include_router(invoice_attachments_router)+app.include_router(invoice_schedules_router)app.include_router(public_invoices_router)app.include_router(settings_router)app.include_router(workspaces_router)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex ee798442..08cedfc7 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -27,6 +27,7 @@ from app.models.group_settlement import GroupSettlementfrom app.models.collection import Collection, collection_accounts, collection_asset_groupsfrom app.models.invoice import Invoice, InvoiceAllocation, InvoiceLine, InvoiceSettingsfrom app.models.invoice_attachment import InvoiceAttachment+from app.models.invoice_schedule import InvoiceSchedule, InvoiceScheduleTermfrom app.models.reconciliation import (ReconciliationEvent,ReconciliationRule,@@ -76,6 +77,8 @@ __all__ = ["InvoiceLine","InvoiceSettings","InvoiceAttachment",+ "InvoiceSchedule",+ "InvoiceScheduleTerm","ReconciliationEvent","ReconciliationRule","ReconciliationSuggestion",diff --git a/backend/app/models/invoice.py b/backend/app/models/invoice.pyindex c87e7837..8853cb62 100644--- a/backend/app/models/invoice.py+++ b/backend/app/models/invoice.py@@ -46,6 +46,7 @@ from app.core.database import Baseif TYPE_CHECKING:from app.models.invoice_attachment import InvoiceAttachment+ from app.models.invoice_schedule import InvoiceSchedulefrom app.models.payee import Payeefrom app.models.transaction import Transaction@@ -159,6 +160,22 @@ class Invoice(Base):name="ck_invoices_number_matches_status",),CheckConstraint("total >= 0", name="ck_invoices_total_non_negative"),+ # One invoice per period of an agreement. This is what makes the+ # generation job idempotent: a retry that tries to emit period 7+ # again hits the index instead of creating a second invoice.+ # Drafts and one-off invoices carry NULLs and are exempt.+ UniqueConstraint("schedule_id", "sequence", name="uq_invoices_schedule_sequence"),+ # An invoice either answers for a period of an agreement, saying+ # which one and when, or it does not belong to any. Half-linked+ # rows would be invoices that count towards a schedule without a+ # period to be counted in.+ CheckConstraint(+ "(schedule_id IS NULL AND sequence IS NULL"+ " AND period_start IS NULL AND period_end IS NULL)"+ " OR (schedule_id IS NOT NULL AND sequence IS NOT NULL"+ " AND period_start IS NOT NULL AND period_end IS NOT NULL)",+ name="ck_invoices_schedule_fields",+ ),)id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)@@ -247,6 +264,25 @@ class Invoice(Base):# revoke one. Unique so the public lookup is a single indexed read.share_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, unique=True)+ # Which agreement this invoice answers for, and which period of it.+ # Provenance and grouping only: the invoice is an ordinary invoice+ # in every other respect, and nothing in the arithmetic reads these.+ # SET NULL because the invoice is money and outlives the agreement.+ #+ # `sequence` is 1-based and is the period's index from the+ # schedule's anchor; `period_start` / `period_end` are the same fact+ # as dates, inclusive on both ends, stored so a reader never has to+ # walk the calendar to label a row "September 2026".+ schedule_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True),+ ForeignKey("invoice_schedules.id", ondelete="SET NULL"),+ nullable=True,+ index=True,+ )+ sequence: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ period_start: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)+ period_end: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)+created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))@@ -282,6 +318,9 @@ class Invoice(Base):order_by="InvoiceAttachment.created_at",lazy="selectin",)+ schedule: Mapped[Optional["InvoiceSchedule"]] = relationship(+ back_populates="invoices", lazy="joined"+ )class InvoiceLine(Base):diff --git a/backend/app/models/invoice_schedule.py b/backend/app/models/invoice_schedule.pynew file mode 100644index 00000000..608db2e0--- /dev/null+++ b/backend/app/models/invoice_schedule.py@@ -0,0 +1,316 @@+"""Recurring invoices: an agreement that emits one invoice per period.++Two tables, and the rule that shapes both: **the schedule is an+agreement, never money**. Money only ever exists as an invoice, and an+invoice born from a schedule is an ordinary invoice that remembers+which agreement and which period it answers for. Everything a reader+wants to know about the agreement financially (recurring revenue,+what a client has paid under it, whether it is behind) is computed+from those invoices and never written here.++`InvoiceSchedule.status` therefore holds only decisions, exactly like+`Invoice.status`: someone paused it, someone ended it. "Past due" is a+fact about an invoice of this schedule and is derived.++The agreed price lives in **terms**, not on the schedule. A retainer+that goes from 3,000 to 3,500 in January is one agreement with two+terms, each saying from when it applies. That is what makes "what was+the deal in May" answerable without an invoice having been issued in+May, and what lets a raise be recorded today and take effect on the+next full period. Nothing is ever prorated: a change applies from a+period boundary, and a mid-period difference is an ordinary one-off+invoice or credit note.++This engine is its own, and is deliberately not `RecurringTransaction`.+That one materialises *placeholder transactions*, which matching+excludes because placeholders are not real money. A retainer emitting a+placeholder while matching binds real inflows to its invoice would make+the same expected money exist twice.+"""+import uuid+from datetime import date as _date, datetime, timezone+from decimal import Decimal+from typing import TYPE_CHECKING, Any, Optional++from sqlalchemy import (+ CheckConstraint,+ Date,+ DateTime,+ ForeignKey,+ Index,+ Integer,+ JSON,+ Numeric,+ String,+ Text,+ UniqueConstraint,+)+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.invoice import Invoice+ from app.models.payee import Payee+++#: Decisions a human takes about an agreement. Closed, decisions only.+#:+#: active: emitting. The job generates the next period when it is due.+#: paused: kept, not emitting. A person paused it, or the job did+#: after repeated failures (see `pause_reason`).+#: ended: over. Terminal; carries `ended_at` and `end_reason`.+#:+#: `past_due` is deliberately absent: it is a fact about this schedule's+#: invoices, derived from them.+SCHEDULE_STATUSES = ("active", "paused", "ended")++#: Why an agreement ended. The one place a schedule records something+#: an invoice cannot: churn has a date and a side, and neither is+#: derivable from the invoices that stopped coming.+SCHEDULE_END_REASONS = (+ "canceled_by_client",+ "canceled_by_us",+ "completed", # ran its term: `after_count` reached or `end_date` passed+ "unpaid",+ "other",+)++#: Why a schedule is paused. `failures` is the job giving up so a broken+#: agreement stops instead of retrying forever; `manual` is a person.+SCHEDULE_PAUSE_REASONS = ("manual", "failures")++#: Same vocabulary as recurring transactions, so the two pickers in the+#: product agree on what a word means.+SCHEDULE_FREQUENCIES = ("weekly", "biweekly", "monthly", "quarterly", "semiannual", "yearly")++#: How an agreement knows it is over. `never` runs until ended by hand.+SCHEDULE_END_TYPES = ("never", "on_date", "after_count")++#: Who authored the agreement. An `imported` schedule mirrors one a+#: gateway holds (a Stripe subscription): that system owns the terms and+#: emits the invoices, Securo groups them and owns the cash. The job+#: never generates for an imported schedule.+SCHEDULE_ORIGINS = ("local", "imported")++#: How many periods each frequency puts in a year, used to normalise+#: any schedule to a monthly figure. Weekly and biweekly are 52 and 26+#: periods over twelve months, not 4 and 2 per month, because a month+#: is not four weeks and the difference is 8% a year.+PERIODS_PER_YEAR: dict[str, Decimal] = {+ "weekly": Decimal("52"),+ "biweekly": Decimal("26"),+ "monthly": Decimal("12"),+ "quarterly": Decimal("4"),+ "semiannual": Decimal("2"),+ "yearly": Decimal("1"),+}++#: After this many consecutive failures the job pauses the schedule+#: rather than retrying it daily forever.+MAX_CONSECUTIVE_FAILURES = 3+++class InvoiceSchedule(Base):+ """One agreement with one client to bill them every period."""++ __tablename__ = "invoice_schedules"+ __table_args__ = (+ # A mirrored gateway subscription is identified by the source's+ # own id, so two syncs converge on one row (same rule as invoices).+ UniqueConstraint(+ "workspace_id",+ "external_source",+ "external_id",+ name="uq_invoice_schedules_workspace_external",+ ),+ # The job reads active schedules due on or before today. Nothing+ # else lists by this pair, so it is the only composite index.+ Index("ix_invoice_schedules_workspace_status", "workspace_id", "status"),+ CheckConstraint(+ "status IN ('active', 'paused', 'ended')", name="ck_invoice_schedules_status"+ ),+ CheckConstraint(+ "origin IN ('local', 'imported')", name="ck_invoice_schedules_origin"+ ),+ CheckConstraint(+ "frequency IN ('weekly', 'biweekly', 'monthly', 'quarterly', 'semiannual', 'yearly')",+ name="ck_invoice_schedules_frequency",+ ),+ CheckConstraint(+ "end_type IN ('never', 'on_date', 'after_count')",+ name="ck_invoice_schedules_end_type",+ ),+ # An end condition has to say what it is conditioned on. Written+ # as a constraint so no code path can leave `on_date` without a+ # date and have the job run forever.+ CheckConstraint(+ "(end_type = 'never')"+ " OR (end_type = 'on_date' AND end_date IS NOT NULL)"+ " OR (end_type = 'after_count' AND end_count IS NOT NULL AND end_count > 0)",+ name="ck_invoice_schedules_end_condition",+ ),+ CheckConstraint(+ "end_reason IS NULL OR end_reason IN"+ " ('canceled_by_client', 'canceled_by_us', 'completed', 'unpaid', 'other')",+ name="ck_invoice_schedules_end_reason",+ ),+ CheckConstraint(+ "pause_reason IS NULL OR pause_reason IN ('manual', 'failures')",+ name="ck_invoice_schedules_pause_reason",+ ),+ # An ended schedule says when and why; a live one says neither.+ CheckConstraint(+ "(status = 'ended' AND ended_at IS NOT NULL AND end_reason IS NOT NULL)"+ " OR (status <> 'ended' AND ended_at IS NULL AND end_reason IS NULL)",+ name="ck_invoice_schedules_ended_fields",+ ),+ CheckConstraint("next_sequence >= 1", name="ck_invoice_schedules_next_sequence"),+ CheckConstraint(+ "payment_terms_days IS NULL OR payment_terms_days >= 0",+ name="ck_invoice_schedules_payment_terms",+ ),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ # Who created it. Not an owner: the agreement belongs to the+ # workspace and outlives any member.+ user_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id"), nullable=True+ )+ # RESTRICT for the same reason as on invoices: deleting a client must+ # never silently delete the record of what they agreed to pay.+ payee_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("payees.id", ondelete="RESTRICT"), nullable=True, index=True+ )++ # What the agreement is called: "Plano Pro", "Retainer mensal". The+ # invoices it emits carry the client's name; this is for the list of+ # agreements, where a client may have more than one.+ name: Mapped[str] = mapped_column(String(200))++ origin: Mapped[str] = mapped_column(String(20), default="local", server_default="local")+ external_source: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)++ status: Mapped[str] = mapped_column(String(20), default="active", server_default="active")+ pause_reason: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)+ ended_at: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)+ end_reason: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)++ # The calendar. `start_date` is the anchor: period `n` (1-based)+ # starts at `start_date` advanced `n - 1` periods, with the day of+ # month clamped in shorter months and recovered afterwards, exactly+ # as recurring transactions do it. Both are frozen once an invoice+ # exists under the schedule, because moving the anchor would change+ # what period every existing invoice answers for.+ frequency: Mapped[str] = mapped_column(String(20))+ start_date: Mapped[_date] = mapped_column(Date)+ end_type: Mapped[str] = mapped_column(String(20), default="never", server_default="never")+ end_date: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)+ end_count: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)++ # Null means the workspace default at the moment each invoice is+ # generated, so a change in settings reaches every retainer that+ # never said otherwise.+ payment_terms_days: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ currency: Mapped[str] = mapped_column(String(3), default="USD")++ # Copied onto every generated invoice. The lines are not here: they+ # belong to a term, because they change and these do not.+ notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ custom_fields: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)++ # Engine state. `next_sequence` is the period the job will emit+ # next; every period below it is either already an invoice or was+ # deliberately skipped when the schedule was created with a start in+ # the past (those are history, linked by hand if the user wants+ # them). Together with the unique `(schedule_id, sequence)` on+ # invoices it is what makes a retried job a no-op.+ next_sequence: Mapped[int] = mapped_column(Integer, default=1, server_default="1")+ last_generated_at: Mapped[Optional[datetime]] = mapped_column(+ DateTime(timezone=True), nullable=True+ )+ consecutive_failures: Mapped[int] = mapped_column(Integer, default=0, server_default="0")++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(timezone.utc),+ onupdate=lambda: datetime.now(timezone.utc),+ )++ payee: Mapped[Optional["Payee"]] = relationship(lazy="joined")+ terms: Mapped[list["InvoiceScheduleTerm"]] = relationship(+ back_populates="schedule",+ cascade="all, delete-orphan",+ order_by="InvoiceScheduleTerm.effective_from",+ lazy="selectin",+ )+ # Not cascaded: the invoices are money and outlive the agreement.+ # The foreign key is SET NULL, so deleting a schedule orphans its+ # invoices rather than deleting a record of what was owed; the+ # service refuses the delete when any exist anyway.+ invoices: Mapped[list["Invoice"]] = relationship(+ back_populates="schedule",+ order_by="Invoice.sequence",+ lazy="noload",+ )+++class InvoiceScheduleTerm(Base):+ """What the agreement says from a given date on.++ One row per change of price. The job picks, for each period, the+ term with the latest `effective_from` on or before the period start,+ so a raise recorded in September for January changes nothing until+ January and every January invoice says 3,500 without anybody+ remembering to do anything.++ Lines are snapshotted as JSON in the same shape `InvoiceLineInput`+ accepts, and copied into real `invoice_lines` rows at generation.+ The invoice, not the term, is the record of what was actually+ billed: editing a future term rewrites nothing that was issued.+ """++ __tablename__ = "invoice_schedule_terms"+ __table_args__ = (+ # Two prices from the same day would be two answers to "what does+ # this cost", and the job would have to pick one arbitrarily.+ UniqueConstraint(+ "schedule_id", "effective_from", name="uq_invoice_schedule_terms_effective_from"+ ),+ Index("ix_invoice_schedule_terms_schedule", "schedule_id"),+ CheckConstraint("discount >= 0", name="ck_invoice_schedule_terms_discount"),+ CheckConstraint("total >= 0", name="ck_invoice_schedule_terms_total"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ schedule_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("invoice_schedules.id", ondelete="CASCADE")+ )+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ effective_from: Mapped[_date] = mapped_column(Date)+ lines: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list)+ discount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ # Derived from the lines at write time and stored so recurring+ # revenue is one SUM over this table rather than a walk through+ # every term's JSON. Recomputed whenever the lines change; never+ # accepted from a caller.+ subtotal: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ tax_total: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ total: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ schedule: Mapped["InvoiceSchedule"] = relationship(back_populates="terms")diff --git a/backend/app/schemas/invoice.py b/backend/app/schemas/invoice.pyindex 8e2edfd3..dc71b961 100644--- a/backend/app/schemas/invoice.py+++ b/backend/app/schemas/invoice.py@@ -138,6 +138,17 @@ class InvoicePayee(BaseModel):model_config = ConfigDict(from_attributes=True)+class InvoiceScheduleRef(BaseModel):+ """Just enough of the agreement to label the invoice with it."""++ id: uuid.UUID+ name: str+ frequency: str+ status: str++ model_config = ConfigDict(from_attributes=True)++class InvoiceRead(BaseModel):id: uuid.UUIDpayee_id: Optional[uuid.UUID]@@ -176,6 +187,13 @@ class InvoiceRead(BaseModel):#: can open. Null until someone asks for one, and null again once#: revoked.share_token: Optional[str] = None+ #: Which agreement and period this invoice answers for, when it+ #: was born from or linked to one. Provenance only.+ schedule_id: Optional[uuid.UUID] = None+ schedule: Optional[InvoiceScheduleRef] = None+ sequence: Optional[int] = None+ period_start: Optional[_Date] = None+ period_end: Optional[_Date] = Nonelines: list[InvoiceLineRead] = []allocations: list[InvoiceAllocationRead] = []created_at: datetimediff --git a/backend/app/schemas/invoice_schedule.py b/backend/app/schemas/invoice_schedule.pynew file mode 100644index 00000000..9aecd6c7--- /dev/null+++ b/backend/app/schemas/invoice_schedule.py@@ -0,0 +1,178 @@+import uuid+from datetime import date as _Date, datetime+from decimal import Decimal+from typing import Any, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from app.schemas.invoice import InvoiceLineInput, InvoicePayee++#: Decisions a human took about an agreement. Never PATCHed as a string:+#: each changes through the action that causes it (`/pause`, `/end`).+ScheduleStatus = Literal["active", "paused", "ended"]+ScheduleFrequency = Literal["weekly", "biweekly", "monthly", "quarterly", "semiannual", "yearly"]+ScheduleEndType = Literal["never", "on_date", "after_count"]+ScheduleEndReason = Literal["canceled_by_client", "canceled_by_us", "completed", "unpaid", "other"]+SchedulePauseReason = Literal["manual", "failures"]+ScheduleOrigin = Literal["local", "imported"]+++class ScheduleTermInput(BaseModel):+ effective_from: _Date+ lines: list[InvoiceLineInput] = Field(..., min_length=1)+ discount: Optional[Decimal] = Field(default=None, ge=0)+++class ScheduleTermUpdate(BaseModel):+ effective_from: Optional[_Date] = None+ lines: Optional[list[InvoiceLineInput]] = Field(default=None, min_length=1)+ discount: Optional[Decimal] = Field(default=None, ge=0)+++class ScheduleTermRead(BaseModel):+ id: uuid.UUID+ effective_from: _Date+ lines: list[dict[str, Any]]+ discount: Decimal+ subtotal: Decimal+ tax_total: Decimal+ total: Decimal+ created_at: datetime++ model_config = ConfigDict(from_attributes=True)+++class ScheduleCreate(BaseModel):+ name: str = Field(..., min_length=1, max_length=200)+ payee_id: Optional[uuid.UUID] = None+ frequency: ScheduleFrequency+ #: Defaults to today. The anchor: every period is counted from it.+ start_date: Optional[_Date] = None+ end_type: ScheduleEndType = "never"+ end_date: Optional[_Date] = None+ end_count: Optional[int] = Field(default=None, ge=1)+ #: Null means the workspace default at each generation.+ payment_terms_days: Optional[int] = Field(default=None, ge=0)+ currency: Optional[str] = Field(default=None, max_length=3)+ notes: Optional[str] = None+ custom_fields: Optional[dict[str, Any]] = None+ #: The first term, in force from `start_date`.+ lines: list[InvoiceLineInput] = Field(..., min_length=1)+ discount: Optional[Decimal] = Field(default=None, ge=0)+ origin: Optional[ScheduleOrigin] = None+ external_source: Optional[str] = Field(default=None, max_length=50)+ external_id: Optional[str] = Field(default=None, max_length=255)+++class ScheduleUpdate(BaseModel):+ name: Optional[str] = Field(default=None, min_length=1, max_length=200)+ payee_id: Optional[uuid.UUID] = None+ #: Fixed once an invoice exists under the agreement.+ frequency: Optional[ScheduleFrequency] = None+ start_date: Optional[_Date] = None+ currency: Optional[str] = Field(default=None, max_length=3)+ end_type: Optional[ScheduleEndType] = None+ end_date: Optional[_Date] = None+ end_count: Optional[int] = Field(default=None, ge=1)+ payment_terms_days: Optional[int] = Field(default=None, ge=0)+ notes: Optional[str] = None+ custom_fields: Optional[dict[str, Any]] = None+++class ScheduleEnd(BaseModel):+ reason: ScheduleEndReason = "other"+ #: Defaults to today.+ ended_at: Optional[_Date] = None+++class ScheduleLinkInvoice(BaseModel):+ invoice_id: uuid.UUID+ #: Must be the first day of one of this agreement's periods.+ period_start: _Date+++class MakeRecurring(BaseModel):+ """Turn an issued invoice into period one of a new agreement."""++ frequency: ScheduleFrequency+ #: Defaults to the invoice's own date. Earlier makes the invoice a+ #: later period, so the ones before it can be linked as history.+ start_date: Optional[_Date] = None+ #: Defaults to the first line's description, then the client's name.+ name: Optional[str] = Field(default=None, max_length=200)+ end_type: ScheduleEndType = "never"+ end_date: Optional[_Date] = None+ end_count: Optional[int] = Field(default=None, ge=1)+ #: Defaults to the invoice's own issue-to-due gap.+ payment_terms_days: Optional[int] = Field(default=None, ge=0)+++class ScheduleRead(BaseModel):+ id: uuid.UUID+ name: str+ payee_id: Optional[uuid.UUID]+ payee: Optional[InvoicePayee] = None+ origin: str+ external_source: Optional[str] = None+ external_id: Optional[str] = None+ status: ScheduleStatus+ pause_reason: Optional[SchedulePauseReason] = None+ ended_at: Optional[_Date] = None+ end_reason: Optional[ScheduleEndReason] = None+ frequency: ScheduleFrequency+ start_date: _Date+ end_type: ScheduleEndType+ end_date: Optional[_Date] = None+ end_count: Optional[int] = None+ payment_terms_days: Optional[int] = None+ currency: str+ notes: Optional[str] = None+ custom_fields: Optional[dict[str, Any]] = None+ next_sequence: int+ last_generated_at: Optional[datetime] = None+ consecutive_failures: int+ terms: list[ScheduleTermRead] = []+ created_at: datetime++ #: The derived answers. `api/invoice_schedules.py::_serialize` is the+ #: sole constructor and fills every one; the defaults only let the+ #: ORM row validate first. None of them is ever stored.+ current_term: Optional[ScheduleTermRead] = None+ #: The term the next emitted period will be priced by, which differs+ #: from `current_term` only when a raise is recorded ahead.+ next_term: Optional[ScheduleTermRead] = None+ monthly_amount: Decimal = Decimal("0")+ next_period_start: Optional[_Date] = None+ invoice_count: int = 0+ amount_invoiced: Decimal = Decimal("0")+ amount_paid: Decimal = Decimal("0")+ past_due_count: int = 0++ model_config = ConfigDict(from_attributes=True)+++class ScheduleCurrencySummary(BaseModel):+ currency: str+ monthly_recurring: Decimal+ active_count: int+ ended_recently_count: int+ monthly_lost: Decimal+ past_due_count: int+++class ScheduleSummaryRead(BaseModel):+ active_count: int+ paused_count: int+ ended_count: int+ by_currency: list[ScheduleCurrencySummary]+++class SchedulePeriodRead(BaseModel):+ """One period as a label: for the picker that asks "which period is+ this invoice for"."""++ sequence: int+ period_start: _Date+ period_end: _Date+ #: Whether an invoice already answers for it.+ taken: booldiff --git a/backend/app/services/invoice_forecast_service.py b/backend/app/services/invoice_forecast_service.pyindex a3389fdd..cc51057d 100644--- a/backend/app/services/invoice_forecast_service.py+++ b/backend/app/services/invoice_forecast_service.py@@ -122,7 +122,7 @@ async def claims_in_range(query = query.where(Invoice.direction.in_(directions))rows = (await session.execute(query)).all()- return [+ claims = [Claim(due_date=row.due_date,currency=row.currency or "USD",@@ -131,3 +131,27 @@ async def claims_in_range()for row in rows]++ # Periods of a recurring agreement that no invoice answers for yet.+ # Same money as the invoice the job will emit for them, and the two+ # never coexist: a period is projected only from the cursor on, and+ # the cursor moves the moment the invoice exists. Receivable only,+ # because that is the only side an agreement emits today.+ if directions is None or "receivable" in directions:+ # Imported lazily: the schedule service reads invoices and the+ # ledger, and this module is read by the dashboard and reports.+ # A top-level import would tie the two directions into a cycle.+ from app.services import invoice_schedule_service++ for period in await invoice_schedule_service.projected_periods(+ session, workspace_id, range_start, range_end+ ):+ claims.append(+ Claim(+ due_date=period.due_date,+ currency=period.currency,+ amount=period.amount,+ direction="receivable",+ )+ )+ return claimsdiff --git a/backend/app/services/invoice_schedule_service.py b/backend/app/services/invoice_schedule_service.pynew file mode 100644index 00000000..1a755a9e--- /dev/null+++ b/backend/app/services/invoice_schedule_service.py@@ -0,0 +1,1193 @@+"""Recurring invoices: the agreement, its price over time, and the job.++The organising rule is the ledger's own, applied one level up: **the+schedule is an agreement, the invoice is the money**. Nothing here+counts as revenue, owed or paid; every such figure is computed from the+invoices a schedule emitted or was given. What the schedule adds is the+one thing invoices cannot say: what was agreed, from when, and when and+why it stopped.++## Periods++Period `n` (1-based) starts at `start_date` advanced `n - 1` times by+the frequency, day of month clamped in shorter months and recovered+afterwards, and ends the day before period `n + 1` starts. That is all+the calendar there is: no separate "next run" date to drift, no+timezone 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.++## Terms++The price is a list of terms, each `effective_from` a date. A period is+priced by the latest term on or before its start. A term may be added,+changed or removed only while no invoice answers for a period it+governs; once one does, the term is history and history is not edited.+There is no proration by design: a change applies from a period+boundary, and a mid-period difference is an ordinary one-off invoice.++## The cursor++`next_sequence` is the period the job emits next. At creation it is the+first period starting on or after today: a schedule anchored in the+past does not back-fill months the user may have billed by hand (those+are linked, see `link_invoice`). Together with the unique+`(schedule_id, sequence)` on invoices, the cursor is what makes a+retried or doubled job a no-op.+"""+from __future__ import annotations++import logging+import uuid+from dataclasses import dataclass+from datetime import date as _date, datetime, timedelta, timezone+from decimal import Decimal+from typing import Any, Optional++from sqlalchemy import func, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.invoice import Invoice, InvoiceAllocation, InvoiceSettings+from app.models.invoice_schedule import (+ MAX_CONSECUTIVE_FAILURES,+ PERIODS_PER_YEAR,+ SCHEDULE_END_REASONS,+ SCHEDULE_END_TYPES,+ SCHEDULE_FREQUENCIES,+ InvoiceSchedule,+ InvoiceScheduleTerm,+)+from app.models.workspace import Workspace+from app.services import invoice_archive, invoice_service, reconciliation_service+from app.services.invoice_service import InvoiceError+from app.services.recurring_transaction_service import _advance_date++logger = logging.getLogger(__name__)++ZERO = Decimal("0.00")+CENT = Decimal("0.01")++#: How many periods one run may emit for one schedule. The cursor+#: starts at today, so this only matters when the worker was down for+#: a while; the cap keeps a schedule that somehow fell far behind from+#: flooding a workspace in one pass, and the next run continues.+MAX_PERIODS_PER_RUN = 12++#: A guard on every calendar walk. A weekly schedule looked at ten+#: years out is 520 steps; nothing legitimate needs more.+_MAX_WALK = 1000+++def _today() -> _date:+ return datetime.now(timezone.utc).date()+++# ---------------------------------------------------------------------------+# The calendar+# ---------------------------------------------------------------------------+def period_start(schedule: InvoiceSchedule, sequence: int) -> _date:+ """The first day of period `sequence` (1-based)."""+ if sequence < 1:+ raise ValueError("sequence is 1-based")+ current = schedule.start_date+ for _ in range(sequence - 1):+ current = _advance_date(current, schedule.frequency, intended_day=schedule.start_date.day)+ return current+++def period_bounds(schedule: InvoiceSchedule, sequence: int) -> tuple[_date, _date]:+ """First and last day of a period, both inclusive."""+ start = period_start(schedule, sequence)+ following = _advance_date(start, schedule.frequency, intended_day=schedule.start_date.day)+ return start, following - timedelta(days=1)+++def first_sequence_on_or_after(schedule: InvoiceSchedule, floor: _date) -> int:+ """The first period starting on or after `floor`."""+ sequence = 1+ current = schedule.start_date+ while current < floor and sequence < _MAX_WALK:+ current = _advance_date(current, schedule.frequency, intended_day=schedule.start_date.day)+ sequence += 1+ return sequence+++def sequence_for_period_start(schedule: InvoiceSchedule, start: _date) -> Optional[int]:+ """Which period starts on `start`, or None if no period does.++ The inverse of `period_start`, used when a person points at an+ invoice and says "this is September": the date has to be a real+ boundary of this schedule, not a day somewhere inside a period.+ """+ if start < schedule.start_date:+ return None+ sequence = first_sequence_on_or_after(schedule, start)+ return sequence if period_start(schedule, sequence) == start else None+++def period_within_end(schedule: InvoiceSchedule, sequence: int) -> bool:+ """Whether the agreement still covers period `sequence`."""+ if schedule.end_type == "after_count":+ return sequence <= (schedule.end_count or 0)+ if schedule.end_type == "on_date":+ return period_start(schedule, sequence) <= (schedule.end_date or schedule.start_date)+ return True+++def next_period_start(schedule: InvoiceSchedule) -> Optional[_date]:+ """When the next invoice would be dated, or None if the agreement+ has nothing left to emit."""+ if schedule.status == "ended" or not period_within_end(schedule, schedule.next_sequence):+ return None+ return period_start(schedule, schedule.next_sequence)+++# ---------------------------------------------------------------------------+# Terms+# ---------------------------------------------------------------------------+def term_for(schedule: InvoiceSchedule, on: _date) -> Optional[InvoiceScheduleTerm]:+ """The term in force on a date: the latest one starting on or before it."""+ chosen: Optional[InvoiceScheduleTerm] = None+ for term in schedule.terms:+ if term.effective_from <= on and (chosen is None or term.effective_from > chosen.effective_from):+ chosen = term+ return chosen+++def current_term(schedule: InvoiceSchedule, today: Optional[_date] = None) -> Optional[InvoiceScheduleTerm]:+ return term_for(schedule, today or _today())+++def upcoming_terms(schedule: InvoiceSchedule, today: Optional[_date] = None) -> list[InvoiceScheduleTerm]:+ """Terms that have not started yet: the recorded raises."""+ today = today or _today()+ return [t for t in schedule.terms if t.effective_from > today]+++def monthly_amount(schedule: InvoiceSchedule, term: Optional[InvoiceScheduleTerm]) -> Decimal:+ """What this agreement is worth per month at a given term.++ A weekly retainer is not four times its amount: it is 52 periods+ over 12 months. Normalising through the year is what makes a+ quarterly and a monthly agreement add up to one honest figure.+ """+ if term is None:+ return ZERO+ per_year = PERIODS_PER_YEAR[schedule.frequency]+ return (Decimal(term.total) * per_year / Decimal("12")).quantize(CENT)+++def _term_totals(lines: list[dict[str, Any]], discount: Decimal) -> tuple[Decimal, Decimal, Decimal]:+ """Subtotal, tax and total of a term's lines, exactly as the invoice+ will compute them at generation. Same arithmetic as+ `invoice_service._recompute_totals`, on dicts instead of rows."""+ subtotal = ZERO+ tax_total = ZERO+ for line in lines:+ quantity = Decimal(str(line.get("quantity", 1)))+ unit_price = Decimal(str(line.get("unit_price", 0)))+ line_total = (quantity * unit_price).quantize(CENT)+ subtotal += line_total+ if line.get("tax_rate") is not None:+ tax_total += (line_total * Decimal(str(line["tax_rate"])) / Decimal("100")).quantize(CENT)+ total = subtotal - discount + tax_total+ if total < ZERO:+ raise InvoiceError(+ "discount_exceeds_total", "The discount is larger than the amount being billed"+ )+ return subtotal, tax_total, total+++def _normalise_lines(lines: Any) -> list[dict[str, Any]]:+ """Lines as they will be stored: plain JSON, decimals as strings."""+ if not lines:+ raise InvoiceError("term_lines_required", "A term needs at least one line")+ out: list[dict[str, Any]] = []+ for raw in lines:+ line = dict(raw)+ if not line.get("description"):+ raise InvoiceError("term_lines_required", "Every line needs a description")+ out.append(+ {+ "description": line["description"],+ "quantity": str(Decimal(str(line.get("quantity", 1)))),+ "unit": line.get("unit") or None,+ "unit_price": str(Decimal(str(line.get("unit_price", 0)))),+ "tax_rate": (+ str(Decimal(str(line["tax_rate"]))) if line.get("tax_rate") is not None else None+ ),+ }+ )+ return out+++def _fill_term(term: InvoiceScheduleTerm, lines: Any, discount: Any) -> None:+ term.lines = _normalise_lines(lines)+ term.discount = Decimal(str(discount or 0))+ if term.discount < ZERO:+ raise InvoiceError("negative_discount", "A discount cannot be negative")+ term.subtotal, term.tax_total, term.total = _term_totals(term.lines, term.discount)+ # A zero-value term would emit invoices the ledger refuses to issue.+ # Refused here, where the person can fix it, instead of on the day+ # the job trips over it.+ if term.total <= ZERO:+ raise InvoiceError("term_empty", "A term must bill something")+++async def _latest_linked_period_start(+ session: AsyncSession, schedule_id: uuid.UUID+) -> Optional[_date]:+ result = await session.execute(+ select(func.max(Invoice.period_start)).where(Invoice.schedule_id == schedule_id)+ )+ return result.scalar_one_or_none()+++async def _assert_term_editable(+ session: AsyncSession, schedule: InvoiceSchedule, effective_from: _date+) -> None:+ """A term governs every period starting on or after its date. Once+ an invoice exists for such a period, the term is history."""+ latest = await _latest_linked_period_start(session, schedule.id)+ if latest is not None and latest >= effective_from:+ raise InvoiceError(+ "term_in_use",+ "An invoice was already issued under this term; add a new term from a later date",+ )+++async def add_term(+ session: AsyncSession,+ schedule: InvoiceSchedule,+ *,+ effective_from: _date,+ lines: Any,+ discount: Any = None,+) -> InvoiceScheduleTerm:+ """Record what the agreement says from a date on.++ Adding on a date that already has a term replaces that term, so+ "actually, make January 3,600 not 3,500" is one call and not a+ delete plus a create. Either way the date must be one no invoice+ has been issued under.+ """+ if schedule.status == "ended":+ raise InvoiceError("schedule_ended", "An ended agreement takes no new terms")+ if effective_from < schedule.start_date:+ raise InvoiceError(+ "term_before_start", "A term cannot start before the agreement does"+ )+ await _assert_term_editable(session, schedule, effective_from)++ existing = next((t for t in schedule.terms if t.effective_from == effective_from), None)+ term = existing or InvoiceScheduleTerm(+ schedule_id=schedule.id,+ workspace_id=schedule.workspace_id,+ effective_from=effective_from,+ )+ _fill_term(term, lines, discount)+ if existing is None:+ session.add(term)+ schedule.terms.append(term)+ await session.flush()+ return term+++async def update_term(+ session: AsyncSession,+ schedule: InvoiceSchedule,+ term: InvoiceScheduleTerm,+ *,+ lines: Any = None,+ discount: Any = None,+ effective_from: Optional[_date] = None,+) -> InvoiceScheduleTerm:+ if term.schedule_id != schedule.id:+ raise InvoiceError("term_not_found", "Term not found on this agreement", 404)+ await _assert_term_editable(session, schedule, term.effective_from)+ if effective_from is not None and effective_from != term.effective_from:+ # The term in force from the start is what prices the first+ # periods. Moving it later would leave them with no price, and+ # the job would fail on each until it paused the agreement.+ if term.effective_from == schedule.start_date:+ raise InvoiceError("first_term", "The price in force from the start cannot be moved")+ if effective_from < schedule.start_date:+ raise InvoiceError(+ "term_before_start", "A term cannot start before the agreement does"+ )+ await _assert_term_editable(session, schedule, effective_from)+ if any(t.effective_from == effective_from for t in schedule.terms if t.id != term.id):+ raise InvoiceError("term_date_taken", "Another term already starts on that date", 409)+ term.effective_from = effective_from+ _fill_term(+ term,+ lines if lines is not None else term.lines,+ discount if discount is not None else term.discount,+ )+ await session.flush()+ return term+++async def delete_term(+ session: AsyncSession, schedule: InvoiceSchedule, term: InvoiceScheduleTerm+) -> None:+ if term.schedule_id != schedule.id:+ raise InvoiceError("term_not_found", "Term not found on this agreement", 404)+ if len(schedule.terms) <= 1:+ raise InvoiceError("last_term", "An agreement needs at least one term")+ if term.effective_from == schedule.start_date:+ raise InvoiceError("first_term", "The price in force from the start cannot be removed")+ await _assert_term_editable(session, schedule, term.effective_from)+ schedule.terms.remove(term)+ await session.delete(term)+ await session.flush()+++# ---------------------------------------------------------------------------+# Reading+# ---------------------------------------------------------------------------+async def get_schedule(+ session: AsyncSession, schedule_id: uuid.UUID, workspace_id: uuid.UUID+) -> Optional[InvoiceSchedule]:+ result = await session.execute(+ select(InvoiceSchedule).where(+ InvoiceSchedule.id == schedule_id, InvoiceSchedule.workspace_id == workspace_id+ )+ )+ return result.unique().scalar_one_or_none()+++async def find_by_external_id(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ external_source: Optional[str],+ external_id: Optional[str],+) -> Optional[InvoiceSchedule]:+ if not external_source or not external_id:+ return None+ result = await session.execute(+ select(InvoiceSchedule).where(+ InvoiceSchedule.workspace_id == workspace_id,+ InvoiceSchedule.external_source == external_source,+ InvoiceSchedule.external_id == external_id,+ )+ )+ return result.unique().scalar_one_or_none()+++async def list_schedules(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ *,+ status: Optional[str] = None,+ payee_id: Optional[uuid.UUID] = None,+) -> list[InvoiceSchedule]:+ query = select(InvoiceSchedule).where(InvoiceSchedule.workspace_id == workspace_id)+ if status:+ query = query.where(InvoiceSchedule.status == status)+ if payee_id:+ query = query.where(InvoiceSchedule.payee_id == payee_id)+ query = query.order_by(InvoiceSchedule.created_at.desc())+ result = await session.execute(query)+ return list(result.unique().scalars().all())+++@dataclass(frozen=True)+class ScheduleFigures:+ """What the invoices say about one agreement. Never stored."""++ invoice_count: int+ amount_invoiced: Decimal+ amount_paid: Decimal+ past_due_count: int+++async def figures_for(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ schedule_ids: list[uuid.UUID],+ today: Optional[_date] = None,+) -> dict[uuid.UUID, ScheduleFigures]:+ """The derived money facts for many schedules in two queries.++ Void and uncollectible invoices count towards nothing here, for the+ same reason they read as zero everywhere else. Drafts are counted as+ invoices but not as money, since nothing is owed yet.+ """+ today = today or _today()+ empty = ScheduleFigures(0, ZERO, ZERO, 0)+ if not schedule_ids:+ return {}++ allocated = (+ select(+ InvoiceAllocation.invoice_id.label("invoice_id"),+ func.coalesce(func.sum(InvoiceAllocation.amount), 0).label("paid"),+ )+ .group_by(InvoiceAllocation.invoice_id)+ .subquery()+ )+ rows = (+ await session.execute(+ select(+ Invoice.schedule_id,+ Invoice.status,+ Invoice.due_date,+ Invoice.total,+ func.coalesce(allocated.c.paid, 0).label("paid"),+ )+ .outerjoin(allocated, allocated.c.invoice_id == Invoice.id)+ .where(+ Invoice.workspace_id == workspace_id,+ Invoice.schedule_id.in_(schedule_ids),+ )+ )+ ).all()++ counts: dict[uuid.UUID, dict[str, Any]] = {}+ for row in rows:+ acc = counts.setdefault(+ row.schedule_id,+ {"n": 0, "invoiced": ZERO, "paid": ZERO, "past_due": 0},+ )+ acc["n"] += 1+ if row.status != "open":+ continue+ total = Decimal(str(row.total))+ paid = Decimal(str(row.paid))+ acc["invoiced"] += total+ acc["paid"] += min(paid, total)+ if row.due_date < today and paid < total:+ acc["past_due"] += 1++ return {+ sid: ScheduleFigures(+ invoice_count=acc["n"],+ amount_invoiced=acc["invoiced"],+ amount_paid=acc["paid"],+ past_due_count=acc["past_due"],+ )+ if (acc := counts.get(sid))+ else empty+ for sid in schedule_ids+ }+++@dataclass(frozen=True)+class CurrencySummary:+ currency: str+ #: Monthly recurring revenue: every active agreement at its current+ #: term, normalised to a month.+ monthly_recurring: Decimal+ active_count: int+ #: Agreements that ended in the trailing 30 days, and what they were+ #: worth per month when they did. The churn figure.+ ended_recently_count: int+ monthly_lost: Decimal+ #: Active agreements with at least one invoice past its due date.+ past_due_count: int+++@dataclass(frozen=True)+class ScheduleSummary:+ active_count: int+ paused_count: int+ ended_count: int+ by_currency: list[CurrencySummary]+++async def summary(+ session: AsyncSession, workspace_id: uuid.UUID, today: Optional[_date] = None+) -> ScheduleSummary:+ today = today or _today()+ schedules = await list_schedules(session, workspace_id)+ active = [s for s in schedules if s.status == "active"]+ figures = await figures_for(session, workspace_id, [s.id for s in active], today)+ since = today - timedelta(days=30)++ buckets: dict[str, dict[str, Any]] = {}++ def bucket(currency: str) -> dict[str, Any]:+ return buckets.setdefault(+ currency,+ {"mrr": ZERO, "active": 0, "ended": 0, "lost": ZERO, "past_due": 0},+ )++ for s in schedules:+ if s.status == "active":+ b = bucket(s.currency)+ b["mrr"] += monthly_amount(s, term_for(s, today))+ b["active"] += 1+ if figures[s.id].past_due_count:+ b["past_due"] += 1+ elif s.status == "ended" and s.ended_at and since <= s.ended_at <= today:+ b = bucket(s.currency)+ b["ended"] += 1+ b["lost"] += monthly_amount(s, term_for(s, s.ended_at))++ return ScheduleSummary(+ active_count=len(active),+ paused_count=sum(1 for s in schedules if s.status == "paused"),+ ended_count=sum(1 for s in schedules if s.status == "ended"),+ by_currency=[+ CurrencySummary(+ currency=currency,+ monthly_recurring=b["mrr"],+ active_count=b["active"],+ ended_recently_count=b["ended"],+ monthly_lost=b["lost"],+ past_due_count=b["past_due"],+ )+ for currency, b in sorted(buckets.items())+ ],+ )+++# ---------------------------------------------------------------------------+# Writing the agreement+# ---------------------------------------------------------------------------+def _validate_end(end_type: str, end_date: Optional[_date], end_count: Optional[int]) -> None:+ if end_type not in SCHEDULE_END_TYPES:+ raise InvoiceError("invalid_end_type", "Unknown end condition")+ if end_type == "on_date" and end_date is None:+ raise InvoiceError("end_date_required", "Say on which date the agreement ends")+ if end_type == "after_count" and (end_count is None or end_count < 1):+ raise InvoiceError("end_count_required", "Say after how many invoices the agreement ends")+++async def _assert_payee(+ session: AsyncSession, payee_id: Optional[uuid.UUID], workspace_id: uuid.UUID+) -> None:+ await invoice_service._assert_payee(session, payee_id, workspace_id)+++async def create_schedule(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: Optional[uuid.UUID],+ data: dict[str, Any],+ today: Optional[_date] = None,+) -> InvoiceSchedule:+ """A new agreement with its first term.++ The cursor starts at the first period on or after today. A start in+ the past is allowed (the retainer began in March) and does not+ back-fill: the months already billed by hand are linked with+ `link_invoice`, and the job takes over from here.+ """+ today = today or _today()+ frequency = data.get("frequency")+ if frequency not in SCHEDULE_FREQUENCIES:+ raise InvoiceError("invalid_frequency", "Unknown frequency")+ start_date = data.get("start_date") or today+ end_type = data.get("end_type") or "never"+ _validate_end(end_type, data.get("end_date"), data.get("end_count"))+ if end_type == "on_date" and data["end_date"] < start_date:+ raise InvoiceError("end_before_start", "The agreement cannot end before it starts")+ await _assert_payee(session, data.get("payee_id"), workspace_id)++ origin = data.get("origin") or "local"+ if origin == "imported" and not data.get("external_source"):+ raise InvoiceError(+ "external_source_required", "An imported agreement must say where it came from"+ )+ name = (data.get("name") or "").strip()+ if not name:+ raise InvoiceError("name_required", "Give the agreement a name")++ schedule = InvoiceSchedule(+ workspace_id=workspace_id,+ user_id=user_id,+ payee_id=data.get("payee_id"),+ name=name,+ origin=origin,+ external_source=data.get("external_source"),+ external_id=data.get("external_id"),+ status="active",+ frequency=frequency,+ start_date=start_date,+ end_type=end_type,+ end_date=data.get("end_date") if end_type == "on_date" else None,+ end_count=data.get("end_count") if end_type == "after_count" else None,+ payment_terms_days=data.get("payment_terms_days"),+ currency=(data.get("currency") or "USD").upper(),+ notes=data.get("notes"),+ custom_fields=data.get("custom_fields"),+ )+ schedule.terms = []+ schedule.next_sequence = first_sequence_on_or_after(schedule, today)+ session.add(schedule)+ await session.flush()++ term = InvoiceScheduleTerm(+ schedule_id=schedule.id,+ workspace_id=workspace_id,+ effective_from=start_date,+ )+ _fill_term(term, data.get("lines"), data.get("discount"))+ session.add(term)+ schedule.terms.append(term)+ await session.flush()+ return schedule+++#: Frozen once any invoice answers for a period: moving the anchor or+#: changing the frequency would change what period every existing+#: invoice was for.+_CALENDAR_FIELDS = ("frequency", "start_date")+++async def update_schedule(+ session: AsyncSession,+ schedule: InvoiceSchedule,+ data: dict[str, Any],+ today: Optional[_date] = None,+) -> InvoiceSchedule:+ today = today or _today()+ if schedule.status == "ended":+ raise InvoiceError("schedule_ended", "An ended agreement cannot be edited")++ touches_calendar = any(+ data.get(f) is not None and data[f] != getattr(schedule, f) for f in _CALENDAR_FIELDS+ )+ if touches_calendar:+ latest = await _latest_linked_period_start(session, schedule.id)+ if latest is not None:+ raise InvoiceError(+ "schedule_locked",+ "The frequency and start date are fixed once an invoice exists under this agreement",+ )+ if data.get("frequency") is not None:+ if data["frequency"] not in SCHEDULE_FREQUENCIES:+ raise InvoiceError("invalid_frequency", "Unknown frequency")+ schedule.frequency = data["frequency"]+ if data.get("start_date") is not None:+ # The first term moves with the anchor: it is the price+ # "from the start", and the start moved.+ first = min(schedule.terms, key=lambda t: t.effective_from)+ if any(t.effective_from <= data["start_date"] for t in schedule.terms if t is not first):+ raise InvoiceError(+ "term_before_start", "A term would start before the agreement does"+ )+ first.effective_from = data["start_date"]+ schedule.start_date = data["start_date"]+ schedule.next_sequence = first_sequence_on_or_after(schedule, today)++ if "payee_id" in data:+ await _assert_payee(session, data["payee_id"], schedule.workspace_id)+ schedule.payee_id = data["payee_id"]+ if data.get("name") is not None:+ name = data["name"].strip()+ if not name:+ raise InvoiceError("name_required", "Give the agreement a name")+ schedule.name = name+ if data.get("currency") is not None:+ latest = await _latest_linked_period_start(session, schedule.id)+ if latest is not None and data["currency"].upper() != schedule.currency:+ raise InvoiceError(+ "schedule_locked", "The currency is fixed once an invoice exists under this agreement"+ )+ schedule.currency = data["currency"].upper()+ for field in ("payment_terms_days", "notes", "custom_fields"):+ if field in data:+ setattr(schedule, field, data[field])++ if any(k in data for k in ("end_type", "end_date", "end_count")):+ end_type = data.get("end_type") or schedule.end_type+ end_date = data["end_date"] if "end_date" in data else schedule.end_date+ end_count = data["end_count"] if "end_count" in data else schedule.end_count+ _validate_end(end_type, end_date, end_count)+ if end_type == "on_date" and end_date is not None and end_date < schedule.start_date:+ raise InvoiceError("end_before_start", "The agreement cannot end before it starts")+ schedule.end_type = end_type+ schedule.end_date = end_date if end_type == "on_date" else None+ schedule.end_count = end_count if end_type == "after_count" else None+ # An end condition already behind the cursor ends the agreement+ # now rather than on the next job run: the user asked for it to+ # be over, and a screen that says "active" until tomorrow lies.+ if schedule.status == "active":+ _complete_if_over(schedule, today)++ await session.flush()+ return schedule+++def _complete_if_over(schedule: InvoiceSchedule, today: _date) -> bool:+ """End the agreement as `completed` when its own condition is met."""+ if not period_within_end(schedule, schedule.next_sequence):+ schedule.status = "ended"+ schedule.ended_at = today+ schedule.end_reason = "completed"+ schedule.pause_reason = None+ return True+ return False+++async def pause_schedule(session: AsyncSession, schedule: InvoiceSchedule) -> InvoiceSchedule:+ if schedule.status == "ended":+ raise InvoiceError("schedule_ended", "An ended agreement cannot be paused")+ schedule.status = "paused"+ schedule.pause_reason = "manual"+ await session.flush()+ return schedule+++async def resume_schedule(+ session: AsyncSession, schedule: InvoiceSchedule, today: Optional[_date] = None+) -> InvoiceSchedule:+ """Back to emitting, from the next period on.++ Periods that fell during a manual pause are not emitted: a pause is+ "stop billing", and billing the gap afterwards would be the+ opposite. The cursor skips to the first period on or after today,+ and anything before it is history the user may link by hand.++ A pause for failures is different: the job gave up on a period that+ was already due, and resuming is the person saying the cause is+ fixed. The cursor stays on that period so it is billed, not dropped.+ """+ today = today or _today()+ if schedule.status == "ended":+ raise InvoiceError("schedule_ended", "An ended agreement cannot be resumed")+ paused_by_failures = schedule.pause_reason == "failures"+ schedule.status = "active"+ schedule.pause_reason = None+ schedule.consecutive_failures = 0+ if not paused_by_failures:+ schedule.next_sequence = max(+ schedule.next_sequence, first_sequence_on_or_after(schedule, today)+ )+ _complete_if_over(schedule, today)+ await session.flush()+ return schedule+++async def end_schedule(+ session: AsyncSession,+ schedule: InvoiceSchedule,+ *,+ reason: str = "other",+ ended_at: Optional[_date] = None,+ today: Optional[_date] = None,+) -> InvoiceSchedule:+ """Terminal. The one decision an invoice cannot record: churn has a+ date and a side."""+ today = today or _today()+ if reason not in SCHEDULE_END_REASONS:+ raise InvoiceError("invalid_end_reason", "Unknown end reason")+ # Not checked against `start_date`: cancelling an agreement that was+ # to begin next month is an ordinary thing to do.+ ended_at = ended_at or today+ if schedule.status == "ended":+ return schedule+ schedule.status = "ended"+ schedule.pause_reason = None+ schedule.ended_at = ended_at+ schedule.end_reason = reason+ await session.flush()+ return schedule+++async def delete_schedule(session: AsyncSession, schedule: InvoiceSchedule) -> None:+ """Only an agreement nothing was ever billed under. Anything else+ is ended, so the invoices keep the record of what they were for."""+ latest = await _latest_linked_period_start(session, schedule.id)+ if latest is not None:+ raise InvoiceError(+ "schedule_has_invoices", "Invoices were issued under this agreement; end it instead"+ )+ await session.delete(schedule)+ await session.flush()+++# ---------------------------------------------------------------------------+# Linking invoices+# ---------------------------------------------------------------------------+async def link_invoice(+ session: AsyncSession,+ schedule: InvoiceSchedule,+ invoice: Invoice,+ period_start_date: _date,+) -> Invoice:+ """Say that an existing invoice answers for a period of this agreement.++ The retroactive door: someone who billed a retainer by hand from+ March to August and only now created the schedule gets their+ history, and a Stripe import lands its invoices the same way. The+ date has to be a real period boundary, the period has to be free,+ and the invoice has to be the same money (currency, and client when+ both say one).+ """+ if invoice.workspace_id != schedule.workspace_id:+ raise InvoiceError("invoice_not_found", "Invoice not found", 404)+ # An agreement bills a client. A bill received is the supplier's+ # agreement, and summing it here would count money going out as+ # money coming in.+ if invoice.direction != "receivable":+ raise InvoiceError("not_receivable", "Only an invoice you issued can belong to an agreement")+ if invoice.schedule_id is not None:+ raise InvoiceError("already_linked", "This invoice already belongs to an agreement", 409)+ if invoice.status == "void":+ raise InvoiceError("invoice_void", "A voided invoice cannot answer for a period")+ if invoice.currency != schedule.currency:+ raise InvoiceError("currency_mismatch", "The invoice and the agreement are in different currencies")+ if invoice.payee_id and schedule.payee_id and invoice.payee_id != schedule.payee_id:+ raise InvoiceError("payee_mismatch", "The invoice and the agreement name different clients")++ sequence = sequence_for_period_start(schedule, period_start_date)+ if sequence is None:+ raise InvoiceError("not_a_period", "That date is not the start of a period of this agreement")+ if not period_within_end(schedule, sequence):+ raise InvoiceError("beyond_end", "That period is after the agreement ends")+ taken = await session.execute(+ select(Invoice.id).where(Invoice.schedule_id == schedule.id, Invoice.sequence == sequence)+ )+ if taken.scalar_one_or_none() is not None:+ raise InvoiceError("period_taken", "Another invoice already answers for that period", 409)++ start, end = period_bounds(schedule, sequence)+ invoice.schedule_id = schedule.id+ invoice.sequence = sequence+ invoice.period_start = start+ invoice.period_end = end+ # A period billed by hand before the job got to it is not billed+ # again by the job.+ if sequence >= schedule.next_sequence:+ schedule.next_sequence = sequence + 1+ await session.flush()+ return invoice+++async def unlink_invoice(session: AsyncSession, invoice: Invoice) -> Invoice:+ """The invoice stays, the period is free again. The cursor is not+ moved back: the job does not re-bill a period a person unlinked."""+ invoice.schedule_id = None+ invoice.sequence = None+ invoice.period_start = None+ invoice.period_end = None+ await session.flush()+ return invoice+++def _lines_from_invoice(invoice: Invoice, fallback_description: str) -> list[dict[str, Any]]:+ if invoice.lines:+ return [+ {+ "description": line.description,+ "quantity": line.quantity,+ "unit": line.unit,+ "unit_price": line.unit_price,+ "tax_rate": line.tax_rate,+ }+ for line in invoice.lines+ ]+ # A three-field invoice has no lines; the agreement gets one that+ # says what the invoice said.+ return [{"description": fallback_description, "quantity": 1, "unit_price": invoice.total}]+++async def make_recurring(+ session: AsyncSession,+ invoice: Invoice,+ user_id: Optional[uuid.UUID],+ data: dict[str, Any],+ today: Optional[_date] = None,+) -> InvoiceSchedule:+ """Turn an invoice into the first period of a new agreement.++ The natural door: the invoice for September is already written, and+ "repeat this monthly" is the whole request. Everything the schedule+ needs is on the invoice; the caller adds a frequency and, if they+ like, a name and an end.+ """+ today = today or _today()+ if invoice.status in ("draft", "void"):+ raise InvoiceError(+ "not_issued", "Only an issued invoice can start an agreement"+ )+ if invoice.direction != "receivable":+ raise InvoiceError("not_receivable", "Only an invoice you issued can start an agreement")+ if invoice.schedule_id is not None:+ raise InvoiceError("already_linked", "This invoice already belongs to an agreement", 409)++ name = (data.get("name") or "").strip() or (+ invoice.lines[0].description if invoice.lines else (invoice.payee.name if invoice.payee else "")+ )+ if not name:+ raise InvoiceError("name_required", "Give the agreement a name")++ # The anchor defaults to the invoice's own date, but may be earlier:+ # "this has been going since March" makes March period one and the+ # invoice in hand a later period, so the months between can be+ # linked. Whatever the anchor, the invoice has to land on a period+ # boundary, or it would not be a period of the agreement it starts.+ frequency = data.get("frequency")+ if frequency not in SCHEDULE_FREQUENCIES:+ raise InvoiceError("invalid_frequency", "Unknown frequency")+ start_date = data.get("start_date") or invoice.issue_date+ if start_date > invoice.issue_date:+ raise InvoiceError("start_after_invoice", "The agreement cannot start after this invoice")+ probe = InvoiceSchedule(frequency=frequency, start_date=start_date)+ if sequence_for_period_start(probe, invoice.issue_date) is None:+ raise InvoiceError(+ "not_a_period", "With that start date, this invoice does not fall on a period boundary"+ )++ schedule = await create_schedule(+ session,+ invoice.workspace_id,+ user_id,+ {+ "name": name,+ "payee_id": invoice.payee_id,+ "frequency": frequency,+ "start_date": start_date,+ "end_type": data.get("end_type") or "never",+ "end_date": data.get("end_date"),+ "end_count": data.get("end_count"),+ "payment_terms_days": (+ data["payment_terms_days"]+ if data.get("payment_terms_days") is not None+ else (invoice.due_date - invoice.issue_date).days+ ),+ "currency": invoice.currency,+ "notes": invoice.notes,+ "custom_fields": invoice.custom_fields,+ "lines": _lines_from_invoice(invoice, name),+ "discount": invoice.discount if invoice.lines else ZERO,+ },+ today=today,+ )+ await link_invoice(session, schedule, invoice, invoice.issue_date)+ return schedule+++# ---------------------------------------------------------------------------+# Generation+# ---------------------------------------------------------------------------+async def _payment_terms(session: AsyncSession, schedule: InvoiceSchedule) -> int:+ if schedule.payment_terms_days is not None:+ return schedule.payment_terms_days+ settings = await invoice_service.get_settings(session, schedule.workspace_id)+ return settings.default_payment_terms_days+++async def _emit(+ session: AsyncSession, schedule: InvoiceSchedule, sequence: int+) -> Invoice:+ """One invoice for one period, priced by the term in force."""+ start, end = period_bounds(schedule, sequence)+ term = term_for(schedule, start)+ if term is None:+ raise InvoiceError("no_term", "No term is in force for this period")+ terms_days = await _payment_terms(session, schedule)+ if schedule.user_id is None:+ # The ledger stamps who created each invoice. An agreement whose+ # author left the workspace keeps emitting, and the invoice is+ # then authored by nobody in particular rather than not at all.+ raise InvoiceError("no_author", "This agreement has no author to issue invoices as")+ invoice = await invoice_service.create_invoice(+ session,+ schedule.workspace_id,+ schedule.user_id,+ {+ "payee_id": schedule.payee_id,+ "issue_date": start,+ "due_date": start + timedelta(days=terms_days),+ "competence_date": start,+ "currency": schedule.currency,+ "discount": Decimal(term.discount),+ "lines": [dict(line) for line in term.lines],+ "notes": schedule.notes,+ "custom_fields": schedule.custom_fields,+ },+ )+ invoice.schedule_id = schedule.id+ invoice.sequence = sequence+ invoice.period_start = start+ invoice.period_end = end+ await session.flush()+ return invoice+++async def generate_due(+ session: AsyncSession,+ schedule: InvoiceSchedule,+ today: Optional[_date] = None,+ *,+ force_next: bool = False,+) -> list[Invoice]:+ """Emit every period whose start has arrived, oldest first.++ Idempotent by construction: a period already answered for (by the+ job or by a hand-linked invoice) is skipped and the cursor moves+ past it. `force_next` emits the next period whether or not its date+ has come, for "bill this now"; it never emits more than one.++ A failure counts against the schedule, and the third in a row+ pauses it. The job's own transaction handling decides whether the+ failure is committed; this function only records it.+ """+ today = today or _today()+ if schedule.status != "active" or schedule.origin != "local":+ return []+ # Two runs on one agreement (a double click on "issue next now", or+ # the button racing the hourly job) would both read the same cursor.+ # Locking the row makes the second wait, then read the cursor the+ # first one moved, so it finds nothing left to emit. Columns rather+ # than the entity: the entity joins the payee, and Postgres refuses+ # FOR UPDATE on the nullable side of an outer join.+ locked = (+ await session.execute(+ select(InvoiceSchedule.status, InvoiceSchedule.next_sequence)+ .where(InvoiceSchedule.id == schedule.id)+ .with_for_update()+ )+ ).one()+ if locked.status != "active":+ return []+ # The instance may predate the lock: a worker loads it, then a PATCH+ # moves the start date and recomputes the cursor, then the worker+ # gets here. Emitting from the stale calendar would skip periods.+ # So everything the emission reads is reloaded now that the row is+ # ours. Only those fields: the failure count lives on the instance+ # until the caller commits it, and reloading it would reset it.+ await session.refresh(+ schedule,+ attribute_names=[+ "status", "frequency", "start_date", "end_type", "end_date",+ "end_count", "next_sequence", "payee_id", "currency",+ "payment_terms_days", "notes", "custom_fields", "terms",+ ],+ )+ emitted: list[Invoice] = []+ try:+ while len(emitted) < MAX_PERIODS_PER_RUN:+ if _complete_if_over(schedule, today):+ break+ sequence = schedule.next_sequence+ if not force_next and period_start(schedule, sequence) > today:+ break+ already = await session.execute(+ select(Invoice.id).where(+ Invoice.schedule_id == schedule.id, Invoice.sequence == sequence+ )+ )+ if already.scalar_one_or_none() is None:+ emitted.append(await _emit(session, schedule, sequence))+ schedule.last_generated_at = datetime.now(timezone.utc)+ schedule.next_sequence = sequence + 1+ if force_next:+ break+ schedule.consecutive_failures = 0+ _complete_if_over(schedule, today)+ except IntegrityError:+ # The unique (schedule, sequence) caught a period another run+ # emitted first. The period exists, so this is not a failure and+ # must not count towards pausing the agreement.+ await session.rollback()+ raise InvoiceError(+ "period_already_issued",+ "This period was issued by another run a moment ago",+ status_code=409,+ ) from None+ except Exception:+ schedule.consecutive_failures += 1+ if schedule.consecutive_failures >= MAX_CONSECUTIVE_FAILURES:+ schedule.status = "paused"+ schedule.pause_reason = "failures"+ raise+ await session.flush()+ return emitted+++async def after_generation(+ session: AsyncSession, invoice: Invoice, workspace: Workspace+) -> None:+ """What the create route does after an invoice is issued, for an+ invoice the job issued: file the document, and look back at money+ that may already have arrived for it. Both are best effort."""+ try:+ await invoice_archive.file_issued_document(session, invoice, workspace, invoice.user_id)+ await session.commit()+ except Exception:+ logger.exception("Could not file the document for invoice %s", invoice.id)+ await session.rollback()+ try:+ await reconciliation_service.match_for_invoice(session, invoice)+ await session.commit()+ except Exception:+ logger.exception("Could not look back for payments for invoice %s", invoice.id)+ await session.rollback()+++async def due_schedule_ids(session: AsyncSession) -> list[uuid.UUID]:+ """Every active local agreement, across workspaces. The date test is+ done per schedule in `generate_due`, because a period start is a+ walk from the anchor and not a column to compare in SQL."""+ result = await session.execute(+ select(InvoiceSchedule.id).where(+ InvoiceSchedule.status == "active", InvoiceSchedule.origin == "local"+ )+ )+ return [row[0] for row in result.all()]+++# ---------------------------------------------------------------------------+# Forecast+# ---------------------------------------------------------------------------+@dataclass(frozen=True)+class ProjectedPeriod:+ """A period not yet invoiced, as the forecast will carry it."""++ due_date: _date+ currency: str+ amount: Decimal+++async def projected_periods(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ range_start: _date,+ range_end: _date,+) -> list[ProjectedPeriod]:+ """Periods of active agreements falling due in `[range_start, range_end)`+ that no invoice answers for yet.++ Only from the cursor onwards: everything before it is either an+ invoice (the forecast already carries it as one) or was skipped on+ purpose. A period at the cursor whose start is already past is still+ projected, dated by its due date, because the job will emit it on+ its next run and the money is still expected.+ """+ schedules = [+ s+ for s in await list_schedules(session, workspace_id, status="active")+ if s.origin == "local"+ ]+ if not schedules:+ return []+ settings: Optional[InvoiceSettings] = None+ out: list[ProjectedPeriod] = []+ for schedule in schedules:+ if schedule.payment_terms_days is None:+ settings = settings or await invoice_service.get_settings(session, workspace_id)+ terms_days = settings.default_payment_terms_days+ else:+ terms_days = schedule.payment_terms_days+ sequence = schedule.next_sequence+ steps = 0+ while steps < _MAX_WALK and period_within_end(schedule, sequence):+ start = period_start(schedule, sequence)+ due = start + timedelta(days=terms_days)+ if due >= range_end:+ break+ if due >= range_start:+ term = term_for(schedule, start)+ if term is not None and term.total > ZERO:+ out.append(ProjectedPeriod(due, schedule.currency, Decimal(term.total)))+ sequence += 1+ steps += 1+ return outdiff --git a/backend/app/services/invoice_service.py b/backend/app/services/invoice_service.pyindex 992b2857..2bcdb070 100644--- a/backend/app/services/invoice_service.py+++ b/backend/app/services/invoice_service.py@@ -321,6 +321,7 @@ async def list_invoices(year: Optional[int] = None,direction: str = DEFAULT_DIRECTION,payee_id: Optional[uuid.UUID] = None,+ schedule_id: Optional[uuid.UUID] = None,q: Optional[str] = None,limit: int = 100,offset: int = 0,@@ -342,6 +343,8 @@ async def list_invoices(query = _apply_year(query, year)if payee_id:query = query.where(Invoice.payee_id == payee_id)+ if schedule_id:+ query = query.where(Invoice.schedule_id == schedule_id)if q:pattern = f"%{q.lower()}%"query = query.where(func.lower(Invoice.notes).like(pattern))diff --git a/backend/app/tasks/invoice_schedule_tasks.py b/backend/app/tasks/invoice_schedule_tasks.pynew file mode 100644index 00000000..fc728283--- /dev/null+++ b/backend/app/tasks/invoice_schedule_tasks.py@@ -0,0 +1,86 @@+"""Emit the invoices of recurring agreements whose period has come.++One schedule per transaction, so a failure on one agreement never+takes the others down with it, and the failure count that eventually+pauses a broken schedule is committed even when the emission is not.+"""+import asyncio+import logging++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine++from app.core.config import get_settings+from app.models.workspace import Workspace+from app.services import invoice_schedule_service, invoice_service+from app.services.invoice_service import InvoiceError+from app.worker import celery_app++logger = logging.getLogger(__name__)+++def _make_session_maker():+ """A fresh engine and session factory for the worker's event loop."""+ settings = get_settings()+ engine = create_async_engine(settings.database_url)+ return engine, async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)+++async def _generate_one(session_maker, schedule_id) -> int:+ """Emit what one agreement is due. Returns how many invoices it made."""+ async with session_maker() as session:+ 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.+ 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()++ 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:+ engine, session_maker = _make_session_maker()+ try:+ async with session_maker() as session:+ schedule_ids = await invoice_schedule_service.due_schedule_ids(session)+ total = 0+ for schedule_id in schedule_ids:+ total += await _generate_one(session_maker, schedule_id)+ finally:+ await engine.dispose()+ return total+++@celery_app.task(name="app.tasks.invoice_schedule_tasks.generate_recurring_invoices")+def generate_recurring_invoices() -> dict:+ """Celery task: emit every recurring invoice whose period has come."""+ total = asyncio.run(_generate_all())+ if total:+ logger.info("Recurring invoices: %d emitted", total)+ return {"generated": total}diff --git a/backend/app/worker.py b/backend/app/worker.pyindex 930fc475..6c490b99 100644--- a/backend/app/worker.py+++ b/backend/app/worker.py@@ -27,6 +27,13 @@ celery_app.conf.beat_schedule = {"task": "app.tasks.recurring_tasks.generate_all_recurring","schedule": 60 * 60, # every hour; generate_pending is idempotent (advances next_occurrence)},+ "generate-recurring-invoices-daily": {+ "task": "app.tasks.invoice_schedule_tasks.generate_recurring_invoices",+ # Hourly, like recurring transactions: a period is emitted the+ # first run after its date, and the cursor plus the unique+ # (schedule, sequence) make every later run a no-op.+ "schedule": 60 * 60,+ },"apply-asset-growth-daily": {"task": "app.tasks.asset_tasks.apply_asset_growth_rules","schedule": 60 * 60, # every hour; idempotent (checks last value date)@@ -58,6 +65,7 @@ celery_app.conf.beat_schedule = {celery_app.conf.include = ["app.tasks.sync_tasks","app.tasks.recurring_tasks",+ "app.tasks.invoice_schedule_tasks","app.tasks.asset_tasks","app.tasks.fx_rate_tasks",# Optional agents module — registering the import is harmless whendiff --git a/backend/tests/test_invoice_schedule_service.py b/backend/tests/test_invoice_schedule_service.pynew file mode 100644index 00000000..76042b05--- /dev/null+++ b/backend/tests/test_invoice_schedule_service.py@@ -0,0 +1,1083 @@+"""Recurring invoices, below the HTTP layer.++Three claims the design rests on, each pinned here:++ 1. **The schedule is an agreement, never money.** Every figure about+ it (recurring revenue, paid, past due) is computed from invoices.+ 2. **A period is billed once.** The cursor, the unique+ `(schedule, sequence)` and the hand-link door all agree on it.+ 3. **A term is history once an invoice was issued under it.** Prices+ change from a period boundary forward, never behind.+"""+import uuid+from datetime import date, timedelta+from decimal import Decimal+from unittest.mock import patch++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.invoice import Invoice, InvoiceAllocation+from app.models.invoice_schedule import InvoiceSchedule, InvoiceScheduleTerm+from app.models.payee import Payee+from app.models.transaction import Transaction+from app.services import invoice_forecast_service as forecast+from app.services import invoice_schedule_service as svc+from app.services import invoice_service+from app.services.invoice_service import InvoiceError++TODAY = date(2026, 9, 22)+LINE = {"description": "Retainer", "quantity": 1, "unit_price": "3000.00"}+++def build(**overrides) -> InvoiceSchedule:+ """An in-memory schedule for the pure calendar and term functions."""+ schedule = InvoiceSchedule(+ id=uuid.uuid4(),+ workspace_id=uuid.uuid4(),+ name="Plano",+ status="active",+ origin="local",+ frequency="monthly",+ start_date=date(2026, 1, 5),+ end_type="never",+ currency="USD",+ next_sequence=1,+ consecutive_failures=0,+ )+ schedule.terms = []+ for key, value in overrides.items():+ setattr(schedule, key, value)+ return schedule+++def term(effective_from: date, total: str, frequency_schedule=None) -> InvoiceScheduleTerm:+ return InvoiceScheduleTerm(+ id=uuid.uuid4(),+ effective_from=effective_from,+ lines=[{"description": "x", "quantity": "1", "unit_price": total}],+ discount=Decimal("0"),+ subtotal=Decimal(total),+ tax_total=Decimal("0"),+ total=Decimal(total),+ )+++# ---------------------------------------------------------------------------+# The calendar: pure functions of the anchor and the frequency+# ---------------------------------------------------------------------------+class TestCalendar:+ def test_periods_count_from_the_anchor(self):+ s = build(start_date=date(2026, 1, 5))+ assert svc.period_start(s, 1) == date(2026, 1, 5)+ assert svc.period_start(s, 2) == date(2026, 2, 5)+ assert svc.period_start(s, 13) == date(2027, 1, 5)++ def test_sequence_is_one_based(self):+ with pytest.raises(ValueError):+ svc.period_start(build(), 0)++ def test_short_months_clamp_and_recover(self):+ """Anchored on the 31st: February clamps, March is the 31st again.+ Not the 28th forever, which is what a naive `+1 month` does."""+ s = build(start_date=date(2026, 1, 31))+ assert svc.period_start(s, 2) == date(2026, 2, 28)+ assert svc.period_start(s, 3) == date(2026, 3, 31)+ assert svc.period_start(s, 4) == date(2026, 4, 30)++ def test_every_frequency_advances_as_named(self):+ anchor = date(2026, 1, 5)+ expected = {+ "weekly": date(2026, 1, 12),+ "biweekly": date(2026, 1, 19),+ "monthly": date(2026, 2, 5),+ "quarterly": date(2026, 4, 5),+ "semiannual": date(2026, 7, 5),+ "yearly": date(2027, 1, 5),+ }+ for frequency, second in expected.items():+ assert svc.period_start(build(frequency=frequency, start_date=anchor), 2) == second++ def test_yearly_on_leap_day_clamps(self):+ s = build(frequency="yearly", start_date=date(2028, 2, 29))+ assert svc.period_start(s, 2) == date(2029, 2, 28)+ assert svc.period_start(s, 5) == date(2032, 2, 29)++ def test_bounds_are_inclusive_and_contiguous(self):+ s = build(start_date=date(2026, 1, 5))+ start, end = svc.period_bounds(s, 1)+ assert (start, end) == (date(2026, 1, 5), date(2026, 2, 4))+ next_start, _ = svc.period_bounds(s, 2)+ assert next_start == end + timedelta(days=1)++ def test_first_sequence_on_or_after(self):+ s = build(start_date=date(2026, 1, 5))+ assert svc.first_sequence_on_or_after(s, date(2025, 12, 1)) == 1+ assert svc.first_sequence_on_or_after(s, date(2026, 1, 5)) == 1+ assert svc.first_sequence_on_or_after(s, date(2026, 1, 6)) == 2+ assert svc.first_sequence_on_or_after(s, date(2026, 9, 22)) == 10 # Oct 5++ def test_sequence_for_period_start_accepts_boundaries_only(self):+ s = build(start_date=date(2026, 1, 5))+ assert svc.sequence_for_period_start(s, date(2026, 3, 5)) == 3+ assert svc.sequence_for_period_start(s, date(2026, 3, 6)) is None+ assert svc.sequence_for_period_start(s, date(2025, 12, 5)) is None++ def test_end_conditions(self):+ assert svc.period_within_end(build(end_type="never"), 10_000)+ counted = build(end_type="after_count", end_count=3)+ assert svc.period_within_end(counted, 3)+ assert not svc.period_within_end(counted, 4)+ dated = build(end_type="on_date", end_date=date(2026, 3, 5))+ assert svc.period_within_end(dated, 3) # starts Mar 5, on the date itself+ assert not svc.period_within_end(dated, 4)++ def test_next_period_start_is_none_once_over(self):+ s = build(end_type="after_count", end_count=2, next_sequence=3)+ assert svc.next_period_start(s) is None+ assert svc.next_period_start(build(next_sequence=3)) == date(2026, 3, 5)+ assert svc.next_period_start(build(status="ended")) is None+++# ---------------------------------------------------------------------------+# Terms: the price over time+# ---------------------------------------------------------------------------+class TestTerms:+ def test_latest_term_on_or_before_the_date_wins(self):+ s = build(terms=[term(date(2026, 1, 5), "3000"), term(date(2027, 1, 1), "3500")])+ before = svc.term_for(s, date(2026, 12, 31))+ after = svc.term_for(s, date(2027, 1, 1))+ assert before is not None and before.total == Decimal("3000")+ assert after is not None and after.total == Decimal("3500")+ assert svc.term_for(s, date(2025, 6, 1)) is None++ def test_monthly_amount_normalises_through_the_year(self):+ """52 weeks in 12 months, not 4 in one: the 8% that a naive x4 loses."""+ t = term(date(2026, 1, 5), "1200")+ expected = {+ "weekly": Decimal("5200.00"),+ "biweekly": Decimal("2600.00"),+ "monthly": Decimal("1200.00"),+ "quarterly": Decimal("400.00"),+ "semiannual": Decimal("200.00"),+ "yearly": Decimal("100.00"),+ }+ for frequency, monthly in expected.items():+ assert svc.monthly_amount(build(frequency=frequency), t) == monthly+ assert svc.monthly_amount(build(), None) == Decimal("0")++ def test_totals_follow_the_invoice_arithmetic(self):+ lines = [+ {"description": "a", "quantity": "2", "unit_price": "100.00", "tax_rate": "10"},+ {"description": "b", "quantity": "1", "unit_price": "50.00"},+ ]+ subtotal, tax, total = svc._term_totals(lines, Decimal("25"))+ assert (subtotal, tax, total) == (Decimal("250.00"), Decimal("20.00"), Decimal("245.00"))++ def test_discount_beyond_the_lines_is_refused(self):+ with pytest.raises(InvoiceError) as exc:+ svc._term_totals([{"description": "a", "unit_price": "10"}], Decimal("11"))+ assert exc.value.code == "discount_exceeds_total"++ def test_a_term_must_bill_something(self):+ t = InvoiceScheduleTerm()+ with pytest.raises(InvoiceError) as exc:+ svc._fill_term(t, [{"description": "free", "unit_price": "0"}], None)+ assert exc.value.code == "term_empty"+ with pytest.raises(InvoiceError) as exc:+ svc._fill_term(t, [], None)+ assert exc.value.code == "term_lines_required"+++# ---------------------------------------------------------------------------+# Against the database+# ---------------------------------------------------------------------------+@pytest_asyncio.fixture+async def business_ws(client: AsyncClient, auth_headers) -> dict:+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Estudio", "kind": "business", "self_membership": True},+ )+ assert resp.status_code == 201, resp.text+ return resp.json()+++@pytest_asyncio.fixture+async def ws_id(business_ws) -> uuid.UUID:+ return uuid.UUID(business_ws["id"])+++@pytest_asyncio.fixture+async def client_payee(session: AsyncSession, ws_id, test_user) -> Payee:+ payee = Payee(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=ws_id, name="Cliente Alpha", source="manual"+ )+ session.add(payee)+ await session.commit()+ return payee+++async def make_schedule(session, ws_id, user_id, today=TODAY, **overrides) -> InvoiceSchedule:+ data = {+ "name": "Retainer",+ "frequency": "monthly",+ "start_date": date(2026, 9, 5),+ "currency": "USD",+ "lines": [dict(LINE)],+ }+ data.update(overrides)+ schedule = await svc.create_schedule(session, ws_id, user_id, data, today=today)+ await session.commit()+ return schedule+++async def invoices_of(session, schedule_id) -> list[Invoice]:+ result = await session.execute(+ select(Invoice).where(Invoice.schedule_id == schedule_id).order_by(Invoice.sequence)+ )+ return list(result.unique().scalars().all())+++class TestCreate:+ @pytest.mark.asyncio+ async def test_creates_with_its_first_term_from_the_anchor(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 1))+ assert s.status == "active"+ assert len(s.terms) == 1+ assert s.terms[0].effective_from == date(2026, 10, 1)+ assert s.terms[0].total == Decimal("3000.00")+ assert s.next_sequence == 1++ @pytest.mark.asyncio+ async def test_a_start_in_the_past_does_not_back_fill(self, session, ws_id, test_user):+ """Anchored in March, created in September: the cursor sits on+ the first period from today, and March to September are history+ the user links by hand if they want them."""+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 3, 5))+ assert s.next_sequence == 8 # Oct 5+ assert svc.next_period_start(s) == date(2026, 10, 5)++ @pytest.mark.asyncio+ async def test_end_conditions_are_validated(self, session, ws_id, test_user):+ with pytest.raises(InvoiceError) as exc:+ await make_schedule(session, ws_id, test_user.id, end_type="on_date")+ assert exc.value.code == "end_date_required"+ with pytest.raises(InvoiceError) as exc:+ await make_schedule(session, ws_id, test_user.id, end_type="after_count", end_count=0)+ assert exc.value.code == "end_count_required"+ with pytest.raises(InvoiceError) as exc:+ await make_schedule(+ session, ws_id, test_user.id, end_type="on_date", end_date=date(2026, 1, 1)+ )+ assert exc.value.code == "end_before_start"++ @pytest.mark.asyncio+ async def test_imported_needs_a_source_and_converges_on_it(self, session, ws_id, test_user):+ with pytest.raises(InvoiceError) as exc:+ await make_schedule(session, ws_id, test_user.id, origin="imported")+ assert exc.value.code == "external_source_required"+ s = await make_schedule(+ session, ws_id, test_user.id, origin="imported", external_source="stripe", external_id="sub_1"+ )+ found = await svc.find_by_external_id(session, ws_id, "stripe", "sub_1")+ assert found is not None and found.id == s.id++ @pytest.mark.asyncio+ async def test_payee_must_belong_to_the_workspace(self, session, ws_id, test_user):+ with pytest.raises(InvoiceError) as exc:+ await make_schedule(session, ws_id, test_user.id, payee_id=uuid.uuid4())+ assert exc.value.code == "payee_not_found"+++class TestGeneration:+ @pytest.mark.asyncio+ async def test_emits_the_period_once_its_date_has_come(self, session, ws_id, test_user, client_payee):+ s = await make_schedule(+ session, ws_id, test_user.id, start_date=date(2026, 10, 5), payee_id=client_payee.id,+ payment_terms_days=10,+ )+ assert await svc.generate_due(session, s, today=date(2026, 10, 4)) == []+ emitted = await svc.generate_due(session, s, today=date(2026, 10, 5))+ await session.commit()+ assert len(emitted) == 1+ inv = emitted[0]+ assert inv.schedule_id == s.id+ assert inv.sequence == 1+ assert (inv.period_start, inv.period_end) == (date(2026, 10, 5), date(2026, 11, 4))+ assert inv.issue_date == date(2026, 10, 5)+ assert inv.competence_date == date(2026, 10, 5)+ assert inv.due_date == date(2026, 10, 15)+ assert inv.payee_id == client_payee.id+ assert inv.currency == "USD"+ assert inv.total == Decimal("3000.00")+ assert [line.description for line in inv.lines] == ["Retainer"]+ assert inv.status == "open" # the business workspace opens on creation+ assert inv.number is not None+ assert s.next_sequence == 2+ assert s.last_generated_at is not None++ @pytest.mark.asyncio+ async def test_a_second_run_is_a_no_op(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert await svc.generate_due(session, s, today=date(2026, 10, 5)) == []+ assert await svc.generate_due(session, s, today=date(2026, 10, 20)) == []+ assert len(await invoices_of(session, s.id)) == 1++ @pytest.mark.asyncio+ async def test_catches_up_every_period_the_worker_missed(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ emitted = await svc.generate_due(session, s, today=date(2027, 1, 10))+ assert [i.sequence for i in emitted] == [1, 2, 3, 4]+ assert [i.issue_date for i in emitted] == [+ date(2026, 10, 5), date(2026, 11, 5), date(2026, 12, 5), date(2027, 1, 5)+ ]+ assert s.next_sequence == 5++ @pytest.mark.asyncio+ async def test_catch_up_is_capped_per_run(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, frequency="weekly", start_date=date(2026, 10, 5))+ first = await svc.generate_due(session, s, today=date(2027, 10, 5))+ assert len(first) == svc.MAX_PERIODS_PER_RUN+ second = await svc.generate_due(session, s, today=date(2027, 10, 5))+ assert len(second) == svc.MAX_PERIODS_PER_RUN+ assert second[0].sequence == svc.MAX_PERIODS_PER_RUN + 1++ @pytest.mark.asyncio+ async def test_force_next_bills_ahead_of_the_date_once(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 12, 1))+ emitted = await svc.generate_due(session, s, today=TODAY, force_next=True)+ assert [i.sequence for i in emitted] == [1]+ assert emitted[0].issue_date == date(2026, 12, 1)+ assert s.next_sequence == 2+ # And only once: the next period is still in the future.+ assert await svc.generate_due(session, s, today=TODAY) == []++ @pytest.mark.asyncio+ async def test_a_period_already_linked_by_hand_is_skipped(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ manual = await invoice_service.create_invoice(+ session, ws_id, test_user.id,+ {"total": Decimal("3000.00"), "issue_date": date(2026, 10, 5), "due_date": date(2026, 10, 20)},+ )+ await svc.link_invoice(session, s, manual, date(2026, 10, 5))+ assert s.next_sequence == 2+ emitted = await svc.generate_due(session, s, today=date(2026, 11, 5))+ assert [i.sequence for i in emitted] == [2]+ assert len(await invoices_of(session, s.id)) == 2++ @pytest.mark.asyncio+ async def test_after_count_ends_as_completed_on_the_last_invoice(self, session, ws_id, test_user):+ s = await make_schedule(+ session, ws_id, test_user.id, start_date=date(2026, 10, 5), end_type="after_count", end_count=3+ )+ emitted = await svc.generate_due(session, s, today=date(2027, 6, 1))+ assert [i.sequence for i in emitted] == [1, 2, 3]+ assert s.status == "ended"+ assert s.end_reason == "completed"+ assert s.ended_at == date(2027, 6, 1)+ assert await svc.generate_due(session, s, today=date(2027, 7, 1)) == []++ @pytest.mark.asyncio+ async def test_on_date_stops_at_the_date(self, session, ws_id, test_user):+ s = await make_schedule(+ session, ws_id, test_user.id, start_date=date(2026, 10, 5),+ end_type="on_date", end_date=date(2026, 12, 5),+ )+ emitted = await svc.generate_due(session, s, today=date(2027, 3, 1))+ assert [i.issue_date for i in emitted] == [date(2026, 10, 5), date(2026, 11, 5), date(2026, 12, 5)]+ assert s.status == "ended"++ @pytest.mark.asyncio+ async def test_the_price_changes_at_the_term_boundary_and_not_before(self, session, ws_id, test_user):+ """A raise recorded in October for January: October to December+ bill the old price, January the new one, nobody had to remember."""+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.add_term(+ session, s, effective_from=date(2027, 1, 1),+ lines=[{"description": "Retainer", "unit_price": "3500.00"}],+ )+ emitted = await svc.generate_due(session, s, today=date(2027, 2, 10))+ assert [(i.issue_date, i.total) for i in emitted] == [+ (date(2026, 10, 5), Decimal("3000.00")),+ (date(2026, 11, 5), Decimal("3000.00")),+ (date(2026, 12, 5), Decimal("3000.00")),+ (date(2027, 1, 5), Decimal("3500.00")),+ (date(2027, 2, 5), Decimal("3500.00")),+ ]++ @pytest.mark.asyncio+ async def test_payment_terms_fall_back_to_the_workspace_default(self, session, ws_id, test_user):+ settings = await invoice_service.get_settings(session, ws_id)+ settings.default_payment_terms_days = 7+ await session.commit()+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ [inv] = await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert inv.due_date == date(2026, 10, 12)++ @pytest.mark.asyncio+ async def test_document_preset_emits_drafts(self, session, ws_id, test_user):+ """The generated invoice obeys the workspace's initial state, like+ one written by hand: a document workspace reviews before sending."""+ await invoice_service.update_settings(session, ws_id, {"preset": "document"})+ await session.commit()+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ [inv] = await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert inv.status == "draft"+ assert inv.number is None++ @pytest.mark.asyncio+ async def test_paused_ended_and_imported_emit_nothing(self, session, ws_id, test_user):+ paused = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.pause_schedule(session, paused)+ ended = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.end_schedule(session, ended, reason="canceled_by_client", today=TODAY)+ imported = await make_schedule(+ session, ws_id, test_user.id, start_date=date(2026, 10, 5),+ origin="imported", external_source="stripe", external_id="sub_x",+ )+ for s in (paused, ended, imported):+ assert await svc.generate_due(session, s, today=date(2027, 1, 1)) == []++ @pytest.mark.asyncio+ async def test_three_failures_pause_the_schedule(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ with patch.object(svc, "_emit", side_effect=RuntimeError("storage down")):+ for attempt in range(1, 4):+ with pytest.raises(RuntimeError):+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert s.consecutive_failures == attempt+ assert s.status == "paused"+ assert s.pause_reason == "failures"+ assert s.next_sequence == 1 # nothing was skipped by failing++ @pytest.mark.asyncio+ async def test_a_success_resets_the_failure_count(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ with patch.object(svc, "_emit", side_effect=RuntimeError("once")):+ with pytest.raises(RuntimeError):+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert s.consecutive_failures == 1+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert s.consecutive_failures == 0+ assert s.status == "active"++ @pytest.mark.asyncio+ async def test_the_unique_index_is_the_last_line_of_defence(self, session, ws_id, test_user):+ """Two invoices for one period cannot exist, whatever the code does."""+ from sqlalchemy.exc import IntegrityError++ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ [first] = await svc.generate_due(session, s, today=date(2026, 10, 5))+ await session.commit()+ dup = await invoice_service.create_invoice(+ session, ws_id, test_user.id, {"total": Decimal("1.00"), "issue_date": date(2026, 10, 5)}+ )+ dup.schedule_id = s.id+ dup.sequence = first.sequence+ dup.period_start, dup.period_end = first.period_start, first.period_end+ with pytest.raises(IntegrityError):+ await session.flush()+ await session.rollback()+++class TestTermRules:+ @pytest.mark.asyncio+ async def test_a_future_term_can_be_added_changed_and_removed(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ t = await svc.add_term(+ session, s, effective_from=date(2027, 1, 1), lines=[{"description": "R", "unit_price": "3500"}]+ )+ assert t.total == Decimal("3500.00")+ await svc.update_term(session, s, t, lines=[{"description": "R", "unit_price": "3600"}])+ assert t.total == Decimal("3600.00")+ await svc.update_term(session, s, t, effective_from=date(2027, 2, 1))+ assert t.effective_from == date(2027, 2, 1)+ await svc.delete_term(session, s, t)+ assert len(s.terms) == 1++ @pytest.mark.asyncio+ async def test_adding_on_an_existing_date_replaces_that_term(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.add_term(session, s, effective_from=date(2027, 1, 1), lines=[{"description": "R", "unit_price": "3500"}])+ await svc.add_term(session, s, effective_from=date(2027, 1, 1), lines=[{"description": "R", "unit_price": "3600"}])+ assert len(s.terms) == 2+ january = svc.term_for(s, date(2027, 1, 1))+ assert january is not None and january.total == Decimal("3600.00")++ @pytest.mark.asyncio+ async def test_a_term_an_invoice_was_issued_under_is_history(self, session, ws_id, test_user):+ """The retroactivity rule. Once January was billed, nothing may+ change what January cost; a raise goes on a later date."""+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.generate_due(session, s, today=date(2026, 11, 5)) # periods 1 and 2++ for effective_from in (date(2026, 10, 5), date(2026, 11, 1), date(2026, 11, 5)):+ with pytest.raises(InvoiceError) as exc:+ await svc.add_term(session, s, effective_from=effective_from, lines=[{"description": "R", "unit_price": "1"}])+ assert exc.value.code == "term_in_use"++ first = s.terms[0]+ with pytest.raises(InvoiceError) as exc:+ await svc.update_term(session, s, first, lines=[{"description": "R", "unit_price": "1"}])+ assert exc.value.code == "term_in_use"+ with pytest.raises(InvoiceError) as exc:+ await svc.delete_term(session, s, first)+ assert exc.value.code in ("term_in_use", "last_term")++ # The day after the last billed period start is free.+ t = await svc.add_term(session, s, effective_from=date(2026, 11, 6), lines=[{"description": "R", "unit_price": "3500"}])+ [december] = await svc.generate_due(session, s, today=date(2026, 12, 5))+ assert december.total == Decimal("3500.00")+ assert december.period_start is not None+ governing = svc.term_for(s, december.period_start)+ assert governing is not None and governing.id == t.id++ @pytest.mark.asyncio+ async def test_the_last_term_cannot_go_and_none_may_precede_the_start(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ with pytest.raises(InvoiceError) as exc:+ await svc.delete_term(session, s, s.terms[0])+ assert exc.value.code == "last_term"+ with pytest.raises(InvoiceError) as exc:+ await svc.add_term(session, s, effective_from=date(2026, 10, 4), lines=[dict(LINE)])+ assert exc.value.code == "term_before_start"++ @pytest.mark.asyncio+ async def test_an_ended_agreement_takes_no_terms(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id)+ await svc.end_schedule(session, s, reason="other", today=TODAY)+ with pytest.raises(InvoiceError) as exc:+ await svc.add_term(session, s, effective_from=date(2027, 1, 1), lines=[dict(LINE)])+ assert exc.value.code == "schedule_ended"+++async def an_invoice(session, ws_id, user_id, **overrides) -> Invoice:+ """Straight into the service, so money is `Decimal` as the API layer+ would have made it, and the due date follows a moved issue date."""+ data: dict[str, object] = {"total": Decimal("3000.00"), "issue_date": date(2026, 9, 5)}+ data.update(overrides)+ issue = data["issue_date"]+ assert isinstance(issue, date)+ data.setdefault("due_date", issue + timedelta(days=15))+ for key in ("total", "discount"):+ value = data.get(key)+ if isinstance(value, str):+ data[key] = Decimal(value)+ invoice = await invoice_service.create_invoice(session, ws_id, user_id, data)+ await session.commit()+ return invoice+++class TestLinking:+ @pytest.mark.asyncio+ async def test_links_on_a_boundary_and_labels_the_period(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 3, 5))+ inv = await an_invoice(session, ws_id, test_user.id, issue_date=date(2026, 6, 7))+ await svc.link_invoice(session, s, inv, date(2026, 6, 5))+ assert inv.sequence == 4+ assert (inv.period_start, inv.period_end) == (date(2026, 6, 5), date(2026, 7, 4))+ # A past period does not move the cursor back or forward.+ assert s.next_sequence == 8++ @pytest.mark.asyncio+ async def test_linking_at_or_past_the_cursor_moves_it(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 3, 5))+ inv = await an_invoice(session, ws_id, test_user.id, issue_date=date(2026, 10, 5))+ await svc.link_invoice(session, s, inv, date(2026, 10, 5))+ assert s.next_sequence == 9 # Nov 5: October was billed by hand++ @pytest.mark.asyncio+ async def test_refusals(self, session, ws_id, test_user, client_payee):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 3, 5), payee_id=client_payee.id)++ inside = await an_invoice(session, ws_id, test_user.id)+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, inside, date(2026, 6, 6))+ assert exc.value.code == "not_a_period"++ euro = await an_invoice(session, ws_id, test_user.id, currency="EUR")+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, euro, date(2026, 6, 5))+ assert exc.value.code == "currency_mismatch"++ other = Payee(id=uuid.uuid4(), user_id=test_user.id, workspace_id=ws_id, name="Beta", source="manual")+ session.add(other)+ await session.flush()+ someone_else = await an_invoice(session, ws_id, test_user.id, payee_id=other.id)+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, someone_else, date(2026, 6, 5))+ assert exc.value.code == "payee_mismatch"++ voided = await an_invoice(session, ws_id, test_user.id)+ await invoice_service.void_invoice(session, voided)+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, voided, date(2026, 6, 5))+ assert exc.value.code == "invoice_void"++ ok = await an_invoice(session, ws_id, test_user.id)+ await svc.link_invoice(session, s, ok, date(2026, 6, 5))+ again = await an_invoice(session, ws_id, test_user.id)+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, again, date(2026, 6, 5))+ assert exc.value.code == "period_taken"+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, ok, date(2026, 7, 5))+ assert exc.value.code == "already_linked"++ capped = await make_schedule(+ session, ws_id, test_user.id, start_date=date(2026, 3, 5), end_type="after_count", end_count=2+ )+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, capped, again, date(2026, 6, 5))+ assert exc.value.code == "beyond_end"++ @pytest.mark.asyncio+ async def test_an_invoice_never_crosses_a_workspace(self, session, ws_id, test_user, client, auth_headers):+ resp = await client.post(+ "/api/workspaces", headers=auth_headers,+ json={"name": "Outra", "kind": "business", "self_membership": True},+ )+ other_ws = uuid.UUID(resp.json()["id"])+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 3, 5))+ foreign = await an_invoice(session, other_ws, test_user.id)+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, foreign, date(2026, 6, 5))+ assert exc.value.code == "invoice_not_found"++ @pytest.mark.asyncio+ async def test_unlink_frees_the_period_and_leaves_the_cursor(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ [inv] = await svc.generate_due(session, s, today=date(2026, 10, 5))+ await svc.unlink_invoice(session, inv)+ assert inv.schedule_id is None and inv.sequence is None and inv.period_start is None+ assert s.next_sequence == 2+ assert await svc.generate_due(session, s, today=date(2026, 10, 5)) == []+ replacement = await an_invoice(session, ws_id, test_user.id, issue_date=date(2026, 10, 5))+ await svc.link_invoice(session, s, replacement, date(2026, 10, 5))+ assert replacement.sequence == 1++ @pytest.mark.asyncio+ async def test_make_recurring_from_an_invoice_with_lines(self, session, ws_id, test_user, client_payee):+ inv = await an_invoice(+ session, ws_id, test_user.id, payee_id=client_payee.id, issue_date=date(2026, 9, 5),+ due_date=date(2026, 9, 25), total=None, discount="100.00",+ lines=[+ {"description": "Consultoria", "quantity": 10, "unit": "h", "unit_price": "200.00", "tax_rate": "5"},+ ],+ )+ s = await svc.make_recurring(session, inv, test_user.id, {"frequency": "monthly"}, today=TODAY)+ assert s.name == "Consultoria"+ assert s.payee_id == client_payee.id+ assert s.start_date == date(2026, 9, 5)+ assert s.payment_terms_days == 20+ assert s.terms[0].total == inv.total+ assert s.terms[0].lines[0]["unit"] == "h"+ assert inv.schedule_id == s.id and inv.sequence == 1+ assert s.next_sequence == 2+ assert svc.next_period_start(s) == date(2026, 10, 5)++ @pytest.mark.asyncio+ async def test_make_recurring_from_a_three_field_invoice(self, session, ws_id, test_user):+ inv = await an_invoice(session, ws_id, test_user.id, total="1500.00")+ s = await svc.make_recurring(+ session, inv, test_user.id, {"frequency": "quarterly", "name": "Hosting"}, today=TODAY+ )+ assert s.terms[0].lines == [+ {"description": "Hosting", "quantity": "1", "unit": None, "unit_price": "1500.00", "tax_rate": None}+ ]+ assert s.terms[0].total == Decimal("1500.00")++ @pytest.mark.asyncio+ async def test_make_recurring_with_an_earlier_anchor_leaves_room_for_history(self, session, ws_id, test_user):+ """"This has been going since March": the invoice in hand becomes+ period seven, March to August are free to link, and the cursor+ still sits on the next period from today."""+ inv = await an_invoice(session, ws_id, test_user.id, issue_date=date(2026, 9, 5))+ s = await svc.make_recurring(+ session, inv, test_user.id,+ {"frequency": "monthly", "name": "Retainer", "start_date": date(2026, 3, 5)}, today=TODAY,+ )+ assert s.start_date == date(2026, 3, 5)+ assert inv.sequence == 7+ assert s.next_sequence == 8+ march = await an_invoice(session, ws_id, test_user.id, issue_date=date(2026, 3, 5))+ await svc.link_invoice(session, s, march, date(2026, 3, 5))+ assert march.sequence == 1++ off = await an_invoice(session, ws_id, test_user.id, issue_date=date(2026, 9, 6))+ with pytest.raises(InvoiceError) as exc:+ await svc.make_recurring(+ session, off, test_user.id,+ {"frequency": "monthly", "name": "R", "start_date": date(2026, 3, 5)}, today=TODAY,+ )+ assert exc.value.code == "not_a_period"+ with pytest.raises(InvoiceError) as exc:+ await svc.make_recurring(+ session, off, test_user.id,+ {"frequency": "monthly", "name": "R", "start_date": date(2026, 10, 1)}, today=TODAY,+ )+ assert exc.value.code == "start_after_invoice"++ @pytest.mark.asyncio+ async def test_make_recurring_needs_an_issued_unlinked_invoice(self, session, ws_id, test_user):+ draft = await an_invoice(session, ws_id, test_user.id, as_draft=True)+ with pytest.raises(InvoiceError) as exc:+ await svc.make_recurring(session, draft, test_user.id, {"frequency": "monthly"})+ assert exc.value.code == "not_issued"+ inv = await an_invoice(session, ws_id, test_user.id)+ # No lines, no client, no name given: nothing to call it.+ with pytest.raises(InvoiceError) as exc:+ await svc.make_recurring(session, inv, test_user.id, {"frequency": "monthly"}, today=TODAY)+ assert exc.value.code == "name_required"+ await svc.make_recurring(session, inv, test_user.id, {"frequency": "monthly", "name": "Hosting"}, today=TODAY)+ with pytest.raises(InvoiceError) as exc:+ await svc.make_recurring(session, inv, test_user.id, {"frequency": "monthly", "name": "Hosting"}, today=TODAY)+ assert exc.value.code == "already_linked"++ @pytest.mark.asyncio+ async def test_delete_refuses_once_anything_was_billed(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ with pytest.raises(InvoiceError) as exc:+ await svc.delete_schedule(session, s)+ assert exc.value.code == "schedule_has_invoices"+ empty = await make_schedule(session, ws_id, test_user.id)+ await svc.delete_schedule(session, empty)+ assert await svc.get_schedule(session, empty.id, ws_id) is None+++class TestLifecycle:+ @pytest.mark.asyncio+ async def test_pause_then_resume_skips_the_gap(self, session, ws_id, test_user):+ """A pause is "stop billing". Resuming does not bill the months+ that fell while paused."""+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ await svc.pause_schedule(session, s)+ assert s.pause_reason == "manual"+ await svc.resume_schedule(session, s, today=date(2027, 1, 20))+ assert s.status == "active" and s.pause_reason is None+ assert s.next_sequence == 5 # Feb 5; Nov, Dec, Jan are not billed+ assert await svc.generate_due(session, s, today=date(2027, 1, 20)) == []++ @pytest.mark.asyncio+ async def test_resuming_past_the_end_completes_it(self, session, ws_id, test_user):+ s = await make_schedule(+ session, ws_id, test_user.id, start_date=date(2026, 10, 5), end_type="on_date", end_date=date(2026, 12, 31)+ )+ await svc.pause_schedule(session, s)+ await svc.resume_schedule(session, s, today=date(2027, 3, 1))+ assert s.status == "ended" and s.end_reason == "completed"++ @pytest.mark.asyncio+ async def test_end_records_when_and_why(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 3, 5))+ await svc.end_schedule(session, s, reason="canceled_by_client", ended_at=date(2026, 9, 1), today=TODAY)+ assert (s.status, s.ended_at, s.end_reason) == ("ended", date(2026, 9, 1), "canceled_by_client")+ with pytest.raises(InvoiceError):+ await svc.resume_schedule(session, s)+ with pytest.raises(InvoiceError):+ await svc.pause_schedule(session, s)+ with pytest.raises(InvoiceError):+ await svc.update_schedule(session, s, {"name": "x"})+ with pytest.raises(InvoiceError) as exc:+ await svc.end_schedule(session, await make_schedule(session, ws_id, test_user.id), reason="nope")+ assert exc.value.code == "invalid_end_reason"++ @pytest.mark.asyncio+ async def test_calendar_is_free_until_the_first_invoice(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.update_schedule(session, s, {"frequency": "weekly", "start_date": date(2026, 10, 1)}, today=TODAY)+ assert (s.frequency, s.start_date, s.next_sequence) == ("weekly", date(2026, 10, 1), 1)+ assert s.terms[0].effective_from == date(2026, 10, 1) # the first term moved with the anchor+ await svc.generate_due(session, s, today=date(2026, 10, 1))+ for change in ({"frequency": "monthly"}, {"start_date": date(2026, 10, 2)}, {"currency": "EUR"}):+ with pytest.raises(InvoiceError) as exc:+ await svc.update_schedule(session, s, change, today=TODAY)+ assert exc.value.code == "schedule_locked"+ # The same value is not a change.+ await svc.update_schedule(session, s, {"frequency": "weekly", "currency": "usd"}, today=TODAY)++ @pytest.mark.asyncio+ async def test_editable_fields_and_an_end_already_behind_the_cursor(self, session, ws_id, test_user, client_payee):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.generate_due(session, s, today=date(2026, 12, 5)) # 1..3, cursor 4+ await svc.update_schedule(+ session, s,+ {"name": " Plano Pro ", "payee_id": client_payee.id, "payment_terms_days": 5, "notes": "n"},+ today=date(2026, 12, 5),+ )+ assert (s.name, s.payee_id, s.payment_terms_days, s.notes) == ("Plano Pro", client_payee.id, 5, "n")+ await svc.update_schedule(session, s, {"end_type": "after_count", "end_count": 3}, today=date(2026, 12, 5))+ assert s.status == "ended" and s.end_reason == "completed"+++class TestFigures:+ @pytest.mark.asyncio+ async def test_figures_come_from_the_invoices(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5), payment_terms_days=10)+ emitted = await svc.generate_due(session, s, today=date(2026, 12, 5)) # 3 invoices of 3000+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=ws_id, name="PJ", type="checking",+ currency="USD", balance=Decimal("0"),+ )+ session.add(account)+ await session.flush()+ tx = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=ws_id, account_id=account.id,+ description="PIX", amount=Decimal("3000.00"), currency="USD", date=date(2026, 10, 10),+ type="credit", source="manual",+ )+ session.add(tx)+ await session.flush()+ session.add(InvoiceAllocation(+ invoice_id=emitted[0].id, workspace_id=ws_id, transaction_id=tx.id, amount=Decimal("3000.00"),+ ))+ await invoice_service.void_invoice(session, emitted[2])+ await session.commit()++ figures = (await svc.figures_for(session, ws_id, [s.id], today=date(2026, 12, 1)))[s.id]+ assert figures.invoice_count == 3+ assert figures.amount_invoiced == Decimal("6000.00") # the voided one reads as zero+ assert figures.amount_paid == Decimal("3000.00")+ assert figures.past_due_count == 1 # November, due Nov 15, unpaid++ @pytest.mark.asyncio+ async def test_summary_is_per_currency_and_counts_churn(self, session, ws_id, test_user):+ usd = await make_schedule(session, ws_id, test_user.id, frequency="monthly")+ quarterly = await make_schedule(+ session, ws_id, test_user.id, frequency="quarterly",+ lines=[{"description": "Q", "unit_price": "900.00"}],+ )+ eur = await make_schedule(session, ws_id, test_user.id, currency="EUR", lines=[{"description": "E", "unit_price": "100.00"}])+ paused = await make_schedule(session, ws_id, test_user.id)+ await svc.pause_schedule(session, paused)+ churned = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 1, 5))+ await svc.end_schedule(session, churned, reason="canceled_by_client", ended_at=TODAY - timedelta(days=10), today=TODAY)+ long_gone = await make_schedule(session, ws_id, test_user.id, start_date=date(2025, 1, 5))+ await svc.end_schedule(session, long_gone, reason="unpaid", ended_at=TODAY - timedelta(days=90), today=TODAY)+ await session.commit()++ summary = await svc.summary(session, ws_id, today=TODAY)+ assert (summary.active_count, summary.paused_count, summary.ended_count) == (3, 1, 2)+ by = {c.currency: c for c in summary.by_currency}+ assert by["USD"].monthly_recurring == Decimal("3300.00") # 3000 + 900/3+ assert by["USD"].active_count == 2+ assert by["USD"].ended_recently_count == 1+ assert by["USD"].monthly_lost == Decimal("3000.00")+ assert by["EUR"].monthly_recurring == Decimal("100.00")+ assert usd.id and quarterly.id and eur.id+++class TestForecast:+ @pytest.mark.asyncio+ async def test_projected_periods_replace_nothing_and_are_replaced_by_the_invoice(self, session, ws_id, test_user):+ """The no-double-count rule, one level up: a period is projected+ until its invoice exists, and then the invoice is what is projected."""+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5), payment_terms_days=10)+ window = (date(2026, 10, 1), date(2027, 1, 1))+ claims = await forecast.claims_in_range(session, ws_id, *window)+ assert sorted((c.due_date, c.amount) for c in claims) == [+ (date(2026, 10, 15), Decimal("3000.00")),+ (date(2026, 11, 15), Decimal("3000.00")),+ (date(2026, 12, 15), Decimal("3000.00")),+ ]+ assert all(c.direction == "receivable" and c.currency == "USD" for c in claims)++ await svc.generate_due(session, s, today=date(2026, 10, 5))+ await session.commit()+ claims = await forecast.claims_in_range(session, ws_id, *window)+ assert len(claims) == 3 # still three: October is now the invoice, not the projection+ assert sum(c.amount for c in claims) == Decimal("9000.00")++ @pytest.mark.asyncio+ async def test_projection_honours_the_end_the_pause_and_the_terms(self, session, ws_id, test_user):+ s = await make_schedule(+ session, ws_id, test_user.id, start_date=date(2026, 10, 5), payment_terms_days=0,+ end_type="after_count", end_count=2,+ )+ await svc.add_term(session, s, effective_from=date(2026, 11, 1), lines=[{"description": "R", "unit_price": "10.00"}])+ projected = await svc.projected_periods(session, ws_id, date(2026, 1, 1), date(2028, 1, 1))+ assert [(p.due_date, p.amount) for p in projected] == [+ (date(2026, 10, 5), Decimal("3000.00")),+ (date(2026, 11, 5), Decimal("10.00")),+ ]+ await svc.pause_schedule(session, s)+ assert await svc.projected_periods(session, ws_id, date(2026, 1, 1), date(2028, 1, 1)) == []++ @pytest.mark.asyncio+ async def test_payables_ask_for_no_projection(self, session, ws_id, test_user):+ await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ claims = await forecast.claims_in_range(+ session, ws_id, date(2026, 1, 1), date(2028, 1, 1), directions=("payable",)+ )+ assert claims == []+++class TestWorkerTask:+ """The Celery task's own promise: one agreement failing never stops+ the others, and the failure count survives the rollback."""++ @pytest.mark.asyncio+ async def test_one_run_emits_for_every_due_schedule(self, session, ws_id, test_user, monkeypatch):+ from tests.conftest import TestSessionLocal+ from app.tasks import invoice_schedule_tasks as task++ a = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 1, 5), today=date(2026, 1, 1))+ b = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 1, 5), today=date(2026, 1, 1))+ monkeypatch.setattr(svc, "_today", lambda: date(2026, 1, 5))+ ids = await svc.due_schedule_ids(session)+ assert {a.id, b.id} <= set(ids)+ total = 0+ for schedule_id in (a.id, b.id):+ total += await task._generate_one(TestSessionLocal, schedule_id)+ assert total == 2+ assert len(await invoices_of(session, a.id)) == 1+ assert len(await invoices_of(session, b.id)) == 1++ @pytest.mark.asyncio+ async def test_a_failure_is_counted_and_committed_without_the_invoice(self, session, ws_id, test_user, monkeypatch):+ from tests.conftest import TestSessionLocal+ from app.tasks import invoice_schedule_tasks as task++ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 1, 5), today=date(2026, 1, 1))+ monkeypatch.setattr(svc, "_today", lambda: date(2026, 1, 5))+ with patch.object(svc, "_emit", side_effect=RuntimeError("boom")):+ for _ in range(3):+ assert await task._generate_one(TestSessionLocal, s.id) == 0+ await session.refresh(s)+ assert s.consecutive_failures == 3+ assert s.status == "paused" and s.pause_reason == "failures"+ assert await invoices_of(session, s.id) == []+ # Once paused it is no longer due, so the next run leaves it alone.+ assert s.id not in await svc.due_schedule_ids(session)++ @pytest.mark.asyncio+ async def test_a_missing_schedule_is_a_no_op(self, session):+ from tests.conftest import TestSessionLocal+ from app.tasks import invoice_schedule_tasks as task++ assert await task._generate_one(TestSessionLocal, uuid.uuid4()) == 0+++class TestReviewRegressions:+ """One test per hole found in review, each failing if it reopens."""++ @pytest.mark.asyncio+ async def test_the_first_term_cannot_be_deleted_or_moved(self, session, ws_id, test_user):+ """Deleting or moving the price in force from the start would leave+ the first periods unpriced, and the job would pause the agreement."""+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ first = s.terms[0]+ await svc.add_term(session, s, effective_from=date(2027, 1, 1), lines=[{"description": "R", "unit_price": "3500"}])+ with pytest.raises(InvoiceError) as exc:+ await svc.delete_term(session, s, first)+ assert exc.value.code == "first_term"+ with pytest.raises(InvoiceError) as exc:+ await svc.update_term(session, s, first, effective_from=date(2026, 11, 1))+ assert exc.value.code == "first_term"+ # Its price may still change, and the later term may still go.+ await svc.update_term(session, s, first, lines=[{"description": "R", "unit_price": "3100"}])+ assert first.total == Decimal("3100.00")+ await svc.delete_term(session, s, s.terms[1])+ [october] = await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert october.total == Decimal("3100.00")++ @pytest.mark.asyncio+ async def test_moving_the_start_onto_a_later_term_is_refused_not_a_500(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.add_term(session, s, effective_from=date(2027, 1, 1), lines=[{"description": "R", "unit_price": "3500"}])+ with pytest.raises(InvoiceError) as exc:+ await svc.update_schedule(session, s, {"start_date": date(2027, 1, 1)}, today=TODAY)+ assert exc.value.code == "term_before_start"++ @pytest.mark.asyncio+ async def test_resuming_after_failures_bills_the_period_that_failed(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ with patch.object(svc, "_emit", side_effect=RuntimeError("storage down")):+ for _ in range(3):+ with pytest.raises(RuntimeError):+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert s.pause_reason == "failures"+ await svc.resume_schedule(session, s, today=date(2026, 10, 10))+ assert s.next_sequence == 1+ [october] = await svc.generate_due(session, s, today=date(2026, 10, 10))+ assert october.period_start == date(2026, 10, 5)++ @pytest.mark.asyncio+ async def test_a_manual_pause_still_skips_the_gap(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))+ await svc.pause_schedule(session, s)+ await svc.resume_schedule(session, s, today=date(2026, 10, 10))+ assert s.next_sequence == 2++ @pytest.mark.asyncio+ async def test_a_payable_never_joins_an_agreement(self, session, ws_id, test_user):+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 3, 5))+ bill = await an_invoice(session, ws_id, test_user.id, direction="payable", issue_date=date(2026, 6, 5))+ with pytest.raises(InvoiceError) as exc:+ await svc.link_invoice(session, s, bill, date(2026, 6, 5))+ assert exc.value.code == "not_receivable"+ with pytest.raises(InvoiceError) as exc:+ await svc.make_recurring(session, bill, test_user.id, {"frequency": "monthly", "name": "Rent"}, today=TODAY)+ assert exc.value.code == "not_receivable"++ @pytest.mark.asyncio+ async def test_a_period_issued_by_another_run_is_a_409_not_a_failure(self, session, ws_id, test_user):+ """Two runs read the same cursor; the second trips the unique+ (schedule, sequence). That is a no-op, never a counted failure."""+ from sqlalchemy.exc import IntegrityError++ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5))++ async def racing_emit(*_args, **_kwargs):+ raise IntegrityError("INSERT", {}, Exception("uq_invoices_schedule_sequence"))++ with patch.object(svc, "_emit", side_effect=racing_emit):+ with pytest.raises(InvoiceError) as exc:+ await svc.generate_due(session, s, today=date(2026, 10, 5))+ assert exc.value.code == "period_already_issued"+ assert exc.value.status_code == 409+ await session.refresh(s)+ assert s.consecutive_failures == 0+ assert s.status == "active"++ @pytest.mark.asyncio+ async def test_the_worker_treats_the_race_as_nothing_to_do(self, session, ws_id, test_user, monkeypatch):+ from tests.conftest import TestSessionLocal+ from app.tasks import invoice_schedule_tasks as task++ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 1, 5), today=date(2026, 1, 1))+ monkeypatch.setattr(svc, "_today", lambda: date(2026, 1, 5))+ race = InvoiceError("period_already_issued", "raced", status_code=409)+ with patch.object(svc, "generate_due", side_effect=race):+ assert await task._generate_one(TestSessionLocal, s.id) == 0+ await session.refresh(s)+ assert s.consecutive_failures == 0 and s.status == "active"++ @pytest.mark.asyncio+ async def test_a_worker_holding_a_stale_instance_emits_from_the_new_calendar(+ self, session, ws_id, test_user+ ):+ """A worker loads the agreement, a PATCH then moves its start and+ cursor, and only after that does the worker emit. It must emit from+ what was committed, not from what it loaded."""+ from tests.conftest import TestSessionLocal++ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5), today=date(2026, 10, 1))+ async with TestSessionLocal() as worker:+ stale = await worker.get(InvoiceSchedule, s.id)+ assert stale is not None and stale.start_date == date(2026, 10, 5)++ await svc.update_schedule(session, s, {"start_date": date(2026, 12, 5)}, today=date(2026, 10, 1))+ await session.commit()++ emitted = await svc.generate_due(worker, stale, today=date(2026, 12, 5))+ assert [(i.sequence, i.period_start) for i in emitted] == [(1, date(2026, 12, 5))]+ await worker.commit()diff --git a/backend/tests/test_invoice_schedules_api.py b/backend/tests/test_invoice_schedules_api.pynew file mode 100644index 00000000..fddb6508--- /dev/null+++ b/backend/tests/test_invoice_schedules_api.py@@ -0,0 +1,440 @@+"""Recurring invoices over HTTP.++The service tests own the rules; these own the wiring: that every route+is gated exactly like `/api/invoices`, that a viewer can read and never+write, and that the journeys a person actually takes (write a retainer,+see its invoices arrive, raise the price, link history, end it) hold+together end to end.+"""+import uuid+from datetime import date, timedelta++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.payee import Payee+from app.models.workspace import WorkspaceMember+++@pytest_asyncio.fixture+async def business_ws(client: AsyncClient, auth_headers) -> dict:+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Estudio", "kind": "business", "self_membership": True},+ )+ assert resp.status_code == 201, resp.text+ return resp.json()+++@pytest_asyncio.fixture+async def biz_headers(auth_headers, business_ws) -> dict:+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}+++@pytest_asyncio.fixture+async def personal_headers(session: AsyncSession, auth_headers, test_user) -> dict:+ from sqlalchemy import select++ from app.models.workspace import Workspace++ result = await session.execute(+ select(Workspace)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(WorkspaceMember.user_id == test_user.id, Workspace.kind == "personal")+ .limit(1)+ )+ return {**auth_headers, "X-Workspace-Id": str(result.scalar_one().id)}+++@pytest_asyncio.fixture+async def client_payee(session: AsyncSession, business_ws, test_user) -> Payee:+ payee = Payee(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=uuid.UUID(business_ws["id"]),+ name="Cliente Alpha",+ source="manual",+ )+ session.add(payee)+ await session.commit()+ return payee+++@pytest_asyncio.fixture+async def viewer_headers(session: AsyncSession, client: AsyncClient, business_ws) -> dict:+ """A viewer of the business workspace: may read, may not write."""+ import bcrypt++ from app.models.user import User++ user = User(+ id=uuid.uuid4(),+ email="[email protected]",+ hashed_password=bcrypt.hashpw(b"viewerpass123", bcrypt.gensalt()).decode(),+ is_active=True,+ is_superuser=False,+ is_verified=True,+ )+ session.add(user)+ await session.flush()+ session.add(+ WorkspaceMember(+ id=uuid.uuid4(), workspace_id=uuid.UUID(business_ws["id"]), user_id=user.id, role="viewer"+ )+ )+ await session.commit()+ resp = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "viewerpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert resp.status_code == 200, resp.text+ return {+ "Authorization": f"Bearer {resp.json()['access_token']}",+ "X-Workspace-Id": business_ws["id"],+ }+++TODAY = date.today()+NEXT_MONTH = (TODAY.replace(day=1) + timedelta(days=32)).replace(day=1)+++async def _create(client, headers, **overrides) -> dict:+ payload = {+ "name": "Retainer",+ "frequency": "monthly",+ "start_date": str(NEXT_MONTH),+ "lines": [{"description": "Retainer", "quantity": 1, "unit_price": "3000.00"}],+ }+ payload.update(overrides)+ resp = await client.post("/api/invoice-schedules", headers=headers, json=payload)+ assert resp.status_code == 201, resp.text+ return resp.json()+++# ---------------------------------------------------------------------------+# Gating+# ---------------------------------------------------------------------------+async def test_personal_workspace_cannot_reach_any_route(client: AsyncClient, personal_headers):+ """Every route, not a sample: one ungated route is the whole hole."""+ fake = str(uuid.uuid4())+ routes = [+ ("get", "/api/invoice-schedules", None),+ ("get", "/api/invoice-schedules/summary", None),+ ("post", "/api/invoice-schedules", {"name": "x", "frequency": "monthly", "lines": [{"description": "a", "unit_price": "1"}]}),+ ("get", f"/api/invoice-schedules/{fake}", None),+ ("patch", f"/api/invoice-schedules/{fake}", {"name": "y"}),+ ("delete", f"/api/invoice-schedules/{fake}", None),+ ("get", f"/api/invoice-schedules/{fake}/invoices", None),+ ("get", f"/api/invoice-schedules/{fake}/periods", None),+ ("post", f"/api/invoice-schedules/{fake}/pause", None),+ ("post", f"/api/invoice-schedules/{fake}/resume", None),+ ("post", f"/api/invoice-schedules/{fake}/end", {"reason": "other"}),+ ("post", f"/api/invoice-schedules/{fake}/generate", None),+ ("post", f"/api/invoice-schedules/{fake}/terms", {"effective_from": str(TODAY), "lines": [{"description": "a", "unit_price": "1"}]}),+ ("patch", f"/api/invoice-schedules/{fake}/terms/{fake}", {"discount": "1"}),+ ("delete", f"/api/invoice-schedules/{fake}/terms/{fake}", None),+ ("post", f"/api/invoice-schedules/{fake}/link", {"invoice_id": fake, "period_start": str(TODAY)}),+ ("post", f"/api/invoices/{fake}/make-recurring", {"frequency": "monthly"}),+ ("delete", f"/api/invoices/{fake}/schedule", None),+ ]+ for method, url, body in routes:+ call = getattr(client, method)+ resp = await call(url, headers=personal_headers, **({"json": body} if body else {}))+ assert resp.status_code == 404, f"{method.upper()} {url} -> {resp.status_code}"+++async def test_viewer_reads_and_never_writes(client: AsyncClient, biz_headers, viewer_headers):+ created = await _create(client, biz_headers)+ sid = created["id"]++ for url in ("/api/invoice-schedules", "/api/invoice-schedules/summary", f"/api/invoice-schedules/{sid}",+ f"/api/invoice-schedules/{sid}/invoices", f"/api/invoice-schedules/{sid}/periods"):+ assert (await client.get(url, headers=viewer_headers)).status_code == 200, url++ writes = [+ ("post", "/api/invoice-schedules", {"name": "x", "frequency": "monthly", "lines": [{"description": "a", "unit_price": "1"}]}),+ ("patch", f"/api/invoice-schedules/{sid}", {"name": "y"}),+ ("delete", f"/api/invoice-schedules/{sid}", None),+ ("post", f"/api/invoice-schedules/{sid}/pause", None),+ ("post", f"/api/invoice-schedules/{sid}/resume", None),+ ("post", f"/api/invoice-schedules/{sid}/end", {"reason": "other"}),+ ("post", f"/api/invoice-schedules/{sid}/generate", None),+ ("post", f"/api/invoice-schedules/{sid}/terms", {"effective_from": str(NEXT_MONTH), "lines": [{"description": "a", "unit_price": "1"}]}),+ ("post", f"/api/invoice-schedules/{sid}/link", {"invoice_id": sid, "period_start": str(NEXT_MONTH)}),+ ]+ for method, url, body in writes:+ call = getattr(client, method)+ resp = await call(url, headers=viewer_headers, **({"json": body} if body else {}))+ assert resp.status_code == 403, f"{method.upper()} {url} -> {resp.status_code}"+++async def test_a_schedule_never_crosses_workspaces(client: AsyncClient, auth_headers, biz_headers):+ created = await _create(client, biz_headers)+ other = await client.post(+ "/api/workspaces", headers=auth_headers,+ json={"name": "Outra", "kind": "business", "self_membership": True},+ )+ other_headers = {**auth_headers, "X-Workspace-Id": other.json()["id"]}+ assert (await client.get(f"/api/invoice-schedules/{created['id']}", headers=other_headers)).status_code == 404+ assert (await client.get("/api/invoice-schedules", headers=other_headers)).json() == []+ resp = await client.post(+ f"/api/invoice-schedules/{created['id']}/link", headers=other_headers,+ json={"invoice_id": str(uuid.uuid4()), "period_start": str(NEXT_MONTH)},+ )+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# Journeys+# ---------------------------------------------------------------------------+async def test_create_reads_back_with_derived_figures(client: AsyncClient, biz_headers, client_payee):+ created = await _create(+ client, biz_headers, payee_id=str(client_payee.id), frequency="quarterly",+ lines=[{"description": "Hosting", "quantity": 1, "unit_price": "900.00", "tax_rate": "10"}],+ discount="50.00", payment_terms_days=10,+ )+ assert created["status"] == "active"+ assert created["payee"]["name"] == "Cliente Alpha"+ assert created["next_sequence"] == 1+ assert created["next_period_start"] == str(NEXT_MONTH)+ assert created["current_term"] is None # not in force until it starts+ assert created["next_term"]["total"] == "940.00" # 900 - 50 + 90+ assert created["invoice_count"] == 0+ assert len(created["terms"]) == 1++ summary = (await client.get("/api/invoice-schedules/summary", headers=biz_headers)).json()+ assert summary["active_count"] == 1+ # The agreement has not started, so nothing recurs yet; it is active+ # but worth zero a month until its first term is in force.+ assert summary["by_currency"][0]["monthly_recurring"] == "0.00"+++async def test_generate_now_emits_an_ordinary_invoice_that_remembers_its_period(+ client: AsyncClient, biz_headers, client_payee+):+ created = await _create(client, biz_headers, payee_id=str(client_payee.id))+ sid = created["id"]+ resp = await client.post(f"/api/invoice-schedules/{sid}/generate", headers=biz_headers)+ assert resp.status_code == 201, resp.text+ [invoice] = resp.json()+ assert invoice["status"] == "open"+ assert invoice["number"] is not None+ assert invoice["schedule_id"] == sid+ assert invoice["schedule"]["name"] == "Retainer"+ assert invoice["sequence"] == 1+ assert invoice["period_start"] == str(NEXT_MONTH)+ assert invoice["issue_date"] == str(NEXT_MONTH)+ assert invoice["total"] == "3000.00"+ assert [line["description"] for line in invoice["lines"]] == ["Retainer"]++ # It is a normal invoice: on the list, in the detail, filterable by agreement.+ listed = (await client.get("/api/invoices", headers=biz_headers, params={"schedule_id": sid})).json()+ assert [i["id"] for i in listed] == [invoice["id"]]+ listed = (await client.get(f"/api/invoice-schedules/{sid}/invoices", headers=biz_headers)).json()+ assert [i["id"] for i in listed] == [invoice["id"]]++ schedule = (await client.get(f"/api/invoice-schedules/{sid}", headers=biz_headers)).json()+ assert schedule["next_sequence"] == 2+ assert schedule["invoice_count"] == 1+ assert schedule["amount_invoiced"] == "3000.00"+ assert schedule["amount_paid"] == "0.00"+ assert schedule["last_generated_at"] is not None++ periods = (await client.get(f"/api/invoice-schedules/{sid}/periods", headers=biz_headers)).json()+ assert periods[0] == {+ "sequence": 1, "period_start": str(NEXT_MONTH),+ "period_end": periods[0]["period_end"], "taken": True,+ }+ assert [p["taken"] for p in periods[1:]] == [False] * (len(periods) - 1)+++async def test_a_raise_is_recorded_ahead_and_history_stays_put(client: AsyncClient, biz_headers):+ created = await _create(client, biz_headers)+ sid = created["id"]+ await client.post(f"/api/invoice-schedules/{sid}/generate", headers=biz_headers)++ later = NEXT_MONTH + timedelta(days=40)+ resp = await client.post(+ f"/api/invoice-schedules/{sid}/terms", headers=biz_headers,+ json={"effective_from": str(later), "lines": [{"description": "Retainer", "unit_price": "3500.00"}]},+ )+ assert resp.status_code == 201, resp.text+ schedule = resp.json()+ assert len(schedule["terms"]) == 2+ new_term = next(t for t in schedule["terms"] if t["effective_from"] == str(later))++ # Touching the term the first invoice was issued under is refused.+ first_term = next(t for t in schedule["terms"] if t["effective_from"] == str(NEXT_MONTH))+ resp = await client.patch(+ f"/api/invoice-schedules/{sid}/terms/{first_term['id']}", headers=biz_headers,+ json={"lines": [{"description": "Retainer", "unit_price": "1.00"}]},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "term_in_use"++ # The future one is free to change, move and go.+ resp = await client.patch(+ f"/api/invoice-schedules/{sid}/terms/{new_term['id']}", headers=biz_headers,+ json={"discount": "100.00", "effective_from": str(later + timedelta(days=1))},+ )+ assert resp.status_code == 200, resp.text+ moved = next(t for t in resp.json()["terms"] if t["id"] == new_term["id"])+ assert moved["total"] == "3400.00"+ resp = await client.delete(f"/api/invoice-schedules/{sid}/terms/{new_term['id']}", headers=biz_headers)+ assert resp.status_code == 200+ assert len(resp.json()["terms"]) == 1+++def _months_back(day: date, months: int) -> date:+ month_index = day.month - 1 - months+ year = day.year + month_index // 12+ return date(year, month_index % 12 + 1, day.day)+++async def test_make_recurring_from_an_invoice_and_link_history(client: AsyncClient, biz_headers, client_payee):+ """The two doors that are not "new agreement": an invoice that+ already exists starts one, and older invoices join it."""+ this_month = TODAY.replace(day=5)+ march = _months_back(this_month, 6)+ older = await client.post(+ "/api/invoices", headers=biz_headers,+ json={"payee_id": str(client_payee.id), "total": "3000.00", "issue_date": str(march),+ "due_date": str(march + timedelta(days=15))},+ )+ assert older.status_code == 201, older.text+ latest = await client.post(+ "/api/invoices", headers=biz_headers,+ json={"payee_id": str(client_payee.id), "issue_date": str(this_month),+ "due_date": str(this_month + timedelta(days=20)),+ "lines": [{"description": "Consultoria", "quantity": 10, "unit": "h", "unit_price": "300.00"}]},+ )+ assert latest.status_code == 201, latest.text++ resp = await client.post(+ f"/api/invoices/{latest.json()['id']}/make-recurring", headers=biz_headers,+ json={"frequency": "monthly", "start_date": str(march)},+ )+ assert resp.status_code == 201, resp.text+ schedule = resp.json()+ assert schedule["name"] == "Consultoria"+ assert schedule["start_date"] == str(march)+ assert schedule["payment_terms_days"] == 20+ assert schedule["invoice_count"] == 1+ assert schedule["monthly_amount"] == "3000.00"+ started = (await client.get(f"/api/invoices/{latest.json()['id']}", headers=biz_headers)).json()+ assert started["schedule_id"] == schedule["id"] and started["sequence"] == 7++ # The periods picker says which dates are boundaries and which are free.+ periods = (await client.get(f"/api/invoice-schedules/{schedule['id']}/periods", headers=biz_headers)).json()+ assert periods[0]["period_start"] == str(march) and periods[0]["taken"] is False+ assert periods[6]["period_start"] == str(this_month) and periods[6]["taken"] is True++ resp = await client.post(+ f"/api/invoice-schedules/{schedule['id']}/link", headers=biz_headers,+ json={"invoice_id": older.json()["id"], "period_start": str(march + timedelta(days=1))},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "not_a_period"++ linked = await client.post(+ f"/api/invoice-schedules/{schedule['id']}/link", headers=biz_headers,+ json={"invoice_id": older.json()["id"], "period_start": str(march)},+ )+ assert linked.status_code == 200, linked.text+ assert linked.json()["schedule_id"] == schedule["id"]+ assert linked.json()["sequence"] == 1+ detail = (await client.get(f"/api/invoice-schedules/{schedule['id']}", headers=biz_headers)).json()+ assert detail["invoice_count"] == 2+ assert detail["amount_invoiced"] == "6000.00"++ # Unlinking gives the invoice back as a one-off.+ resp = await client.delete(f"/api/invoices/{older.json()['id']}/schedule", headers=biz_headers)+ assert resp.status_code == 200+ assert resp.json()["schedule_id"] is None++ # A second make-recurring on the same invoice is refused.+ resp = await client.post(+ f"/api/invoices/{latest.json()['id']}/make-recurring", headers=biz_headers,+ json={"frequency": "monthly"},+ )+ assert resp.status_code == 409+++async def test_lifecycle_over_http(client: AsyncClient, biz_headers):+ created = await _create(client, biz_headers)+ sid = created["id"]++ resp = await client.post(f"/api/invoice-schedules/{sid}/pause", headers=biz_headers)+ assert resp.json()["status"] == "paused" and resp.json()["pause_reason"] == "manual"+ resp = await client.post(f"/api/invoice-schedules/{sid}/generate", headers=biz_headers)+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "schedule_not_active"+ resp = await client.post(f"/api/invoice-schedules/{sid}/resume", headers=biz_headers)+ assert resp.json()["status"] == "active"++ resp = await client.patch(+ f"/api/invoice-schedules/{sid}", headers=biz_headers,+ json={"name": "Plano Pro", "end_type": "after_count", "end_count": 2},+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["name"] == "Plano Pro"+ assert resp.json()["end_count"] == 2++ resp = await client.post(+ f"/api/invoice-schedules/{sid}/end", headers=biz_headers,+ json={"reason": "canceled_by_client", "ended_at": str(TODAY)},+ )+ assert resp.status_code == 200, resp.text+ body = resp.json()+ assert (body["status"], body["end_reason"], body["ended_at"]) == ("ended", "canceled_by_client", str(TODAY))+ assert body["next_period_start"] is None++ listed = (await client.get("/api/invoice-schedules", headers=biz_headers, params={"status": "ended"})).json()+ assert [s["id"] for s in listed] == [sid]+ summary = (await client.get("/api/invoice-schedules/summary", headers=biz_headers)).json()+ assert summary["ended_count"] == 1 and summary["active_count"] == 0++ # Nothing was billed, so it may still be deleted.+ assert (await client.delete(f"/api/invoice-schedules/{sid}", headers=biz_headers)).status_code == 204+ assert (await client.get(f"/api/invoice-schedules/{sid}", headers=biz_headers)).status_code == 404+++async def test_delete_refuses_once_billed_and_errors_carry_codes(client: AsyncClient, biz_headers):+ created = await _create(client, biz_headers)+ sid = created["id"]+ await client.post(f"/api/invoice-schedules/{sid}/generate", headers=biz_headers)+ resp = await client.delete(f"/api/invoice-schedules/{sid}", headers=biz_headers)+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "schedule_has_invoices"++ resp = await client.patch(f"/api/invoice-schedules/{sid}", headers=biz_headers, json={"frequency": "weekly"})+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "schedule_locked"++ resp = await client.post(+ "/api/invoice-schedules", headers=biz_headers,+ json={"name": "x", "frequency": "monthly", "end_type": "on_date",+ "lines": [{"description": "a", "unit_price": "1"}]},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "end_date_required"++ resp = await client.post(+ "/api/invoice-schedules", headers=biz_headers,+ json={"name": "x", "frequency": "monthly", "lines": [{"description": "a", "unit_price": "0"}]},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "term_empty"diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 66c69065..df93d483 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -37,6 +37,8 @@ const AgentsListPage = lazy(() => import('@/pages/agents-list'))const AgentDetailPage = lazy(() => import('@/pages/agent-detail'))const AgentConnectionsPage = lazy(() => import('@/pages/agent-connections'))const InvoicesPage = lazy(() => import('@/pages/invoices'))+const InvoiceSchedulesPage = lazy(() => import('@/pages/invoice-schedules'))+const InvoiceScheduleDetailPage = lazy(() => import('@/pages/invoice-schedule-detail'))const InvoiceDetailPage = lazy(() => import('@/pages/invoice-detail'))const SharedInvoicePage = lazy(() => import('@/pages/shared-invoice'))const WorkspaceSettingsPage = lazy(() => import('@/pages/workspace-settings'))@@ -109,6 +111,9 @@ function App() {<Route path="/groups" element={<ModuleRoute module="split_groups"><GroupsPage /></ModuleRoute>} /><Route path="/groups/:id" element={<ModuleRoute module="split_groups"><GroupDetailPage /></ModuleRoute>} /><Route path="/invoices" element={<ModuleRoute module="invoices"><InvoicesPage /></ModuleRoute>} />+ {/* Declared before `/invoices/:id`, which would otherwise take "schedules" for an id. */}+ <Route path="/invoices/schedules" element={<ModuleRoute module="invoices"><InvoiceSchedulesPage /></ModuleRoute>} />+ <Route path="/invoices/schedules/:id" element={<ModuleRoute module="invoices"><InvoiceScheduleDetailPage /></ModuleRoute>} /><Route path="/invoices/:id" element={<ModuleRoute module="invoices"><InvoiceDetailPage /></ModuleRoute>} /><Route path="/workspace/settings" element={<WorkspaceSettingsPage />} /><Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} />diff --git a/frontend/src/components/invoice-schedule-ui.tsx b/frontend/src/components/invoice-schedule-ui.tsxnew file mode 100644index 00000000..f5006427--- /dev/null+++ b/frontend/src/components/invoice-schedule-ui.tsx@@ -0,0 +1,131 @@+import { useTranslation } from 'react-i18next'+import { Link } from 'react-router-dom'+import { Repeat } from 'lucide-react'++import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { cn } from '@/lib/utils'+import { periodLabel, scheduleLabel, scheduleTone } from '@/lib/invoice-schedule-utils'+import { useDateLocale } from '@/hooks/use-display-locale'+import type { Invoice, InvoiceSchedule, InvoiceScheduleEndType } from '@/types'++/** Status pill for an agreement, in the invoice badge's shape. */+export function ScheduleBadge({+ schedule,+}: {+ schedule: Pick<InvoiceSchedule, 'status' | 'pause_reason' | 'past_due_count'>+}) {+ const { t } = useTranslation()+ const label = scheduleLabel(schedule)+ return (+ <span+ data-testid={`schedule-state-${label}`}+ className={cn(+ 'text-[11px] font-semibold px-2 py-0.5 rounded-full border whitespace-nowrap',+ scheduleTone(schedule),+ )}+ >+ {t(`invoices.schedules.state.${label}`)}+ </span>+ )+}++/**+ * The chip an invoice wears when it answers for a period of an+ * agreement: the agreement's name and the period, linking to it. Small+ * on purpose: the invoice is the subject, this is its provenance.+ */+export function SchedulePeriodChip({ invoice }: { invoice: Invoice }) {+ const dateLocale = useDateLocale()+ if (!invoice.schedule || !invoice.period_start || !invoice.period_end) return null+ return (+ <Link+ to={`/invoices/schedules/${invoice.schedule.id}`}+ onClick={(e) => e.stopPropagation()}+ data-testid="invoice-schedule-chip"+ className="inline-flex items-center gap-1.5 rounded-full border border-border bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground hover:text-foreground transition-colors"+ >+ <Repeat className="h-3 w-3" />+ <span className="truncate max-w-[160px]">{invoice.schedule.name}</span>+ <span className="text-muted-foreground/70 tabular-nums">+ {periodLabel(invoice.period_start, invoice.period_end, dateLocale)}+ </span>+ </Link>+ )+}++/**+ * The end condition, as one control. Three shapes (never, a date, a+ * count) share a select, and the field for the chosen one appears+ * beside it. Used by the create and edit dialogs and the "make+ * recurring" one on the invoice page, so the three agree.+ */+export function EndConditionFields({+ endType,+ endDate,+ endCount,+ onChange,+ idPrefix,+}: {+ endType: InvoiceScheduleEndType+ endDate: string+ endCount: string+ onChange: (next: { endType: InvoiceScheduleEndType; endDate: string; endCount: string }) => void+ idPrefix: string+}) {+ const { t } = useTranslation()+ return (+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label>{t('invoices.schedules.field.ends')}</Label>+ <Select+ value={endType}+ onValueChange={(value) => onChange({ endType: value as InvoiceScheduleEndType, endDate, endCount })}+ >+ <SelectTrigger data-testid={`${idPrefix}-end-type`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(['never', 'on_date', 'after_count'] as const).map((value) => (+ <SelectItem key={value} value={value}>+ {t(`invoices.schedules.endType.${value}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {endType === 'on_date' && (+ <div className="space-y-1.5">+ <Label htmlFor={`${idPrefix}-end-date`}>{t('invoices.schedules.field.endDate')}</Label>+ <Input+ id={`${idPrefix}-end-date`}+ data-testid={`${idPrefix}-end-date`}+ type="date"+ value={endDate}+ onChange={(e) => onChange({ endType, endDate: e.target.value, endCount })}+ />+ </div>+ )}+ {endType === 'after_count' && (+ <div className="space-y-1.5">+ <Label htmlFor={`${idPrefix}-end-count`}>{t('invoices.schedules.field.endCount')}</Label>+ <Input+ id={`${idPrefix}-end-count`}+ data-testid={`${idPrefix}-end-count`}+ type="number"+ min={1}+ value={endCount}+ onChange={(e) => onChange({ endType, endDate, endCount: e.target.value })}+ />+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/components/invoice-ui.tsx b/frontend/src/components/invoice-ui.tsxindex 5ddd6ab4..76886a5e 100644--- a/frontend/src/components/invoice-ui.tsx+++ b/frontend/src/components/invoice-ui.tsx@@ -33,14 +33,21 @@ export function SectionCard({export function SectionHeader({title,+ description,action,}: {title: string+ /** One line under the title, for a section whose rule is not obvious+ * from its rows (what a "term" is, say). */+ description?: stringaction?: React.ReactNode}) {return (<div className="px-4 sm:px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-2">- <p className="text-sm font-semibold text-foreground">{title}</p>+ <div className="min-w-0">+ <p className="text-sm font-semibold text-foreground">{title}</p>+ {description && <p className="text-xs text-muted-foreground mt-0.5">{description}</p>}+ </div>{action}</div>)diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 6e39d496..4339f400 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -23,6 +23,13 @@ import type {InvoiceDirection,InvoiceDocumentPayload,InvoiceFacets,+ InvoiceSchedule,+ InvoiceScheduleEndReason,+ InvoiceScheduleEndType,+ InvoiceScheduleFrequency,+ InvoiceSchedulePeriod,+ InvoiceScheduleStatus,+ InvoiceScheduleSummary,InvoiceLineInput,InvoiceShareLink,IssuerProfile,@@ -1861,6 +1868,109 @@ export interface InvoiceWritePayload {lines?: InvoiceLineInput[]}+export interface MakeRecurringPayload {+ frequency: InvoiceScheduleFrequency+ start_date?: string+ name?: string+ end_type?: InvoiceScheduleEndType+ end_date?: string | null+ end_count?: number | null+ payment_terms_days?: number | null+}++export interface InvoiceScheduleWritePayload {+ name?: string+ payee_id?: string | null+ frequency?: InvoiceScheduleFrequency+ start_date?: string+ end_type?: InvoiceScheduleEndType+ end_date?: string | null+ end_count?: number | null+ payment_terms_days?: number | null+ currency?: string+ notes?: string | null+ custom_fields?: Record<string, string> | null+ /** Create only: the first term, in force from `start_date`. */+ lines?: InvoiceLineInput[]+ discount?: string | null+}++export interface InvoiceScheduleTermPayload {+ effective_from?: string+ lines?: InvoiceLineInput[]+ discount?: string | null+}++/** Recurring invoices: an agreement that emits one invoice per period.+ * Its own prefix, because `/invoices/{id}` would swallow `schedules`. */+export const invoiceSchedules = {+ list: async (params?: { status?: InvoiceScheduleStatus; payee_id?: string }): Promise<InvoiceSchedule[]> => {+ const { data } = await api.get('/invoice-schedules', { params })+ return data+ },+ summary: async (): Promise<InvoiceScheduleSummary> => {+ const { data } = await api.get('/invoice-schedules/summary')+ return data+ },+ get: async (id: string): Promise<InvoiceSchedule> => {+ const { data } = await api.get(`/invoice-schedules/${id}`)+ return data+ },+ invoices: async (id: string): Promise<Invoice[]> => {+ const { data } = await api.get(`/invoice-schedules/${id}/invoices`)+ return data+ },+ periods: async (id: string, ahead = 3): Promise<InvoiceSchedulePeriod[]> => {+ const { data } = await api.get(`/invoice-schedules/${id}/periods`, { params: { ahead } })+ return data+ },+ create: async (payload: InvoiceScheduleWritePayload): Promise<InvoiceSchedule> => {+ const { data } = await api.post('/invoice-schedules', payload)+ return data+ },+ update: async (id: string, payload: InvoiceScheduleWritePayload): Promise<InvoiceSchedule> => {+ const { data } = await api.patch(`/invoice-schedules/${id}`, payload)+ return data+ },+ remove: async (id: string): Promise<void> => {+ await api.delete(`/invoice-schedules/${id}`)+ },+ pause: async (id: string): Promise<InvoiceSchedule> => {+ const { data } = await api.post(`/invoice-schedules/${id}/pause`)+ return data+ },+ resume: async (id: string): Promise<InvoiceSchedule> => {+ const { data } = await api.post(`/invoice-schedules/${id}/resume`)+ return data+ },+ end: async (id: string, payload: { reason: InvoiceScheduleEndReason; ended_at?: string }): Promise<InvoiceSchedule> => {+ const { data } = await api.post(`/invoice-schedules/${id}/end`, payload)+ return data+ },+ /** Emit the next period now, whether or not its date has come. */+ generate: async (id: string): Promise<Invoice[]> => {+ const { data } = await api.post(`/invoice-schedules/${id}/generate`)+ return data+ },+ addTerm: async (id: string, payload: InvoiceScheduleTermPayload): Promise<InvoiceSchedule> => {+ const { data } = await api.post(`/invoice-schedules/${id}/terms`, payload)+ return data+ },+ updateTerm: async (id: string, termId: string, payload: InvoiceScheduleTermPayload): Promise<InvoiceSchedule> => {+ const { data } = await api.patch(`/invoice-schedules/${id}/terms/${termId}`, payload)+ return data+ },+ removeTerm: async (id: string, termId: string): Promise<InvoiceSchedule> => {+ const { data } = await api.delete(`/invoice-schedules/${id}/terms/${termId}`)+ return data+ },+ /** Say an existing invoice answers for a period of this agreement. */+ link: async (id: string, payload: { invoice_id: string; period_start: string }): Promise<Invoice> => {+ const { data } = await api.post(`/invoice-schedules/${id}/link`, payload)+ return data+ },+}+export const invoices = {facets: async (year?: number, direction?: InvoiceDirection): Promise<InvoiceFacets> => {const { data } = await api.get('/invoices/facets', {@@ -1868,7 +1978,7 @@ export const invoices = {})return data},- list: async (params?: { state?: string; year?: number; direction?: InvoiceDirection; payee_id?: string; q?: string } | Record<string, unknown>): Promise<Invoice[]> => {+ list: async (params?: { state?: string; year?: number; direction?: InvoiceDirection; payee_id?: string; schedule_id?: string; q?: string; limit?: number } | Record<string, unknown>): Promise<Invoice[]> => {const cleanParams = params && !('queryKey' in params) ? params : undefinedconst { data } = await api.get('/invoices', { params: cleanParams })return data@@ -1894,6 +2004,16 @@ export const invoices = {remove: async (id: string): Promise<void> => {await api.delete(`/invoices/${id}`)},+ /** Turn this invoice into period one of a new agreement that repeats it. */+ makeRecurring: async (id: string, payload: MakeRecurringPayload): Promise<InvoiceSchedule> => {+ const { data } = await api.post(`/invoices/${id}/make-recurring`, payload)+ return data+ },+ /** The invoice stops answering for a period. It stays as it is. */+ unlinkSchedule: async (id: string): Promise<Invoice> => {+ const { data } = await api.delete(`/invoices/${id}/schedule`)+ return data+ },// The decisions. Each is its own call for the same reason it is its own// route on the server: a status change always has a cause.issue: async (id: string): Promise<Invoice> => {diff --git a/frontend/src/lib/invoice-schedule-utils.test.ts b/frontend/src/lib/invoice-schedule-utils.test.tsnew file mode 100644index 00000000..5e507ed1--- /dev/null+++ b/frontend/src/lib/invoice-schedule-utils.test.ts@@ -0,0 +1,111 @@+import { describe, expect, it } from 'vitest'++import {+ FREQUENCIES,+ PERIODS_PER_YEAR,+ endPayload,+ isUpcomingTerm,+ localToday,+ monthlyEquivalent,+ periodLabel,+ scheduleActions,+ scheduleLabel,+ scheduleTone,+} from './invoice-schedule-utils'++describe('monthlyEquivalent', () => {+ it('normalises through the year, not through a four-week month', () => {+ expect(monthlyEquivalent(1200, 'weekly')).toBe(5200)+ expect(monthlyEquivalent(1200, 'biweekly')).toBe(2600)+ expect(monthlyEquivalent(1200, 'monthly')).toBe(1200)+ expect(monthlyEquivalent(1200, 'quarterly')).toBe(400)+ expect(monthlyEquivalent(1200, 'semiannual')).toBe(200)+ expect(monthlyEquivalent(1200, 'yearly')).toBe(100)+ })++ it('rounds to cents', () => {+ expect(monthlyEquivalent(100, 'quarterly')).toBe(33.33)+ })++ it('covers every frequency the picker offers', () => {+ for (const frequency of FREQUENCIES) expect(PERIODS_PER_YEAR[frequency]).toBeGreaterThan(0)+ })+})++describe('scheduleLabel and scheduleTone', () => {+ it('outranks "active" with what needs a person', () => {+ expect(scheduleLabel({ status: 'active', pause_reason: null, past_due_count: 0 })).toBe('active')+ expect(scheduleLabel({ status: 'active', pause_reason: null, past_due_count: 2 })).toBe('past_due')+ expect(scheduleLabel({ status: 'paused', pause_reason: 'manual', past_due_count: 0 })).toBe('paused')+ expect(scheduleLabel({ status: 'paused', pause_reason: 'failures', past_due_count: 0 })).toBe('paused_failures')+ expect(scheduleLabel({ status: 'ended', pause_reason: null, past_due_count: 3 })).toBe('ended')+ })++ it('is loud only for a pause after failures and a late invoice', () => {+ expect(scheduleTone({ status: 'paused', pause_reason: 'failures', past_due_count: 0 })).toContain('rose')+ expect(scheduleTone({ status: 'active', pause_reason: null, past_due_count: 1 })).toContain('amber')+ expect(scheduleTone({ status: 'active', pause_reason: null, past_due_count: 0 })).toContain('emerald')+ expect(scheduleTone({ status: 'ended', pause_reason: null, past_due_count: 0 })).toContain('muted')+ })+})++describe('scheduleActions', () => {+ it('follows the stored decisions', () => {+ const active = scheduleActions({ status: 'active', invoice_count: 0, origin: 'local' })+ expect(active).toMatchObject({ canPause: true, canResume: false, canEnd: true, canGenerate: true, canDelete: true })++ const billed = scheduleActions({ status: 'active', invoice_count: 3, origin: 'local' })+ expect(billed.canDelete).toBe(false)++ const paused = scheduleActions({ status: 'paused', invoice_count: 3, origin: 'local' })+ expect(paused).toMatchObject({ canPause: false, canResume: true, canGenerate: false, canChangePrice: true })++ const ended = scheduleActions({ status: 'ended', invoice_count: 3, origin: 'local' })+ expect(ended).toMatchObject({ canPause: false, canResume: false, canEnd: false, canEdit: false, canChangePrice: false })+ })++ it('never generates for a mirrored gateway agreement', () => {+ expect(scheduleActions({ status: 'active', invoice_count: 0, origin: 'imported' }).canGenerate).toBe(false)+ })+})++describe('isUpcomingTerm', () => {+ it('is strictly after today', () => {+ const today = new Date(2026, 8, 22)+ expect(isUpcomingTerm('2026-09-23', today)).toBe(true)+ expect(isUpcomingTerm('2026-09-22', today)).toBe(false)+ expect(isUpcomingTerm('2026-09-21', today)).toBe(false)+ })+})++describe('periodLabel', () => {+ it('writes a span the way the locale does, dropping the repeated year', () => {+ const label = periodLabel('2026-09-05', '2026-10-04', 'en-US')+ expect(label).toContain('Sep 5')+ expect(label).toContain('Oct 4, 2026')+ expect(label.match(/2026/g)).toHaveLength(1)+ })++ it('keeps both years when the period crosses one', () => {+ const label = periodLabel('2026-12-05', '2027-01-04', 'en-US')+ expect(label).toContain('2026')+ expect(label).toContain('2027')+ })+})++describe('endPayload', () => {+ it('sends only the field the chosen shape needs, and nulls the other', () => {+ expect(endPayload('never', '2027-01-01', '5')).toEqual({ end_type: 'never', end_date: null, end_count: null })+ expect(endPayload('on_date', '2027-01-01', '5')).toEqual({ end_type: 'on_date', end_date: '2027-01-01', end_count: null })+ expect(endPayload('after_count', '2027-01-01', '5')).toEqual({ end_type: 'after_count', end_date: null, end_count: 5 })+ })+})++describe('localToday', () => {+ it('is the local calendar date, not the UTC one', () => {+ // 23:30 on Sep 22 in local time. In UTC west of Greenwich this is+ // already Sep 23, which is what `toISOString()` would have said.+ expect(localToday(new Date(2026, 8, 22, 23, 30))).toBe('2026-09-22')+ expect(localToday(new Date(2026, 0, 5, 0, 5))).toBe('2026-01-05')+ })+})diff --git a/frontend/src/lib/invoice-schedule-utils.ts b/frontend/src/lib/invoice-schedule-utils.tsnew file mode 100644index 00000000..52a39c36--- /dev/null+++ b/frontend/src/lib/invoice-schedule-utils.ts@@ -0,0 +1,131 @@+import type {+ InvoiceSchedule,+ InvoiceScheduleEndType,+ InvoiceScheduleFrequency,+ InvoiceScheduleStatus,+} from '@/types'++/**+ * Pure helpers for recurring invoices. Everything here is a function of+ * the row the server sent: the server derives the money and the dates,+ * and the UI only decides how to say them.+ */++/** Periods in a year per frequency. Mirrors `PERIODS_PER_YEAR` on the+ * server and exists here only so a form can preview the monthly figure+ * before the schedule exists. */+export const PERIODS_PER_YEAR: Record<InvoiceScheduleFrequency, number> = {+ weekly: 52,+ biweekly: 26,+ monthly: 12,+ quarterly: 4,+ semiannual: 2,+ yearly: 1,+}++export const FREQUENCIES: InvoiceScheduleFrequency[] = [+ 'weekly',+ 'biweekly',+ 'monthly',+ 'quarterly',+ 'semiannual',+ 'yearly',+]++/** A per-period amount as a per-month one. A weekly retainer is 52+ * periods over 12 months, not four a month. */+export function monthlyEquivalent(amount: number, frequency: InvoiceScheduleFrequency): number {+ return Math.round(((amount * PERIODS_PER_YEAR[frequency]) / 12) * 100) / 100+}++/** The tone of a schedule's status pill. Quiet unless something needs a+ * person: paused after failures is the one loud state, because nothing+ * will be billed until somebody looks. */+export function scheduleTone(schedule: Pick<InvoiceSchedule, 'status' | 'pause_reason' | 'past_due_count'>): string {+ if (schedule.status === 'paused' && schedule.pause_reason === 'failures') {+ return 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20'+ }+ if (schedule.status === 'active' && schedule.past_due_count > 0) {+ return 'bg-amber-50 text-amber-700 border-amber-100 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20'+ }+ if (schedule.status === 'active') {+ return 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20'+ }+ return 'bg-muted text-muted-foreground border-border'+}++/** What the pill says. `past_due` is not a stored status: it is an+ * active agreement with an invoice past its date, and it outranks+ * "active" on screen because it is the one thing to act on. */+export function scheduleLabel(+ schedule: Pick<InvoiceSchedule, 'status' | 'pause_reason' | 'past_due_count'>,+): InvoiceScheduleStatus | 'past_due' | 'paused_failures' {+ if (schedule.status === 'paused' && schedule.pause_reason === 'failures') return 'paused_failures'+ if (schedule.status === 'active' && schedule.past_due_count > 0) return 'past_due'+ return schedule.status+}++/** Which actions a schedule offers. Derived from the stored decisions+ * alone, so the buttons and the server agree about what is allowed. */+export function scheduleActions(schedule: Pick<InvoiceSchedule, 'status' | 'invoice_count' | 'origin'>): {+ canPause: boolean+ canResume: boolean+ canEnd: boolean+ canEdit: boolean+ canGenerate: boolean+ canChangePrice: boolean+ canDelete: boolean+} {+ const live = schedule.status !== 'ended'+ const local = schedule.origin === 'local'+ return {+ canPause: schedule.status === 'active',+ canResume: schedule.status === 'paused',+ canEnd: live,+ canEdit: live,+ canGenerate: schedule.status === 'active' && local,+ canChangePrice: live,+ // Nothing was ever billed under it, so nothing is lost with it.+ canDelete: schedule.invoice_count === 0,+ }+}++/** Whether a term is still ahead of today, and so may still be edited+ * or removed from the UI's point of view. The server has the last+ * word: it also refuses when an invoice was issued under the term. */+export function isUpcomingTerm(effectiveFrom: string, today = new Date()): boolean {+ const start = new Date(`${effectiveFrom}T00:00:00`)+ const reference = new Date(today.getFullYear(), today.getMonth(), today.getDate())+ return start.getTime() > reference.getTime()+}++/** The period label the invoice list and the picker share: "5 Sep to 4 Oct 2026". */+export function periodLabel(start: string, end: string, locale: string): string {+ const from = new Date(`${start}T00:00:00`)+ const to = new Date(`${end}T00:00:00`)+ const options: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'short', year: 'numeric' }+ const formatter = new Intl.DateTimeFormat(locale, options)+ // `formatRange` knows how each locale writes a span and drops the+ // repeated year on its own; the fallback is for a runtime without it.+ if (typeof formatter.formatRange === 'function') return formatter.formatRange(from, to)+ return `${formatter.format(from)} / ${formatter.format(to)}`+}++/** The end condition as the server takes it: only the field the chosen+ * shape needs, the other explicitly null so a PATCH clears it. */+export function endPayload(endType: InvoiceScheduleEndType, endDate: string, endCount: string) {+ return {+ end_type: endType,+ end_date: endType === 'on_date' && endDate ? endDate : null,+ end_count: endType === 'after_count' && endCount ? Number(endCount) : null,+ }+}++/** Today as `YYYY-MM-DD` in the viewer's own calendar. Not+ * `toISOString()`, which is the UTC date: in the evening west of UTC+ * it is already tomorrow, and a billing date defaulted from it is off+ * by one without anybody noticing. */+export function localToday(now = new Date()): string {+ const pad = (n: number) => String(n).padStart(2, '0')+ return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`+}diff --git a/frontend/src/lib/invoice-utils.test.ts b/frontend/src/lib/invoice-utils.test.tsindex 8905353a..4bb78e9d 100644--- a/frontend/src/lib/invoice-utils.test.ts+++ b/frontend/src/lib/invoice-utils.test.ts@@ -51,6 +51,11 @@ function makeInvoice(overrides: Partial<Invoice> = {}): Invoice {custom_fields: null,snapshot: null,share_token: null,+ schedule_id: null,+ schedule: null,+ sequence: null,+ period_start: null,+ period_end: null,lines: [],allocations: [],created_at: '2026-08-01T00:00:00Z',diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 2940a990..506c037e 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -292,7 +292,40 @@"payable_not_shareable": "Eine erhaltene Rechnung kann nicht geteilt werden.","discount_exceeds_total": "Der Rabatt ist größer als der berechnete Betrag.","no_document_filed": "Dieses Dokument wurde anderswo ausgestellt. Hängen Sie die erhaltene Datei an.",- "already_imported": "Dieses Dokument wurde bereits importiert."+ "already_imported": "Dieses Dokument wurde bereits importiert.",+ "term_lines_required": "Eine Kondition braucht mindestens eine Position.",+ "term_empty": "Eine Kondition muss etwas berechnen.",+ "term_in_use": "Unter dieser Kondition wurde bereits eine Rechnung ausgestellt. Fügen Sie eine neue Kondition ab einem späteren Datum hinzu.",+ "term_before_start": "Eine Kondition kann nicht vor der Vereinbarung beginnen.",+ "term_date_taken": "An diesem Datum beginnt bereits eine andere Kondition.",+ "last_term": "Eine Vereinbarung braucht mindestens eine Kondition.",+ "term_not_found": "Kondition nicht gefunden.",+ "schedule_ended": "Diese Vereinbarung ist beendet und kann nicht mehr geändert werden.",+ "schedule_locked": "Häufigkeit, Startdatum und Währung sind fest, sobald eine Rechnung unter dieser Vereinbarung existiert.",+ "schedule_has_invoices": "Unter dieser Vereinbarung wurden Rechnungen ausgestellt. Beenden Sie sie, statt sie zu löschen.",+ "schedule_not_active": "Nur eine aktive Vereinbarung stellt Rechnungen aus.",+ "invalid_frequency": "Unbekannte Häufigkeit.",+ "invalid_end_type": "Unbekannte Endbedingung.",+ "invalid_end_reason": "Unbekannter Endgrund.",+ "end_date_required": "Geben Sie an, an welchem Datum die Vereinbarung endet.",+ "end_count_required": "Geben Sie an, nach wie vielen Rechnungen die Vereinbarung endet.",+ "end_before_start": "Die Vereinbarung kann nicht enden, bevor sie beginnt.",+ "name_required": "Geben Sie der Vereinbarung einen Namen.",+ "not_issued": "Nur eine ausgestellte Rechnung kann eine Vereinbarung beginnen.",+ "already_linked": "Diese Rechnung gehört bereits zu einer Vereinbarung.",+ "invoice_void": "Eine stornierte Rechnung kann keine Periode abdecken.",+ "payee_mismatch": "Rechnung und Vereinbarung nennen unterschiedliche Kunden.",+ "not_a_period": "Dieses Datum ist nicht der Beginn einer Periode dieser Vereinbarung.",+ "beyond_end": "Diese Periode liegt nach dem Ende der Vereinbarung.",+ "period_taken": "Eine andere Rechnung deckt diese Periode bereits ab.",+ "start_after_invoice": "Die Vereinbarung kann nicht nach dieser Rechnung beginnen.",+ "invoice_not_found": "Rechnung nicht gefunden.",+ "no_term": "Für diese Periode gilt keine Kondition.",+ "no_author": "Diese Vereinbarung hat keinen Autor, in dessen Namen Rechnungen ausgestellt werden.",+ "negative_discount": "Ein Rabatt kann nicht negativ sein.",+ "first_term": "Der Preis, der ab Beginn gilt, kann weder verschoben noch entfernt werden. Ändern Sie ihn oder fügen Sie einen neuen Preis ab einem späteren Datum hinzu.",+ "not_receivable": "Nur eine von Ihnen ausgestellte Rechnung kann zu einer Vereinbarung gehören.",+ "period_already_issued": "Dieser Zeitraum wurde gerade ausgestellt. Aktualisieren Sie die Seite, um ihn zu sehen."},"comingNext": "Stelle deinen Kunden Rechnungen und behalte im Blick, was bezahlt ist und was offen bleibt. Das ist das Nächste, was gebaut wird.","document": {@@ -381,6 +414,152 @@"wouldApply": "würde {{amount}} anrechnen","alsoCovers_one": "deckt auch {{count}} weitere Rechnung","alsoCovers_other": "deckt auch {{count}} weitere Rechnungen"+ },+ "schedules": {+ "title": "Wiederkehrend",+ "new": "Neue wiederkehrende Rechnung",+ "newDescription": "Eine Vereinbarung mit einem Kunden, ihm jede Periode eine Rechnung zu stellen. Die Rechnungen werden am Stichtag für Sie erstellt.",+ "backToList": "Zurück zu Wiederkehrend",+ "empty": "Noch keine wiederkehrenden Rechnungen. Richten Sie eine ein, oder öffnen Sie eine Rechnung und wählen Sie \"Diese Rechnung wiederholen\".",+ "emptyFiltered": "Nichts mit diesem Status.",+ "created": "Wiederkehrende Rechnung erstellt",+ "saved": "Änderungen gespeichert",+ "deleted": "Wiederkehrende Rechnung gelöscht",+ "paused": "Pausiert. Es wird nichts berechnet, bis Sie sie fortsetzen.",+ "resumed": "Ab der nächsten Periode fortgesetzt.",+ "ended": "Vereinbarung beendet",+ "generated_one": "Rechnung ausgestellt",+ "generated_other": "{{count}} Rechnungen ausgestellt",+ "termSaved": "Preis gespeichert",+ "termRemoved": "Preisänderung entfernt",+ "linked": "Rechnung mit der Vereinbarung verknüpft",+ "unlinked": "Rechnung von der Vereinbarung gelöst",+ "recurringInvoice": "Wiederkehrende Rechnung",+ "monthlyPreview": "Etwa {{amount}} pro Monat.",+ "since": "seit {{date}}",+ "untilDate": "bis {{date}}",+ "untilCount_one": "{{count}} Rechnung insgesamt",+ "untilCount_other": "{{count}} Rechnungen insgesamt",+ "endedOn": "beendet am {{date}} ({{reason}})",+ "pausedByFailures": "Nach wiederholten Fehlern pausiert. Prüfen Sie die Konditionen und setzen Sie fort.",+ "editTitle": "Wiederkehrende Rechnung bearbeiten",+ "editDescription": "Name, Kunde, Konditionen und Ende.",+ "editLockedDescription": "Unter dieser Vereinbarung wurden bereits Rechnungen ausgestellt, daher sind Häufigkeit und Startdatum fest. Alles andere kann sich ändern.",+ "endTitle": "Diese Vereinbarung beenden?",+ "endDescription": "Es werden keine weiteren Rechnungen ausgestellt. Die bereits ausgestellten bleiben genau so, wie sie sind. Geben Sie den Grund an: Er ist das Einzige, was die Rechnungen später nicht verraten.",+ "linkTitle": "Vorhandene Rechnung verknüpfen",+ "linkDescription": "Eine Rechnung, die Sie von Hand für eine Periode dieser Vereinbarung erstellt haben. Sie behält Nummer, Datum und Zahlungen; sie erfährt nur, zu welcher Periode sie gehört.",+ "noCandidates": "Keine unverknüpfte Rechnung für diesen Kunden in dieser Währung.",+ "makeRecurringDescription": "Diese Rechnung wird zu einer Periode einer neuen Vereinbarung, und die nächsten werden für Sie erstellt. Ihr Datum, {{date}}, ist die erste Periode, sofern die Vereinbarung nicht früher begonnen hat.",+ "filter": {+ "all": "Alle",+ "active": "Aktiv",+ "paused": "Pausiert",+ "ended": "Beendet"+ },+ "state": {+ "active": "Aktiv",+ "past_due": "Überfällig",+ "paused": "Pausiert",+ "paused_failures": "Braucht Aufmerksamkeit",+ "ended": "Beendet"+ },+ "frequency": {+ "weekly": "Wöchentlich",+ "biweekly": "Alle 2 Wochen",+ "monthly": "Monatlich",+ "quarterly": "Vierteljährlich",+ "semiannual": "Alle 6 Monate",+ "yearly": "Jährlich"+ },+ "endType": {+ "never": "Nie",+ "on_date": "An einem Datum",+ "after_count": "Nach einer Anzahl Rechnungen"+ },+ "endReason": {+ "canceled_by_client": "Vom Kunden gekündigt",+ "canceled_by_us": "Von uns gekündigt",+ "completed": "Regulär ausgelaufen",+ "unpaid": "Nicht bezahlt",+ "other": "Sonstiges"+ },+ "summary": {+ "monthly": "Monatlich wiederkehrend",+ "yearly": "Pro Jahr",+ "lost": "Verloren in den letzten 30 Tagen",+ "endedRecently_one": "{{count}} Vereinbarung beendet",+ "endedRecently_other": "{{count}} Vereinbarungen beendet",+ "pastDue": "Überfällig",+ "pastDueHint": "Vereinbarungen mit einer überfälligen Rechnung",+ "activeCount_one": "{{count}} aktive Vereinbarung",+ "activeCount_other": "{{count}} aktive Vereinbarungen",+ "none": "Noch nichts Wiederkehrendes"+ },+ "column": {+ "name": "Vereinbarung",+ "cadence": "Rhythmus",+ "monthly": "Pro Monat",+ "next": "Nächste Rechnung",+ "invoices": "Rechnungen",+ "status": "Status",+ "period": "Periode"+ },+ "figure": {+ "invoiced": "In Rechnung gestellt",+ "paid": "Erhalten",+ "pastDue_one": "{{count}} Rechnung überfällig",+ "pastDue_other": "{{count}} Rechnungen überfällig"+ },+ "field": {+ "name": "Name",+ "namePlaceholder": "Pro-Plan, monatliche Pauschale, Hosting",+ "frequency": "Häufigkeit",+ "startDate": "Beginnt am",+ "startDateHint": "Ein Datum vor der Rechnung schafft Platz, um die vorherigen zu verknüpfen.",+ "paymentTerms": "Zahlungsziel (Tage)",+ "currency": "Währung",+ "ends": "Endet",+ "endDate": "Enddatum",+ "endCount": "Anzahl Rechnungen",+ "endReason": "Grund",+ "endedAt": "Beendet am",+ "invoice": "Rechnung",+ "invoicePlaceholder": "Rechnung wählen",+ "period": "Periode",+ "periodPlaceholder": "Periode wählen"+ },+ "action": {+ "changePrice": "Preis ändern",+ "generate": "Nächste jetzt ausstellen",+ "pause": "Pausieren",+ "resume": "Fortsetzen",+ "end": "Vereinbarung beenden",+ "linkInvoice": "Rechnung verknüpfen",+ "link": "Verknüpfen",+ "makeRecurring": "Diese Rechnung wiederholen",+ "unlink": "Aus der Vereinbarung entfernen"+ },+ "terms": {+ "title": "Preis",+ "description": "Was die Vereinbarung pro Periode berechnet, und ab wann. Eine Änderung gilt ab der ersten Periode, die an oder nach ihrem Datum beginnt; nichts wird anteilig berechnet.",+ "from": "Ab {{date}}",+ "current": "Aktuell",+ "upcoming": "Bevorstehend",+ "perMonth": "{{amount}} pro Monat",+ "editTitle": "Preisänderung bearbeiten",+ "changeDescription": "Erfassen Sie einen neuen Preis ab einem Datum. Bereits berechnete Perioden behalten ihren Betrag; die Änderung beginnt mit der ersten Periode an oder nach dem Datum, in voller Höhe.",+ "effectiveFrom": "Ab",+ "nextPeriodHint": "Die nächste Periode beginnt am {{date}}.",+ "discount": "Rabatt",+ "preview": "{{period}} pro Periode, etwa {{monthly}} pro Monat."+ },+ "invoices": {+ "title": "Rechnungen",+ "description": "Eine pro Periode, am Stichtag erstellt. Eine von Hand erstellte Rechnung kann ebenfalls verknüpft werden.",+ "empty": "Noch keine Rechnung unter dieser Vereinbarung.",+ "emptyNext": "Noch keine Rechnung. Die erste wird am {{date}} erstellt."+ }}},"collections": {diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex 840074fe..7d1a7ea6 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -292,7 +292,40 @@"payable_not_shareable": "Ένας λογαριασμός που λάβατε δεν μπορεί να κοινοποιηθεί.","discount_exceeds_total": "Η έκπτωση είναι μεγαλύτερη από το τιμολογούμενο ποσό.","no_document_filed": "Αυτό το παραστατικό εκδόθηκε αλλού. Επισυνάψτε το αρχείο που παραλήφθηκε.",- "already_imported": "Αυτό το έγγραφο έχει ήδη εισαχθεί."+ "already_imported": "Αυτό το έγγραφο έχει ήδη εισαχθεί.",+ "term_lines_required": "Ένας όρος χρειάζεται τουλάχιστον μία γραμμή.",+ "term_empty": "Ένας όρος πρέπει να χρεώνει κάτι.",+ "term_in_use": "Έχει ήδη εκδοθεί τιμολόγιο βάσει αυτού του όρου. Προσθέστε νέο όρο από μεταγενέστερη ημερομηνία.",+ "term_before_start": "Ένας όρος δεν μπορεί να ξεκινά πριν από τη συμφωνία.",+ "term_date_taken": "Άλλος όρος ξεκινά ήδη αυτή την ημερομηνία.",+ "last_term": "Μια συμφωνία χρειάζεται τουλάχιστον έναν όρο.",+ "term_not_found": "Ο όρος δεν βρέθηκε.",+ "schedule_ended": "Αυτή η συμφωνία έχει τερματιστεί και δεν μπορεί πλέον να αλλάξει.",+ "schedule_locked": "Η συχνότητα, η ημερομηνία έναρξης και το νόμισμα είναι σταθερά μόλις υπάρξει τιμολόγιο βάσει αυτής της συμφωνίας.",+ "schedule_has_invoices": "Έχουν εκδοθεί τιμολόγια βάσει αυτής της συμφωνίας. Τερματίστε την αντί να τη διαγράψετε.",+ "schedule_not_active": "Μόνο μια ενεργή συμφωνία εκδίδει τιμολόγια.",+ "invalid_frequency": "Άγνωστη συχνότητα.",+ "invalid_end_type": "Άγνωστη συνθήκη λήξης.",+ "invalid_end_reason": "Άγνωστος λόγος λήξης.",+ "end_date_required": "Δηλώστε σε ποια ημερομηνία λήγει η συμφωνία.",+ "end_count_required": "Δηλώστε μετά από πόσα τιμολόγια λήγει η συμφωνία.",+ "end_before_start": "Η συμφωνία δεν μπορεί να λήξει πριν ξεκινήσει.",+ "name_required": "Δώστε ένα όνομα στη συμφωνία.",+ "not_issued": "Μόνο ένα εκδοθέν τιμολόγιο μπορεί να ξεκινήσει μια συμφωνία.",+ "already_linked": "Αυτό το τιμολόγιο ανήκει ήδη σε μια συμφωνία.",+ "invoice_void": "Ένα ακυρωμένο τιμολόγιο δεν μπορεί να καλύψει μια περίοδο.",+ "payee_mismatch": "Το τιμολόγιο και η συμφωνία αναφέρουν διαφορετικούς πελάτες.",+ "not_a_period": "Αυτή η ημερομηνία δεν είναι η έναρξη μιας περιόδου αυτής της συμφωνίας.",+ "beyond_end": "Αυτή η περίοδος είναι μετά τη λήξη της συμφωνίας.",+ "period_taken": "Άλλο τιμολόγιο καλύπτει ήδη αυτή την περίοδο.",+ "start_after_invoice": "Η συμφωνία δεν μπορεί να ξεκινά μετά από αυτό το τιμολόγιο.",+ "invoice_not_found": "Το τιμολόγιο δεν βρέθηκε.",+ "no_term": "Κανένας όρος δεν ισχύει για αυτή την περίοδο.",+ "no_author": "Αυτή η συμφωνία δεν έχει συντάκτη για να εκδίδει τιμολόγια.",+ "negative_discount": "Μια έκπτωση δεν μπορεί να είναι αρνητική.",+ "first_term": "Η τιμή που ισχύει από την αρχή δεν μπορεί να μετακινηθεί ή να αφαιρεθεί. Αλλάξτε την ή προσθέστε νέα τιμή από μεταγενέστερη ημερομηνία.",+ "not_receivable": "Μόνο ένα τιμολόγιο που εκδώσατε εσείς μπορεί να ανήκει σε μια συμφωνία.",+ "period_already_issued": "Αυτή η περίοδος μόλις εκδόθηκε. Ανανεώστε τη σελίδα για να τη δείτε."},"comingNext": "Τιμολογήστε τους πελάτες σας και παρακολουθήστε τι έχει πληρωθεί και τι εκκρεμεί. Αυτή είναι η επόμενη λειτουργία που αναπτύσσεται.","document": {@@ -381,6 +414,152 @@"wouldApply": "θα εφάρμοζε {{amount}}","alsoCovers_one": "καλύπτει επίσης {{count}} ακόμη τιμολόγιο","alsoCovers_other": "καλύπτει επίσης {{count}} ακόμη τιμολόγια"+ },+ "schedules": {+ "title": "Επαναλαμβανόμενα",+ "new": "Νέο επαναλαμβανόμενο τιμολόγιο",+ "newDescription": "Μια συμφωνία με έναν πελάτη για χρέωση κάθε περίοδο. Τα τιμολόγια συντάσσονται για εσάς, την προβλεπόμενη ημέρα.",+ "backToList": "Πίσω στα επαναλαμβανόμενα",+ "empty": "Δεν υπάρχουν ακόμη επαναλαμβανόμενα τιμολόγια. Δημιουργήστε ένα, ή ανοίξτε ένα τιμολόγιο και επιλέξτε \"Επανάληψη αυτού του τιμολογίου\".",+ "emptyFiltered": "Τίποτα εδώ με αυτή την κατάσταση.",+ "created": "Το επαναλαμβανόμενο τιμολόγιο δημιουργήθηκε",+ "saved": "Οι αλλαγές αποθηκεύτηκαν",+ "deleted": "Το επαναλαμβανόμενο τιμολόγιο διαγράφηκε",+ "paused": "Σε παύση. Δεν θα χρεωθεί τίποτα μέχρι να το συνεχίσετε.",+ "resumed": "Συνεχίζεται από την επόμενη περίοδο.",+ "ended": "Η συμφωνία τερματίστηκε",+ "generated_one": "Το τιμολόγιο εκδόθηκε",+ "generated_other": "Εκδόθηκαν {{count}} τιμολόγια",+ "termSaved": "Η τιμή αποθηκεύτηκε",+ "termRemoved": "Η αλλαγή τιμής αφαιρέθηκε",+ "linked": "Το τιμολόγιο συνδέθηκε με τη συμφωνία",+ "unlinked": "Το τιμολόγιο αποσυνδέθηκε από τη συμφωνία",+ "recurringInvoice": "Επαναλαμβανόμενο τιμολόγιο",+ "monthlyPreview": "Περίπου {{amount}} τον μήνα.",+ "since": "από {{date}}",+ "untilDate": "έως {{date}}",+ "untilCount_one": "{{count}} τιμολόγιο συνολικά",+ "untilCount_other": "{{count}} τιμολόγια συνολικά",+ "endedOn": "τερματίστηκε στις {{date}} ({{reason}})",+ "pausedByFailures": "Σε παύση μετά από επανειλημμένες αποτυχίες. Ελέγξτε τους όρους και συνεχίστε.",+ "editTitle": "Επεξεργασία επαναλαμβανόμενου τιμολογίου",+ "editDescription": "Το όνομα, ο πελάτης, οι όροι και πότε λήγει.",+ "editLockedDescription": "Έχουν εκδοθεί τιμολόγια βάσει αυτής της συμφωνίας, οπότε η συχνότητα και η ημερομηνία έναρξης είναι σταθερές. Όλα τα υπόλοιπα μπορούν να αλλάξουν.",+ "endTitle": "Τερματισμός αυτής της συμφωνίας;",+ "endDescription": "Δεν θα εκδοθούν άλλα τιμολόγια. Όσα έχουν ήδη εκδοθεί μένουν ακριβώς όπως είναι. Δηλώστε τον λόγο: είναι το μόνο που τα τιμολόγια δεν θα μπορούν να σας πουν αργότερα.",+ "linkTitle": "Σύνδεση υπάρχοντος τιμολογίου",+ "linkDescription": "Ένα τιμολόγιο που συντάξατε χειροκίνητα για μία από τις περιόδους αυτής της συμφωνίας. Διατηρεί τον αριθμό, την ημερομηνία και τις πληρωμές του. Μαθαίνει μόνο για ποια περίοδο ήταν.",+ "noCandidates": "Δεν υπάρχει μη συνδεδεμένο τιμολόγιο για αυτόν τον πελάτη σε αυτό το νόμισμα.",+ "makeRecurringDescription": "Αυτό το τιμολόγιο γίνεται μία περίοδος μιας νέας συμφωνίας, και τα επόμενα συντάσσονται για εσάς. Η ημερομηνία του, {{date}}, είναι η πρώτη περίοδος, εκτός αν δηλώσετε ότι η συμφωνία ξεκίνησε νωρίτερα.",+ "filter": {+ "all": "Όλα",+ "active": "Ενεργά",+ "paused": "Σε παύση",+ "ended": "Τερματισμένα"+ },+ "state": {+ "active": "Ενεργή",+ "past_due": "Ληξιπρόθεσμη",+ "paused": "Σε παύση",+ "paused_failures": "Χρειάζεται προσοχή",+ "ended": "Τερματισμένη"+ },+ "frequency": {+ "weekly": "Εβδομαδιαία",+ "biweekly": "Κάθε 2 εβδομάδες",+ "monthly": "Μηνιαία",+ "quarterly": "Τριμηνιαία",+ "semiannual": "Κάθε 6 μήνες",+ "yearly": "Ετήσια"+ },+ "endType": {+ "never": "Ποτέ",+ "on_date": "Σε μια ημερομηνία",+ "after_count": "Μετά από έναν αριθμό τιμολογίων"+ },+ "endReason": {+ "canceled_by_client": "Ακυρώθηκε από τον πελάτη",+ "canceled_by_us": "Ακυρώθηκε από εμάς",+ "completed": "Ολοκληρώθηκε",+ "unpaid": "Απλήρωτη",+ "other": "Άλλο"+ },+ "summary": {+ "monthly": "Μηνιαία επαναλαμβανόμενα",+ "yearly": "Ανά έτος",+ "lost": "Χάθηκαν τις τελευταίες 30 ημέρες",+ "endedRecently_one": "{{count}} συμφωνία τερματίστηκε",+ "endedRecently_other": "{{count}} συμφωνίες τερματίστηκαν",+ "pastDue": "Ληξιπρόθεσμα",+ "pastDueHint": "συμφωνίες με καθυστερημένο τιμολόγιο",+ "activeCount_one": "{{count}} ενεργή συμφωνία",+ "activeCount_other": "{{count}} ενεργές συμφωνίες",+ "none": "Τίποτα επαναλαμβανόμενο ακόμη"+ },+ "column": {+ "name": "Συμφωνία",+ "cadence": "Ρυθμός",+ "monthly": "Ανά μήνα",+ "next": "Επόμενο τιμολόγιο",+ "invoices": "Τιμολόγια",+ "status": "Κατάσταση",+ "period": "Περίοδος"+ },+ "figure": {+ "invoiced": "Τιμολογήθηκαν",+ "paid": "Εισπράχθηκαν",+ "pastDue_one": "{{count}} ληξιπρόθεσμο τιμολόγιο",+ "pastDue_other": "{{count}} ληξιπρόθεσμα τιμολόγια"+ },+ "field": {+ "name": "Όνομα",+ "namePlaceholder": "Πλάνο Pro, μηνιαία αμοιβή, φιλοξενία",+ "frequency": "Συχνότητα",+ "startDate": "Ξεκινά στις",+ "startDateHint": "Μια ημερομηνία πριν από το τιμολόγιο αφήνει χώρο για να συνδέσετε τα προηγούμενα.",+ "paymentTerms": "Όροι πληρωμής (ημέρες)",+ "currency": "Νόμισμα",+ "ends": "Λήγει",+ "endDate": "Ημερομηνία λήξης",+ "endCount": "Αριθμός τιμολογίων",+ "endReason": "Λόγος",+ "endedAt": "Τερματίστηκε στις",+ "invoice": "Τιμολόγιο",+ "invoicePlaceholder": "Επιλέξτε τιμολόγιο",+ "period": "Περίοδος",+ "periodPlaceholder": "Επιλέξτε περίοδο"+ },+ "action": {+ "changePrice": "Αλλαγή τιμής",+ "generate": "Έκδοση επόμενου τώρα",+ "pause": "Παύση",+ "resume": "Συνέχιση",+ "end": "Τερματισμός συμφωνίας",+ "linkInvoice": "Σύνδεση τιμολογίου",+ "link": "Σύνδεση",+ "makeRecurring": "Επανάληψη αυτού του τιμολογίου",+ "unlink": "Αφαίρεση από τη συμφωνία"+ },+ "terms": {+ "title": "Τιμή",+ "description": "Τι χρεώνει η συμφωνία ανά περίοδο, και από πότε. Μια αλλαγή ισχύει από την πρώτη περίοδο που ξεκινά την ημερομηνία της ή μετά. Τίποτα δεν υπολογίζεται αναλογικά.",+ "from": "Από {{date}}",+ "current": "Σε ισχύ",+ "upcoming": "Επερχόμενη",+ "perMonth": "{{amount}} τον μήνα",+ "editTitle": "Επεξεργασία αλλαγής τιμής",+ "changeDescription": "Καταχωρίστε μια νέα τιμή από μια ημερομηνία και μετά. Οι περίοδοι που έχουν ήδη τιμολογηθεί διατηρούν ό,τι χρεώθηκαν. Η αλλαγή ξεκινά με την πρώτη περίοδο την ημερομηνία αυτή ή μετά, εξ ολοκλήρου.",+ "effectiveFrom": "Από",+ "nextPeriodHint": "Η επόμενη περίοδος ξεκινά στις {{date}}.",+ "discount": "Έκπτωση",+ "preview": "{{period}} ανά περίοδο, περίπου {{monthly}} τον μήνα."+ },+ "invoices": {+ "title": "Τιμολόγια",+ "description": "Ένα ανά περίοδο, συντάσσεται την προβλεπόμενη ημέρα. Ένα τιμολόγιο που συντάξατε χειροκίνητα μπορεί επίσης να συνδεθεί.",+ "empty": "Κανένα τιμολόγιο βάσει αυτής της συμφωνίας ακόμη.",+ "emptyNext": "Κανένα τιμολόγιο ακόμη. Το πρώτο θα συνταχθεί στις {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex bcfd3a13..9f67027d 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -292,7 +292,40 @@"payable_not_shareable": "A bill you received cannot be shared.","discount_exceeds_total": "The discount is larger than the amount being billed.","no_document_filed": "This document was issued elsewhere. Attach the file that was received.",- "already_imported": "This document has already been imported."+ "already_imported": "This document has already been imported.",+ "term_lines_required": "A term needs at least one line.",+ "term_empty": "A term must bill something.",+ "term_in_use": "An invoice was already issued under this term. Add a new term from a later date.",+ "term_before_start": "A term cannot start before the agreement does.",+ "term_date_taken": "Another term already starts on that date.",+ "last_term": "An agreement needs at least one term.",+ "term_not_found": "Term not found.",+ "schedule_ended": "This agreement has ended and can no longer change.",+ "schedule_locked": "The frequency, start date and currency are fixed once an invoice exists under this agreement.",+ "schedule_has_invoices": "Invoices were issued under this agreement. End it instead of deleting it.",+ "schedule_not_active": "Only an active agreement emits invoices.",+ "invalid_frequency": "Unknown frequency.",+ "invalid_end_type": "Unknown end condition.",+ "invalid_end_reason": "Unknown end reason.",+ "end_date_required": "Say on which date the agreement ends.",+ "end_count_required": "Say after how many invoices the agreement ends.",+ "end_before_start": "The agreement cannot end before it starts.",+ "name_required": "Give the agreement a name.",+ "not_issued": "Only an issued invoice can start an agreement.",+ "already_linked": "This invoice already belongs to an agreement.",+ "invoice_void": "A voided invoice cannot answer for a period.",+ "payee_mismatch": "The invoice and the agreement name different clients.",+ "not_a_period": "That date is not the start of a period of this agreement.",+ "beyond_end": "That period is after the agreement ends.",+ "period_taken": "Another invoice already answers for that period.",+ "start_after_invoice": "The agreement cannot start after this invoice.",+ "invoice_not_found": "Invoice not found.",+ "no_term": "No term is in force for this period.",+ "no_author": "This agreement has no author to issue invoices as.",+ "negative_discount": "A discount cannot be negative.",+ "first_term": "The price in force from the start cannot be moved or removed. Change it, or add a new price from a later date.",+ "not_receivable": "Only an invoice you issued can belong to an agreement.",+ "period_already_issued": "This period was just issued. Refresh to see it."},"comingNext": "Bill your clients and keep track of what has been paid and what is still open. This is the next thing being built.","document": {@@ -381,6 +414,152 @@"wouldApply": "would apply {{amount}}","alsoCovers_one": "also covers {{count}} other invoice","alsoCovers_other": "also covers {{count}} other invoices"+ },+ "schedules": {+ "title": "Recurring",+ "new": "New recurring invoice",+ "newDescription": "An agreement with a client to bill them every period. The invoices are written for you, on the day.",+ "backToList": "Back to recurring",+ "empty": "No recurring invoices yet. Set one up, or open an invoice and choose \"Repeat this invoice\".",+ "emptyFiltered": "Nothing here with this status.",+ "created": "Recurring invoice created",+ "saved": "Changes saved",+ "deleted": "Recurring invoice deleted",+ "paused": "Paused. Nothing will be billed until you resume it.",+ "resumed": "Resumed from the next period on.",+ "ended": "Agreement ended",+ "generated_one": "Invoice issued",+ "generated_other": "{{count}} invoices issued",+ "termSaved": "Price saved",+ "termRemoved": "Price change removed",+ "linked": "Invoice linked to the agreement",+ "unlinked": "Invoice unlinked from the agreement",+ "recurringInvoice": "Recurring invoice",+ "monthlyPreview": "About {{amount}} a month.",+ "since": "since {{date}}",+ "untilDate": "until {{date}}",+ "untilCount_one": "{{count}} invoice in total",+ "untilCount_other": "{{count}} invoices in total",+ "endedOn": "ended {{date}} ({{reason}})",+ "pausedByFailures": "Paused after repeated failures. Check the terms and resume.",+ "editTitle": "Edit recurring invoice",+ "editDescription": "The name, the client, the terms and when it ends.",+ "editLockedDescription": "Invoices were issued under this agreement, so its frequency and start date are fixed. Everything else can change.",+ "endTitle": "End this agreement?",+ "endDescription": "No more invoices will be issued. The ones already issued stay exactly as they are. Say why: it is the one thing the invoices cannot tell you later.",+ "linkTitle": "Link an existing invoice",+ "linkDescription": "An invoice you wrote by hand for one of this agreement's periods. It keeps its number, its date and its payments; it only learns which period it was for.",+ "noCandidates": "No unlinked invoice for this client in this currency.",+ "makeRecurringDescription": "This invoice becomes one period of a new agreement, and the next ones are written for you. Its own date, {{date}}, is the first period unless you say the agreement started earlier.",+ "filter": {+ "all": "All",+ "active": "Active",+ "paused": "Paused",+ "ended": "Ended"+ },+ "state": {+ "active": "Active",+ "past_due": "Past due",+ "paused": "Paused",+ "paused_failures": "Needs attention",+ "ended": "Ended"+ },+ "frequency": {+ "weekly": "Weekly",+ "biweekly": "Every 2 weeks",+ "monthly": "Monthly",+ "quarterly": "Quarterly",+ "semiannual": "Every 6 months",+ "yearly": "Yearly"+ },+ "endType": {+ "never": "Never",+ "on_date": "On a date",+ "after_count": "After a number of invoices"+ },+ "endReason": {+ "canceled_by_client": "Canceled by the client",+ "canceled_by_us": "Canceled by us",+ "completed": "Ran its course",+ "unpaid": "Unpaid",+ "other": "Other"+ },+ "summary": {+ "monthly": "Monthly recurring",+ "yearly": "Per year",+ "lost": "Lost in the last 30 days",+ "endedRecently_one": "{{count}} agreement ended",+ "endedRecently_other": "{{count}} agreements ended",+ "pastDue": "Past due",+ "pastDueHint": "agreements with a late invoice",+ "activeCount_one": "{{count}} active agreement",+ "activeCount_other": "{{count}} active agreements",+ "none": "Nothing recurring yet"+ },+ "column": {+ "name": "Agreement",+ "cadence": "Cadence",+ "monthly": "Per month",+ "next": "Next invoice",+ "invoices": "Invoices",+ "status": "Status",+ "period": "Period"+ },+ "figure": {+ "invoiced": "Invoiced",+ "paid": "Received",+ "pastDue_one": "{{count}} invoice past due",+ "pastDue_other": "{{count}} invoices past due"+ },+ "field": {+ "name": "Name",+ "namePlaceholder": "Pro plan, monthly retainer, hosting",+ "frequency": "Frequency",+ "startDate": "Starts on",+ "startDateHint": "Earlier than the invoice makes room to link the ones before it.",+ "paymentTerms": "Payment terms (days)",+ "currency": "Currency",+ "ends": "Ends",+ "endDate": "End date",+ "endCount": "Number of invoices",+ "endReason": "Reason",+ "endedAt": "Ended on",+ "invoice": "Invoice",+ "invoicePlaceholder": "Choose an invoice",+ "period": "Period",+ "periodPlaceholder": "Choose a period"+ },+ "action": {+ "changePrice": "Change price",+ "generate": "Issue next now",+ "pause": "Pause",+ "resume": "Resume",+ "end": "End agreement",+ "linkInvoice": "Link invoice",+ "link": "Link",+ "makeRecurring": "Repeat this invoice",+ "unlink": "Remove from agreement"+ },+ "terms": {+ "title": "Price",+ "description": "What the agreement bills per period, and from when. A change applies from the first period starting on or after its date; nothing is prorated.",+ "from": "From {{date}}",+ "current": "Current",+ "upcoming": "Upcoming",+ "perMonth": "{{amount}} a month",+ "editTitle": "Edit price change",+ "changeDescription": "Record a new price from a date on. Periods already invoiced keep what they were billed; the change starts with the first period on or after the date, in full.",+ "effectiveFrom": "From",+ "nextPeriodHint": "The next period starts {{date}}.",+ "discount": "Discount",+ "preview": "{{period}} per period, about {{monthly}} a month."+ },+ "invoices": {+ "title": "Invoices",+ "description": "One per period, written on the day. An invoice you wrote by hand can be linked too.",+ "empty": "No invoice under this agreement yet.",+ "emptyNext": "No invoice yet. The first one is written on {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 1e58aea7..4838b1d2 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -292,7 +292,40 @@"payable_not_shareable": "Una factura recibida no se puede compartir.","discount_exceeds_total": "El descuento es mayor que el importe facturado.","no_document_filed": "Este documento se emitió en otro lugar. Adjunta el archivo recibido.",- "already_imported": "Este documento ya fue importado."+ "already_imported": "Este documento ya fue importado.",+ "term_lines_required": "Una condición necesita al menos una línea.",+ "term_empty": "Una condición debe facturar algo.",+ "term_in_use": "Ya se emitió una factura bajo esta condición. Añade una nueva condición desde una fecha posterior.",+ "term_before_start": "Una condición no puede empezar antes que el acuerdo.",+ "term_date_taken": "Otra condición ya empieza en esa fecha.",+ "last_term": "Un acuerdo necesita al menos una condición.",+ "term_not_found": "Condición no encontrada.",+ "schedule_ended": "Este acuerdo ha finalizado y ya no puede cambiar.",+ "schedule_locked": "La frecuencia, la fecha de inicio y la moneda quedan fijas en cuanto existe una factura bajo este acuerdo.",+ "schedule_has_invoices": "Se emitieron facturas bajo este acuerdo. Finalízalo en lugar de eliminarlo.",+ "schedule_not_active": "Solo un acuerdo activo emite facturas.",+ "invalid_frequency": "Frecuencia desconocida.",+ "invalid_end_type": "Condición de fin desconocida.",+ "invalid_end_reason": "Motivo de fin desconocido.",+ "end_date_required": "Indica en qué fecha termina el acuerdo.",+ "end_count_required": "Indica tras cuántas facturas termina el acuerdo.",+ "end_before_start": "El acuerdo no puede terminar antes de empezar.",+ "name_required": "Dale un nombre al acuerdo.",+ "not_issued": "Solo una factura emitida puede iniciar un acuerdo.",+ "already_linked": "Esta factura ya pertenece a un acuerdo.",+ "invoice_void": "Una factura anulada no puede cubrir un período.",+ "payee_mismatch": "La factura y el acuerdo indican clientes distintos.",+ "not_a_period": "Esa fecha no es el inicio de un período de este acuerdo.",+ "beyond_end": "Ese período es posterior al fin del acuerdo.",+ "period_taken": "Otra factura ya cubre ese período.",+ "start_after_invoice": "El acuerdo no puede empezar después de esta factura.",+ "invoice_not_found": "Factura no encontrada.",+ "no_term": "No hay ninguna condición vigente para este período.",+ "no_author": "Este acuerdo no tiene un autor con el que emitir facturas.",+ "negative_discount": "Un descuento no puede ser negativo.",+ "first_term": "El precio vigente desde el inicio no se puede mover ni eliminar. Cámbialo o añade un nuevo precio a partir de una fecha posterior.",+ "not_receivable": "Solo una factura emitida por ti puede pertenecer a un acuerdo.",+ "period_already_issued": "Este período se acaba de emitir. Actualiza para verlo."},"comingNext": "Cobra a tus clientes y controla lo que ya se pagó y lo que sigue pendiente. Es lo próximo que se está construyendo.","document": {@@ -381,6 +414,152 @@"wouldApply": "aplicaría {{amount}}","alsoCovers_one": "también cubre otra {{count}} factura","alsoCovers_other": "también cubre otras {{count}} facturas"+ },+ "schedules": {+ "title": "Recurrentes",+ "new": "Nueva factura recurrente",+ "newDescription": "Un acuerdo con un cliente para facturarle cada período. Las facturas se generan por ti, el mismo día.",+ "backToList": "Volver a recurrentes",+ "empty": "Aún no hay facturas recurrentes. Crea una, o abre una factura y elige \"Repetir esta factura\".",+ "emptyFiltered": "Nada aquí con este estado.",+ "created": "Factura recurrente creada",+ "saved": "Cambios guardados",+ "deleted": "Factura recurrente eliminada",+ "paused": "En pausa. No se facturará nada hasta que la reanudes.",+ "resumed": "Reanudada a partir del próximo período.",+ "ended": "Acuerdo finalizado",+ "generated_one": "Factura emitida",+ "generated_other": "{{count}} facturas emitidas",+ "termSaved": "Precio guardado",+ "termRemoved": "Cambio de precio eliminado",+ "linked": "Factura vinculada al acuerdo",+ "unlinked": "Factura desvinculada del acuerdo",+ "recurringInvoice": "Factura recurrente",+ "monthlyPreview": "Cerca de {{amount}} al mes.",+ "since": "desde {{date}}",+ "untilDate": "hasta {{date}}",+ "untilCount_one": "{{count}} factura en total",+ "untilCount_other": "{{count}} facturas en total",+ "endedOn": "finalizado el {{date}} ({{reason}})",+ "pausedByFailures": "En pausa tras fallos repetidos. Revisa las condiciones y reanuda.",+ "editTitle": "Editar factura recurrente",+ "editDescription": "El nombre, el cliente, las condiciones y cuándo termina.",+ "editLockedDescription": "Ya se emitieron facturas bajo este acuerdo, así que la frecuencia y la fecha de inicio quedan fijas. Todo lo demás puede cambiar.",+ "endTitle": "¿Finalizar este acuerdo?",+ "endDescription": "No se emitirán más facturas. Las ya emitidas quedan exactamente como están. Indica el motivo: es lo único que las facturas no podrán contarte después.",+ "linkTitle": "Vincular una factura existente",+ "linkDescription": "Una factura que hiciste a mano para uno de los períodos de este acuerdo. Conserva su número, su fecha y sus pagos; solo pasa a saber a qué período pertenece.",+ "noCandidates": "No hay facturas sin vincular para este cliente en esta moneda.",+ "makeRecurringDescription": "Esta factura pasa a ser un período de un nuevo acuerdo, y las siguientes se generan por ti. Su fecha, {{date}}, es el primer período, a menos que indiques que el acuerdo empezó antes.",+ "filter": {+ "all": "Todos",+ "active": "Activos",+ "paused": "En pausa",+ "ended": "Finalizados"+ },+ "state": {+ "active": "Activo",+ "past_due": "Vencido",+ "paused": "En pausa",+ "paused_failures": "Requiere atención",+ "ended": "Finalizado"+ },+ "frequency": {+ "weekly": "Semanal",+ "biweekly": "Cada 2 semanas",+ "monthly": "Mensual",+ "quarterly": "Trimestral",+ "semiannual": "Semestral",+ "yearly": "Anual"+ },+ "endType": {+ "never": "Nunca",+ "on_date": "En una fecha",+ "after_count": "Tras un número de facturas"+ },+ "endReason": {+ "canceled_by_client": "Cancelado por el cliente",+ "canceled_by_us": "Cancelado por nosotros",+ "completed": "Llegó a su fin",+ "unpaid": "Impago",+ "other": "Otro"+ },+ "summary": {+ "monthly": "Recurrente mensual",+ "yearly": "Por año",+ "lost": "Perdido en los últimos 30 días",+ "endedRecently_one": "{{count}} acuerdo finalizado",+ "endedRecently_other": "{{count}} acuerdos finalizados",+ "pastDue": "Vencido",+ "pastDueHint": "acuerdos con una factura atrasada",+ "activeCount_one": "{{count}} acuerdo activo",+ "activeCount_other": "{{count}} acuerdos activos",+ "none": "Nada recurrente todavía"+ },+ "column": {+ "name": "Acuerdo",+ "cadence": "Cadencia",+ "monthly": "Por mes",+ "next": "Próxima factura",+ "invoices": "Facturas",+ "status": "Estado",+ "period": "Período"+ },+ "figure": {+ "invoiced": "Facturado",+ "paid": "Cobrado",+ "pastDue_one": "{{count}} factura vencida",+ "pastDue_other": "{{count}} facturas vencidas"+ },+ "field": {+ "name": "Nombre",+ "namePlaceholder": "Plan Pro, retainer mensual, hosting",+ "frequency": "Frecuencia",+ "startDate": "Empieza el",+ "startDateHint": "Una fecha anterior a la factura deja espacio para vincular las anteriores.",+ "paymentTerms": "Plazo de pago (días)",+ "currency": "Moneda",+ "ends": "Termina",+ "endDate": "Fecha de fin",+ "endCount": "Número de facturas",+ "endReason": "Motivo",+ "endedAt": "Finalizado el",+ "invoice": "Factura",+ "invoicePlaceholder": "Elige una factura",+ "period": "Período",+ "periodPlaceholder": "Elige un período"+ },+ "action": {+ "changePrice": "Cambiar precio",+ "generate": "Emitir la siguiente ahora",+ "pause": "Pausar",+ "resume": "Reanudar",+ "end": "Finalizar acuerdo",+ "linkInvoice": "Vincular factura",+ "link": "Vincular",+ "makeRecurring": "Repetir esta factura",+ "unlink": "Quitar del acuerdo"+ },+ "terms": {+ "title": "Precio",+ "description": "Lo que el acuerdo factura por período, y desde cuándo. Un cambio se aplica desde el primer período que empieza en su fecha o después; nada se prorratea.",+ "from": "Desde {{date}}",+ "current": "Vigente",+ "upcoming": "Próximo",+ "perMonth": "{{amount}} al mes",+ "editTitle": "Editar cambio de precio",+ "changeDescription": "Registra un nuevo precio a partir de una fecha. Los períodos ya facturados conservan lo que se les facturó; el cambio empieza con el primer período en esa fecha o después, completo.",+ "effectiveFrom": "Desde",+ "nextPeriodHint": "El próximo período empieza el {{date}}.",+ "discount": "Descuento",+ "preview": "{{period}} por período, cerca de {{monthly}} al mes."+ },+ "invoices": {+ "title": "Facturas",+ "description": "Una por período, generada el mismo día. Una factura hecha a mano también se puede vincular.",+ "empty": "Aún no hay facturas bajo este acuerdo.",+ "emptyNext": "Aún no hay facturas. La primera se generará el {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex fc10f3cb..be7642b1 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -292,7 +292,40 @@"payable_not_shareable": "Une facture reçue ne peut pas être partagée.","discount_exceeds_total": "La remise dépasse le montant facturé.","no_document_filed": "Ce document a été émis ailleurs. Joignez le fichier reçu.",- "already_imported": "Ce document a déjà été importé."+ "already_imported": "Ce document a déjà été importé.",+ "term_lines_required": "Une condition a besoin d'au moins une ligne.",+ "term_empty": "Une condition doit facturer quelque chose.",+ "term_in_use": "Une facture a déjà été émise sous cette condition. Ajoutez une nouvelle condition à partir d'une date ultérieure.",+ "term_before_start": "Une condition ne peut pas commencer avant l'accord.",+ "term_date_taken": "Une autre condition commence déjà à cette date.",+ "last_term": "Un accord a besoin d'au moins une condition.",+ "term_not_found": "Condition introuvable.",+ "schedule_ended": "Cet accord est terminé et ne peut plus changer.",+ "schedule_locked": "La fréquence, la date de début et la devise sont figées dès qu'une facture existe sous cet accord.",+ "schedule_has_invoices": "Des factures ont été émises sous cet accord. Terminez-le au lieu de le supprimer.",+ "schedule_not_active": "Seul un accord actif émet des factures.",+ "invalid_frequency": "Fréquence inconnue.",+ "invalid_end_type": "Condition de fin inconnue.",+ "invalid_end_reason": "Motif de fin inconnu.",+ "end_date_required": "Indiquez à quelle date l'accord se termine.",+ "end_count_required": "Indiquez après combien de factures l'accord se termine.",+ "end_before_start": "L'accord ne peut pas se terminer avant de commencer.",+ "name_required": "Donnez un nom à l'accord.",+ "not_issued": "Seule une facture émise peut démarrer un accord.",+ "already_linked": "Cette facture appartient déjà à un accord.",+ "invoice_void": "Une facture annulée ne peut pas couvrir une période.",+ "payee_mismatch": "La facture et l'accord désignent des clients différents.",+ "not_a_period": "Cette date n'est pas le début d'une période de cet accord.",+ "beyond_end": "Cette période est postérieure à la fin de l'accord.",+ "period_taken": "Une autre facture couvre déjà cette période.",+ "start_after_invoice": "L'accord ne peut pas commencer après cette facture.",+ "invoice_not_found": "Facture introuvable.",+ "no_term": "Aucune condition n'est en vigueur pour cette période.",+ "no_author": "Cet accord n'a pas d'auteur au nom duquel émettre les factures.",+ "negative_discount": "Une remise ne peut pas être négative.",+ "first_term": "Le prix en vigueur depuis le début ne peut être ni déplacé ni supprimé. Modifiez-le, ou ajoutez un nouveau prix à partir d'une date ultérieure.",+ "not_receivable": "Seule une facture que vous avez émise peut appartenir à un accord.",+ "period_already_issued": "Cette période vient d'être émise. Actualisez pour la voir."},"comingNext": "Facturez vos clients et suivez ce qui a été payé et ce qui reste ouvert. C'est la prochaine chose en construction.","document": {@@ -381,6 +414,152 @@"wouldApply": "appliquerait {{amount}}","alsoCovers_one": "couvre aussi {{count}} autre facture","alsoCovers_other": "couvre aussi {{count}} autres factures"+ },+ "schedules": {+ "title": "Récurrentes",+ "new": "Nouvelle facture récurrente",+ "newDescription": "Un accord avec un client pour le facturer à chaque période. Les factures sont rédigées pour vous, le jour même.",+ "backToList": "Retour aux récurrentes",+ "empty": "Aucune facture récurrente pour l'instant. Créez-en une, ou ouvrez une facture et choisissez \"Répéter cette facture\".",+ "emptyFiltered": "Rien ici avec ce statut.",+ "created": "Facture récurrente créée",+ "saved": "Modifications enregistrées",+ "deleted": "Facture récurrente supprimée",+ "paused": "En pause. Rien ne sera facturé tant que vous ne la reprenez pas.",+ "resumed": "Reprise à partir de la prochaine période.",+ "ended": "Accord terminé",+ "generated_one": "Facture émise",+ "generated_other": "{{count}} factures émises",+ "termSaved": "Prix enregistré",+ "termRemoved": "Changement de prix supprimé",+ "linked": "Facture liée à l'accord",+ "unlinked": "Facture détachée de l'accord",+ "recurringInvoice": "Facture récurrente",+ "monthlyPreview": "Environ {{amount}} par mois.",+ "since": "depuis le {{date}}",+ "untilDate": "jusqu'au {{date}}",+ "untilCount_one": "{{count}} facture au total",+ "untilCount_other": "{{count}} factures au total",+ "endedOn": "terminé le {{date}} ({{reason}})",+ "pausedByFailures": "En pause après des échecs répétés. Vérifiez les conditions et reprenez.",+ "editTitle": "Modifier la facture récurrente",+ "editDescription": "Le nom, le client, les conditions et la date de fin.",+ "editLockedDescription": "Des factures ont été émises sous cet accord, donc sa fréquence et sa date de début sont figées. Tout le reste peut changer.",+ "endTitle": "Terminer cet accord ?",+ "endDescription": "Plus aucune facture ne sera émise. Celles déjà émises restent exactement telles quelles. Indiquez le motif : c'est la seule chose que les factures ne pourront pas vous dire plus tard.",+ "linkTitle": "Lier une facture existante",+ "linkDescription": "Une facture que vous avez rédigée à la main pour l'une des périodes de cet accord. Elle garde son numéro, sa date et ses paiements ; elle apprend seulement à quelle période elle correspond.",+ "noCandidates": "Aucune facture non liée pour ce client dans cette devise.",+ "makeRecurringDescription": "Cette facture devient une période d'un nouvel accord, et les suivantes sont rédigées pour vous. Sa propre date, {{date}}, est la première période, sauf si vous indiquez que l'accord a commencé plus tôt.",+ "filter": {+ "all": "Toutes",+ "active": "Actives",+ "paused": "En pause",+ "ended": "Terminées"+ },+ "state": {+ "active": "Actif",+ "past_due": "En retard",+ "paused": "En pause",+ "paused_failures": "Attention requise",+ "ended": "Terminé"+ },+ "frequency": {+ "weekly": "Hebdomadaire",+ "biweekly": "Toutes les 2 semaines",+ "monthly": "Mensuelle",+ "quarterly": "Trimestrielle",+ "semiannual": "Tous les 6 mois",+ "yearly": "Annuelle"+ },+ "endType": {+ "never": "Jamais",+ "on_date": "À une date",+ "after_count": "Après un nombre de factures"+ },+ "endReason": {+ "canceled_by_client": "Annulé par le client",+ "canceled_by_us": "Annulé par nous",+ "completed": "Arrivé à son terme",+ "unpaid": "Impayé",+ "other": "Autre"+ },+ "summary": {+ "monthly": "Récurrent mensuel",+ "yearly": "Par an",+ "lost": "Perdu sur les 30 derniers jours",+ "endedRecently_one": "{{count}} accord terminé",+ "endedRecently_other": "{{count}} accords terminés",+ "pastDue": "En retard",+ "pastDueHint": "accords avec une facture en retard",+ "activeCount_one": "{{count}} accord actif",+ "activeCount_other": "{{count}} accords actifs",+ "none": "Rien de récurrent pour l'instant"+ },+ "column": {+ "name": "Accord",+ "cadence": "Cadence",+ "monthly": "Par mois",+ "next": "Prochaine facture",+ "invoices": "Factures",+ "status": "Statut",+ "period": "Période"+ },+ "figure": {+ "invoiced": "Facturé",+ "paid": "Encaissé",+ "pastDue_one": "{{count}} facture en retard",+ "pastDue_other": "{{count}} factures en retard"+ },+ "field": {+ "name": "Nom",+ "namePlaceholder": "Offre Pro, forfait mensuel, hébergement",+ "frequency": "Fréquence",+ "startDate": "Commence le",+ "startDateHint": "Une date antérieure à la facture laisse la place pour lier celles d'avant.",+ "paymentTerms": "Délai de paiement (jours)",+ "currency": "Devise",+ "ends": "Se termine",+ "endDate": "Date de fin",+ "endCount": "Nombre de factures",+ "endReason": "Motif",+ "endedAt": "Terminé le",+ "invoice": "Facture",+ "invoicePlaceholder": "Choisir une facture",+ "period": "Période",+ "periodPlaceholder": "Choisir une période"+ },+ "action": {+ "changePrice": "Changer le prix",+ "generate": "Émettre la prochaine maintenant",+ "pause": "Mettre en pause",+ "resume": "Reprendre",+ "end": "Terminer l'accord",+ "linkInvoice": "Lier une facture",+ "link": "Lier",+ "makeRecurring": "Répéter cette facture",+ "unlink": "Retirer de l'accord"+ },+ "terms": {+ "title": "Prix",+ "description": "Ce que l'accord facture par période, et à partir de quand. Un changement s'applique dès la première période qui commence à sa date ou après ; rien n'est calculé au prorata.",+ "from": "À partir du {{date}}",+ "current": "En vigueur",+ "upcoming": "À venir",+ "perMonth": "{{amount}} par mois",+ "editTitle": "Modifier le changement de prix",+ "changeDescription": "Enregistrez un nouveau prix à partir d'une date. Les périodes déjà facturées gardent ce qui leur a été facturé ; le changement commence avec la première période à cette date ou après, en entier.",+ "effectiveFrom": "À partir du",+ "nextPeriodHint": "La prochaine période commence le {{date}}.",+ "discount": "Remise",+ "preview": "{{period}} par période, environ {{monthly}} par mois."+ },+ "invoices": {+ "title": "Factures",+ "description": "Une par période, rédigée le jour même. Une facture rédigée à la main peut aussi être liée.",+ "empty": "Aucune facture sous cet accord pour l'instant.",+ "emptyNext": "Aucune facture pour l'instant. La première sera rédigée le {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex c8f9a878..c97f092e 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -292,7 +292,40 @@"payable_not_shareable": "आपको मिला बिल शेयर नहीं किया जा सकता।","discount_exceeds_total": "छूट, बिल की जा रही राशि से बड़ी है।","no_document_filed": "यह दस्तावेज़ कहीं और जारी हुआ था। जो फ़ाइल मिली थी उसे संलग्न करें।",- "already_imported": "यह दस्तावेज़ पहले ही इंपोर्ट किया जा चुका है।"+ "already_imported": "यह दस्तावेज़ पहले ही इंपोर्ट किया जा चुका है।",+ "term_lines_required": "एक शर्त में कम से कम एक पंक्ति होनी चाहिए।",+ "term_empty": "एक शर्त में कुछ न कुछ बिल होना चाहिए।",+ "term_in_use": "इस शर्त के तहत पहले ही एक इनवॉइस जारी हो चुका है। बाद की तारीख से नई शर्त जोड़ें।",+ "term_before_start": "कोई शर्त समझौते से पहले शुरू नहीं हो सकती।",+ "term_date_taken": "उस तारीख से पहले ही एक और शर्त शुरू होती है।",+ "last_term": "एक समझौते में कम से कम एक शर्त होनी चाहिए।",+ "term_not_found": "शर्त नहीं मिली।",+ "schedule_ended": "यह समझौता समाप्त हो चुका है और अब बदला नहीं जा सकता।",+ "schedule_locked": "इस समझौते के तहत कोई इनवॉइस होने के बाद आवृत्ति, शुरुआत की तारीख और मुद्रा तय हो जाती हैं।",+ "schedule_has_invoices": "इस समझौते के तहत इनवॉइस जारी हुए हैं। इसे हटाने के बजाय समाप्त करें।",+ "schedule_not_active": "केवल सक्रिय समझौता ही इनवॉइस जारी करता है।",+ "invalid_frequency": "अज्ञात आवृत्ति।",+ "invalid_end_type": "अज्ञात समाप्ति शर्त।",+ "invalid_end_reason": "अज्ञात समाप्ति कारण।",+ "end_date_required": "बताएँ कि समझौता किस तारीख को समाप्त होगा।",+ "end_count_required": "बताएँ कि कितने इनवॉइस के बाद समझौता समाप्त होगा।",+ "end_before_start": "समझौता शुरू होने से पहले समाप्त नहीं हो सकता।",+ "name_required": "समझौते को एक नाम दें।",+ "not_issued": "केवल जारी इनवॉइस ही समझौता शुरू कर सकता है।",+ "already_linked": "यह इनवॉइस पहले से किसी समझौते का हिस्सा है।",+ "invoice_void": "रद्द किया गया इनवॉइस किसी अवधि के लिए नहीं गिना जा सकता।",+ "payee_mismatch": "इनवॉइस और समझौते में अलग-अलग क्लाइंट हैं।",+ "not_a_period": "वह तारीख इस समझौते की किसी अवधि की शुरुआत नहीं है।",+ "beyond_end": "वह अवधि समझौते की समाप्ति के बाद की है।",+ "period_taken": "उस अवधि के लिए पहले से एक और इनवॉइस है।",+ "start_after_invoice": "समझौता इस इनवॉइस के बाद शुरू नहीं हो सकता।",+ "invoice_not_found": "इनवॉइस नहीं मिला।",+ "no_term": "इस अवधि के लिए कोई शर्त लागू नहीं है।",+ "no_author": "इस समझौते में इनवॉइस जारी करने के लिए कोई लेखक नहीं है।",+ "negative_discount": "छूट ऋणात्मक नहीं हो सकती।",+ "first_term": "शुरुआत से लागू मूल्य को न तो खिसकाया जा सकता है और न ही हटाया जा सकता है। इसे बदलें, या किसी बाद की तारीख से नया मूल्य जोड़ें।",+ "not_receivable": "समझौते में केवल आपके द्वारा जारी किया गया इनवॉइस ही शामिल हो सकता है।",+ "period_already_issued": "यह अवधि अभी-अभी जारी की गई है। देखने के लिए पेज रीफ़्रेश करें।"},"comingNext": "अपने क्लाइंट को बिल भेजें और ट्रैक रखें कि क्या चुकाया गया और क्या अब भी बकाया है। यह अगली चीज़ है जो बनाई जा रही है।","document": {@@ -381,6 +414,152 @@"wouldApply": "{{amount}} लगाया जाएगा","alsoCovers_one": "{{count}} और इनवॉइस भी शामिल है","alsoCovers_other": "{{count}} और इनवॉइस भी शामिल हैं"+ },+ "schedules": {+ "title": "आवर्ती",+ "new": "नया आवर्ती इनवॉइस",+ "newDescription": "किसी क्लाइंट के साथ हर अवधि में बिल भेजने का समझौता। इनवॉइस तय दिन पर आपके लिए अपने आप बनते हैं।",+ "backToList": "आवर्ती पर वापस जाएँ",+ "empty": "अभी कोई आवर्ती इनवॉइस नहीं है। एक बनाएँ, या कोई इनवॉइस खोलकर \"इस इनवॉइस को दोहराएँ\" चुनें।",+ "emptyFiltered": "इस स्थिति में यहाँ कुछ नहीं है।",+ "created": "आवर्ती इनवॉइस बनाया गया",+ "saved": "बदलाव सहेजे गए",+ "deleted": "आवर्ती इनवॉइस हटाया गया",+ "paused": "रोका गया। जब तक आप फिर से शुरू नहीं करते, कुछ भी बिल नहीं होगा।",+ "resumed": "अगली अवधि से फिर से शुरू।",+ "ended": "समझौता समाप्त",+ "generated_one": "इनवॉइस जारी किया गया",+ "generated_other": "{{count}} इनवॉइस जारी किए गए",+ "termSaved": "कीमत सहेजी गई",+ "termRemoved": "कीमत बदलाव हटाया गया",+ "linked": "इनवॉइस समझौते से जोड़ा गया",+ "unlinked": "इनवॉइस समझौते से अलग किया गया",+ "recurringInvoice": "आवर्ती इनवॉइस",+ "monthlyPreview": "लगभग {{amount}} प्रति माह।",+ "since": "{{date}} से",+ "untilDate": "{{date}} तक",+ "untilCount_one": "कुल {{count}} इनवॉइस",+ "untilCount_other": "कुल {{count}} इनवॉइस",+ "endedOn": "{{date}} को समाप्त ({{reason}})",+ "pausedByFailures": "बार-बार विफलता के बाद रोका गया। शर्तें जाँचें और फिर से शुरू करें।",+ "editTitle": "आवर्ती इनवॉइस संपादित करें",+ "editDescription": "नाम, क्लाइंट, शर्तें और यह कब समाप्त होगा।",+ "editLockedDescription": "इस समझौते के तहत इनवॉइस जारी हो चुके हैं, इसलिए इसकी आवृत्ति और शुरुआत की तारीख तय हैं। बाकी सब बदला जा सकता है।",+ "endTitle": "यह समझौता समाप्त करें?",+ "endDescription": "अब और इनवॉइस जारी नहीं होंगे। जो जारी हो चुके हैं, वे जैसे हैं वैसे ही रहेंगे। कारण बताएँ: यही एक चीज़ है जो इनवॉइस आपको बाद में नहीं बता सकते।",+ "linkTitle": "मौजूदा इनवॉइस जोड़ें",+ "linkDescription": "इस समझौते की किसी अवधि के लिए आपने हाथ से जो इनवॉइस बनाया था। उसका नंबर, तारीख और भुगतान वैसे ही रहते हैं; उसे बस यह पता चलता है कि वह किस अवधि का था।",+ "noCandidates": "इस क्लाइंट के लिए इस मुद्रा में कोई बिना जुड़ा इनवॉइस नहीं है।",+ "makeRecurringDescription": "यह इनवॉइस एक नए समझौते की एक अवधि बन जाता है, और अगले इनवॉइस आपके लिए अपने आप बनते हैं। इसकी तारीख, {{date}}, पहली अवधि है, जब तक आप यह न बताएँ कि समझौता पहले शुरू हुआ था।",+ "filter": {+ "all": "सभी",+ "active": "सक्रिय",+ "paused": "रुके हुए",+ "ended": "समाप्त"+ },+ "state": {+ "active": "सक्रिय",+ "past_due": "बकाया",+ "paused": "रुका हुआ",+ "paused_failures": "ध्यान देने की ज़रूरत",+ "ended": "समाप्त"+ },+ "frequency": {+ "weekly": "साप्ताहिक",+ "biweekly": "हर 2 सप्ताह",+ "monthly": "मासिक",+ "quarterly": "तिमाही",+ "semiannual": "हर 6 महीने",+ "yearly": "वार्षिक"+ },+ "endType": {+ "never": "कभी नहीं",+ "on_date": "किसी तारीख को",+ "after_count": "इनवॉइस की एक संख्या के बाद"+ },+ "endReason": {+ "canceled_by_client": "क्लाइंट ने रद्द किया",+ "canceled_by_us": "हमने रद्द किया",+ "completed": "पूरा हुआ",+ "unpaid": "भुगतान नहीं हुआ",+ "other": "अन्य"+ },+ "summary": {+ "monthly": "मासिक आवर्ती",+ "yearly": "प्रति वर्ष",+ "lost": "पिछले 30 दिनों में खोया",+ "endedRecently_one": "{{count}} समझौता समाप्त",+ "endedRecently_other": "{{count}} समझौते समाप्त",+ "pastDue": "बकाया",+ "pastDueHint": "ऐसे समझौते जिनका कोई इनवॉइस बकाया है",+ "activeCount_one": "{{count}} सक्रिय समझौता",+ "activeCount_other": "{{count}} सक्रिय समझौते",+ "none": "अभी कुछ भी आवर्ती नहीं"+ },+ "column": {+ "name": "समझौता",+ "cadence": "अंतराल",+ "monthly": "प्रति माह",+ "next": "अगला इनवॉइस",+ "invoices": "इनवॉइस",+ "status": "स्थिति",+ "period": "अवधि"+ },+ "figure": {+ "invoiced": "बिल किया गया",+ "paid": "प्राप्त",+ "pastDue_one": "{{count}} इनवॉइस बकाया",+ "pastDue_other": "{{count}} इनवॉइस बकाया"+ },+ "field": {+ "name": "नाम",+ "namePlaceholder": "प्रो प्लान, मासिक रिटेनर, होस्टिंग",+ "frequency": "आवृत्ति",+ "startDate": "शुरुआत",+ "startDateHint": "इनवॉइस से पहले की तारीख रखने पर उससे पहले के इनवॉइस भी जोड़े जा सकते हैं।",+ "paymentTerms": "भुगतान अवधि (दिन)",+ "currency": "मुद्रा",+ "ends": "समाप्ति",+ "endDate": "समाप्ति तारीख",+ "endCount": "इनवॉइस की संख्या",+ "endReason": "कारण",+ "endedAt": "समाप्त हुआ",+ "invoice": "इनवॉइस",+ "invoicePlaceholder": "एक इनवॉइस चुनें",+ "period": "अवधि",+ "periodPlaceholder": "एक अवधि चुनें"+ },+ "action": {+ "changePrice": "कीमत बदलें",+ "generate": "अगला अभी जारी करें",+ "pause": "रोकें",+ "resume": "फिर से शुरू करें",+ "end": "समझौता समाप्त करें",+ "linkInvoice": "इनवॉइस जोड़ें",+ "link": "जोड़ें",+ "makeRecurring": "इस इनवॉइस को दोहराएँ",+ "unlink": "समझौते से हटाएँ"+ },+ "terms": {+ "title": "कीमत",+ "description": "समझौता हर अवधि में कितना बिल करता है, और कब से। बदलाव उस पहली अवधि से लागू होता है जो उसकी तारीख को या उसके बाद शुरू होती है; कुछ भी आनुपातिक नहीं होता।",+ "from": "{{date}} से",+ "current": "वर्तमान",+ "upcoming": "आगामी",+ "perMonth": "{{amount}} प्रति माह",+ "editTitle": "कीमत बदलाव संपादित करें",+ "changeDescription": "किसी तारीख से नई कीमत दर्ज करें। जिन अवधियों का बिल बन चुका है, उनमें वही राशि रहती है; बदलाव उस तारीख को या उसके बाद की पहली अवधि से पूरा लागू होता है।",+ "effectiveFrom": "से",+ "nextPeriodHint": "अगली अवधि {{date}} को शुरू होती है।",+ "discount": "छूट",+ "preview": "{{period}} प्रति अवधि, लगभग {{monthly}} प्रति माह।"+ },+ "invoices": {+ "title": "इनवॉइस",+ "description": "हर अवधि में एक, तय दिन पर बनता है। हाथ से बनाया इनवॉइस भी जोड़ा जा सकता है।",+ "empty": "इस समझौते के तहत अभी कोई इनवॉइस नहीं है।",+ "emptyNext": "अभी कोई इनवॉइस नहीं है। पहला {{date}} को बनेगा।"+ }}},"collections": {diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 15798eba..b5740245 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -292,7 +292,40 @@"payable_not_shareable": "Una fattura ricevuta non può essere condivisa.","discount_exceeds_total": "Lo sconto è maggiore dell'importo fatturato.","no_document_filed": "Questo documento è stato emesso altrove. Allega il file ricevuto.",- "already_imported": "Questo documento è già stato importato."+ "already_imported": "Questo documento è già stato importato.",+ "term_lines_required": "Una condizione ha bisogno di almeno una riga.",+ "term_empty": "Una condizione deve fatturare qualcosa.",+ "term_in_use": "È già stata emessa una fattura con questa condizione. Aggiungi una nuova condizione da una data successiva.",+ "term_before_start": "Una condizione non può iniziare prima dell'accordo.",+ "term_date_taken": "Un'altra condizione inizia già in quella data.",+ "last_term": "Un accordo ha bisogno di almeno una condizione.",+ "term_not_found": "Condizione non trovata.",+ "schedule_ended": "Questo accordo è concluso e non può più cambiare.",+ "schedule_locked": "Frequenza, data di inizio e valuta sono fisse una volta che esiste una fattura in questo accordo.",+ "schedule_has_invoices": "Sono state emesse fatture con questo accordo. Concludilo invece di eliminarlo.",+ "schedule_not_active": "Solo un accordo attivo emette fatture.",+ "invalid_frequency": "Frequenza sconosciuta.",+ "invalid_end_type": "Condizione di fine sconosciuta.",+ "invalid_end_reason": "Motivo di fine sconosciuto.",+ "end_date_required": "Indica in quale data finisce l'accordo.",+ "end_count_required": "Indica dopo quante fatture finisce l'accordo.",+ "end_before_start": "L'accordo non può finire prima di iniziare.",+ "name_required": "Dai un nome all'accordo.",+ "not_issued": "Solo una fattura emessa può avviare un accordo.",+ "already_linked": "Questa fattura appartiene già a un accordo.",+ "invoice_void": "Una fattura annullata non può coprire un periodo.",+ "payee_mismatch": "La fattura e l'accordo indicano clienti diversi.",+ "not_a_period": "Quella data non è l'inizio di un periodo di questo accordo.",+ "beyond_end": "Quel periodo è successivo alla fine dell'accordo.",+ "period_taken": "Un'altra fattura copre già quel periodo.",+ "start_after_invoice": "L'accordo non può iniziare dopo questa fattura.",+ "invoice_not_found": "Fattura non trovata.",+ "no_term": "Nessuna condizione è in vigore per questo periodo.",+ "no_author": "Questo accordo non ha un autore a nome del quale emettere fatture.",+ "negative_discount": "Uno sconto non può essere negativo.",+ "first_term": "Il prezzo in vigore dall'inizio non può essere spostato né rimosso. Modificalo o aggiungi un nuovo prezzo da una data successiva.",+ "not_receivable": "Solo una fattura emessa da te può appartenere a un accordo.",+ "period_already_issued": "Questo periodo è appena stato emesso. Aggiorna per vederlo."},"comingNext": "Fattura i tuoi clienti e tieni traccia di cosa è stato pagato e cosa è ancora aperto. È la prossima cosa in costruzione.","document": {@@ -381,6 +414,152 @@"wouldApply": "applicherebbe {{amount}}","alsoCovers_one": "copre anche altra {{count}} fattura","alsoCovers_other": "copre anche altre {{count}} fatture"+ },+ "schedules": {+ "title": "Ricorrenti",+ "new": "Nuova fattura ricorrente",+ "newDescription": "Un accordo con un cliente per fatturargli ogni periodo. Le fatture vengono scritte per te, nel giorno previsto.",+ "backToList": "Torna alle ricorrenti",+ "empty": "Nessuna fattura ricorrente ancora. Creane una, oppure apri una fattura e scegli \"Ripeti questa fattura\".",+ "emptyFiltered": "Niente qui con questo stato.",+ "created": "Fattura ricorrente creata",+ "saved": "Modifiche salvate",+ "deleted": "Fattura ricorrente eliminata",+ "paused": "In pausa. Non verrà fatturato nulla finché non la riprendi.",+ "resumed": "Ripresa dal prossimo periodo.",+ "ended": "Accordo concluso",+ "generated_one": "Fattura emessa",+ "generated_other": "{{count}} fatture emesse",+ "termSaved": "Prezzo salvato",+ "termRemoved": "Cambio di prezzo rimosso",+ "linked": "Fattura collegata all'accordo",+ "unlinked": "Fattura scollegata dall'accordo",+ "recurringInvoice": "Fattura ricorrente",+ "monthlyPreview": "Circa {{amount}} al mese.",+ "since": "dal {{date}}",+ "untilDate": "fino al {{date}}",+ "untilCount_one": "{{count}} fattura in totale",+ "untilCount_other": "{{count}} fatture in totale",+ "endedOn": "concluso il {{date}} ({{reason}})",+ "pausedByFailures": "In pausa dopo errori ripetuti. Controlla le condizioni e riprendi.",+ "editTitle": "Modifica fattura ricorrente",+ "editDescription": "Il nome, il cliente, le condizioni e quando finisce.",+ "editLockedDescription": "Sono già state emesse fatture con questo accordo, quindi frequenza e data di inizio sono fisse. Tutto il resto può cambiare.",+ "endTitle": "Concludere questo accordo?",+ "endDescription": "Non verranno emesse altre fatture. Quelle già emesse restano esattamente come sono. Indica il motivo: è l'unica cosa che le fatture non potranno dirti più tardi.",+ "linkTitle": "Collega una fattura esistente",+ "linkDescription": "Una fattura che hai scritto a mano per uno dei periodi di questo accordo. Mantiene numero, data e pagamenti; impara soltanto a quale periodo appartiene.",+ "noCandidates": "Nessuna fattura non collegata per questo cliente in questa valuta.",+ "makeRecurringDescription": "Questa fattura diventa un periodo di un nuovo accordo, e le successive vengono scritte per te. La sua data, {{date}}, è il primo periodo, a meno che tu non indichi che l'accordo è iniziato prima.",+ "filter": {+ "all": "Tutte",+ "active": "Attive",+ "paused": "In pausa",+ "ended": "Concluse"+ },+ "state": {+ "active": "Attivo",+ "past_due": "Scaduto",+ "paused": "In pausa",+ "paused_failures": "Richiede attenzione",+ "ended": "Concluso"+ },+ "frequency": {+ "weekly": "Settimanale",+ "biweekly": "Ogni 2 settimane",+ "monthly": "Mensile",+ "quarterly": "Trimestrale",+ "semiannual": "Ogni 6 mesi",+ "yearly": "Annuale"+ },+ "endType": {+ "never": "Mai",+ "on_date": "In una data",+ "after_count": "Dopo un numero di fatture"+ },+ "endReason": {+ "canceled_by_client": "Annullato dal cliente",+ "canceled_by_us": "Annullato da noi",+ "completed": "Giunto al termine",+ "unpaid": "Non pagato",+ "other": "Altro"+ },+ "summary": {+ "monthly": "Ricorrente mensile",+ "yearly": "All'anno",+ "lost": "Perso negli ultimi 30 giorni",+ "endedRecently_one": "{{count}} accordo concluso",+ "endedRecently_other": "{{count}} accordi conclusi",+ "pastDue": "Scaduto",+ "pastDueHint": "accordi con una fattura in ritardo",+ "activeCount_one": "{{count}} accordo attivo",+ "activeCount_other": "{{count}} accordi attivi",+ "none": "Niente di ricorrente ancora"+ },+ "column": {+ "name": "Accordo",+ "cadence": "Cadenza",+ "monthly": "Al mese",+ "next": "Prossima fattura",+ "invoices": "Fatture",+ "status": "Stato",+ "period": "Periodo"+ },+ "figure": {+ "invoiced": "Fatturato",+ "paid": "Incassato",+ "pastDue_one": "{{count}} fattura scaduta",+ "pastDue_other": "{{count}} fatture scadute"+ },+ "field": {+ "name": "Nome",+ "namePlaceholder": "Piano Pro, canone mensile, hosting",+ "frequency": "Frequenza",+ "startDate": "Inizia il",+ "startDateHint": "Una data precedente alla fattura lascia spazio per collegare quelle precedenti.",+ "paymentTerms": "Termini di pagamento (giorni)",+ "currency": "Valuta",+ "ends": "Finisce",+ "endDate": "Data di fine",+ "endCount": "Numero di fatture",+ "endReason": "Motivo",+ "endedAt": "Concluso il",+ "invoice": "Fattura",+ "invoicePlaceholder": "Scegli una fattura",+ "period": "Periodo",+ "periodPlaceholder": "Scegli un periodo"+ },+ "action": {+ "changePrice": "Cambia prezzo",+ "generate": "Emetti la prossima ora",+ "pause": "Metti in pausa",+ "resume": "Riprendi",+ "end": "Concludi accordo",+ "linkInvoice": "Collega fattura",+ "link": "Collega",+ "makeRecurring": "Ripeti questa fattura",+ "unlink": "Rimuovi dall'accordo"+ },+ "terms": {+ "title": "Prezzo",+ "description": "Quanto l'accordo fattura per periodo, e da quando. Un cambio vale dal primo periodo che inizia nella sua data o dopo; niente viene calcolato pro rata.",+ "from": "Dal {{date}}",+ "current": "In vigore",+ "upcoming": "In arrivo",+ "perMonth": "{{amount}} al mese",+ "editTitle": "Modifica cambio di prezzo",+ "changeDescription": "Registra un nuovo prezzo a partire da una data. I periodi già fatturati mantengono quanto è stato fatturato; il cambio parte dal primo periodo in quella data o dopo, per intero.",+ "effectiveFrom": "Dal",+ "nextPeriodHint": "Il prossimo periodo inizia il {{date}}.",+ "discount": "Sconto",+ "preview": "{{period}} per periodo, circa {{monthly}} al mese."+ },+ "invoices": {+ "title": "Fatture",+ "description": "Una per periodo, scritta nel giorno previsto. Anche una fattura scritta a mano può essere collegata.",+ "empty": "Nessuna fattura in questo accordo ancora.",+ "emptyNext": "Nessuna fattura ancora. La prima verrà scritta il {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex f929202a..8511dd48 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -292,7 +292,40 @@"payable_not_shareable": "受領した請求書は共有できません。","discount_exceeds_total": "割引額が請求金額を超えています。","no_document_filed": "この書類は他で発行されたものです。受領したファイルを添付してください。",- "already_imported": "この書類はすでにインポート済みです。"+ "already_imported": "この書類はすでにインポート済みです。",+ "term_lines_required": "条件には少なくとも1つの明細が必要です。",+ "term_empty": "条件には請求する内容が必要です。",+ "term_in_use": "この条件で請求書がすでに発行されています。それより後の日付から新しい条件を追加してください。",+ "term_before_start": "条件を契約の開始前に始めることはできません。",+ "term_date_taken": "その日付から始まる別の条件がすでにあります。",+ "last_term": "契約には少なくとも1つの条件が必要です。",+ "term_not_found": "条件が見つかりません。",+ "schedule_ended": "この契約は終了しているため、変更できません。",+ "schedule_locked": "この契約で請求書が存在する場合、頻度、開始日、通貨は変更できません。",+ "schedule_has_invoices": "この契約で請求書が発行されています。削除ではなく終了してください。",+ "schedule_not_active": "請求書を発行できるのは有効な契約のみです。",+ "invalid_frequency": "不明な頻度です。",+ "invalid_end_type": "不明な終了条件です。",+ "invalid_end_reason": "不明な終了理由です。",+ "end_date_required": "契約が終了する日付を指定してください。",+ "end_count_required": "契約が何件の請求書で終了するかを指定してください。",+ "end_before_start": "契約を開始前に終了することはできません。",+ "name_required": "契約に名前を付けてください。",+ "not_issued": "契約を開始できるのは発行済みの請求書のみです。",+ "already_linked": "この請求書はすでに契約に属しています。",+ "invoice_void": "無効化された請求書を期間に割り当てることはできません。",+ "payee_mismatch": "請求書と契約のクライアントが異なります。",+ "not_a_period": "その日付はこの契約の期間の開始日ではありません。",+ "beyond_end": "その期間は契約の終了後です。",+ "period_taken": "その期間にはすでに別の請求書が割り当てられています。",+ "start_after_invoice": "契約をこの請求書より後に開始することはできません。",+ "invoice_not_found": "請求書が見つかりません。",+ "no_term": "この期間に有効な条件がありません。",+ "no_author": "この契約には請求書を発行する作成者がいません。",+ "negative_discount": "割引を負の値にすることはできません。",+ "first_term": "開始時から有効な料金は移動も削除もできません。変更するか、より後の日付から新しい料金を追加してください。",+ "not_receivable": "契約に含められるのは、あなたが発行した請求書のみです。",+ "period_already_issued": "この期間はたった今発行されました。更新して確認してください。"},"comingNext": "クライアントに請求し、支払い済みのものと未払いのものを管理します。現在開発中の次の機能です。","document": {@@ -381,6 +414,152 @@"wouldApply": "{{amount}}を充当します","alsoCovers_one": "他に{{count}}件の請求書もカバーします","alsoCovers_other": "他に{{count}}件の請求書もカバーします"+ },+ "schedules": {+ "title": "定期請求",+ "new": "新しい定期請求書",+ "newDescription": "クライアントに期間ごとに請求する契約です。請求書は当日に自動で作成されます。",+ "backToList": "定期請求に戻る",+ "empty": "定期請求書はまだありません。新しく作成するか、請求書を開いて「この請求書を繰り返す」を選んでください。",+ "emptyFiltered": "このステータスのものはありません。",+ "created": "定期請求書を作成しました",+ "saved": "変更を保存しました",+ "deleted": "定期請求書を削除しました",+ "paused": "一時停止しました。再開するまで請求は行われません。",+ "resumed": "次の期間から再開します。",+ "ended": "契約を終了しました",+ "generated_one": "請求書を発行しました",+ "generated_other": "{{count}}件の請求書を発行しました",+ "termSaved": "価格を保存しました",+ "termRemoved": "価格変更を削除しました",+ "linked": "請求書を契約に紐付けました",+ "unlinked": "請求書の契約への紐付けを解除しました",+ "recurringInvoice": "定期請求書",+ "monthlyPreview": "月あたり約{{amount}}。",+ "since": "{{date}}から",+ "untilDate": "{{date}}まで",+ "untilCount_one": "合計{{count}}件の請求書",+ "untilCount_other": "合計{{count}}件の請求書",+ "endedOn": "{{date}}に終了({{reason}})",+ "pausedByFailures": "失敗が続いたため一時停止しました。条件を確認して再開してください。",+ "editTitle": "定期請求書を編集",+ "editDescription": "名前、クライアント、条件、終了時期。",+ "editLockedDescription": "この契約で請求書が発行済みのため、頻度と開始日は変更できません。それ以外は変更できます。",+ "endTitle": "この契約を終了しますか?",+ "endDescription": "今後の請求書は発行されません。発行済みの請求書はそのまま残ります。理由を記録してください。請求書だけでは後から分からない唯一の情報です。",+ "linkTitle": "既存の請求書を紐付ける",+ "linkDescription": "この契約のいずれかの期間について手動で作成した請求書です。番号、日付、入金はそのままで、どの期間のものかが記録されるだけです。",+ "noCandidates": "このクライアントのこの通貨で、未紐付けの請求書はありません。",+ "makeRecurringDescription": "この請求書は新しい契約の1期間分となり、以降の請求書は自動で作成されます。契約がそれより前に始まっていたと指定しない限り、この請求書の日付{{date}}が最初の期間になります。",+ "filter": {+ "all": "すべて",+ "active": "有効",+ "paused": "一時停止中",+ "ended": "終了"+ },+ "state": {+ "active": "有効",+ "past_due": "期限超過",+ "paused": "一時停止中",+ "paused_failures": "要確認",+ "ended": "終了"+ },+ "frequency": {+ "weekly": "毎週",+ "biweekly": "2週間ごと",+ "monthly": "毎月",+ "quarterly": "四半期ごと",+ "semiannual": "6か月ごと",+ "yearly": "毎年"+ },+ "endType": {+ "never": "終了しない",+ "on_date": "指定日に",+ "after_count": "指定件数の発行後に"+ },+ "endReason": {+ "canceled_by_client": "クライアントによる解約",+ "canceled_by_us": "こちらからの解約",+ "completed": "満了",+ "unpaid": "未払い",+ "other": "その他"+ },+ "summary": {+ "monthly": "月次定期収入",+ "yearly": "年あたり",+ "lost": "過去30日間の喪失分",+ "endedRecently_one": "{{count}}件の契約が終了",+ "endedRecently_other": "{{count}}件の契約が終了",+ "pastDue": "期限超過",+ "pastDueHint": "期限超過の請求書がある契約",+ "activeCount_one": "{{count}}件の有効な契約",+ "activeCount_other": "{{count}}件の有効な契約",+ "none": "定期請求はまだありません"+ },+ "column": {+ "name": "契約",+ "cadence": "周期",+ "monthly": "月あたり",+ "next": "次回の請求書",+ "invoices": "請求書",+ "status": "ステータス",+ "period": "期間"+ },+ "figure": {+ "invoiced": "請求済み",+ "paid": "入金済み",+ "pastDue_one": "{{count}}件の請求書が期限超過",+ "pastDue_other": "{{count}}件の請求書が期限超過"+ },+ "field": {+ "name": "名前",+ "namePlaceholder": "Proプラン、月額顧問料、ホスティング",+ "frequency": "頻度",+ "startDate": "開始日",+ "startDateHint": "請求書より前の日付にすると、それ以前の請求書も紐付けられます。",+ "paymentTerms": "支払期限(日数)",+ "currency": "通貨",+ "ends": "終了",+ "endDate": "終了日",+ "endCount": "請求書の件数",+ "endReason": "理由",+ "endedAt": "終了日",+ "invoice": "請求書",+ "invoicePlaceholder": "請求書を選択",+ "period": "期間",+ "periodPlaceholder": "期間を選択"+ },+ "action": {+ "changePrice": "価格を変更",+ "generate": "次回分を今すぐ発行",+ "pause": "一時停止",+ "resume": "再開",+ "end": "契約を終了",+ "linkInvoice": "請求書を紐付ける",+ "link": "紐付ける",+ "makeRecurring": "この請求書を繰り返す",+ "unlink": "契約から外す"+ },+ "terms": {+ "title": "価格",+ "description": "この契約が期間ごとに請求する金額と、その適用開始日です。変更は指定日以降に始まる最初の期間から適用され、日割り計算は行われません。",+ "from": "{{date}}から",+ "current": "現在",+ "upcoming": "予定",+ "perMonth": "月あたり{{amount}}",+ "editTitle": "価格変更を編集",+ "changeDescription": "指定日以降の新しい価格を記録します。請求済みの期間はそのままの金額で、変更は指定日以降に始まる最初の期間から全額適用されます。",+ "effectiveFrom": "適用開始",+ "nextPeriodHint": "次の期間は{{date}}に始まります。",+ "discount": "割引",+ "preview": "期間あたり{{period}}、月あたり約{{monthly}}。"+ },+ "invoices": {+ "title": "請求書",+ "description": "期間ごとに1件、当日に作成されます。手動で作成した請求書も紐付けできます。",+ "empty": "この契約の請求書はまだありません。",+ "emptyNext": "請求書はまだありません。最初の請求書は{{date}}に作成されます。"+ }}},"collections": {diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 6d346935..2756790e 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -292,7 +292,40 @@"payable_not_shareable": "Een ontvangen factuur kan niet worden gedeeld.","discount_exceeds_total": "De korting is groter dan het gefactureerde bedrag.","no_document_filed": "Dit document is elders uitgegeven. Voeg het ontvangen bestand toe.",- "already_imported": "Dit document is al geïmporteerd."+ "already_imported": "Dit document is al geïmporteerd.",+ "term_lines_required": "Een voorwaarde heeft minstens één regel nodig.",+ "term_empty": "Een voorwaarde moet iets factureren.",+ "term_in_use": "Er is al een factuur uitgegeven onder deze voorwaarde. Voeg een nieuwe voorwaarde toe vanaf een latere datum.",+ "term_before_start": "Een voorwaarde kan niet beginnen vóór de afspraak.",+ "term_date_taken": "Een andere voorwaarde begint al op die datum.",+ "last_term": "Een afspraak heeft minstens één voorwaarde nodig.",+ "term_not_found": "Voorwaarde niet gevonden.",+ "schedule_ended": "Deze afspraak is beëindigd en kan niet meer veranderen.",+ "schedule_locked": "De frequentie, startdatum en valuta liggen vast zodra er een factuur onder deze afspraak bestaat.",+ "schedule_has_invoices": "Er zijn facturen uitgegeven onder deze afspraak. Beëindig hem in plaats van hem te verwijderen.",+ "schedule_not_active": "Alleen een actieve afspraak geeft facturen uit.",+ "invalid_frequency": "Onbekende frequentie.",+ "invalid_end_type": "Onbekende eindvoorwaarde.",+ "invalid_end_reason": "Onbekende eindreden.",+ "end_date_required": "Geef aan op welke datum de afspraak eindigt.",+ "end_count_required": "Geef aan na hoeveel facturen de afspraak eindigt.",+ "end_before_start": "De afspraak kan niet eindigen voordat hij begint.",+ "name_required": "Geef de afspraak een naam.",+ "not_issued": "Alleen een uitgegeven factuur kan een afspraak starten.",+ "already_linked": "Deze factuur hoort al bij een afspraak.",+ "invoice_void": "Een geannuleerde factuur kan geen periode dekken.",+ "payee_mismatch": "De factuur en de afspraak noemen verschillende klanten.",+ "not_a_period": "Die datum is niet het begin van een periode van deze afspraak.",+ "beyond_end": "Die periode ligt na het einde van de afspraak.",+ "period_taken": "Een andere factuur dekt die periode al.",+ "start_after_invoice": "De afspraak kan niet beginnen na deze factuur.",+ "invoice_not_found": "Factuur niet gevonden.",+ "no_term": "Er geldt geen voorwaarde voor deze periode.",+ "no_author": "Deze afspraak heeft geen auteur om facturen namens uit te geven.",+ "negative_discount": "Een korting kan niet negatief zijn.",+ "first_term": "De prijs die vanaf het begin geldt, kan niet worden verplaatst of verwijderd. Wijzig hem, of voeg een nieuwe prijs toe vanaf een latere datum.",+ "not_receivable": "Alleen een factuur die u hebt uitgegeven kan bij een afspraak horen.",+ "period_already_issued": "Deze periode is zojuist uitgegeven. Vernieuw om hem te zien."},"comingNext": "Factureer uw klanten en houd bij wat er is betaald en wat er nog open staat. Dit is het volgende dat gebouwd wordt.","document": {@@ -381,6 +414,152 @@"wouldApply": "zou {{amount}} toepassen","alsoCovers_one": "dekt ook {{count}} andere factuur","alsoCovers_other": "dekt ook {{count}} andere facturen"+ },+ "schedules": {+ "title": "Terugkerend",+ "new": "Nieuwe terugkerende factuur",+ "newDescription": "Een afspraak met een klant om elke periode te factureren. De facturen worden op de dag zelf voor je opgesteld.",+ "backToList": "Terug naar terugkerend",+ "empty": "Nog geen terugkerende facturen. Maak er een aan, of open een factuur en kies \"Deze factuur herhalen\".",+ "emptyFiltered": "Niets hier met deze status.",+ "created": "Terugkerende factuur aangemaakt",+ "saved": "Wijzigingen opgeslagen",+ "deleted": "Terugkerende factuur verwijderd",+ "paused": "Gepauzeerd. Er wordt niets gefactureerd tot je hem hervat.",+ "resumed": "Hervat vanaf de volgende periode.",+ "ended": "Afspraak beëindigd",+ "generated_one": "Factuur uitgegeven",+ "generated_other": "{{count}} facturen uitgegeven",+ "termSaved": "Prijs opgeslagen",+ "termRemoved": "Prijswijziging verwijderd",+ "linked": "Factuur gekoppeld aan de afspraak",+ "unlinked": "Factuur ontkoppeld van de afspraak",+ "recurringInvoice": "Terugkerende factuur",+ "monthlyPreview": "Ongeveer {{amount}} per maand.",+ "since": "sinds {{date}}",+ "untilDate": "tot {{date}}",+ "untilCount_one": "{{count}} factuur in totaal",+ "untilCount_other": "{{count}} facturen in totaal",+ "endedOn": "beëindigd op {{date}} ({{reason}})",+ "pausedByFailures": "Gepauzeerd na herhaalde fouten. Controleer de voorwaarden en hervat.",+ "editTitle": "Terugkerende factuur bewerken",+ "editDescription": "De naam, de klant, de voorwaarden en wanneer hij eindigt.",+ "editLockedDescription": "Er zijn al facturen uitgegeven onder deze afspraak, dus de frequentie en de startdatum liggen vast. Al het andere kan veranderen.",+ "endTitle": "Deze afspraak beëindigen?",+ "endDescription": "Er worden geen facturen meer uitgegeven. De al uitgegeven facturen blijven precies zoals ze zijn. Geef de reden op: dat is het enige wat de facturen je later niet kunnen vertellen.",+ "linkTitle": "Bestaande factuur koppelen",+ "linkDescription": "Een factuur die je met de hand hebt opgesteld voor een van de periodes van deze afspraak. Hij houdt zijn nummer, datum en betalingen; hij leert alleen bij welke periode hij hoort.",+ "noCandidates": "Geen ongekoppelde factuur voor deze klant in deze valuta.",+ "makeRecurringDescription": "Deze factuur wordt één periode van een nieuwe afspraak, en de volgende worden voor je opgesteld. Zijn eigen datum, {{date}}, is de eerste periode, tenzij je aangeeft dat de afspraak eerder is begonnen.",+ "filter": {+ "all": "Alle",+ "active": "Actief",+ "paused": "Gepauzeerd",+ "ended": "Beëindigd"+ },+ "state": {+ "active": "Actief",+ "past_due": "Achterstallig",+ "paused": "Gepauzeerd",+ "paused_failures": "Aandacht nodig",+ "ended": "Beëindigd"+ },+ "frequency": {+ "weekly": "Wekelijks",+ "biweekly": "Elke 2 weken",+ "monthly": "Maandelijks",+ "quarterly": "Per kwartaal",+ "semiannual": "Elke 6 maanden",+ "yearly": "Jaarlijks"+ },+ "endType": {+ "never": "Nooit",+ "on_date": "Op een datum",+ "after_count": "Na een aantal facturen"+ },+ "endReason": {+ "canceled_by_client": "Opgezegd door de klant",+ "canceled_by_us": "Opgezegd door ons",+ "completed": "Afgerond",+ "unpaid": "Onbetaald",+ "other": "Anders"+ },+ "summary": {+ "monthly": "Maandelijks terugkerend",+ "yearly": "Per jaar",+ "lost": "Verloren in de laatste 30 dagen",+ "endedRecently_one": "{{count}} afspraak beëindigd",+ "endedRecently_other": "{{count}} afspraken beëindigd",+ "pastDue": "Achterstallig",+ "pastDueHint": "afspraken met een te late factuur",+ "activeCount_one": "{{count}} actieve afspraak",+ "activeCount_other": "{{count}} actieve afspraken",+ "none": "Nog niets terugkerends"+ },+ "column": {+ "name": "Afspraak",+ "cadence": "Ritme",+ "monthly": "Per maand",+ "next": "Volgende factuur",+ "invoices": "Facturen",+ "status": "Status",+ "period": "Periode"+ },+ "figure": {+ "invoiced": "Gefactureerd",+ "paid": "Ontvangen",+ "pastDue_one": "{{count}} factuur achterstallig",+ "pastDue_other": "{{count}} facturen achterstallig"+ },+ "field": {+ "name": "Naam",+ "namePlaceholder": "Pro-abonnement, maandelijkse retainer, hosting",+ "frequency": "Frequentie",+ "startDate": "Begint op",+ "startDateHint": "Een datum vóór de factuur maakt ruimte om de eerdere te koppelen.",+ "paymentTerms": "Betaaltermijn (dagen)",+ "currency": "Valuta",+ "ends": "Eindigt",+ "endDate": "Einddatum",+ "endCount": "Aantal facturen",+ "endReason": "Reden",+ "endedAt": "Beëindigd op",+ "invoice": "Factuur",+ "invoicePlaceholder": "Kies een factuur",+ "period": "Periode",+ "periodPlaceholder": "Kies een periode"+ },+ "action": {+ "changePrice": "Prijs wijzigen",+ "generate": "Volgende nu uitgeven",+ "pause": "Pauzeren",+ "resume": "Hervatten",+ "end": "Afspraak beëindigen",+ "linkInvoice": "Factuur koppelen",+ "link": "Koppelen",+ "makeRecurring": "Deze factuur herhalen",+ "unlink": "Uit de afspraak verwijderen"+ },+ "terms": {+ "title": "Prijs",+ "description": "Wat de afspraak per periode factureert, en vanaf wanneer. Een wijziging geldt vanaf de eerste periode die op of na de datum begint; er wordt niets naar rato berekend.",+ "from": "Vanaf {{date}}",+ "current": "Huidig",+ "upcoming": "Aankomend",+ "perMonth": "{{amount}} per maand",+ "editTitle": "Prijswijziging bewerken",+ "changeDescription": "Leg een nieuwe prijs vast vanaf een datum. Al gefactureerde periodes houden wat ze gefactureerd kregen; de wijziging begint met de eerste periode op of na de datum, volledig.",+ "effectiveFrom": "Vanaf",+ "nextPeriodHint": "De volgende periode begint op {{date}}.",+ "discount": "Korting",+ "preview": "{{period}} per periode, ongeveer {{monthly}} per maand."+ },+ "invoices": {+ "title": "Facturen",+ "description": "Eén per periode, op de dag zelf opgesteld. Een met de hand opgestelde factuur kan ook worden gekoppeld.",+ "empty": "Nog geen factuur onder deze afspraak.",+ "emptyNext": "Nog geen factuur. De eerste wordt opgesteld op {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex b98b128f..3ca1ae50 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -292,7 +292,40 @@"payable_not_shareable": "Otrzymanej faktury nie można udostępnić.","discount_exceeds_total": "Rabat jest większy niż kwota do zapłaty.","no_document_filed": "Ten dokument został wystawiony gdzie indziej. Dołącz otrzymany plik.",- "already_imported": "Ten dokument został już zaimportowany."+ "already_imported": "Ten dokument został już zaimportowany.",+ "term_lines_required": "Warunek wymaga co najmniej jednej pozycji.",+ "term_empty": "Warunek musi coś rozliczać.",+ "term_in_use": "Na podstawie tego warunku wystawiono już fakturę. Dodaj nowy warunek od późniejszej daty.",+ "term_before_start": "Warunek nie może zaczynać się przed umową.",+ "term_date_taken": "Inny warunek zaczyna się już w tym dniu.",+ "last_term": "Umowa wymaga co najmniej jednego warunku.",+ "term_not_found": "Nie znaleziono warunku.",+ "schedule_ended": "Ta umowa została zakończona i nie można jej już zmieniać.",+ "schedule_locked": "Częstotliwość, data rozpoczęcia i waluta są stałe, gdy w ramach tej umowy istnieje faktura.",+ "schedule_has_invoices": "W ramach tej umowy wystawiono faktury. Zakończ ją zamiast usuwać.",+ "schedule_not_active": "Tylko aktywna umowa wystawia faktury.",+ "invalid_frequency": "Nieznana częstotliwość.",+ "invalid_end_type": "Nieznany warunek zakończenia.",+ "invalid_end_reason": "Nieznany powód zakończenia.",+ "end_date_required": "Podaj, w którym dniu umowa się kończy.",+ "end_count_required": "Podaj, po ilu fakturach umowa się kończy.",+ "end_before_start": "Umowa nie może zakończyć się przed rozpoczęciem.",+ "name_required": "Nadaj umowie nazwę.",+ "not_issued": "Tylko wystawiona faktura może rozpocząć umowę.",+ "already_linked": "Ta faktura należy już do umowy.",+ "invoice_void": "Anulowana faktura nie może odpowiadać za okres.",+ "payee_mismatch": "Faktura i umowa wskazują różnych klientów.",+ "not_a_period": "Ta data nie jest początkiem okresu tej umowy.",+ "beyond_end": "Ten okres przypada po zakończeniu umowy.",+ "period_taken": "Inna faktura odpowiada już za ten okres.",+ "start_after_invoice": "Umowa nie może zaczynać się po tej fakturze.",+ "invoice_not_found": "Nie znaleziono faktury.",+ "no_term": "Dla tego okresu nie obowiązuje żaden warunek.",+ "no_author": "Ta umowa nie ma autora, w imieniu którego można wystawiać faktury.",+ "negative_discount": "Rabat nie może być ujemny.",+ "first_term": "Ceny obowiązującej od początku nie można przesunąć ani usunąć. Zmień ją lub dodaj nową cenę od późniejszej daty.",+ "not_receivable": "Do umowy może należeć tylko faktura wystawiona przez Ciebie.",+ "period_already_issued": "Ten okres został właśnie wystawiony. Odśwież, aby go zobaczyć."},"comingNext": "Wystawiaj faktury klientom i śledź, co zostało zapłacone, a co wciąż jest otwarte. To następna rzecz w budowie.","document": {@@ -385,6 +418,152 @@"alsoCovers_many": "i jeszcze {{count}} faktur","alsoCovers_other": "obejmuje też {{count}} innych faktur","wouldApply": "zastosowałaby {{amount}}"+ },+ "schedules": {+ "title": "Cykliczne",+ "new": "Nowa faktura cykliczna",+ "newDescription": "Umowa z klientem na rozliczanie co okres. Faktury są wystawiane za Ciebie, w wyznaczonym dniu.",+ "backToList": "Wróć do cyklicznych",+ "empty": "Nie ma jeszcze faktur cyklicznych. Utwórz jedną albo otwórz fakturę i wybierz \"Powtarzaj tę fakturę\".",+ "emptyFiltered": "Nic tu nie ma z tym statusem.",+ "created": "Faktura cykliczna utworzona",+ "saved": "Zmiany zapisane",+ "deleted": "Faktura cykliczna usunięta",+ "paused": "Wstrzymano. Nic nie zostanie rozliczone, dopóki jej nie wznowisz.",+ "resumed": "Wznowiono od następnego okresu.",+ "ended": "Umowa zakończona",+ "generated_one": "Faktura wystawiona",+ "generated_other": "Wystawiono faktur: {{count}}",+ "termSaved": "Cena zapisana",+ "termRemoved": "Zmiana ceny usunięta",+ "linked": "Faktura powiązana z umową",+ "unlinked": "Faktura odłączona od umowy",+ "recurringInvoice": "Faktura cykliczna",+ "monthlyPreview": "Około {{amount}} miesięcznie.",+ "since": "od {{date}}",+ "untilDate": "do {{date}}",+ "untilCount_one": "{{count}} faktura łącznie",+ "untilCount_other": "Łącznie faktur: {{count}}",+ "endedOn": "zakończona {{date}} ({{reason}})",+ "pausedByFailures": "Wstrzymano po powtarzających się błędach. Sprawdź warunki i wznów.",+ "editTitle": "Edytuj fakturę cykliczną",+ "editDescription": "Nazwa, klient, warunki i kiedy się kończy.",+ "editLockedDescription": "W ramach tej umowy wystawiono już faktury, więc częstotliwość i data rozpoczęcia są stałe. Wszystko inne można zmienić.",+ "endTitle": "Zakończyć tę umowę?",+ "endDescription": "Nie będą wystawiane kolejne faktury. Te już wystawione zostają dokładnie takie, jakie są. Podaj powód: to jedyna rzecz, której faktury nie powiedzą Ci później.",+ "linkTitle": "Powiąż istniejącą fakturę",+ "linkDescription": "Faktura, którą wystawiono ręcznie za jeden z okresów tej umowy. Zachowuje swój numer, datę i płatności; dowiaduje się tylko, którego okresu dotyczy.",+ "noCandidates": "Brak niepowiązanej faktury dla tego klienta w tej walucie.",+ "makeRecurringDescription": "Ta faktura staje się jednym okresem nowej umowy, a kolejne są wystawiane za Ciebie. Jej data, {{date}}, jest pierwszym okresem, chyba że wskażesz, że umowa zaczęła się wcześniej.",+ "filter": {+ "all": "Wszystkie",+ "active": "Aktywne",+ "paused": "Wstrzymane",+ "ended": "Zakończone"+ },+ "state": {+ "active": "Aktywna",+ "past_due": "Po terminie",+ "paused": "Wstrzymana",+ "paused_failures": "Wymaga uwagi",+ "ended": "Zakończona"+ },+ "frequency": {+ "weekly": "Co tydzień",+ "biweekly": "Co 2 tygodnie",+ "monthly": "Co miesiąc",+ "quarterly": "Co kwartał",+ "semiannual": "Co 6 miesięcy",+ "yearly": "Co rok"+ },+ "endType": {+ "never": "Nigdy",+ "on_date": "W dniu",+ "after_count": "Po określonej liczbie faktur"+ },+ "endReason": {+ "canceled_by_client": "Anulowana przez klienta",+ "canceled_by_us": "Anulowana przez nas",+ "completed": "Dobiegła końca",+ "unpaid": "Nieopłacona",+ "other": "Inny"+ },+ "summary": {+ "monthly": "Cykliczne miesięcznie",+ "yearly": "Rocznie",+ "lost": "Utracone w ostatnich 30 dniach",+ "endedRecently_one": "{{count}} umowa zakończona",+ "endedRecently_other": "Zakończonych umów: {{count}}",+ "pastDue": "Po terminie",+ "pastDueHint": "umowy z zaległą fakturą",+ "activeCount_one": "{{count}} aktywna umowa",+ "activeCount_other": "Aktywnych umów: {{count}}",+ "none": "Nic cyklicznego jeszcze nie ma"+ },+ "column": {+ "name": "Umowa",+ "cadence": "Cykl",+ "monthly": "Miesięcznie",+ "next": "Następna faktura",+ "invoices": "Faktury",+ "status": "Status",+ "period": "Okres"+ },+ "figure": {+ "invoiced": "Zafakturowano",+ "paid": "Otrzymano",+ "pastDue_one": "{{count}} faktura po terminie",+ "pastDue_other": "Faktur po terminie: {{count}}"+ },+ "field": {+ "name": "Nazwa",+ "namePlaceholder": "Plan Pro, miesięczny abonament, hosting",+ "frequency": "Częstotliwość",+ "startDate": "Zaczyna się",+ "startDateHint": "Data wcześniejsza niż faktura zostawia miejsce na powiązanie tych sprzed niej.",+ "paymentTerms": "Termin płatności (dni)",+ "currency": "Waluta",+ "ends": "Kończy się",+ "endDate": "Data zakończenia",+ "endCount": "Liczba faktur",+ "endReason": "Powód",+ "endedAt": "Zakończona",+ "invoice": "Faktura",+ "invoicePlaceholder": "Wybierz fakturę",+ "period": "Okres",+ "periodPlaceholder": "Wybierz okres"+ },+ "action": {+ "changePrice": "Zmień cenę",+ "generate": "Wystaw następną teraz",+ "pause": "Wstrzymaj",+ "resume": "Wznów",+ "end": "Zakończ umowę",+ "linkInvoice": "Powiąż fakturę",+ "link": "Powiąż",+ "makeRecurring": "Powtarzaj tę fakturę",+ "unlink": "Usuń z umowy"+ },+ "terms": {+ "title": "Cena",+ "description": "Ile umowa rozlicza za okres i od kiedy. Zmiana obowiązuje od pierwszego okresu zaczynającego się w jej dniu lub później; nic nie jest liczone proporcjonalnie.",+ "from": "Od {{date}}",+ "current": "Obowiązująca",+ "upcoming": "Nadchodząca",+ "perMonth": "{{amount}} miesięcznie",+ "editTitle": "Edytuj zmianę ceny",+ "changeDescription": "Zapisz nową cenę od wybranej daty. Okresy już zafakturowane zachowują to, co im naliczono; zmiana zaczyna się od pierwszego okresu w tym dniu lub później, w całości.",+ "effectiveFrom": "Od",+ "nextPeriodHint": "Następny okres zaczyna się {{date}}.",+ "discount": "Rabat",+ "preview": "{{period}} za okres, około {{monthly}} miesięcznie."+ },+ "invoices": {+ "title": "Faktury",+ "description": "Jedna na okres, wystawiana w wyznaczonym dniu. Fakturę wystawioną ręcznie też można powiązać.",+ "empty": "W tej umowie nie ma jeszcze faktury.",+ "emptyNext": "Nie ma jeszcze faktury. Pierwsza zostanie wystawiona {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex ea26f4d5..674e8188 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -292,7 +292,40 @@"payable_not_shareable": "Uma conta a pagar não pode ser compartilhada.","discount_exceeds_total": "O desconto é maior do que o valor cobrado.","no_document_filed": "Este documento foi emitido em outro lugar. Anexe o arquivo recebido.",- "already_imported": "Este documento já foi importado."+ "already_imported": "Este documento já foi importado.",+ "term_lines_required": "Um termo precisa de pelo menos um item.",+ "term_empty": "Um termo precisa cobrar algum valor.",+ "term_in_use": "Já existe uma cobrança emitida com este termo. Adicione um novo termo a partir de uma data posterior.",+ "term_before_start": "Um termo não pode começar antes do acordo.",+ "term_date_taken": "Já existe um termo começando nessa data.",+ "last_term": "Um acordo precisa de pelo menos um termo.",+ "term_not_found": "Termo não encontrado.",+ "schedule_ended": "Este acordo foi encerrado e não pode mais ser alterado.",+ "schedule_locked": "A frequência, a data de início e a moeda ficam fixas depois que existe uma cobrança neste acordo.",+ "schedule_has_invoices": "Já existem cobranças emitidas por este acordo. Encerre-o em vez de excluir.",+ "schedule_not_active": "Só um acordo ativo emite cobranças.",+ "invalid_frequency": "Frequência desconhecida.",+ "invalid_end_type": "Condição de término desconhecida.",+ "invalid_end_reason": "Motivo de término desconhecido.",+ "end_date_required": "Informe em que data o acordo termina.",+ "end_count_required": "Informe após quantas cobranças o acordo termina.",+ "end_before_start": "O acordo não pode terminar antes de começar.",+ "name_required": "Dê um nome ao acordo.",+ "not_issued": "Só uma cobrança emitida pode iniciar um acordo.",+ "already_linked": "Esta cobrança já pertence a um acordo.",+ "invoice_void": "Uma cobrança cancelada não pode representar um período.",+ "payee_mismatch": "A cobrança e o acordo apontam para clientes diferentes.",+ "not_a_period": "Essa data não é o início de um período deste acordo.",+ "beyond_end": "Esse período é posterior ao fim do acordo.",+ "period_taken": "Já existe uma cobrança para esse período.",+ "start_after_invoice": "O acordo não pode começar depois desta cobrança.",+ "invoice_not_found": "Cobrança não encontrada.",+ "no_term": "Nenhum termo está em vigor para este período.",+ "no_author": "Este acordo não tem um autor para emitir cobranças.",+ "negative_discount": "Um desconto não pode ser negativo.",+ "first_term": "O preço vigente desde o início não pode ser movido nem removido. Altere-o ou adicione um novo preço a partir de uma data posterior.",+ "not_receivable": "Só uma cobrança emitida por você pode pertencer a um acordo.",+ "period_already_issued": "Este período acabou de ser emitido. Atualize a página para vê-lo."},"comingNext": "Cobre seus clientes e acompanhe o que já foi pago e o que continua em aberto. É a próxima coisa sendo construída.","document": {@@ -381,6 +414,152 @@"wouldApply": "aplicaria {{amount}}","alsoCovers_one": "cobre também outra {{count}} cobrança","alsoCovers_other": "cobre também outras {{count}} cobranças"+ },+ "schedules": {+ "title": "Recorrentes",+ "new": "Nova cobrança recorrente",+ "newDescription": "Um acordo com um cliente para cobrar a cada período. As cobranças são geradas para você, no dia.",+ "backToList": "Voltar para recorrentes",+ "empty": "Nenhuma cobrança recorrente ainda. Crie uma, ou abra uma cobrança e escolha \"Repetir esta cobrança\".",+ "emptyFiltered": "Nada aqui com esse status.",+ "created": "Cobrança recorrente criada",+ "saved": "Alterações salvas",+ "deleted": "Cobrança recorrente excluída",+ "paused": "Pausada. Nada será cobrado até você retomar.",+ "resumed": "Retomada a partir do próximo período.",+ "ended": "Acordo encerrado",+ "generated_one": "Cobrança emitida",+ "generated_other": "{{count}} cobranças emitidas",+ "termSaved": "Preço salvo",+ "termRemoved": "Mudança de preço removida",+ "linked": "Cobrança vinculada ao acordo",+ "unlinked": "Cobrança desvinculada do acordo",+ "recurringInvoice": "Cobrança recorrente",+ "monthlyPreview": "Cerca de {{amount}} por mês.",+ "since": "desde {{date}}",+ "untilDate": "até {{date}}",+ "untilCount_one": "{{count}} cobrança no total",+ "untilCount_other": "{{count}} cobranças no total",+ "endedOn": "encerrado em {{date}} ({{reason}})",+ "pausedByFailures": "Pausada após falhas repetidas. Verifique os termos e retome.",+ "editTitle": "Editar cobrança recorrente",+ "editDescription": "O nome, o cliente, o prazo e quando termina.",+ "editLockedDescription": "Já existem cobranças emitidas por este acordo, então a frequência e a data de início ficam fixas. O restante pode mudar.",+ "endTitle": "Encerrar este acordo?",+ "endDescription": "Nenhuma cobrança nova será emitida. As já emitidas ficam exatamente como estão. Diga o motivo: é a única coisa que as cobranças não vão contar depois.",+ "linkTitle": "Vincular uma cobrança existente",+ "linkDescription": "Uma cobrança que você emitiu à mão para um dos períodos deste acordo. Ela mantém número, data e pagamentos; só passa a saber de qual período era.",+ "noCandidates": "Nenhuma cobrança sem vínculo para este cliente nesta moeda.",+ "makeRecurringDescription": "Esta cobrança vira um período de um novo acordo, e as próximas são geradas para você. A data dela, {{date}}, é o primeiro período, a menos que o acordo tenha começado antes.",+ "filter": {+ "all": "Todos",+ "active": "Ativos",+ "paused": "Pausados",+ "ended": "Encerrados"+ },+ "state": {+ "active": "Ativo",+ "past_due": "Em atraso",+ "paused": "Pausado",+ "paused_failures": "Precisa de atenção",+ "ended": "Encerrado"+ },+ "frequency": {+ "weekly": "Semanal",+ "biweekly": "A cada 2 semanas",+ "monthly": "Mensal",+ "quarterly": "Trimestral",+ "semiannual": "Semestral",+ "yearly": "Anual"+ },+ "endType": {+ "never": "Nunca",+ "on_date": "Em uma data",+ "after_count": "Após um número de cobranças"+ },+ "endReason": {+ "canceled_by_client": "Cancelado pelo cliente",+ "canceled_by_us": "Cancelado por nós",+ "completed": "Chegou ao fim",+ "unpaid": "Inadimplência",+ "other": "Outro"+ },+ "summary": {+ "monthly": "Receita recorrente mensal",+ "yearly": "Por ano",+ "lost": "Perdido nos últimos 30 dias",+ "endedRecently_one": "{{count}} acordo encerrado",+ "endedRecently_other": "{{count}} acordos encerrados",+ "pastDue": "Em atraso",+ "pastDueHint": "acordos com cobrança vencida",+ "activeCount_one": "{{count}} acordo ativo",+ "activeCount_other": "{{count}} acordos ativos",+ "none": "Nada recorrente ainda"+ },+ "column": {+ "name": "Acordo",+ "cadence": "Cadência",+ "monthly": "Por mês",+ "next": "Próxima cobrança",+ "invoices": "Cobranças",+ "status": "Status",+ "period": "Período"+ },+ "figure": {+ "invoiced": "Cobrado",+ "paid": "Recebido",+ "pastDue_one": "{{count}} cobrança em atraso",+ "pastDue_other": "{{count}} cobranças em atraso"+ },+ "field": {+ "name": "Nome",+ "namePlaceholder": "Plano Pro, retainer mensal, hospedagem",+ "frequency": "Frequência",+ "startDate": "Começa em",+ "startDateHint": "Uma data anterior à cobrança abre espaço para vincular as anteriores.",+ "paymentTerms": "Prazo de pagamento (dias)",+ "currency": "Moeda",+ "ends": "Termina",+ "endDate": "Data de término",+ "endCount": "Número de cobranças",+ "endReason": "Motivo",+ "endedAt": "Encerrado em",+ "invoice": "Cobrança",+ "invoicePlaceholder": "Escolha uma cobrança",+ "period": "Período",+ "periodPlaceholder": "Escolha um período"+ },+ "action": {+ "changePrice": "Alterar preço",+ "generate": "Emitir próxima agora",+ "pause": "Pausar",+ "resume": "Retomar",+ "end": "Encerrar acordo",+ "linkInvoice": "Vincular cobrança",+ "link": "Vincular",+ "makeRecurring": "Repetir esta cobrança",+ "unlink": "Remover do acordo"+ },+ "terms": {+ "title": "Preço",+ "description": "O que o acordo cobra por período, e a partir de quando. Uma mudança vale a partir do primeiro período que começa na data ou depois dela; nada é rateado.",+ "from": "A partir de {{date}}",+ "current": "Vigente",+ "upcoming": "Agendado",+ "perMonth": "{{amount}} por mês",+ "editTitle": "Editar mudança de preço",+ "changeDescription": "Registre um novo preço a partir de uma data. Períodos já cobrados mantêm o valor cobrado; a mudança começa no primeiro período a partir da data, por inteiro.",+ "effectiveFrom": "A partir de",+ "nextPeriodHint": "O próximo período começa em {{date}}.",+ "discount": "Desconto",+ "preview": "{{period}} por período, cerca de {{monthly}} por mês."+ },+ "invoices": {+ "title": "Cobranças",+ "description": "Uma por período, gerada no dia. Uma cobrança emitida à mão também pode ser vinculada.",+ "empty": "Nenhuma cobrança neste acordo ainda.",+ "emptyNext": "Nenhuma cobrança ainda. A primeira será gerada em {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 553a9049..eb82e8d3 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -292,7 +292,40 @@"payable_not_shareable": "Uma conta a pagar não pode ser compartilhada.","discount_exceeds_total": "O desconto é maior do que o valor cobrado.","no_document_filed": "Este documento foi emitido noutro lugar. Anexe o ficheiro recebido.",- "already_imported": "Este documento já foi importado."+ "already_imported": "Este documento já foi importado.",+ "term_lines_required": "Uma condição precisa de pelo menos uma linha.",+ "term_empty": "Uma condição tem de cobrar algo.",+ "term_in_use": "Já foi emitida uma cobrança com esta condição. Adicione uma nova condição a partir de uma data posterior.",+ "term_before_start": "Uma condição não pode começar antes do acordo.",+ "term_date_taken": "Outra condição já começa nessa data.",+ "last_term": "Um acordo precisa de pelo menos uma condição.",+ "term_not_found": "Condição não encontrada.",+ "schedule_ended": "Este acordo terminou e já não pode mudar.",+ "schedule_locked": "A frequência, a data de início e a moeda ficam fixas assim que existe uma cobrança neste acordo.",+ "schedule_has_invoices": "Foram emitidas cobranças ao abrigo deste acordo. Termine-o em vez de o eliminar.",+ "schedule_not_active": "Só um acordo ativo emite cobranças.",+ "invalid_frequency": "Frequência desconhecida.",+ "invalid_end_type": "Condição de fim desconhecida.",+ "invalid_end_reason": "Motivo de fim desconhecido.",+ "end_date_required": "Indique em que data o acordo termina.",+ "end_count_required": "Indique após quantas cobranças o acordo termina.",+ "end_before_start": "O acordo não pode terminar antes de começar.",+ "name_required": "Dê um nome ao acordo.",+ "not_issued": "Só uma cobrança emitida pode iniciar um acordo.",+ "already_linked": "Esta cobrança já pertence a um acordo.",+ "invoice_void": "Uma cobrança cancelada não pode representar um período.",+ "payee_mismatch": "A cobrança e o acordo indicam clientes diferentes.",+ "not_a_period": "Essa data não é o início de um período deste acordo.",+ "beyond_end": "Esse período é posterior ao fim do acordo.",+ "period_taken": "Já existe outra cobrança para esse período.",+ "start_after_invoice": "O acordo não pode começar depois desta cobrança.",+ "invoice_not_found": "Cobrança não encontrada.",+ "no_term": "Não há nenhuma condição em vigor para este período.",+ "no_author": "Este acordo não tem um autor em nome de quem emitir cobranças.",+ "negative_discount": "Um desconto não pode ser negativo.",+ "first_term": "O preço em vigor desde o início não pode ser movido nem removido. Altere-o ou adicione um novo preço a partir de uma data posterior.",+ "not_receivable": "Só uma cobrança emitida por si pode pertencer a um acordo.",+ "period_already_issued": "Este período acabou de ser emitido. Atualize a página para o ver."},"comingNext": "Cobra os teus clientes e acompanha o que já foi pago e o que continua em aberto. É a próxima coisa a ser construída.","document": {@@ -381,6 +414,152 @@"wouldApply": "aplicaria {{amount}}","alsoCovers_one": "cobre também outra {{count}} cobrança","alsoCovers_other": "cobre também outras {{count}} cobranças"+ },+ "schedules": {+ "title": "Recorrentes",+ "new": "Nova cobrança recorrente",+ "newDescription": "Um acordo com um cliente para cobrar a cada período. As cobranças são geradas por si, no dia.",+ "backToList": "Voltar às recorrentes",+ "empty": "Ainda não há cobranças recorrentes. Crie uma, ou abra uma cobrança e escolha \"Repetir esta cobrança\".",+ "emptyFiltered": "Nada aqui com este estado.",+ "created": "Cobrança recorrente criada",+ "saved": "Alterações guardadas",+ "deleted": "Cobrança recorrente eliminada",+ "paused": "Em pausa. Nada será cobrado até a retomar.",+ "resumed": "Retomada a partir do próximo período.",+ "ended": "Acordo terminado",+ "generated_one": "Cobrança emitida",+ "generated_other": "{{count}} cobranças emitidas",+ "termSaved": "Preço guardado",+ "termRemoved": "Alteração de preço removida",+ "linked": "Cobrança associada ao acordo",+ "unlinked": "Cobrança desassociada do acordo",+ "recurringInvoice": "Cobrança recorrente",+ "monthlyPreview": "Cerca de {{amount}} por mês.",+ "since": "desde {{date}}",+ "untilDate": "até {{date}}",+ "untilCount_one": "{{count}} cobrança no total",+ "untilCount_other": "{{count}} cobranças no total",+ "endedOn": "terminado a {{date}} ({{reason}})",+ "pausedByFailures": "Em pausa após falhas repetidas. Verifique as condições e retome.",+ "editTitle": "Editar cobrança recorrente",+ "editDescription": "O nome, o cliente, as condições e quando termina.",+ "editLockedDescription": "Já foram emitidas cobranças ao abrigo deste acordo, por isso a frequência e a data de início ficam fixas. Tudo o resto pode mudar.",+ "endTitle": "Terminar este acordo?",+ "endDescription": "Não serão emitidas mais cobranças. As já emitidas ficam exatamente como estão. Indique o motivo: é a única coisa que as cobranças não lhe poderão dizer mais tarde.",+ "linkTitle": "Associar uma cobrança existente",+ "linkDescription": "Uma cobrança que emitiu à mão para um dos períodos deste acordo. Mantém o número, a data e os pagamentos; só fica a saber a que período pertence.",+ "noCandidates": "Nenhuma cobrança sem associação para este cliente nesta moeda.",+ "makeRecurringDescription": "Esta cobrança passa a ser um período de um novo acordo, e as seguintes são geradas por si. A sua data, {{date}}, é o primeiro período, a menos que indique que o acordo começou antes.",+ "filter": {+ "all": "Todos",+ "active": "Ativos",+ "paused": "Em pausa",+ "ended": "Terminados"+ },+ "state": {+ "active": "Ativo",+ "past_due": "Em atraso",+ "paused": "Em pausa",+ "paused_failures": "Precisa de atenção",+ "ended": "Terminado"+ },+ "frequency": {+ "weekly": "Semanal",+ "biweekly": "A cada 2 semanas",+ "monthly": "Mensal",+ "quarterly": "Trimestral",+ "semiannual": "Semestral",+ "yearly": "Anual"+ },+ "endType": {+ "never": "Nunca",+ "on_date": "Numa data",+ "after_count": "Após um número de cobranças"+ },+ "endReason": {+ "canceled_by_client": "Cancelado pelo cliente",+ "canceled_by_us": "Cancelado por nós",+ "completed": "Chegou ao fim",+ "unpaid": "Não pago",+ "other": "Outro"+ },+ "summary": {+ "monthly": "Recorrente mensal",+ "yearly": "Por ano",+ "lost": "Perdido nos últimos 30 dias",+ "endedRecently_one": "{{count}} acordo terminado",+ "endedRecently_other": "{{count}} acordos terminados",+ "pastDue": "Em atraso",+ "pastDueHint": "acordos com uma cobrança em atraso",+ "activeCount_one": "{{count}} acordo ativo",+ "activeCount_other": "{{count}} acordos ativos",+ "none": "Ainda nada recorrente"+ },+ "column": {+ "name": "Acordo",+ "cadence": "Cadência",+ "monthly": "Por mês",+ "next": "Próxima cobrança",+ "invoices": "Cobranças",+ "status": "Estado",+ "period": "Período"+ },+ "figure": {+ "invoiced": "Cobrado",+ "paid": "Recebido",+ "pastDue_one": "{{count}} cobrança em atraso",+ "pastDue_other": "{{count}} cobranças em atraso"+ },+ "field": {+ "name": "Nome",+ "namePlaceholder": "Plano Pro, avença mensal, alojamento",+ "frequency": "Frequência",+ "startDate": "Começa a",+ "startDateHint": "Uma data anterior à cobrança abre espaço para associar as anteriores.",+ "paymentTerms": "Prazo de pagamento (dias)",+ "currency": "Moeda",+ "ends": "Termina",+ "endDate": "Data de fim",+ "endCount": "Número de cobranças",+ "endReason": "Motivo",+ "endedAt": "Terminado a",+ "invoice": "Cobrança",+ "invoicePlaceholder": "Escolha uma cobrança",+ "period": "Período",+ "periodPlaceholder": "Escolha um período"+ },+ "action": {+ "changePrice": "Alterar preço",+ "generate": "Emitir a próxima agora",+ "pause": "Pausar",+ "resume": "Retomar",+ "end": "Terminar acordo",+ "linkInvoice": "Associar cobrança",+ "link": "Associar",+ "makeRecurring": "Repetir esta cobrança",+ "unlink": "Remover do acordo"+ },+ "terms": {+ "title": "Preço",+ "description": "O que o acordo cobra por período, e a partir de quando. Uma alteração aplica-se a partir do primeiro período que começa na data ou depois dela; nada é rateado.",+ "from": "A partir de {{date}}",+ "current": "Em vigor",+ "upcoming": "Agendado",+ "perMonth": "{{amount}} por mês",+ "editTitle": "Editar alteração de preço",+ "changeDescription": "Registe um novo preço a partir de uma data. Os períodos já cobrados mantêm o valor cobrado; a alteração começa no primeiro período a partir da data, por inteiro.",+ "effectiveFrom": "A partir de",+ "nextPeriodHint": "O próximo período começa a {{date}}.",+ "discount": "Desconto",+ "preview": "{{period}} por período, cerca de {{monthly}} por mês."+ },+ "invoices": {+ "title": "Cobranças",+ "description": "Uma por período, gerada no dia. Uma cobrança emitida à mão também pode ser associada.",+ "empty": "Ainda não há cobranças neste acordo.",+ "emptyNext": "Ainda não há cobranças. A primeira será gerada a {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 138575ac..6eaf4b8f 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -292,7 +292,40 @@"payable_not_shareable": "Полученный счёт нельзя опубликовать по ссылке.","discount_exceeds_total": "Скидка больше выставленной суммы.","no_document_filed": "Документ выпущен в другом месте. Прикрепите полученный файл.",- "already_imported": "Этот документ уже импортирован."+ "already_imported": "Этот документ уже импортирован.",+ "term_lines_required": "Условию нужна хотя бы одна строка.",+ "term_empty": "Условие должно что-то выставлять.",+ "term_in_use": "По этому условию уже выставлен счёт. Добавьте новое условие с более поздней даты.",+ "term_before_start": "Условие не может начаться раньше договорённости.",+ "term_date_taken": "С этой даты уже начинается другое условие.",+ "last_term": "Договорённости нужно хотя бы одно условие.",+ "term_not_found": "Условие не найдено.",+ "schedule_ended": "Эта договорённость завершена, и её больше нельзя менять.",+ "schedule_locked": "Периодичность, дата начала и валюта зафиксированы, как только по этой договорённости существует счёт.",+ "schedule_has_invoices": "По этой договорённости выставлены счета. Завершите её вместо удаления.",+ "schedule_not_active": "Счета выставляет только активная договорённость.",+ "invalid_frequency": "Неизвестная периодичность.",+ "invalid_end_type": "Неизвестное условие окончания.",+ "invalid_end_reason": "Неизвестная причина окончания.",+ "end_date_required": "Укажите, в какую дату заканчивается договорённость.",+ "end_count_required": "Укажите, после скольких счетов заканчивается договорённость.",+ "end_before_start": "Договорённость не может закончиться раньше, чем началась.",+ "name_required": "Дайте договорённости название.",+ "not_issued": "Начать договорённость может только выставленный счёт.",+ "already_linked": "Этот счёт уже относится к договорённости.",+ "invoice_void": "Аннулированный счёт не может закрывать период.",+ "payee_mismatch": "В счёте и договорённости указаны разные клиенты.",+ "not_a_period": "Эта дата не является началом периода этой договорённости.",+ "beyond_end": "Этот период наступает после окончания договорённости.",+ "period_taken": "Этот период уже закрыт другим счётом.",+ "start_after_invoice": "Договорённость не может начаться после этого счёта.",+ "invoice_not_found": "Счёт не найден.",+ "no_term": "Для этого периода не действует ни одно условие.",+ "no_author": "У этой договорённости нет автора, от имени которого выставлять счета.",+ "negative_discount": "Скидка не может быть отрицательной.",+ "first_term": "Цену, действующую с начала, нельзя перенести или удалить. Измените её или добавьте новую цену с более поздней даты.",+ "not_receivable": "К договорённости может относиться только выставленный вами счёт.",+ "period_already_issued": "Этот период только что выставлен. Обновите страницу, чтобы его увидеть."},"comingNext": "Выставляйте счета клиентам и следите за тем, что оплачено, а что остаётся открытым. Это следующее, что будет сделано.","document": {@@ -385,6 +418,152 @@"alsoCovers_many": "и ещё {{count}} счетов","alsoCovers_other": "также покрывает ещё {{count}} счетов","wouldApply": "применит {{amount}}"+ },+ "schedules": {+ "title": "Регулярные",+ "new": "Новый регулярный счёт",+ "newDescription": "Договорённость с клиентом выставлять счёт каждый период. Счета выставляются за вас, в назначенный день.",+ "backToList": "Назад к регулярным",+ "empty": "Регулярных счетов пока нет. Создайте один, или откройте счёт и выберите \"Повторять этот счёт\".",+ "emptyFiltered": "С таким статусом здесь ничего нет.",+ "created": "Регулярный счёт создан",+ "saved": "Изменения сохранены",+ "deleted": "Регулярный счёт удалён",+ "paused": "Приостановлено. Ничего не будет выставляться, пока вы не возобновите.",+ "resumed": "Возобновлено со следующего периода.",+ "ended": "Договорённость завершена",+ "generated_one": "Счёт выставлен",+ "generated_other": "Выставлено счетов: {{count}}",+ "termSaved": "Цена сохранена",+ "termRemoved": "Изменение цены удалено",+ "linked": "Счёт привязан к договорённости",+ "unlinked": "Счёт отвязан от договорённости",+ "recurringInvoice": "Регулярный счёт",+ "monthlyPreview": "Около {{amount}} в месяц.",+ "since": "с {{date}}",+ "untilDate": "до {{date}}",+ "untilCount_one": "{{count}} счёт всего",+ "untilCount_other": "Счетов всего: {{count}}",+ "endedOn": "завершена {{date}} ({{reason}})",+ "pausedByFailures": "Приостановлено после повторных сбоев. Проверьте условия и возобновите.",+ "editTitle": "Изменить регулярный счёт",+ "editDescription": "Название, клиент, условия и когда заканчивается.",+ "editLockedDescription": "По этой договорённости уже выставлены счета, поэтому периодичность и дата начала зафиксированы. Всё остальное можно менять.",+ "endTitle": "Завершить эту договорённость?",+ "endDescription": "Новые счета выставляться не будут. Уже выставленные останутся ровно такими, какие есть. Укажите причину: это единственное, чего счета потом не расскажут.",+ "linkTitle": "Привязать существующий счёт",+ "linkDescription": "Счёт, который вы выставили вручную за один из периодов этой договорённости. Он сохраняет номер, дату и платежи; он лишь узнаёт, за какой период был выставлен.",+ "noCandidates": "Нет непривязанных счетов для этого клиента в этой валюте.",+ "makeRecurringDescription": "Этот счёт становится одним периодом новой договорённости, а следующие выставляются за вас. Его дата, {{date}}, считается первым периодом, если вы не укажете, что договорённость началась раньше.",+ "filter": {+ "all": "Все",+ "active": "Активные",+ "paused": "Приостановленные",+ "ended": "Завершённые"+ },+ "state": {+ "active": "Активна",+ "past_due": "Просрочена",+ "paused": "Приостановлена",+ "paused_failures": "Требует внимания",+ "ended": "Завершена"+ },+ "frequency": {+ "weekly": "Еженедельно",+ "biweekly": "Раз в 2 недели",+ "monthly": "Ежемесячно",+ "quarterly": "Ежеквартально",+ "semiannual": "Раз в 6 месяцев",+ "yearly": "Ежегодно"+ },+ "endType": {+ "never": "Никогда",+ "on_date": "В указанную дату",+ "after_count": "После определённого числа счетов"+ },+ "endReason": {+ "canceled_by_client": "Отменена клиентом",+ "canceled_by_us": "Отменена нами",+ "completed": "Истёк срок",+ "unpaid": "Не оплачено",+ "other": "Другое"+ },+ "summary": {+ "monthly": "Регулярно в месяц",+ "yearly": "В год",+ "lost": "Потеряно за последние 30 дней",+ "endedRecently_one": "{{count}} договорённость завершена",+ "endedRecently_other": "Завершено договорённостей: {{count}}",+ "pastDue": "Просрочено",+ "pastDueHint": "договорённости с просроченным счётом",+ "activeCount_one": "{{count}} активная договорённость",+ "activeCount_other": "Активных договорённостей: {{count}}",+ "none": "Регулярного пока ничего нет"+ },+ "column": {+ "name": "Договорённость",+ "cadence": "Периодичность",+ "monthly": "В месяц",+ "next": "Следующий счёт",+ "invoices": "Счета",+ "status": "Статус",+ "period": "Период"+ },+ "figure": {+ "invoiced": "Выставлено",+ "paid": "Получено",+ "pastDue_one": "{{count}} счёт просрочен",+ "pastDue_other": "Просрочено счетов: {{count}}"+ },+ "field": {+ "name": "Название",+ "namePlaceholder": "Тариф Pro, ежемесячный ретейнер, хостинг",+ "frequency": "Периодичность",+ "startDate": "Начинается",+ "startDateHint": "Дата раньше счёта оставляет место, чтобы привязать предыдущие.",+ "paymentTerms": "Срок оплаты (дней)",+ "currency": "Валюта",+ "ends": "Заканчивается",+ "endDate": "Дата окончания",+ "endCount": "Число счетов",+ "endReason": "Причина",+ "endedAt": "Завершена",+ "invoice": "Счёт",+ "invoicePlaceholder": "Выберите счёт",+ "period": "Период",+ "periodPlaceholder": "Выберите период"+ },+ "action": {+ "changePrice": "Изменить цену",+ "generate": "Выставить следующий сейчас",+ "pause": "Приостановить",+ "resume": "Возобновить",+ "end": "Завершить договорённость",+ "linkInvoice": "Привязать счёт",+ "link": "Привязать",+ "makeRecurring": "Повторять этот счёт",+ "unlink": "Убрать из договорённости"+ },+ "terms": {+ "title": "Цена",+ "description": "Сколько договорённость выставляет за период и с какого момента. Изменение действует с первого периода, начинающегося в его дату или позже; ничего не считается пропорционально.",+ "from": "С {{date}}",+ "current": "Действует",+ "upcoming": "Предстоит",+ "perMonth": "{{amount}} в месяц",+ "editTitle": "Изменить изменение цены",+ "changeDescription": "Запишите новую цену с указанной даты. Уже выставленные периоды сохраняют свою сумму; изменение начинается с первого периода в эту дату или позже, целиком.",+ "effectiveFrom": "С",+ "nextPeriodHint": "Следующий период начинается {{date}}.",+ "discount": "Скидка",+ "preview": "{{period}} за период, около {{monthly}} в месяц."+ },+ "invoices": {+ "title": "Счета",+ "description": "Один за период, выставляется в назначенный день. Счёт, выставленный вручную, тоже можно привязать.",+ "empty": "По этой договорённости пока нет счетов.",+ "emptyNext": "Счетов пока нет. Первый будет выставлен {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 6b7314a4..fae95f70 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -292,7 +292,40 @@"payable_not_shareable": "Prijatú faktúru nemožno zdieľať.","discount_exceeds_total": "Zľava je vyššia než účtovaná suma.","no_document_filed": "Tento dokument bol vystavený inde. Priložte prijatý súbor.",- "already_imported": "Tento dokument už bol importovaný."+ "already_imported": "Tento dokument už bol importovaný.",+ "term_lines_required": "Podmienka potrebuje aspoň jednu položku.",+ "term_empty": "Podmienka musí niečo fakturovať.",+ "term_in_use": "Podľa tejto podmienky už bola vystavená faktúra. Pridajte novú podmienku od neskoršieho dátumu.",+ "term_before_start": "Podmienka nemôže začať skôr než dohoda.",+ "term_date_taken": "V tomto dátume už začína iná podmienka.",+ "last_term": "Dohoda potrebuje aspoň jednu podmienku.",+ "term_not_found": "Podmienka sa nenašla.",+ "schedule_ended": "Táto dohoda bola ukončená a už sa nedá meniť.",+ "schedule_locked": "Frekvencia, dátum začiatku a mena sú pevné, len čo v tejto dohode existuje faktúra.",+ "schedule_has_invoices": "V rámci tejto dohody boli vystavené faktúry. Ukončite ju namiesto odstránenia.",+ "schedule_not_active": "Faktúry vystavuje len aktívna dohoda.",+ "invalid_frequency": "Neznáma frekvencia.",+ "invalid_end_type": "Neznáma podmienka ukončenia.",+ "invalid_end_reason": "Neznámy dôvod ukončenia.",+ "end_date_required": "Uveďte, ku ktorému dátumu dohoda končí.",+ "end_count_required": "Uveďte, po koľkých faktúrach dohoda končí.",+ "end_before_start": "Dohoda nemôže skončiť skôr, než začne.",+ "name_required": "Dajte dohode názov.",+ "not_issued": "Dohodu môže začať len vystavená faktúra.",+ "already_linked": "Táto faktúra už patrí k dohode.",+ "invoice_void": "Stornovaná faktúra nemôže pokrývať obdobie.",+ "payee_mismatch": "Faktúra a dohoda uvádzajú rôznych klientov.",+ "not_a_period": "Tento dátum nie je začiatkom obdobia tejto dohody.",+ "beyond_end": "Toto obdobie je po ukončení dohody.",+ "period_taken": "Toto obdobie už pokrýva iná faktúra.",+ "start_after_invoice": "Dohoda nemôže začať po tejto faktúre.",+ "invoice_not_found": "Faktúra sa nenašla.",+ "no_term": "Pre toto obdobie neplatí žiadna podmienka.",+ "no_author": "Táto dohoda nemá autora, v mene ktorého by sa vystavovali faktúry.",+ "negative_discount": "Zľava nemôže byť záporná.",+ "first_term": "Cenu platnú od začiatku nemožno presunúť ani odstrániť. Zmeňte ju alebo pridajte novú cenu od neskoršieho dátumu.",+ "not_receivable": "K dohode môže patriť iba faktúra, ktorú ste vystavili vy.",+ "period_already_issued": "Toto obdobie bolo práve vystavené. Obnovte stránku, aby ste ho videli."},"comingNext": "Fakturujte klientom a majte prehľad o tom, čo je zaplatené a čo ešte otvorené. Toto sa práve stavia.","document": {@@ -385,6 +418,152 @@"alsoCovers_many": "a ďalších {{count}} faktúr","alsoCovers_other": "pokrýva aj {{count}} ďalších faktúr","wouldApply": "použila by {{amount}}"+ },+ "schedules": {+ "title": "Opakované",+ "new": "Nová opakovaná faktúra",+ "newDescription": "Dohoda s klientom o fakturácii každé obdobie. Faktúry sa vystavia za vás, v daný deň.",+ "backToList": "Späť na opakované",+ "empty": "Zatiaľ žiadne opakované faktúry. Vytvorte jednu, alebo otvorte faktúru a zvoľte \"Opakovať túto faktúru\".",+ "emptyFiltered": "Nič s týmto stavom.",+ "created": "Opakovaná faktúra vytvorená",+ "saved": "Zmeny uložené",+ "deleted": "Opakovaná faktúra odstránená",+ "paused": "Pozastavené. Nič sa nebude fakturovať, kým ju neobnovíte.",+ "resumed": "Obnovené od nasledujúceho obdobia.",+ "ended": "Dohoda ukončená",+ "generated_one": "Faktúra vystavená",+ "generated_other": "Vystavených faktúr: {{count}}",+ "termSaved": "Cena uložená",+ "termRemoved": "Zmena ceny odstránená",+ "linked": "Faktúra priradená k dohode",+ "unlinked": "Faktúra odpojená od dohody",+ "recurringInvoice": "Opakovaná faktúra",+ "monthlyPreview": "Približne {{amount}} mesačne.",+ "since": "od {{date}}",+ "untilDate": "do {{date}}",+ "untilCount_one": "{{count}} faktúra celkom",+ "untilCount_other": "Faktúr celkom: {{count}}",+ "endedOn": "ukončená {{date}} ({{reason}})",+ "pausedByFailures": "Pozastavené po opakovaných zlyhaniach. Skontrolujte podmienky a obnovte.",+ "editTitle": "Upraviť opakovanú faktúru",+ "editDescription": "Názov, klient, podmienky a kedy končí.",+ "editLockedDescription": "V rámci tejto dohody už boli vystavené faktúry, takže frekvencia a dátum začiatku sú pevné. Všetko ostatné sa dá zmeniť.",+ "endTitle": "Ukončiť túto dohodu?",+ "endDescription": "Ďalšie faktúry sa už nevystavia. Tie už vystavené zostanú presne také, aké sú. Uveďte dôvod: je to jediná vec, ktorú vám faktúry neskôr nepovedia.",+ "linkTitle": "Priradiť existujúcu faktúru",+ "linkDescription": "Faktúra, ktorú ste vystavili ručne za jedno z období tejto dohody. Zachová si číslo, dátum a platby; len sa dozvie, ktorého obdobia sa týka.",+ "noCandidates": "Žiadna nepriradená faktúra pre tohto klienta v tejto mene.",+ "makeRecurringDescription": "Táto faktúra sa stane jedným obdobím novej dohody a ďalšie sa vystavia za vás. Jej dátum, {{date}}, je prvým obdobím, pokiaľ neuvediete, že dohoda začala skôr.",+ "filter": {+ "all": "Všetky",+ "active": "Aktívne",+ "paused": "Pozastavené",+ "ended": "Ukončené"+ },+ "state": {+ "active": "Aktívna",+ "past_due": "Po splatnosti",+ "paused": "Pozastavená",+ "paused_failures": "Vyžaduje pozornosť",+ "ended": "Ukončená"+ },+ "frequency": {+ "weekly": "Týždenne",+ "biweekly": "Každé 2 týždne",+ "monthly": "Mesačne",+ "quarterly": "Štvrťročne",+ "semiannual": "Každých 6 mesiacov",+ "yearly": "Ročne"+ },+ "endType": {+ "never": "Nikdy",+ "on_date": "K dátumu",+ "after_count": "Po určitom počte faktúr"+ },+ "endReason": {+ "canceled_by_client": "Zrušená klientom",+ "canceled_by_us": "Zrušená nami",+ "completed": "Dobehla do konca",+ "unpaid": "Nezaplatené",+ "other": "Iný"+ },+ "summary": {+ "monthly": "Opakované mesačne",+ "yearly": "Ročne",+ "lost": "Stratené za posledných 30 dní",+ "endedRecently_one": "{{count}} dohoda ukončená",+ "endedRecently_other": "Ukončených dohôd: {{count}}",+ "pastDue": "Po splatnosti",+ "pastDueHint": "dohody s faktúrou po splatnosti",+ "activeCount_one": "{{count}} aktívna dohoda",+ "activeCount_other": "Aktívnych dohôd: {{count}}",+ "none": "Zatiaľ nič opakované"+ },+ "column": {+ "name": "Dohoda",+ "cadence": "Interval",+ "monthly": "Mesačne",+ "next": "Ďalšia faktúra",+ "invoices": "Faktúry",+ "status": "Stav",+ "period": "Obdobie"+ },+ "figure": {+ "invoiced": "Fakturované",+ "paid": "Prijaté",+ "pastDue_one": "{{count}} faktúra po splatnosti",+ "pastDue_other": "Faktúr po splatnosti: {{count}}"+ },+ "field": {+ "name": "Názov",+ "namePlaceholder": "Plán Pro, mesačný paušál, hosting",+ "frequency": "Frekvencia",+ "startDate": "Začína",+ "startDateHint": "Skorší dátum než faktúra dáva priestor priradiť tie pred ňou.",+ "paymentTerms": "Splatnosť (dni)",+ "currency": "Mena",+ "ends": "Končí",+ "endDate": "Dátum ukončenia",+ "endCount": "Počet faktúr",+ "endReason": "Dôvod",+ "endedAt": "Ukončená",+ "invoice": "Faktúra",+ "invoicePlaceholder": "Vyberte faktúru",+ "period": "Obdobie",+ "periodPlaceholder": "Vyberte obdobie"+ },+ "action": {+ "changePrice": "Zmeniť cenu",+ "generate": "Vystaviť ďalšiu teraz",+ "pause": "Pozastaviť",+ "resume": "Obnoviť",+ "end": "Ukončiť dohodu",+ "linkInvoice": "Priradiť faktúru",+ "link": "Priradiť",+ "makeRecurring": "Opakovať túto faktúru",+ "unlink": "Odstrániť z dohody"+ },+ "terms": {+ "title": "Cena",+ "description": "Čo dohoda fakturuje za obdobie a odkedy. Zmena platí od prvého obdobia, ktoré začína v jej dátume alebo neskôr; nič sa neprepočítava pomerne.",+ "from": "Od {{date}}",+ "current": "Platná",+ "upcoming": "Nadchádzajúca",+ "perMonth": "{{amount}} mesačne",+ "editTitle": "Upraviť zmenu ceny",+ "changeDescription": "Zaznamenajte novú cenu od zvoleného dátumu. Už fakturované obdobia si zachovajú, čo im bolo účtované; zmena začne prvým obdobím v tomto dátume alebo neskôr, v plnej výške.",+ "effectiveFrom": "Od",+ "nextPeriodHint": "Ďalšie obdobie začína {{date}}.",+ "discount": "Zľava",+ "preview": "{{period}} za obdobie, približne {{monthly}} mesačne."+ },+ "invoices": {+ "title": "Faktúry",+ "description": "Jedna za obdobie, vystavená v daný deň. Ručne vystavenú faktúru možno tiež priradiť.",+ "empty": "V tejto dohode zatiaľ nie je žiadna faktúra.",+ "emptyNext": "Zatiaľ žiadna faktúra. Prvá sa vystaví {{date}}."+ }}},"collections": {diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 1561c2b1..b366c69b 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -292,7 +292,40 @@"payable_not_shareable": "Отриманий рахунок не можна поширити за посиланням.","discount_exceeds_total": "Знижка більша за виставлену суму.","no_document_filed": "Документ виписано в іншому місці. Прикріпіть отриманий файл.",- "already_imported": "Цей документ уже імпортовано."+ "already_imported": "Цей документ уже імпортовано.",+ "term_lines_required": "Умові потрібен хоча б один рядок.",+ "term_empty": "Умова має щось виставляти.",+ "term_in_use": "За цією умовою вже виставлено рахунок. Додайте нову умову з пізнішої дати.",+ "term_before_start": "Умова не може початися раніше за домовленість.",+ "term_date_taken": "З цієї дати вже починається інша умова.",+ "last_term": "Домовленості потрібна хоча б одна умова.",+ "term_not_found": "Умову не знайдено.",+ "schedule_ended": "Цю домовленість завершено, і її більше не можна змінювати.",+ "schedule_locked": "Періодичність, дата початку та валюта зафіксовані, щойно за цією домовленістю існує рахунок.",+ "schedule_has_invoices": "За цією домовленістю виставлено рахунки. Завершіть її замість видалення.",+ "schedule_not_active": "Рахунки виставляє лише активна домовленість.",+ "invalid_frequency": "Невідома періодичність.",+ "invalid_end_type": "Невідома умова закінчення.",+ "invalid_end_reason": "Невідома причина закінчення.",+ "end_date_required": "Вкажіть, у яку дату закінчується домовленість.",+ "end_count_required": "Вкажіть, після скількох рахунків закінчується домовленість.",+ "end_before_start": "Домовленість не може закінчитися раніше, ніж почалася.",+ "name_required": "Дайте домовленості назву.",+ "not_issued": "Почати домовленість може лише виставлений рахунок.",+ "already_linked": "Цей рахунок уже належить до домовленості.",+ "invoice_void": "Анульований рахунок не може закривати період.",+ "payee_mismatch": "У рахунку та домовленості вказано різних клієнтів.",+ "not_a_period": "Ця дата не є початком періоду цієї домовленості.",+ "beyond_end": "Цей період настає після закінчення домовленості.",+ "period_taken": "Цей період уже закрито іншим рахунком.",+ "start_after_invoice": "Домовленість не може початися після цього рахунку.",+ "invoice_not_found": "Рахунок не знайдено.",+ "no_term": "Для цього періоду не діє жодна умова.",+ "no_author": "У цієї домовленості немає автора, від імені якого виставляти рахунки.",+ "negative_discount": "Знижка не може бути від'ємною.",+ "first_term": "Ціну, що діє від початку, не можна перенести чи видалити. Змініть її або додайте нову ціну з пізнішої дати.",+ "not_receivable": "До домовленості може належати лише рахунок, виставлений вами.",+ "period_already_issued": "Цей період щойно виставлено. Оновіть сторінку, щоб його побачити."},"comingNext": "Виставляйте рахунки клієнтам і стежте за тим, що оплачено, а що залишається відкритим. Це наступне, що буде зроблено.","document": {@@ -385,6 +418,152 @@"alsoCovers_many": "і ще {{count}} рахунків","alsoCovers_other": "також покриває ще {{count}} рахунків","wouldApply": "застосує {{amount}}"+ },+ "schedules": {+ "title": "Регулярні",+ "new": "Новий регулярний рахунок",+ "newDescription": "Домовленість із клієнтом виставляти рахунок щоперіоду. Рахунки виставляються за вас, у призначений день.",+ "backToList": "Назад до регулярних",+ "empty": "Регулярних рахунків поки немає. Створіть один, або відкрийте рахунок і виберіть \"Повторювати цей рахунок\".",+ "emptyFiltered": "З таким статусом тут нічого немає.",+ "created": "Регулярний рахунок створено",+ "saved": "Зміни збережено",+ "deleted": "Регулярний рахунок видалено",+ "paused": "Призупинено. Нічого не виставлятиметься, доки ви не відновите.",+ "resumed": "Відновлено з наступного періоду.",+ "ended": "Домовленість завершено",+ "generated_one": "Рахунок виставлено",+ "generated_other": "Виставлено рахунків: {{count}}",+ "termSaved": "Ціну збережено",+ "termRemoved": "Зміну ціни видалено",+ "linked": "Рахунок прив'язано до домовленості",+ "unlinked": "Рахунок відв'язано від домовленості",+ "recurringInvoice": "Регулярний рахунок",+ "monthlyPreview": "Близько {{amount}} на місяць.",+ "since": "з {{date}}",+ "untilDate": "до {{date}}",+ "untilCount_one": "{{count}} рахунок загалом",+ "untilCount_other": "Рахунків загалом: {{count}}",+ "endedOn": "завершено {{date}} ({{reason}})",+ "pausedByFailures": "Призупинено після повторних збоїв. Перевірте умови та відновіть.",+ "editTitle": "Змінити регулярний рахунок",+ "editDescription": "Назва, клієнт, умови та коли закінчується.",+ "editLockedDescription": "За цією домовленістю вже виставлено рахунки, тому періодичність і дата початку зафіксовані. Усе інше можна змінювати.",+ "endTitle": "Завершити цю домовленість?",+ "endDescription": "Нові рахунки більше не виставлятимуться. Уже виставлені залишаться саме такими, як є. Вкажіть причину: це єдине, чого рахунки потім не розкажуть.",+ "linkTitle": "Прив'язати наявний рахунок",+ "linkDescription": "Рахунок, який ви виставили вручну за один із періодів цієї домовленості. Він зберігає номер, дату та платежі; він лише дізнається, за який період був виставлений.",+ "noCandidates": "Немає неприв'язаних рахунків для цього клієнта в цій валюті.",+ "makeRecurringDescription": "Цей рахунок стає одним періодом нової домовленості, а наступні виставляються за вас. Його дата, {{date}}, вважається першим періодом, якщо ви не вкажете, що домовленість почалася раніше.",+ "filter": {+ "all": "Усі",+ "active": "Активні",+ "paused": "Призупинені",+ "ended": "Завершені"+ },+ "state": {+ "active": "Активна",+ "past_due": "Прострочена",+ "paused": "Призупинена",+ "paused_failures": "Потребує уваги",+ "ended": "Завершена"+ },+ "frequency": {+ "weekly": "Щотижня",+ "biweekly": "Раз на 2 тижні",+ "monthly": "Щомісяця",+ "quarterly": "Щокварталу",+ "semiannual": "Раз на 6 місяців",+ "yearly": "Щороку"+ },+ "endType": {+ "never": "Ніколи",+ "on_date": "У вказану дату",+ "after_count": "Після певної кількості рахунків"+ },+ "endReason": {+ "canceled_by_client": "Скасовано клієнтом",+ "canceled_by_us": "Скасовано нами",+ "completed": "Добігла кінця",+ "unpaid": "Не оплачено",+ "other": "Інше"+ },+ "summary": {+ "monthly": "Регулярно на місяць",+ "yearly": "На рік",+ "lost": "Втрачено за останні 30 днів",+ "endedRecently_one": "{{count}} домовленість завершено",+ "endedRecently_other": "Завершено домовленостей: {{count}}",+ "pastDue": "Прострочено",+ "pastDueHint": "домовленості з простроченим рахунком",+ "activeCount_one": "{{count}} активна домовленість",+ "activeCount_other": "Активних домовленостей: {{count}}",+ "none": "Регулярного поки нічого немає"+ },+ "column": {+ "name": "Домовленість",+ "cadence": "Періодичність",+ "monthly": "На місяць",+ "next": "Наступний рахунок",+ "invoices": "Рахунки",+ "status": "Статус",+ "period": "Період"+ },+ "figure": {+ "invoiced": "Виставлено",+ "paid": "Отримано",+ "pastDue_one": "{{count}} рахунок прострочено",+ "pastDue_other": "Прострочено рахунків: {{count}}"+ },+ "field": {+ "name": "Назва",+ "namePlaceholder": "Тариф Pro, щомісячний ретейнер, хостинг",+ "frequency": "Періодичність",+ "startDate": "Починається",+ "startDateHint": "Дата раніше за рахунок залишає місце, щоб прив'язати попередні.",+ "paymentTerms": "Термін оплати (днів)",+ "currency": "Валюта",+ "ends": "Закінчується",+ "endDate": "Дата закінчення",+ "endCount": "Кількість рахунків",+ "endReason": "Причина",+ "endedAt": "Завершено",+ "invoice": "Рахунок",+ "invoicePlaceholder": "Виберіть рахунок",+ "period": "Період",+ "periodPlaceholder": "Виберіть період"+ },+ "action": {+ "changePrice": "Змінити ціну",+ "generate": "Виставити наступний зараз",+ "pause": "Призупинити",+ "resume": "Відновити",+ "end": "Завершити домовленість",+ "linkInvoice": "Прив'язати рахунок",+ "link": "Прив'язати",+ "makeRecurring": "Повторювати цей рахунок",+ "unlink": "Прибрати з домовленості"+ },+ "terms": {+ "title": "Ціна",+ "description": "Скільки домовленість виставляє за період і відколи. Зміна діє з першого періоду, що починається в її дату або пізніше; нічого не рахується пропорційно.",+ "from": "З {{date}}",+ "current": "Чинна",+ "upcoming": "Майбутня",+ "perMonth": "{{amount}} на місяць",+ "editTitle": "Змінити зміну ціни",+ "changeDescription": "Запишіть нову ціну з указаної дати. Уже виставлені періоди зберігають свою суму; зміна починається з першого періоду в цю дату або пізніше, повністю.",+ "effectiveFrom": "З",+ "nextPeriodHint": "Наступний період починається {{date}}.",+ "discount": "Знижка",+ "preview": "{{period}} за період, близько {{monthly}} на місяць."+ },+ "invoices": {+ "title": "Рахунки",+ "description": "Один за період, виставляється в призначений день. Рахунок, виставлений вручну, теж можна прив'язати.",+ "empty": "За цією домовленістю поки немає рахунків.",+ "emptyNext": "Рахунків поки немає. Перший буде виставлено {{date}}."+ }}},"collections": {diff --git a/frontend/src/pages/invoice-detail.tsx b/frontend/src/pages/invoice-detail.tsxindex 0d6d1a04..2041775b 100644--- a/frontend/src/pages/invoice-detail.tsx+++ b/frontend/src/pages/invoice-detail.tsx@@ -4,7 +4,7 @@ import { useNavigate, useParams } from 'react-router-dom'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import {ArrowLeft, Ban, Check, CheckCircle2, CircleSlash, Copy, Download, Link2,- MoreHorizontal, Pencil, RotateCcw, Send, Share2, Trash2, Unlink,+ MoreHorizontal, Pencil, Repeat, RotateCcw, Send, Share2, Trash2, Unlink,} from 'lucide-react'import { toast } from 'sonner'@@ -45,7 +45,15 @@ import {import { InvoiceDocumentView } from '@/components/invoice-document'import { InvoiceDocumentBrowser } from '@/components/invoice-documents'import { InvoiceLineEditor } from '@/components/invoice-line-editor'-import type { Invoice, InvoiceDirection, InvoiceLineInput } from '@/types'+import { EndConditionFields, SchedulePeriodChip } from '@/components/invoice-schedule-ui'+import { FREQUENCIES, endPayload } from '@/lib/invoice-schedule-utils'+import type {+ Invoice,+ InvoiceDirection,+ InvoiceLineInput,+ InvoiceScheduleEndType,+ InvoiceScheduleFrequency,+} from '@/types'import { cn } from '@/lib/utils'import { formatCurrency } from '@/lib/format'import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'@@ -90,6 +98,7 @@ export default function InvoiceDetailPage() {const [linkOpen, setLinkOpen] = useState(false)const [editOpen, setEditOpen] = useState(false)+ const [recurringOpen, setRecurringOpen] = useState(false)const [tab, setTab] = useState<Tab>('details')const [copied, setCopied] = useState(false)@@ -127,6 +136,12 @@ export default function InvoiceDetailPage() {void queryClient.invalidateQueries({ queryKey: ['invoices'] })void queryClient.invalidateQueries({ queryKey: ['invoice-summary'] })void queryClient.invalidateQueries({ queryKey: ['invoice-facets'] })+ // An invoice of an agreement changes what the agreement reads:+ // issuing it moves "invoiced", a payment moves "received".+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-invoices'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-summary'] })}const onError = (error: unknown) => {@@ -158,6 +173,15 @@ export default function InvoiceDetailPage() {},onError,})+ const unlinkScheduleMutation = useMutation({+ mutationFn: () => invoicesApi.unlinkSchedule(id),+ onSuccess: () => {+ toast.success(t('invoices.schedules.unlinked'))+ refresh()+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })+ },+ onError,+ })const unlinkMutation = useMutation({mutationFn: (allocationId: string) => invoicesApi.unallocate(id, allocationId),onSuccess: () => {@@ -231,6 +255,14 @@ export default function InvoiceDetailPage() {const shareUrl = invoice.share_token? `${window.location.origin}/i/${invoice.share_token}`: null+ // "Repeat this": an issued receivable that is not already a period of+ // an agreement. A draft has nothing agreed yet, and a bill received is+ // the supplier's to repeat.+ const canRecur =+ invoice.direction === 'receivable' &&+ invoice.status !== 'draft' &&+ invoice.status !== 'void' &&+ !invoice.schedule_idreturn (<div>@@ -322,7 +354,9 @@ export default function InvoiceDetailPage() {were indistinguishable, and giving "void" the sameweight as "mark as paid" is how someone voids byreflex. */}- {(actions.canWriteOff ||+ {(canRecur ||+ invoice.schedule_id ||+ actions.canWriteOff ||actions.canReopen ||actions.canVoid ||actions.canDelete) && (@@ -341,6 +375,26 @@ export default function InvoiceDetailPage() {align="end"className="w-[220px] p-1 bg-card border border-border rounded-xl shadow-md">+ {canRecur && (+ <DropdownMenuItem+ onClick={() => setRecurringOpen(true)}+ data-testid="invoice-make-recurring"+ className="gap-2 text-sm"+ >+ <Repeat className="h-4 w-4 text-muted-foreground" />+ {t('invoices.schedules.action.makeRecurring')}+ </DropdownMenuItem>+ )}+ {invoice.schedule_id && (+ <DropdownMenuItem+ onClick={() => unlinkScheduleMutation.mutate()}+ data-testid="invoice-unlink-schedule"+ className="gap-2 text-sm"+ >+ <Unlink className="h-4 w-4 text-muted-foreground" />+ {t('invoices.schedules.action.unlink')}+ </DropdownMenuItem>+ )}{actions.canWriteOff && (<DropdownMenuItemonClick={() => writeOffMutation.mutate()}@@ -405,6 +459,7 @@ export default function InvoiceDetailPage() {{t('invoices.daysLate', { count: invoice.days_overdue })}</span>)}+ <SchedulePeriodChip invoice={invoice} /></div>{tab === 'document' ? (@@ -635,6 +690,26 @@ export default function InvoiceDetailPage() {onSaved={refresh}/>+ <MakeRecurringDialog++ key={recurringOpen ? 'recurring-open' : 'recurring-closed'}++ open={recurringOpen}++ onOpenChange={setRecurringOpen}++ invoice={invoice}++ onCreated={(scheduleId) => {++ refresh()++ navigate(`/invoices/schedules/${scheduleId}`)++ }}++ />+<LinkPaymentDialogopen={linkOpen}onOpenChange={setLinkOpen}@@ -941,3 +1016,130 @@ function EditDraftDialog({</Dialog>)}++function MakeRecurringDialog({+ open,+ onOpenChange,+ invoice,+ onCreated,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ invoice: Invoice+ onCreated: (scheduleId: string) => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const dateLocale = useDateLocale()+ const [name, setName] = useState(invoice.lines[0]?.description ?? invoice.payee?.name ?? '')+ const [frequency, setFrequency] = useState<InvoiceScheduleFrequency>('monthly')+ // The invoice's own date by default. Earlier makes this invoice a+ // later period, so the ones billed by hand before it can be linked.+ const [startDate, setStartDate] = useState(invoice.issue_date)+ const [endType, setEndType] = useState<InvoiceScheduleEndType>('never')+ const [endDate, setEndDate] = useState('')+ const [endCount, setEndCount] = useState('')++ const mutation = useMutation({+ mutationFn: () =>+ invoicesApi.makeRecurring(invoice.id, {+ frequency,+ name: name.trim() || undefined,+ start_date: startDate,+ ...endPayload(endType, endDate, endCount),+ }),+ onSuccess: (schedule) => {+ toast.success(t('invoices.schedules.created'))+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-summary'] })+ onOpenChange(false)+ onCreated(schedule.id)+ },+ onError: (error) => {+ const key = invoiceErrorKey(error)+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ },+ })++ const ready =+ name.trim().length > 0 &&+ Boolean(startDate) &&+ (endType !== 'on_date' || Boolean(endDate)) &&+ (endType !== 'after_count' || Number(endCount) >= 1)++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('invoices.schedules.action.makeRecurring')}</DialogTitle>+ <DialogDescription>+ {t('invoices.schedules.makeRecurringDescription', {+ date: new Date(`${invoice.issue_date}T00:00:00`).toLocaleDateString(dateLocale),+ })}+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="recurring-name">{t('invoices.schedules.field.name')}</Label>+ <Input+ id="recurring-name"+ data-testid="recurring-name-input"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t('invoices.schedules.field.namePlaceholder')}+ />+ </div>+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label>{t('invoices.schedules.field.frequency')}</Label>+ <Select value={frequency} onValueChange={(v) => setFrequency(v as InvoiceScheduleFrequency)}>+ <SelectTrigger data-testid="recurring-frequency-select">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {FREQUENCIES.map((value) => (+ <SelectItem key={value} value={value}>+ {t(`invoices.schedules.frequency.${value}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="recurring-start">{t('invoices.schedules.field.startDate')}</Label>+ <Input+ id="recurring-start"+ data-testid="recurring-start-input"+ type="date"+ max={invoice.issue_date}+ value={startDate}+ onChange={(e) => setStartDate(e.target.value)}+ />+ <p className="text-[11px] text-muted-foreground">{t('invoices.schedules.field.startDateHint')}</p>+ </div>+ </div>+ <EndConditionFields+ idPrefix="recurring"+ endType={endType}+ endDate={endDate}+ endCount={endCount}+ onChange={(next) => {+ setEndType(next.endType)+ setEndDate(next.endDate)+ setEndCount(next.endCount)+ }}+ />+ </div>+ <DialogFooter className="gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>+ {t('common.cancel')}+ </Button>+ <Button onClick={() => mutation.mutate()} disabled={!ready || mutation.isPending} data-testid="recurring-submit">+ <Repeat className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.action.makeRecurring')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/pages/invoice-schedule-detail.test.tsx b/frontend/src/pages/invoice-schedule-detail.test.tsxnew file mode 100644index 00000000..08bbd66d--- /dev/null+++ b/frontend/src/pages/invoice-schedule-detail.test.tsx@@ -0,0 +1,264 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, within } from '@testing-library/react'++import InvoiceScheduleDetailPage from '@/pages/invoice-schedule-detail'+import { renderWithProviders, t } from '@/test/utils'+import type { Invoice, InvoiceSchedule, InvoiceScheduleTerm } from '@/types'++const api = vi.hoisted(() => ({+ invoiceSchedules: {+ get: vi.fn(),+ invoices: vi.fn(),+ periods: vi.fn(),+ pause: vi.fn(),+ resume: vi.fn(),+ end: vi.fn(),+ generate: vi.fn(),+ remove: vi.fn(),+ addTerm: vi.fn(),+ updateTerm: vi.fn(),+ removeTerm: vi.fn(),+ link: vi.fn(),+ update: vi.fn(),+ },+ invoices: { settings: vi.fn(), list: vi.fn() },+ payees: { list: vi.fn() },+}))++vi.mock('@/lib/api', () => ({+ invoiceSchedules: api.invoiceSchedules,+ invoices: api.invoices,+ payees: api.payees,+}))++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++let canWrite = true+vi.mock('@/contexts/workspace-context', () => ({+ useWorkspace: () => ({ canWrite }),+}))++vi.mock('@/hooks/use-privacy-mode', () => ({+ usePrivacyMode: () => ({ mask: (value: string) => value }),+}))++const FAR_FUTURE = new Date(Date.now() + 200 * 86_400_000).toISOString().slice(0, 10)++function term(overrides: Partial<InvoiceScheduleTerm> = {}): InvoiceScheduleTerm {+ return {+ id: 'term-1',+ effective_from: '2026-01-05',+ lines: [{ description: 'Retainer', quantity: '1', unit_price: '3000.00' }],+ discount: '0.00',+ subtotal: '3000.00',+ tax_total: '0.00',+ total: '3000.00',+ created_at: '2026-01-01T00:00:00Z',+ ...overrides,+ }+}++const current = term()+const raise_ = term({ id: 'term-2', effective_from: FAR_FUTURE, total: '3500.00', subtotal: '3500.00' })++function schedule(overrides: Partial<InvoiceSchedule> = {}): InvoiceSchedule {+ return {+ id: 'sched-1',+ name: 'Plano Pro',+ payee_id: 'alpha',+ payee: { id: 'alpha', name: 'Cliente Alpha' },+ origin: 'local',+ external_source: null,+ external_id: null,+ status: 'active',+ pause_reason: null,+ ended_at: null,+ end_reason: null,+ frequency: 'monthly',+ start_date: '2026-01-05',+ end_type: 'never',+ end_date: null,+ end_count: null,+ payment_terms_days: 10,+ currency: 'USD',+ notes: null,+ custom_fields: null,+ next_sequence: 3,+ last_generated_at: null,+ consecutive_failures: 0,+ terms: [current, raise_],+ created_at: '2026-01-01T00:00:00Z',+ current_term: current,+ next_term: current,+ monthly_amount: '3000.00',+ next_period_start: '2026-03-05',+ invoice_count: 2,+ amount_invoiced: '6000.00',+ amount_paid: '3000.00',+ past_due_count: 1,+ ...overrides,+ }+}++function invoice(overrides: Partial<Invoice> = {}): Invoice {+ return {+ id: 'inv-1',+ payee_id: 'alpha',+ payee: { id: 'alpha', name: 'Cliente Alpha' },+ document_type: 'invoice',+ direction: 'receivable',+ origin: 'local',+ external_source: null,+ external_id: null,+ number: 12,+ series: null,+ external_number: null,+ status: 'open',+ state: 'paid',+ issue_date: '2026-01-05',+ due_date: '2026-01-15',+ competence_date: '2026-01-05',+ sent_at: null,+ currency: 'USD',+ subtotal: '3000.00',+ discount: '0.00',+ tax_total: '0.00',+ total: '3000.00',+ amount_paid: '3000.00',+ balance: '0.00',+ days_overdue: 0,+ notes: null,+ internal_notes: null,+ custom_fields: null,+ snapshot: null,+ share_token: null,+ schedule_id: 'sched-1',+ schedule: { id: 'sched-1', name: 'Plano Pro', frequency: 'monthly', status: 'active' },+ sequence: 1,+ period_start: '2026-01-05',+ period_end: '2026-02-04',+ lines: [],+ allocations: [],+ created_at: '2026-01-05T00:00:00Z',+ ...overrides,+ }+}++function render() {+ return renderWithProviders(<InvoiceScheduleDetailPage />, {+ route: '/invoices/schedules/sched-1',+ path: '/invoices/schedules/:id',+ })+}++describe('InvoiceScheduleDetailPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ canWrite = true+ api.invoiceSchedules.get.mockResolvedValue(schedule())+ api.invoiceSchedules.invoices.mockResolvedValue([+ invoice(),+ invoice({ id: 'inv-2', number: 13, state: 'overdue', days_overdue: 20, sequence: 2,+ period_start: '2026-02-05', period_end: '2026-03-04', due_date: '2026-02-15', amount_paid: '0.00', balance: '3000.00' }),+ ])+ api.invoiceSchedules.periods.mockResolvedValue([])+ api.invoices.settings.mockResolvedValue({ default_payment_terms_days: 30, tax_fields: 'hidden', number_prefix: 'INV-' })+ api.invoices.list.mockResolvedValue([])+ api.payees.list.mockResolvedValue([])+ })++ it('shows the derived figures and flags the late invoice', async () => {+ render()+ expect(await screen.findByText('Plano Pro')).toBeInTheDocument()+ expect(screen.getByText('$6,000.00')).toBeInTheDocument()+ expect(screen.getByText(t('invoices.schedules.figure.pastDue', { count: 1 }))).toBeInTheDocument()+ expect(screen.getByTestId('schedule-state-past_due')).toBeInTheDocument()+ })++ it('lists the price history with the current and the upcoming term', async () => {+ render()+ await screen.findByText('Plano Pro')+ const rows = within(screen.getByTestId('schedule-terms')).getAllByTestId('schedule-term-row')+ expect(rows).toHaveLength(2)+ expect(within(rows[0]).getByText(t('invoices.schedules.terms.current'))).toBeInTheDocument()+ expect(within(rows[0]).getByText('$3,000.00')).toBeInTheDocument()+ expect(within(rows[1]).getByText(t('invoices.schedules.terms.upcoming'))).toBeInTheDocument()+ expect(within(rows[1]).getByText('$3,500.00')).toBeInTheDocument()+ // Only the upcoming term may be touched; the current one is history.+ expect(within(rows[0]).queryByLabelText(t('common.edit'))).not.toBeInTheDocument()+ expect(within(rows[1]).getByLabelText(t('common.edit'))).toBeInTheDocument()+ })++ it('lists every invoice by its period, newest first', async () => {+ render()+ await screen.findByText('Plano Pro')+ const rows = screen.getAllByTestId('schedule-invoice-row')+ expect(rows).toHaveLength(2)+ expect(within(rows[0]).getByText('INV-13')).toBeInTheDocument()+ expect(within(rows[0]).getByTestId('invoice-state-overdue')).toBeInTheDocument()+ expect(within(rows[1]).getByText('INV-12')).toBeInTheDocument()+ expect(within(rows[1]).getByText(/Jan 5/)).toBeInTheDocument()+ })++ it('offers the actions an active agreement has, and hides them from a viewer', async () => {+ const { user } = render()+ await screen.findByText('Plano Pro')+ expect(screen.getByTestId('schedule-generate')).toBeInTheDocument()+ expect(screen.getByTestId('schedule-change-price')).toBeInTheDocument()+ await user.click(screen.getByTestId('schedule-more-actions'))+ expect(await screen.findByTestId('schedule-pause')).toBeInTheDocument()+ expect(screen.getByTestId('schedule-end')).toBeInTheDocument()+ // Two invoices were issued under it, so it cannot be deleted.+ expect(screen.queryByTestId('schedule-delete')).not.toBeInTheDocument()+ })++ it('shows nothing to press to a viewer', async () => {+ canWrite = false+ render()+ await screen.findByText('Plano Pro')+ expect(screen.queryByTestId('schedule-generate')).not.toBeInTheDocument()+ expect(screen.queryByTestId('schedule-more-actions')).not.toBeInTheDocument()+ expect(screen.queryByTestId('schedule-link-invoice')).not.toBeInTheDocument()+ })++ it('reads an ended agreement as history: when, why, and nothing to emit', async () => {+ api.invoiceSchedules.get.mockResolvedValue(+ schedule({ status: 'ended', ended_at: '2026-09-01', end_reason: 'canceled_by_client', next_period_start: null, monthly_amount: '0.00' }),+ )+ render()+ await screen.findByText('Plano Pro')+ expect(screen.getByTestId('schedule-state-ended')).toBeInTheDocument()+ expect(screen.getByTestId('schedule-ended-line')).toHaveTextContent(t('invoices.schedules.endReason.canceled_by_client'))+ expect(screen.queryByTestId('schedule-generate')).not.toBeInTheDocument()+ expect(screen.queryByTestId('schedule-change-price')).not.toBeInTheDocument()+ expect(screen.queryByTestId('schedule-more-actions')).not.toBeInTheDocument()+ })++ it('warns loudly when the job paused the agreement after failures', async () => {+ api.invoiceSchedules.get.mockResolvedValue(schedule({ status: 'paused', pause_reason: 'failures' }))+ render()+ await screen.findByText('Plano Pro')+ expect(screen.getByTestId('schedule-state-paused_failures')).toBeInTheDocument()+ expect(screen.getByText(t('invoices.schedules.pausedByFailures'))).toBeInTheDocument()+ })++ it('records the price change with the next period as the default date', async () => {+ api.invoiceSchedules.addTerm.mockResolvedValue(schedule())+ const { user } = render()+ await screen.findByText('Plano Pro')+ await user.click(screen.getByTestId('schedule-change-price'))+ expect(await screen.findByTestId('term-from-input')).toHaveValue('2026-03-05')+ await user.clear(screen.getByTestId('invoice-line-price-0'))+ await user.type(screen.getByTestId('invoice-line-price-0'), '3200')+ expect(screen.getByTestId('term-monthly-preview')).toHaveTextContent('$3,200.00')+ await user.click(screen.getByTestId('term-save'))+ expect(api.invoiceSchedules.addTerm).toHaveBeenCalledWith('sched-1', {+ effective_from: '2026-03-05',+ lines: [{ description: 'Retainer', quantity: '1', unit_price: '3200' }],+ discount: '0.00',+ })+ })+})diff --git a/frontend/src/pages/invoice-schedule-detail.tsx b/frontend/src/pages/invoice-schedule-detail.tsxnew file mode 100644index 00000000..1c1aba2e--- /dev/null+++ b/frontend/src/pages/invoice-schedule-detail.tsx@@ -0,0 +1,902 @@+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useNavigate, useParams } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import {+ ArrowLeft, Ban, Link2, MoreHorizontal, Pause, Pencil, Play, Plus, Receipt,+ Repeat, Trash2, Zap,+} from 'lucide-react'+import { toast } from 'sonner'++import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { PageHeader } from '@/components/page-header'+import { IconAction, SectionCard, SectionHeader, StateBadge, TH } from '@/components/invoice-ui'+import { EndConditionFields, ScheduleBadge } from '@/components/invoice-schedule-ui'+import { InvoiceLineEditor } from '@/components/invoice-line-editor'+import { cn } from '@/lib/utils'+import { formatCurrency } from '@/lib/format'+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'+import { usePrivacyMode } from '@/hooks/use-privacy-mode'+import { useWorkspace } from '@/contexts/workspace-context'+import { invoiceSchedules as schedulesApi, invoices as invoicesApi, payees as payeesApi } from '@/lib/api'+import { displayNumber, invoiceErrorKey, linesTotal } from '@/lib/invoice-utils'+import {+ FREQUENCIES,+ endPayload,+ isUpcomingTerm,+ localToday,+ monthlyEquivalent,+ periodLabel,+ scheduleActions,+} from '@/lib/invoice-schedule-utils'+import type {+ InvoiceLineInput,+ InvoiceSchedule,+ InvoiceScheduleEndReason,+ InvoiceScheduleEndType,+ InvoiceScheduleFrequency,+ InvoiceScheduleTerm,+} from '@/types'++/**+ * One agreement: what it is worth, what it has produced, and the price+ * over time.+ *+ * Two sections carry the design. **Terms** is the price as a history:+ * a raise recorded today for January sits there as an upcoming row and+ * changes nothing until then. **Invoices** is the money: every period+ * that was billed, born from the job or linked by hand, each an+ * ordinary invoice that knows which period it answers for.+ */+export default function InvoiceScheduleDetailPage() {+ const { t } = useTranslation()+ const { id = '' } = useParams()+ const navigate = useNavigate()+ const queryClient = useQueryClient()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const { mask } = usePrivacyMode()+ const { canWrite } = useWorkspace()++ const [editOpen, setEditOpen] = useState(false)+ const [endOpen, setEndOpen] = useState(false)+ const [linkOpen, setLinkOpen] = useState(false)+ const [termTarget, setTermTarget] = useState<InvoiceScheduleTerm | 'new' | null>(null)++ const { data: schedule, isLoading } = useQuery({+ queryKey: ['invoice-schedule', id],+ queryFn: () => schedulesApi.get(id),+ enabled: Boolean(id),+ })+ const { data: invoices = [] } = useQuery({+ queryKey: ['invoice-schedule-invoices', id],+ queryFn: () => schedulesApi.invoices(id),+ enabled: Boolean(id),+ })+ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ })++ const refresh = () => {+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule', id] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-invoices', id] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-periods', id] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-summary'] })+ void queryClient.invalidateQueries({ queryKey: ['invoices'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-summary'] })+ }++ const onError = (error: unknown) => {+ const key = invoiceErrorKey(error)+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ }+ const decision = (run: () => Promise<unknown>, successKey: string) => ({+ mutationFn: run,+ onSuccess: () => {+ toast.success(t(successKey))+ refresh()+ },+ onError,+ })++ const pauseMutation = useMutation(decision(() => schedulesApi.pause(id), 'invoices.schedules.paused'))+ const resumeMutation = useMutation(decision(() => schedulesApi.resume(id), 'invoices.schedules.resumed'))+ const generateMutation = useMutation({+ mutationFn: () => schedulesApi.generate(id),+ onSuccess: (emitted) => {+ toast.success(t('invoices.schedules.generated', { count: emitted.length }))+ refresh()+ if (emitted.length === 1) navigate(`/invoices/${emitted[0].id}`)+ },+ onError,+ })+ const deleteMutation = useMutation({+ mutationFn: () => schedulesApi.remove(id),+ onSuccess: () => {+ toast.success(t('invoices.schedules.deleted'))+ refresh()+ navigate('/invoices/schedules')+ },+ onError,+ })+ const removeTermMutation = useMutation({+ mutationFn: (termId: string) => schedulesApi.removeTerm(id, termId),+ onSuccess: () => {+ toast.success(t('invoices.schedules.termRemoved'))+ refresh()+ },+ onError,+ })++ const sortedTerms = useMemo(+ () => (schedule ? [...schedule.terms].sort((a, b) => a.effective_from.localeCompare(b.effective_from)) : []),+ [schedule],+ )++ if (isLoading || !schedule) {+ return (+ <div>+ <Skeleton className="h-4 w-28 mb-6" />+ <Skeleton className="h-40 w-full rounded-xl" />+ </div>+ )+ }++ const actions = scheduleActions(schedule)+ // An ended agreement with invoices under it has no decision left to+ // take, and an empty menu is worse than none.+ const hasMenu =+ actions.canEdit || actions.canPause || actions.canResume || actions.canEnd || actions.canDelete+ const money = (value: string | number | null | undefined) =>+ mask(formatCurrency(Number(value ?? 0), schedule.currency, locale))+ const showDate = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)+ const currentId = schedule.current_term?.id+ // The latest period already billed. A term governing it, or anything+ // before it, is history: the server refuses to change it, so the+ // buttons that would try are not offered.+ const billedUpTo = invoices.reduce<string | null>(+ (latest, inv) => (inv.period_start && (!latest || inv.period_start > latest) ? inv.period_start : latest),+ null,+ )++ return (+ <div>+ <button+ onClick={() => navigate('/invoices/schedules')}+ className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors mb-3"+ data-testid="schedule-back"+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ {t('invoices.schedules.backToList')}+ </button>++ <PageHeader+ section={schedule.payee?.name ?? t('invoices.noClient')}+ title={schedule.name}+ action={+ canWrite ? (+ <div className="flex flex-wrap items-center gap-2">+ {actions.canChangePrice && (+ <Button size="sm" variant="outline" onClick={() => setTermTarget('new')} data-testid="schedule-change-price">+ <Pencil className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.action.changePrice')}+ </Button>+ )}+ {actions.canGenerate && (+ <Button+ size="sm"+ onClick={() => generateMutation.mutate()}+ disabled={generateMutation.isPending}+ data-testid="schedule-generate"+ >+ <Zap className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.action.generate')}+ </Button>+ )}+ {hasMenu && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t('invoices.moreActions')}+ data-testid="schedule-more-actions"+ className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-border/80 bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ >+ <MoreHorizontal className="h-4 w-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-[220px] p-1 bg-card border border-border rounded-xl shadow-md">+ {actions.canEdit && (+ <DropdownMenuItem onClick={() => setEditOpen(true)} data-testid="schedule-edit" className="gap-2 text-sm">+ <Pencil className="h-4 w-4 text-muted-foreground" />+ {t('common.edit')}+ </DropdownMenuItem>+ )}+ {actions.canPause && (+ <DropdownMenuItem onClick={() => pauseMutation.mutate()} data-testid="schedule-pause" className="gap-2 text-sm">+ <Pause className="h-4 w-4 text-muted-foreground" />+ {t('invoices.schedules.action.pause')}+ </DropdownMenuItem>+ )}+ {actions.canResume && (+ <DropdownMenuItem onClick={() => resumeMutation.mutate()} data-testid="schedule-resume" className="gap-2 text-sm">+ <Play className="h-4 w-4 text-muted-foreground" />+ {t('invoices.schedules.action.resume')}+ </DropdownMenuItem>+ )}+ {actions.canEnd && (+ <DropdownMenuItem onClick={() => setEndOpen(true)} data-testid="schedule-end" className="gap-2 text-sm text-destructive focus:text-destructive">+ <Ban className="h-4 w-4" />+ {t('invoices.schedules.action.end')}+ </DropdownMenuItem>+ )}+ {actions.canDelete && (+ <DropdownMenuItem onClick={() => deleteMutation.mutate()} data-testid="schedule-delete" className="gap-2 text-sm text-destructive focus:text-destructive">+ <Trash2 className="h-4 w-4" />+ {t('common.delete')}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ ) : undefined+ }+ />++ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 mb-5 text-xs text-muted-foreground">+ <ScheduleBadge schedule={schedule} />+ <span className="inline-flex items-center gap-1">+ <Repeat className="h-3 w-3" />+ {t(`invoices.schedules.frequency.${schedule.frequency}`)}+ </span>+ <span>{t('invoices.schedules.since', { date: showDate(schedule.start_date) })}</span>+ {schedule.end_type === 'on_date' && schedule.end_date && (+ <span>{t('invoices.schedules.untilDate', { date: showDate(schedule.end_date) })}</span>+ )}+ {schedule.end_type === 'after_count' && schedule.end_count && (+ <span>{t('invoices.schedules.untilCount', { count: schedule.end_count })}</span>+ )}+ {schedule.status === 'ended' && schedule.ended_at && schedule.end_reason && (+ <span data-testid="schedule-ended-line">+ {t('invoices.schedules.endedOn', {+ date: showDate(schedule.ended_at),+ reason: t(`invoices.schedules.endReason.${schedule.end_reason}`),+ })}+ </span>+ )}+ {schedule.status === 'paused' && schedule.pause_reason === 'failures' && (+ <span className="text-rose-500 font-medium">{t('invoices.schedules.pausedByFailures')}</span>+ )}+ </div>++ <div className="space-y-5">+ <SectionCard>+ <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-border">+ {[+ { label: t('invoices.schedules.column.monthly'), value: money(schedule.monthly_amount) },+ { label: t('invoices.schedules.figure.invoiced'), value: money(schedule.amount_invoiced) },+ { label: t('invoices.schedules.figure.paid'), value: money(schedule.amount_paid) },+ {+ label: t('invoices.schedules.column.next'),+ value:+ schedule.status === 'active' && schedule.next_period_start+ ? showDate(schedule.next_period_start)+ : '—',+ tone: schedule.past_due_count > 0 ? 'text-amber-600' : undefined,+ hint:+ schedule.past_due_count > 0+ ? t('invoices.schedules.figure.pastDue', { count: schedule.past_due_count })+ : undefined,+ },+ ].map((figure) => (+ <div key={figure.label} className="px-4 sm:px-5 py-4">+ <p className="text-xs font-medium text-muted-foreground mb-0.5">{figure.label}</p>+ <p className={cn('text-lg font-semibold tracking-tight tabular-nums', 'tone' in figure && figure.tone)}>+ {figure.value}+ </p>+ {'hint' in figure && figure.hint && (+ <p className="text-[11px] text-amber-600">{figure.hint}</p>+ )}+ </div>+ ))}+ </div>+ </SectionCard>++ <SectionCard>+ <SectionHeader+ title={t('invoices.schedules.terms.title')}+ description={t('invoices.schedules.terms.description')}+ />+ <div className="divide-y divide-border" data-testid="schedule-terms">+ {sortedTerms.map((term) => {+ const upcoming = isUpcomingTerm(term.effective_from)+ const editable = upcoming && (!billedUpTo || term.effective_from > billedUpTo)+ const isCurrent = term.id === currentId+ return (+ <div key={term.id} className="flex items-center gap-3 px-4 sm:px-5 py-3" data-testid="schedule-term-row">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm font-medium tabular-nums">+ {t('invoices.schedules.terms.from', { date: showDate(term.effective_from) })}+ </span>+ {isCurrent && (+ <span className="text-[11px] font-semibold px-2 py-0.5 rounded-full border bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20">+ {t('invoices.schedules.terms.current')}+ </span>+ )}+ {upcoming && (+ <span className="text-[11px] font-semibold px-2 py-0.5 rounded-full border bg-muted text-muted-foreground border-border">+ {t('invoices.schedules.terms.upcoming')}+ </span>+ )}+ </div>+ <p className="text-xs text-muted-foreground truncate">+ {term.lines.map((line) => line.description).join(' · ')}+ </p>+ </div>+ <div className="text-right">+ <p className="text-sm font-bold tabular-nums">{money(term.total)}</p>+ <p className="text-[11px] text-muted-foreground tabular-nums">+ {t('invoices.schedules.terms.perMonth', {+ amount: money(monthlyEquivalent(Number(term.total), schedule.frequency)),+ })}+ </p>+ </div>+ {canWrite && editable && schedule.status !== 'ended' && (+ <div className="flex items-center gap-1">+ <IconAction onClick={() => setTermTarget(term)} label={t('common.edit')}>+ <Pencil className="h-3.5 w-3.5" />+ </IconAction>+ {sortedTerms.length > 1 && (+ <IconAction onClick={() => removeTermMutation.mutate(term.id)} label={t('common.delete')}>+ <Trash2 className="h-3.5 w-3.5" />+ </IconAction>+ )}+ </div>+ )}+ </div>+ )+ })}+ </div>+ </SectionCard>++ <SectionCard>+ <SectionHeader+ title={t('invoices.schedules.invoices.title')}+ description={t('invoices.schedules.invoices.description')}+ action={+ canWrite && schedule.status !== 'ended' ? (+ <Button size="sm" variant="outline" onClick={() => setLinkOpen(true)} data-testid="schedule-link-invoice">+ <Link2 className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.action.linkInvoice')}+ </Button>+ ) : undefined+ }+ />+ {invoices.length === 0 ? (+ <div className="px-5 py-10 text-center" data-testid="schedule-invoices-empty">+ <Receipt className="h-7 w-7 mx-auto text-muted-foreground/50" />+ <p className="mt-3 text-sm text-muted-foreground max-w-sm mx-auto">+ {schedule.status === 'active' && schedule.next_period_start+ ? t('invoices.schedules.invoices.emptyNext', { date: showDate(schedule.next_period_start) })+ : t('invoices.schedules.invoices.empty')}+ </p>+ </div>+ ) : (+ <div className="overflow-x-auto">+ <table className="w-full">+ <thead>+ <tr className="border-b border-border">+ <th className={`${TH} pl-4 sm:pl-5 text-left`}>{t('invoices.schedules.column.period')}</th>+ <th className={`${TH} text-left w-24 hidden sm:table-cell`}>{t('invoices.column.number')}</th>+ <th className={`${TH} text-left w-32 hidden md:table-cell`}>{t('invoices.column.due')}</th>+ <th className={`${TH} text-right w-32`}>{t('invoices.column.total')}</th>+ <th className={`${TH} pr-4 sm:pr-5 text-right w-28`}>{t('invoices.column.state')}</th>+ </tr>+ </thead>+ <tbody>+ {[...invoices]+ .sort((a, b) => (b.sequence ?? 0) - (a.sequence ?? 0))+ .map((invoice) => (+ <tr+ key={invoice.id}+ onClick={() => navigate(`/invoices/${invoice.id}`)}+ data-testid="schedule-invoice-row"+ className="border-b border-border last:border-0 hover:bg-muted transition-colors cursor-pointer"+ >+ <td className="py-3 pl-4 sm:pl-5 text-sm tabular-nums">+ {invoice.period_start && invoice.period_end+ ? periodLabel(invoice.period_start, invoice.period_end, dateLocale)+ : showDate(invoice.issue_date)}+ </td>+ <td className="py-3 text-xs text-muted-foreground tabular-nums hidden sm:table-cell">+ {displayNumber(invoice, settings?.number_prefix) ?? t('invoices.noNumber')}+ </td>+ <td className="py-3 text-xs text-muted-foreground tabular-nums hidden md:table-cell">+ {showDate(invoice.due_date)}+ </td>+ <td className="py-3 text-right text-sm tabular-nums">{money(invoice.total)}</td>+ <td className="py-3 pr-4 sm:pr-5 text-right">+ <StateBadge state={invoice.state} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </SectionCard>+ </div>++ <EditScheduleDialog+ key={editOpen ? 'open' : 'closed'}+ open={editOpen}+ onOpenChange={setEditOpen}+ schedule={schedule}+ onSaved={refresh}+ />+ <EndScheduleDialog+ key={endOpen ? 'end-open' : 'end-closed'}+ open={endOpen}+ onOpenChange={setEndOpen}+ schedule={schedule}+ onEnded={refresh}+ />+ <TermDialog+ key={termTarget === null ? 'term-closed' : termTarget === 'new' ? 'term-new' : termTarget.id}+ open={termTarget !== null}+ onOpenChange={(open) => !open && setTermTarget(null)}+ schedule={schedule}+ term={termTarget === 'new' ? null : termTarget}+ onSaved={refresh}+ />+ <LinkInvoiceDialog+ key={linkOpen ? 'link-open' : 'link-closed'}+ open={linkOpen}+ onOpenChange={setLinkOpen}+ schedule={schedule}+ onLinked={refresh}+ />+ </div>+ )+}++function useScheduleError() {+ const { t } = useTranslation()+ return (error: unknown) => {+ const key = invoiceErrorKey(error)+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ }+}++function EditScheduleDialog({+ open,+ onOpenChange,+ schedule,+ onSaved,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ schedule: InvoiceSchedule+ onSaved: () => void+}) {+ const { t } = useTranslation()+ const onError = useScheduleError()+ const { data: clients = [] } = useQuery({+ queryKey: ['payees', 'for-invoice'],+ queryFn: () => payeesApi.list({}),+ enabled: open,+ })+ const [name, setName] = useState(schedule.name)+ const [payeeId, setPayeeId] = useState(schedule.payee_id ?? '')+ const [frequency, setFrequency] = useState<InvoiceScheduleFrequency>(schedule.frequency)+ const [startDate, setStartDate] = useState(schedule.start_date)+ const [endType, setEndType] = useState<InvoiceScheduleEndType>(schedule.end_type)+ const [endDate, setEndDate] = useState(schedule.end_date ?? '')+ const [endCount, setEndCount] = useState(schedule.end_count ? String(schedule.end_count) : '')+ const [paymentTerms, setPaymentTerms] = useState(+ schedule.payment_terms_days === null ? '' : String(schedule.payment_terms_days),+ )+ const [notes, setNotes] = useState(schedule.notes ?? '')+ // The calendar is fixed once anything was billed: moving the anchor+ // would change what period every existing invoice was for.+ const calendarLocked = schedule.invoice_count > 0++ const mutation = useMutation({+ mutationFn: () =>+ schedulesApi.update(schedule.id, {+ name,+ payee_id: payeeId || null,+ ...(calendarLocked ? {} : { frequency, start_date: startDate }),+ ...endPayload(endType, endDate, endCount),+ payment_terms_days: paymentTerms ? Number(paymentTerms) : null,+ notes: notes || null,+ }),+ onSuccess: () => {+ toast.success(t('invoices.schedules.saved'))+ onOpenChange(false)+ onSaved()+ },+ onError,+ })++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('invoices.schedules.editTitle')}</DialogTitle>+ <DialogDescription>+ {calendarLocked+ ? t('invoices.schedules.editLockedDescription')+ : t('invoices.schedules.editDescription')}+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label htmlFor="edit-schedule-name">{t('invoices.schedules.field.name')}</Label>+ <Input id="edit-schedule-name" data-testid="edit-schedule-name" value={name} onChange={(e) => setName(e.target.value)} />+ </div>+ <div className="space-y-1.5">+ <Label>{t('invoices.field.client')}</Label>+ <Select value={payeeId} onValueChange={setPayeeId}>+ <SelectTrigger data-testid="edit-schedule-client">+ <SelectValue placeholder={t('invoices.field.clientPlaceholder')} />+ </SelectTrigger>+ <SelectContent>+ {clients.map((client) => (+ <SelectItem key={client.id} value={client.id}>{client.name}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="grid grid-cols-3 gap-3">+ <div className="space-y-1.5">+ <Label>{t('invoices.schedules.field.frequency')}</Label>+ <Select value={frequency} onValueChange={(v) => setFrequency(v as InvoiceScheduleFrequency)} disabled={calendarLocked}>+ <SelectTrigger data-testid="edit-schedule-frequency"><SelectValue /></SelectTrigger>+ <SelectContent>+ {FREQUENCIES.map((value) => (+ <SelectItem key={value} value={value}>{t(`invoices.schedules.frequency.${value}`)}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="edit-schedule-start">{t('invoices.schedules.field.startDate')}</Label>+ <Input id="edit-schedule-start" type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} disabled={calendarLocked} />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="edit-schedule-terms">{t('invoices.schedules.field.paymentTerms')}</Label>+ <Input id="edit-schedule-terms" type="number" min={0} value={paymentTerms} onChange={(e) => setPaymentTerms(e.target.value)} />+ </div>+ </div>+ <EndConditionFields+ idPrefix="edit-schedule"+ endType={endType}+ endDate={endDate}+ endCount={endCount}+ onChange={(next) => { setEndType(next.endType); setEndDate(next.endDate); setEndCount(next.endCount) }}+ />+ <div className="space-y-1.5">+ <Label htmlFor="edit-schedule-notes">{t('invoices.field.notes')}</Label>+ <Input id="edit-schedule-notes" value={notes} onChange={(e) => setNotes(e.target.value)} />+ </div>+ </div>+ <DialogFooter className="gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>+ <Button onClick={() => mutation.mutate()} disabled={!name.trim() || mutation.isPending} data-testid="edit-schedule-save">+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++const END_REASONS: InvoiceScheduleEndReason[] = ['canceled_by_client', 'canceled_by_us', 'completed', 'unpaid', 'other']++function EndScheduleDialog({+ open,+ onOpenChange,+ schedule,+ onEnded,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ schedule: InvoiceSchedule+ onEnded: () => void+}) {+ const { t } = useTranslation()+ const onError = useScheduleError()+ const [reason, setReason] = useState<InvoiceScheduleEndReason>('canceled_by_client')+ const [endedAt, setEndedAt] = useState(() => localToday())+ const mutation = useMutation({+ mutationFn: () => schedulesApi.end(schedule.id, { reason, ended_at: endedAt }),+ onSuccess: () => {+ toast.success(t('invoices.schedules.ended'))+ onOpenChange(false)+ onEnded()+ },+ onError,+ })+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('invoices.schedules.endTitle')}</DialogTitle>+ {/* Why it ended is the one fact no invoice can record, and the+ whole reason this is a dialog rather than a button. */}+ <DialogDescription>{t('invoices.schedules.endDescription')}</DialogDescription>+ </DialogHeader>+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label>{t('invoices.schedules.field.endReason')}</Label>+ <Select value={reason} onValueChange={(v) => setReason(v as InvoiceScheduleEndReason)}>+ <SelectTrigger data-testid="end-schedule-reason"><SelectValue /></SelectTrigger>+ <SelectContent>+ {END_REASONS.map((value) => (+ <SelectItem key={value} value={value}>{t(`invoices.schedules.endReason.${value}`)}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="end-schedule-date">{t('invoices.schedules.field.endedAt')}</Label>+ <Input id="end-schedule-date" data-testid="end-schedule-date" type="date" value={endedAt} onChange={(e) => setEndedAt(e.target.value)} />+ </div>+ </div>+ <DialogFooter className="gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>+ <Button variant="destructive" onClick={() => mutation.mutate()} disabled={mutation.isPending} data-testid="end-schedule-confirm">+ {t('invoices.schedules.action.end')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++function TermDialog({+ open,+ onOpenChange,+ schedule,+ term,+ onSaved,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ schedule: InvoiceSchedule+ /** Null creates a new term: the "change price" door. */+ term: InvoiceScheduleTerm | null+ onSaved: () => void+}) {+ const { t } = useTranslation()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const onError = useScheduleError()+ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ enabled: open,+ })+ const source = term ?? schedule.next_term ?? schedule.current_term+ const [effectiveFrom, setEffectiveFrom] = useState(+ term?.effective_from ?? schedule.next_period_start ?? localToday(),+ )+ const [lines, setLines] = useState<InvoiceLineInput[]>(+ source ? source.lines.map((line) => ({ ...line })) : [{ description: '', quantity: '1', unit_price: '0' }],+ )+ const [discount, setDiscount] = useState(source?.discount ?? '')++ const perPeriod = linesTotal(lines) - Number(discount || 0)+ const mutation = useMutation({+ mutationFn: () => {+ const payload = { effective_from: effectiveFrom, lines, discount: discount || null }+ return term+ ? schedulesApi.updateTerm(schedule.id, term.id, payload)+ : schedulesApi.addTerm(schedule.id, payload)+ },+ onSuccess: () => {+ toast.success(t('invoices.schedules.termSaved'))+ onOpenChange(false)+ onSaved()+ },+ onError,+ })++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="flex flex-col max-h-[calc(100dvh-2rem)] sm:max-w-3xl">+ <DialogHeader>+ <DialogTitle>+ {term ? t('invoices.schedules.terms.editTitle') : t('invoices.schedules.action.changePrice')}+ </DialogTitle>+ {/* No proration, by design: the change applies from the first+ period starting on or after the date. The description says+ so, because the alternative is someone expecting a mid-month+ difference to appear on its own. */}+ <DialogDescription>{t('invoices.schedules.terms.changeDescription')}</DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label htmlFor="term-from">{t('invoices.schedules.terms.effectiveFrom')}</Label>+ <Input id="term-from" data-testid="term-from-input" type="date" value={effectiveFrom} onChange={(e) => setEffectiveFrom(e.target.value)} />+ {schedule.next_period_start && (+ <p className="text-[11px] text-muted-foreground">+ {t('invoices.schedules.terms.nextPeriodHint', {+ date: new Date(`${schedule.next_period_start}T00:00:00`).toLocaleDateString(dateLocale),+ })}+ </p>+ )}+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="term-discount">{t('invoices.schedules.terms.discount')}</Label>+ <Input id="term-discount" data-testid="term-discount-input" inputMode="decimal" value={discount} onChange={(e) => setDiscount(e.target.value)} placeholder="0.00" />+ </div>+ </div>+ <InvoiceLineEditor+ lines={lines}+ onChange={setLines}+ currency={schedule.currency}+ showTax={(settings?.tax_fields ?? 'hidden') !== 'hidden'}+ required+ />+ <p className="text-xs text-muted-foreground" data-testid="term-monthly-preview">+ {t('invoices.schedules.terms.preview', {+ period: formatCurrency(perPeriod, schedule.currency, locale),+ monthly: formatCurrency(monthlyEquivalent(perPeriod, schedule.frequency), schedule.currency, locale),+ })}+ </p>+ </div>+ <DialogFooter className="gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>+ <Button onClick={() => mutation.mutate()} disabled={perPeriod <= 0 || !effectiveFrom || mutation.isPending} data-testid="term-save">+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++function LinkInvoiceDialog({+ open,+ onOpenChange,+ schedule,+ onLinked,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ schedule: InvoiceSchedule+ onLinked: () => void+}) {+ const { t } = useTranslation()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const { mask } = usePrivacyMode()+ const onError = useScheduleError()+ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ enabled: open,+ })+ const { data: periods = [] } = useQuery({+ queryKey: ['invoice-schedule-periods', schedule.id],+ queryFn: () => schedulesApi.periods(schedule.id, 3),+ enabled: open,+ })+ // Same client, same currency, not yet part of any agreement: the+ // only invoices that could answer for a period of this one.+ const { data: candidates = [] } = useQuery({+ queryKey: ['invoices', 'linkable', schedule.id],+ queryFn: () =>+ invoicesApi.list({+ ...(schedule.payee_id ? { payee_id: schedule.payee_id } : {}),+ limit: 500,+ }),+ select: (rows) =>+ rows.filter(+ (invoice) =>+ !invoice.schedule_id && invoice.status !== 'void' && invoice.currency === schedule.currency,+ ),+ enabled: open,+ })+ const [invoiceId, setInvoiceId] = useState('')+ const [periodStart, setPeriodStart] = useState('')+ const free = periods.filter((p) => !p.taken)++ const mutation = useMutation({+ mutationFn: () => schedulesApi.link(schedule.id, { invoice_id: invoiceId, period_start: periodStart }),+ onSuccess: () => {+ toast.success(t('invoices.schedules.linked'))+ onOpenChange(false)+ onLinked()+ },+ onError,+ })++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('invoices.schedules.linkTitle')}</DialogTitle>+ <DialogDescription>{t('invoices.schedules.linkDescription')}</DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label>{t('invoices.schedules.field.invoice')}</Label>+ <Select value={invoiceId} onValueChange={setInvoiceId}>+ <SelectTrigger data-testid="link-invoice-select">+ <SelectValue placeholder={t('invoices.schedules.field.invoicePlaceholder')} />+ </SelectTrigger>+ <SelectContent>+ {candidates.map((invoice) => (+ <SelectItem key={invoice.id} value={invoice.id}>+ {(displayNumber(invoice, settings?.number_prefix) ?? t('invoices.noNumber')) ++ ' · ' ++ new Date(`${invoice.issue_date}T00:00:00`).toLocaleDateString(dateLocale) ++ ' · ' ++ mask(formatCurrency(Number(invoice.total), invoice.currency, locale))}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ {candidates.length === 0 && (+ <p className="text-[11px] text-muted-foreground">{t('invoices.schedules.noCandidates')}</p>+ )}+ </div>+ <div className="space-y-1.5">+ <Label>{t('invoices.schedules.field.period')}</Label>+ <Select value={periodStart} onValueChange={setPeriodStart}>+ <SelectTrigger data-testid="link-period-select">+ <SelectValue placeholder={t('invoices.schedules.field.periodPlaceholder')} />+ </SelectTrigger>+ <SelectContent>+ {free.map((period) => (+ <SelectItem key={period.sequence} value={period.period_start}>+ {periodLabel(period.period_start, period.period_end, dateLocale)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>+ <DialogFooter className="gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>+ <Button onClick={() => mutation.mutate()} disabled={!invoiceId || !periodStart || mutation.isPending} data-testid="link-invoice-submit">+ <Plus className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.action.link')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/pages/invoice-schedules.test.tsx b/frontend/src/pages/invoice-schedules.test.tsxnew file mode 100644index 00000000..3488fc86--- /dev/null+++ b/frontend/src/pages/invoice-schedules.test.tsx@@ -0,0 +1,202 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, within } from '@testing-library/react'++import InvoiceSchedulesPage from '@/pages/invoice-schedules'+import { renderWithProviders, t } from '@/test/utils'+import type { InvoiceSchedule, InvoiceScheduleSummary } from '@/types'++const api = vi.hoisted(() => ({+ invoiceSchedules: {+ list: vi.fn(),+ summary: vi.fn(),+ create: vi.fn(),+ },+ invoices: { settings: vi.fn() },+ payees: { list: vi.fn() },+}))++vi.mock('@/lib/api', () => ({+ invoiceSchedules: api.invoiceSchedules,+ invoices: api.invoices,+ payees: api.payees,+}))++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++vi.mock('@/contexts/auth-context', () => ({+ useAuth: () => ({ user: { preferences: { currency_display: 'USD' } } }),+}))++let canWrite = true+vi.mock('@/contexts/workspace-context', () => ({+ useWorkspace: () => ({ canWrite }),+}))++vi.mock('@/hooks/use-privacy-mode', () => ({+ usePrivacyMode: () => ({ mask: (value: string) => value }),+}))++const term = {+ id: 'term-1',+ effective_from: '2026-01-05',+ lines: [{ description: 'Retainer', quantity: '1', unit_price: '3000.00' }],+ discount: '0.00',+ subtotal: '3000.00',+ tax_total: '0.00',+ total: '3000.00',+ created_at: '2026-01-01T00:00:00Z',+}++function schedule(overrides: Partial<InvoiceSchedule> = {}): InvoiceSchedule {+ return {+ id: 'sched-1',+ name: 'Plano Pro',+ payee_id: 'alpha',+ payee: { id: 'alpha', name: 'Cliente Alpha' },+ origin: 'local',+ external_source: null,+ external_id: null,+ status: 'active',+ pause_reason: null,+ ended_at: null,+ end_reason: null,+ frequency: 'monthly',+ start_date: '2026-01-05',+ end_type: 'never',+ end_date: null,+ end_count: null,+ payment_terms_days: null,+ currency: 'USD',+ notes: null,+ custom_fields: null,+ next_sequence: 10,+ last_generated_at: null,+ consecutive_failures: 0,+ terms: [term],+ created_at: '2026-01-01T00:00:00Z',+ current_term: term,+ next_term: term,+ monthly_amount: '3000.00',+ next_period_start: '2026-10-05',+ invoice_count: 9,+ amount_invoiced: '27000.00',+ amount_paid: '24000.00',+ past_due_count: 0,+ ...overrides,+ }+}++const summary: InvoiceScheduleSummary = {+ active_count: 2,+ paused_count: 1,+ ended_count: 1,+ by_currency: [+ {+ currency: 'USD',+ monthly_recurring: '3300.00',+ active_count: 2,+ ended_recently_count: 1,+ monthly_lost: '500.00',+ past_due_count: 1,+ },+ ],+}++describe('InvoiceSchedulesPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ canWrite = true+ api.invoiceSchedules.summary.mockResolvedValue(summary)+ api.invoiceSchedules.list.mockResolvedValue([+ schedule(),+ schedule({+ id: 'sched-2',+ name: 'Hosting',+ frequency: 'quarterly',+ monthly_amount: '300.00',+ past_due_count: 1,+ current_term: { ...term, id: 'term-2', total: '900.00' },+ }),+ schedule({+ id: 'sched-3',+ name: 'Old retainer',+ status: 'ended',+ ended_at: '2026-09-01',+ end_reason: 'canceled_by_client',+ monthly_amount: '0.00',+ next_period_start: null,+ }),+ ])+ api.invoices.settings.mockResolvedValue({ default_payment_terms_days: 30, tax_fields: 'hidden' })+ api.payees.list.mockResolvedValue([])+ })++ it('reads the financial summary the server derived', async () => {+ renderWithProviders(<InvoiceSchedulesPage />, { route: '/invoices/schedules' })+ const card = await screen.findByTestId('schedules-summary-USD')+ expect(within(card).getByText('$3,300.00')).toBeInTheDocument()+ expect(within(card).getByText('$39,600.00')).toBeInTheDocument()+ expect(within(card).getByText('$500.00')).toBeInTheDocument()+ expect(within(card).getByText(t('invoices.schedules.summary.endedRecently', { count: 1 }))).toBeInTheDocument()+ expect(within(card).getByText(t('invoices.schedules.summary.activeCount', { count: 2 }))).toBeInTheDocument()+ })++ it('lists every agreement with its cadence, monthly worth and state', async () => {+ renderWithProviders(<InvoiceSchedulesPage />, { route: '/invoices/schedules' })+ const rows = await screen.findAllByTestId('schedule-row')+ expect(rows).toHaveLength(3)++ const pro = rows[0]+ expect(within(pro).getByText('Plano Pro')).toBeInTheDocument()+ expect(within(pro).getByText('Cliente Alpha')).toBeInTheDocument()+ expect(within(pro).getByText('$3,000.00')).toBeInTheDocument()+ expect(within(pro).getByTestId('schedule-state-active')).toBeInTheDocument()++ // A late invoice outranks "active" on the pill: it is the thing to act on.+ const hosting = rows[1]+ expect(within(hosting).getByText(t('invoices.schedules.frequency.quarterly'), { exact: false })).toBeInTheDocument()+ expect(within(hosting).getByTestId('schedule-state-past_due')).toBeInTheDocument()++ // Ended agreements are worth nothing a month and have no next invoice.+ const old = rows[2]+ expect(within(old).getByTestId('schedule-state-ended')).toBeInTheDocument()+ expect(within(old).queryByText('$3,000.00')).not.toBeInTheDocument()+ })++ it('filters by status through the server, with counts from the summary', async () => {+ const { user } = renderWithProviders(<InvoiceSchedulesPage />, { route: '/invoices/schedules' })+ await screen.findAllByTestId('schedule-row')+ expect(screen.getByTestId('schedule-filter-all-count')).toHaveTextContent('4')+ expect(screen.getByTestId('schedule-filter-paused-count')).toHaveTextContent('1')++ await user.click(screen.getByTestId('schedule-filter-ended'))+ expect(api.invoiceSchedules.list).toHaveBeenLastCalledWith({ status: 'ended' })+ })++ it('offers to create only to a member who can write', async () => {+ canWrite = false+ renderWithProviders(<InvoiceSchedulesPage />, { route: '/invoices/schedules' })+ await screen.findAllByTestId('schedule-row')+ expect(screen.queryByTestId('schedule-new-button')).not.toBeInTheDocument()+ })++ it('previews the monthly worth while the agreement is being written', async () => {+ const { user } = renderWithProviders(<InvoiceSchedulesPage />, { route: '/invoices/schedules' })+ await screen.findAllByTestId('schedule-row')+ await user.click(screen.getByTestId('schedule-new-button'))+ await screen.findByTestId('schedule-name-input')++ // Submit stays off until there is a name and something to bill.+ expect(screen.getByTestId('schedule-create-submit')).toBeDisabled()+ await user.type(screen.getByTestId('schedule-name-input'), 'Retainer')+ await user.type(screen.getByTestId('invoice-line-description-0'), 'Monthly retainer')+ await user.clear(screen.getByTestId('invoice-line-price-0'))+ await user.type(screen.getByTestId('invoice-line-price-0'), '1200')++ expect(screen.getByTestId('schedule-monthly-preview')).toHaveTextContent('$1,200.00')+ expect(screen.getByTestId('schedule-create-submit')).toBeEnabled()+ })+})diff --git a/frontend/src/pages/invoice-schedules.tsx b/frontend/src/pages/invoice-schedules.tsxnew file mode 100644index 00000000..83d8aeb1--- /dev/null+++ b/frontend/src/pages/invoice-schedules.tsx@@ -0,0 +1,520 @@+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useNavigate } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { ArrowLeft, Plus, Repeat } from 'lucide-react'+import { toast } from 'sonner'++import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { PageHeader } from '@/components/page-header'+import { SectionCard, Segmented, TH } from '@/components/invoice-ui'+import { InvoiceLineEditor } from '@/components/invoice-line-editor'+import { EndConditionFields, ScheduleBadge } from '@/components/invoice-schedule-ui'+import { CurrencySelect } from '@/components/currency-select'+import { cn } from '@/lib/utils'+import { formatCurrency } from '@/lib/format'+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'+import { usePrivacyMode } from '@/hooks/use-privacy-mode'+import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'+import { invoiceSchedules as schedulesApi, invoices as invoicesApi, payees as payeesApi } from '@/lib/api'+import { invoiceErrorKey, linesTotal } from '@/lib/invoice-utils'+import { FREQUENCIES, endPayload, localToday, monthlyEquivalent } from '@/lib/invoice-schedule-utils'+import type {+ InvoiceLineInput,+ InvoiceSchedule,+ InvoiceScheduleEndType,+ InvoiceScheduleFrequency,+ InvoiceScheduleStatus,+} from '@/types'++/**+ * Recurring invoices: the agreements, what they are worth a month, and+ * which one needs a person.+ *+ * The summary is the financial reading of a subscription: what recurs,+ * what stopped recurring lately, and what is behind. All of it is+ * derived server-side from the invoices; nothing on this screen is a+ * number somebody typed.+ */+type Filter = 'all' | InvoiceScheduleStatus++export default function InvoiceSchedulesPage() {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const { mask } = usePrivacyMode()+ const { canWrite } = useWorkspace()++ const [filter, setFilter] = useState<Filter>('all')+ const [createOpen, setCreateOpen] = useState(false)++ const { data: summary } = useQuery({+ queryKey: ['invoice-schedule-summary'],+ queryFn: schedulesApi.summary,+ })+ const { data: list, isLoading } = useQuery({+ queryKey: ['invoice-schedules', filter],+ queryFn: () => schedulesApi.list(filter === 'all' ? undefined : { status: filter }),+ })++ const money = (value: string | number | null | undefined, code: string) =>+ mask(formatCurrency(Number(value ?? 0), code, locale))+ const showDate = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)++ const counts = useMemo(+ () =>+ summary+ ? {+ all: summary.active_count + summary.paused_count + summary.ended_count,+ active: summary.active_count,+ paused: summary.paused_count,+ ended: summary.ended_count,+ }+ : undefined,+ [summary],+ )++ return (+ <div>+ <button+ onClick={() => navigate('/invoices')}+ className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors mb-3"+ data-testid="schedules-back"+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ {t('invoices.backToList')}+ </button>++ <PageHeader+ section={t('invoices.title')}+ title={t('invoices.schedules.title')}+ action={+ canWrite ? (+ <Button size="sm" onClick={() => setCreateOpen(true)} data-testid="schedule-new-button">+ <Plus className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.new')}+ </Button>+ ) : undefined+ }+ />++ {/* One row per currency, in the invoices page's shape: the headline+ figure with what supports it beside it. An agreement in euros and+ one in reais never add up, so they never share a line. */}+ <div className="bg-card rounded-xl border border-border shadow-sm mb-5" data-testid="schedules-summary">+ {!summary ? (+ <div className="px-5 py-4">+ <Skeleton className="h-10 w-48" />+ </div>+ ) : summary.by_currency.length === 0 ? (+ <div className="px-5 py-4">+ <p className="text-xs font-medium text-muted-foreground mb-0.5">+ {t('invoices.schedules.summary.monthly')}+ </p>+ <p className="text-2xl font-semibold tracking-tight text-muted-foreground">+ {t('invoices.schedules.summary.none')}+ </p>+ </div>+ ) : (+ summary.by_currency.map((row) => (+ <div+ key={row.currency}+ className="grid grid-cols-2 sm:grid-cols-4 gap-y-3 px-5 py-4 border-b border-border last:border-0"+ data-testid={`schedules-summary-${row.currency}`}+ >+ <div className="col-span-2 sm:col-span-1">+ <p className="text-xs font-medium text-muted-foreground mb-0.5">+ {t('invoices.schedules.summary.monthly')}+ </p>+ <p className="text-2xl font-semibold tracking-tight tabular-nums">+ {money(row.monthly_recurring, row.currency)}+ </p>+ <p className="text-[11px] text-muted-foreground">+ {t('invoices.schedules.summary.activeCount', { count: row.active_count })}+ </p>+ </div>+ <Stat+ label={t('invoices.schedules.summary.yearly')}+ value={money(Number(row.monthly_recurring) * 12, row.currency)}+ />+ <Stat+ label={t('invoices.schedules.summary.lost')}+ value={money(row.monthly_lost, row.currency)}+ hint={t('invoices.schedules.summary.endedRecently', { count: row.ended_recently_count })}+ tone={Number(row.monthly_lost) > 0 ? 'text-rose-500' : undefined}+ />+ <Stat+ label={t('invoices.schedules.summary.pastDue')}+ value={String(row.past_due_count)}+ hint={t('invoices.schedules.summary.pastDueHint')}+ tone={row.past_due_count > 0 ? 'text-amber-600' : undefined}+ />+ </div>+ ))+ )}+ </div>++ <div className="mb-4">+ <Segmented<Filter>+ value={filter}+ onChange={setFilter}+ testIdPrefix="schedule-filter"+ options={(['all', 'active', 'paused', 'ended'] as const).map((value) => ({+ value,+ label: t(`invoices.schedules.filter.${value}`),+ count: counts?.[value],+ }))}+ />+ </div>++ <SectionCard>+ {isLoading ? (+ <div className="p-5 space-y-3">+ {[0, 1, 2].map((i) => (+ <Skeleton key={i} className="h-9 w-full" />+ ))}+ </div>+ ) : !list || list.length === 0 ? (+ <div className="px-5 py-14 text-center" data-testid="schedules-empty">+ <Repeat className="h-8 w-8 mx-auto text-muted-foreground/50" />+ <p className="mt-3 text-sm text-muted-foreground max-w-sm mx-auto">+ {filter === 'all'+ ? t('invoices.schedules.empty')+ : t('invoices.schedules.emptyFiltered')}+ </p>+ {filter === 'all' && canWrite && (+ <Button size="sm" className="mt-4" onClick={() => setCreateOpen(true)}>+ <Plus className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.new')}+ </Button>+ )}+ </div>+ ) : (+ <div className="overflow-x-auto">+ <table className="w-full">+ <thead>+ <tr className="border-b border-border">+ <th className={`${TH} pl-4 sm:pl-5 text-left`}>{t('invoices.schedules.column.name')}</th>+ <th className={`${TH} text-left hidden md:table-cell`}>+ {t('invoices.schedules.column.cadence')}+ </th>+ <th className={`${TH} text-right w-32 pr-6`}>{t('invoices.schedules.column.monthly')}</th>+ <th className={`${TH} text-left w-36 hidden sm:table-cell`}>+ {t('invoices.schedules.column.next')}+ </th>+ <th className={`${TH} text-right w-20 hidden lg:table-cell`}>+ {t('invoices.schedules.column.invoices')}+ </th>+ <th className={`${TH} pr-4 sm:pr-5 text-right w-28`}>+ {t('invoices.schedules.column.status')}+ </th>+ </tr>+ </thead>+ <tbody>+ {list.map((schedule) => (+ <tr+ key={schedule.id}+ onClick={() => navigate(`/invoices/schedules/${schedule.id}`)}+ data-testid="schedule-row"+ className="border-b border-border last:border-0 hover:bg-muted transition-colors cursor-pointer"+ >+ <td className="py-3 pl-4 sm:pl-5">+ <div className="text-sm font-medium text-foreground truncate">{schedule.name}</div>+ <div className="text-xs text-muted-foreground truncate">+ {schedule.payee?.name ?? t('invoices.noClient')}+ </div>+ </td>+ <td className="py-3 hidden md:table-cell text-xs text-muted-foreground">+ {t(`invoices.schedules.frequency.${schedule.frequency}`)}+ {(schedule.current_term ?? schedule.next_term) && (+ <span className="tabular-nums">+ {' · '}+ {money((schedule.current_term ?? schedule.next_term)!.total, schedule.currency)}+ </span>+ )}+ </td>+ <td className="py-3 pr-6 text-right text-sm font-bold tabular-nums">+ {schedule.status === 'active'+ ? money(schedule.monthly_amount, schedule.currency)+ : <span className="text-muted-foreground font-medium">—</span>}+ </td>+ <td className="py-3 hidden sm:table-cell text-xs text-muted-foreground tabular-nums">+ {schedule.status === 'active' && schedule.next_period_start+ ? showDate(schedule.next_period_start)+ : '—'}+ </td>+ <td className="py-3 text-right hidden lg:table-cell text-xs text-muted-foreground tabular-nums">+ {schedule.invoice_count}+ </td>+ <td className="py-3 pr-4 sm:pr-5 text-right">+ <ScheduleBadge schedule={schedule} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </SectionCard>++ <CreateScheduleDialog+ key={createOpen ? 'open' : 'closed'}+ open={createOpen}+ onOpenChange={setCreateOpen}+ onCreated={(schedule) => navigate(`/invoices/schedules/${schedule.id}`)}+ />+ </div>+ )+}++function Stat({+ label,+ value,+ hint,+ tone,+}: {+ label: string+ value: string+ hint?: string+ tone?: string+}) {+ return (+ <div>+ <p className="text-xs font-medium text-muted-foreground mb-0.5">{label}</p>+ <p className={cn('text-lg font-semibold tracking-tight tabular-nums', tone)}>{value}</p>+ {hint && <p className="text-[11px] text-muted-foreground">{hint}</p>}+ </div>+ )+}++function CreateScheduleDialog({+ open,+ onOpenChange,+ onCreated,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ onCreated: (schedule: InvoiceSchedule) => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const locale = useDisplayLocale()+ const { user } = useAuth()+ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ enabled: open,+ })+ const { data: clients = [] } = useQuery({+ queryKey: ['payees', 'for-invoice'],+ queryFn: () => payeesApi.list({}),+ enabled: open,+ })++ const [name, setName] = useState('')+ const [payeeId, setPayeeId] = useState('')+ const [frequency, setFrequency] = useState<InvoiceScheduleFrequency>('monthly')+ const [startDate, setStartDate] = useState(() => localToday())+ const [endType, setEndType] = useState<InvoiceScheduleEndType>('never')+ const [endDate, setEndDate] = useState('')+ const [endCount, setEndCount] = useState('')+ const [paymentTerms, setPaymentTerms] = useState('')+ const [notes, setNotes] = useState('')+ const [currencyCode, setCurrencyCode] = useState(user?.preferences?.currency_display ?? 'USD')+ const [lines, setLines] = useState<InvoiceLineInput[]>([+ { description: '', quantity: '1', unit_price: '0' },+ ])++ const perPeriod = linesTotal(lines)+ const monthly = monthlyEquivalent(perPeriod, frequency)++ const mutation = useMutation({+ mutationFn: () =>+ schedulesApi.create({+ name,+ payee_id: payeeId || null,+ frequency,+ start_date: startDate,+ ...endPayload(endType, endDate, endCount),+ payment_terms_days: paymentTerms ? Number(paymentTerms) : null,+ currency: currencyCode,+ notes: notes || null,+ lines,+ }),+ onSuccess: (schedule) => {+ toast.success(t('invoices.schedules.created'))+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedules'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-schedule-summary'] })+ onOpenChange(false)+ onCreated(schedule)+ },+ onError: (error) => {+ const key = invoiceErrorKey(error)+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ },+ })++ const ready =+ name.trim().length > 0 &&+ perPeriod > 0 &&+ Boolean(startDate) &&+ (endType !== 'on_date' || Boolean(endDate)) &&+ (endType !== 'after_count' || Number(endCount) >= 1)++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="flex flex-col max-h-[calc(100dvh-2rem)] sm:max-w-3xl">+ <DialogHeader>+ <DialogTitle>{t('invoices.schedules.new')}</DialogTitle>+ <DialogDescription>{t('invoices.schedules.newDescription')}</DialogDescription>+ </DialogHeader>++ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label htmlFor="schedule-name">{t('invoices.schedules.field.name')}</Label>+ <Input+ id="schedule-name"+ data-testid="schedule-name-input"+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t('invoices.schedules.field.namePlaceholder')}+ />+ </div>+ <div className="space-y-1.5">+ <Label>{t('invoices.field.client')}</Label>+ <Select value={payeeId} onValueChange={setPayeeId}>+ <SelectTrigger data-testid="schedule-client-select">+ <SelectValue placeholder={t('invoices.field.clientPlaceholder')} />+ </SelectTrigger>+ <SelectContent>+ {clients.map((client) => (+ <SelectItem key={client.id} value={client.id}>+ {client.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>++ <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">+ <div className="space-y-1.5">+ <Label>{t('invoices.schedules.field.frequency')}</Label>+ <Select value={frequency} onValueChange={(v) => setFrequency(v as InvoiceScheduleFrequency)}>+ <SelectTrigger data-testid="schedule-frequency-select">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {FREQUENCIES.map((value) => (+ <SelectItem key={value} value={value}>+ {t(`invoices.schedules.frequency.${value}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="schedule-start">{t('invoices.schedules.field.startDate')}</Label>+ <Input+ id="schedule-start"+ data-testid="schedule-start-input"+ type="date"+ value={startDate}+ onChange={(e) => setStartDate(e.target.value)}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="schedule-terms">{t('invoices.schedules.field.paymentTerms')}</Label>+ <Input+ id="schedule-terms"+ data-testid="schedule-terms-input"+ type="number"+ min={0}+ value={paymentTerms}+ onChange={(e) => setPaymentTerms(e.target.value)}+ placeholder={String(settings?.default_payment_terms_days ?? 30)}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="schedule-currency">{t('invoices.schedules.field.currency')}</Label>+ <CurrencySelect id="schedule-currency" value={currencyCode} onChange={setCurrencyCode} />+ </div>+ </div>++ <EndConditionFields+ idPrefix="schedule"+ endType={endType}+ endDate={endDate}+ endCount={endCount}+ onChange={(next) => {+ setEndType(next.endType)+ setEndDate(next.endDate)+ setEndCount(next.endCount)+ }}+ />++ <InvoiceLineEditor+ lines={lines}+ onChange={setLines}+ currency={currencyCode}+ showTax={(settings?.tax_fields ?? 'hidden') !== 'hidden'}+ required+ />++ {/* What the agreement is worth a month, before it exists. The+ same normalisation the summary uses, so the number the+ person sees here is the number they will see there. */}+ <p className="text-xs text-muted-foreground" data-testid="schedule-monthly-preview">+ {t('invoices.schedules.monthlyPreview', {+ amount: formatCurrency(monthly, currencyCode, locale),+ })}+ </p>++ <div className="space-y-1.5">+ <Label htmlFor="schedule-notes">{t('invoices.field.notes')}</Label>+ <Input+ id="schedule-notes"+ data-testid="schedule-notes-input"+ value={notes}+ onChange={(e) => setNotes(e.target.value)}+ />+ </div>+ </div>++ <DialogFooter className="gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={() => mutation.mutate()}+ disabled={!ready || mutation.isPending}+ data-testid="schedule-create-submit"+ >+ {t('common.create')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/pages/invoices.tsx b/frontend/src/pages/invoices.tsxindex 9b77ede0..73717b2e 100644--- a/frontend/src/pages/invoices.tsx+++ b/frontend/src/pages/invoices.tsx@@ -7,6 +7,7 @@ import {ChevronDown,Plus,Receipt,+ Repeat,Settings2,} from 'lucide-react'import { toast } from 'sonner'@@ -156,6 +157,19 @@ export default function InvoicesPage() {title={t('invoices.title')}action={<div className="flex items-center gap-2">+ {/* Only on the receivable side: an agreement is something we+ bill, and the payable ledger has nothing to emit. */}+ {direction === 'receivable' && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => navigate('/invoices/schedules')}+ data-testid="invoice-schedules-button"+ >+ <Repeat className="h-4 w-4 mr-1.5" />+ {t('invoices.schedules.title')}+ </Button>+ )}<Buttonvariant="outline"size="sm"@@ -420,7 +434,17 @@ export default function InvoicesPage() {className="border-b border-border last:border-0 hover:bg-muted transition-colors cursor-pointer"><td className="py-3 pl-4 sm:pl-5">- <div className="text-sm font-medium text-foreground truncate">+ <div className="flex items-center gap-1.5 text-sm font-medium text-foreground truncate">+ {/* A recurring invoice says so with a glyph, not a+ column: the list is about money, and which+ agreement it came from is one hop away. */}+ {invoice.schedule_id && (+ <Repeat+ className="h-3.5 w-3.5 shrink-0 text-muted-foreground"+ aria-label={t('invoices.schedules.recurringInvoice')}+ data-testid="invoice-row-recurring"+ />+ )}{invoice.payee?.name ?? (<span className="text-muted-foreground">{direction === 'payable'diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex ad36e088..0a7693d0 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -1167,11 +1167,113 @@ export interface Invoice {/** Present once a shareable link exists. Null until someone asks for* one, and null again once revoked. */share_token: string | null+ /** Which agreement and period this invoice answers for, when it was+ * born from or linked to one. Provenance only: nothing about the+ * money reads these. */+ schedule_id: string | null+ schedule: { id: string; name: string; frequency: InvoiceScheduleFrequency; status: InvoiceScheduleStatus } | null+ sequence: number | null+ period_start: string | null+ period_end: string | nulllines: InvoiceLine[]allocations: InvoiceAllocation[]created_at: string}+// ---------------------------------------------------------------------------+// Recurring invoices+// ---------------------------------------------------------------------------++/** Decisions a person took about an agreement. `past_due` is not one of+ * them: it is derived from the agreement's invoices. */+export type InvoiceScheduleStatus = 'active' | 'paused' | 'ended'+export type InvoiceScheduleFrequency =+ | 'weekly'+ | 'biweekly'+ | 'monthly'+ | 'quarterly'+ | 'semiannual'+ | 'yearly'+export type InvoiceScheduleEndType = 'never' | 'on_date' | 'after_count'+export type InvoiceScheduleEndReason =+ | 'canceled_by_client'+ | 'canceled_by_us'+ | 'completed'+ | 'unpaid'+ | 'other'++/** What the agreement says from a date on. One row per price change. */+export interface InvoiceScheduleTerm {+ id: string+ effective_from: string+ lines: InvoiceLineInput[]+ discount: string+ subtotal: string+ tax_total: string+ total: string+ created_at: string+}++export interface InvoiceSchedule {+ id: string+ name: string+ payee_id: string | null+ payee: { id: string; name: string } | null+ origin: string+ external_source: string | null+ external_id: string | null+ status: InvoiceScheduleStatus+ pause_reason: 'manual' | 'failures' | null+ ended_at: string | null+ end_reason: InvoiceScheduleEndReason | null+ frequency: InvoiceScheduleFrequency+ start_date: string+ end_type: InvoiceScheduleEndType+ end_date: string | null+ end_count: number | null+ payment_terms_days: number | null+ currency: string+ notes: string | null+ custom_fields: Record<string, string> | null+ next_sequence: number+ last_generated_at: string | null+ consecutive_failures: number+ terms: InvoiceScheduleTerm[]+ created_at: string+ /** Derived by the server on every read; never stored. */+ current_term: InvoiceScheduleTerm | null+ next_term: InvoiceScheduleTerm | null+ monthly_amount: string+ next_period_start: string | null+ invoice_count: number+ amount_invoiced: string+ amount_paid: string+ past_due_count: number+}++export interface InvoiceScheduleCurrencySummary {+ currency: string+ monthly_recurring: string+ active_count: number+ ended_recently_count: number+ monthly_lost: string+ past_due_count: number+}++export interface InvoiceScheduleSummary {+ active_count: number+ paused_count: number+ ended_count: number+ by_currency: InvoiceScheduleCurrencySummary[]+}++export interface InvoiceSchedulePeriod {+ sequence: number+ period_start: string+ period_end: string+ taken: boolean+}+export interface InvoiceAgingBuckets {current: stringd1_30: string