Open-source personal finance manager. Self-hosted, privacy-first.
feat(invoices): installments and deductions (#1021)
Tássio Noronha97aee851fdf4
diff --git a/backend/alembic/versions/095_installments_deductions.py b/backend/alembic/versions/095_installments_deductions.pynew file mode 100644index 00000000..83907a8d--- /dev/null+++ b/backend/alembic/versions/095_installments_deductions.py@@ -0,0 +1,85 @@+"""installments, and debt settled without money++Two ways the money of one invoice fails to be one amount on one date,+both kept inside the invoice rather than becoming features of their own.++ - `invoice_installments`: the dates the money is expected on ("3x",+ "50% upfront"). They add up to the total, and the invoice's own+ `due_date` becomes the last of them so every existing sort and+ filter keeps its meaning. Nothing is allocated to an installment:+ settled money covers the schedule first-to-last when read.+ - `invoice_deductions`: tax the client withheld, a fee the gateway+ kept. They close the debt without counting as received, so the+ invoice reads as paid while "received this month" stays cash.++Revision ID: 095+Revises: 094+"""+from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects import postgresql++revision = "095"+down_revision = "094"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.create_table(+ "invoice_installments",+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("invoice_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("position", sa.Integer(), nullable=False),+ sa.Column("label", sa.String(length=60), nullable=True),+ sa.Column("due_date", sa.Date(), nullable=False),+ sa.Column("amount", sa.Numeric(precision=15, scale=2), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(["invoice_id"], ["invoices.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ sa.UniqueConstraint("invoice_id", "position", name="uq_invoice_installments_position"),+ sa.CheckConstraint("amount > 0", name="ck_invoice_installments_amount_positive"),+ )+ op.create_index("ix_invoice_installments_invoice", "invoice_installments", ["invoice_id"])+ op.create_index(+ "ix_invoice_installments_workspace_id", "invoice_installments", ["workspace_id"]+ )++ op.create_table(+ "invoice_deductions",+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("invoice_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("kind", sa.String(length=30), nullable=False),+ sa.Column("tax_kind", sa.String(length=30), nullable=True),+ sa.Column("amount", sa.Numeric(precision=15, scale=2), nullable=False),+ sa.Column("note", sa.String(length=500), nullable=True),+ sa.Column("transaction_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("deducted_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(["invoice_id"], ["invoices.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["transaction_id"], ["transactions.id"], ondelete="SET NULL"),+ sa.PrimaryKeyConstraint("id"),+ sa.CheckConstraint("amount > 0", name="ck_invoice_deductions_amount_positive"),+ sa.CheckConstraint(+ "kind IN ('withholding_tax', 'gateway_fee', 'fx_difference', 'other')",+ name="ck_invoice_deductions_kind",+ ),+ )+ op.create_index("ix_invoice_deductions_invoice", "invoice_deductions", ["invoice_id"])+ op.create_index(+ "ix_invoice_deductions_workspace_id", "invoice_deductions", ["workspace_id"]+ )+++def downgrade() -> None:+ # Dropping the deductions reopens the balance they closed, which is+ # the honest reading of a schema that no longer knows about them.+ op.drop_index("ix_invoice_deductions_workspace_id", table_name="invoice_deductions")+ op.drop_index("ix_invoice_deductions_invoice", table_name="invoice_deductions")+ op.drop_table("invoice_deductions")+ op.drop_index("ix_invoice_installments_workspace_id", table_name="invoice_installments")+ op.drop_index("ix_invoice_installments_invoice", table_name="invoice_installments")+ op.drop_table("invoice_installments")diff --git a/backend/app/api/invoices.py b/backend/app/api/invoices.pyindex 49b693b7..637b8d1e 100644--- a/backend/app/api/invoices.py+++ b/backend/app/api/invoices.py@@ -21,6 +21,8 @@ from app.core.module_gate import require_module, require_module_writefrom app.core.workspace_context import WorkspaceContextfrom app.schemas.invoice import (AllocationCreate,+ DeductionCreate,+ InstallmentRead,InvoiceCreate,InvoiceDirection,InvoiceFacets,@@ -44,6 +46,7 @@ from app.services import (invoice_service,reconciliation_history_service,reconciliation_service,+ reconciliation_suggestion_service,)from app.services.invoice_service import InvoiceErrorfrom app.services.module_service import ModuleId@@ -70,8 +73,13 @@ def _serialize(invoice, today: Optional[_date] = None) -> InvoiceRead:payload = InvoiceRead.model_validate(invoice, from_attributes=True)payload.state = invoice_service.derive_state(invoice, today)payload.amount_paid = invoice_service.allocated_total(invoice)+ payload.amount_deducted = invoice_service.deducted_total(invoice)payload.balance = invoice_service.balance(invoice)payload.days_overdue = invoice_service.days_overdue(invoice, today)+ payload.next_due_date = invoice_service.first_unpaid_due(invoice)+ payload.installments = [+ InstallmentRead(**row) for row in invoice_service.installment_states(invoice, today)+ ]return payload@@ -253,6 +261,8 @@ async def create_invoice(data = payload.model_dump(exclude_unset=True)if data.get("lines") is not None:data["lines"] = [dict(line) for line in data["lines"]]+ if data.get("installments") is not None:+ data["installments"] = [dict(row) for row in data["installments"]]try:invoice = await invoice_service.create_invoice(session, ctx.workspace.id, ctx.user_id, data@@ -292,6 +302,8 @@ async def update_invoice(data = payload.model_dump(exclude_unset=True)if data.get("lines") is not None:data["lines"] = [dict(line) for line in data["lines"]]+ if data.get("installments") is not None:+ data["installments"] = [dict(row) for row in data["installments"]]try:invoice = await invoice_service.update_invoice(session, invoice, data)except InvoiceError as exc:@@ -454,6 +466,51 @@ async def create_allocation(strategy_id=allocation.method,user_id=ctx.user_id,)+ if payload.transaction_id is not None:+ await reconciliation_suggestion_service.settled_by_hand(+ session, ctx.workspace.id, payload.transaction_id, invoice.id, ctx.user_id+ )+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}/deductions", response_model=InvoiceRead, status_code=status.HTTP_201_CREATED)+async def create_deduction(+ invoice_id: uuid.UUID,+ payload: DeductionCreate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """Close part of the debt without money: tax withheld, a fee kept."""+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ try:+ await invoice_service.deduct(+ session,+ invoice,+ payload.kind,+ payload.amount,+ tax_kind=payload.tax_kind,+ note=payload.note,+ transaction_id=payload.transaction_id,+ )+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}/deductions/{deduction_id}", response_model=InvoiceRead)+async def remove_deduction(+ invoice_id: uuid.UUID,+ deduction_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ try:+ await invoice_service.undeduct(session, invoice, deduction_id)+ except InvoiceError as exc:+ raise _http(exc)await session.commit()return _serialize(await _load(session, invoice_id, ctx.workspace.id))@@ -649,6 +706,44 @@ async def download_pdf()[email protected]("/{invoice_id}/statement")+async def download_statement(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """The statement of account: what was paid and deducted since the+ invoice was issued, and how that arrives at the balance.++ Rendered live on purpose, unlike `/pdf`: the invoice as issued is+ frozen, and this is the document that is supposed to change.++ Only for what we issued. A draft has been sent to nobody, and a bill+ we received is the supplier's to state; a page in their name drawn by+ us would be the invention `/pdf` refuses too.+ """+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ if invoice.status == "draft":+ raise _http(InvoiceError("statement_of_draft", "A draft has nothing to state yet", status_code=status.HTTP_409_CONFLICT))+ if invoice.direction != "receivable" or invoice.origin == "imported":+ raise _http(InvoiceError("statement_not_ours", "Only an invoice we issued has a statement", status_code=status.HTTP_409_CONFLICT))++ settings = await invoice_service.get_settings(session, ctx.workspace.id)+ document = await invoice_document.build_statement(session, invoice, settings, ctx.workspace)+ logo_bytes = (+ await invoice_logo_service.read(ctx.workspace.id, uuid.UUID(document.logo_id))+ if document.logo_id+ else None+ )+ pdf = invoice_pdf.render_pdf(document, logo_bytes)+ filename = f"{document.number or 'invoice'}-statement.pdf".replace("/", "-")+ return Response(+ content=pdf,+ media_type="application/pdf",+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},+ )++@router.post("/{invoice_id}/share", response_model=ShareLinkRead, status_code=status.HTTP_201_CREATED)async def create_share_link(invoice_id: uuid.UUID,diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 20107828..696c275f 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -25,7 +25,14 @@ from app.models.group import Group, GroupMemberfrom app.models.transaction_split import TransactionSplitfrom app.models.group_settlement import GroupSettlementfrom app.models.collection import Collection, collection_accounts, collection_asset_groups-from app.models.invoice import Invoice, InvoiceAllocation, InvoiceLine, InvoiceSettings+from app.models.invoice import (+ Invoice,+ InvoiceAllocation,+ InvoiceDeduction,+ InvoiceInstallment,+ InvoiceLine,+ InvoiceSettings,+)from app.models.invoice_attachment import InvoiceAttachmentfrom app.models.invoice_schedule import InvoiceSchedule, InvoiceScheduleTermfrom app.models.product import Product, ProductPrice@@ -78,6 +85,8 @@ __all__ = ["InvoiceLine","InvoiceSettings","InvoiceAttachment",+ "InvoiceDeduction",+ "InvoiceInstallment","InvoiceSchedule","InvoiceScheduleTerm","Product",diff --git a/backend/app/models/invoice.py b/backend/app/models/invoice.pyindex 65a61a97..1055f771 100644--- a/backend/app/models/invoice.py+++ b/backend/app/models/invoice.py@@ -321,6 +321,23 @@ class Invoice(Base):schedule: Mapped[Optional["InvoiceSchedule"]] = relationship(back_populates="invoices", lazy="joined")+ # When the money is expected in more than one date. Empty for the+ # ordinary invoice, whose one `due_date` is the whole schedule.+ installments: Mapped[list["InvoiceInstallment"]] = relationship(+ back_populates="invoice",+ cascade="all, delete-orphan",+ order_by="InvoiceInstallment.position",+ lazy="selectin",+ )+ # Debt settled without money arriving: tax the client withheld, a+ # fee the gateway kept. Counts towards "settled", never towards+ # "received".+ deductions: Mapped[list["InvoiceDeduction"]] = relationship(+ back_populates="invoice",+ cascade="all, delete-orphan",+ order_by="InvoiceDeduction.deducted_at",+ lazy="selectin",+ )class InvoiceLine(Base):@@ -427,6 +444,109 @@ class InvoiceAllocation(Base):transaction: Mapped[Optional["Transaction"]] = relationship(lazy="joined")+#: Why an invoice closed without the whole amount arriving.+#:+#: withholding_tax: the client kept part of it for the tax office+#: (IRRF, ISS, INSS in Brazil; IRPF in Spain; the+#: `tax_kind` says which, in the jurisdiction's words)+#: gateway_fee: the processor kept its cut before paying out+#: fx_difference: paid in another currency and the conversion+#: landed short (or long) of the face value+#: other: with a note saying what+#:+#: A write-off (giving up on the money) is not here: that is the+#: whole-invoice `uncollectible` decision, and the two never coexist.+DEDUCTION_KINDS = ("withholding_tax", "gateway_fee", "fx_difference", "other")+++class InvoiceInstallment(Base):+ """One of the dates an invoice's money is expected on.++ "3x no boleto", "50% upfront, 50% on delivery": the schedule the+ client agreed to, as rows. The amounts add up to the invoice total+ (enforced when written), and the invoice's own `due_date` becomes+ the last of them so every list and filter that sorts by it still+ holds.++ Nothing is allocated *to* an installment. Money settles the invoice,+ and which installments that covers is read first-to-last from the+ running total: the first unpaid installment is the one that can be+ late. That keeps the N:N allocation table untouched and means a+ client who pays two installments in one transfer needs no ceremony.+ """++ __tablename__ = "invoice_installments"+ __table_args__ = (+ Index("ix_invoice_installments_invoice", "invoice_id"),+ UniqueConstraint("invoice_id", "position", name="uq_invoice_installments_position"),+ CheckConstraint("amount > 0", name="ck_invoice_installments_amount_positive"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ invoice_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("invoices.id", ondelete="CASCADE")+ )+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ position: Mapped[int] = mapped_column(Integer, default=0)+ # "Entrada", "2/3", "Na entrega": free text, optional.+ label: Mapped[Optional[str]] = mapped_column(String(60), nullable=True)+ due_date: Mapped[_date] = mapped_column(Date)+ amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ invoice: Mapped["Invoice"] = relationship(back_populates="installments")+++class InvoiceDeduction(Base):+ """Debt settled without money arriving.++ The R$ 150 an invoice stays short of forever because the client+ withheld tax, or the gateway kept its fee. Recording it here closes+ the invoice honestly: `balance` subtracts it, `amount_paid` does+ not, so "received this month" stays the cash figure and the+ accountant can still see what was withheld and why.+ """++ __tablename__ = "invoice_deductions"+ __table_args__ = (+ Index("ix_invoice_deductions_invoice", "invoice_id"),+ CheckConstraint("amount > 0", name="ck_invoice_deductions_amount_positive"),+ CheckConstraint(+ "kind IN ('withholding_tax', 'gateway_fee', 'fx_difference', 'other')",+ name="ck_invoice_deductions_kind",+ ),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ invoice_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("invoices.id", ondelete="CASCADE")+ )+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ kind: Mapped[str] = mapped_column(String(30))+ # Which tax, in the jurisdiction's own vocabulary (`irrf`, `iss`,+ # `irpf`...). Free text on purpose: a pack may suggest, the column+ # never restricts.+ tax_kind: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)+ amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))+ note: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)+ # The payment this was noticed on, when there was one: the transfer+ # that came in net. Provenance only.+ transaction_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="SET NULL"), nullable=True+ )+ deducted_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ invoice: Mapped["Invoice"] = relationship(back_populates="deductions")++class InvoiceSettings(Base):"""How this workspace's invoicing behaves and how it looks.diff --git a/backend/app/schemas/invoice.py b/backend/app/schemas/invoice.pyindex 86a28528..cac26d51 100644--- a/backend/app/schemas/invoice.py+++ b/backend/app/schemas/invoice.py@@ -71,6 +71,50 @@ class AllocationTransaction(BaseModel):model_config = ConfigDict(from_attributes=True)+class InstallmentInput(BaseModel):+ due_date: _Date+ amount: Decimal = Field(..., gt=0)+ #: "Entrada", "2/3", "On delivery". Optional.+ label: Optional[str] = Field(default=None, max_length=60)+++class InstallmentRead(BaseModel):+ id: uuid.UUID+ position: int+ label: Optional[str] = None+ due_date: _Date+ amount: Decimal+ #: Derived: how much of this installment the settled money covers,+ #: read first-to-last, and what it reads as. Never stored.+ settled: Decimal = Decimal("0")+ state: str = "open"+++DeductionKind = Literal["withholding_tax", "gateway_fee", "fx_difference", "other"]+++class DeductionCreate(BaseModel):+ kind: DeductionKind+ amount: Decimal = Field(..., gt=0)+ #: Which tax, in the jurisdiction's words (`irrf`, `iss`, `irpf`).+ tax_kind: Optional[str] = Field(default=None, max_length=30)+ note: Optional[str] = Field(default=None, max_length=500)+ #: The payment it was noticed on, when there was one.+ transaction_id: Optional[uuid.UUID] = None+++class InvoiceDeductionRead(BaseModel):+ id: uuid.UUID+ kind: DeductionKind+ tax_kind: Optional[str] = None+ amount: Decimal+ note: Optional[str] = None+ transaction_id: Optional[uuid.UUID] = None+ deducted_at: datetime++ model_config = ConfigDict(from_attributes=True)++class InvoiceAllocationRead(BaseModel):id: uuid.UUIDtransaction_id: Optional[uuid.UUID]@@ -123,6 +167,9 @@ class InvoiceCreate(BaseModel):internal_notes: Optional[str] = Nonecustom_fields: Optional[dict[str, Any]] = Nonelines: Optional[list[InvoiceLineInput]] = None+ #: When the money is expected in more than one date. Must add up to+ #: the total; the invoice's due date becomes the last of them.+ installments: Optional[list[InstallmentInput]] = Noneclass InvoiceUpdate(BaseModel):@@ -139,6 +186,8 @@ class InvoiceUpdate(BaseModel):internal_notes: Optional[str] = Nonecustom_fields: Optional[dict[str, Any]] = Nonelines: Optional[list[InvoiceLineInput]] = None+ #: Draft only. An empty list clears the schedule.+ installments: Optional[list[InstallmentInput]] = Noneclass InvoicePayee(BaseModel):@@ -187,8 +236,13 @@ class InvoiceRead(BaseModel):tax_total: Decimaltotal: Decimalamount_paid: Decimal = Decimal("0")+ #: Settled without cash (tax withheld, fees kept). Not in `amount_paid`.+ amount_deducted: Decimal = Decimal("0")balance: Decimal = Decimal("0")days_overdue: int = 0+ #: When the next money is late after: the first unpaid installment's+ #: date, or the due date. Null once nothing is owed.+ next_due_date: Optional[_Date] = Nonenotes: Optional[str]internal_notes: Optional[str]custom_fields: Optional[dict[str, Any]]@@ -206,6 +260,8 @@ class InvoiceRead(BaseModel):period_end: Optional[_Date] = Nonelines: list[InvoiceLineRead] = []allocations: list[InvoiceAllocationRead] = []+ installments: list[InstallmentRead] = []+ deductions: list[InvoiceDeductionRead] = []created_at: datetimemodel_config = ConfigDict(from_attributes=True)diff --git a/backend/app/services/invoice_document.py b/backend/app/services/invoice_document.pyindex 3ceee63c..a9219885 100644--- a/backend/app/services/invoice_document.py+++ b/backend/app/services/invoice_document.py@@ -58,9 +58,19 @@ DEFAULT_LABELS: dict[str, str] = {"tax": "Tax","total": "Total","paid": "Paid",+ "deducted": "Deductions","balance": "Balance due",+ "statement": "Statement of account",+ "history": "Payments and deductions",+ "date": "Date",+ "payment": "Payment received",+ "withholdingTax": "Tax withheld",+ "gatewayFee": "Processing fee",+ "fxDifference": "Currency difference",+ "otherDeduction": "Other deduction","paymentDetails": "Payment details","notes": "Notes",+ "schedule": "Payment schedule",}#: Shipped label packs, by language. Deliberately few: this is the set@@ -89,8 +99,18 @@ LABEL_PACKS: dict[str, dict[str, str]] = {"tax": "Impostos","total": "Total","paid": "Recebido",+ "deducted": "Deduções","balance": "Saldo devedor",+ "statement": "Extrato da fatura",+ "history": "Pagamentos e deduções",+ "date": "Data",+ "payment": "Pagamento recebido",+ "withholdingTax": "Imposto retido",+ "gatewayFee": "Taxa de processamento",+ "fxDifference": "Diferença de câmbio",+ "otherDeduction": "Outra dedução","paymentDetails": "Dados para pagamento",+ "schedule": "Cronograma de pagamento","notes": "Observações",},"es": {@@ -109,8 +129,18 @@ LABEL_PACKS: dict[str, dict[str, str]] = {"tax": "Impuestos","total": "Total","paid": "Cobrado",+ "deducted": "Deducciones","balance": "Saldo pendiente",+ "statement": "Estado de cuenta",+ "history": "Pagos y deducciones",+ "date": "Fecha",+ "payment": "Pago recibido",+ "withholdingTax": "Impuesto retenido",+ "gatewayFee": "Comisión de procesamiento",+ "fxDifference": "Diferencia de cambio",+ "otherDeduction": "Otra deducción","paymentDetails": "Datos de pago",+ "schedule": "Calendario de pagos","notes": "Notas",},"fr": {@@ -129,8 +159,18 @@ LABEL_PACKS: dict[str, dict[str, str]] = {"tax": "TVA","total": "Total","paid": "Réglé",+ "deducted": "Déductions","balance": "Reste à payer",+ "statement": "Relevé de compte",+ "history": "Paiements et déductions",+ "date": "Date",+ "payment": "Paiement reçu",+ "withholdingTax": "Impôt retenu",+ "gatewayFee": "Frais de traitement",+ "fxDifference": "Écart de change",+ "otherDeduction": "Autre déduction","paymentDetails": "Coordonnées de paiement",+ "schedule": "Échéancier","notes": "Notes",},"de": {@@ -149,8 +189,18 @@ LABEL_PACKS: dict[str, dict[str, str]] = {"tax": "USt.","total": "Gesamt","paid": "Bezahlt",+ "deducted": "Abzüge","balance": "Offener Betrag",+ "statement": "Kontoauszug",+ "history": "Zahlungen und Abzüge",+ "date": "Datum",+ "payment": "Zahlung erhalten",+ "withholdingTax": "Einbehaltene Steuer",+ "gatewayFee": "Bearbeitungsgebühr",+ "fxDifference": "Währungsdifferenz",+ "otherDeduction": "Sonstiger Abzug","paymentDetails": "Zahlungsinformationen",+ "schedule": "Zahlungsplan","notes": "Hinweise",},"it": {@@ -169,8 +219,18 @@ LABEL_PACKS: dict[str, dict[str, str]] = {"tax": "IVA","total": "Totale","paid": "Incassato",+ "deducted": "Trattenute","balance": "Saldo dovuto",+ "statement": "Estratto conto",+ "history": "Pagamenti e trattenute",+ "date": "Data",+ "payment": "Pagamento ricevuto",+ "withholdingTax": "Ritenuta d'acconto",+ "gatewayFee": "Commissione di elaborazione",+ "fxDifference": "Differenza di cambio",+ "otherDeduction": "Altra trattenuta","paymentDetails": "Dati per il pagamento",+ "schedule": "Scadenze di pagamento","notes": "Note",},}@@ -222,6 +282,24 @@ class DocumentLine:unit: Optional[str] = None+@dataclass(frozen=True)+class DocumentMovement:+ """One settlement on a statement: money that arrived, or an amount+ closed without it. The description is already in the document's+ language and says what kind it was, never the bank's own text."""++ day: _date+ description: str+ amount: Decimal+++@dataclass(frozen=True)+class DocumentInstallment:+ label: Optional[str]+ due_date: _date+ amount: Decimal++@dataclassclass InvoiceDocument:"""Everything a renderer needs, and nothing it has to look up."""@@ -237,6 +315,9 @@ class InvoiceDocument:tax_total: Decimaltotal: Decimalamount_paid: Decimal+ #: Settled without money arriving: tax withheld, a fee kept. Shown+ #: so that total, paid and balance add up on the page.+ amount_deducted: Decimalbalance: Decimalissuer: DocumentPartyclient: DocumentParty@@ -258,6 +339,16 @@ class InvoiceDocument:#: difference between showing a document and claiming to have written#: one.direction: str = "receivable"+ #: The dates the money is expected on, when there is more than one.+ #: Rendered as a small table under the header so the client sees+ #: the same split they agreed to.+ installments: list[DocumentInstallment] = field(default_factory=list)+ #: Set on a statement of account: what settled the invoice, in date+ #: order. Empty on the invoice itself, which is the document as issued.+ movements: list[DocumentMovement] = field(default_factory=list)+ #: A statement of account rather than the invoice: titled as one, and+ #: always showing what is paid, deducted and left.+ statement: bool = Falsedef _label_map(@@ -414,12 +505,17 @@ async def build_document(state=invoice_service.derive_state(invoice),issue_date=invoice.issue_date,due_date=invoice.due_date,+ installments=[+ DocumentInstallment(label=i.label, due_date=i.due_date, amount=i.amount)+ for i in invoice.installments+ ],currency=invoice.currency,subtotal=invoice.subtotal or Decimal("0"),discount=invoice.discount or Decimal("0"),tax_total=invoice.tax_total or Decimal("0"),total=invoice.total or Decimal("0"),amount_paid=invoice_service.allocated_total(invoice),+ amount_deducted=invoice_service.deducted_total(invoice),balance=invoice_service.balance(invoice),issuer=issuer,client=client,@@ -475,6 +571,52 @@ async def build_document()+#: The document label for each deduction kind, so a statement names the+#: reason in the document's language.+_DEDUCTION_LABEL = {+ "withholding_tax": "withholdingTax",+ "gateway_fee": "gatewayFee",+ "fx_difference": "fxDifference",+ "other": "otherDeduction",+}+++async def build_statement(+ session: AsyncSession,+ invoice: Invoice,+ settings: InvoiceSettings,+ workspace: Workspace,+) -> InvoiceDocument:+ """The invoice's statement of account: the document with what settled+ it since, and how that arrives at the balance.++ The invoice as issued stays what it was (see `invoice_archive`); this+ is the other document, the one that is supposed to change. Payments+ are named as payments, not by the bank's text, which is the+ workspace's own record and has no business on a page sent out. Notes+ on deductions stay off it for the same reason.+ """+ from dataclasses import replace++ document = await build_document(session, invoice, settings, workspace)+ labels = document.labels+ movements: list[DocumentMovement] = []+ for allocation in invoice.allocations:+ day = (+ allocation.transaction.date+ if allocation.transaction is not None+ else allocation.allocated_at.date()+ )+ movements.append(DocumentMovement(day, labels["payment"], allocation.amount))+ for deduction in invoice.deductions:+ description = labels[_DEDUCTION_LABEL.get(deduction.kind, "otherDeduction")]+ if deduction.tax_kind:+ description = f"{description} ({deduction.tax_kind.upper()})"+ movements.append(DocumentMovement(deduction.deducted_at.date(), description, deduction.amount))+ movements.sort(key=lambda m: m.day)+ return replace(document, movements=movements, statement=True)++def document_payload(document: InvoiceDocument) -> dict[str, Any]:"""The document as JSON, for the on-screen renderer and the share page.@@ -494,6 +636,7 @@ def document_payload(document: InvoiceDocument) -> dict[str, Any]:"tax_total": str(document.tax_total),"total": str(document.total),"amount_paid": str(document.amount_paid),+ "amount_deducted": str(document.amount_deducted),"balance": str(document.balance),"issuer": {"name": document.issuer.name,@@ -527,4 +670,8 @@ def document_payload(document: InvoiceDocument) -> dict[str, Any]:"custom_fields": [{"label": k, "value": v} for k, v in document.custom_fields],"has_line_items": document.has_line_items,"direction": document.direction,+ "installments": [+ {"label": i.label, "due_date": i.due_date.isoformat(), "amount": str(i.amount)}+ for i in document.installments+ ],}diff --git a/backend/app/services/invoice_forecast_service.py b/backend/app/services/invoice_forecast_service.pyindex cc51057d..02fe52eb 100644--- a/backend/app/services/invoice_forecast_service.py+++ b/backend/app/services/invoice_forecast_service.py@@ -53,10 +53,10 @@ from datetime import datefrom decimal import Decimalfrom typing import Optional-from sqlalchemy import func, select+from sqlalchemy import and_, func, or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession-from app.models.invoice import Invoice, InvoiceAllocation+from app.models.invoice import Invoice, InvoiceAllocation, InvoiceDeduction, InvoiceInstallmentZERO = Decimal("0")@@ -100,21 +100,45 @@ async def claims_in_range(.group_by(InvoiceAllocation.invoice_id).subquery())+ deducted = (+ select(+ InvoiceDeduction.invoice_id.label("invoice_id"),+ func.coalesce(func.sum(InvoiceDeduction.amount), 0).label("total"),+ )+ .group_by(InvoiceDeduction.invoice_id)+ .subquery()+ )+ settled = func.coalesce(allocated.c.total, 0) + func.coalesce(deducted.c.total, 0)+ # An invoice whose money is expected in several dates enters the+ # window through any of them; the walk below decides which part.+ has_installment_in_range = (+ select(InvoiceInstallment.id)+ .where(+ InvoiceInstallment.invoice_id == Invoice.id,+ InvoiceInstallment.due_date >= range_start,+ InvoiceInstallment.due_date < range_end,+ )+ .exists()+ )query = (select(+ Invoice.id,Invoice.due_date,Invoice.currency,Invoice.direction,- (Invoice.total - func.coalesce(allocated.c.total, 0)).label("outstanding"),+ (Invoice.total - settled).label("outstanding"),).outerjoin(allocated, allocated.c.invoice_id == Invoice.id)+ .outerjoin(deducted, deducted.c.invoice_id == Invoice.id).where(Invoice.workspace_id == workspace_id,Invoice.status == "open",- Invoice.due_date >= range_start,- Invoice.due_date < range_end,- (Invoice.total - func.coalesce(allocated.c.total, 0)) > 0,+ or_(+ and_(Invoice.due_date >= range_start, Invoice.due_date < range_end),+ has_installment_in_range,+ ),+ (Invoice.total - settled) > 0,))@@ -122,15 +146,35 @@ async def claims_in_range(query = query.where(Invoice.direction.in_(directions))rows = (await session.execute(query)).all()- claims = [- Claim(- due_date=row.due_date,- currency=row.currency or "USD",- amount=Decimal(str(row.outstanding)),- direction=row.direction,- )- for row in rows- ]+ ids = [row.id for row in rows]+ schedules: dict[uuid.UUID, list[InvoiceInstallment]] = {}+ if ids:+ for installment in (+ await session.execute(+ select(InvoiceInstallment)+ .where(InvoiceInstallment.invoice_id.in_(ids))+ .order_by(InvoiceInstallment.position)+ )+ ).scalars():+ schedules.setdefault(installment.invoice_id, []).append(installment)++ claims: list[Claim] = []+ for row in rows:+ currency = row.currency or "USD"+ outstanding = Decimal(str(row.outstanding))+ installments = schedules.get(row.id)+ if not installments:+ claims.append(Claim(row.due_date, currency, outstanding, row.direction))+ continue+ # Settled money covers the schedule first-to-last; what is left+ # of each installment is promised for that installment's date.+ covered = sum((i.amount for i in installments), Decimal("0")) - outstanding+ for installment in installments:+ share = min(installment.amount, max(covered, ZERO))+ covered -= share+ left = installment.amount - share+ if left > ZERO and range_start <= installment.due_date < range_end:+ claims.append(Claim(installment.due_date, currency, left, row.direction))# Periods of a recurring agreement that no invoice answers for yet.# Same money as the invoice the job will emit for them, and the twodiff --git a/backend/app/services/invoice_pdf.py b/backend/app/services/invoice_pdf.pyindex 6d2d4a8e..45aaa0c0 100644--- a/backend/app/services/invoice_pdf.py+++ b/backend/app/services/invoice_pdf.py@@ -113,6 +113,14 @@ def _para(return Paragraph(escape(text).replace("\n", "<br/>"), style)+def _title(document: InvoiceDocument) -> str:+ """What the page says it is. A statement must never read as the+ invoice: the invoice is the document as issued, and a second page+ with the same title and different figures is the drift the archive+ exists to prevent."""+ return document.labels["statement"] if document.statement else document.labels["invoice"]++def _label(text: str) -> Paragraph:"""A section label. Small, spaced, quiet — the same treatment the webpreview gives it, so the two read as one design."""@@ -181,7 +189,7 @@ def _draw_header(canvas, document: InvoiceDocument, accent, logo_bytes) -> floatcanvas.setFont("Helvetica-Bold", 19)canvas.setFillColor(INK)- canvas.drawString(MARGIN, y - 6.5 * mm, document.labels["invoice"])+ canvas.drawString(MARGIN, y - 6.5 * mm, _title(document))if document.number:canvas.setFont("Helvetica-Bold", 12.5)@@ -240,6 +248,83 @@ def _draw_parties_and_dates(canvas, document: InvoiceDocument, y: float) -> floareturn y - 11 * mm+def _schedule_table(document: InvoiceDocument) -> Optional[Table]:+ """The schedule, when the money is expected on more than one date.++ Drawn under the dates and above the lines: it is about when, not+ what. A table rather than part of the header so that a long one+ breaks across pages the way the lines do, instead of running off+ the bottom of page one.+ """+ if not document.installments:+ return None+ # The same treatment as the lines below it: a ruled header, a hairline+ # between rows, and every money column right-aligned, header included.+ header = [+ _label(document.labels["schedule"]),+ _label(document.labels["dueDate"]),+ _para(document.labels["amount"].upper(), size=7, color=MUTED, bold=True, align=TA_RIGHT),+ ]+ rows = [header]+ for index, installment in enumerate(document.installments, start=1):+ rows.append([+ _para(installment.label or f"{index}/{len(document.installments)}"),+ _para(installment.due_date.isoformat(), color=MUTED),+ _para(_money(installment.amount, document.currency), align=TA_RIGHT),+ ])+ table = Table(+ rows,+ colWidths=[CONTENT_WIDTH * 0.5, CONTENT_WIDTH * 0.25, CONTENT_WIDTH * 0.25],+ repeatRows=1,+ splitInRow=1,+ )+ table.setStyle(TableStyle([+ ("VALIGN", (0, 0), (-1, -1), "TOP"),+ ("LINEBELOW", (0, 0), (-1, 0), 0.6, RULE),+ ("LINEBELOW", (0, 1), (-1, -2), 0.4, RULE),+ ("TOPPADDING", (0, 0), (-1, -1), 5),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 5),+ ("LEFTPADDING", (0, 0), (-1, -1), 0),+ ("RIGHTPADDING", (0, 0), (-1, -1), 0),+ ]))+ return table+++def _movements_table(document: InvoiceDocument) -> Optional[Table]:+ """On a statement: every payment and deduction, by date, so the reader+ can walk from the total to the balance line by line."""+ if not document.movements:+ return None+ header = [+ _label(document.labels["history"]),+ _label(document.labels["date"]),+ _para(document.labels["amount"].upper(), size=7, color=MUTED, bold=True, align=TA_RIGHT),+ ]+ rows = [header]+ for movement in document.movements:+ rows.append([+ _para(movement.description),+ _para(movement.day.isoformat(), color=MUTED),+ _para(_money(movement.amount, document.currency), align=TA_RIGHT),+ ])+ table = Table(+ rows,+ colWidths=[CONTENT_WIDTH * 0.5, CONTENT_WIDTH * 0.25, CONTENT_WIDTH * 0.25],+ repeatRows=1,+ splitInRow=1,+ )+ table.setStyle(TableStyle([+ ("VALIGN", (0, 0), (-1, -1), "TOP"),+ ("LINEBELOW", (0, 0), (-1, 0), 0.6, RULE),+ ("LINEBELOW", (0, 1), (-1, -2), 0.4, RULE),+ ("TOPPADDING", (0, 0), (-1, -1), 5),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 5),+ ("LEFTPADDING", (0, 0), (-1, -1), 0),+ ("RIGHTPADDING", (0, 0), (-1, -1), 0),+ ]))+ return table++def _lines_table(document: InvoiceDocument) -> Optional[Table]:if not document.lines:return None@@ -291,10 +376,18 @@ def _totals_table(document: InvoiceDocument, accent) -> Table:if document.tax_total and document.tax_total > 0:rows.append((document.labels["tax"], _money(document.tax_total, document.currency), False))rows.append((document.labels["total"], _money(document.total, document.currency), True))- # Paid and balance only once money has moved: on an untouched invoice- # they restate the total twice and add nothing.- if document.amount_paid and document.amount_paid > 0:- rows.append((document.labels["paid"], _money(document.amount_paid, document.currency), False))+ # Paid and balance only once something has settled: on an untouched+ # invoice they restate the total twice and add nothing. Deductions get+ # their own row, or the page would say total 3,000, paid 1,455,+ # balance 1,500, and the 45 the client withheld would be missing.+ paid = document.amount_paid or Decimal("0")+ deducted = document.amount_deducted or Decimal("0")+ # A statement always shows them: saying what is left is its purpose.+ if paid > 0 or deducted > 0 or document.statement:+ if paid > 0:+ rows.append((document.labels["paid"], _money(paid, document.currency), False))+ if deducted > 0:+ rows.append((document.labels["deducted"], _money(deducted, document.currency), False))rows.append((document.labels["balance"], _money(document.balance, document.currency), True))width = 74 * mm@@ -410,7 +503,7 @@ def render_pdf(document: InvoiceDocument, logo_bytes: Optional[bytes] = None) ->accent = _accent(document.accent_color)buffer = io.BytesIO()canvas = pdf_canvas.Canvas(buffer, pagesize=A4)- canvas.setTitle(f"{document.labels['invoice']} {document.number or ''}".strip())+ canvas.setTitle(f"{_title(document)} {document.number or ''}".strip())footer, closing = _footer_flowables(document)footer_height = _footer_height(footer, closing)@@ -425,55 +518,29 @@ def render_pdf(document: InvoiceDocument, logo_bytes: Optional[bytes] = None) ->pages: list[list] = []y = _draw_parties_and_dates(canvas, document, _draw_header(canvas, document, accent, logo_bytes))- if lines is not None:- remaining: Optional[Table] = lines- # Whether the next attempt is happening on an otherwise empty- # page, which is what tells a "too full" failure apart from a- # "will never fit" one.- on_fresh_page = False- while remaining is not None:- available = y - floor- # The totals must share the last page with the table, so the- # final chunk needs room for both.- needed = remaining.wrap(CONTENT_WIDTH, PAGE_HEIGHT)[1]- if needed + totals_height + 8 * mm <= available:- remaining.drawOn(canvas, MARGIN, y - needed)- y -= needed- remaining = None- break-- parts = remaining.split(CONTENT_WIDTH, available)- if len(parts) < 2:- # Cannot split into this space. Normally that means the- # page is too full, and a fresh one solves it.- #- # If we are *already* at the top of a fresh page, it does- # not: the content will not fit anywhere, and asking for- # another page would ask forever. Draw it and move on —- # an overrun on one invoice beats a request that never- # returns and holds a worker until it is killed.- if on_fresh_page:- remaining.drawOn(canvas, MARGIN, y - needed)- remaining = None- break- pages.append([])- canvas.showPage()- y = _draw_continuation_header(canvas, document, accent)- on_fresh_page = True- continue-- head, tail = parts[0], parts[1]- head_height = head.wrap(CONTENT_WIDTH, PAGE_HEIGHT)[1]- head.drawOn(canvas, MARGIN, y - head_height)- pages.append([])- canvas.showPage()- y = _draw_continuation_header(canvas, document, accent)- remaining = tail- # The page the tail lands on carries only the continuation- # header, so it counts as fresh for the same reason.- on_fresh_page = True+ # The totals must share the last page with the last table, so its+ # final chunk needs room for both.+ reserve = totals_height + 8 * mm++ # When, what, then (on a statement) what settled it. Each table is+ # flowed in turn; only the last one has to leave room for the totals.+ tables = [+ table+ for table in (_schedule_table(document), lines, _movements_table(document))+ if table is not None+ ]+ for index, table in enumerate(tables):+ last = index == len(tables) - 1+ y = _flow(canvas, document, accent, table, y, floor, pages, reserve=reserve if last else 0.0)+ if not last:+ y -= 8 * mmy -= 8 * mm+ if y - totals_height < floor:+ # Whatever the tables did, the totals never sink into the footer.+ pages.append([])+ canvas.showPage()+ y = _draw_continuation_header(canvas, document, accent)totals.drawOn(canvas, PAGE_WIDTH - MARGIN - 74 * mm, y - totals_height)_draw_footer(canvas, footer, closing)@@ -485,6 +552,72 @@ def render_pdf(document: InvoiceDocument, logo_bytes: Optional[bytes] = None) ->return buffer.getvalue()+def _flow(+ canvas,+ document: InvoiceDocument,+ accent,+ table: Table,+ y: float,+ floor: float,+ pages: list[list],+ reserve: float = 0.0,+) -> float:+ """Draw `table` downwards from `y`, breaking onto continuation pages+ as needed, and return the y just under it.++ `reserve` is room the last chunk must leave under itself on its page,+ for whatever has to share that page with it. `pages` grows by one per+ page break, for the page count.+ """+ remaining: Optional[Table] = table+ # Whether the next attempt is happening on an otherwise empty page,+ # which is what tells a "too full" failure apart from a "will never+ # fit" one.+ on_fresh_page = False+ while remaining is not None:+ available = y - floor+ needed = remaining.wrap(CONTENT_WIDTH, PAGE_HEIGHT)[1]+ if needed + reserve <= available:+ remaining.drawOn(canvas, MARGIN, y - needed)+ return y - needed++ parts = remaining.split(CONTENT_WIDTH, available)+ if len(parts) == 1 and reserve:+ # The whole of it fits this page, but not with what has to+ # follow it. Split so the tail and what follows share the+ # next page, instead of drawing it whole over the reserve.+ parts = remaining.split(CONTENT_WIDTH, available - reserve)+ if len(parts) < 2:+ # Cannot split into this space. Normally that means the page+ # is too full, and a fresh one solves it.+ #+ # If we are *already* at the top of a fresh page, it does+ # not: the content will not fit anywhere, and asking for+ # another page would ask forever. Draw it and move on; an+ # overrun on one invoice beats a request that never returns+ # and holds a worker until it is killed.+ if on_fresh_page:+ remaining.drawOn(canvas, MARGIN, y - needed)+ return y - needed+ pages.append([])+ canvas.showPage()+ y = _draw_continuation_header(canvas, document, accent)+ on_fresh_page = True+ continue++ head, tail = parts[0], parts[1]+ head_height = head.wrap(CONTENT_WIDTH, PAGE_HEIGHT)[1]+ head.drawOn(canvas, MARGIN, y - head_height)+ pages.append([])+ canvas.showPage()+ y = _draw_continuation_header(canvas, document, accent)+ remaining = tail+ # The page the tail lands on carries only the continuation+ # header, so it counts as fresh for the same reason.+ on_fresh_page = True+ return y++def _draw_continuation_header(canvas, document: InvoiceDocument, accent) -> float:"""A slim masthead for pages 2+.@@ -494,7 +627,7 @@ def _draw_continuation_header(canvas, document: InvoiceDocument, accent) -> floay = PAGE_HEIGHT - MARGINcanvas.setFont("Helvetica-Bold", 11)canvas.setFillColor(INK)- canvas.drawString(MARGIN, y - 4 * mm, document.labels["invoice"])+ canvas.drawString(MARGIN, y - 4 * mm, _title(document))if document.number:canvas.setFont("Helvetica-Bold", 11)canvas.setFillColor(accent)diff --git a/backend/app/services/invoice_schedule_service.py b/backend/app/services/invoice_schedule_service.pyindex 4ffe3bea..c73119f7 100644--- a/backend/app/services/invoice_schedule_service.py+++ b/backend/app/services/invoice_schedule_service.py@@ -49,7 +49,13 @@ from sqlalchemy import func, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession-from app.models.invoice import Invoice, InvoiceAllocation, InvoiceSettings+from app.models.invoice import (+ Invoice,+ InvoiceAllocation,+ InvoiceDeduction,+ InvoiceInstallment,+ InvoiceSettings,+)from app.models.invoice_schedule import (MAX_CONSECUTIVE_FAILURES,PERIODS_PER_YEAR,@@ -419,17 +425,40 @@ class ScheduleFigures:past_due_count: int+def _first_unpaid_due(+ installments: Optional[list[tuple[_date, Decimal]]],+ settled: Decimal,+ total: Decimal,+ due_date: _date,+) -> Optional[_date]:+ """`invoice_service.first_unpaid_due` over plain rows instead of a+ loaded invoice: settled money covers the schedule first to last, and+ the first installment it does not cover is the one that can be late."""+ if not installments:+ return due_date if settled < total else None+ running = ZERO+ for due, amount in installments:+ running += amount+ if running > settled:+ return due+ return None++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.+ """The derived money facts for many schedules in three queries.Void and uncollectible invoices count towards nothing here, for thesame reason they read as zero everywhere else. Drafts are counted asinvoices but not as money, since nothing is owed yet.++ Past due follows the invoice's own reading: with installments, the+ first one the settled money does not cover is the one that can be+ late, not the invoice's due date (which is the last of them)."""today = today or _today()empty = ScheduleFigures(0, ZERO, ZERO, 0)@@ -444,16 +473,27 @@ async def figures_for(.group_by(InvoiceAllocation.invoice_id).subquery())+ deducted = (+ select(+ InvoiceDeduction.invoice_id.label("invoice_id"),+ func.coalesce(func.sum(InvoiceDeduction.amount), 0).label("deducted"),+ )+ .group_by(InvoiceDeduction.invoice_id)+ .subquery()+ )rows = (await session.execute(select(+ Invoice.id,Invoice.schedule_id,Invoice.status,Invoice.due_date,Invoice.total,func.coalesce(allocated.c.paid, 0).label("paid"),+ func.coalesce(deducted.c.deducted, 0).label("deducted"),).outerjoin(allocated, allocated.c.invoice_id == Invoice.id)+ .outerjoin(deducted, deducted.c.invoice_id == Invoice.id).where(Invoice.workspace_id == workspace_id,Invoice.schedule_id.in_(schedule_ids),@@ -461,6 +501,17 @@ async def figures_for()).all()+ # The schedules of the open invoices, in one query, first to last.+ open_ids = [row.id for row in rows if row.status == "open"]+ installments: dict[uuid.UUID, list[tuple[_date, Decimal]]] = {}+ if open_ids:+ for invoice_id, due_date, amount in await session.execute(+ select(InvoiceInstallment.invoice_id, InvoiceInstallment.due_date, InvoiceInstallment.amount)+ .where(InvoiceInstallment.invoice_id.in_(open_ids))+ .order_by(InvoiceInstallment.invoice_id, InvoiceInstallment.position)+ ):+ installments.setdefault(invoice_id, []).append((due_date, Decimal(str(amount))))+counts: dict[uuid.UUID, dict[str, Any]] = {}for row in rows:acc = counts.setdefault(@@ -472,9 +523,11 @@ async def figures_for(continuetotal = Decimal(str(row.total))paid = Decimal(str(row.paid))+ settled = paid + Decimal(str(row.deducted))acc["invoiced"] += totalacc["paid"] += min(paid, total)- if row.due_date < today and paid < total:+ unpaid_due = _first_unpaid_due(installments.get(row.id), settled, total, row.due_date)+ if unpaid_due is not None and unpaid_due < today:acc["past_due"] += 1return {diff --git a/backend/app/services/invoice_service.py b/backend/app/services/invoice_service.pyindex ea2b2920..5e5efd0c 100644--- a/backend/app/services/invoice_service.py+++ b/backend/app/services/invoice_service.py@@ -26,9 +26,12 @@ from sqlalchemy.orm import selectinloadfrom app.core.app_clock import app_timezone, app_todayfrom app.fiscal.registry import TaxIdKind, normalise_and_validatefrom app.models.invoice import (+ DEDUCTION_KINDS,MANUAL_METHOD,Invoice,InvoiceAllocation,+ InvoiceDeduction,+ InvoiceInstallment,InvoiceLine,InvoiceSettings,)@@ -205,11 +208,88 @@ async def set_issuer_tax_ids(# Derived state — the whole point# ---------------------------------------------------------------------------def allocated_total(invoice: Invoice) -> Decimal:+ """Money that arrived. Cash, and only cash."""return sum((a.amount for a in invoice.allocations), ZERO)+def deducted_total(invoice: Invoice) -> Decimal:+ """Debt closed without cash: tax withheld, fees kept."""+ return sum((d.amount for d in invoice.deductions), ZERO)+++def settled_total(invoice: Invoice) -> Decimal:+ return allocated_total(invoice) + deducted_total(invoice)++def balance(invoice: Invoice) -> Decimal:- return (invoice.total or ZERO) - allocated_total(invoice)+ return (invoice.total or ZERO) - settled_total(invoice)+++def first_unpaid_due(invoice: Invoice) -> Optional[_date]:+ """The date the next money is late after.++ Without installments it is the invoice's own due date. With them,+ settled money is read first-to-last against the schedule, and the+ first installment the running total does not cover is the one that+ can be late. None once nothing is owed.+ """+ if not invoice.installments:+ return invoice.due_date if balance(invoice) > ZERO else None+ covered = settled_total(invoice)+ running = ZERO+ for installment in invoice.installments:+ running += installment.amount+ if running > covered:+ return installment.due_date+ return None+++def open_installments(invoice: Invoice) -> list[tuple[_date, Decimal]]:+ """What is still owed on each installment not yet covered, first to+ last, as (due date, remainder). The remainders add up to the balance.+ Empty for an invoice without a schedule, or once it is settled."""+ covered = settled_total(invoice)+ out: list[tuple[_date, Decimal]] = []+ for installment in invoice.installments:+ share = min(installment.amount, max(covered, ZERO))+ covered -= share+ if share < installment.amount:+ out.append((installment.due_date, installment.amount - share))+ return out+++def installment_states(+ invoice: Invoice, today: Optional[_date] = None+) -> list[dict[str, Any]]:+ """Each installment with how much of it is settled and what it reads as."""+ reference = today or app_today()+ covered = settled_total(invoice)+ out: list[dict[str, Any]] = []+ for installment in invoice.installments:+ share = min(installment.amount, max(covered, ZERO))+ covered -= share+ if share >= installment.amount:+ state = "paid"+ elif invoice.status in ("void", "uncollectible", "draft"):+ state = invoice.status+ elif installment.due_date < reference:+ state = "overdue"+ elif share > ZERO:+ state = "partial"+ else:+ state = "open"+ out.append(+ {+ "id": installment.id,+ "position": installment.position,+ "label": installment.label,+ "due_date": installment.due_date,+ "amount": installment.amount,+ "settled": share,+ "state": state,+ }+ )+ return out#: What a reader sees: the three terminal decisions, plus the four facts@@ -244,16 +324,18 @@ def derive_state(invoice: Invoice, today: Optional[_date] = None) -> DerivedStatreturn "paid"reference = today or app_today()- if invoice.due_date and invoice.due_date < reference:+ due = first_unpaid_due(invoice)+ if due and due < reference:return "overdue"- return "partial" if allocated_total(invoice) > ZERO else "open"+ return "partial" if settled_total(invoice) > ZERO else "open"def days_overdue(invoice: Invoice, today: Optional[_date] = None) -> int:reference = today or app_today()if derive_state(invoice, reference) != "overdue":return 0- return (reference - invoice.due_date).days+ due = first_unpaid_due(invoice) or invoice.due_date+ return (reference - due).days# ---------------------------------------------------------------------------@@ -595,6 +677,58 @@ async def _resolved_lines(return await product_service.resolve_lines(session, workspace_id, lines)+async def _set_installments(+ session: AsyncSession, invoice: Invoice, rows: Optional[list[dict[str, Any]]]+) -> None:+ """Replace the schedule. Amounts must add up to the total, to the+ cent, and the invoice's own due date becomes the last one so every+ sort and filter on `due_date` keeps meaning "when is the last of it+ owed". An empty list clears the schedule and leaves `due_date` as+ the caller set it."""+ # The old rows go first, and are flushed first: the new ones reuse+ # their positions, and one flush with both would trip the unique+ # (invoice, position) on the insert that runs before the delete.+ for existing in list(invoice.installments):+ await session.delete(existing)+ invoice.installments = []+ await session.flush()+ if not rows:+ return+ if len(rows) < 2:+ raise InvoiceError("installments_too_few", "A schedule needs at least two installments")+ cleaned: list[tuple[_date, Decimal, Optional[str]]] = []+ for row in rows:+ amount = Decimal(str(row.get("amount", 0))).quantize(Decimal("0.01"))+ if amount <= ZERO:+ raise InvoiceError("installment_amount_not_positive", "Every installment must be worth something")+ due = row.get("due_date")+ if due is None:+ raise InvoiceError("installment_due_required", "Every installment needs a due date")+ if due < invoice.issue_date:+ raise InvoiceError("due_before_issue", "Due date cannot precede the issue date")+ label = (row.get("label") or "").strip() or None+ cleaned.append((due, amount, label))+ total = sum((amount for _, amount, _ in cleaned), ZERO)+ if total != (invoice.total or ZERO).quantize(Decimal("0.01")):+ raise InvoiceError(+ "installments_mismatch",+ f"The installments add up to {total}, the invoice to {invoice.total}",+ )+ cleaned.sort(key=lambda row: row[0])+ for position, (due, amount, label) in enumerate(cleaned):+ invoice.installments.append(+ InvoiceInstallment(+ invoice_id=invoice.id,+ workspace_id=invoice.workspace_id,+ position=position,+ label=label,+ due_date=due,+ amount=amount,+ )+ )+ invoice.due_date = cleaned[-1][0]++async def create_invoice(session: AsyncSession,workspace_id: uuid.UUID,@@ -678,8 +812,11 @@ async def create_invoice(for position, line in enumerate(lines_data):session.add(_build_line(invoice, line, position))await session.flush()- await session.refresh(invoice, ["lines", "allocations", "payee"])+ await session.refresh(invoice, ["lines", "allocations", "deductions", "installments", "payee"])_recompute_totals(invoice)+ # After the totals, because the schedule has to add up to them.+ if data.get("installments"):+ await _set_installments(session, invoice, data["installments"])# `open` on creation is the tracking preset's whole point: the money# is already owed, and making the user press "issue" on a note to@@ -741,9 +878,23 @@ async def update_invoice(session: AsyncSession, invoice: Invoice, data: dict[strif invoice.due_date < invoice.issue_date:raise InvoiceError("due_before_issue", "Due date cannot precede the issue date")++ # A schedule follows the total. Sent along, it replaces the old+ # one; left out while the total moved, the old one no longer adds+ # up and the caller has to say what the new split is.+ if "installments" in data:+ await _set_installments(session, invoice, data["installments"])+ elif invoice.installments:+ scheduled = sum((i.amount for i in invoice.installments), ZERO)+ if scheduled != (invoice.total or ZERO).quantize(Decimal("0.01")):+ raise InvoiceError(+ "installments_mismatch",+ "The total changed; send the installments again so they add up to it",+ )+ invoice.due_date = invoice.installments[-1].due_dateelse:rejected = {k for k in data if k in _DRAFT_ONLY_FIELDS and data[k] is not None}- if rejected or data.get("lines") is not None:+ if rejected or data.get("lines") is not None or data.get("installments") is not None:raise InvoiceError("issued_invoice_immutable","An issued invoice's financial fields cannot change — void it and issue a new one",@@ -881,7 +1032,7 @@ async def void_invoice(session: AsyncSession, invoice: Invoice) -> Invoice:raise InvoiceError("draft_not_voidable", "Delete the draft instead of voiding it")if invoice.status == "void":return invoice- if invoice.allocations:+ if invoice.allocations or invoice.deductions:raise InvoiceError("void_with_allocations", "Unlink the payments before voiding this invoice")@@ -951,6 +1102,9 @@ async def allocate("""if invoice.status != "open":raise InvoiceError("not_open", "Only an open invoice can be settled")+ # The balance reads both collections, and an instance that was just+ # written may not have loaded them yet.+ await session.refresh(invoice, ["allocations", "deductions"])result = await session.execute(select(Transaction).where(@@ -1003,10 +1157,68 @@ async def allocate(raise InvoiceError("already_allocated", "This transaction is already linked to this invoice")- await session.refresh(invoice, ["allocations"])+ await session.refresh(invoice, ["allocations", "deductions"])return allocation+async def deduct(+ session: AsyncSession,+ invoice: Invoice,+ kind: str,+ amount: Decimal,+ *,+ tax_kind: Optional[str] = None,+ note: Optional[str] = None,+ transaction_id: Optional[uuid.UUID] = None,+) -> InvoiceDeduction:+ """Close part of the debt without money: the client withheld tax,+ the gateway kept its fee. Same guards as a payment, one difference:+ `amount_paid` never moves."""+ if invoice.status != "open":+ raise InvoiceError("not_open", "Only an open invoice can be settled")+ if kind not in DEDUCTION_KINDS:+ raise InvoiceError("invalid_deduction_kind", "Unknown deduction kind")+ await session.refresh(invoice, ["allocations", "deductions"])+ available = balance(invoice)+ if available <= ZERO:+ raise InvoiceError("already_settled", "This invoice is already fully settled")+ proposed = Decimal(str(amount)).quantize(Decimal("0.01"))+ if proposed <= ZERO:+ raise InvoiceError("amount_not_positive", "Deduction amount must be positive")+ if proposed > available:+ raise InvoiceError("over_allocation", f"Only {available} remains on this invoice")+ if transaction_id is not None:+ owned = await session.execute(+ select(Transaction.id).where(+ Transaction.id == transaction_id, Transaction.workspace_id == invoice.workspace_id+ )+ )+ if owned.scalar_one_or_none() is None:+ raise InvoiceError("transaction_not_found", "Transaction not found in this workspace", 404)+ deduction = InvoiceDeduction(+ invoice_id=invoice.id,+ workspace_id=invoice.workspace_id,+ kind=kind,+ tax_kind=((tax_kind or "").strip().lower() or None),+ amount=proposed,+ note=((note or "").strip() or None),+ transaction_id=transaction_id,+ )+ session.add(deduction)+ await session.flush()+ await session.refresh(invoice, ["deductions"])+ return deduction+++async def undeduct(session: AsyncSession, invoice: Invoice, deduction_id: uuid.UUID) -> None:+ deduction = next((d for d in invoice.deductions if d.id == deduction_id), None)+ if deduction is None:+ raise InvoiceError("deduction_not_found", "Deduction not found", 404)+ await session.delete(deduction)+ await session.flush()+ await session.refresh(invoice, ["deductions"])++async def unallocate(session: AsyncSession, invoice: Invoice, allocation_id: uuid.UUID) -> None:result = await session.execute(select(InvoiceAllocation).where(@@ -1019,7 +1231,7 @@ async def unallocate(session: AsyncSession, invoice: Invoice, allocation_id: uuiraise InvoiceError("allocation_not_found", "Allocation not found", 404)await session.delete(allocation)await session.flush()- await session.refresh(invoice, ["allocations"])+ await session.refresh(invoice, ["allocations", "deductions"])# ---------------------------------------------------------------------------diff --git a/backend/app/services/reconciliation_engine.py b/backend/app/services/reconciliation_engine.pyindex fdb06bce..866c20f6 100644--- a/backend/app/services/reconciliation_engine.py+++ b/backend/app/services/reconciliation_engine.py@@ -207,6 +207,17 @@ class Expectation:#: from when it comes due. An invoice has both and they are weeks#: apart; a recurring occurrence has one, and leaves this null.issued: Optional[date] = None+ #: The amounts at which this promise closes a whole part, smallest+ #: first, ending at `amount`. Set when the money was agreed in+ #: installments: a client paying the next one, or the next two at+ #: once, is paying exactly what was asked, and comparing that against+ #: the whole balance would call every installment a mismatch. Empty+ #: for a promise that is one amount on one date.+ stops: tuple[Decimal, ...] = ()++ def targets(self) -> tuple[Decimal, ...]:+ """What a movement's amount is compared against, in order."""+ return self.stops or (self.amount,)@dataclass(frozen=True)@@ -223,6 +234,10 @@ class Settlement:expectation: Expectationamount: Decimal+ #: The part of the promise the amount was measured against: the next+ #: installment, say, rather than the whole balance. None when that is+ #: the balance itself.+ target: Optional[Decimal] = None@dataclass@@ -750,7 +765,9 @@ def evaluate(return decisioncontinue- matched: list[tuple[Expectation, Optional[Decimal], Optional[str], float]] = []+ matched: list[+ tuple[Expectation, Optional[Decimal], Optional[str], float, Optional[Decimal]]+ ] = []for candidate in candidates:note = Consideration(expectation_id=candidate.id, strategy=strategy["id"])@@ -852,9 +869,16 @@ def evaluate(continuenaming = sum(1 for side in sides if side) / 2.0- ok, difference, difference_kind = _amount_verdict(- movement.amount, candidate.amount, rule.get("amount", {}), ratios- )+ # Against each whole part in turn, next installment first,+ # so the smallest honest reading wins: a payment of exactly+ # one installment is that installment, not a part of the rest.+ ok, difference, difference_kind, target = False, None, None, None+ for target in candidate.targets():+ ok, difference, difference_kind = _amount_verdict(+ movement.amount, target, rule.get("amount", {}), ratios+ )+ if ok:+ breakif not ok:note.rejected_by = Reason.AMOUNTtrace.append(note)@@ -884,7 +908,7 @@ def evaluate(note.score = scoretrace.append(note)- matched.append((candidate, difference, difference_kind, score))+ matched.append((candidate, difference, difference_kind, score, target))if not matched:continue@@ -912,7 +936,7 @@ def evaluate(# whatever `unique_candidate` says next applies to those. A# clear winner is one candidate and links; a genuine tie is# still several and does not.- def _closeness(entry: tuple[Expectation, Any, Any, float]):+ def _closeness(entry: tuple[Expectation, Any, Any, float, Any]):return (-entry[3], abs((movement.when - entry[0].when).days))ranked = sorted(matched, key=_closeness)@@ -944,14 +968,20 @@ def evaluate(note.rejected_by = Reason.AMBIGUOUSmatched.sort(key=lambda m: m[3], reverse=True)- winner, difference, difference_kind, score = matched[0]+ winner, difference, difference_kind, score, target = matched[0]settled = min(abs(movement.amount), winner.amount)return Decision(port="linked" if outcome == "link" else "suggested",# Always a set, even when it holds one. A caller that has to# ask "is this the single kind or the several kind" before it# can write anything is a caller that will one day forget to.- settlements=[Settlement(expectation=winner, amount=settled)],+ settlements=[+ Settlement(+ expectation=winner,+ amount=settled,+ target=target if target != winner.amount else None,+ )+ ],expectation=winner,strategy=strategy["id"],amount=settled,diff --git a/backend/app/services/reconciliation_service.py b/backend/app/services/reconciliation_service.pyindex 79d469fe..17eaa8d4 100644--- a/backend/app/services/reconciliation_service.py+++ b/backend/app/services/reconciliation_service.py@@ -85,15 +85,25 @@ def _as_expectation(invoice: Invoice) -> Expectation:The amount is the **balance**, never the total: an invoice half paidexpects the other half, and a market that pays by Pix pays in parts."""+ # In installments, what is expected next is the next one, not the+ # whole balance: the date it is due, and the amounts at which one,+ # two or all of the remaining ones close.+ remaining = invoice_service.open_installments(invoice)+ stops: list[Decimal] = []+ running = Decimal("0")+ for _, remainder in remaining:+ running += remainder+ stops.append(running)return Expectation(kind="invoice",id=invoice.id,amount=invoice_service.balance(invoice),+ stops=tuple(stops),currency=invoice.currency,# A receivable is settled by money coming in, a payable by money# going out. The engine refuses a candidate facing the wrong way.direction="credit" if invoice.direction == "receivable" else "debit",- when=invoice.due_date,+ when=remaining[0][0] if remaining else invoice.due_date,# Both dates: late is measured from the due date, early from the# day the document was written.issued=invoice.issue_date,@@ -462,7 +472,11 @@ async def match_for_invoice(if not policy["strategies"]:return None- window_start = invoice.due_date - timedelta(days=LOOKBACK_DAYS)+ # From the first date money is owed, not the invoice's due date: in+ # installments that is the last one, and the upfront payment made the+ # day the document was written would sit months before the window.+ anchor = invoice_service.first_unpaid_due(invoice) or invoice.due_date+ window_start = min(anchor, invoice.issue_date) - timedelta(days=LOOKBACK_DAYS)wanted_direction = "credit" if invoice.direction == "receivable" else "debit"# Not narrowed by payee any more. The old query could afford itdiff --git a/backend/app/services/reconciliation_suggestion_service.py b/backend/app/services/reconciliation_suggestion_service.pyindex 2c2aad23..75193fc7 100644--- a/backend/app/services/reconciliation_suggestion_service.py+++ b/backend/app/services/reconciliation_suggestion_service.py@@ -60,6 +60,9 @@ def _signal_scores(verdict."""expectation = settlement.expectation+ # The part that was expected (the next installment) when there was+ # one, so the queue does not call an exact installment "short".+ expected = settlement.target if settlement.target is not None else expectation.amountreturn {"strategy": decision.strategy,# How many promises this one payment is being offered against, so@@ -67,9 +70,9 @@ def _signal_scores(# that looks wrong on its own."of_set": len(decision.settlements),"description": round(decision.score, 3),- "amount_expected": str(expectation.amount),+ "amount_expected": str(expected),"amount_moved": str(abs(movement.amount)),- "amount_exact": settlement.amount == expectation.amount,+ "amount_exact": settlement.amount == expected,"days_apart": (movement.when - expectation.when).days,"same_counterparty": bool(movement.payee_id and movement.payee_id == expectation.payee_id@@ -331,6 +334,38 @@ async def mark_accepted(return suggestion+async def settled_by_hand(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ transaction_id: uuid.UUID,+ expectation_id: uuid.UUID,+ user_id: Optional[uuid.UUID],+) -> int:+ """A person linked this money to this promise themselves: the question+ the queue was asking about the pair has been answered.++ Left pending, the suggestion kept offering a link that already exists,+ and taking it would only fail. Marked accepted rather than deleted,+ because that is what happened: somebody agreed, by another door. The+ link itself was already written to the history by the caller, so no+ second event is recorded here.+ """+ result = await session.execute(+ select(ReconciliationSuggestion).where(+ ReconciliationSuggestion.workspace_id == workspace_id,+ ReconciliationSuggestion.transaction_id == transaction_id,+ ReconciliationSuggestion.expectation_id == expectation_id,+ ReconciliationSuggestion.status == "pending",+ )+ )+ rows = list(result.unique().scalars().all())+ for suggestion in rows:+ _resolve(suggestion, "accepted", user_id)+ if rows:+ await session.flush()+ return len(rows)++def _by_question(rows: list[ReconciliationSuggestion],) -> list[list[ReconciliationSuggestion]]:diff --git a/backend/tests/test_installments_deductions.py b/backend/tests/test_installments_deductions.pynew file mode 100644index 00000000..a6fcf83a--- /dev/null+++ b/backend/tests/test_installments_deductions.py@@ -0,0 +1,458 @@+"""Two ways one invoice's money is not one amount on one date.++Installments: the schedule the client agreed to. Nothing is allocated to+an installment; settled money covers the schedule first-to-last when+read, so the tests here are mostly about that reading: which+installment is late, when the invoice as a whole is late, and what the+forecast promises on which date.++Deductions: debt closed without money. The one rule to pin down is the+split between *settled* and *received*: a deduction moves the balance+and the state, never `amount_paid` or "received this month".+"""+import uuid+from datetime import date+from decimal import Decimal++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.invoice import Invoice+from app.models.payee import Payee+from app.models.transaction import Transaction+from app.models.workspace import WorkspaceMember+from app.services import invoice_forecast_service as forecast+from app.services import invoice_service as svc+from app.services.invoice_service import InvoiceError++TODAY = date(2026, 9, 24)+ISSUE = date(2026, 9, 1)+++@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 biz_headers(auth_headers, business_ws) -> dict:+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}+++@pytest_asyncio.fixture+async def account(session: AsyncSession, ws_id, test_user) -> Account:+ acc = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=ws_id, name="PJ", type="checking",+ currency="USD", balance=Decimal("0"),+ )+ session.add(acc)+ await session.commit()+ return acc+++async def credit(session, ws_id, user_id, account, amount: str, on: date = TODAY) -> Transaction:+ tx = Transaction(+ id=uuid.uuid4(), user_id=user_id, workspace_id=ws_id, account_id=account.id,+ description="PIX", amount=Decimal(amount), currency="USD", date=on, type="credit", source="manual",+ )+ session.add(tx)+ await session.commit()+ return tx+++THREE = [+ {"due_date": date(2026, 10, 1), "amount": "1000.00", "label": "1/3"},+ {"due_date": date(2026, 11, 1), "amount": "1000.00", "label": "2/3"},+ {"due_date": date(2026, 12, 1), "amount": "1000.00", "label": "3/3"},+]+++async def an_invoice(session, ws_id, user_id, **overrides) -> Invoice:+ data = {"total": Decimal("3000.00"), "issue_date": ISSUE, "due_date": date(2026, 10, 1), "currency": "USD"}+ data.update(overrides)+ invoice = await svc.create_invoice(session, ws_id, user_id, data)+ await session.commit()+ return invoice+++# ---------------------------------------------------------------------------+# Installments+# ---------------------------------------------------------------------------+class TestInstallments:+ @pytest.mark.asyncio+ async def test_the_schedule_is_written_sorted_and_sets_the_due_date(self, session, ws_id, test_user):+ inv = await an_invoice(session, ws_id, test_user.id, installments=list(reversed(THREE)))+ assert [(i.position, i.label, i.due_date) for i in inv.installments] == [+ (0, "1/3", date(2026, 10, 1)), (1, "2/3", date(2026, 11, 1)), (2, "3/3", date(2026, 12, 1)),+ ]+ # The invoice's own due date is the last of them, so "due" keeps+ # meaning "when is the last of it owed" in every list.+ assert inv.due_date == date(2026, 12, 1)+ assert svc.first_unpaid_due(inv) == date(2026, 10, 1)++ @pytest.mark.asyncio+ async def test_the_schedule_must_add_up_and_make_sense(self, session, ws_id, test_user):+ for rows, code in (+ ([THREE[0], {**THREE[1], "amount": "999.00"}, THREE[2]], "installments_mismatch"),+ ([THREE[0]], "installments_too_few"),+ ([THREE[0], {**THREE[1], "amount": "0"}, {**THREE[2], "amount": "2000"}], "installment_amount_not_positive"),+ ([THREE[0], {**THREE[1], "due_date": date(2026, 8, 1)}, THREE[2]], "due_before_issue"),+ ):+ with pytest.raises(InvoiceError) as exc:+ await an_invoice(session, ws_id, test_user.id, installments=rows)+ assert exc.value.code == code++ @pytest.mark.asyncio+ async def test_money_covers_the_schedule_first_to_last(self, session, ws_id, test_user, account):+ """One transfer of 1,500 pays the first installment and half of the+ second. Nobody had to say which."""+ inv = await an_invoice(session, ws_id, test_user.id, installments=THREE)+ tx = await credit(session, ws_id, test_user.id, account, "1500.00")+ await svc.allocate(session, inv, tx.id)+ states = svc.installment_states(inv, today=date(2026, 10, 15))+ assert [(s["state"], s["settled"]) for s in states] == [+ ("paid", Decimal("1000.00")), ("partial", Decimal("500.00")), ("open", Decimal("0")),+ ]+ assert svc.first_unpaid_due(inv) == date(2026, 11, 1)+ # Not late on October 15: the first one is paid and the second is+ # not due yet. The whole invoice reads as partial.+ assert svc.derive_state(inv, date(2026, 10, 15)) == "partial"+ assert svc.days_overdue(inv, date(2026, 10, 15)) == 0++ @pytest.mark.asyncio+ async def test_late_means_the_first_unpaid_installment_is_late(self, session, ws_id, test_user, account):+ inv = await an_invoice(session, ws_id, test_user.id, installments=THREE)+ # October 2: the first installment was due yesterday. Late by one+ # day, even though the invoice's own due date is December.+ assert svc.derive_state(inv, date(2026, 10, 2)) == "overdue"+ assert svc.days_overdue(inv, date(2026, 10, 2)) == 1+ states = svc.installment_states(inv, today=date(2026, 10, 2))+ assert [s["state"] for s in states] == ["overdue", "open", "open"]+ # Paying it stops the clock until November.+ tx = await credit(session, ws_id, test_user.id, account, "1000.00")+ await svc.allocate(session, inv, tx.id)+ assert svc.derive_state(inv, date(2026, 10, 2)) == "partial"+ assert svc.derive_state(inv, date(2026, 11, 2)) == "overdue"+ assert svc.days_overdue(inv, date(2026, 11, 2)) == 1++ @pytest.mark.asyncio+ async def test_paid_in_full_reads_paid_whatever_the_dates(self, session, ws_id, test_user, account):+ inv = await an_invoice(session, ws_id, test_user.id, installments=THREE)+ tx = await credit(session, ws_id, test_user.id, account, "3000.00")+ await svc.allocate(session, inv, tx.id)+ assert svc.derive_state(inv, date(2027, 6, 1)) == "paid"+ assert svc.first_unpaid_due(inv) is None+ assert [s["state"] for s in svc.installment_states(inv)] == ["paid"] * 3++ @pytest.mark.asyncio+ async def test_a_draft_edit_keeps_the_schedule_honest(self, session, ws_id, test_user):+ inv = await an_invoice(session, ws_id, test_user.id, as_draft=True, installments=THREE)+ assert inv.status == "draft"+ # A new total without a new schedule is refused: the old one no+ # longer adds up and nobody said what the split is now.+ with pytest.raises(InvoiceError) as exc:+ await svc.update_invoice(session, inv, {"total": Decimal("4000.00")})+ assert exc.value.code == "installments_mismatch"+ await svc.update_invoice(+ session, inv,+ {"total": Decimal("4000.00"),+ "installments": [{"due_date": date(2026, 10, 1), "amount": "2000"}, {"due_date": date(2026, 12, 1), "amount": "2000"}]},+ )+ assert [i.amount for i in inv.installments] == [Decimal("2000.00"), Decimal("2000.00")]+ assert inv.due_date == date(2026, 12, 1)+ # An empty list clears it, and the due date is the caller's again.+ await svc.update_invoice(session, inv, {"installments": [], "due_date": date(2026, 10, 20)})+ assert inv.installments == [] and inv.due_date == date(2026, 10, 20)++ @pytest.mark.asyncio+ async def test_an_issued_invoice_keeps_its_schedule(self, session, ws_id, test_user):+ inv = await an_invoice(session, ws_id, test_user.id, installments=THREE)+ assert inv.status == "open"+ with pytest.raises(InvoiceError) as exc:+ await svc.update_invoice(session, inv, {"installments": []})+ assert exc.value.code == "issued_invoice_immutable"++ @pytest.mark.asyncio+ async def test_the_forecast_promises_each_installment_on_its_date(self, session, ws_id, test_user, account):+ inv = await an_invoice(session, ws_id, test_user.id, installments=THREE)+ window = (date(2026, 9, 1), date(2027, 1, 1))+ claims = sorted((c.due_date, c.amount) for c in await forecast.claims_in_range(session, ws_id, *window))+ assert claims == [(date(2026, 10, 1), Decimal("1000.00")), (date(2026, 11, 1), Decimal("1000.00")), (date(2026, 12, 1), Decimal("1000.00"))]+ # 1,500 received: the first is gone, the second is half, the third whole.+ tx = await credit(session, ws_id, test_user.id, account, "1500.00")+ await svc.allocate(session, inv, tx.id)+ await session.commit()+ claims = sorted((c.due_date, c.amount) for c in await forecast.claims_in_range(session, ws_id, *window))+ assert claims == [(date(2026, 11, 1), Decimal("500.00")), (date(2026, 12, 1), Decimal("1000.00"))]+ # A window that only holds the middle date holds only the middle claim.+ claims = await forecast.claims_in_range(session, ws_id, date(2026, 10, 15), date(2026, 11, 15))+ assert [(c.due_date, c.amount) for c in claims] == [(date(2026, 11, 1), Decimal("500.00"))]++ @pytest.mark.asyncio+ async def test_aging_reads_the_late_installment_not_the_last_date(self, session, ws_id, test_user):+ """December's invoice, first installment a week late: the whole+ balance is 1 to 30 days overdue, not "current"."""+ await an_invoice(session, ws_id, test_user.id, installments=THREE)+ summary = await svc.aging_summary(session, ws_id, today=date(2026, 10, 8))+ assert summary["overdue_count"] == 1+ assert summary["overdue_amount"] == Decimal("3000.00")+ assert summary["buckets"]["d1_30"] == Decimal("3000.00")+++# ---------------------------------------------------------------------------+# Deductions+# ---------------------------------------------------------------------------+class TestDeductions:+ @pytest.mark.asyncio+ async def test_a_deduction_settles_without_being_received(self, session, ws_id, test_user, account):+ """The client paid 2,850 and withheld 150 of tax. The invoice is+ paid; what arrived is 2,850; the accountant can see the 150."""+ inv = await an_invoice(session, ws_id, test_user.id)+ tx = await credit(session, ws_id, test_user.id, account, "2850.00")+ await svc.allocate(session, inv, tx.id)+ assert svc.derive_state(inv, TODAY) == "partial"+ await svc.deduct(session, inv, "withholding_tax", Decimal("150"), tax_kind=" IRRF ", note="1.5%", transaction_id=tx.id)+ await session.commit()+ assert svc.derive_state(inv, TODAY) == "paid"+ assert svc.allocated_total(inv) == Decimal("2850.00")+ assert svc.deducted_total(inv) == Decimal("150.00")+ assert svc.balance(inv) == Decimal("0.00")+ assert inv.deductions[0].tax_kind == "irrf"+ summary = await svc.aging_summary(session, ws_id, today=TODAY)+ assert summary["received_this_month"] == Decimal("2850.00")+ assert summary["outstanding"] == Decimal("0.00")++ @pytest.mark.asyncio+ async def test_guards(self, session, ws_id, test_user):+ inv = await an_invoice(session, ws_id, test_user.id)+ cases: list[tuple[str, Decimal, uuid.UUID | None, str]] = [+ ("tip", Decimal("1"), None, "invalid_deduction_kind"),+ ("gateway_fee", Decimal("0"), None, "amount_not_positive"),+ ("gateway_fee", Decimal("3000.01"), None, "over_allocation"),+ ("gateway_fee", Decimal("1"), uuid.uuid4(), "transaction_not_found"),+ ]+ for kind, amount, transaction_id, code in cases:+ with pytest.raises(InvoiceError) as exc:+ await svc.deduct(session, inv, kind, amount, transaction_id=transaction_id)+ assert exc.value.code == code+ draft = await an_invoice(session, ws_id, test_user.id, as_draft=True)+ with pytest.raises(InvoiceError) as exc:+ await svc.deduct(session, draft, "gateway_fee", Decimal("1"))+ assert exc.value.code == "not_open"++ @pytest.mark.asyncio+ async def test_removing_a_deduction_reopens_the_balance_and_void_waits_for_it(self, session, ws_id, test_user):+ inv = await an_invoice(session, ws_id, test_user.id)+ d = await svc.deduct(session, inv, "gateway_fee", Decimal("3000"))+ assert svc.derive_state(inv, TODAY) == "paid"+ with pytest.raises(InvoiceError) as exc:+ await svc.void_invoice(session, inv)+ assert exc.value.code == "void_with_allocations"+ await svc.undeduct(session, inv, d.id)+ assert svc.balance(inv) == Decimal("3000.00")+ with pytest.raises(InvoiceError) as exc:+ await svc.undeduct(session, inv, d.id)+ assert exc.value.code == "deduction_not_found"+ await svc.void_invoice(session, inv)+ assert inv.status == "void"++ @pytest.mark.asyncio+ async def test_a_deduction_covers_installments_like_money_does(self, session, ws_id, test_user):+ inv = await an_invoice(session, ws_id, test_user.id, installments=THREE)+ await svc.deduct(session, inv, "other", Decimal("1000"), note="credit agreed by phone")+ assert [s["state"] for s in svc.installment_states(inv, today=date(2026, 10, 2))] == ["paid", "open", "open"]+ assert svc.derive_state(inv, date(2026, 10, 2)) == "partial"+ await session.commit()+ claims = await forecast.claims_in_range(session, ws_id, date(2026, 9, 1), date(2027, 1, 1))+ assert sorted(c.due_date for c in claims) == [date(2026, 11, 1), date(2026, 12, 1)]+++# ---------------------------------------------------------------------------+# Over HTTP+# ---------------------------------------------------------------------------+@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+++@pytest_asyncio.fixture+async def viewer_headers(session: AsyncSession, client: AsyncClient, business_ws) -> dict:+ 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"]}+++async def test_installments_and_deductions_over_http(client: AsyncClient, biz_headers, session, ws_id, test_user, account):+ resp = await client.post(+ "/api/invoices", headers=biz_headers,+ json={"total": "3000.00", "issue_date": str(ISSUE), "currency": "USD",+ "installments": [{"due_date": "2026-10-01", "amount": "1500.00", "label": "Upfront"},+ {"due_date": "2026-12-01", "amount": "1500.00", "label": "On delivery"}]},+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert body["due_date"] == "2026-12-01"+ assert body["next_due_date"] == "2026-10-01"+ assert [(i["label"], i["state"], i["settled"]) for i in body["installments"]] == [+ ("Upfront", "open", "0.00"), ("On delivery", "open", "0.00"),+ ]+ invoice_id = body["id"]++ resp = await client.post("/api/invoices", headers=biz_headers, json={"total": "10", "installments": [{"due_date": "2026-10-01", "amount": "5"}, {"due_date": "2026-11-01", "amount": "6"}]})+ assert resp.status_code == 400 and resp.json()["detail"]["code"] == "installments_mismatch"++ # A deduction of 100 closes part of the first installment.+ resp = await client.post(f"/api/invoices/{invoice_id}/deductions", headers=biz_headers, json={"kind": "gateway_fee", "amount": "100.00", "note": "processor fee"})+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert body["amount_deducted"] == "100.00" and body["amount_paid"] == "0.00" and body["balance"] == "2900.00"+ assert body["installments"][0]["settled"] == "100.00" and body["installments"][0]["state"] in ("partial", "overdue")+ deduction_id = body["deductions"][0]["id"]+ assert body["deductions"][0]["kind"] == "gateway_fee"+ # The document the client reads carries it too, so its totals add up.+ doc = (await client.get(f"/api/invoices/{invoice_id}/document", headers=biz_headers)).json()+ assert doc["amount_deducted"] == "100.00" and doc["balance"] == "2900.00"+ assert doc["labels"]["deducted"] == "Deduções" # the workspace writes in Portuguese++ resp = await client.post(f"/api/invoices/{invoice_id}/deductions", headers=biz_headers, json={"kind": "other", "amount": "5000"})+ assert resp.status_code == 400 and resp.json()["detail"]["code"] == "over_allocation"++ resp = await client.delete(f"/api/invoices/{invoice_id}/deductions/{deduction_id}", headers=biz_headers)+ assert resp.status_code == 200 and resp.json()["balance"] == "3000.00" and resp.json()["deductions"] == []+ assert (await client.delete(f"/api/invoices/{invoice_id}/deductions/{uuid.uuid4()}", headers=biz_headers)).status_code == 404+++async def test_gates(client: AsyncClient, biz_headers, viewer_headers, auth_headers):+ created = (await client.post("/api/invoices", headers=biz_headers, json={"total": "10"})).json()+ iid, fake = created["id"], str(uuid.uuid4())+ assert (await client.post(f"/api/invoices/{iid}/deductions", headers=viewer_headers, json={"kind": "other", "amount": "1"})).status_code == 403+ assert (await client.delete(f"/api/invoices/{iid}/deductions/{fake}", headers=viewer_headers)).status_code == 403+ 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.post(f"/api/invoices/{iid}/deductions", headers=other_headers, json={"kind": "other", "amount": "1"})).status_code == 404+++# ---------------------------------------------------------------------------+# Statement of account: how the invoice arrives at its balance+# ---------------------------------------------------------------------------+def _pdf_text(content: bytes) -> str:+ import io++ import pypdf++ return "\n".join(page.extract_text() for page in pypdf.PdfReader(io.BytesIO(content)).pages)+++async def test_the_statement_walks_from_the_total_to_the_balance(+ client: AsyncClient, biz_headers, session, ws_id, test_user, account+):+ """The invoice PDF is the document as issued and stays so. The+ statement is the one that says what happened since: each payment and+ deduction, then total, paid, deducted and what is left."""+ invoice = (await client.post(+ "/api/invoices", headers=biz_headers,+ json={"total": "3000.00", "issue_date": str(ISSUE), "currency": "USD",+ "installments": [{"due_date": "2026-10-01", "amount": "1500.00"},+ {"due_date": "2026-12-01", "amount": "1500.00"}]},+ )).json()+ tx = await credit(session, ws_id, test_user.id, account, "1455.00", on=date(2026, 9, 20))+ resp = await client.post(+ f"/api/invoices/{invoice['id']}/allocations", headers=biz_headers,+ json={"transaction_id": str(tx.id)},+ )+ assert resp.status_code in (200, 201), resp.text+ resp = await client.post(+ f"/api/invoices/{invoice['id']}/deductions", headers=biz_headers,+ json={"kind": "withholding_tax", "tax_kind": "irrf", "amount": "45.00", "note": "internal note",+ "transaction_id": str(tx.id)},+ )+ assert resp.status_code == 201, resp.text++ resp = await client.get(f"/api/invoices/{invoice['id']}/statement", headers=biz_headers)+ assert resp.status_code == 200, resp.text+ assert resp.headers["content-type"] == "application/pdf"+ assert "statement" in resp.headers["content-disposition"]+ text = _pdf_text(resp.content)+ # Titled as a statement, in the workspace's language (Portuguese here).+ assert "Extrato da fatura" in text+ # Each movement, named by kind and never by the bank's or our own text.+ assert "Pagamento recebido" in text and "USD 1,455.00" in text+ assert "Imposto retido (IRRF)" in text and "USD 45.00" in text+ assert "internal note" not in text and "PIX" not in text+ # And the walk from the total to the balance.+ assert "Deduções" in text and "USD 1,500.00" in text++ # The invoice itself is still the invoice.+ invoice_pdf = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert "Extrato da fatura" not in _pdf_text(invoice_pdf.content)+++async def test_an_untouched_invoice_states_its_whole_balance(client: AsyncClient, biz_headers):+ invoice = (await client.post("/api/invoices", headers=biz_headers, json={"total": "800.00", "currency": "USD"})).json()+ resp = await client.get(f"/api/invoices/{invoice['id']}/statement", headers=biz_headers)+ assert resp.status_code == 200+ text = _pdf_text(resp.content)+ assert "Saldo devedor" in text and "USD 800.00" in text+++async def test_no_statement_for_a_draft_or_a_bill_we_received(client: AsyncClient, biz_headers):+ draft = (await client.post("/api/invoices", headers=biz_headers, json={"total": "10.00", "as_draft": True})).json()+ resp = await client.get(f"/api/invoices/{draft['id']}/statement", headers=biz_headers)+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "statement_of_draft"++ bill = (await client.post("/api/invoices", headers=biz_headers, json={"total": "10.00", "direction": "payable"})).json()+ resp = await client.get(f"/api/invoices/{bill['id']}/statement", headers=biz_headers)+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "statement_not_ours"+++async def test_the_statement_stays_inside_its_workspace(client: AsyncClient, biz_headers, auth_headers):+ invoice = (await client.post("/api/invoices", headers=biz_headers, json={"total": "10.00"})).json()+ other = (await client.post(+ "/api/workspaces", headers=auth_headers,+ json={"name": "Other", "kind": "business", "self_membership": True},+ )).json()+ resp = await client.get(+ f"/api/invoices/{invoice['id']}/statement",+ headers={**auth_headers, "X-Workspace-Id": other["id"]},+ )+ assert resp.status_code == 404diff --git a/backend/tests/test_invoice_document.py b/backend/tests/test_invoice_document.pyindex 619dd15f..4a347064 100644--- a/backend/tests/test_invoice_document.py+++ b/backend/tests/test_invoice_document.py@@ -307,7 +307,7 @@ class TestPdf:number="1", status="open", state="open", issue_date=TODAY, due_date=TODAY,currency="USD", subtotal=Decimal("0"), discount=Decimal("0"),tax_total=Decimal("0"), total=Decimal("10"), amount_paid=Decimal("0"),- balance=Decimal("10"), issuer=DocumentParty(name="A"),+ amount_deducted=Decimal("0"), balance=Decimal("10"), issuer=DocumentParty(name="A"),client=DocumentParty(name="B"), lines=[], labels=dict(DEFAULT_LABELS),accent_color="#000000", logo_id=None, payment_details=None, notes=None,footer_note=None, custom_fields=[], has_line_items=False,@@ -510,7 +510,13 @@ class TestIssuerProfile:# ---------------------------------------------------------------------------# Page structure — the band layout and its pagination# ----------------------------------------------------------------------------def _doc(n_lines: int, footer_note: str = "Alpha ME"):+def _doc(+ n_lines: int,+ footer_note: str = "Alpha ME",+ n_installments: int = 0,+ paid: str = "0",+ deducted: str = "0",+):"""A document with `n_lines` items, for exercising page breaks.Built field by field rather than from a dict: keyword-splatting a@@ -518,7 +524,7 @@ def _doc(n_lines: int, footer_note: str = "Alpha ME"):one fixture the PDF tests all lean on."""from app.services.invoice_document import (- DEFAULT_LABELS, DocumentLine, DocumentParty, InvoiceDocument,+ DEFAULT_LABELS, DocumentInstallment, DocumentLine, DocumentParty, InvoiceDocument,)return InvoiceDocument(@@ -532,8 +538,9 @@ def _doc(n_lines: int, footer_note: str = "Alpha ME"):discount=Decimal("0"),tax_total=Decimal("0"),total=Decimal("1200"),- amount_paid=Decimal("0"),- balance=Decimal("1200"),+ amount_paid=Decimal(paid),+ amount_deducted=Decimal(deducted),+ balance=Decimal("1200") - Decimal(paid) - Decimal(deducted),issuer=DocumentParty(name="Alpha ME", tax_ids=[]),client=DocumentParty(name="Beta LTDA", address=None, tax_ids=[]),lines=[@@ -548,6 +555,10 @@ def _doc(n_lines: int, footer_note: str = "Alpha ME"):footer_note=footer_note,custom_fields=[],has_line_items=n_lines > 0,+ installments=[+ DocumentInstallment(f"Parcela {i + 1}", date(2026, 9, 20) + timedelta(days=30 * i), Decimal("10"))+ for i in range(n_installments)+ ],)@@ -559,6 +570,40 @@ def _pages(document):return pypdf.PdfReader(io.BytesIO(invoice_pdf.render_pdf(document))).pages+def _lowest_text_y(page) -> float:+ """Where the lowest piece of text on the page sits, in points from+ the bottom edge. Text drawn below zero is in the file and on no+ page anyone will ever see; pypdf's plain extraction still finds it,+ which is why the page-break tests cannot rely on text alone."""+ ys: list[float] = []++ def visit(text, cm, tm, font_dict, font_size):+ if text.strip():+ ys.append(tm[4] * cm[1] + tm[5] * cm[3] + cm[5])++ page.extract_text(visitor_text=visit)+ return min(ys)+++def _text_y(page, needle: str) -> float:+ """The lowest baseline of the text containing `needle` on the page."""+ ys: list[float] = []++ def visit(text, cm, tm, font_dict, font_size):+ if needle in text:+ ys.append(tm[4] * cm[1] + tm[5] * cm[3] + cm[5])++ page.extract_text(visitor_text=visit)+ assert ys, f"{needle!r} not on the page"+ return min(ys)+++def _floor(document) -> float:+ """Where the body must stop: the footer band plus its breathing room."""+ footer, closing = invoice_pdf._footer_flowables(document)+ return invoice_pdf.MARGIN + invoice_pdf._footer_height(footer, closing) + invoice_pdf.FOOTER_GAP++class TestPageStructure:def test_a_short_invoice_is_one_page(self):assert len(_pages(_doc(3))) == 1@@ -598,6 +643,78 @@ class TestPageStructure:assert "Item 45" in texts[-1]assert "1,200.00" in texts[-1]+ def test_a_deduction_is_on_the_page_so_the_totals_add_up(self):+ """Total 1,200, paid 1,000, balance 155: without its own row the+ 45 the client withheld is nowhere, and the page does not add up."""+ text = _pages(_doc(3, paid="1000", deducted="45"))[0].extract_text()+ assert "Deductions" in text and "BRL 45.00" in text+ assert "BRL 1,000.00" in text and "BRL 155.00" in text++ def test_settled_by_deduction_alone_still_shows_the_balance(self):+ text = _pages(_doc(3, deducted="200"))[0].extract_text()+ assert "Deductions" in text and "BRL 200.00" in text+ assert "Paid" not in text+ assert "BRL 1,000.00" in text++ def test_an_untouched_invoice_shows_neither(self):+ text = _pages(_doc(3))[0].extract_text()+ assert "Deductions" not in text and "Balance due" not in text++ def test_a_short_schedule_shares_page_one(self):+ pages = _pages(_doc(3, n_installments=3))+ assert len(pages) == 1+ assert "Parcela 3" in pages[0].extract_text()++ def test_a_long_schedule_paginates_and_loses_no_installment(self):+ """The schedule used to be drawn as part of the header, with no+ page break: enough installments and the rows ran under the footer+ and off the page, taking the line items with them."""+ n = 80+ pages = _pages(_doc(3, n_installments=n))+ assert len(pages) > 1+ text = "\n".join(p.extract_text() for p in pages)+ for i in range(n):+ assert f"Parcela {i + 1}" in text, f"installment {i + 1} vanished"+ assert "Item 3" in text+ assert "1,200.00" in pages[-1].extract_text()+ for page in pages:+ assert "FAT-7" in page.extract_text()+ assert _lowest_text_y(page) > 0, "text drawn below the bottom edge"++ def test_the_schedule_amount_header_sits_over_its_amounts(self):+ """Both AMOUNT headers are right-aligned like the figures under+ them. The schedule's used to start at its column's left edge,+ a quarter of the page away from the numbers it named."""+ page = _pages(_doc(3, n_installments=2))[0]+ xs: list[float] = []++ def visit(text, cm, tm, font_dict, font_size):+ if text.strip() == "AMOUNT":+ xs.append(tm[4] * cm[0] + tm[5] * cm[2] + cm[4])++ page.extract_text(visitor_text=visit)+ assert len(xs) == 2+ assert min(xs) > invoice_pdf.PAGE_WIDTH * 0.8++ @pytest.mark.parametrize("n_lines", [39, 40, 61, 62])+ def test_totals_never_sink_into_the_footer(self, n_lines):+ """Counts found by sweeping: the last chunk of the lines fit the+ page on its own but not together with the totals, and the+ renderer drew it anyway and put the totals over the footer."""+ document = _doc(n_lines)+ pages = _pages(document)+ last = pages[-1]+ assert f"Item {n_lines}" in last.extract_text()+ assert _text_y(last, "1,200.00") >= _floor(document)++ @pytest.mark.parametrize("n_installments", [25, 57, 59])+ def test_a_schedule_with_no_lines_leaves_room_for_the_totals(self, n_installments):+ document = _doc(0, n_installments=n_installments)+ pages = _pages(document)+ assert _text_y(pages[-1], "1,200.00") >= _floor(document)+ for page in pages:+ assert _lowest_text_y(page) > 0+def test_page_numbers_appear_only_when_there_is_more_than_one(self):""""1 / 1" on a single-page invoice is noise that makes thedocument look machine-made."""diff --git a/backend/tests/test_invoice_schedule_service.py b/backend/tests/test_invoice_schedule_service.pyindex 6ec8a3d6..291ada9c 100644--- a/backend/tests/test_invoice_schedule_service.py+++ b/backend/tests/test_invoice_schedule_service.py@@ -21,7 +21,7 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.models.account import Account-from app.models.invoice import Invoice, InvoiceAllocation+from app.models.invoice import Invoice, InvoiceAllocation, InvoiceInstallmentfrom app.models.invoice_schedule import InvoiceSchedule, InvoiceScheduleTermfrom app.models.payee import Payeefrom app.models.transaction import Transaction@@ -851,6 +851,53 @@ class TestFigures:assert figures.amount_paid == Decimal("3000.00")assert figures.past_due_count == 1 # November, due Nov 15, unpaid+ @pytest.mark.asyncio+ async def test_past_due_reads_the_first_unpaid_installment(self, session, ws_id, test_user):+ """An invoice's own due date is the last installment. A client who+ is late on the first one is late, whatever the last one says."""+ s = await make_schedule(session, ws_id, test_user.id, start_date=date(2026, 10, 5), payment_terms_days=10)+ (invoice,) = await svc.generate_due(session, s, today=date(2026, 10, 6)) # 3000, due Oct 15+ invoice.due_date = date(2026, 12, 20)+ session.add_all([+ InvoiceInstallment(+ invoice_id=invoice.id, workspace_id=ws_id, position=0,+ due_date=date(2026, 10, 10), amount=Decimal("1000.00"),+ ),+ InvoiceInstallment(+ invoice_id=invoice.id, workspace_id=ws_id, position=1,+ due_date=date(2026, 12, 20), amount=Decimal("2000.00"),+ ),+ ])+ await session.commit()++ today = date(2026, 12, 1)+ figures = (await svc.figures_for(session, ws_id, [s.id], today=today))[s.id]+ assert figures.past_due_count == 1 # the first installment, not the invoice date++ 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("1000.00"), currency="USD", date=date(2026, 10, 12),+ type="credit", source="manual",+ )+ session.add(tx)+ await session.flush()+ session.add(InvoiceAllocation(+ invoice_id=invoice.id, workspace_id=ws_id, transaction_id=tx.id, amount=Decimal("1000.00"),+ ))+ await session.commit()++ figures = (await svc.figures_for(session, ws_id, [s.id], today=today))[s.id]+ assert figures.past_due_count == 0 # the late one is covered, the next is not due+ assert figures.amount_paid == Decimal("1000.00")+ summary = await svc.summary(session, ws_id, today=today)+ assert all(c.past_due_count == 0 for c in summary.by_currency)+@pytest.mark.asyncioasync 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")diff --git a/backend/tests/test_invoice_service.py b/backend/tests/test_invoice_service.pyindex 884ef354..747276ec 100644--- a/backend/tests/test_invoice_service.py+++ b/backend/tests/test_invoice_service.py@@ -40,6 +40,10 @@ def build_invoice(**overrides) -> Invoice:setattr(invoice, key, value)if not hasattr(invoice, "allocations") or invoice.allocations is None:invoice.allocations = []+ if "deductions" not in overrides:+ invoice.deductions = []+ if "installments" not in overrides:+ invoice.installments = []return invoicediff --git a/backend/tests/test_reconciliation_engine.py b/backend/tests/test_reconciliation_engine.pyindex 4a8f453e..6f8e5fd5 100644--- a/backend/tests/test_reconciliation_engine.py+++ b/backend/tests/test_reconciliation_engine.py@@ -418,3 +418,100 @@ def test_the_winning_strategy_is_named():def test_an_unknown_node_is_refused_rather_than_silently_empty():with pytest.raises(ValueError, match="Unknown reconciliation node"):policy_module.default_policy("reconciliation.does_not_exist")+++# ---------------------------------------------------------------------------+# Installments: the promise is the next part, not the whole+# ---------------------------------------------------------------------------+def an_installment_invoice(+ *, stops: tuple[Decimal, ...], when: date = TODAY, payee_id: uuid.UUID | None = CLIENT+) -> Expectation:+ """3000 in installments: `stops` are the amounts at which one, two or+ all of the remaining installments close, the last being the balance."""+ return Expectation(+ kind="invoice",+ id=uuid.uuid4(),+ amount=stops[-1],+ currency="BRL",+ direction="credit",+ when=when,+ issued=TODAY - timedelta(days=30),+ description="Consultoria",+ payee_id=payee_id,+ stops=stops,+ )+++class TestInstallments:+ def test_exactly_the_next_installment_links(self):+ invoice = an_installment_invoice(stops=(Decimal("1000.00"), Decimal("2000.00"), Decimal("3000.00")))+ decision = evaluate(an_inflow(amount=Decimal("1000.00")), [invoice], receivable())+ assert decision.port == "linked"+ assert decision.strategy == "same_client_exact"+ assert decision.settlements[0].amount == Decimal("1000.00")+ # The queue and the history read the installment, not the balance.+ assert decision.settlements[0].target == Decimal("1000.00")++ def test_two_installments_at_once_link(self):+ invoice = an_installment_invoice(stops=(Decimal("1000.00"), Decimal("2000.00"), Decimal("3000.00")))+ decision = evaluate(an_inflow(amount=Decimal("2000.00")), [invoice], receivable())+ assert decision.port == "linked"+ assert decision.settlements[0].amount == Decimal("2000.00")+ assert decision.settlements[0].target == Decimal("2000.00")++ def test_the_whole_balance_still_links_and_names_no_part(self):+ invoice = an_installment_invoice(stops=(Decimal("1000.00"), Decimal("2000.00"), Decimal("3000.00")))+ decision = evaluate(an_inflow(amount=Decimal("3000.00")), [invoice], receivable())+ assert decision.port == "linked"+ assert decision.settlements[0].amount == Decimal("3000.00")+ assert decision.settlements[0].target is None++ def test_an_amount_between_installments_is_not_taken_as_exact(self):+ """1500 against 1000 / 2000 / 3000 closes no installment. At most+ it is offered as a part payment for a person to confirm."""+ invoice = an_installment_invoice(stops=(Decimal("1000.00"), Decimal("2000.00"), Decimal("3000.00")))+ decision = evaluate(an_inflow(amount=Decimal("1500.00")), [invoice], receivable())+ assert decision.port != "linked"++ def test_less_than_the_next_installment_is_a_part_of_it(self):+ """The difference a part payment reports is what is left of the+ installment, not of the whole invoice."""+ invoice = an_installment_invoice(stops=(Decimal("1000.00"), Decimal("2000.00"), Decimal("3000.00")))+ decision = evaluate(an_inflow(amount=Decimal("600.00")), [invoice], receivable())+ assert decision.port == "suggested"+ assert decision.difference_kind == "part_payment"+ assert decision.difference == Decimal("400.00")++ def test_a_payment_net_of_withholding_on_one_installment_links(self):+ ratio = Decimal("0.985") # as the existing withholding tests use+ installment = Decimal("1000.00")+ net = (installment * ratio).quantize(Decimal("0.01"))+ invoice = an_installment_invoice(stops=(installment, Decimal("3000.00")))+ decision = evaluate(+ an_inflow(amount=net), [invoice], receivable(), withholding_ratios=[ratio]+ )+ assert decision.port == "linked"+ assert decision.difference == installment - net++ def test_without_stops_nothing_changes(self):+ """An invoice that is one amount on one date reads exactly as it+ always did: half of it is not an exact match."""+ decision = evaluate(an_inflow(amount=Decimal("1500.00")), [an_invoice()], receivable())+ assert decision.port != "linked"+++def test_the_queue_shows_the_installment_as_what_was_expected():+ """A suggestion against an installment says "expected 1000", not+ "expected 3000, got 1000": the second reads as a short payment."""+ from app.services.reconciliation_suggestion_service import _signal_scores++ policy = receivable()+ for strategy in policy["strategies"]:+ strategy["outcome"] = "suggest"+ invoice = an_installment_invoice(stops=(Decimal("1000.00"), Decimal("3000.00")))+ movement = an_inflow(amount=Decimal("1000.00"))+ decision = evaluate(movement, [invoice], policy)++ scores = _signal_scores(decision, movement, decision.settlements[0])+ assert scores["amount_expected"] == "1000.00"+ assert scores["amount_exact"] is Truediff --git a/backend/tests/test_reconciliation_service.py b/backend/tests/test_reconciliation_service.pyindex 258d453d..00be7967 100644--- a/backend/tests/test_reconciliation_service.py+++ b/backend/tests/test_reconciliation_service.py@@ -107,6 +107,7 @@ async def an_invoice(payee_id: uuid.UUID | None = None,direction: str = "receivable",as_draft: bool = False,+ installments: list[tuple[date, str]] | None = None,) -> dict:payload: dict = {"total": total,@@ -114,6 +115,10 @@ async def an_invoice("direction": direction,"as_draft": as_draft,}+ if installments:+ payload["installments"] = [+ {"due_date": str(when), "amount": amount} for when, amount in installments+ ]if payee_id:payload["payee_id"] = str(payee_id)resp = await client.post("/api/invoices", headers=headers, json=payload)@@ -434,3 +439,137 @@ async def test_a_draft_looks_back_at_nothing(assert loaded.status == "draft"assert await reconciliation_service.match_for_invoice(session, loaded) is None+++# ---------------------------------------------------------------------------+# Installments: each one is a promise of its own amount and date+# ---------------------------------------------------------------------------+THREE_PARTS = [+ (TODAY, "1000.00"),+ (TODAY + timedelta(days=60), "1000.00"),+ (TODAY + timedelta(days=120), "1000.00"),+]+++async def test_each_installment_settles_as_it_arrives(+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user+):+ """The regression this exists for: an installment used to be compared+ with the whole balance, so 1000 against 3000 was never exact and+ every installment waited for a person."""+ invoice = await an_invoice(+ client, biz_headers, payee_id=client_payee.id, installments=THREE_PARTS+ )+ for n in (1, 2):+ tx = await a_transaction(+ session, account, test_user, amount=Decimal("1000.00"), payee_id=client_payee.id,+ when=TODAY + timedelta(days=60 * (n - 1)),+ )+ applied = await reconciliation_service.match_incoming(session, account.workspace_id, [tx])+ await session.commit()+ assert len(applied) == 1, f"installment {n} was not matched"++ settled = await _load(session, invoice["id"])+ assert sum(a.amount for a in settled.allocations) == Decimal("2000.00")+ assert invoice_service.first_unpaid_due(settled) == TODAY + timedelta(days=120)+++async def test_two_installments_paid_at_once_settle_both(+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user+):+ invoice = await an_invoice(+ client, biz_headers, payee_id=client_payee.id, installments=THREE_PARTS+ )+ tx = await a_transaction(+ session, account, test_user, amount=Decimal("2000.00"), payee_id=client_payee.id+ )+ applied = await reconciliation_service.match_incoming(session, account.workspace_id, [tx])+ await session.commit()++ assert len(applied) == 1+ assert applied[0].amount == Decimal("2000.00")+ settled = await _load(session, invoice["id"])+ assert invoice_service.first_unpaid_due(settled) == TODAY + timedelta(days=120)+++async def test_an_amount_that_closes_no_installment_is_not_taken(+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user+):+ invoice = await an_invoice(+ client, biz_headers, payee_id=client_payee.id, installments=THREE_PARTS+ )+ tx = await a_transaction(+ session, account, test_user, amount=Decimal("1500.00"), payee_id=client_payee.id+ )+ applied = await reconciliation_service.match_incoming(session, account.workspace_id, [tx])+ await session.commit()++ assert applied == []+ assert (await _load(session, invoice["id"])).allocations == []+++async def test_an_upfront_paid_before_the_invoice_is_found(+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user+):+ """The client pays the first installment, the invoice is written+ afterwards. Its due date is the last installment, four months out;+ looking back from there used to start the window after the payment."""+ paid = await a_transaction(+ session, account, test_user, amount=Decimal("1000.00"),+ when=TODAY - timedelta(days=6), payee_id=client_payee.id,+ )+ invoice = await an_invoice(+ client, biz_headers, payee_id=client_payee.id, installments=THREE_PARTS+ )+ settled = await _load(session, invoice["id"])++ assert len(settled.allocations) == 1+ assert settled.allocations[0].transaction_id == paid.id+ assert settled.allocations[0].amount == Decimal("1000.00")+++async def test_linking_by_hand_answers_the_pending_suggestion(+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user+):+ """A short installment payment is offered as a suggestion. When the+ person links it themselves (the "mark as paid" dialog, recording the+ difference), the suggestion used to stay pending, still offering a+ link that already existed."""+ from app.models.reconciliation import ReconciliationSuggestion++ invoice = await an_invoice(+ client, biz_headers, payee_id=client_payee.id, installments=THREE_PARTS+ )+ short = await a_transaction(+ session, account, test_user, amount=Decimal("985.00"), payee_id=client_payee.id+ )+ applied = await reconciliation_service.match_incoming(session, account.workspace_id, [short])+ await session.commit()+ assert applied == []++ short_id = short.id++ def pending():+ return select(ReconciliationSuggestion.status).where(+ ReconciliationSuggestion.transaction_id == short_id,+ ReconciliationSuggestion.expectation_id == uuid.UUID(invoice["id"]),+ )++ assert list((await session.execute(pending())).scalars().all()) == ["pending"]++ resp = await client.post(+ f"/api/invoices/{invoice['id']}/allocations", headers=biz_headers,+ json={"transaction_id": str(short_id)},+ )+ assert resp.status_code == 201, resp.text++ session.expire_all()+ assert list((await session.execute(pending())).scalars().all()) == ["accepted"]+ queue = await client.get("/api/reconciliation/suggestions", headers=biz_headers)+ assert queue.status_code == 200, queue.text+ assert all(str(short_id) not in str(item) for item in queue.json())diff --git a/frontend/src/components/invoice-document.test.tsx b/frontend/src/components/invoice-document.test.tsxnew file mode 100644index 00000000..8ebb8d07--- /dev/null+++ b/frontend/src/components/invoice-document.test.tsx@@ -0,0 +1,62 @@+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { InvoiceDocumentView } from '@/components/invoice-document'+import { renderWithProviders } from '@/test/utils'+import type { InvoiceDocumentPayload } from '@/types'++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++const LABELS = {+ invoice: 'Invoice', from: 'From', billTo: 'Bill to', issueDate: 'Issue date', dueDate: 'Due date',+ description: 'Description', quantity: 'Qty', unitPrice: 'Unit price', amount: 'Amount',+ subtotal: 'Subtotal', discount: 'Discount', tax: 'Tax', total: 'Total', paid: 'Paid',+ deducted: 'Deductions', balance: 'Balance due', paymentDetails: 'Payment details',+ notes: 'Notes', schedule: 'Payment schedule',+}++function payload(overrides: Partial<InvoiceDocumentPayload> = {}): InvoiceDocumentPayload {+ return {+ number: 'AUR22', status: 'open', state: 'partial', issue_date: '2026-09-24', due_date: '2026-10-24',+ currency: 'USD', subtotal: '3000.00', discount: '0.00', tax_total: '0.00', total: '3000.00',+ amount_paid: '0.00', amount_deducted: '0.00', balance: '3000.00',+ issuer: { name: 'Aurora Studio', address: null, tax_ids: [] },+ client: { name: 'Flux Studio', address: null, tax_ids: [] },+ lines: [{ description: 'Brand identity project', quantity: '1', unit: null, unit_price: '3000.00', total: '3000.00' }],+ labels: LABELS, accent_color: '#6d5efc', logo_url: null, payment_details: null, notes: null,+ footer_note: null, custom_fields: [], direction: 'receivable', has_line_items: true,+ source_file: null, installments: [],+ ...overrides,+ } as InvoiceDocumentPayload+}++function row(label: string) {+ return screen.getByText(label).parentElement as HTMLElement+}++describe('InvoiceDocumentView totals', () => {+ it('shows the deduction so total, paid and balance add up', () => {+ renderWithProviders(+ <InvoiceDocumentView document={payload({ amount_paid: '1455.00', amount_deducted: '45.00', balance: '1500.00' })} />,+ )+ expect(row('Paid')).toHaveTextContent('$1,455.00')+ expect(row('Deductions')).toHaveTextContent('$45.00')+ expect(row('Balance due')).toHaveTextContent('$1,500.00')+ })++ it('shows the balance when a deduction alone settled part of it', () => {+ renderWithProviders(<InvoiceDocumentView document={payload({ amount_deducted: '200.00', balance: '2800.00' })} />)+ expect(row('Deductions')).toHaveTextContent('$200.00')+ expect(row('Balance due')).toHaveTextContent('$2,800.00')+ expect(screen.queryByText('Paid')).not.toBeInTheDocument()+ })++ it('shows neither on an untouched invoice', () => {+ renderWithProviders(<InvoiceDocumentView document={payload()} />)+ expect(screen.queryByText('Deductions')).not.toBeInTheDocument()+ expect(screen.queryByText('Balance due')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/invoice-document.tsx b/frontend/src/components/invoice-document.tsxindex 32d6919f..73fc7d71 100644--- a/frontend/src/components/invoice-document.tsx+++ b/frontend/src/components/invoice-document.tsx@@ -124,6 +124,7 @@ export function InvoiceDocumentView({ document }: { document: InvoiceDocumentPayconst L = document.labelsconst accent = document.accent_colorconst hasPaid = Number(document.amount_paid) > 0+ const hasDeducted = Number(document.amount_deducted ?? 0) > 0const money = (value: string) => formatCurrency(Number(value), document.currency, locale)const showDate = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)@@ -139,10 +140,12 @@ export function InvoiceDocumentView({ document }: { document: InvoiceDocumentPaytotals.push({ label: L.tax, value: money(document.tax_total) })}totals.push({ label: L.total, value: money(document.total), strong: true })- // Paid and balance only once money has moved: on an untouched invoice- // they restate the total twice and add nothing.- if (hasPaid) {- totals.push({ label: L.paid, value: money(document.amount_paid) })+ // Paid and balance only once something has settled: on an untouched+ // invoice they restate the total twice and add nothing. Deductions get+ // their own row, or total, paid and balance would not add up.+ if (hasPaid || hasDeducted) {+ if (hasPaid) totals.push({ label: L.paid, value: money(document.amount_paid) })+ if (hasDeducted) totals.push({ label: L.deducted, value: money(document.amount_deducted) })totals.push({ label: L.balance, value: money(document.balance), strong: true })}@@ -230,6 +233,25 @@ export function InvoiceDocumentView({ document }: { document: InvoiceDocumentPay))}</div>+ {document.installments.length > 0 && (+ <div className="mt-6" data-testid="document-installments">+ <div className="text-[10px] font-semibold uppercase tracking-[0.14em]" style={{ color: MUTED }}>+ {L.schedule}+ </div>+ <table className="mt-1.5 w-full text-sm">+ <tbody>+ {document.installments.map((row, index) => (+ <tr key={index} style={{ borderBottom: `1px solid ${RULE}` }}>+ <td className="py-1.5 pr-4">{row.label ?? `${index + 1}/${document.installments.length}`}</td>+ <td className="py-1.5 pr-4 tabular-nums" style={{ color: MUTED }}>{showDate(row.due_date)}</td>+ <td className="py-1.5 text-right tabular-nums">{money(row.amount)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+{document.lines.length > 0 ? (<table className="mt-9 w-full"><thead>diff --git a/frontend/src/components/invoice-installments-editor.test.tsx b/frontend/src/components/invoice-installments-editor.test.tsxnew file mode 100644index 00000000..dcfa526b--- /dev/null+++ b/frontend/src/components/invoice-installments-editor.test.tsx@@ -0,0 +1,73 @@+import { useState } from 'react'+import { describe, expect, it, vi } from 'vitest'+import { screen } from '@testing-library/react'++import { InvoiceInstallmentsEditor } from '@/components/invoice-installments-editor'+import { renderWithProviders, t } from '@/test/utils'+import type { InstallmentInput } from '@/types'++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++function Harness({ total = 3000, initial = null }: { total?: number; initial?: InstallmentInput[] | null }) {+ const [value, setValue] = useState<InstallmentInput[] | null>(initial)+ return (+ <InvoiceInstallmentsEditor+ value={value}+ onChange={setValue}+ total={total}+ currency="USD"+ firstDueDate="2026-10-01"+ minDate="2026-09-01"+ />+ )+}++describe('InvoiceInstallmentsEditor', () => {+ it('is one switch, off, until asked', () => {+ renderWithProviders(<Harness />)+ expect(screen.getByRole('switch')).toBeInTheDocument()+ expect(screen.queryByTestId('installment-row')).not.toBeInTheDocument()+ })++ it('seeds two equal installments a month apart when switched on', async () => {+ const { user } = renderWithProviders(<Harness />)+ await user.click(screen.getByRole('switch'))+ const rows = screen.getAllByTestId('installment-row')+ expect(rows).toHaveLength(2)+ expect(screen.getByTestId('installment-due-0')).toHaveValue('2026-10-01')+ expect(screen.getByTestId('installment-due-1')).toHaveValue('2026-11-01')+ expect(screen.getByTestId('installment-amount-0')).toHaveValue('1500.00')+ expect(screen.getByTestId('installments-check')).toHaveTextContent(t('invoices.installments.addsUp', { total: '$3,000.00' }))+ })++ it('shows the mismatch, to the cent, as the amounts are edited', async () => {+ const { user } = renderWithProviders(<Harness />)+ await user.click(screen.getByRole('switch'))+ await user.clear(screen.getByTestId('installment-amount-1'))+ await user.type(screen.getByTestId('installment-amount-1'), '1499.99')+ expect(screen.getByTestId('installments-check')).toHaveTextContent(+ t('invoices.installments.mismatch', { scheduled: '$2,999.99', total: '$3,000.00' }),+ )+ })++ it('adds a row a month after the last one and never drops below two', async () => {+ const { user } = renderWithProviders(<Harness />)+ await user.click(screen.getByRole('switch'))+ await user.click(screen.getByTestId('installments-add'))+ expect(screen.getAllByTestId('installment-row')).toHaveLength(3)+ expect(screen.getByTestId('installment-due-2')).toHaveValue('2026-12-01')+ await user.click(screen.getByTestId('installment-remove-2'))+ expect(screen.getAllByTestId('installment-row')).toHaveLength(2)+ expect(screen.getByTestId('installment-remove-0')).toBeDisabled()+ })++ it('switching off clears the schedule', async () => {+ const { user } = renderWithProviders(<Harness initial={[{ due_date: '2026-10-01', amount: '1500.00' }, { due_date: '2026-11-01', amount: '1500.00' }]} />)+ expect(screen.getAllByTestId('installment-row')).toHaveLength(2)+ await user.click(screen.getByRole('switch'))+ expect(screen.queryByTestId('installment-row')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/components/invoice-installments-editor.tsx b/frontend/src/components/invoice-installments-editor.tsxnew file mode 100644index 00000000..2e41a1a5--- /dev/null+++ b/frontend/src/components/invoice-installments-editor.tsx@@ -0,0 +1,180 @@+import { useTranslation } from 'react-i18next'+import { Plus, Trash2 } from 'lucide-react'++import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Switch } from '@/components/ui/switch'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { formatCurrency } from '@/lib/format'+import { useDisplayLocale } from '@/hooks/use-display-locale'+import { cn } from '@/lib/utils'+import { addMonths, installmentsTotal, splitEvenly } from '@/lib/installment-utils'+import type { InstallmentInput } from '@/types'++/**+ * The dates the money is expected on, when there is more than one.+ *+ * Off by default and one switch away: the ordinary invoice has one due+ * date and never sees this. On, it is a small table the person fills or+ * seeds with "split in N", and a running check against the total,+ * because the server refuses a schedule that does not add up and the+ * mismatch is better shown here than as an error after the submit.+ */+const TH = 'text-[11px] font-medium text-muted-foreground pb-1.5'+const SPLITS = [2, 3, 4, 6, 12]++export function InvoiceInstallmentsEditor({+ value,+ onChange,+ total,+ currency,+ firstDueDate,+ minDate,+}: {+ /** Null means "one due date, no schedule". */+ value: InstallmentInput[] | null+ onChange: (value: InstallmentInput[] | null) => void+ total: number+ currency: string+ /** Where "split in N" starts counting from: the invoice's due date. */+ firstDueDate: string+ /** Nothing may be due before the issue date. */+ minDate?: string+}) {+ const { t } = useTranslation()+ const locale = useDisplayLocale()+ const enabled = value !== null+ const rows = value ?? []+ const scheduled = installmentsTotal(rows)+ const mismatch = enabled && Math.abs(scheduled - total) >= 0.005+ const money = (n: number) => formatCurrency(n, currency, locale)++ const update = (index: number, patch: Partial<InstallmentInput>) =>+ onChange(rows.map((row, i) => (i === index ? { ...row, ...patch } : row)))++ return (+ <div className="space-y-2" data-testid="invoice-installments-editor">+ <div className="flex items-center justify-between">+ <Label htmlFor="installments-toggle">{t('invoices.installments.title')}</Label>+ <Switch+ id="installments-toggle"+ checked={enabled}+ onCheckedChange={(on) =>+ onChange(on ? splitEvenly(total, 2, firstDueDate) : null)+ }+ />+ </div>++ {enabled && (+ <div className="rounded-lg border border-border overflow-hidden">+ <div className="flex flex-wrap items-center gap-2 px-3 py-2 bg-muted/40 border-b border-border">+ <span className="text-xs text-muted-foreground">{t('invoices.installments.splitIn')}</span>+ <Select onValueChange={(n) => onChange(splitEvenly(total, Number(n), firstDueDate))}>+ <SelectTrigger className="h-8 w-24" data-testid="installments-split">+ <SelectValue placeholder="N" />+ </SelectTrigger>+ <SelectContent>+ {SPLITS.map((n) => (+ <SelectItem key={n} value={String(n)}>{`${n}x`}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ <span className="text-[11px] text-muted-foreground">{t('invoices.installments.splitHint')}</span>+ <Button+ size="sm"+ variant="ghost"+ className="ml-auto"+ onClick={() =>+ onChange([+ ...rows,+ { due_date: addMonths(rows[rows.length - 1]?.due_date ?? firstDueDate, 1), amount: '0', label: null },+ ])+ }+ data-testid="installments-add"+ >+ <Plus className="h-3.5 w-3.5 mr-1" />+ {t('invoices.installments.add')}+ </Button>+ </div>++ <div className="hidden sm:grid grid-cols-[1fr_8rem_8rem_2rem] gap-2 px-3 pt-2">+ <span className={TH}>{t('invoices.installments.label')}</span>+ <span className={TH}>{t('invoices.column.due')}</span>+ <span className={`${TH} text-right`}>{t('invoices.column.amount')}</span>+ <span className={TH} />+ </div>+ <div className="divide-y divide-border">+ {rows.map((row, index) => (+ <div+ key={index}+ data-testid="installment-row"+ className="grid grid-cols-2 sm:grid-cols-[1fr_8rem_8rem_2rem] gap-2 px-3 py-2 items-center"+ >+ <Input+ className="h-9 col-span-2 sm:col-span-1"+ placeholder={t('invoices.installments.labelPlaceholder', { n: index + 1, total: rows.length })}+ value={row.label ?? ''}+ onChange={(e) => update(index, { label: e.target.value || null })}+ data-testid={`installment-label-${index}`}+ maxLength={60}+ />+ <Input+ className="h-9"+ type="date"+ min={minDate}+ value={row.due_date}+ onChange={(e) => update(index, { due_date: e.target.value })}+ data-testid={`installment-due-${index}`}+ aria-label={t('invoices.column.due')}+ />+ <Input+ className="h-9 text-right"+ inputMode="decimal"+ value={row.amount}+ onChange={(e) => update(index, { amount: e.target.value })}+ data-testid={`installment-amount-${index}`}+ aria-label={t('invoices.column.amount')}+ />+ <div className="flex justify-end">+ <Button+ size="sm"+ variant="ghost"+ className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"+ disabled={rows.length <= 2}+ onClick={() => onChange(rows.filter((_, i) => i !== index))}+ data-testid={`installment-remove-${index}`}+ aria-label={t('common.delete')}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ </div>+ ))}+ </div>++ <div+ className={cn(+ 'flex items-center justify-between px-3 py-2 text-xs border-t border-border',+ mismatch ? 'bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400' : 'bg-muted/40 text-muted-foreground',+ )}+ data-testid="installments-check"+ >+ <span>+ {mismatch+ ? t('invoices.installments.mismatch', { scheduled: money(scheduled), total: money(total) })+ : t('invoices.installments.addsUp', { total: money(total) })}+ </span>+ <span className="tabular-nums font-medium">{money(scheduled)}</span>+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 793ad9aa..4c62bc3c 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -19,6 +19,8 @@ import type {Transaction,Payee,PayeeSummary,+ DeductionKind,+ InstallmentInput,Invoice,InvoiceDirection,InvoiceDocumentPayload,@@ -1960,6 +1962,8 @@ export interface InvoiceWritePayload {internal_notes?: string | nullcustom_fields?: Record<string, string> | nulllines?: InvoiceLineInput[]+ /** More than one due date. Must add up to the total; an empty list clears it. */+ installments?: InstallmentInput[]}export interface MakeRecurringPayload {@@ -2133,6 +2137,18 @@ export const invoices = {})return data},+ /** Close part of the debt without money: tax withheld, a fee kept. */+ deduct: async (+ id: string,+ payload: { kind: DeductionKind; amount: string; tax_kind?: string | null; note?: string | null; transaction_id?: string | null },+ ): Promise<Invoice> => {+ const { data } = await api.post(`/invoices/${id}/deductions`, payload)+ return data+ },+ undeduct: async (id: string, deductionId: string): Promise<Invoice> => {+ const { data } = await api.delete(`/invoices/${id}/deductions/${deductionId}`)+ return data+ },unallocate: async (id: string, allocationId: string): Promise<Invoice> => {const { data } = await api.delete(`/invoices/${id}/allocations/${allocationId}`)return data@@ -2168,6 +2184,11 @@ export const invoices = {const { data } = await api.get(`/invoices/${id}/pdf`, { responseType: 'blob' })return data},+ /** The statement of account: payments and deductions since issue. */+ statement: async (id: string): Promise<Blob> => {+ const { data } = await api.get(`/invoices/${id}/statement`, { responseType: 'blob' })+ return data+ },share: async (id: string): Promise<InvoiceShareLink> => {const { data } = await api.post(`/invoices/${id}/share`)return datadiff --git a/frontend/src/lib/installment-utils.test.ts b/frontend/src/lib/installment-utils.test.tsnew file mode 100644index 00000000..9f063b18--- /dev/null+++ b/frontend/src/lib/installment-utils.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest'++import { addMonths, displayDue, installmentsTotal, splitEvenly } from './installment-utils'++describe('addMonths', () => {+ it('steps by calendar months and clamps in shorter ones', () => {+ expect(addMonths('2026-01-31', 1)).toBe('2026-02-28')+ expect(addMonths('2026-01-31', 2)).toBe('2026-03-31')+ expect(addMonths('2026-11-15', 2)).toBe('2027-01-15')+ expect(addMonths('2026-03-05', 0)).toBe('2026-03-05')+ })+})++describe('splitEvenly', () => {+ it('divides to the cent and puts the remainder on the last installment', () => {+ const rows = splitEvenly(100, 3, '2026-10-01')+ expect(rows.map((r) => r.amount)).toEqual(['33.33', '33.33', '33.34'])+ expect(rows.map((r) => r.due_date)).toEqual(['2026-10-01', '2026-11-01', '2026-12-01'])+ expect(installmentsTotal(rows)).toBeCloseTo(100, 2)+ })++ it('never makes fewer than two', () => {+ expect(splitEvenly(10, 1, '2026-10-01')).toHaveLength(2)+ })+})++describe('installmentsTotal', () => {+ it('ignores what is not a number yet', () => {+ expect(installmentsTotal([{ due_date: '2026-10-01', amount: '10' }, { due_date: '2026-11-01', amount: '' }])).toBe(10)+ })+})++describe('displayDue', () => {+ it('prefers the next unpaid date while money is owed', () => {+ expect(displayDue({ due_date: '2026-12-01', next_due_date: '2026-10-01' })).toBe('2026-10-01')+ expect(displayDue({ due_date: '2026-12-01', next_due_date: null })).toBe('2026-12-01')+ })+})diff --git a/frontend/src/lib/installment-utils.ts b/frontend/src/lib/installment-utils.tsnew file mode 100644index 00000000..1892ce37--- /dev/null+++ b/frontend/src/lib/installment-utils.ts@@ -0,0 +1,48 @@+import type { DeductionKind, InstallmentInput, Invoice } from '@/types'++/**+ * Pure helpers for installments and deductions. The server owns every+ * rule (the schedule adds up, money covers it first-to-last); these+ * only shape what the forms send and how the screen reads it.+ */++/** `YYYY-MM-DD` plus N calendar months, day clamped to the target month. */+export function addMonths(iso: string, months: number): string {+ const [y, m, d] = iso.split('-').map(Number)+ if (!y || !m || !d) return iso+ const index = m - 1 + months+ const year = y + Math.floor(index / 12)+ const month = (((index % 12) + 12) % 12) + 1+ const lastDay = new Date(year, month, 0).getDate()+ const day = Math.min(d, lastDay)+ return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`+}++/** A schedule of `count` equal installments a month apart from `first`.+ * Cents that do not divide land on the last one, so the sum is exact. */+export function splitEvenly(total: number, count: number, first: string): InstallmentInput[] {+ const n = Math.max(2, Math.floor(count))+ const cents = Math.round(total * 100)+ const base = Math.floor(cents / n)+ const rows: InstallmentInput[] = []+ for (let i = 0; i < n; i += 1) {+ const amount = i === n - 1 ? cents - base * (n - 1) : base+ rows.push({ due_date: addMonths(first, i), amount: (amount / 100).toFixed(2), label: null })+ }+ return rows+}++export function installmentsTotal(rows: InstallmentInput[]): number {+ return rows.reduce((sum, row) => {+ const n = Number(row.amount)+ return sum + (Number.isFinite(n) ? n : 0)+ }, 0)+}++export const DEDUCTION_KINDS: DeductionKind[] = ['withholding_tax', 'gateway_fee', 'fx_difference', 'other']++/** What the "Due" figure should say: the next unpaid date while money is+ * owed, the last one otherwise. */+export function displayDue(invoice: Pick<Invoice, 'due_date' | 'next_due_date'>): string {+ return invoice.next_due_date ?? invoice.due_date+}diff --git a/frontend/src/lib/invoice-utils.test.ts b/frontend/src/lib/invoice-utils.test.tsindex 4bb78e9d..2fcbd0f9 100644--- a/frontend/src/lib/invoice-utils.test.ts+++ b/frontend/src/lib/invoice-utils.test.ts@@ -46,6 +46,10 @@ function makeInvoice(overrides: Partial<Invoice> = {}): Invoice {amount_paid: '0.00',balance: '1000.00',days_overdue: 0,+ amount_deducted: '0.00',+ next_due_date: null,+ installments: [],+ deductions: [],notes: null,internal_notes: null,custom_fields: null,diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex d7e48fb2..cc4be4e6 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Als Entwurf speichern"+ "saveDraft": "Als Entwurf speichern",+ "downloadStatement": "Kontoauszug herunterladen"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Ein Preis braucht einen Betrag.","negative_price": "Ein Preis kann nicht negativ sein.","invalid_fiscal_refs": "Steuerliche Referenzen müssen kurze Textwerte unter einfachen Schlüsseln sein (Buchstaben, Ziffern, Unterstrich).",- "price_key_taken": "Ein anderer Preis verwendet diesen Suchschlüssel oder diese externe ID bereits."+ "price_key_taken": "Ein anderer Preis verwendet diesen Suchschlüssel oder diese externe ID bereits.",+ "installments_mismatch": "Die Raten ergeben nicht den Rechnungsbetrag.",+ "installments_too_few": "Ein Zahlungsplan braucht mindestens zwei Raten.",+ "installment_amount_not_positive": "Jede Rate muss einen Betrag haben.",+ "installment_due_required": "Jede Rate braucht ein Fälligkeitsdatum.",+ "invalid_deduction_kind": "Unbekannte Abzugsart.",+ "deduction_not_found": "Abzug nicht gefunden."},"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": {@@ -643,6 +650,61 @@"archive": "Archivieren","restore": "Wiederherstellen"}+ },+ "installments": {+ "title": "In Raten aufteilen",+ "splitIn": "Aufteilen in",+ "splitHint": "gleiche Teile, im Monatsabstand, ab dem Fälligkeitsdatum",+ "add": "Rate hinzufügen",+ "label": "Bezeichnung",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Ergibt {{total}}.",+ "mismatch": "Die Raten ergeben {{scheduled}}, die Rechnung {{total}}.",+ "schedule": "Zahlungsplan",+ "nextDue": "Nächste Fälligkeit",+ "dueDerived": "Wird von der letzten Rate bestimmt.",+ "count_one": "{{count}} Rate",+ "count_other": "{{count}} Raten",+ "state": {+ "open": "Offen",+ "partial": "Teilweise",+ "paid": "Bezahlt",+ "overdue": "Überfällig",+ "draft": "Entwurf",+ "void": "Storniert",+ "uncollectible": "Uneinbringlich"+ }+ },+ "deductions": {+ "title": "Abzug erfassen",+ "description": "Schließt einen Teil der Forderung, ohne dass Geld eingeht: der Kunde hat Steuern einbehalten, der Zahlungsdienstleister seine Gebühr, die Umrechnung fiel geringer aus. Es zählt als beglichen, nie als erhalten.",+ "action": "Abzug erfassen",+ "recorded": "Abzug erfasst",+ "removed": "Abzug entfernt",+ "amount": "Betrag",+ "amountHint": "Bis zum offenen Saldo: {{balance}}.",+ "kindLabel": "Grund",+ "taxKind": "Welche Steuer (optional)",+ "taxKindPlaceholder": "Quellensteuer, Bauabzugsteuer...",+ "note": "Notiz (optional)",+ "settledWithout": "Ohne Zahlung beglichen",+ "kind": {+ "withholding_tax": "Vom Kunden einbehaltene Steuer",+ "gateway_fee": "Vom Zahlungsdienstleister einbehaltene Gebühr",+ "fx_difference": "Währungsumrechnungsdifferenz",+ "other": "Sonstiges"+ },+ "differenceTitle": "Die Zahlung ist {{difference}} zu niedrig",+ "differenceHint": "Erfassen Sie die Differenz, damit die Rechnung geschlossen wird",+ "differenceNone": "Nicht erfassen",+ "figure": "Abgezogen"+ },+ "statement": {+ "asIssued": "Rechnung wie ausgestellt",+ "asIssuedHint": "Das an den Kunden gesendete Dokument",+ "hint": "Zahlungen und Abzüge seit Ausstellung, und der Saldo",+ "banner": "Dieses PDF ist die Rechnung wie ausgestellt. Seitdem wurden {{paid}} erhalten und {{deducted}} abgezogen: der Kontoauszug zeigt jeden Posten und den Saldo.",+ "title": "Kontoauszug"}},"collections": {diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex e3afcd27..bd7bf8a4 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -236,7 +236,8 @@"downloadPdf": "Λήψη PDF","share": "Κοινοποίηση συνδέσμου","revokeLink": "Ανάκληση συνδέσμου",- "saveDraft": "Αποθήκευση ως πρόχειρο"+ "saveDraft": "Αποθήκευση ως πρόχειρο",+ "downloadStatement": "Λήψη κατάστασης λογαριασμού"},"settings": {"title": "Ρυθμίσεις τιμολογίων",@@ -341,7 +342,13 @@"unit_price_required": "Μια τιμή χρειάζεται ποσό.","negative_price": "Μια τιμή δεν μπορεί να είναι αρνητική.","invalid_fiscal_refs": "Οι φορολογικές αναφορές πρέπει να είναι σύντομες τιμές κειμένου κάτω από απλά κλειδιά (γράμματα, ψηφία, κάτω παύλα).",- "price_key_taken": "Μια άλλη τιμή χρησιμοποιεί ήδη αυτό το κλειδί αναζήτησης ή εξωτερικό αναγνωριστικό."+ "price_key_taken": "Μια άλλη τιμή χρησιμοποιεί ήδη αυτό το κλειδί αναζήτησης ή εξωτερικό αναγνωριστικό.",+ "installments_mismatch": "Οι δόσεις δεν αθροίζουν το σύνολο του τιμολογίου.",+ "installments_too_few": "Ένα πρόγραμμα πληρωμών χρειάζεται τουλάχιστον δύο δόσεις.",+ "installment_amount_not_positive": "Κάθε δόση πρέπει να έχει ποσό.",+ "installment_due_required": "Κάθε δόση χρειάζεται ημερομηνία λήξης.",+ "invalid_deduction_kind": "Άγνωστος τύπος κράτησης.",+ "deduction_not_found": "Η κράτηση δεν βρέθηκε."},"comingNext": "Τιμολογήστε τους πελάτες σας και παρακολουθήστε τι έχει πληρωθεί και τι εκκρεμεί. Αυτή είναι η επόμενη λειτουργία που αναπτύσσεται.","document": {@@ -643,6 +650,61 @@"archive": "Αρχειοθέτηση","restore": "Επαναφορά"}+ },+ "installments": {+ "title": "Διαχωρισμός σε δόσεις",+ "splitIn": "Διαχωρισμός σε",+ "splitHint": "ίσα μέρη, ανά μήνα, από την ημερομηνία λήξης",+ "add": "Προσθήκη δόσης",+ "label": "Ετικέτα",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Σύνολο {{total}}.",+ "mismatch": "Οι δόσεις αθροίζουν {{scheduled}}, το τιμολόγιο {{total}}.",+ "schedule": "Πρόγραμμα πληρωμών",+ "nextDue": "Επόμενη λήξη",+ "dueDerived": "Ορίζεται από την τελευταία δόση.",+ "count_one": "{{count}} δόση",+ "count_other": "{{count}} δόσεις",+ "state": {+ "open": "Σε εκκρεμότητα",+ "partial": "Μερική",+ "paid": "Εξοφλημένη",+ "overdue": "Εκπρόθεσμη",+ "draft": "Πρόχειρο",+ "void": "Ακυρωμένη",+ "uncollectible": "Ανεπίδεκτη είσπραξης"+ }+ },+ "deductions": {+ "title": "Καταχώριση κράτησης",+ "description": "Κλείνει μέρος της οφειλής χωρίς να εισπραχθούν χρήματα: ο πελάτης παρακράτησε φόρο, ο πάροχος πληρωμών κράτησε την προμήθειά του, η μετατροπή συναλλάγματος βγήκε λιγότερη. Μετράει ως διακανονισμένο, ποτέ ως εισπραχθέν.",+ "action": "Καταχώριση κράτησης",+ "recorded": "Η κράτηση καταχωρίστηκε",+ "removed": "Η κράτηση αφαιρέθηκε",+ "amount": "Ποσό",+ "amountHint": "Έως το υπόλοιπο: {{balance}}.",+ "kindLabel": "Αιτία",+ "taxKind": "Ποιος φόρος (προαιρετικό)",+ "taxKindPlaceholder": "Παρακράτηση φόρου, ΦΠΑ...",+ "note": "Σημείωση (προαιρετικό)",+ "settledWithout": "Διακανονίστηκε χωρίς πληρωμή",+ "kind": {+ "withholding_tax": "Φόρος που παρακρατήθηκε από τον πελάτη",+ "gateway_fee": "Προμήθεια που κράτησε ο πάροχος πληρωμών",+ "fx_difference": "Διαφορά μετατροπής συναλλάγματος",+ "other": "Άλλο"+ },+ "differenceTitle": "Η πληρωμή υπολείπεται κατά {{difference}}",+ "differenceHint": "Καταχωρίστε τη διαφορά για να κλείσει το τιμολόγιο",+ "differenceNone": "Να μην καταχωριστεί",+ "figure": "Παρακρατήθηκε"+ },+ "statement": {+ "asIssued": "Τιμολόγιο όπως εκδόθηκε",+ "asIssuedHint": "Το έγγραφο που στάλθηκε στον πελάτη",+ "hint": "Πληρωμές και παρακρατήσεις από την έκδοση, και το υπόλοιπο",+ "banner": "Αυτό το PDF είναι το τιμολόγιο όπως εκδόθηκε. Από τότε εισπράχθηκαν {{paid}} και παρακρατήθηκαν {{deducted}}: η κατάσταση λογαριασμού δείχνει κάθε κίνηση και το υπόλοιπο.",+ "title": "Κατάσταση λογαριασμού"}},"collections": {diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 2fd5ff30..f46eeda2 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Save as draft"+ "saveDraft": "Save as draft",+ "downloadStatement": "Download statement"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "A price needs an amount.","negative_price": "A price cannot be negative.","invalid_fiscal_refs": "Fiscal references must be short text values under simple keys (letters, digits, underscore).",- "price_key_taken": "Another price already uses this lookup key or external id."+ "price_key_taken": "Another price already uses this lookup key or external id.",+ "installments_mismatch": "The installments do not add up to the invoice total.",+ "installments_too_few": "A schedule needs at least two installments.",+ "installment_amount_not_positive": "Every installment must be worth something.",+ "installment_due_required": "Every installment needs a due date.",+ "invalid_deduction_kind": "Unknown deduction kind.",+ "deduction_not_found": "Deduction not found."},"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": {@@ -643,6 +650,61 @@"archive": "Archive","restore": "Restore"}+ },+ "installments": {+ "title": "Split into installments",+ "splitIn": "Split in",+ "splitHint": "equal parts, a month apart, from the due date",+ "add": "Add installment",+ "label": "Label",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Adds up to {{total}}.",+ "mismatch": "The installments add up to {{scheduled}}, the invoice to {{total}}.",+ "schedule": "Payment schedule",+ "nextDue": "Next due",+ "dueDerived": "Set by the last installment.",+ "count_one": "{{count}} installment",+ "count_other": "{{count}} installments",+ "state": {+ "open": "Open",+ "partial": "Partial",+ "paid": "Paid",+ "overdue": "Overdue",+ "draft": "Draft",+ "void": "Void",+ "uncollectible": "Uncollectible"+ }+ },+ "deductions": {+ "title": "Record a deduction",+ "description": "Close part of what is owed without money arriving: the client withheld tax, the processor kept its fee, the conversion landed short. It counts as settled, never as received.",+ "action": "Record deduction",+ "recorded": "Deduction recorded",+ "removed": "Deduction removed",+ "amount": "Amount",+ "amountHint": "Up to the balance: {{balance}}.",+ "kindLabel": "Reason",+ "taxKind": "Which tax (optional)",+ "taxKindPlaceholder": "IRRF, ISS, IRPF...",+ "note": "Note (optional)",+ "settledWithout": "Settled without payment",+ "kind": {+ "withholding_tax": "Tax withheld by the client",+ "gateway_fee": "Fee kept by the processor",+ "fx_difference": "Currency conversion difference",+ "other": "Other"+ },+ "differenceTitle": "The payment is {{difference}} short",+ "differenceHint": "Record the difference so the invoice closes",+ "differenceNone": "Do not record",+ "figure": "Deducted"+ },+ "statement": {+ "asIssued": "Invoice as issued",+ "asIssuedHint": "The document sent to the client",+ "hint": "Payments and deductions since issue, and the balance",+ "banner": "This PDF is the invoice as issued. Since then {{paid}} was received and {{deducted}} deducted: the statement of account shows each one and the balance.",+ "title": "Statement of account"}},"collections": {diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 22117757..46046c07 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Guardar borrador"+ "saveDraft": "Guardar borrador",+ "downloadStatement": "Descargar estado de cuenta"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Un precio necesita un importe.","negative_price": "Un precio no puede ser negativo.","invalid_fiscal_refs": "Las referencias fiscales deben ser textos cortos bajo claves simples (letras, dígitos, guion bajo).",- "price_key_taken": "Otro precio ya usa esta clave de búsqueda o id externo."+ "price_key_taken": "Otro precio ya usa esta clave de búsqueda o id externo.",+ "installments_mismatch": "Las cuotas no suman el total de la factura.",+ "installments_too_few": "Un calendario necesita al menos dos cuotas.",+ "installment_amount_not_positive": "Cada cuota debe tener un importe.",+ "installment_due_required": "Cada cuota necesita una fecha de vencimiento.",+ "invalid_deduction_kind": "Tipo de deducción desconocido.",+ "deduction_not_found": "Deducción no encontrada."},"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": {@@ -643,6 +650,61 @@"archive": "Archivar","restore": "Restaurar"}+ },+ "installments": {+ "title": "Dividir en cuotas",+ "splitIn": "Dividir en",+ "splitHint": "partes iguales, una por mes, desde la fecha de vencimiento",+ "add": "Añadir cuota",+ "label": "Etiqueta",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Suma {{total}}.",+ "mismatch": "Las cuotas suman {{scheduled}}, la factura {{total}}.",+ "schedule": "Calendario de pagos",+ "nextDue": "Próximo vencimiento",+ "dueDerived": "Definido por la última cuota.",+ "count_one": "{{count}} cuota",+ "count_other": "{{count}} cuotas",+ "state": {+ "open": "Pendiente",+ "partial": "Parcial",+ "paid": "Pagada",+ "overdue": "Vencida",+ "draft": "Borrador",+ "void": "Anulada",+ "uncollectible": "Incobrable"+ }+ },+ "deductions": {+ "title": "Registrar una deducción",+ "description": "Cierra parte de lo adeudado sin que entre dinero: el cliente retuvo impuestos, el procesador se quedó con su comisión, la conversión llegó corta. Cuenta como liquidado, nunca como recibido.",+ "action": "Registrar deducción",+ "recorded": "Deducción registrada",+ "removed": "Deducción eliminada",+ "amount": "Importe",+ "amountHint": "Hasta el saldo: {{balance}}.",+ "kindLabel": "Motivo",+ "taxKind": "Qué impuesto (opcional)",+ "taxKindPlaceholder": "IRPF, IVA, ISR...",+ "note": "Nota (opcional)",+ "settledWithout": "Liquidado sin pago",+ "kind": {+ "withholding_tax": "Impuesto retenido por el cliente",+ "gateway_fee": "Comisión retenida por el procesador",+ "fx_difference": "Diferencia de cambio",+ "other": "Otro"+ },+ "differenceTitle": "El pago llegó {{difference}} por debajo",+ "differenceHint": "Registre la diferencia para cerrar la factura",+ "differenceNone": "No registrar",+ "figure": "Deducido"+ },+ "statement": {+ "asIssued": "Factura tal como se emitió",+ "asIssuedHint": "El documento enviado al cliente",+ "hint": "Pagos y deducciones desde la emisión, y el saldo",+ "banner": "Este PDF es la factura tal como se emitió. Desde entonces se recibieron {{paid}} y se dedujeron {{deducted}}: el estado de cuenta muestra cada uno y el saldo.",+ "title": "Estado de cuenta"}},"collections": {diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex eb9f5023..ad62070f 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Enregistrer le brouillon"+ "saveDraft": "Enregistrer le brouillon",+ "downloadStatement": "Télécharger le relevé"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Un prix a besoin d'un montant.","negative_price": "Un prix ne peut pas être négatif.","invalid_fiscal_refs": "Les références fiscales doivent être de courtes valeurs texte sous des clés simples (lettres, chiffres, tiret bas).",- "price_key_taken": "Un autre prix utilise déjà cette clé de recherche ou cet identifiant externe."+ "price_key_taken": "Un autre prix utilise déjà cette clé de recherche ou cet identifiant externe.",+ "installments_mismatch": "Les échéances ne totalisent pas le montant de la facture.",+ "installments_too_few": "Un échéancier nécessite au moins deux échéances.",+ "installment_amount_not_positive": "Chaque échéance doit avoir un montant.",+ "installment_due_required": "Chaque échéance nécessite une date d'échéance.",+ "invalid_deduction_kind": "Type de déduction inconnu.",+ "deduction_not_found": "Déduction introuvable."},"comingNext": "Facturez vos clients et suivez ce qui a été payé et ce qui reste ouvert. C'est la prochaine chose en construction.","document": {@@ -643,6 +650,61 @@"archive": "Archiver","restore": "Restaurer"}+ },+ "installments": {+ "title": "Fractionner en échéances",+ "splitIn": "Fractionner en",+ "splitHint": "parts égales, à un mois d'intervalle, à partir de la date d'échéance",+ "add": "Ajouter une échéance",+ "label": "Libellé",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Total : {{total}}.",+ "mismatch": "Les échéances totalisent {{scheduled}}, la facture {{total}}.",+ "schedule": "Échéancier de paiement",+ "nextDue": "Prochaine échéance",+ "dueDerived": "Définie par la dernière échéance.",+ "count_one": "{{count}} échéance",+ "count_other": "{{count}} échéances",+ "state": {+ "open": "En attente",+ "partial": "Partielle",+ "paid": "Payée",+ "overdue": "En retard",+ "draft": "Brouillon",+ "void": "Annulée",+ "uncollectible": "Irrécouvrable"+ }+ },+ "deductions": {+ "title": "Enregistrer une déduction",+ "description": "Solde une partie du montant dû sans qu'aucun argent n'arrive : le client a retenu un impôt, le prestataire de paiement a gardé ses frais, la conversion est arrivée en dessous. Elle compte comme réglée, jamais comme encaissée.",+ "action": "Enregistrer la déduction",+ "recorded": "Déduction enregistrée",+ "removed": "Déduction supprimée",+ "amount": "Montant",+ "amountHint": "Jusqu'au solde : {{balance}}.",+ "kindLabel": "Motif",+ "taxKind": "Quel impôt (facultatif)",+ "taxKindPlaceholder": "Retenue à la source, TVA...",+ "note": "Note (facultatif)",+ "settledWithout": "Réglé sans paiement",+ "kind": {+ "withholding_tax": "Impôt retenu par le client",+ "gateway_fee": "Frais retenus par le prestataire de paiement",+ "fx_difference": "Écart de conversion de devise",+ "other": "Autre"+ },+ "differenceTitle": "Il manque {{difference}} au paiement",+ "differenceHint": "Enregistrez la différence pour que la facture soit soldée",+ "differenceNone": "Ne pas enregistrer",+ "figure": "Déduit"+ },+ "statement": {+ "asIssued": "Facture telle qu'émise",+ "asIssuedHint": "Le document envoyé au client",+ "hint": "Paiements et déductions depuis l'émission, et le solde",+ "banner": "Ce PDF est la facture telle qu'émise. Depuis, {{paid}} ont été reçus et {{deducted}} déduits : le relevé de compte détaille chacun et le solde.",+ "title": "Relevé de compte"}},"collections": {diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex e2f15bcd..184adb17 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -236,7 +236,8 @@"downloadPdf": "PDF डाउनलोड करें","share": "लिंक शेयर करें","revokeLink": "लिंक रद्द करें",- "saveDraft": "ड्राफ़्ट के रूप में सहेजें"+ "saveDraft": "ड्राफ़्ट के रूप में सहेजें",+ "downloadStatement": "विवरण डाउनलोड करें"},"settings": {"title": "इनवॉइस सेटिंग्स",@@ -341,7 +342,13 @@"unit_price_required": "कीमत के लिए राशि ज़रूरी है।","negative_price": "कीमत ऋणात्मक नहीं हो सकती।","invalid_fiscal_refs": "कर संदर्भ सरल कुंजियों (अक्षर, अंक, अंडरस्कोर) के अंतर्गत छोटे टेक्स्ट मान होने चाहिए।",- "price_key_taken": "कोई अन्य मूल्य पहले से इस खोज कुंजी या बाहरी आईडी का उपयोग कर रहा है।"+ "price_key_taken": "कोई अन्य मूल्य पहले से इस खोज कुंजी या बाहरी आईडी का उपयोग कर रहा है।",+ "installments_mismatch": "किस्तों का योग इनवॉइस के कुल के बराबर नहीं है।",+ "installments_too_few": "अनुसूची में कम से कम दो किस्तें होनी चाहिए।",+ "installment_amount_not_positive": "हर किस्त की कोई राशि होनी चाहिए।",+ "installment_due_required": "हर किस्त की देय तिथि ज़रूरी है।",+ "invalid_deduction_kind": "अज्ञात कटौती प्रकार।",+ "deduction_not_found": "कटौती नहीं मिली।"},"comingNext": "अपने क्लाइंट को बिल भेजें और ट्रैक रखें कि क्या चुकाया गया और क्या अब भी बकाया है। यह अगली चीज़ है जो बनाई जा रही है।","document": {@@ -643,6 +650,61 @@"archive": "संग्रहीत करें","restore": "बहाल करें"}+ },+ "installments": {+ "title": "किस्तों में बाँटें",+ "splitIn": "विभाजित करें",+ "splitHint": "बराबर किस्तों में, एक महीने के अंतर पर, देय तिथि से",+ "add": "किस्त जोड़ें",+ "label": "लेबल",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "कुल {{total}} होता है।",+ "mismatch": "किस्तों का योग {{scheduled}} है, इनवॉइस का {{total}}।",+ "schedule": "भुगतान अनुसूची",+ "nextDue": "अगली देय तिथि",+ "dueDerived": "अंतिम किस्त से तय होती है।",+ "count_one": "{{count}} किस्त",+ "count_other": "{{count}} किस्तें",+ "state": {+ "open": "बकाया",+ "partial": "आंशिक",+ "paid": "भुगतान हो गया",+ "overdue": "अतिदेय",+ "draft": "ड्राफ़्ट",+ "void": "रद्द",+ "uncollectible": "वसूली-अयोग्य"+ }+ },+ "deductions": {+ "title": "कटौती दर्ज करें",+ "description": "बिना पैसा आए बकाया का एक हिस्सा बंद करें: क्लाइंट ने कर काट लिया, प्रोसेसर ने अपना शुल्क रख लिया, मुद्रा रूपांतरण में कम मिला। यह निपटान माना जाता है, प्राप्ति कभी नहीं।",+ "action": "कटौती दर्ज करें",+ "recorded": "कटौती दर्ज हो गई",+ "removed": "कटौती हटा दी गई",+ "amount": "राशि",+ "amountHint": "शेष तक: {{balance}}।",+ "kindLabel": "कारण",+ "taxKind": "कौन सा कर (वैकल्पिक)",+ "taxKindPlaceholder": "TDS, GST...",+ "note": "नोट (वैकल्पिक)",+ "settledWithout": "बिना भुगतान के निपटाया गया",+ "kind": {+ "withholding_tax": "क्लाइंट द्वारा काटा गया कर",+ "gateway_fee": "प्रोसेसर द्वारा रखा गया शुल्क",+ "fx_difference": "मुद्रा रूपांतरण का अंतर",+ "other": "अन्य"+ },+ "differenceTitle": "भुगतान {{difference}} कम है",+ "differenceHint": "इनवॉइस बंद करने के लिए अंतर दर्ज करें",+ "differenceNone": "दर्ज न करें",+ "figure": "कटौती"+ },+ "statement": {+ "asIssued": "जारी किया गया इनवॉइस",+ "asIssuedHint": "ग्राहक को भेजा गया दस्तावेज़",+ "hint": "जारी होने के बाद के भुगतान और कटौतियाँ, और शेष राशि",+ "banner": "यह PDF जारी किया गया इनवॉइस है। तब से {{paid}} प्राप्त हुए और {{deducted}} काटे गए: विवरण हर प्रविष्टि और शेष राशि दिखाता है।",+ "title": "खाता विवरण"}},"collections": {diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 90cab7c3..6a175a11 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Salva bozza"+ "saveDraft": "Salva bozza",+ "downloadStatement": "Scarica estratto conto"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Un prezzo ha bisogno di un importo.","negative_price": "Un prezzo non può essere negativo.","invalid_fiscal_refs": "I riferimenti fiscali devono essere brevi valori di testo sotto chiavi semplici (lettere, cifre, trattino basso).",- "price_key_taken": "Un altro prezzo usa già questa chiave di ricerca o id esterno."+ "price_key_taken": "Un altro prezzo usa già questa chiave di ricerca o id esterno.",+ "installments_mismatch": "Le rate non sommano il totale della fattura.",+ "installments_too_few": "Un piano richiede almeno due rate.",+ "installment_amount_not_positive": "Ogni rata deve avere un importo.",+ "installment_due_required": "Ogni rata richiede una data di scadenza.",+ "invalid_deduction_kind": "Tipo di deduzione sconosciuto.",+ "deduction_not_found": "Deduzione non trovata."},"comingNext": "Fattura i tuoi clienti e tieni traccia di cosa è stato pagato e cosa è ancora aperto. È la prossima cosa in costruzione.","document": {@@ -643,6 +650,61 @@"archive": "Archivia","restore": "Ripristina"}+ },+ "installments": {+ "title": "Dividi in rate",+ "splitIn": "Dividi in",+ "splitHint": "parti uguali, a un mese di distanza, dalla data di scadenza",+ "add": "Aggiungi rata",+ "label": "Etichetta",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Totale {{total}}.",+ "mismatch": "Le rate sommano {{scheduled}}, la fattura {{total}}.",+ "schedule": "Piano di pagamento",+ "nextDue": "Prossima scadenza",+ "dueDerived": "Definita dall'ultima rata.",+ "count_one": "{{count}} rata",+ "count_other": "{{count}} rate",+ "state": {+ "open": "Aperta",+ "partial": "Parziale",+ "paid": "Pagata",+ "overdue": "Scaduta",+ "draft": "Bozza",+ "void": "Annullata",+ "uncollectible": "Inesigibile"+ }+ },+ "deductions": {+ "title": "Registra una deduzione",+ "description": "Chiude parte del dovuto senza che arrivi denaro: il cliente ha trattenuto un'imposta, il processore ha tenuto la sua commissione, la conversione è arrivata più bassa. Conta come saldato, mai come incassato.",+ "action": "Registra deduzione",+ "recorded": "Deduzione registrata",+ "removed": "Deduzione rimossa",+ "amount": "Importo",+ "amountHint": "Fino al saldo: {{balance}}.",+ "kindLabel": "Motivo",+ "taxKind": "Quale imposta (facoltativo)",+ "taxKindPlaceholder": "Ritenuta d'acconto, IVA...",+ "note": "Nota (facoltativo)",+ "settledWithout": "Saldato senza pagamento",+ "kind": {+ "withholding_tax": "Imposta trattenuta dal cliente",+ "gateway_fee": "Commissione trattenuta dal processore",+ "fx_difference": "Differenza di cambio",+ "other": "Altro"+ },+ "differenceTitle": "Il pagamento è inferiore di {{difference}}",+ "differenceHint": "Registra la differenza per chiudere la fattura",+ "differenceNone": "Non registrare",+ "figure": "Trattenuto"+ },+ "statement": {+ "asIssued": "Fattura come emessa",+ "asIssuedHint": "Il documento inviato al cliente",+ "hint": "Pagamenti e trattenute dall'emissione, e il saldo",+ "banner": "Questo PDF è la fattura come emessa. Da allora sono stati ricevuti {{paid}} e trattenuti {{deducted}}: l'estratto conto mostra ogni voce e il saldo.",+ "title": "Estratto conto"}},"collections": {diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex 95019dee..730c0edb 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -236,7 +236,8 @@"downloadPdf": "PDFをダウンロード","share": "リンクを共有","revokeLink": "リンクを失効",- "saveDraft": "下書き保存"+ "saveDraft": "下書き保存",+ "downloadStatement": "明細書をダウンロード"},"settings": {"title": "請求書設定",@@ -341,7 +342,13 @@"unit_price_required": "価格には金額が必要です。","negative_price": "価格をマイナスにはできません。","invalid_fiscal_refs": "税務参照コードは、シンプルなキー(英字、数字、アンダースコア)の下にある短いテキスト値である必要があります。",- "price_key_taken": "別の価格がすでにこの検索キーまたは外部IDを使用しています。"+ "price_key_taken": "別の価格がすでにこの検索キーまたは外部IDを使用しています。",+ "installments_mismatch": "分割の合計が請求書の合計と一致しません。",+ "installments_too_few": "分割払いには2回以上の分割が必要です。",+ "installment_amount_not_positive": "各分割には金額が必要です。",+ "installment_due_required": "各分割には期日が必要です。",+ "invalid_deduction_kind": "不明な控除の種類です。",+ "deduction_not_found": "控除が見つかりません。"},"comingNext": "クライアントに請求し、支払い済みのものと未払いのものを管理します。現在開発中の次の機能です。","document": {@@ -643,6 +650,61 @@"archive": "アーカイブ","restore": "復元"}+ },+ "installments": {+ "title": "分割払いにする",+ "splitIn": "分割数",+ "splitHint": "回に均等分割、1か月間隔、支払期日から",+ "add": "分割を追加",+ "label": "ラベル",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "合計 {{total}}。",+ "mismatch": "分割の合計は {{scheduled}}、請求書は {{total}} です。",+ "schedule": "支払いスケジュール",+ "nextDue": "次回期日",+ "dueDerived": "最後の分割で決まります。",+ "count_one": "{{count}} 回払い",+ "count_other": "{{count}} 回払い",+ "state": {+ "open": "未回収",+ "partial": "一部入金",+ "paid": "入金済み",+ "overdue": "延滞",+ "draft": "下書き",+ "void": "無効",+ "uncollectible": "回収不能"+ }+ },+ "deductions": {+ "title": "控除を記録",+ "description": "入金なしで債権の一部を消し込みます。取引先が源泉徴収した、決済業者が手数料を差し引いた、為替換算で目減りした、といった場合です。回収済みではなく、精算済みとして扱われます。",+ "action": "控除を記録",+ "recorded": "控除を記録しました",+ "removed": "控除を削除しました",+ "amount": "金額",+ "amountHint": "残高まで: {{balance}}。",+ "kindLabel": "理由",+ "taxKind": "税の種類(任意)",+ "taxKindPlaceholder": "源泉所得税、消費税...",+ "note": "メモ(任意)",+ "settledWithout": "入金なしで精算",+ "kind": {+ "withholding_tax": "取引先による源泉徴収",+ "gateway_fee": "決済業者が差し引いた手数料",+ "fx_difference": "為替換算差額",+ "other": "その他"+ },+ "differenceTitle": "入金が {{difference}} 不足しています",+ "differenceHint": "差額を記録すると請求書が完了します",+ "differenceNone": "記録しない",+ "figure": "控除額"+ },+ "statement": {+ "asIssued": "発行時の請求書",+ "asIssuedHint": "顧客に送付した書類",+ "hint": "発行後の入金と控除、および残高",+ "banner": "このPDFは発行時の請求書です。その後 {{paid}} が入金され、{{deducted}} が控除されました。明細書で各項目と残高を確認できます。",+ "title": "取引明細書"}},"collections": {diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 92d198bd..806d526b 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Opslaan als concept"+ "saveDraft": "Opslaan als concept",+ "downloadStatement": "Rekeningoverzicht downloaden"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Een prijs heeft een bedrag nodig.","negative_price": "Een prijs kan niet negatief zijn.","invalid_fiscal_refs": "Fiscale referenties moeten korte tekstwaarden zijn onder eenvoudige sleutels (letters, cijfers, underscore).",- "price_key_taken": "Een andere prijs gebruikt deze zoeksleutel of externe id al."+ "price_key_taken": "Een andere prijs gebruikt deze zoeksleutel of externe id al.",+ "installments_mismatch": "De termijnen tellen niet op tot het factuurtotaal.",+ "installments_too_few": "Een schema heeft minstens twee termijnen nodig.",+ "installment_amount_not_positive": "Elke termijn moet een bedrag hebben.",+ "installment_due_required": "Elke termijn heeft een vervaldatum nodig.",+ "invalid_deduction_kind": "Onbekende soort aftrek.",+ "deduction_not_found": "Aftrek niet gevonden."},"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": {@@ -643,6 +650,61 @@"archive": "Archiveren","restore": "Herstellen"}+ },+ "installments": {+ "title": "In termijnen splitsen",+ "splitIn": "Splitsen in",+ "splitHint": "gelijke delen, een maand uit elkaar, vanaf de vervaldatum",+ "add": "Termijn toevoegen",+ "label": "Label",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Telt op tot {{total}}.",+ "mismatch": "De termijnen tellen op tot {{scheduled}}, de factuur tot {{total}}.",+ "schedule": "Betalingsschema",+ "nextDue": "Volgende vervaldatum",+ "dueDerived": "Bepaald door de laatste termijn.",+ "count_one": "{{count}} termijn",+ "count_other": "{{count}} termijnen",+ "state": {+ "open": "Open",+ "partial": "Gedeeltelijk",+ "paid": "Betaald",+ "overdue": "Verlopen",+ "draft": "Concept",+ "void": "Geannuleerd",+ "uncollectible": "Oninbaar"+ }+ },+ "deductions": {+ "title": "Aftrek vastleggen",+ "description": "Sluit een deel van het verschuldigde bedrag af zonder dat er geld binnenkomt: de klant heeft belasting ingehouden, de betaalprovider heeft zijn kosten ingehouden, de valutaomrekening viel lager uit. Het telt als vereffend, nooit als ontvangen.",+ "action": "Aftrek vastleggen",+ "recorded": "Aftrek vastgelegd",+ "removed": "Aftrek verwijderd",+ "amount": "Bedrag",+ "amountHint": "Tot het saldo: {{balance}}.",+ "kindLabel": "Reden",+ "taxKind": "Welke belasting (optioneel)",+ "taxKindPlaceholder": "Loonheffing, btw...",+ "note": "Notitie (optioneel)",+ "settledWithout": "Vereffend zonder betaling",+ "kind": {+ "withholding_tax": "Belasting ingehouden door de klant",+ "gateway_fee": "Kosten ingehouden door de betaalprovider",+ "fx_difference": "Valutaomrekeningsverschil",+ "other": "Overig"+ },+ "differenceTitle": "De betaling is {{difference}} te laag",+ "differenceHint": "Leg het verschil vast zodat de factuur wordt afgesloten",+ "differenceNone": "Niet vastleggen",+ "figure": "Ingehouden"+ },+ "statement": {+ "asIssued": "Factuur zoals uitgegeven",+ "asIssuedHint": "Het document dat naar de klant is gestuurd",+ "hint": "Betalingen en inhoudingen sinds uitgifte, en het saldo",+ "banner": "Deze PDF is de factuur zoals uitgegeven. Sindsdien is {{paid}} ontvangen en {{deducted}} ingehouden: het rekeningoverzicht toont elke post en het saldo.",+ "title": "Rekeningoverzicht"}},"collections": {diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 39b4304d..9da308cc 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Zapisz szkic"+ "saveDraft": "Zapisz szkic",+ "downloadStatement": "Pobierz wyciąg"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Cena wymaga kwoty.","negative_price": "Cena nie może być ujemna.","invalid_fiscal_refs": "Odniesienia podatkowe muszą być krótkimi wartościami tekstowymi pod prostymi kluczami (litery, cyfry, podkreślenie).",- "price_key_taken": "Inna cena już używa tego klucza wyszukiwania lub zewnętrznego identyfikatora."+ "price_key_taken": "Inna cena już używa tego klucza wyszukiwania lub zewnętrznego identyfikatora.",+ "installments_mismatch": "Raty nie sumują się do kwoty faktury.",+ "installments_too_few": "Harmonogram wymaga co najmniej dwóch rat.",+ "installment_amount_not_positive": "Każda rata musi mieć kwotę.",+ "installment_due_required": "Każda rata wymaga terminu płatności.",+ "invalid_deduction_kind": "Nieznany rodzaj potrącenia.",+ "deduction_not_found": "Nie znaleziono potrącenia."},"comingNext": "Wystawiaj faktury klientom i śledź, co zostało zapłacone, a co wciąż jest otwarte. To następna rzecz w budowie.","document": {@@ -647,6 +654,61 @@"archive": "Archiwizuj","restore": "Przywróć"}+ },+ "installments": {+ "title": "Podziel na raty",+ "splitIn": "Podziel na",+ "splitHint": "równych części, co miesiąc, od terminu płatności",+ "add": "Dodaj ratę",+ "label": "Etykieta",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Suma: {{total}}.",+ "mismatch": "Raty sumują się do {{scheduled}}, faktura do {{total}}.",+ "schedule": "Harmonogram płatności",+ "nextDue": "Najbliższy termin",+ "dueDerived": "Ustalany przez ostatnią ratę.",+ "count_one": "{{count}} rata",+ "count_other": "Raty: {{count}}",+ "state": {+ "open": "Otwarta",+ "partial": "Częściowa",+ "paid": "Opłacona",+ "overdue": "Przeterminowana",+ "draft": "Szkic",+ "void": "Anulowana",+ "uncollectible": "Nieściągalna"+ }+ },+ "deductions": {+ "title": "Zarejestruj potrącenie",+ "description": "Zamyka część należności bez wpływu pieniędzy: klient potrącił podatek, operator płatności zatrzymał prowizję, przewalutowanie wyszło niżej. Liczy się jako rozliczone, nigdy jako otrzymane.",+ "action": "Zarejestruj potrącenie",+ "recorded": "Potrącenie zarejestrowane",+ "removed": "Potrącenie usunięte",+ "amount": "Kwota",+ "amountHint": "Do wysokości salda: {{balance}}.",+ "kindLabel": "Powód",+ "taxKind": "Jaki podatek (opcjonalnie)",+ "taxKindPlaceholder": "PIT, VAT, podatek u źródła...",+ "note": "Notatka (opcjonalnie)",+ "settledWithout": "Rozliczone bez płatności",+ "kind": {+ "withholding_tax": "Podatek potrącony przez klienta",+ "gateway_fee": "Prowizja zatrzymana przez operatora płatności",+ "fx_difference": "Różnica kursowa",+ "other": "Inne"+ },+ "differenceTitle": "Płatność jest niższa o {{difference}}",+ "differenceHint": "Zarejestruj różnicę, aby zamknąć fakturę",+ "differenceNone": "Nie rejestruj",+ "figure": "Potrącono"+ },+ "statement": {+ "asIssued": "Faktura w wystawionej postaci",+ "asIssuedHint": "Dokument wysłany do klienta",+ "hint": "Płatności i potrącenia od wystawienia oraz saldo",+ "banner": "Ten PDF to faktura w wystawionej postaci. Od tego czasu otrzymano {{paid}} i potrącono {{deducted}}: wyciąg pokazuje każdą pozycję i saldo.",+ "title": "Wyciąg z konta"}},"collections": {diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex c67e81fd..0c1f6115 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -236,7 +236,8 @@"downloadPdf": "Baixar PDF","share": "Compartilhar","revokeLink": "Revogar link",- "saveDraft": "Salvar rascunho"+ "saveDraft": "Salvar rascunho",+ "downloadStatement": "Baixar extrato"},"settings": {"title": "Configurações de cobrança",@@ -341,7 +342,13 @@"unit_price_required": "Um preço precisa de um valor.","negative_price": "Um preço não pode ser negativo.","invalid_fiscal_refs": "Referências fiscais devem ser textos curtos sob chaves simples (letras, dígitos, sublinhado).",- "price_key_taken": "Outro preço já usa essa chave de busca ou id externo."+ "price_key_taken": "Outro preço já usa essa chave de busca ou id externo.",+ "installments_mismatch": "As parcelas não somam o total da cobrança.",+ "installments_too_few": "Um parcelamento precisa de pelo menos duas parcelas.",+ "installment_amount_not_positive": "Toda parcela precisa ter um valor.",+ "installment_due_required": "Toda parcela precisa de um vencimento.",+ "invalid_deduction_kind": "Tipo de dedução desconhecido.",+ "deduction_not_found": "Dedução não encontrada."},"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": {@@ -643,6 +650,61 @@"archive": "Arquivar","restore": "Restaurar"}+ },+ "installments": {+ "title": "Parcelar",+ "splitIn": "Dividir em",+ "splitHint": "partes iguais, uma por mês, a partir do vencimento",+ "add": "Adicionar parcela",+ "label": "Rótulo",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Soma {{total}}.",+ "mismatch": "As parcelas somam {{scheduled}}, a cobrança {{total}}.",+ "schedule": "Cronograma de pagamento",+ "nextDue": "Próximo vencimento",+ "dueDerived": "Definido pela última parcela.",+ "count_one": "{{count}} parcela",+ "count_other": "{{count}} parcelas",+ "state": {+ "open": "Em aberto",+ "partial": "Parcial",+ "paid": "Paga",+ "overdue": "Vencida",+ "draft": "Rascunho",+ "void": "Cancelada",+ "uncollectible": "Perda"+ }+ },+ "deductions": {+ "title": "Registrar dedução",+ "description": "Fecha parte do que é devido sem dinheiro entrar: o cliente reteve imposto, o processador ficou com a taxa, a conversão veio menor. Conta como liquidado, nunca como recebido.",+ "action": "Registrar dedução",+ "recorded": "Dedução registrada",+ "removed": "Dedução removida",+ "amount": "Valor",+ "amountHint": "Até o saldo: {{balance}}.",+ "kindLabel": "Motivo",+ "taxKind": "Qual imposto (opcional)",+ "taxKindPlaceholder": "IRRF, ISS, INSS...",+ "note": "Observação (opcional)",+ "settledWithout": "Liquidado sem pagamento",+ "kind": {+ "withholding_tax": "Imposto retido pelo cliente",+ "gateway_fee": "Taxa retida pelo processador",+ "fx_difference": "Diferença de câmbio",+ "other": "Outro"+ },+ "differenceTitle": "O pagamento veio {{difference}} menor",+ "differenceHint": "Registre a diferença para a cobrança fechar",+ "differenceNone": "Não registrar",+ "figure": "Deduzido"+ },+ "statement": {+ "asIssued": "Fatura como emitida",+ "asIssuedHint": "O documento enviado ao cliente",+ "hint": "Pagamentos e deduções desde a emissão, e o saldo",+ "banner": "Este PDF é a fatura como foi emitida. Desde então foram recebidos {{paid}} e deduzidos {{deducted}}: o extrato mostra cada um e o saldo.",+ "title": "Extrato da fatura"}},"collections": {diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 8fc7eb0c..bc50c0df 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -236,7 +236,8 @@"downloadPdf": "Baixar PDF","share": "Compartilhar","revokeLink": "Revogar link",- "saveDraft": "Guardar rascunho"+ "saveDraft": "Guardar rascunho",+ "downloadStatement": "Descarregar extrato"},"settings": {"title": "Configurações de cobrança",@@ -341,7 +342,13 @@"unit_price_required": "Um preço precisa de um valor.","negative_price": "Um preço não pode ser negativo.","invalid_fiscal_refs": "As referências fiscais devem ser textos curtos sob chaves simples (letras, dígitos, sublinhado).",- "price_key_taken": "Outro preço já usa esta chave de pesquisa ou id externo."+ "price_key_taken": "Outro preço já usa esta chave de pesquisa ou id externo.",+ "installments_mismatch": "As prestações não somam o total da cobrança.",+ "installments_too_few": "Um plano precisa de pelo menos duas prestações.",+ "installment_amount_not_positive": "Cada prestação precisa de ter um valor.",+ "installment_due_required": "Cada prestação precisa de um vencimento.",+ "invalid_deduction_kind": "Tipo de dedução desconhecido.",+ "deduction_not_found": "Dedução não encontrada."},"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": {@@ -643,6 +650,61 @@"archive": "Arquivar","restore": "Restaurar"}+ },+ "installments": {+ "title": "Dividir em prestações",+ "splitIn": "Dividir em",+ "splitHint": "partes iguais, uma por mês, a partir do vencimento",+ "add": "Adicionar prestação",+ "label": "Rótulo",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Soma {{total}}.",+ "mismatch": "As prestações somam {{scheduled}}, a cobrança {{total}}.",+ "schedule": "Plano de pagamento",+ "nextDue": "Próximo vencimento",+ "dueDerived": "Definido pela última prestação.",+ "count_one": "{{count}} prestação",+ "count_other": "{{count}} prestações",+ "state": {+ "open": "Em aberto",+ "partial": "Parcial",+ "paid": "Recebida",+ "overdue": "Vencida",+ "draft": "Rascunho",+ "void": "Cancelada",+ "uncollectible": "Incobrável"+ }+ },+ "deductions": {+ "title": "Registar dedução",+ "description": "Fecha parte do que é devido sem entrar dinheiro: o cliente reteve imposto, o processador ficou com a comissão, a conversão cambial veio abaixo. Conta como liquidado, nunca como recebido.",+ "action": "Registar dedução",+ "recorded": "Dedução registada",+ "removed": "Dedução removida",+ "amount": "Valor",+ "amountHint": "Até ao saldo: {{balance}}.",+ "kindLabel": "Motivo",+ "taxKind": "Qual imposto (opcional)",+ "taxKindPlaceholder": "IRS, IRC, IVA...",+ "note": "Nota (opcional)",+ "settledWithout": "Liquidado sem pagamento",+ "kind": {+ "withholding_tax": "Imposto retido pelo cliente",+ "gateway_fee": "Comissão retida pelo processador",+ "fx_difference": "Diferença cambial",+ "other": "Outro"+ },+ "differenceTitle": "O pagamento veio {{difference}} abaixo",+ "differenceHint": "Registe a diferença para a cobrança fechar",+ "differenceNone": "Não registar",+ "figure": "Deduzido"+ },+ "statement": {+ "asIssued": "Fatura como emitida",+ "asIssuedHint": "O documento enviado ao cliente",+ "hint": "Pagamentos e deduções desde a emissão, e o saldo",+ "banner": "Este PDF é a fatura como foi emitida. Desde então foram recebidos {{paid}} e deduzidos {{deducted}}: o extrato mostra cada um e o saldo.",+ "title": "Extrato da fatura"}},"collections": {diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex f77082e2..2d92b597 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Сохранить черновик"+ "saveDraft": "Сохранить черновик",+ "downloadStatement": "Скачать выписку"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Цене нужна сумма.","negative_price": "Цена не может быть отрицательной.","invalid_fiscal_refs": "Налоговые ссылки должны быть короткими текстовыми значениями под простыми ключами (буквы, цифры, подчёркивание).",- "price_key_taken": "Другая цена уже использует этот ключ поиска или внешний идентификатор."+ "price_key_taken": "Другая цена уже использует этот ключ поиска или внешний идентификатор.",+ "installments_mismatch": "Сумма платежей не совпадает с суммой счёта.",+ "installments_too_few": "В графике должно быть не меньше двух платежей.",+ "installment_amount_not_positive": "У каждого платежа должна быть сумма.",+ "installment_due_required": "У каждого платежа должен быть срок оплаты.",+ "invalid_deduction_kind": "Неизвестный тип удержания.",+ "deduction_not_found": "Удержание не найдено."},"comingNext": "Выставляйте счета клиентам и следите за тем, что оплачено, а что остаётся открытым. Это следующее, что будет сделано.","document": {@@ -647,6 +654,61 @@"archive": "В архив","restore": "Восстановить"}+ },+ "installments": {+ "title": "Разбить на платежи",+ "splitIn": "Разбить на",+ "splitHint": "равных частей, с интервалом в месяц, начиная со срока оплаты",+ "add": "Добавить платёж",+ "label": "Метка",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Итого {{total}}.",+ "mismatch": "Платежи в сумме дают {{scheduled}}, счёт: {{total}}.",+ "schedule": "График платежей",+ "nextDue": "Ближайший срок",+ "dueDerived": "Определяется последним платежом.",+ "count_one": "{{count}} платёж",+ "count_other": "Платежей: {{count}}",+ "state": {+ "open": "Открыт",+ "partial": "Частично",+ "paid": "Оплачен",+ "overdue": "Просрочен",+ "draft": "Черновик",+ "void": "Аннулирован",+ "uncollectible": "Безнадёжный"+ }+ },+ "deductions": {+ "title": "Записать удержание",+ "description": "Закрывает часть долга без поступления денег: клиент удержал налог, платёжный сервис оставил себе комиссию, конвертация валюты дала меньше. Считается погашенным, но не полученным.",+ "action": "Записать удержание",+ "recorded": "Удержание записано",+ "removed": "Удержание удалено",+ "amount": "Сумма",+ "amountHint": "Не больше остатка: {{balance}}.",+ "kindLabel": "Причина",+ "taxKind": "Какой налог (необязательно)",+ "taxKindPlaceholder": "НДФЛ, НДС...",+ "note": "Заметка (необязательно)",+ "settledWithout": "Погашено без оплаты",+ "kind": {+ "withholding_tax": "Налог, удержанный клиентом",+ "gateway_fee": "Комиссия платёжного сервиса",+ "fx_difference": "Курсовая разница",+ "other": "Другое"+ },+ "differenceTitle": "Платёж меньше на {{difference}}",+ "differenceHint": "Запишите разницу, чтобы закрыть счёт",+ "differenceNone": "Не записывать",+ "figure": "Удержано"+ },+ "statement": {+ "asIssued": "Счёт в выставленном виде",+ "asIssuedHint": "Документ, отправленный клиенту",+ "hint": "Платежи и удержания с момента выставления и остаток",+ "banner": "Этот PDF является счётом в выставленном виде. С тех пор получено {{paid}} и удержано {{deducted}}: выписка показывает каждую операцию и остаток.",+ "title": "Выписка по счёту"}},"collections": {diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 3a72d192..678d38a2 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -236,7 +236,8 @@"downloadPdf": "Stiahnuť PDF","share": "Zdieľať odkaz","revokeLink": "Zrušiť odkaz",- "saveDraft": "Uložiť ako koncept"+ "saveDraft": "Uložiť ako koncept",+ "downloadStatement": "Stiahnuť výpis"},"settings": {"title": "Nastavenia faktúr",@@ -341,7 +342,13 @@"unit_price_required": "Cena potrebuje sumu.","negative_price": "Cena nemôže byť záporná.","invalid_fiscal_refs": "Daňové referencie musia byť krátke textové hodnoty pod jednoduchými kľúčmi (písmená, číslice, podčiarknutie).",- "price_key_taken": "Iná cena už používa tento vyhľadávací kľúč alebo externé id."+ "price_key_taken": "Iná cena už používa tento vyhľadávací kľúč alebo externé id.",+ "installments_mismatch": "Splátky nedávajú spolu sumu faktúry.",+ "installments_too_few": "Splátkový kalendár potrebuje aspoň dve splátky.",+ "installment_amount_not_positive": "Každá splátka musí mať sumu.",+ "installment_due_required": "Každá splátka potrebuje dátum splatnosti.",+ "invalid_deduction_kind": "Neznámy typ zrážky.",+ "deduction_not_found": "Zrážka sa nenašla."},"comingNext": "Fakturujte klientom a majte prehľad o tom, čo je zaplatené a čo ešte otvorené. Toto sa práve stavia.","document": {@@ -647,6 +654,61 @@"archive": "Archivovať","restore": "Obnoviť"}+ },+ "installments": {+ "title": "Rozdeliť na splátky",+ "splitIn": "Rozdeliť na",+ "splitHint": "rovnakých častí, s mesačným odstupom, od dátumu splatnosti",+ "add": "Pridať splátku",+ "label": "Označenie",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Spolu {{total}}.",+ "mismatch": "Splátky dávajú spolu {{scheduled}}, faktúra {{total}}.",+ "schedule": "Splátkový kalendár",+ "nextDue": "Najbližšia splatnosť",+ "dueDerived": "Určená poslednou splátkou.",+ "count_one": "{{count}} splátka",+ "count_other": "Splátky: {{count}}",+ "state": {+ "open": "Otvorená",+ "partial": "Čiastočná",+ "paid": "Uhradená",+ "overdue": "Po splatnosti",+ "draft": "Koncept",+ "void": "Stornovaná",+ "uncollectible": "Nevymožiteľná"+ }+ },+ "deductions": {+ "title": "Zaznamenať zrážku",+ "description": "Uzavrie časť pohľadávky bez toho, aby prišli peniaze: klient zrazil daň, platobná brána si nechala poplatok, prepočet meny vyšiel nižšie. Počíta sa ako vyrovnané, nikdy ako prijaté.",+ "action": "Zaznamenať zrážku",+ "recorded": "Zrážka zaznamenaná",+ "removed": "Zrážka odstránená",+ "amount": "Suma",+ "amountHint": "Najviac do výšky zostatku: {{balance}}.",+ "kindLabel": "Dôvod",+ "taxKind": "Ktorá daň (voliteľné)",+ "taxKindPlaceholder": "Zrážková daň, DPH...",+ "note": "Poznámka (voliteľné)",+ "settledWithout": "Vyrovnané bez platby",+ "kind": {+ "withholding_tax": "Daň zrazená klientom",+ "gateway_fee": "Poplatok, ktorý si nechala platobná brána",+ "fx_difference": "Kurzový rozdiel",+ "other": "Iné"+ },+ "differenceTitle": "Platba je o {{difference}} nižšia",+ "differenceHint": "Zaznamenajte rozdiel, aby sa faktúra uzavrela",+ "differenceNone": "Nezaznamenať",+ "figure": "Zrazené"+ },+ "statement": {+ "asIssued": "Faktúra v vystavenej podobe",+ "asIssuedHint": "Dokument odoslaný klientovi",+ "hint": "Platby a zrážky od vystavenia a zostatok",+ "banner": "Toto PDF je faktúra vo vystavenej podobe. Odvtedy bolo prijatých {{paid}} a zrazených {{deducted}}: výpis ukazuje každú položku a zostatok.",+ "title": "Výpis z účtu"}},"collections": {diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex d58370af..d2e3bd61 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -236,7 +236,8 @@"downloadPdf": "Download PDF","share": "Share link","revokeLink": "Revoke link",- "saveDraft": "Зберегти чернетку"+ "saveDraft": "Зберегти чернетку",+ "downloadStatement": "Завантажити виписку"},"settings": {"title": "Invoice settings",@@ -341,7 +342,13 @@"unit_price_required": "Ціні потрібна сума.","negative_price": "Ціна не може бути від'ємною.","invalid_fiscal_refs": "Податкові посилання мають бути короткими текстовими значеннями під простими ключами (літери, цифри, підкреслення).",- "price_key_taken": "Інша ціна вже використовує цей ключ пошуку або зовнішній ідентифікатор."+ "price_key_taken": "Інша ціна вже використовує цей ключ пошуку або зовнішній ідентифікатор.",+ "installments_mismatch": "Сума внесків не збігається з сумою рахунку.",+ "installments_too_few": "У графіку має бути щонайменше два внески.",+ "installment_amount_not_positive": "Кожен внесок повинен мати суму.",+ "installment_due_required": "Кожен внесок потребує терміну оплати.",+ "invalid_deduction_kind": "Невідомий тип утримання.",+ "deduction_not_found": "Утримання не знайдено."},"comingNext": "Виставляйте рахунки клієнтам і стежте за тим, що оплачено, а що залишається відкритим. Це наступне, що буде зроблено.","document": {@@ -647,6 +654,61 @@"archive": "В архів","restore": "Відновити"}+ },+ "installments": {+ "title": "Розбити на внески",+ "splitIn": "Розбити на",+ "splitHint": "рівних частин, з інтервалом у місяць, починаючи з терміну оплати",+ "add": "Додати внесок",+ "label": "Мітка",+ "labelPlaceholder": "{{n}}/{{total}}",+ "addsUp": "Разом {{total}}.",+ "mismatch": "Внески в сумі дають {{scheduled}}, рахунок: {{total}}.",+ "schedule": "Графік платежів",+ "nextDue": "Найближчий термін",+ "dueDerived": "Визначається останнім внеском.",+ "count_one": "{{count}} внесок",+ "count_other": "Внесків: {{count}}",+ "state": {+ "open": "Відкритий",+ "partial": "Частково",+ "paid": "Оплачений",+ "overdue": "Прострочений",+ "draft": "Чернетка",+ "void": "Анульований",+ "uncollectible": "Безнадійний"+ }+ },+ "deductions": {+ "title": "Записати утримання",+ "description": "Закриває частину боргу без надходження грошей: клієнт утримав податок, платіжний сервіс залишив собі комісію, конвертація валюти дала менше. Вважається погашеним, але не отриманим.",+ "action": "Записати утримання",+ "recorded": "Утримання записано",+ "removed": "Утримання видалено",+ "amount": "Сума",+ "amountHint": "Не більше залишку: {{balance}}.",+ "kindLabel": "Причина",+ "taxKind": "Який податок (необов'язково)",+ "taxKindPlaceholder": "ПДФО, ПДВ...",+ "note": "Нотатка (необов'язково)",+ "settledWithout": "Погашено без оплати",+ "kind": {+ "withholding_tax": "Податок, утриманий клієнтом",+ "gateway_fee": "Комісія платіжного сервісу",+ "fx_difference": "Курсова різниця",+ "other": "Інше"+ },+ "differenceTitle": "Платіж менший на {{difference}}",+ "differenceHint": "Запишіть різницю, щоб закрити рахунок",+ "differenceNone": "Не записувати",+ "figure": "Утримано"+ },+ "statement": {+ "asIssued": "Рахунок у виставленому вигляді",+ "asIssuedHint": "Документ, надісланий клієнту",+ "hint": "Платежі та утримання з моменту виставлення і залишок",+ "banner": "Цей PDF є рахунком у виставленому вигляді. Відтоді отримано {{paid}} і утримано {{deducted}}: виписка показує кожну операцію і залишок.",+ "title": "Виписка по рахунку"}},"collections": {diff --git a/frontend/src/pages/invoice-detail.test.tsx b/frontend/src/pages/invoice-detail.test.tsxnew file mode 100644index 00000000..698f1e3a--- /dev/null+++ b/frontend/src/pages/invoice-detail.test.tsx@@ -0,0 +1,144 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { screen, waitFor } from '@testing-library/react'++import { LinkPaymentDialog } from '@/pages/invoice-detail'+import { renderWithProviders, t } from '@/test/utils'+import type { Transaction } from '@/types'++const api = vi.hoisted(() => ({+ invoices: { allocate: vi.fn(), deduct: vi.fn() },+ transactions: { list: vi.fn() },+}))++vi.mock('@/lib/api', () => ({+ invoices: api.invoices,+ transactions: api.transactions,+}))++vi.mock('@/hooks/use-display-locale', () => ({+ useDisplayLocale: () => 'en-US',+ useDateLocale: () => 'en-US',+}))++const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }))+vi.mock('sonner', () => ({ toast }))++const payment = {+ id: 'tx-1',+ description: 'Wire from Beta',+ amount: 1000,+ currency: 'USD',+ date: '2026-10-12',+ type: 'credit',+} as Transaction++function apiError(code: string) {+ return { response: { data: { detail: { code } } } }+}++function renderDialog() {+ const onOpenChange = vi.fn()+ const onLinked = vi.fn()+ const { user } = renderWithProviders(+ <LinkPaymentDialog+ open+ onOpenChange={onOpenChange}+ invoiceId="inv-1"+ direction="receivable"+ balance="3000.00"+ settleTarget="1500.00"+ currency="USD"+ onLinked={onLinked}+ />,+ )+ return { user, onOpenChange, onLinked }+}++async function pickPaymentAndDifference(user: ReturnType<typeof renderDialog>['user']) {+ await user.click(await screen.findByTestId('invoice-candidate'))+ // 1500 expected, 1000 paid: the dialog offers to record the 500.+ expect(screen.getByTestId('invoice-difference')).toHaveTextContent('$500.00')+ await user.click(screen.getByTestId('invoice-difference-kind'))+ await user.click(screen.getByRole('option', { name: t('invoices.deductions.kind.withholding_tax') }))+}++describe('LinkPaymentDialog', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ api.transactions.list.mockResolvedValue({ items: [payment], total: 1 })+ })++ it('links the payment and records the difference as a deduction', async () => {+ api.invoices.allocate.mockResolvedValue({})+ api.invoices.deduct.mockResolvedValue({})+ const { user, onOpenChange, onLinked } = renderDialog()+ await pickPaymentAndDifference(user)++ await user.click(screen.getByTestId('invoice-allocation-submit'))++ await waitFor(() => expect(onLinked).toHaveBeenCalled())+ expect(api.invoices.allocate).toHaveBeenCalledWith('inv-1', 'tx-1', undefined)+ expect(api.invoices.deduct).toHaveBeenCalledWith('inv-1', {+ kind: 'withholding_tax',+ amount: '500.00',+ transaction_id: 'tx-1',+ })+ expect(onOpenChange).toHaveBeenCalledWith(false)+ expect(toast.success).toHaveBeenCalledWith(t('invoices.linked'))+ })++ it('stays open when the link itself fails, so the person can retry', async () => {+ api.invoices.allocate.mockRejectedValue(apiError('over_allocation'))+ const { user, onOpenChange, onLinked } = renderDialog()+ await pickPaymentAndDifference(user)++ await user.click(screen.getByTestId('invoice-allocation-submit'))++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(t('invoices.errors.over_allocation')))+ expect(api.invoices.deduct).not.toHaveBeenCalled()+ expect(onLinked).not.toHaveBeenCalled()+ expect(onOpenChange).not.toHaveBeenCalled()+ })++ it('closes and refreshes when the payment linked but the deduction failed', async () => {+ // Left open, a second "link" would allocate the same payment twice.+ api.invoices.allocate.mockResolvedValue({})+ api.invoices.deduct.mockRejectedValue(apiError('over_allocation'))+ const { user, onOpenChange, onLinked } = renderDialog()+ await pickPaymentAndDifference(user)++ await user.click(screen.getByTestId('invoice-allocation-submit'))++ await waitFor(() => expect(onLinked).toHaveBeenCalled())+ expect(onOpenChange).toHaveBeenCalledWith(false)+ expect(toast.error).toHaveBeenCalledWith(t('invoices.errors.over_allocation'))+ expect(toast.success).toHaveBeenCalledWith(t('invoices.linked'))+ })+})+++describe('LinkPaymentDialog candidates', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('leaves out money already linked here or spent in full elsewhere', async () => {+ const link = (invoice_id: string, amount: string) => ({+ invoice_id, amount, number: 1, series: null, external_number: null,+ })+ api.transactions.list.mockResolvedValue({+ items: [+ { ...payment, id: 'here', description: 'Already on this invoice', invoice_links: [link('inv-1', '1000.00')] },+ { ...payment, id: 'spent', description: 'Spent on another', invoice_links: [link('inv-9', '1000.00')] },+ { ...payment, id: 'part', description: 'Half used elsewhere', invoice_links: [link('inv-9', '400.00')] },+ { ...payment, id: 'free', description: 'Untouched' },+ ],+ total: 4,+ })+ renderDialog()+ expect(await screen.findByText('Untouched')).toBeInTheDocument()+ expect(screen.getByText('Half used elsewhere')).toBeInTheDocument()+ expect(screen.queryByText('Already on this invoice')).not.toBeInTheDocument()+ expect(screen.queryByText('Spent on another')).not.toBeInTheDocument()+ })+})diff --git a/frontend/src/pages/invoice-detail.tsx b/frontend/src/pages/invoice-detail.tsxindex 2041775b..a7b6d26d 100644--- a/frontend/src/pages/invoice-detail.tsx+++ b/frontend/src/pages/invoice-detail.tsx@@ -1,10 +1,10 @@-import { useMemo, useState } from 'react'+import { useMemo, useRef, 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, Check, CheckCircle2, CircleSlash, Copy, Download, Link2,- MoreHorizontal, Pencil, Repeat, RotateCcw, Send, Share2, Trash2, Unlink,+ ArrowLeft, Ban, Check, CheckCircle2, CircleSlash, Copy, Download, FileText, Link2,+ MinusCircle, MoreHorizontal, Pencil, Repeat, RotateCcw, Send, Share2, Trash2, Unlink,} from 'lucide-react'import { toast } from 'sonner'@@ -45,9 +45,13 @@ import {import { InvoiceDocumentView } from '@/components/invoice-document'import { InvoiceDocumentBrowser } from '@/components/invoice-documents'import { InvoiceLineEditor } from '@/components/invoice-line-editor'+import { InvoiceInstallmentsEditor } from '@/components/invoice-installments-editor'+import { DEDUCTION_KINDS, displayDue, installmentsTotal } from '@/lib/installment-utils'import { EndConditionFields, SchedulePeriodChip } from '@/components/invoice-schedule-ui'import { FREQUENCIES, endPayload } from '@/lib/invoice-schedule-utils'import type {+ DeductionKind,+ InstallmentInput,Invoice,InvoiceDirection,InvoiceLineInput,@@ -99,6 +103,7 @@ export default function InvoiceDetailPage() {const [linkOpen, setLinkOpen] = useState(false)const [editOpen, setEditOpen] = useState(false)const [recurringOpen, setRecurringOpen] = useState(false)+ const [deductionOpen, setDeductionOpen] = useState(false)const [tab, setTab] = useState<Tab>('details')const [copied, setCopied] = useState(false)@@ -182,6 +187,14 @@ export default function InvoiceDetailPage() {},onError,})+ const undeductMutation = useMutation({+ mutationFn: (deductionId: string) => invoicesApi.undeduct(id, deductionId),+ onSuccess: () => {+ toast.success(t('invoices.deductions.removed'))+ refresh()+ },+ onError,+ })const unlinkMutation = useMutation({mutationFn: (allocationId: string) => invoicesApi.unallocate(id, allocationId),onSuccess: () => {@@ -207,6 +220,22 @@ export default function InvoiceDetailPage() {onError,})+ // The statement of account: what was paid and deducted since issue,+ // and how that arrives at the balance. The invoice PDF is the document+ // as issued and never shows it.+ const statementMutation = useMutation({+ mutationFn: async () => {+ const blob = await invoicesApi.statement(id)+ const url = URL.createObjectURL(blob)+ const anchor = window.document.createElement('a')+ anchor.href = url+ anchor.download = `${invoice?.number ?? 'invoice'}-statement.pdf`+ anchor.click()+ URL.revokeObjectURL(url)+ },+ onError,+ })+const shareMutation = useMutation({mutationFn: () => invoicesApi.share(id),onSuccess: async (link) => {@@ -263,6 +292,17 @@ export default function InvoiceDetailPage() {invoice.status !== 'draft' &&invoice.status !== 'void' &&!invoice.schedule_id+ // Only for what we issued: a draft was sent to nobody, and a bill we+ // received is the supplier's to state.+ const canStatement =+ invoice.direction === 'receivable' &&+ invoice.status !== 'draft' &&+ invoice.origin !== 'imported'+ const hasDeductions = Number(invoice.amount_deducted) > 0+ // Once money has moved, the invoice PDF (frozen at issue) no longer says+ // everything: what was paid and deducted since is on the statement, and+ // the page offers both instead of letting the first pass for the whole.+ const offerStatement = canStatement && (Number(invoice.amount_paid) > 0 || hasDeductions)return (<div>@@ -313,7 +353,39 @@ export default function InvoiceDetailPage() {somebody else issued — the same invention theDocument tab refuses to make. Nothing to downloaduntil the real file arrives. */}- {(invoice.origin !== 'imported' || hasFiledDocument) && (+ {offerStatement ? (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button size="sm" variant="outline" data-testid="invoice-download-pdf">+ <Download className="h-4 w-4 mr-1.5" />+ {t('invoices.action.downloadPdf')}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-[260px] p-1 bg-card border border-border rounded-xl shadow-md"+ >+ <DropdownMenuItem+ onClick={() => downloadMutation.mutate()}+ disabled={downloadMutation.isPending}+ data-testid="invoice-download-issued"+ className="flex-col items-start gap-0.5 text-sm"+ >+ <span>{t('invoices.statement.asIssued')}</span>+ <span className="text-[11px] text-muted-foreground">{t('invoices.statement.asIssuedHint')}</span>+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={() => statementMutation.mutate()}+ disabled={statementMutation.isPending}+ data-testid="invoice-download-statement"+ className="flex-col items-start gap-0.5 text-sm"+ >+ <span>{t('invoices.statement.title')}</span>+ <span className="text-[11px] text-muted-foreground">{t('invoices.statement.hint')}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ ) : (invoice.origin !== 'imported' || hasFiledDocument) && (<Buttonsize="sm"variant="outline"@@ -464,6 +536,31 @@ export default function InvoiceDetailPage() {{tab === 'document' ? (<div className="space-y-4">+ {offerStatement && (+ <SectionCard>+ <div+ className="flex flex-wrap items-center gap-3 px-4 sm:px-5 py-3 text-sm"+ data-testid="invoice-statement-banner"+ >+ <FileText className="h-4 w-4 text-muted-foreground shrink-0" />+ <p className="flex-1 min-w-[16rem] text-muted-foreground">+ {t('invoices.statement.banner', {+ paid: money(invoice.amount_paid),+ deducted: money(invoice.amount_deducted),+ })}+ </p>+ <Button+ size="sm"+ variant="outline"+ onClick={() => statementMutation.mutate()}+ disabled={statementMutation.isPending}+ >+ <Download className="h-4 w-4 mr-1.5" />+ {t('invoices.action.downloadStatement')}+ </Button>+ </div>+ </SectionCard>+ )}{shareUrl && (<SectionCard><div@@ -509,7 +606,15 @@ export default function InvoiceDetailPage() {) : (<div className="space-y-5"><SectionCard>- <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-border">+ {/* Total, then what reduced it, then what is left: read left+ to right it is the arithmetic. Deductions only when there+ are any, so an ordinary invoice keeps its four figures. */}+ <div+ className={cn(+ 'grid grid-cols-2 divide-x divide-border',+ hasDeductions ? 'sm:grid-cols-5' : 'sm:grid-cols-4',+ )}+ >{[{ label: t('invoices.column.total'), value: money(invoice.total) },{@@ -519,6 +624,13 @@ export default function InvoiceDetailPage() {: t('invoices.field.paid'),value: money(invoice.amount_paid),},+ ...(hasDeductions+ ? [{+ label: t('invoices.deductions.figure'),+ value: money(invoice.amount_deducted),+ testId: 'invoice-deducted',+ }]+ : []),{label: t('invoices.column.balance'),value: money(invoice.balance),@@ -528,7 +640,11 @@ export default function InvoiceDetailPage() {: 'text-emerald-600',testId: 'invoice-balance',},- { label: t('invoices.column.due'), value: showDate(invoice.due_date) },+ {+ label: invoice.installments.length ? t('invoices.installments.nextDue') : t('invoices.column.due'),+ value: showDate(displayDue(invoice)),+ testId: 'invoice-due-figure',+ },].map((figure) => (<div key={figure.label} className="px-4 sm:px-5 py-4" data-testid={figure.testId}><p className="text-xs font-medium text-muted-foreground mb-0.5">{figure.label}</p>@@ -545,6 +661,49 @@ export default function InvoiceDetailPage() {</div></SectionCard>+ {invoice.installments.length > 0 && (+ <SectionCard>+ <SectionHeader+ title={t('invoices.installments.schedule')}+ description={t('invoices.installments.count', { count: invoice.installments.length })}+ />+ <table className="w-full" data-testid="invoice-installments">+ <tbody>+ {invoice.installments.map((row, index) => (+ <tr key={row.id} className="border-b border-border last:border-0" data-testid="invoice-installment-row">+ <td className="py-2.5 pl-4 sm:pl-5 text-sm">+ {row.label ?? `${index + 1}/${invoice.installments.length}`}+ </td>+ <td className="py-2.5 text-xs text-muted-foreground tabular-nums">{showDate(row.due_date)}</td>+ <td className="py-2.5 text-right text-sm tabular-nums">+ {money(row.amount)}+ {Number(row.settled) > 0 && Number(row.settled) < Number(row.amount) && (+ <span className="ml-1.5 text-[11px] text-muted-foreground">+ {t('invoices.field.paid').toLowerCase()} {money(row.settled)}+ </span>+ )}+ </td>+ <td className="py-2.5 pr-4 sm:pr-5 text-right w-28">+ <span+ data-testid={`installment-state-${row.state}`}+ className={cn(+ 'text-[11px] font-semibold px-2 py-0.5 rounded-full border whitespace-nowrap',+ row.state === 'paid' && 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20',+ row.state === 'overdue' && 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20',+ row.state === 'partial' && 'bg-amber-50 text-amber-700 border-amber-100 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20',+ !['paid', 'overdue', 'partial'].includes(row.state) && 'bg-muted text-muted-foreground border-border',+ )}+ >+ {t(`invoices.installments.state.${row.state}`)}+ </span>+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </SectionCard>+ )}+{(invoice.lines.length > 0 || invoice.notes || customFields.length > 0) && (<SectionCard><SectionHeader title={t('invoices.detailsTitle')} />@@ -611,13 +770,57 @@ export default function InvoiceDetailPage() {title={t('invoices.payments')}action={actions.canAllocate && canWrite ? (- <Button size="sm" variant="outline" onClick={() => setLinkOpen(true)}>- <Link2 className="h-3.5 w-3.5 mr-1.5" />- {t('invoices.action.link')}- </Button>+ <div className="flex items-center gap-2">+ {/* The other way a debt closes: without money. Quieter+ than the payment button, because it is the exception. */}+ <Button size="sm" variant="ghost" onClick={() => setDeductionOpen(true)} data-testid="invoice-record-deduction">+ <MinusCircle className="h-3.5 w-3.5 mr-1.5" />+ {t('invoices.deductions.action')}+ </Button>+ <Button size="sm" variant="outline" onClick={() => setLinkOpen(true)}>+ <Link2 className="h-3.5 w-3.5 mr-1.5" />+ {t('invoices.action.link')}+ </Button>+ </div>) : undefined}/>+ {invoice.deductions.length > 0 && (+ <table className="w-full border-b border-border" data-testid="invoice-deductions">+ <tbody>+ {invoice.deductions.map((deduction) => (+ <tr key={deduction.id} data-testid="invoice-deduction" className="border-b border-border last:border-0 bg-muted/20">+ <td className="py-3 pl-4 sm:pl-5">+ <div className="text-sm font-medium text-foreground truncate">+ {t(`invoices.deductions.kind.${deduction.kind}`)}+ {deduction.tax_kind && (+ <span className="ml-1.5 text-xs uppercase text-muted-foreground">{deduction.tax_kind}</span>+ )}+ </div>+ <div className="text-xs text-muted-foreground truncate">+ {t('invoices.deductions.settledWithout')}+ {deduction.note ? ` · ${deduction.note}` : ''}+ </div>+ </td>+ <td className="py-3 text-right text-sm font-bold tabular-nums text-muted-foreground">+ {money(deduction.amount)}+ </td>+ <td className="py-3 pr-4 sm:pr-5 text-right w-16">+ {canWrite && invoice.status === 'open' && (+ <IconAction+ onClick={() => undeductMutation.mutate(deduction.id)}+ label={t('common.delete')}+ destructive+ >+ <Trash2 className="h-4 w-4" />+ </IconAction>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}{invoice.allocations.length === 0 ? (<pclassName="px-4 sm:px-5 py-8 text-center text-sm text-muted-foreground"@@ -716,19 +919,134 @@ export default function InvoiceDetailPage() {invoiceId={id}direction={invoice.direction}balance={invoice.balance}+ // With a schedule, a short payment is short of the installment+ // being paid, not of the whole invoice.+ settleTarget={(() => {+ const next = invoice.installments.find((row) => Number(row.settled) < Number(row.amount))+ return next ? (Number(next.amount) - Number(next.settled)).toFixed(2) : invoice.balance+ })()}currency={currency}onLinked={refresh}/>+ <RecordDeductionDialog+ key={deductionOpen ? 'deduction-open' : 'deduction-closed'}+ open={deductionOpen}+ onOpenChange={setDeductionOpen}+ invoiceId={id}+ balance={invoice.balance}+ currency={currency}+ onRecorded={refresh}+ /></div>)}-function LinkPaymentDialog({+/**+ * Closing part of the debt without money. The exception to the payment+ * flow, kept as its own small dialog: a reason, an amount defaulting to+ * whatever is left, and a note the accountant will thank you for.+ */+function RecordDeductionDialog({+ open,+ onOpenChange,+ invoiceId,+ balance,+ currency,+ onRecorded,+ initialAmount,+ transactionId,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ invoiceId: string+ balance: string+ currency: string+ onRecorded: () => void+ initialAmount?: string+ transactionId?: string | null+}) {+ const { t } = useTranslation()+ const locale = useDisplayLocale()+ const [kind, setKind] = useState<DeductionKind>('withholding_tax')+ const [amount, setAmount] = useState(initialAmount ?? balance)+ const [taxKind, setTaxKind] = useState('')+ const [note, setNote] = useState('')+ const mutation = useMutation({+ mutationFn: () =>+ invoicesApi.deduct(invoiceId, {+ kind,+ amount,+ tax_kind: kind === 'withholding_tax' ? taxKind || null : null,+ note: note || null,+ transaction_id: transactionId ?? null,+ }),+ onSuccess: () => {+ toast.success(t('invoices.deductions.recorded'))+ onOpenChange(false)+ onRecorded()+ },+ onError: (error) => {+ const key = invoiceErrorKey(error)+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ },+ })+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>{t('invoices.deductions.title')}</DialogTitle>+ <DialogDescription>{t('invoices.deductions.description')}</DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label>{t('invoices.deductions.kindLabel')}</Label>+ <Select value={kind} onValueChange={(v) => setKind(v as DeductionKind)}>+ <SelectTrigger data-testid="deduction-kind"><SelectValue /></SelectTrigger>+ <SelectContent>+ {DEDUCTION_KINDS.map((k) => (+ <SelectItem key={k} value={k}>{t(`invoices.deductions.kind.${k}`)}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label htmlFor="deduction-amount">{t('invoices.deductions.amount')}</Label>+ <Input id="deduction-amount" data-testid="deduction-amount" inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} />+ <p className="text-[11px] text-muted-foreground">+ {t('invoices.deductions.amountHint', { balance: formatCurrency(Number(balance), currency, locale) })}+ </p>+ </div>+ {kind === 'withholding_tax' && (+ <div className="space-y-1.5">+ <Label htmlFor="deduction-tax-kind">{t('invoices.deductions.taxKind')}</Label>+ <Input id="deduction-tax-kind" data-testid="deduction-tax-kind" value={taxKind} onChange={(e) => setTaxKind(e.target.value)} placeholder={t('invoices.deductions.taxKindPlaceholder')} maxLength={30} />+ </div>+ )}+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="deduction-note">{t('invoices.deductions.note')}</Label>+ <Input id="deduction-note" data-testid="deduction-note" value={note} onChange={(e) => setNote(e.target.value)} maxLength={500} />+ </div>+ </div>+ <DialogFooter className="gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>+ <Button onClick={() => mutation.mutate()} disabled={!(Number(amount) > 0) || mutation.isPending} data-testid="deduction-submit">+ {t('invoices.deductions.action')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++export function LinkPaymentDialog({open,onOpenChange,invoiceId,direction,balance,+ settleTarget,currency,onLinked,}: {@@ -737,12 +1055,20 @@ function LinkPaymentDialog({invoiceId: stringdirection: InvoiceDirectionbalance: string+ /** What this payment is expected to cover: the next installment's+ * remainder, or the balance. The "short by" reading uses it. */+ settleTarget?: stringcurrency: stringonLinked: () => void}) {const { t } = useTranslation()+ const locale = useDisplayLocale()const [selected, setSelected] = useState<string>('')const [amount, setAmount] = useState('')+ // When the payment is short of the balance: what the difference is,+ // or nothing. Answered once, here, instead of leaving the invoice+ // partial and sending the person to find another button.+ const [differenceKind, setDifferenceKind] = useState<DeductionKind | 'none'>('none')// Money moving the way this invoice is settled: a receivable by money// coming in, a payable by money going out. Asking for credits either@@ -759,23 +1085,64 @@ function LinkPaymentDialog({// Same currency only — the server refuses a cross-currency allocation// rather than inventing a rate, so offering one here would only be// offering an error.+ //+ // And only money with something left to give: a payment already linked+ // to this invoice, or spent in full on others, was offered here too, and+ // picking it could only fail.const candidates = useMemo(- () => (data?.items ?? []).filter((tx) => (tx.currency ?? currency) === currency),- [data, currency],+ () =>+ (data?.items ?? []).filter((tx) => {+ if ((tx.currency ?? currency) !== currency) return false+ const links = tx.invoice_links ?? []+ if (links.some((link) => link.invoice_id === invoiceId)) return false+ const used = links.reduce((sum, link) => sum + Number(link.amount), 0)+ return Math.abs(Number(tx.amount)) - used > 0.005+ }),+ [data, currency, invoiceId],)+ const selectedTx = candidates.find((tx) => tx.id === selected)+ const target = Number(settleTarget ?? balance)+ const applied = amount ? Number(amount) : Math.min(Number(balance), Math.abs(Number(selectedTx?.amount ?? 0)))+ const difference = selectedTx ? Math.round((target - applied) * 100) / 100 : 0++ // Linking and deducting are two requests. Once the first has landed+ // the invoice is already different, so if the second fails the dialog+ // still closes and refreshes: left open, "try again" would link the+ // same payment a second time.+ const linked = useRef(false)+ const close = () => {+ onOpenChange(false)+ setSelected('')+ setAmount('')+ setDifferenceKind('none')+ onLinked()+ }const mutation = useMutation({- mutationFn: () => invoicesApi.allocate(invoiceId, selected, amount || undefined),+ mutationFn: async () => {+ linked.current = false+ const after = await invoicesApi.allocate(invoiceId, selected, amount || undefined)+ linked.current = true+ if (differenceKind !== 'none' && difference > 0) {+ await invoicesApi.deduct(invoiceId, {+ kind: differenceKind,+ amount: difference.toFixed(2),+ transaction_id: selected,+ })+ }+ return after+ },onSuccess: () => {toast.success(t('invoices.linked'))- onOpenChange(false)- setSelected('')- setAmount('')- onLinked()+ close()},onError: (error) => {const key = invoiceErrorKey(error)toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ if (linked.current) {+ toast.success(t('invoices.linked'))+ close()+ }},})@@ -830,6 +1197,24 @@ function LinkPaymentDialog({<p className="text-[11px] text-muted-foreground">{t('invoices.field.amountHint')}</p></div>+ {selectedTx && difference > 0 && (+ <div className="rounded-lg border border-border bg-muted/30 px-3 py-2.5 space-y-2" data-testid="invoice-difference">+ <p className="text-sm font-medium">+ {t('invoices.deductions.differenceTitle', { difference: formatCurrency(difference, currency, locale) })}+ </p>+ <p className="text-[11px] text-muted-foreground">{t('invoices.deductions.differenceHint')}</p>+ <Select value={differenceKind} onValueChange={(v) => setDifferenceKind(v as DeductionKind | 'none')}>+ <SelectTrigger data-testid="invoice-difference-kind"><SelectValue /></SelectTrigger>+ <SelectContent>+ <SelectItem value="none">{t('invoices.deductions.differenceNone')}</SelectItem>+ {DEDUCTION_KINDS.map((k) => (+ <SelectItem key={k} value={k}>{t(`invoices.deductions.kind.${k}`)}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}+<DialogFooter><Button variant="outline" onClick={() => onOpenChange(false)}>{t('common.cancel')}@@ -886,6 +1271,11 @@ function EditDraftDialog({const [total, setTotal] = useState(invoice.total)const [dueDate, setDueDate] = useState(invoice.due_date)const [notes, setNotes] = useState(invoice.notes ?? '')+ const [installments, setInstallments] = useState<InstallmentInput[] | null>(() =>+ invoice.installments.length+ ? invoice.installments.map((row) => ({ due_date: row.due_date, amount: row.amount, label: row.label }))+ : null,+ )const [lines, setLines] = useState<InvoiceLineInput[]>(() =>invoice.lines.map((line) => ({description: line.description,@@ -901,6 +1291,9 @@ function EditDraftDialog({payee_id: payeeId || null,due_date: dueDate,notes: notes || null,+ // Always sent: the server takes an omitted key as "leave the+ // schedule alone" and an empty list as "clear it".+ installments: installments ?? [],// Lines are the source of truth once they exist: the server// recomputes the total from them and ignores what was typed.//@@ -976,8 +1369,9 @@ function EditDraftDialog({id="edit-due"data-testid="edit-due-input"type="date"- value={dueDate}+ value={installments ? installments[installments.length - 1]?.due_date ?? '' : dueDate}onChange={(e) => setDueDate(e.target.value)}+ disabled={installments !== null}/></div></div>@@ -989,6 +1383,15 @@ function EditDraftDialog({showTax={showTax}/>+ <InvoiceInstallmentsEditor+ value={installments}+ onChange={setInstallments}+ total={lines.length ? linesTotal(lines) : Number(total || 0)}+ currency={currency}+ firstDueDate={dueDate}+ minDate={invoice.issue_date}+ />+<div className="space-y-1.5"><Label htmlFor="edit-notes">{t('invoices.field.notes')}</Label><Input@@ -1006,7 +1409,7 @@ function EditDraftDialog({</Button><ButtononClick={() => mutation.mutate()}- disabled={mutation.isPending}+ disabled={mutation.isPending || (installments !== null && Math.abs(installmentsTotal(installments) - (lines.length ? linesTotal(lines) : Number(total || 0))) >= 0.005)}data-testid="edit-submit">{t('common.save')}diff --git a/frontend/src/pages/invoice-schedule-detail.test.tsx b/frontend/src/pages/invoice-schedule-detail.test.tsxindex 08bbd66d..70e79d1c 100644--- a/frontend/src/pages/invoice-schedule-detail.test.tsx+++ b/frontend/src/pages/invoice-schedule-detail.test.tsx@@ -130,6 +130,10 @@ function invoice(overrides: Partial<Invoice> = {}): Invoice {amount_paid: '3000.00',balance: '0.00',days_overdue: 0,+ amount_deducted: '0.00',+ next_due_date: null,+ installments: [],+ deductions: [],notes: null,internal_notes: null,custom_fields: null,diff --git a/frontend/src/pages/invoices.tsx b/frontend/src/pages/invoices.tsxindex 80e04d36..1885df5e 100644--- a/frontend/src/pages/invoices.tsx+++ b/frontend/src/pages/invoices.tsx@@ -41,6 +41,9 @@ import {import { PageHeader } from '@/components/page-header'import { SectionCard, Segmented, StateBadge, TH } from '@/components/invoice-ui'import { InvoiceLineEditor } from '@/components/invoice-line-editor'+import { InvoiceInstallmentsEditor } from '@/components/invoice-installments-editor'+import { displayDue, installmentsTotal } from '@/lib/installment-utils'+import { localToday } from '@/lib/invoice-schedule-utils'import { InvoiceLogoField } from '@/components/invoice-logo-field'import { CurrencySelect } from '@/components/currency-select'import { cn } from '@/lib/utils'@@ -57,6 +60,7 @@ import {linesTotal,} from '@/lib/invoice-utils'import type {+ InstallmentInput,Invoice,InvoiceDirection,InvoiceLineInput,@@ -480,8 +484,13 @@ export default function InvoicesPage() {</td><td className="py-3 hidden md:table-cell"><span className="text-xs text-muted-foreground tabular-nums">- {showDate(invoice.due_date)}+ {showDate(displayDue(invoice))}</span>+ {invoice.installments.length > 0 && (+ <span className="ml-1.5 text-[11px] text-muted-foreground/70" data-testid="invoice-row-installments">+ {t('invoices.installments.count', { count: invoice.installments.length })}+ </span>+ )}{invoice.days_overdue > 0 && (<span className="ml-1.5 text-[11px] font-medium text-rose-500">{t('invoices.daysLate', { count: invoice.days_overdue })}@@ -560,6 +569,10 @@ function CreateInvoiceDialog({const [notes, setNotes] = useState('')const [custom, setCustom] = useState<Record<string, string>>({})const [lines, setLines] = useState<InvoiceLineInput[]>([])+ // Null is the ordinary invoice: one due date. A list is a schedule.+ const [installments, setInstallments] = useState<InstallmentInput[] | null>(null)+ const grossTotal = lines.length ? linesTotal(lines) : Number(total || 0)+ const scheduleOff = installments !== null && Math.abs(installmentsTotal(installments) - grossTotal) >= 0.005const defs = customFieldDefs(settings?.template)const { user } = useAuth()@@ -581,6 +594,7 @@ function CreateInvoiceDialog({// recomputes the total from them and ignores what was typed....(lines.length ? { lines } : { total }),...(dueDate ? { due_date: dueDate } : {}),+ ...(installments ? { installments } : {}),currency: currencyCode,notes: notes || null,...(Object.keys(custom).length ? { custom_fields: custom } : {}),@@ -603,6 +617,7 @@ function CreateInvoiceDialog({setCurrencyCode(user?.preferences?.currency_display ?? 'USD')setCustom({})setLines([])+ setInstallments(null)onCreated(invoice)},onError: (error) => {@@ -691,16 +706,20 @@ function CreateInvoiceDialog({id="invoice-due"data-testid="invoice-due-input"type="date"- value={dueDate}+ value={installments ? installments[installments.length - 1]?.due_date ?? '' : dueDate}onChange={(e) => setDueDate(e.target.value)}+ // With a schedule, the due date is the last installment's.+ disabled={installments !== null}/><p className="text-[11px] text-muted-foreground">- {t(- direction === 'payable'- ? 'invoices.field.dueDateHintPayable'- : 'invoices.field.dueDateHint',- { days: settings?.default_payment_terms_days ?? 30 },- )}+ {installments+ ? t('invoices.installments.dueDerived')+ : t(+ direction === 'payable'+ ? 'invoices.field.dueDateHintPayable'+ : 'invoices.field.dueDateHint',+ { days: settings?.default_payment_terms_days ?? 30 },+ )}</p></div></div>@@ -728,6 +747,14 @@ function CreateInvoiceDialog({required={settings?.document_required ?? false}/>+ <InvoiceInstallmentsEditor+ value={installments}+ onChange={setInstallments}+ total={grossTotal}+ currency={currencyCode}+ firstDueDate={dueDate || localToday()}+ />+<div className="space-y-1.5"><Label htmlFor="invoice-notes">{t('invoices.field.notes')}</Label><Input@@ -759,7 +786,7 @@ function CreateInvoiceDialog({</Button><ButtononClick={() => mutation.mutate(false)}- disabled={(lines.length ? linesTotal(lines) <= 0 : !total) || mutation.isPending}+ disabled={(lines.length ? linesTotal(lines) <= 0 : !total) || scheduleOff || mutation.isPending}data-testid="invoice-create-submit">{t('common.create')}diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 5356366d..c124b244 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -1149,6 +1149,39 @@ export interface Product {invoice_count: number}+export interface InstallmentInput {+ due_date: string+ amount: string+ label?: string | null+}++export type InstallmentState = 'open' | 'partial' | 'paid' | 'overdue' | 'draft' | 'void' | 'uncollectible'++export interface InvoiceInstallment {+ id: string+ position: number+ label: string | null+ due_date: string+ amount: string+ /** Derived: how much of it the settled money covers, first-to-last. */+ settled: string+ state: InstallmentState+}++export type DeductionKind = 'withholding_tax' | 'gateway_fee' | 'fx_difference' | 'other'++/** Debt closed without money: tax withheld, a fee kept. Counts towards+ * settled, never towards received. */+export interface InvoiceDeduction {+ id: string+ kind: DeductionKind+ tax_kind: string | null+ amount: string+ note: string | null+ transaction_id: string | null+ deducted_at: string+}+export interface InvoiceAllocation {id: stringtransaction_id: string | null@@ -1218,8 +1251,12 @@ export interface Invoice {tax_total: stringtotal: stringamount_paid: string+ /** Settled without cash. Not part of `amount_paid`. */+ amount_deducted: stringbalance: stringdays_overdue: number+ /** The next date money is late after; null once nothing is owed. */+ next_due_date: string | nullnotes: string | nullinternal_notes: string | nullcustom_fields: Record<string, string> | null@@ -1245,6 +1282,8 @@ export interface Invoice {period_end: string | nulllines: InvoiceLine[]allocations: InvoiceAllocation[]+ installments: InvoiceInstallment[]+ deductions: InvoiceDeduction[]created_at: string}@@ -1429,6 +1468,8 @@ export interface InvoiceDocumentPayload {tax_total: stringtotal: stringamount_paid: string+ /** Settled without money arriving: tax withheld, a fee kept. */+ amount_deducted: stringbalance: stringissuer: InvoiceDocumentPartyclient: InvoiceDocumentParty@@ -1450,6 +1491,8 @@ export interface InvoiceDocumentPayload {* that file is the document and the page below is only a summary of* it — nothing here needs redrawing. */source_file: { id: string; filename: string; content_type: string } | null+ /** The dates the money is expected on, when more than one. */+ installments: { label: string | null; due_date: string; amount: string }[]}export interface IssuerTaxId {