Open-source personal finance manager. Self-hosted, privacy-first.
feat(invoices): receivables ledger, invoice document and PDF (#718)
Tássio Noronhabf3c6d3fcf4d
diff --git a/backend/alembic/versions/078_invoices.py b/backend/alembic/versions/078_invoices.pynew file mode 100644index 00000000..e1a09088--- /dev/null+++ b/backend/alembic/versions/078_invoices.py@@ -0,0 +1,246 @@+"""the invoicing ledger: invoices, lines, allocations and settings++Revision ID: 078+Revises: 077+Create Date: 2026-08-26++Four new tables, no change to any existing one. That is deliberate and+worth stating: the link between an invoice and the money that settles it+lives entirely in `invoice_allocations`, so `transactions` — the largest+and hottest table in every install — is not touched by this feature at+all. A foreign key there would also have been wrong on the merits: a+gateway payout is one bank credit settling many invoices, and a Pix-paid+invoice is one debt settled by several credits.++The status column holds only decisions a human took (`draft`, `open`,+`void`, `uncollectible`). Paid, partial and overdue are computed from+allocations and the due date at read time. Products that store `overdue`+need a nightly job to set it and compensating SQL to unset it when a due+date moves; there is nothing here for such a job to write.++Nothing in this migration is specific to a country. `document_type`+carries UNTDID's shape (invoice / credit note), `competence_date` is the+accrual date that Brazil calls competência, France fait générateur and+Germany requires on the invoice as Leistungsdatum, and the vocabulary+that fills any of it comes from the jurisdiction packs, never from DDL.++Downgrade drops all four tables. Safe by construction: nothing outside+them references them.++Numbering note: renumbered once already. This chains off `076`+(`payee_workspace_uniqueness`), which landed on `main` while this branch+was open. Any migration that lands before this one merges will need the+same two-line change plus a rename — nothing references the revision id+but the chain itself, which is why the CI check for it exists.+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "078"+down_revision: Union[str, None] = "077"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "invoices",+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("payee_id", postgresql.UUID(as_uuid=True), nullable=True),+ # UNTDID 1001: 380 invoice, 381 credit note. Only `invoice` is+ # accepted by the API today; the column exists now because adding+ # it later means backfilling every row in every self-hosted+ # install for a feature they were not using.+ sa.Column("document_type", sa.String(length=20), nullable=False, server_default="invoice"),+ # Which side of the ledger. Everything issued today is a+ # receivable; `payable` is here because supplier invoices are a+ # stated direction for this module, and adding the column later+ # means rewriting every row in every self-hosted install.+ sa.Column("direction", sa.String(length=20), nullable=False, server_default="receivable"),+ sa.Column("corrects_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("origin", sa.String(length=20), nullable=False, server_default="local"),+ sa.Column("external_source", sa.String(length=50), nullable=True),+ sa.Column("external_id", sa.String(length=255), nullable=True),+ sa.Column("number", sa.Integer(), nullable=True),+ sa.Column("series", sa.String(length=20), nullable=True),+ sa.Column("status", sa.String(length=20), nullable=False, server_default="draft"),+ sa.Column("issue_date", sa.Date(), nullable=False),+ sa.Column("due_date", sa.Date(), nullable=False),+ sa.Column("competence_date", sa.Date(), nullable=True),+ sa.Column("sent_at", sa.DateTime(timezone=True), nullable=True),+ sa.Column("currency", sa.String(length=3), nullable=False, server_default="USD"),+ sa.Column("subtotal", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),+ sa.Column("discount", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),+ sa.Column("tax_total", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),+ sa.Column("total", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),+ sa.Column("notes", sa.Text(), nullable=True),+ sa.Column("internal_notes", sa.Text(), nullable=True),+ sa.Column("snapshot", sa.JSON(), nullable=True),+ sa.Column("custom_fields", sa.JSON(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),+ # RESTRICT: deleting a client must never silently delete the+ # record of money they owed.+ sa.ForeignKeyConstraint(["payee_id"], ["payees.id"], ondelete="RESTRICT"),+ sa.ForeignKeyConstraint(["corrects_id"], ["invoices.id"], ondelete="SET NULL"),+ sa.PrimaryKeyConstraint("id"),+ sa.CheckConstraint(+ "status IN ('draft', 'open', 'void', 'uncollectible')", name="ck_invoices_status"+ ),+ sa.CheckConstraint(+ "document_type IN ('invoice', 'credit_note')", name="ck_invoices_document_type"+ ),+ sa.CheckConstraint(+ "direction IN ('receivable', 'payable')", name="ck_invoices_direction"+ ),+ sa.CheckConstraint("origin IN ('local', 'imported')", name="ck_invoices_origin"),+ # A draft has no number, and anything we issued has one. In the+ # database because the alternative is trusting every future code+ # path to remember. Imported rows are outside it: their identity+ # came with them, and a source that numbers nothing leaves the+ # column null rather than borrowing from our sequence.+ sa.CheckConstraint(+ "(status = 'draft' AND number IS NULL)"+ " OR (status <> 'draft' AND origin = 'local' AND number IS NOT NULL)"+ " OR origin = 'imported'",+ name="ck_invoices_number_matches_status",+ ),+ sa.CheckConstraint("total >= 0", name="ck_invoices_total_non_negative"),+ # Unique when present: SQL treats NULLs as distinct, so drafts+ # (which carry no number) are exempt for free.+ sa.UniqueConstraint(+ "workspace_id", "series", "number", name="uq_invoices_workspace_series_number"+ ),+ # Two syncs of the same external document converge on one row.+ sa.UniqueConstraint(+ "workspace_id", "external_source", "external_id", name="uq_invoices_workspace_external"+ ),+ )+ op.create_index("ix_invoices_workspace_id", "invoices", ["workspace_id"])+ op.create_index("ix_invoices_payee_id", "invoices", ["payee_id"])+ op.create_index("ix_invoices_status", "invoices", ["status"])+ # The read path: one workspace, one side of the ledger, open rows, by+ # due date. Every list and every aging bucket starts here.+ op.create_index(+ "ix_invoices_workspace_direction_status_due",+ "invoices",+ ["workspace_id", "direction", "status", "due_date"],+ )++ op.create_table(+ "invoice_lines",+ 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("description", sa.String(length=500), nullable=False),+ sa.Column("quantity", sa.Numeric(precision=15, scale=4), nullable=False, server_default="1"),+ sa.Column("unit_price", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),+ # A rate, not an amount, and nullable: most workspaces under the+ # tracking preset never fill it in.+ sa.Column("tax_rate", sa.Numeric(precision=7, scale=4), nullable=True),+ sa.Column("total", sa.Numeric(precision=15, scale=2), nullable=False, server_default="0"),+ sa.Column("position", sa.Integer(), nullable=False, server_default="0"),+ sa.ForeignKeyConstraint(["invoice_id"], ["invoices.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ sa.CheckConstraint("quantity >= 0", name="ck_invoice_lines_quantity_non_negative"),+ )+ op.create_index("ix_invoice_lines_invoice", "invoice_lines", ["invoice_id"])+ op.create_index("ix_invoice_lines_workspace_id", "invoice_lines", ["workspace_id"])++ op.create_table(+ "invoice_allocations",+ 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("transaction_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("credit_note_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("amount", sa.Numeric(precision=15, scale=2), nullable=False),+ # How the link came to exist: `manual`, or the id of the matching+ # strategy that produced the row. Sized for a strategy id rather+ # than an enum value, and left without a CHECK on purpose — those+ # ids come from a policy document the user will edit, so+ # constraining them here would mean a migration per strategy.+ sa.Column("method", sa.String(length=60), nullable=False, server_default="manual"),+ sa.Column("allocated_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(["invoice_id"], ["invoices.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ # CASCADE here and nowhere else in this migration: if the+ # transaction is gone the money it represented is gone, and a+ # link pointing at nothing would overstate what was received.+ sa.ForeignKeyConstraint(["transaction_id"], ["transactions.id"], ondelete="CASCADE"),+ sa.ForeignKeyConstraint(["credit_note_id"], ["invoices.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ sa.CheckConstraint("amount > 0", name="ck_invoice_allocations_amount_positive"),+ # Exactly one source. A row settling from both a transaction and+ # a credit note is not richer, it is ambiguous.+ sa.CheckConstraint(+ "(transaction_id IS NOT NULL AND credit_note_id IS NULL)"+ " OR (transaction_id IS NULL AND credit_note_id IS NOT NULL)",+ name="ck_invoice_allocations_one_source",+ ),+ # The same transaction is never applied twice to the same+ # invoice. Two genuine partial payments are two transactions.+ sa.UniqueConstraint(+ "invoice_id", "transaction_id", name="uq_invoice_allocation_transaction"+ ),+ )+ op.create_index("ix_invoice_allocations_invoice", "invoice_allocations", ["invoice_id"])+ op.create_index("ix_invoice_allocations_transaction", "invoice_allocations", ["transaction_id"])+ op.create_index("ix_invoice_allocations_workspace_id", "invoice_allocations", ["workspace_id"])++ op.create_table(+ "invoice_settings",+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),+ # `tracking` (the document was issued elsewhere, or there is+ # none) vs `document` (the invoice is the deliverable). A+ # starting point that fills the next three fields, each+ # overridable afterwards — never a mode, and never a branch on+ # the UI language.+ sa.Column("preset", sa.String(length=20), nullable=False, server_default="tracking"),+ sa.Column("document_required", sa.Boolean(), nullable=False, server_default="false"),+ sa.Column("initial_state", sa.String(length=10), nullable=False, server_default="open"),+ sa.Column("tax_fields", sa.String(length=10), nullable=False, server_default="hidden"),+ sa.Column("default_payment_terms_days", sa.Integer(), nullable=False, server_default="30"),+ sa.Column("number_prefix", sa.String(length=20), nullable=True),+ sa.Column("series", sa.String(length=20), nullable=True),+ # Consumed at issuance and never rolled back — not even when an+ # invoice is voided a second later. A reused number would put two+ # documents under one identifier.+ sa.Column("next_number", sa.Integer(), nullable=False, server_default="1"),+ sa.Column("logo_url", sa.String(length=1000), nullable=True),+ sa.Column("issuer_display_name", sa.String(length=255), nullable=True),+ sa.Column("footer_note", sa.Text(), nullable=True),+ # Labels and custom-field definitions in one document. Peers ship+ # a column per label and pay a migration every time a label is+ # added; a workspace defining a PO-number field here pays none.+ sa.Column("template", sa.JSON(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ sa.UniqueConstraint("workspace_id", name="uq_invoice_settings_workspace"),+ sa.CheckConstraint("preset IN ('tracking', 'document')", name="ck_invoice_settings_preset"),+ sa.CheckConstraint(+ "initial_state IN ('draft', 'open')", name="ck_invoice_settings_initial_state"+ ),+ sa.CheckConstraint(+ "tax_fields IN ('hidden', 'optional', 'required')", name="ck_invoice_settings_tax_fields"+ ),+ )+ op.create_index("ix_invoice_settings_workspace_id", "invoice_settings", ["workspace_id"])+++def downgrade() -> None:+ op.drop_table("invoice_settings")+ op.drop_table("invoice_allocations")+ op.drop_table("invoice_lines")+ op.drop_table("invoices")diff --git a/backend/alembic/versions/079_invoice_document.py b/backend/alembic/versions/079_invoice_document.pynew file mode 100644index 00000000..1e68a73d--- /dev/null+++ b/backend/alembic/versions/079_invoice_document.py@@ -0,0 +1,88 @@+"""the invoice document: issuer fiscal identity, payment details, share links++Revision ID: 079+Revises: 078+Create Date: 2026-08-26++Three groups of change, all additive.++**The issuer side of the fiscal pack.** `workspace_tax_ids` mirrors+`payee_tax_ids` from `070` exactly — same closed `kind` vocabulary, same+named validators, same normalisation. Two small tables rather than one+with a polymorphic owner: the cardinality differs by orders of magnitude+(one row set per workspace against thousands of payees), and a+discriminator column would buy nothing but a filter on every query.++`workspaces.legal_name` and `workspaces.address` sit on the workspace+rather than in `invoice_settings` because they are the workspace+describing *itself*, not a preference about invoicing — fiscal documents+will want the same two fields, and a personal workspace simply leaves+them null forever, which is the expected end state and not an incomplete+migration.++**What the document needs to render.** `payment_details` is deliberately+free text: a Brazilian writes a Pix key, a German an IBAN and BIC, an+American a routing number. Structuring it would bake one country's shape+into the schema, which is exactly the rule this model refuses.+`accent_color` is the one visual knob worth having — a document that+carries the sender's colour reads as theirs.++**Delivery.** `share_token` is null until someone asks for a link, and+nulling it again revokes one. Unique so the public lookup is a single+indexed read, and long enough that guessing is not a strategy.++Downgrade drops all of it. Nothing outside these columns references them.+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "079"+down_revision: Union[str, None] = "078"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ # --- T10: the workspace's own fiscal identity -------------------------+ op.create_table(+ "workspace_tax_ids",+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),+ # A value from `fiscal.registry.TaxIdKind`. A string so a new kind is+ # a pull request rather than a migration, kept closed by validation+ # on the way in — the same trade `payee_tax_ids` makes.+ sa.Column("kind", sa.String(length=30), nullable=False),+ sa.Column("value", sa.String(length=60), nullable=False),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),+ sa.PrimaryKeyConstraint("id"),+ # One document per kind: a workspace has one CNPJ, not several.+ sa.UniqueConstraint("workspace_id", "kind", name="uq_workspace_tax_id_kind"),+ )+ op.create_index("ix_workspace_tax_ids_workspace_id", "workspace_tax_ids", ["workspace_id"])++ op.add_column("workspaces", sa.Column("legal_name", sa.String(length=255), nullable=True))+ op.add_column("workspaces", sa.Column("address", sa.String(length=500), nullable=True))++ # --- T7: what the rendered document carries ---------------------------+ op.add_column("invoice_settings", sa.Column("payment_details", sa.Text(), nullable=True))+ op.add_column(+ "invoice_settings", sa.Column("accent_color", sa.String(length=9), nullable=True)+ )++ op.add_column("invoices", sa.Column("share_token", sa.String(length=64), nullable=True))+ op.create_unique_constraint("uq_invoices_share_token", "invoices", ["share_token"])+++def downgrade() -> None:+ op.drop_constraint("uq_invoices_share_token", "invoices", type_="unique")+ op.drop_column("invoices", "share_token")+ op.drop_column("invoice_settings", "accent_color")+ op.drop_column("invoice_settings", "payment_details")+ op.drop_column("workspaces", "address")+ op.drop_column("workspaces", "legal_name")+ op.drop_index("ix_workspace_tax_ids_workspace_id", table_name="workspace_tax_ids")+ op.drop_table("workspace_tax_ids")diff --git a/backend/alembic/versions/080_invoice_attachments.py b/backend/alembic/versions/080_invoice_attachments.pynew file mode 100644index 00000000..b9bacabd--- /dev/null+++ b/backend/alembic/versions/080_invoice_attachments.py@@ -0,0 +1,135 @@+"""invoice attachments, and a name for an imported document++Two changes that belong together, because both say the same thing: an+invoice gathers paper it did not necessarily write.++ - `invoice_attachments` holds the files, each with the role it plays+ and at most one marked as *the* document.+ - `invoices.external_number` holds the name an imported document+ arrived with. It replaces the earlier attempt to store it in our own+ integer column, which could not hold `2026/A/0031` and quietly spent+ a number from a sequence that is supposed to be ours alone.++Revision ID: 080+Revises: 079+"""+from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects import postgresql++revision = "080"+down_revision = "079"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column(+ "invoices",+ sa.Column("external_number", sa.String(length=60), nullable=True),+ )++ # Anything imported that took a number from our sequence gets its name+ # back and gives the number up. Reversing it in SQL rather than in a+ # later code path is what keeps installs that ran the previous+ # revision from carrying a document renamed into our numbering.+ op.execute(+ """+ UPDATE invoices+ SET external_number = COALESCE(series, '') || number::text,+ number = NULL,+ series = NULL+ WHERE origin = 'imported'+ AND number IS NOT NULL+ """+ )++ op.drop_constraint("ck_invoices_number_matches_status", "invoices", type_="check")+ op.create_check_constraint(+ "ck_invoices_number_matches_status",+ "invoices",+ "(origin = 'imported' AND number IS NULL)"+ " OR (status = 'draft' AND number IS NULL)"+ " OR (status <> 'draft' AND number IS NOT NULL)",+ )++ op.create_table(+ "invoice_attachments",+ 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("user_id", postgresql.UUID(as_uuid=True), nullable=True),+ sa.Column("kind", sa.String(length=20), server_default="other", nullable=False),+ sa.Column("is_primary", sa.Boolean(), server_default="false", nullable=False),+ sa.Column("document_number", sa.String(length=120), nullable=True),+ sa.Column("issued_at", sa.Date(), nullable=True),+ sa.Column("filename", sa.String(length=255), nullable=False),+ sa.Column("storage_key", sa.String(length=500), nullable=False),+ sa.Column("content_type", sa.String(length=100), nullable=False),+ sa.Column("size", sa.BigInteger(), 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.ForeignKeyConstraint(["user_id"], ["users.id"]),+ sa.PrimaryKeyConstraint("id"),+ sa.CheckConstraint(+ "kind IN ('bill', 'fiscal', 'receipt', 'contract', 'other')",+ name="ck_invoice_attachments_kind",+ ),+ )+ op.create_index(+ "ix_invoice_attachments_invoice", "invoice_attachments", ["invoice_id"]+ )+ op.create_index(+ "ix_invoice_attachments_workspace_id", "invoice_attachments", ["workspace_id"]+ )+ # "Unique among the true ones": one file per invoice may be the+ # document, and any number of files may not be.+ op.create_index(+ "uq_invoice_attachments_primary",+ "invoice_attachments",+ ["invoice_id"],+ unique=True,+ postgresql_where=sa.text("is_primary"),+ )+++def downgrade() -> None:+ """Gives back what `upgrade` took, as far as it can be given back.++ `upgrade` folded `series || number` into one text column and cleared+ both. Splitting that back apart is guesswork in general — a source+ that numbered a document `2026/A/0031` leaves nothing to say where+ the series ended — so only the unambiguous case is restored: a value+ that is digits and nothing else goes back into `number`.++ Anything else stays in `external_number` until the column is dropped+ on the next statement, and is then gone. On a self-hosted install+ that is the only copy of the name the source gave the document, which+ is why it is said here rather than discovered afterwards.+ """+ op.drop_index("uq_invoice_attachments_primary", table_name="invoice_attachments")+ op.drop_index("ix_invoice_attachments_workspace_id", table_name="invoice_attachments")+ op.drop_index("ix_invoice_attachments_invoice", table_name="invoice_attachments")+ op.drop_table("invoice_attachments")++ op.drop_constraint("ck_invoices_number_matches_status", "invoices", type_="check")+ op.create_check_constraint(+ "ck_invoices_number_matches_status",+ "invoices",+ "(status = 'draft' AND number IS NULL)"+ " OR (status <> 'draft' AND origin = 'local' AND number IS NOT NULL)"+ " OR origin = 'imported'",+ )++ # The reversible half: a purely numeric name is the same value the+ # column held before, so it goes home.+ op.execute(+ """+ UPDATE invoices+ SET number = external_number::integer+ WHERE origin = 'imported'+ AND external_number ~ '^[0-9]+$'+ """+ )+ op.drop_column("invoices", "external_number")diff --git a/backend/alembic/versions/081_invoice_attachment_source.py b/backend/alembic/versions/081_invoice_attachment_source.pynew file mode 100644index 00000000..c36cf8fa--- /dev/null+++ b/backend/alembic/versions/081_invoice_attachment_source.py@@ -0,0 +1,44 @@+"""where each filed document came from++An invoice is assembled from several systems: the bill from a payment+provider, the fiscal document from a government portal, a receipt+forwarded by email. Without recording which produced which, the folder is+a pile of files with no author and no way to recognise one already+collected when that system syncs again.++Revision ID: 081+Revises: 080+"""+from alembic import op+import sqlalchemy as sa++revision = "081"+down_revision = "080"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column(+ "invoice_attachments", sa.Column("source", sa.String(length=50), nullable=True)+ )+ op.add_column(+ "invoice_attachments",+ sa.Column("external_id", sa.String(length=255), nullable=True),+ )+ # Partial: a null external id means "this system does not name its+ # files", not a value two rows can collide on, and a hand-uploaded+ # file has no source at all.+ op.create_index(+ "uq_invoice_attachments_external",+ "invoice_attachments",+ ["workspace_id", "source", "external_id"],+ unique=True,+ postgresql_where=sa.text("source IS NOT NULL AND external_id IS NOT NULL"),+ )+++def downgrade() -> None:+ op.drop_index("uq_invoice_attachments_external", table_name="invoice_attachments")+ op.drop_column("invoice_attachments", "external_id")+ op.drop_column("invoice_attachments", "source")diff --git a/backend/alembic/versions/082_invoice_logo_upload.py b/backend/alembic/versions/082_invoice_logo_upload.pynew file mode 100644index 00000000..1883d18f--- /dev/null+++ b/backend/alembic/versions/082_invoice_logo_upload.py@@ -0,0 +1,37 @@+"""the logo becomes a file this workspace owns++A URL fetched the mark from a third party every time a document was+drawn, and on a self-hosted install that is a request out of the building+for an image the user already has. It is uploaded now, and the column+holds the id the storage key is derived from.++`logo_url` is dropped rather than migrated: it was introduced in this+same series and has never been in a release, so nothing in the world+holds one.++Revision ID: 082+Revises: 081+"""+from alembic import op+import sqlalchemy as sa+from sqlalchemy.dialects import postgresql++revision = "082"+down_revision = "081"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column(+ "invoice_settings",+ sa.Column("logo_id", postgresql.UUID(as_uuid=True), nullable=True),+ )+ op.drop_column("invoice_settings", "logo_url")+++def downgrade() -> None:+ op.add_column(+ "invoice_settings", sa.Column("logo_url", sa.String(length=1000), nullable=True)+ )+ op.drop_column("invoice_settings", "logo_id")diff --git a/backend/alembic/versions/083_invoice_line_unit.py b/backend/alembic/versions/083_invoice_line_unit.pynew file mode 100644index 00000000..cc669a60--- /dev/null+++ b/backend/alembic/versions/083_invoice_line_unit.py@@ -0,0 +1,28 @@+"""what a line's quantity counts++"12 hours x 180.00" is a different claim from "12 x 180.00", and only the+first one can be checked by the person paying it.++Free text rather than a list: a translator bills by word, a photographer+by image, a freight company by tonne-kilometre. An enum here would be a+guess about somebody else's trade, and a migration every time the guess+turned out to be short.++Revision ID: 083+Revises: 082+"""+from alembic import op+import sqlalchemy as sa++revision = "083"+down_revision = "082"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.add_column("invoice_lines", sa.Column("unit", sa.String(length=20), nullable=True))+++def downgrade() -> None:+ op.drop_column("invoice_lines", "unit")diff --git a/backend/app/api/invoice_attachments.py b/backend/app/api/invoice_attachments.pynew file mode 100644index 00000000..7828beff--- /dev/null+++ b/backend/app/api/invoice_attachments.py@@ -0,0 +1,126 @@+"""The files gathered under an invoice.++Kept in its own router rather than folded into `invoices.py` because it+is the transaction-attachment shape verbatim — multipart in, bytes out —+and mixing that with a JSON resource makes both harder to read.+"""+import uuid+from datetime import date as _date+from typing import Optional++from fastapi import APIRouter, Depends, Form, HTTPException, UploadFile, status+from fastapi.responses import Response+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.database import get_async_session+from app.core.module_gate import require_module, require_module_write+from app.services.module_service import ModuleId+from app.core.workspace_context import WorkspaceContext+from app.schemas.invoice import InvoiceAttachmentRead, InvoiceAttachmentUpdate+from app.services import invoice_attachment_service++router = APIRouter(+ prefix="/api/invoices/{invoice_id}/attachments", tags=["invoices"]+)++_read = require_module(ModuleId.INVOICES)+_write = require_module_write(ModuleId.INVOICES)++[email protected]("", response_model=InvoiceAttachmentRead, status_code=status.HTTP_201_CREATED)+async def upload_attachment(+ invoice_id: uuid.UUID,+ file: UploadFile,+ kind: str = Form("other"),+ #: Which system produced the file. Omitted when a person uploads one.+ source: Optional[str] = Form(None),+ external_id: Optional[str] = Form(None),+ document_number: Optional[str] = Form(None),+ issued_at: Optional[_date] = Form(None),+ is_primary: Optional[bool] = Form(None),+ ctx: WorkspaceContext = Depends(_write),+ session: AsyncSession = Depends(get_async_session),+):+ try:+ return await invoice_attachment_service.upload(+ session=session,+ workspace_id=ctx.workspace.id,+ user_id=ctx.user_id,+ invoice_id=invoice_id,+ filename=file.filename or "unnamed",+ content_type=file.content_type or "application/octet-stream",+ data=await file.read(),+ kind=kind,+ source=source,+ external_id=external_id,+ document_number=document_number,+ issued_at=issued_at,+ is_primary=is_primary,+ )+ except LookupError:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invoice not found")+ except ValueError as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))++[email protected]("", response_model=list[InvoiceAttachmentRead])+async def list_attachments(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(_read),+ session: AsyncSession = Depends(get_async_session),+):+ try:+ return await invoice_attachment_service.listing(session, ctx.workspace.id, invoice_id)+ except LookupError:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invoice not found")++[email protected]("/{attachment_id}")+async def download_attachment(+ invoice_id: uuid.UUID,+ attachment_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(_read),+ session: AsyncSession = Depends(get_async_session),+):+ try:+ attachment, data = await invoice_attachment_service.download(+ session, attachment_id, ctx.workspace.id+ )+ except LookupError:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")+ return Response(+ content=data,+ media_type=attachment.content_type,+ headers={"Content-Disposition": f'inline; filename="{attachment.filename}"'},+ )++[email protected]("/{attachment_id}", response_model=InvoiceAttachmentRead)+async def update_attachment(+ invoice_id: uuid.UUID,+ attachment_id: uuid.UUID,+ body: InvoiceAttachmentUpdate,+ ctx: WorkspaceContext = Depends(_write),+ session: AsyncSession = Depends(get_async_session),+):+ try:+ return await invoice_attachment_service.update(+ session, attachment_id, ctx.workspace.id, body.model_dump(exclude_unset=True)+ )+ except LookupError:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")+ except ValueError as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))++[email protected]("/{attachment_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_attachment(+ invoice_id: uuid.UUID,+ attachment_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(_write),+ session: AsyncSession = Depends(get_async_session),+):+ try:+ await invoice_attachment_service.delete(session, attachment_id, ctx.workspace.id)+ except LookupError:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Attachment not found")diff --git a/backend/app/api/invoices.py b/backend/app/api/invoices.pynew file mode 100644index 00000000..e73d86ab--- /dev/null+++ b/backend/app/api/invoices.py@@ -0,0 +1,557 @@+"""Invoicing ledger routes.++Every route is gated twice: `require_module(INVOICES)` asks whether this+workspace has the module at all, and the write variant additionally asks+whether the member's role may write. A personal workspace gets a 404+from all of them — the same answer it would get for a URL that does not+exist, which is the honest thing to say to a client that should not know+the feature is there.+"""+import uuid+from datetime import date as _date+from typing import Optional++from fastapi import APIRouter, Depends, HTTPException, Query, Response, UploadFile, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.database import get_async_session+from app.models.workspace import Workspace+from app.core.module_gate import require_module, require_module_write+from app.core.workspace_context import WorkspaceContext+from app.schemas.invoice import (+ AllocationCreate,+ InvoiceCreate,+ InvoiceDirection,+ InvoiceFacets,+ InvoiceRead,+ InvoiceSettingsRead,+ InvoiceSettingsUpdate,+ InvoiceSummary,+ InvoiceUpdate,+ IssuerProfileRead,+ IssuerProfileUpdate,+ ShareLinkRead,+)+from app.services import (+ invoice_attachment_service,+ invoice_logo_service,+ invoice_document,+ invoice_pdf,+ invoice_service,+)+from app.services.invoice_service import InvoiceError+from app.services.module_service import ModuleId++router = APIRouter(prefix="/api/invoices", tags=["invoices"])++read_ctx = require_module(ModuleId.INVOICES)+write_ctx = require_module_write(ModuleId.INVOICES)++#: Every list, count and total is about one side of the ledger. The+#: parameter defaults rather than being required so today's callers keep+#: working unchanged, and so a caller that forgets it gets receivables —+#: the side that exists — instead of both mixed together.+DirectionParam = Query("receivable", description="Which side of the ledger to read")+++def _serialize(invoice, today: Optional[_date] = None) -> InvoiceRead:+ """Attach the derived answers to the stored row.++ Computed here, once, from the single definition in the service — so+ the API can expose `state`, `balance` and `days_overdue` without any+ of them ever being written to a column that could drift.+ """+ 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.balance = invoice_service.balance(invoice)+ payload.days_overdue = invoice_service.days_overdue(invoice, today)+ return payload+++async def _load(session: AsyncSession, invoice_id: uuid.UUID, workspace_id: uuid.UUID):+ invoice = await invoice_service.get_invoice(session, invoice_id, workspace_id)+ if invoice is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Invoice not found")+ return invoice+++def _http(error: InvoiceError) -> HTTPException:+ """Map a ledger rule to a response the frontend can translate."""+ return HTTPException(+ status_code=error.status_code,+ detail={"code": error.code, "message": error.message},+ )+++# ---------------------------------------------------------------------------+# Settings — before /{invoice_id} so the literal path wins the match+# ---------------------------------------------------------------------------[email protected]("/settings", response_model=InvoiceSettingsRead)+async def read_settings(+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ return await invoice_service.get_settings(session, ctx.workspace.id)++[email protected]("/settings", response_model=InvoiceSettingsRead)+async def write_settings(+ payload: InvoiceSettingsUpdate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ settings = await invoice_service.update_settings(+ session, ctx.workspace.id, payload.model_dump(exclude_unset=True)+ )+ await session.commit()+ return settings++[email protected]("/facets", response_model=InvoiceFacets)+async def read_facets(+ year: Optional[int] = Query(None, ge=1970, le=2200),+ direction: InvoiceDirection = DirectionParam,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """Years that have invoices, and how many are in each state.++ One call for the whole filter bar. The counts use the same derived+ state the list does, so a chip reading 3 opens a list of exactly 3.+ """+ return await invoice_service.facets(session, ctx.workspace.id, year, direction)++[email protected]("/summary", response_model=InvoiceSummary)+async def read_summary(+ direction: InvoiceDirection = DirectionParam,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ data = await invoice_service.aging_summary(+ session, ctx.workspace.id, direction=direction+ )+ data["upcoming"] = [_serialize(inv) for inv in data["upcoming"]]+ return data+++# ---------------------------------------------------------------------------+# Issuer identity — the workspace describing itself (T10)+# ---------------------------------------------------------------------------[email protected]("/issuer", response_model=IssuerProfileRead)+async def read_issuer(+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ tax_ids = await invoice_service.get_issuer_tax_ids(session, ctx.workspace.id)+ return IssuerProfileRead(+ legal_name=ctx.workspace.legal_name,+ address=ctx.workspace.address,+ tax_jurisdiction=ctx.workspace.tax_jurisdiction,+ tax_ids=tax_ids,+ )++[email protected]("/issuer", response_model=IssuerProfileRead)+async def write_issuer(+ payload: IssuerProfileUpdate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ # The context's workspace is already attached to this session; fetching+ # it again would only add a query and a `| None` to reason about.+ workspace = ctx.workspace+ data = payload.model_dump(exclude_unset=True)+ # Blankable on purpose: clearing a legal name is a thing people do.+ for field in ("legal_name", "address"):+ if field in data:+ setattr(workspace, field, data[field])+ tax_ids = None+ if data.get("tax_ids") is not None:+ try:+ tax_ids = await invoice_service.set_issuer_tax_ids(+ session, ctx.workspace.id, [dict(t) for t in data["tax_ids"]]+ )+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ if tax_ids is None:+ tax_ids = await invoice_service.get_issuer_tax_ids(session, ctx.workspace.id)+ return IssuerProfileRead(+ legal_name=workspace.legal_name,+ address=workspace.address,+ tax_jurisdiction=workspace.tax_jurisdiction,+ tax_ids=tax_ids,+ )+++# ---------------------------------------------------------------------------+# Invoices+# ---------------------------------------------------------------------------[email protected]("", response_model=list[InvoiceRead])+async def list_invoices(+ state: Optional[str] = Query(None, description="Filter by derived state"),+ # Scopes the list only. The summary stays global on purpose: an+ # unpaid invoice from two years ago is still owed today, so+ # "outstanding" has no year.+ year: Optional[int] = Query(None, ge=1970, le=2200, description="Filter by issue year"),+ direction: InvoiceDirection = DirectionParam,+ payee_id: Optional[uuid.UUID] = Query(None),+ q: Optional[str] = Query(None),+ limit: int = Query(100, ge=1, le=500),+ offset: int = Query(0, ge=0),+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ invoices = await invoice_service.list_invoices(+ session, ctx.workspace.id, state=state, year=year, direction=direction,+ payee_id=payee_id, q=q, limit=limit, offset=offset,+ )+ return [_serialize(inv) for inv in invoices]++[email protected]("", response_model=InvoiceRead, status_code=status.HTTP_201_CREATED)+async def create_invoice(+ payload: InvoiceCreate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ data = payload.model_dump(exclude_unset=True)+ if data.get("lines") is not None:+ data["lines"] = [dict(line) for line in data["lines"]]+ try:+ invoice = await invoice_service.create_invoice(+ session, ctx.workspace.id, ctx.user_id, data+ )+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ invoice = await _load(session, invoice.id, ctx.workspace.id)+ return _serialize(invoice)++[email protected]("/{invoice_id}", response_model=InvoiceRead)+async def get_invoice(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}", response_model=InvoiceRead)+async def update_invoice(+ invoice_id: uuid.UUID,+ payload: InvoiceUpdate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ data = payload.model_dump(exclude_unset=True)+ if data.get("lines") is not None:+ data["lines"] = [dict(line) for line in data["lines"]]+ try:+ invoice = await invoice_service.update_invoice(session, invoice, data)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_invoice(+ invoice_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.delete_invoice(session, invoice)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+++# ---------------------------------------------------------------------------+# The decisions. Each is its own route, because a status that changed+# always has a reason, and a PATCH of a string never records one.+# ---------------------------------------------------------------------------[email protected]("/{invoice_id}/issue", response_model=InvoiceRead)+async def issue_invoice(+ invoice_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.issue_invoice(session, invoice)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}/void", response_model=InvoiceRead)+async def void_invoice(+ invoice_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.void_invoice(session, invoice)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}/uncollectible", response_model=InvoiceRead)+async def write_off_invoice(+ invoice_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.mark_uncollectible(session, invoice)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}/reopen", response_model=InvoiceRead)+async def reopen_invoice(+ invoice_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.reopen_invoice(session, invoice)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))+++# ---------------------------------------------------------------------------+# Allocations — money bound to debt+# ---------------------------------------------------------------------------[email protected]("/{invoice_id}/allocations", response_model=InvoiceRead, status_code=status.HTTP_201_CREATED)+async def create_allocation(+ invoice_id: uuid.UUID,+ payload: AllocationCreate,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ try:+ await invoice_service.allocate(session, invoice, payload.transaction_id, payload.amount)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))++[email protected]("/{invoice_id}/allocations/{allocation_id}", response_model=InvoiceRead)+async def remove_allocation(+ invoice_id: uuid.UUID,+ allocation_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.unallocate(session, invoice, allocation_id)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return _serialize(await _load(session, invoice_id, ctx.workspace.id))+++# ---------------------------------------------------------------------------+# The rendered document+# ---------------------------------------------------------------------------+async def _document(session: AsyncSession, invoice, workspace: Workspace):+ settings = await invoice_service.get_settings(session, workspace.id)+ return await invoice_document.build_document(session, invoice, settings, workspace)++[email protected]("/{invoice_id}/document")+async def read_document(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """The invoice as a document, resolved.++ The same structure the PDF renderer consumes, so the preview on+ screen and the file the client receives cannot disagree.+ """+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ document = await _document(session, invoice, ctx.workspace)+ payload = invoice_document.document_payload(document)+ # The URL is built by whoever serves the document: this surface is+ # behind a session, the share page is behind a token, and the+ # resolver knows about neither.+ payload["logo_url"] = (+ f"/api/invoices/logo/{payload['logo_id']}" if payload.get("logo_id") else None+ )++ # If a real document was filed, say so. The resolved page is still+ # returned — it is the summary the screen shows around the file — but+ # the reader now knows a page exists that nobody has to redraw.+ primary = await invoice_attachment_service.primary_for(session, invoice.id)+ payload["source_file"] = (+ {+ "id": str(primary.id),+ "filename": primary.filename,+ "content_type": primary.content_type,+ }+ if primary is not None+ else None+ )+ return payload++[email protected]("/settings/logo", response_model=InvoiceSettingsRead)+async def upload_logo(+ file: UploadFile,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """Replace the workspace's mark with an uploaded image."""+ settings = await invoice_service.get_settings(session, ctx.workspace.id)+ try:+ await invoice_logo_service.store(+ session,+ settings,+ ctx.workspace.id,+ await file.read(),+ file.content_type or "application/octet-stream",+ )+ except ValueError as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))+ await session.commit()+ await session.refresh(settings)+ return settings++[email protected]("/settings/logo", response_model=InvoiceSettingsRead)+async def remove_logo(+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ settings = await invoice_service.get_settings(session, ctx.workspace.id)+ await invoice_logo_service.clear(session, settings)+ await session.commit()+ await session.refresh(settings)+ return settings++[email protected]("/logo/{logo_id}")+async def read_logo(+ logo_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ """One logo by id.++ By id rather than "the current one" because a document issued under+ an older mark froze that id, and asking for the current logo would+ repaint it.+ """+ data = await invoice_logo_service.read(ctx.workspace.id, logo_id)+ if data is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Logo not found")+ return Response(+ content=data,+ media_type="image/png",+ # Immutable: an id names one file forever, so a client that has+ # it never needs to ask again.+ headers={"Cache-Control": "private, max-age=31536000, immutable"},+ )++[email protected]("/{invoice_id}/pdf")+async def download_pdf(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(read_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ invoice = await _load(session, invoice_id, ctx.workspace.id)++ # When a real document was filed, that file is the answer. Rendering+ # our own page over the top of one we were handed produces something+ # that looks official and is not — and on a supplier's bill it would+ # be a page nobody issued.+ primary = await invoice_attachment_service.primary_for(session, invoice.id)+ if primary is not None:+ data = await invoice_attachment_service.read_bytes(session, primary)+ return Response(+ content=data,+ media_type=primary.content_type,+ headers={+ "Content-Disposition": f'attachment; filename="{primary.filename}"'+ },+ )++ # Nothing filed and we did not write it: there is no document to hand+ # over. Rendering one would produce a page for a document somebody+ # else issued, which is the invention this module exists to stop.+ # Refused here as well as hidden in the UI, because a rule enforced+ # only in a button is a rule the next caller does not know about.+ if invoice.origin == "imported":+ raise _http(+ InvoiceError(+ "no_document_filed",+ "This document was issued elsewhere. Attach the file that was received.",+ status_code=status.HTTP_409_CONFLICT,+ )+ )++ document = await _document(session, invoice, ctx.workspace)+ # Loaded here rather than inside the renderer, which does no I/O on+ # purpose. Until now nothing passed it at all, so a workspace with a+ # logo saw it on screen and got a file without one.+ 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 'draft'}.pdf".replace("/", "-")+ return Response(+ content=pdf,+ media_type="application/pdf",+ headers={"Content-Disposition": f'attachment; filename="{filename}"'},+ )++[email protected]("/{invoice_id}/share", response_model=ShareLinkRead, status_code=status.HTTP_201_CREATED)+async def create_share_link(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ try:+ token = await invoice_service.create_share_token(session, invoice)+ except InvoiceError as exc:+ raise _http(exc)+ await session.commit()+ return ShareLinkRead(token=token, path=f"/i/{token}")++[email protected]("/{invoice_id}/share", status_code=status.HTTP_204_NO_CONTENT)+async def revoke_share_link(+ invoice_id: uuid.UUID,+ ctx: WorkspaceContext = Depends(write_ctx),+ session: AsyncSession = Depends(get_async_session),+):+ invoice = await _load(session, invoice_id, ctx.workspace.id)+ await invoice_service.revoke_share_token(session, invoice)+ await session.commit()diff --git a/backend/app/api/payees.py b/backend/app/api/payees.pyindex 00c6b629..ba3b42ae 100644--- a/backend/app/api/payees.py+++ b/backend/app/api/payees.py@@ -18,6 +18,32 @@ from app.services import payee_servicerouter = APIRouter(prefix="/api/payees", tags=["payees"])+def _payee_in_use(error: ValueError) -> HTTPException:+ """Turn "this counterparty is still referenced" into an answer.++ Invoices hold their payee under a RESTRICT foreign key on purpose:+ deleting a client must never silently delete the record of money they+ owed. Without this the constraint surfaces as a 500, which tells the+ user nothing and tells the operator that something crashed.++ 409 rather than 400: the request is well formed and the refusal is+ about the state of the data, which is exactly what Conflict means.+ """+ reason = str(error)+ if reason.startswith("payee_has_invoices:"):+ return HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail={+ "code": "payee_has_invoices",+ "count": int(reason.split(":", 1)[1] or 0),+ # The way out, named: merging keeps the history, which is+ # what someone deleting a duplicate actually wants.+ "message": "This client has invoices. Merge it into another client instead.",+ },+ )+ return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=reason)++@router.get("", response_model=list[PayeeRead])async def list_payees(q: Optional[str] = Query(None),@@ -99,7 +125,10 @@ async def delete_payee(ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):- deleted = await payee_service.delete_payee(session, payee_id, ctx.workspace.id)+ try:+ deleted = await payee_service.delete_payee(session, payee_id, ctx.workspace.id)+ except ValueError as exc:+ raise _payee_in_use(exc)if not deleted:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Payee not found")@@ -123,5 +152,10 @@ async def bulk_delete_payees(ctx: WorkspaceContext = Depends(current_writable_workspace),session: AsyncSession = Depends(get_async_session),):- deleted_count = await payee_service.bulk_delete_payees(session, ctx.workspace.id, data.ids)+ try:+ deleted_count = await payee_service.bulk_delete_payees(+ session, ctx.workspace.id, data.ids+ )+ except ValueError as exc:+ raise _payee_in_use(exc)return {"deleted": deleted_count}diff --git a/backend/app/api/public_invoices.py b/backend/app/api/public_invoices.pynew file mode 100644index 00000000..3cc3b0a1--- /dev/null+++ b/backend/app/api/public_invoices.py@@ -0,0 +1,108 @@+"""The shared invoice: one document, reachable by its link alone.++This is the only unauthenticated surface in the invoicing module, so the+rules it plays by are worth stating plainly:++ - **The token is the credential.** It is 32 random bytes, never derived+ from the invoice id, and it is the entire scope of the request. There+ is no workspace header, no session, and nothing to enumerate.+ - **It serves the document and only the document.** The response is the+ same resolved structure the owner sees on the invoice page — issuer,+ client, lines, totals. Internal notes, allocations, the payee record+ and every other workspace object stay behind the authenticated API.+ - **A revoked or voided invoice is indistinguishable from one that+ never existed.** Both answer 404, because "this used to be here" is+ itself information.++No rate limiting is added here beyond the app's own: the token is not+guessable, so there is nothing to brute-force at a rate that matters.+"""+import uuid++from fastapi import APIRouter, Depends, HTTPException, Response, status+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.database import get_async_session+from app.models.workspace import Workspace+from app.services import (+ invoice_document,+ invoice_logo_service,+ invoice_pdf,+ invoice_service,+)++router = APIRouter(prefix="/api/public/invoices", tags=["invoices"])+++async def _resolve(session: AsyncSession, token: str):+ invoice = await invoice_service.get_invoice_by_share_token(session, token)+ if invoice is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")+ workspace = await session.get(Workspace, invoice.workspace_id)+ if workspace is None:+ # Unreachable in practice — the invoice cascades with its+ # workspace — but a document with no issuer is not a document.+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")+ settings = await invoice_service.get_settings(session, invoice.workspace_id)+ return invoice, await invoice_document.build_document(+ session, invoice, settings, workspace+ )++[email protected]("/{token}")+async def read_shared_invoice(+ token: str, session: AsyncSession = Depends(get_async_session)+):+ _, document = await _resolve(session, token)+ payload = invoice_document.document_payload(document)+ # Reached through the token, like everything else here. The logo id+ # is dropped from the response: a client needs the picture, not the+ # workspace's internal handle for it.+ payload["logo_url"] = f"/api/public/invoices/{token}/logo" if payload.pop("logo_id", None) else None+ return payload++[email protected]("/{token}/logo")+async def read_shared_logo(+ token: str, session: AsyncSession = Depends(get_async_session)+):+ """The mark on the shared document.++ Scoped by the same token as everything else, and by the id frozen in+ the invoice's snapshot rather than the workspace's current logo — a+ document a client is holding does not change its letterhead because+ the issuer rebranded.+ """+ invoice, document = await _resolve(session, token)+ data = (+ await invoice_logo_service.read(invoice.workspace_id, uuid.UUID(document.logo_id))+ if document.logo_id+ else None+ )+ if data is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")+ return Response(+ content=data,+ media_type="image/png",+ headers={"Cache-Control": "public, max-age=31536000, immutable"},+ )++[email protected]("/{token}/pdf")+async def download_shared_pdf(+ token: str, session: AsyncSession = Depends(get_async_session)+):+ invoice, document = await _resolve(session, token)+ logo_bytes = (+ await invoice_logo_service.read(invoice.workspace_id, uuid.UUID(document.logo_id))+ if document.logo_id+ else None+ )+ filename = f"{document.number or 'invoice'}.pdf".replace("/", "-")+ return Response(+ content=invoice_pdf.render_pdf(document, logo_bytes),+ media_type="application/pdf",+ # `inline` rather than `attachment`: someone opening a link+ # expects to see the document, not to receive a download.+ headers={"Content-Disposition": f'inline; filename="{filename}"'},+ )diff --git a/backend/app/api/settings.py b/backend/app/api/settings.pyindex 6d1a6aca..8dc78e89 100644--- a/backend/app/api/settings.py+++ b/backend/app/api/settings.py@@ -14,4 +14,5 @@ async def get_attachment_settings():"allowed_extensions": allowed,"max_file_size_mb": settings.storage_max_file_size_mb,"max_attachments_per_transaction": settings.storage_max_attachments_per_transaction,+ "max_attachments_per_invoice": settings.storage_max_attachments_per_invoice,}diff --git a/backend/app/api/transactions.py b/backend/app/api/transactions.pyindex 2e0ef390..2ec97033 100644--- a/backend/app/api/transactions.py+++ b/backend/app/api/transactions.py@@ -24,6 +24,35 @@ from app.services.transaction_calendar_service import get_transaction_calendarrouter = APIRouter(prefix="/api/transactions", tags=["transactions"])+async def _attach_invoice_links(session, ctx, items: list) -> None:+ """Mark the rows on this page that settle an invoice.++ One query for the whole page rather than one per row: this is the+ hottest list in the product and an N+1 here would be felt.++ Skipped entirely unless the workspace has the invoicing module, so a+ personal workspace pays nothing — not a query, not a field on the+ response. The import is local for the same reason the check is: the+ transaction list must not grow a hard dependency on a module most+ workspaces never enable.+ """+ from app.services.module_service import ModuleId, resolve_modules++ if ModuleId.INVOICES.value not in resolve_modules(ctx.workspace):+ return++ from app.schemas.transaction import TransactionInvoiceLink+ from app.services.invoice_service import invoice_links_for_transactions++ links = await invoice_links_for_transactions(+ session, ctx.workspace.id, [item.id for item in items]+ )+ for item in items:+ item.invoice_links = [+ TransactionInvoiceLink(**link) for link in links.get(item.id, [])+ ]++def _tag_fx_fallback(tx: TransactionRead, primary_currency: str) -> TransactionRead:"""Set fx_fallback=True when a cross-currency tx isn't backed by a real rate.@@ -131,6 +160,7 @@ async def list_transactions()primary_currency = ctx.user.primary_currencyitems = [_tag_fx_fallback(TransactionRead.model_validate(tx, from_attributes=True), primary_currency) for tx in transactions]+ await _attach_invoice_links(session, ctx, items)summary_out = (TransactionsSummary(**summary, currency=primary_currency)if summary is not Nonediff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex ba6961c7..858503e7 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -75,6 +75,10 @@ class Settings(BaseSettings):storage_max_file_size_mb: int = 10storage_allowed_extensions: str = "jpg,jpeg,png,webp,gif,heic,pdf"storage_max_attachments_per_transaction: int = 10+ # An invoice gathers more paper than a transaction does: the bill, the+ # fiscal document, a receipt, the contract behind it, and a correction+ # of any of them.+ storage_max_attachments_per_invoice: int = 20# S3 Storage (for future use)storage_s3_bucket: str = ""diff --git a/backend/app/core/module_gate.py b/backend/app/core/module_gate.pynew file mode 100644index 00000000..157d5740--- /dev/null+++ b/backend/app/core/module_gate.py@@ -0,0 +1,55 @@+"""Refuse requests for a module this workspace does not have.++Module resolution started as a visibility rule — the nav hid what a+workspace did not need, and there was nothing behind the entries to+enforce. The invoicing ledger is the first module with its own data, so+hiding the link is no longer the whole answer: a personal workspace must+not be able to create an invoice by calling the API directly.++This is deliberately *not* a permission system. It answers "does this+workspace have this module", never "may this user write" — that stays+with `require_write` and the role on the membership. Both have to pass,+and they are asked separately because they are different questions.+"""+from collections.abc import Awaitable, Callable++from fastapi import Depends, HTTPException++from app.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)+from app.services.module_service import ModuleId, resolve_modules+++def _assert_enabled(ctx: WorkspaceContext, module: ModuleId) -> None:+ if module.value not in resolve_modules(ctx.workspace):+ # 404, not 403. A workspace without the module should not be+ # able to tell that the feature exists at all, and "forbidden"+ # would say it does.+ raise HTTPException(status_code=404, detail="Not found")+++def require_module(module: ModuleId) -> Callable[..., Awaitable[WorkspaceContext]]:+ """Read access to a module's routes."""++ async def dependency(+ ctx: WorkspaceContext = Depends(current_workspace),+ ) -> WorkspaceContext:+ _assert_enabled(ctx, module)+ return ctx++ return dependency+++def require_module_write(module: ModuleId) -> Callable[..., Awaitable[WorkspaceContext]]:+ """Write access: the workspace has the module *and* the role can write."""++ async def dependency(+ ctx: WorkspaceContext = Depends(current_writable_workspace),+ ) -> WorkspaceContext:+ _assert_enabled(ctx, module)+ return ctx++ return dependencydiff --git a/backend/app/core/workspace_autostamp.py b/backend/app/core/workspace_autostamp.pyindex 0b166b72..c75023d9 100644--- a/backend/app/core/workspace_autostamp.py+++ b/backend/app/core/workspace_autostamp.py@@ -31,6 +31,7 @@ from app.models.goal import Goalfrom app.models.group import Group, GroupMemberfrom app.models.group_settlement import GroupSettlementfrom app.models.import_log import ImportLog+from app.models.invoice import Invoice, InvoiceAllocation, InvoiceLine, InvoiceSettingsfrom app.models.payee import Payee, PayeeMapping, PayeeTaxIdfrom app.models.recurring_transaction import RecurringTransactionfrom app.models.rule import Rule@@ -55,6 +56,10 @@ _AUTOSTAMP_MODELS = (GroupMember,GroupSettlement,ImportLog,+ Invoice,+ InvoiceAllocation,+ InvoiceLine,+ InvoiceSettings,Payee,PayeeMapping,PayeeTaxId,diff --git a/backend/app/fiscal/registry.py b/backend/app/fiscal/registry.pyindex 9e82dda8..e569f4db 100644--- a/backend/app/fiscal/registry.py+++ b/backend/app/fiscal/registry.py@@ -265,6 +265,45 @@ def pack_for(jurisdiction: str | None) -> JurisdictionPack:return _packs().get(jurisdiction.strip().upper(), FALLBACK)+def apply_mask(value: str, mask: str | None) -> str:+ """A stored value formatted for a human to read.++ A mask is a template where `#` takes one digit and every other+ character is a literal, so `##.###.###/####-##` turns 14 digits into+ a CNPJ. A kind with no mask is returned untouched, which is what+ keeps a jurisdiction nobody has described from being mangled.++ This mirrors `applyMask` in `frontend/src/lib/tax-id.ts` deliberately:+ the frontend needs it to format *as the user types*, and the server+ needs it because a PDF has no frontend to ask. Same rule, and the+ tests on both sides assert the same CNPJ.+ """+ if not mask:+ return value+ digits = [c for c in value if c.isdigit()]+ # Only a value that fills the mask exactly is formatted. Too few digits+ # would render a half-masked document ("12.3" for "123"), and too many+ # would silently drop the tail — both worse than showing what is+ # stored. Values reaching here are normalised on write, so a mismatch+ # means an unmasked kind or data from before a pack changed.+ if len(digits) != mask.count("#"):+ return value+ out: list[str] = []+ index = 0+ for char in mask:+ if char == "#":+ out.append(digits[index])+ index += 1+ else:+ out.append(char)+ return "".join(out)+++def format_for_display(kind: TaxIdKind, value: str) -> str:+ """The document as it should appear on a rendered page."""+ return apply_mask(value, spec_for(kind).mask)++def normalise_and_validate(kind: TaxIdKind, value: str) -> tuple[str, str | None]:"""Store-ready value, plus a reason when it should be refused.diff --git a/backend/app/main.py b/backend/app/main.pyindex a859acf6..cf7bbcd8 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -33,6 +33,9 @@ from app.api.export import router as export_routerfrom app.api.fx_rates import router as fx_rates_routerfrom app.api.attachments import router as attachments_routerfrom app.api.fiscal import router as fiscal_router+from app.api.invoice_attachments import router as invoice_attachments_router+from app.api.invoices import router as invoices_router+from app.api.public_invoices import router as public_invoices_routerfrom app.api.payees import router as payees_routerfrom app.api.settings import router as settings_routerfrom app.api.transactions import router as transactions_router@@ -185,6 +188,9 @@ app.include_router(export_router)app.include_router(attachments_router)app.include_router(fiscal_router)app.include_router(payees_router)+app.include_router(invoices_router)+app.include_router(invoice_attachments_router)+app.include_router(public_invoices_router)app.include_router(settings_router)app.include_router(workspaces_router)app.include_router(admin_router)diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 1d91e9d3..1aad089f 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -1,6 +1,6 @@from app.models.user import Userfrom app.models.passkey import UserPasskey-from app.models.workspace import Workspace, WorkspaceMember+from app.models.workspace import Workspace, WorkspaceMember, WorkspaceTaxIdfrom app.models.category import Categoryfrom app.models.category_group import CategoryGroupfrom app.models.bank_connection import BankConnection@@ -25,6 +25,8 @@ 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_attachment import InvoiceAttachment# Side-effect import: register the before_insert listener that auto-stamps# workspace_id from user_id on financial entities. Imported last so all@@ -36,6 +38,7 @@ __all__ = ["UserPasskey","Workspace","WorkspaceMember",+ "WorkspaceTaxId","Category","CategoryGroup","BankConnection",@@ -63,6 +66,11 @@ __all__ = ["TransactionSplit","GroupSettlement","Collection",+ "Invoice",+ "InvoiceAllocation",+ "InvoiceLine",+ "InvoiceSettings",+ "InvoiceAttachment","collection_accounts","collection_asset_groups",]diff --git a/backend/app/models/invoice.py b/backend/app/models/invoice.pynew file mode 100644index 00000000..c87e7837--- /dev/null+++ b/backend/app/models/invoice.py@@ -0,0 +1,459 @@+"""The invoicing ledger: what a client owes, and what settled it.++Four tables and one rule that shapes all of them:++ Stored status is a decision a human took.+ Derived status is a fact about money and time.++`Invoice.status` therefore holds only decisions — someone issued it,+someone voided it, someone gave up on it. Whether an invoice is paid,+partially paid or overdue is computed from its allocations and its due+date, never written down. Peers that store `overdue` need a job to set+it and compensating SQL to unset it when a due date moves, and every+query downstream has to remember to say `IN ('unpaid', 'overdue')`.++Nothing here is jurisdiction-specific. The schema carries *shapes* — a+document type, a fiscal reference, a competence date — and the+jurisdiction packs (`app/fiscal/`) carry the vocabulary that fills them.+Brazil is the stress test because it is among the most demanding, not+because the model is shaped around it: the same tables serve a French+freelancer issuing a Factur-X invoice and a US contractor issuing+nothing at all.+"""+import uuid+from datetime import date as _date, datetime, timezone+from decimal import Decimal+from typing import TYPE_CHECKING, Any, Optional++from sqlalchemy import (+ Boolean,+ CheckConstraint,+ Date,+ DateTime,+ ForeignKey,+ Index,+ Integer,+ JSON,+ Numeric,+ String,+ Text,+ UniqueConstraint,+)+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.invoice_attachment import InvoiceAttachment+ from app.models.payee import Payee+ from app.models.transaction import Transaction+++#: Decisions a human takes about an invoice. Closed, and closed on+#: decisions only.+#:+#: draft — being written. Mutable, deletable, counted nowhere.+#: open — issued. Carries a number, appears in receivables.+#: void — cancelled. Keeps its number, reads as zero, terminal.+#: uncollectible — given up on. Leaves aging, never counts as paid.+#:+#: `paid`, `partial` and `overdue` are deliberately absent: they are+#: derived (see `invoice_service.derive_state`).+INVOICE_STATUSES = ("draft", "open", "void", "uncollectible")++#: UNTDID 1001 document types, by their common names. Only `invoice`+#: (380) is accepted today; `credit_note` (381) is reserved so the column+#: exists before the feature does, because adding it later means+#: backfilling every row in every self-hosted install.+INVOICE_DOCUMENT_TYPES = ("invoice", "credit_note")++#: Which side of the ledger a document sits on.+#:+#: receivable — we issued it; the money comes in+#: payable — we received it; the money goes out+#:+#: Kept **separate from `document_type`** rather than folded into a single+#: four-value enum (out_invoice / out_refund / in_invoice / in_refund, as+#: some accounting systems do). They answer different questions — which+#: direction the money moves, and what kind of document this is — and+#: crossing them means every new document type doubles the enum.+#:+#: Everything issued today is `receivable`. `payable` exists now because+#: supplier invoices are a stated direction for this module, and a column+#: added later is a migration over every row in every self-hosted install.+INVOICE_DIRECTIONS = ("receivable", "payable")++#: Who authored the document. `imported` rows are reconstructed from an+#: external system (Stripe, Asaas, a CSV): that system owns the document,+#: and Securo owns the cash that settled it.+INVOICE_ORIGINS = ("local", "imported")++#: How an allocation came to exist.+#:+#: Deliberately **not** a closed set. `manual` is a person pointing at a+#: transaction; everything else is the **id of the matching strategy that+#: produced the row**, and those ids come from the reconciliation policy —+#: a document the user will eventually edit, not an enum this file owns.+#: Closing this tuple would mean a migration every time somebody adds a+#: strategy, which is the opposite of the point.+#:+#: What it buys: the ledger can answer *why* a link exists and not merely+#: that it does. "Matched by: same client, net of withholding" is a+#: sentence; `payee_join` was a shrug.+MANUAL_METHOD = "manual"+++class Invoice(Base):+ """One expected payment, with an optional document attached to it."""++ __tablename__ = "invoices"+ __table_args__ = (+ # A number is unique within its series, within a workspace. Drafts+ # carry NULL and are exempt for free: SQL treats NULLs as distinct+ # in a unique index, which is exactly the "unique when present"+ # rule wanted here.+ UniqueConstraint(+ "workspace_id", "series", "number", name="uq_invoices_workspace_series_number"+ ),+ # An imported document is identified by its source's own id, so+ # two syncs of the same Stripe invoice converge on one row.+ UniqueConstraint(+ "workspace_id",+ "external_source",+ "external_id",+ name="uq_invoices_workspace_external",+ ),+ # Leads with direction because every list starts by choosing a+ # side of the ledger; status and due date narrow within it.+ Index(+ "ix_invoices_workspace_direction_status_due",+ "workspace_id",+ "direction",+ "status",+ "due_date",+ ),+ CheckConstraint(+ "status IN ('draft', 'open', 'void', 'uncollectible')",+ name="ck_invoices_status",+ ),+ CheckConstraint(+ "document_type IN ('invoice', 'credit_note')",+ name="ck_invoices_document_type",+ ),+ CheckConstraint(+ "direction IN ('receivable', 'payable')", name="ck_invoices_direction"+ ),+ CheckConstraint("origin IN ('local', 'imported')", name="ck_invoices_origin"),+ # A draft has no number, and anything we issued has one. Written as+ # a constraint because the alternative is trusting every future+ # code path to remember.+ #+ # An imported row never carries one of ours at all: its name lives+ # in `external_number`, and leaving this column null is what keeps+ # our sequence answerable for nothing but our own documents.+ CheckConstraint(+ "(origin = 'imported' AND number IS NULL)"+ " OR (status = 'draft' AND number IS NULL)"+ " OR (status <> 'draft' AND number IS NOT NULL)",+ name="ck_invoices_number_matches_status",+ ),+ CheckConstraint("total >= 0", name="ck_invoices_total_non_negative"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ # Who created the row. Not an owner: an invoice belongs to the+ # workspace, and a member leaving does not take it with them.+ user_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id"), nullable=True+ )+ # The client. Nullable because an imported document may name a+ # counterparty this workspace has never seen, and refusing the import+ # over it would be worse than storing the name in the snapshot.+ #+ # RESTRICT, not CASCADE: deleting a payee must never silently delete+ # the record of money someone owed.+ payee_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("payees.id", ondelete="RESTRICT"), nullable=True, index=True+ )++ document_type: Mapped[str] = mapped_column(String(20), default="invoice", server_default="invoice")+ direction: Mapped[str] = mapped_column(+ String(20), default="receivable", server_default="receivable"+ )+ # Lineage for a credit note: which document it corrects. Provenance+ # only — applying a credit is an allocation, and this column never+ # takes part in the arithmetic.+ corrects_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("invoices.id", ondelete="SET NULL"), nullable=True+ )++ origin: Mapped[str] = mapped_column(String(20), default="local", server_default="local")+ external_source: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)++ # Assigned at issuance, gapless within a series, never reused — not+ # even by a voided invoice, which keeps the number it was given.+ #+ # Ours alone. An imported document is named in `external_number`+ # instead: an integer plus a series cannot hold `2026/A/0031` without+ # dropping the padding and turning the series into a workaround, and+ # a source's numbering is not a sequence we may reason about — only a+ # name we must reproduce exactly.+ number: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ series: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)+ external_number: Mapped[Optional[str]] = mapped_column(String(60), nullable=True)++ status: Mapped[str] = mapped_column(String(20), default="draft", server_default="draft", index=True)++ issue_date: Mapped[_date] = mapped_column(Date)+ due_date: Mapped[_date] = mapped_column(Date)+ # The accountant's axis, and only it. Defaults to `issue_date`, but is+ # its own field because the two genuinely diverge: work delivered in+ # July and invoiced in August is booked in July under accrual+ # accounting — competência in Brazil, fait générateur in France, and+ # the Leistungsdatum that German law requires on the invoice itself.+ competence_date: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)+ # A timestamp, not a status. It distinguishes "sent, awaiting payment"+ # from "recorded but never sent" without inflating the enum.+ sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)++ currency: Mapped[str] = mapped_column(String(3), default="USD")+ subtotal: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ discount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ # Tax charged TO the client — part of what they owe. Tax withheld BY+ # the client is not this: that reduces the cash without reducing the+ # debt, and lands in the deductions table T6 introduces.+ tax_total: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ total: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))++ notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ internal_notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)++ # Everything the document said about itself when it was issued:+ # issuer identity, counterparty details, the labels and logo in force.+ # Frozen on purpose — renaming a client or changing a logo in+ # September must not rewrite August's invoice.+ snapshot: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)+ # Values for fields this workspace defined (a PO number, a project+ # reference, a municipal service code). The *definitions* live in+ # settings, so a new field is a settings edit and never a migration.+ custom_fields: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)++ # Null until someone asks for a shareable link, and nulled again to+ # revoke one. Unique so the public lookup is a single indexed read.+ share_token: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, unique=True)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(timezone.utc),+ onupdate=lambda: datetime.now(timezone.utc),+ )++ payee: Mapped[Optional["Payee"]] = relationship(lazy="joined")+ lines: Mapped[list["InvoiceLine"]] = relationship(+ back_populates="invoice",+ cascade="all, delete-orphan",+ order_by="InvoiceLine.position",+ lazy="selectin",+ )+ # `foreign_keys` is not optional here: an allocation points at+ # `invoices` twice — once for the debt it settles, once for a credit+ # note that settles it — and SQLAlchemy cannot guess which edge this+ # collection means.+ allocations: Mapped[list["InvoiceAllocation"]] = relationship(+ back_populates="invoice",+ cascade="all, delete-orphan",+ foreign_keys="InvoiceAllocation.invoice_id",+ lazy="selectin",+ )+ # The paper gathered under this debt. Deleting the invoice takes the+ # rows with it; the stored files are removed by the service, which is+ # the only layer that can talk to the storage provider.+ attachments: Mapped[list["InvoiceAttachment"]] = relationship(+ back_populates="invoice",+ cascade="all, delete-orphan",+ order_by="InvoiceAttachment.created_at",+ lazy="selectin",+ )+++class InvoiceLine(Base):+ """One billed item. Optional under the `tracking` preset."""++ __tablename__ = "invoice_lines"+ __table_args__ = (+ Index("ix_invoice_lines_invoice", "invoice_id"),+ CheckConstraint("quantity >= 0", name="ck_invoice_lines_quantity_non_negative"),+ )++ 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+ )+ description: Mapped[str] = mapped_column(String(500))+ quantity: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=4), default=Decimal("1"))+ # What the quantity counts — hours, days, pieces, kilos. Free text+ # rather than a list: a translator bills by word, a photographer by+ # image, a freight company by tonne-kilometre, and an enum here would+ # be a guess about somebody else's trade. Null keeps the line reading+ # exactly as it does today.+ unit: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)+ unit_price: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ # A rate, not an amount, and nullable: most workspaces under the+ # `tracking` preset never fill it in.+ tax_rate: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=7, scale=4), nullable=True)+ total: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))+ position: Mapped[int] = mapped_column(Integer, default=0)++ invoice: Mapped["Invoice"] = relationship(back_populates="lines")+++class InvoiceAllocation(Base):+ """A slice of money bound to a slice of debt.++ N:N with an amount, deliberately. A gateway payout is one bank credit+ settling many invoices net of fees; a Pix-paid invoice is one debt+ settled by several credits. A foreign key on the transaction could+ express neither, and would put a column on the hottest table in the+ system to do it — so the whole relationship lives here, and+ `transactions` is untouched by this feature.+ """++ __tablename__ = "invoice_allocations"+ __table_args__ = (+ Index("ix_invoice_allocations_invoice", "invoice_id"),+ Index("ix_invoice_allocations_transaction", "transaction_id"),+ CheckConstraint("amount > 0", name="ck_invoice_allocations_amount_positive"),+ # Exactly one source. A row that settles from both a transaction+ # and a credit note is not a richer row, it is an ambiguous one.+ CheckConstraint(+ "(transaction_id IS NOT NULL AND credit_note_id IS NULL)"+ " OR (transaction_id IS NULL AND credit_note_id IS NOT NULL)",+ name="ck_invoice_allocations_one_source",+ ),+ # The same transaction is never applied twice to the same invoice.+ # Two genuine partial payments are two different transactions.+ UniqueConstraint("invoice_id", "transaction_id", name="uq_invoice_allocation_transaction"),+ )++ 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+ )+ # CASCADE is right here and nowhere else in this file: if the+ # transaction is gone, the money it represented is gone, and a link+ # pointing at nothing would overstate what was received.+ transaction_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="CASCADE"), nullable=True+ )+ credit_note_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("invoices.id", ondelete="CASCADE"), nullable=True+ )+ amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))+ # Wide enough for a strategy id, not for an enum value: the policy's+ # own ids already run to 30 characters. See `MANUAL_METHOD`.+ method: Mapped[str] = mapped_column(String(60), default="manual", server_default="manual")+ allocated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ invoice: Mapped["Invoice"] = relationship(back_populates="allocations", foreign_keys=[invoice_id])+ transaction: Mapped[Optional["Transaction"]] = relationship(lazy="joined")+++class InvoiceSettings(Base):+ """How this workspace's invoicing behaves and how it looks.++ One row per workspace. The two presets exist so the Brazilian+ tracking flow and the international document flow are the same+ product configured differently — never two code paths, and never a+ branch on the UI language. A jurisdiction may *suggest* a preset; it+ never imposes one, because a Brazilian MEI serving a foreign client+ has every reason to pick the other.+ """++ __tablename__ = "invoice_settings"+ __table_args__ = (+ UniqueConstraint("workspace_id", name="uq_invoice_settings_workspace"),+ CheckConstraint("preset IN ('tracking', 'document')", name="ck_invoice_settings_preset"),+ CheckConstraint(+ "initial_state IN ('draft', 'open')", name="ck_invoice_settings_initial_state"+ ),+ CheckConstraint(+ "tax_fields IN ('hidden', 'optional', 'required')",+ name="ck_invoice_settings_tax_fields",+ ),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )++ # The preset is a starting point, not a mode: it fills the three+ # fields below, each individually overridable afterwards.+ preset: Mapped[str] = mapped_column(String(20), default="tracking", server_default="tracking")+ document_required: Mapped[bool] = mapped_column(+ Boolean, default=False, server_default="false"+ )+ initial_state: Mapped[str] = mapped_column(String(10), default="open", server_default="open")+ tax_fields: Mapped[str] = mapped_column(String(10), default="hidden", server_default="hidden")+ default_payment_terms_days: Mapped[int] = mapped_column(Integer, default=30, server_default="30")++ # Numbering. `next_number` is the counter the issue path consumes;+ # gapless means it is never rolled back, not even when an invoice is+ # voided one second after being issued.+ number_prefix: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)+ series: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)+ next_number: Mapped[int] = mapped_column(Integer, default=1, server_default="1")++ # Presentation.+ #+ # The logo is a file this workspace uploaded, not a URL pointing+ # somewhere else. A remote address would fetch the mark from a third+ # party every time a document is drawn — on a self-hosted install+ # that is a request out of the building for something the user+ # already owns, and it breaks the day that host does.+ #+ # Stored as an id rather than a path: the storage key is derived from+ # it, every upload mints a new one, and the old file is left in place+ # because an invoice issued last month froze *that* id in its+ # snapshot. Replacing a logo must not repaint a document a client+ # already holds.+ logo_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True)+ issuer_display_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ footer_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ # Free text, deliberately. A Brazilian writes a Pix key, a German an+ # IBAN and a BIC, an American a routing number — structuring this+ # would bake one country's shape into the schema.+ payment_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)+ # The one visual knob worth having: a document that carries the+ # sender's colour reads as theirs rather than as the tool's.+ accent_color: Mapped[Optional[str]] = mapped_column(String(9), nullable=True)++ # Labels and custom-field definitions. One jsonb rather than a column+ # per label: peers ship twenty columns for this and pay a migration+ # every time a label is added.+ template: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True),+ default=lambda: datetime.now(timezone.utc),+ onupdate=lambda: datetime.now(timezone.utc),+ )diff --git a/backend/app/models/invoice_attachment.py b/backend/app/models/invoice_attachment.pynew file mode 100644index 00000000..9f14ac00--- /dev/null+++ b/backend/app/models/invoice_attachment.py@@ -0,0 +1,145 @@+"""The files an invoice gathers, and which one of them *is* the invoice.++An invoice is not always a document. It is often a folder: the supplier's+PDF arrives by email, the fiscal document arrives days later from a+government portal, a payment receipt arrives after that, and the contract+that started it predates all three. The debt is one thing; the paper that+proves it accumulates.++Two consequences shape this table:++ - **`kind` is a role, not a file type.** What matters is what a file+ proves, not that it is a PDF. The roles are the ones every+ jurisdiction has — the bill, the fiscal document, the receipt, the+ agreement — and each pack names them in its own vocabulary. Nota+ fiscal, facture, Rechnung and invoice all land on `fiscal` here.++ - **`is_primary` marks the document itself.** When we wrote the invoice,+ our render is the document and nothing here outranks it. When we+ received it, the file the supplier sent *is* the document, and+ redrawing it from our own fields produces a page that looks official+ and is not. The primary attachment is what `/pdf` serves and what the+ screen shows, precisely so the product stops reconstructing something+ it was handed.+"""+import uuid+from datetime import date as _date, datetime, timezone+from typing import TYPE_CHECKING, Optional++from sqlalchemy import (+ BigInteger,+ Boolean,+ CheckConstraint,+ Date,+ DateTime,+ ForeignKey,+ Index,+ String,+ text,+)+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.invoice import Invoice+++#: What a file proves. Roles, deliberately — a jurisdiction pack supplies+#: the words a user sees, and no value here names a country's paperwork.+#:+#: bill — the demand for payment, as issued or as received+#: fiscal — the tax document (nota fiscal, facture, Rechnung, invoice)+#: receipt — proof the money moved+#: contract — the agreement or order the work came from+#: other — anything else worth keeping next to the debt+ATTACHMENT_KINDS = ("bill", "fiscal", "receipt", "contract", "other")+++class InvoiceAttachment(Base):+ """One file gathered under an invoice."""++ __tablename__ = "invoice_attachments"+ __table_args__ = (+ Index("ix_invoice_attachments_invoice", "invoice_id"),+ # At most one file can be *the* document: a partial unique index+ # is the only way to say "unique among the true ones". Declared+ # for both dialects on purpose — `postgresql_where` alone is+ # silently dropped elsewhere, and the index then degrades into+ # "one attachment per invoice", the opposite of a table whose+ # whole point is gathering several.+ Index(+ "uq_invoice_attachments_primary",+ "invoice_id",+ unique=True,+ postgresql_where=text("is_primary"),+ sqlite_where=text("is_primary"),+ ),+ # One row per file per source. Partial, because a null external id+ # is "this system does not name its files", not a value two rows+ # can collide on — and hand-uploaded files have no source at all.+ Index(+ "uq_invoice_attachments_external",+ "workspace_id",+ "source",+ "external_id",+ unique=True,+ postgresql_where=text("source IS NOT NULL AND external_id IS NOT NULL"),+ sqlite_where=text("source IS NOT NULL AND external_id IS NOT NULL"),+ ),+ CheckConstraint(+ "kind IN ('bill', 'fiscal', 'receipt', 'contract', 'other')",+ name="ck_invoice_attachments_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+ )+ # Who uploaded it. Not an owner: the file belongs to the workspace.+ user_id: Mapped[Optional[uuid.UUID]] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id"), nullable=True+ )++ # Where the file came from, and its name over there.+ #+ # An invoice assembled from several systems — the bill from a payment+ # provider, the fiscal document from a government portal, a receipt+ # forwarded by email — is a folder whose contents have different+ # authors. Without this the folder is a pile: three files, no way to+ # say which system produced which, or to recognise one already+ # collected when that system syncs again.+ #+ # Null means a person uploaded it here. Everything else is the id of+ # the system that produced or delivered it.+ source: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)+ # The file's id in that system, when it has one. Paired with `source`+ # it is what makes a second sync converge on the row it already wrote+ # rather than filing a duplicate.+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)++ kind: Mapped[str] = mapped_column(String(20), default="other", server_default="other")+ is_primary: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")++ # The number the document carries on its face — an NF-e key, a+ # facture number, a receipt reference. Text, because it is a name+ # given elsewhere and nothing here may assume it counts.+ document_number: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)+ # The date on the document, which is rarely the date it was uploaded.+ issued_at: Mapped[Optional[_date]] = mapped_column(Date, nullable=True)++ filename: Mapped[str] = mapped_column(String(255))+ storage_key: Mapped[str] = mapped_column(String(500))+ content_type: Mapped[str] = mapped_column(String(100))+ size: Mapped[int] = mapped_column(BigInteger)++ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++ invoice: Mapped["Invoice"] = relationship(back_populates="attachments")diff --git a/backend/app/models/workspace.py b/backend/app/models/workspace.pyindex 717c07d0..a684f37f 100644--- a/backend/app/models/workspace.py+++ b/backend/app/models/workspace.py@@ -79,6 +79,12 @@ class Workspace(Base):# Nullable, and null is a working configuration: the pack registry falls# back to free-text documents with no mask, so a country nobody has# contributed a pack for is usable on day one.+ # The workspace describing itself, for the issuer block on a document+ # and for the fiscal documents that will want the same two fields.+ # Null forever in a personal workspace, which is the expected end+ # state and not an incomplete row.+ legal_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)+ address: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)tax_jurisdiction: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)icon: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)color: Mapped[Optional[str]] = mapped_column(String(7), nullable=True)@@ -91,6 +97,38 @@ class Workspace(Base):)+class WorkspaceTaxId(Base):+ """A fiscal document the workspace itself holds.++ The issuer side of the same pack that describes counterparties. A+ separate table from `payee_tax_ids` on purpose: the cardinality+ differs by orders of magnitude, and one table with a discriminator+ would put a filter on every read to save a `CREATE TABLE`.++ Which kinds a workspace is *offered* comes from its own+ `tax_jurisdiction`; which kinds it may *store* is not restricted,+ because a company can legitimately hold a document its country's+ pack never anticipated.+ """++ __tablename__ = "workspace_tax_ids"+ __table_args__ = (+ UniqueConstraint("workspace_id", "kind", name="uq_workspace_tax_id_kind"),+ )++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ workspace_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True+ )+ kind: Mapped[str] = mapped_column(String(30))+ #: Normalised per kind on write by the same validators the payee side+ #: uses. Display formatting is the frontend's job, from the pack mask.+ value: Mapped[str] = mapped_column(String(60))+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )++class WorkspaceMember(Base):__tablename__ = "workspace_members"__table_args__ = (diff --git a/backend/app/schemas/invoice.py b/backend/app/schemas/invoice.pynew file mode 100644index 00000000..8e2edfd3--- /dev/null+++ b/backend/app/schemas/invoice.py@@ -0,0 +1,337 @@+import uuid+from datetime import date as _Date, datetime+from decimal import Decimal+from typing import Any, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++#: Decisions a human took. The API accepts none of these directly — a+#: status changes through the action that causes it (`/issue`, `/void`),+#: never by PATCHing a string, because "why is this void" must always+#: have an answer.+InvoiceStatus = Literal["draft", "open", "void", "uncollectible"]++#: What a reader sees. The three decisions above plus the four facts+#: computed from allocations and the due date.+InvoiceState = Literal[+ "draft", "open", "partial", "paid", "overdue", "void", "uncollectible"+]++#: Which side of the ledger. Everything the UI writes today is a+#: receivable; `payable` is accepted so supplier documents have somewhere+#: to land without a migration when that path arrives.+InvoiceDirection = Literal["receivable", "payable"]++InvoicePreset = Literal["tracking", "document"]+TaxFieldsMode = Literal["hidden", "optional", "required"]+++class InvoiceLineInput(BaseModel):+ description: str = Field(..., max_length=500)+ quantity: Decimal = Field(default=Decimal("1"), ge=0)+ #: What the quantity counts — hours, words, pieces. Free text.+ unit: Optional[str] = Field(default=None, max_length=20)+ unit_price: Decimal = Field(default=Decimal("0"))+ # A percentage, not an amount — and only meaningful when the+ # workspace shows tax fields at all.+ tax_rate: Optional[Decimal] = Field(default=None, ge=0, le=100)+++class InvoiceLineRead(BaseModel):+ id: uuid.UUID+ description: str+ quantity: Decimal+ unit: Optional[str] = None+ unit_price: Decimal+ tax_rate: Optional[Decimal]+ total: Decimal+ position: int++ model_config = ConfigDict(from_attributes=True)+++class AllocationTransaction(BaseModel):+ """Just enough of the transaction to render the row it came from."""++ id: uuid.UUID+ description: Optional[str] = None+ date: Optional[_Date] = None+ amount: Optional[Decimal] = None++ model_config = ConfigDict(from_attributes=True)+++class InvoiceAllocationRead(BaseModel):+ id: uuid.UUID+ transaction_id: Optional[uuid.UUID]+ credit_note_id: Optional[uuid.UUID]+ amount: Decimal+ method: str+ allocated_at: datetime+ transaction: Optional[AllocationTransaction] = None++ model_config = ConfigDict(from_attributes=True)+++#: Where a document came from. `local` is one someone typed here;+#: `imported` is one that arrived from somewhere else and was+#: reconstructed — a gateway sync, a forwarded email, a photographed+#: supplier invoice. The *source* goes in `external_source`.+InvoiceOrigin = Literal["local", "imported"]+++class InvoiceCreate(BaseModel):+ direction: Optional[InvoiceDirection] = None+ #: Provenance. Every future intake — gateway sync, email, upload,+ #: OCR — writes through these three fields, which is why they are+ #: accepted here before any of those intakes exist.+ origin: Optional[InvoiceOrigin] = None+ external_source: Optional[str] = Field(default=None, max_length=50)+ external_id: Optional[str] = Field(default=None, max_length=255)+ #: The name the source gave it, exactly as it reads. Text, not an+ #: integer plus a series: `2026/A/0031` is a name, and treating it as+ #: a number loses the padding and invents a sequence we do not own.+ #: Ignored on a document written here, which is numbered from this+ #: workspace's own counter.+ external_number: Optional[str] = Field(default=None, max_length=60)+ #: Keep it a draft even where the workspace would open it. Not a+ #: status field — the caller cannot ask for `void` here — only the+ #: difference between "I am still writing this" and "this is owed".+ as_draft: bool = False+ payee_id: Optional[uuid.UUID] = None+ issue_date: Optional[_Date] = None+ # Optional: falls back to the workspace's default payment terms, so+ # the three-field flow really is three fields.+ due_date: Optional[_Date] = None+ competence_date: Optional[_Date] = None+ currency: Optional[str] = Field(default=None, max_length=3)+ total: Optional[Decimal] = Field(default=None, ge=0)+ discount: Optional[Decimal] = Field(default=None, ge=0)+ subtotal: Optional[Decimal] = Field(default=None, ge=0)+ tax_total: Optional[Decimal] = Field(default=None, ge=0)+ notes: Optional[str] = None+ internal_notes: Optional[str] = None+ custom_fields: Optional[dict[str, Any]] = None+ lines: Optional[list[InvoiceLineInput]] = None+++class InvoiceUpdate(BaseModel):+ payee_id: Optional[uuid.UUID] = None+ issue_date: Optional[_Date] = None+ due_date: Optional[_Date] = None+ competence_date: Optional[_Date] = None+ currency: Optional[str] = Field(default=None, max_length=3)+ total: Optional[Decimal] = Field(default=None, ge=0)+ discount: Optional[Decimal] = Field(default=None, ge=0)+ subtotal: Optional[Decimal] = Field(default=None, ge=0)+ tax_total: Optional[Decimal] = Field(default=None, ge=0)+ notes: Optional[str] = None+ internal_notes: Optional[str] = None+ custom_fields: Optional[dict[str, Any]] = None+ lines: Optional[list[InvoiceLineInput]] = None+++class InvoicePayee(BaseModel):+ id: uuid.UUID+ name: str++ model_config = ConfigDict(from_attributes=True)+++class InvoiceRead(BaseModel):+ id: uuid.UUID+ payee_id: Optional[uuid.UUID]+ payee: Optional[InvoicePayee] = None+ document_type: str+ direction: InvoiceDirection+ origin: str+ external_source: Optional[str] = None+ external_id: Optional[str] = None+ number: Optional[int]+ series: Optional[str]+ external_number: Optional[str] = None+ status: InvoiceStatus+ #: The derived answers. Defaults exist only so the ORM row can be+ #: validated before they are attached; `api/invoices.py::_serialize`+ #: is the sole constructor and always fills all four. They are never+ #: stored — see `invoice_service.derive_state`.+ state: InvoiceState = "draft"+ issue_date: _Date+ due_date: _Date+ competence_date: Optional[_Date]+ sent_at: Optional[datetime]+ currency: str+ subtotal: Decimal+ discount: Decimal+ tax_total: Decimal+ total: Decimal+ amount_paid: Decimal = Decimal("0")+ balance: Decimal = Decimal("0")+ days_overdue: int = 0+ notes: Optional[str]+ internal_notes: Optional[str]+ custom_fields: Optional[dict[str, Any]]+ snapshot: Optional[dict[str, Any]]+ #: Present once the invoice has been issued: a link anyone holding it+ #: can open. Null until someone asks for one, and null again once+ #: revoked.+ share_token: Optional[str] = None+ lines: list[InvoiceLineRead] = []+ allocations: list[InvoiceAllocationRead] = []+ created_at: datetime++ model_config = ConfigDict(from_attributes=True)+++class AllocationCreate(BaseModel):+ transaction_id: uuid.UUID+ #: Omitted means "as much as fits": the smaller of what remains on+ #: the invoice and what the transaction carries.+ amount: Optional[Decimal] = Field(default=None, gt=0)+++class AgingBuckets(BaseModel):+ current: Decimal+ d1_30: Decimal+ d31_60: Decimal+ d61_90: Decimal+ d90_plus: Decimal+++class InvoiceSummary(BaseModel):+ outstanding: Decimal+ overdue_amount: Decimal+ overdue_count: int+ received_this_month: Decimal+ buckets: AgingBuckets+ upcoming: list[InvoiceRead] = []+++class IssuerTaxIdInput(BaseModel):+ kind: str+ value: str = Field(..., max_length=120)+++class IssuerTaxIdRead(BaseModel):+ kind: str+ value: str++ model_config = ConfigDict(from_attributes=True)+++class IssuerProfileRead(BaseModel):+ """The workspace describing itself, as the issuer block on a document."""++ legal_name: Optional[str]+ address: Optional[str]+ tax_jurisdiction: Optional[str]+ tax_ids: list[IssuerTaxIdRead] = []+++class IssuerProfileUpdate(BaseModel):+ legal_name: Optional[str] = Field(default=None, max_length=255)+ address: Optional[str] = Field(default=None, max_length=500)+ #: Omit to leave documents untouched; send a list to replace the set.+ tax_ids: Optional[list[IssuerTaxIdInput]] = None+++class ShareLinkRead(BaseModel):+ token: str+ #: Path rather than an absolute URL: the server does not reliably know+ #: the public origin behind a reverse proxy, and the frontend does.+ path: str+++class InvoiceFacetCounts(BaseModel):+ all: int+ open: int+ overdue: int+ paid: int+ draft: int+++class InvoiceFacets(BaseModel):+ """What the filter bar needs to render itself.++ `years` is every year that has an invoice, newest first, and is never+ narrowed by the `year` parameter — otherwise picking a year would+ remove every other year from the picker.+ """++ years: list[int]+ counts: InvoiceFacetCounts+++class InvoiceSettingsRead(BaseModel):+ preset: InvoicePreset+ document_required: bool+ initial_state: Literal["draft", "open"]+ tax_fields: TaxFieldsMode+ default_payment_terms_days: int+ number_prefix: Optional[str]+ series: Optional[str]+ next_number: int+ logo_id: Optional[uuid.UUID] = None+ issuer_display_name: Optional[str]+ footer_note: Optional[str]+ payment_details: Optional[str]+ accent_color: Optional[str]+ template: Optional[dict[str, Any]]++ model_config = ConfigDict(from_attributes=True)+++class InvoiceSettingsUpdate(BaseModel):+ preset: Optional[InvoicePreset] = None+ document_required: Optional[bool] = None+ initial_state: Optional[Literal["draft", "open"]] = None+ tax_fields: Optional[TaxFieldsMode] = None+ default_payment_terms_days: Optional[int] = Field(default=None, ge=0, le=365)+ #: These five are blankable on purpose — clearing a logo is a thing+ #: people do, and it must not read as "leave it alone".+ number_prefix: Optional[str] = Field(default=None, max_length=20)+ series: Optional[str] = Field(default=None, max_length=20)+ issuer_display_name: Optional[str] = Field(default=None, max_length=255)+ footer_note: Optional[str] = None+ #: Free text on purpose — a Pix key, an IBAN and a routing number have+ #: nothing structural in common, and picking one shape would pick a+ #: country.+ payment_details: Optional[str] = None+ accent_color: Optional[str] = Field(default=None, max_length=9)+ #: Labels and custom-field definitions. Free-form by design: adding a+ #: field a workspace needs must never be a database migration.+ template: Optional[dict[str, Any]] = None+++#: What a filed document proves. Roles, not file types — the vocabulary+#: that names them for a user comes from the jurisdiction pack.+InvoiceAttachmentKind = Literal["bill", "fiscal", "receipt", "contract", "other"]+++class InvoiceAttachmentRead(BaseModel):+ id: uuid.UUID+ invoice_id: uuid.UUID+ #: The system that produced or delivered the file. Null when a person+ #: uploaded it here.+ source: Optional[str] = None+ external_id: Optional[str] = None+ kind: str+ #: True on the one file that *is* the document. What `/pdf` serves and+ #: what the screen shows instead of a page drawn from our own fields.+ is_primary: bool+ document_number: Optional[str] = None+ issued_at: Optional[_Date] = None+ filename: str+ content_type: str+ size: int+ created_at: datetime++ model_config = ConfigDict(from_attributes=True)+++class InvoiceAttachmentUpdate(BaseModel):+ kind: Optional[InvoiceAttachmentKind] = None+ source: Optional[str] = Field(default=None, max_length=50)+ document_number: Optional[str] = Field(default=None, max_length=120)+ issued_at: Optional[_Date] = None+ is_primary: Optional[bool] = Nonediff --git a/backend/app/schemas/transaction.py b/backend/app/schemas/transaction.pyindex 2a60c9c5..6f6a68b7 100644--- a/backend/app/schemas/transaction.py+++ b/backend/app/schemas/transaction.py@@ -138,12 +138,33 @@ class InstallmentSeriesCreate(BaseModel):return self+class TransactionInvoiceLink(BaseModel):+ """The invoice this transaction settles, when it settles one.++ Present only for workspaces with the invoicing module, and only on+ rows that carry an allocation — a personal workspace never sees this+ field at all, because the query that fills it is not run there.+ """++ invoice_id: uuid.UUID+ number: Optional[int] = None+ series: Optional[str] = None+ #: The name an imported invoice arrived with. Without it the badge for+ #: one has nothing to show, since it carries no number of ours.+ external_number: Optional[str] = None+ amount: Decimal++class TransactionRead(TransactionBase):id: uuid.UUIDuser_id: uuid.UUIDaccount_id: Optional[uuid.UUID] = Nonecategory_id: Optional[uuid.UUID] = Nonecategory: Optional[CategoryRead] = None+ #: Every invoice this transaction settles. A list because one+ #: payment can settle several — a payout net of fees is the+ #: ordinary case, not the exotic one.+ invoice_links: list[TransactionInvoiceLink] = []currency: str = "USD"source: strstatus: str = "posted"diff --git a/backend/app/services/invoice_attachment_service.py b/backend/app/services/invoice_attachment_service.pynew file mode 100644index 00000000..8edd4aa7--- /dev/null+++ b/backend/app/services/invoice_attachment_service.py@@ -0,0 +1,288 @@+"""Gathering paper under an invoice.++Mirrors `attachment_service` — same validation, same storage provider,+same sanitised filenames — and adds the two things an invoice needs that+a transaction does not: the role a file plays, and which file *is* the+document.+"""+import uuid+from datetime import date as _date+from typing import Optional++from sqlalchemy import func, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession++from app.core.config import get_settings+from app.models.invoice import Invoice+from app.models.invoice_attachment import ATTACHMENT_KINDS, InvoiceAttachment+from app.providers import get_storage_provider+from app.services.attachment_service import _validate_file, sanitize_filename+++async def _invoice_in_workspace(+ session: AsyncSession, invoice_id: uuid.UUID, workspace_id: uuid.UUID+) -> Invoice:+ result = await session.execute(+ select(Invoice).where(+ Invoice.id == invoice_id, Invoice.workspace_id == workspace_id+ )+ )+ invoice = result.scalar_one_or_none()+ if not invoice:+ raise LookupError("Invoice not found")+ return invoice+++async def _clear_primary(session: AsyncSession, invoice_id: uuid.UUID) -> None:+ """Demote whatever currently holds the flag.++ Done before setting the new one because the partial unique index+ admits exactly one true row per invoice, and a second insert would+ otherwise be rejected instead of taking over.+ """+ result = await session.execute(+ select(InvoiceAttachment).where(+ InvoiceAttachment.invoice_id == invoice_id,+ InvoiceAttachment.is_primary.is_(True),+ )+ )+ for row in result.scalars().all():+ row.is_primary = False+ await session.flush()+++async def find_by_external_id(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ source: str,+ external_id: str,+) -> Optional[InvoiceAttachment]:+ """The row a previous sync of the same file already wrote, if any.++ What keeps a second run of an integration from filing the same fiscal+ document twice under one invoice.+ """+ result = await session.execute(+ select(InvoiceAttachment).where(+ InvoiceAttachment.workspace_id == workspace_id,+ InvoiceAttachment.source == source,+ InvoiceAttachment.external_id == external_id,+ )+ )+ return result.scalar_one_or_none()+++async def upload(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: Optional[uuid.UUID],+ invoice_id: uuid.UUID,+ filename: str,+ content_type: str,+ data: bytes,+ kind: str = "other",+ source: Optional[str] = None,+ external_id: Optional[str] = None,+ document_number: Optional[str] = None,+ issued_at: Optional[_date] = None,+ is_primary: Optional[bool] = None,+) -> InvoiceAttachment:+ if kind not in ATTACHMENT_KINDS:+ raise ValueError(f"Unknown document kind '{kind}'.")++ filename = sanitize_filename(filename)+ _validate_file(filename, content_type, len(data))+ invoice = await _invoice_in_workspace(session, invoice_id, workspace_id)++ settings = get_settings()+ count = (+ await session.execute(+ select(func.count()).where(InvoiceAttachment.invoice_id == invoice_id)+ )+ ).scalar_one()+ if count >= settings.storage_max_attachments_per_invoice:+ raise ValueError(+ f"Maximum of {settings.storage_max_attachments_per_invoice} documents per invoice reached."+ )++ # The first bill filed against a document we did not write is the+ # document. Nobody should have to tell us that the supplier's own PDF+ # outranks a page we would have drawn from our own fields, and the+ # flag stays explicit so it can still be moved by hand afterwards.+ if is_primary is None:+ is_primary = (+ kind == "bill" and invoice.origin == "imported" and not invoice.attachments+ )++ prefix = uuid.uuid4().hex[:8]+ storage_key = f"{workspace_id}/invoices/{invoice_id}/{prefix}_{filename}"++ # Checked before the bytes are written. `source` + `external_id` is+ # unique per workspace, so a second sync of the same file is rejected+ # by the index — and if that happened after the upload, the blob it+ # had just written would stay in storage with no row pointing at it+ # and nothing to find it by.+ if source and external_id:+ existing = await find_by_external_id(session, workspace_id, source, external_id)+ if existing is not None:+ return existing++ storage = get_storage_provider()+ stored = await storage.upload(storage_key, data, content_type)++ if is_primary:+ await _clear_primary(session, invoice_id)++ attachment = InvoiceAttachment(+ invoice_id=invoice_id,+ workspace_id=workspace_id,+ user_id=user_id,+ source=(source or None),+ external_id=(external_id or None),+ kind=kind,+ is_primary=bool(is_primary),+ document_number=(document_number or None),+ issued_at=issued_at,+ filename=filename,+ storage_key=stored.storage_key,+ content_type=stored.content_type,+ size=stored.size,+ )+ session.add(attachment)+ try:+ await session.commit()+ except IntegrityError:+ # Lost a race with a concurrent sync of the same file. The row is+ # not ours, so neither is the blob: leaving it would be an orphan+ # nothing can reach.+ await session.rollback()+ try:+ await storage.delete(stored.storage_key)+ except Exception:+ pass+ existing = (+ await find_by_external_id(session, workspace_id, source, external_id)+ if source and external_id+ else None+ )+ if existing is not None:+ return existing+ raise+ await session.refresh(attachment)+ return attachment+++async def listing(+ session: AsyncSession, workspace_id: uuid.UUID, invoice_id: uuid.UUID+) -> list[InvoiceAttachment]:+ await _invoice_in_workspace(session, invoice_id, workspace_id)+ result = await session.execute(+ select(InvoiceAttachment)+ .where(InvoiceAttachment.invoice_id == invoice_id)+ .order_by(InvoiceAttachment.is_primary.desc(), InvoiceAttachment.created_at)+ )+ return list(result.scalars().all())+++async def primary_for(+ session: AsyncSession, invoice_id: uuid.UUID+) -> Optional[InvoiceAttachment]:+ """The file that *is* the document, if one was filed."""+ result = await session.execute(+ select(InvoiceAttachment).where(+ InvoiceAttachment.invoice_id == invoice_id,+ InvoiceAttachment.is_primary.is_(True),+ )+ )+ return result.scalar_one_or_none()+++async def _get(+ session: AsyncSession, attachment_id: uuid.UUID, workspace_id: uuid.UUID+) -> InvoiceAttachment:+ result = await session.execute(+ select(InvoiceAttachment).where(+ InvoiceAttachment.id == attachment_id,+ InvoiceAttachment.workspace_id == workspace_id,+ )+ )+ attachment = result.scalar_one_or_none()+ if not attachment:+ raise LookupError("Attachment not found")+ return attachment+++async def download(+ session: AsyncSession, attachment_id: uuid.UUID, workspace_id: uuid.UUID+) -> tuple[InvoiceAttachment, bytes]:+ attachment = await _get(session, attachment_id, workspace_id)+ storage = get_storage_provider()+ return attachment, await storage.download(attachment.storage_key)+++async def read_bytes(session: AsyncSession, attachment: InvoiceAttachment) -> bytes:+ storage = get_storage_provider()+ return await storage.download(attachment.storage_key)+++async def update(+ session: AsyncSession,+ attachment_id: uuid.UUID,+ workspace_id: uuid.UUID,+ data: dict,+) -> InvoiceAttachment:+ attachment = await _get(session, attachment_id, workspace_id)++ if "kind" in data and data["kind"] is not None:+ if data["kind"] not in ATTACHMENT_KINDS:+ raise ValueError(f"Unknown document kind '{data['kind']}'.")+ attachment.kind = data["kind"]+ if "source" in data:+ attachment.source = data["source"] or None+ if "document_number" in data:+ attachment.document_number = data["document_number"] or None+ if "issued_at" in data:+ attachment.issued_at = data["issued_at"]+ if data.get("is_primary") is True:+ await _clear_primary(session, attachment.invoice_id)+ attachment.is_primary = True+ elif data.get("is_primary") is False:+ attachment.is_primary = False++ await session.commit()+ await session.refresh(attachment)+ return attachment+++async def delete(+ session: AsyncSession, attachment_id: uuid.UUID, workspace_id: uuid.UUID+) -> None:+ attachment = await _get(session, attachment_id, workspace_id)+ storage = get_storage_provider()+ await storage.delete(attachment.storage_key)+ await session.delete(attachment)+ await session.commit()+++async def cleanup_files(session: AsyncSession, invoice_id: uuid.UUID) -> None:+ """Remove the stored files for an invoice about to be deleted.++ The rows go with the invoice through the cascade; the files have to be+ asked for, and are best-effort — one already gone must not block a+ delete the user asked for.+ """+ result = await session.execute(+ select(InvoiceAttachment.storage_key).where(+ InvoiceAttachment.invoice_id == invoice_id+ )+ )+ keys = [row[0] for row in result.all()]+ if not keys:+ return+ storage = get_storage_provider()+ for key in keys:+ try:+ await storage.delete(key)+ except Exception:+ passdiff --git a/backend/app/services/invoice_document.py b/backend/app/services/invoice_document.pynew file mode 100644index 00000000..3ceee63c--- /dev/null+++ b/backend/app/services/invoice_document.py@@ -0,0 +1,530 @@+"""The rendered invoice: one resolved document, two renderers.++The screen and the PDF must agree, forever. The way they do that here is+that neither of them decides anything: `build_document` resolves the+invoice, its snapshot and the workspace's identity into one plain+structure, and both renderers only lay it out. A field that appears on+the PDF but not on screen is a bug in one renderer, never a difference+of opinion about what the document says.++What is resolved, and in what order, is the whole subject:++ - **The snapshot wins.** It is what the document said when it was+ issued. A logo changed in September must not reach August's invoice,+ and a client renamed after the fact must not rename itself on a+ document they already hold.+ - **Live settings fill only what the snapshot never captured** — an+ invoice issued before a field existed, or a draft that has not been+ issued at all and therefore has no snapshot yet.++Nothing here is jurisdiction-specific. Whether the document reads as a+fiscal instrument or as a commercial request for payment is a matter of+what the workspace configured and what the reader's law says — the same+bytes serve a French auto-entrepreneur and a Brazilian MEI whose NFS-e+was issued at the prefeitura.+"""+from dataclasses import dataclass, field+from datetime import date as _date+from decimal import Decimal+from typing import Any, Optional++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.fiscal.registry import TaxIdKind, format_for_display, spec_for+from app.models.invoice import Invoice, InvoiceSettings+from app.models.workspace import Workspace, WorkspaceTaxId++#: Labels a template may override. Anything not listed is not overridable,+#: which keeps a stray key in the jsonb from silently becoming UI.+#:+#: English is the fallback, not the default: `default_labels()` picks the+#: pack for the *issuer's* locale first. The document is written in the+#: sender's language, and a Brazilian shipping "Invoice / Bill to / Qty"+#: until they rename all eighteen by hand is a bad first run.+DEFAULT_LABELS: dict[str, str] = {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "number": "Number",+ "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",+ "balance": "Balance due",+ "paymentDetails": "Payment details",+ "notes": "Notes",+}++#: Shipped label packs, by language. Deliberately few: this is the set+#: the product is actually sold in, and a half-translated document reads+#: worse than an English one. A locale with no pack falls back to+#: `DEFAULT_LABELS`, and every label stays individually overridable+#: afterwards regardless.+#:+#: These are *defaults for the sender*, never a translation for the+#: reader: the document keeps the words its issuer chose, whoever opens+#: it. That is why they are resolved once, at issuance, into the snapshot.+LABEL_PACKS: dict[str, dict[str, str]] = {+ "pt": {+ "invoice": "Fatura",+ "billTo": "Cliente",+ "from": "Emitente",+ "number": "Número",+ "issueDate": "Emissão",+ "dueDate": "Vencimento",+ "description": "Descrição",+ "quantity": "Qtd",+ "unitPrice": "Valor unit.",+ "amount": "Valor",+ "subtotal": "Subtotal",+ "discount": "Desconto",+ "tax": "Impostos",+ "total": "Total",+ "paid": "Recebido",+ "balance": "Saldo devedor",+ "paymentDetails": "Dados para pagamento",+ "notes": "Observações",+ },+ "es": {+ "invoice": "Factura",+ "billTo": "Cliente",+ "from": "Emisor",+ "number": "Número",+ "issueDate": "Emisión",+ "dueDate": "Vencimiento",+ "description": "Descripción",+ "quantity": "Cant.",+ "unitPrice": "Precio unit.",+ "amount": "Importe",+ "subtotal": "Subtotal",+ "discount": "Descuento",+ "tax": "Impuestos",+ "total": "Total",+ "paid": "Cobrado",+ "balance": "Saldo pendiente",+ "paymentDetails": "Datos de pago",+ "notes": "Notas",+ },+ "fr": {+ "invoice": "Facture",+ "billTo": "Client",+ "from": "Émetteur",+ "number": "Numéro",+ "issueDate": "Date d'émission",+ "dueDate": "Échéance",+ "description": "Désignation",+ "quantity": "Qté",+ "unitPrice": "Prix unit.",+ "amount": "Montant",+ "subtotal": "Sous-total",+ "discount": "Remise",+ "tax": "TVA",+ "total": "Total",+ "paid": "Réglé",+ "balance": "Reste à payer",+ "paymentDetails": "Coordonnées de paiement",+ "notes": "Notes",+ },+ "de": {+ "invoice": "Rechnung",+ "billTo": "Rechnungsempfänger",+ "from": "Rechnungssteller",+ "number": "Nummer",+ "issueDate": "Rechnungsdatum",+ "dueDate": "Fällig am",+ "description": "Bezeichnung",+ "quantity": "Menge",+ "unitPrice": "Einzelpreis",+ "amount": "Betrag",+ "subtotal": "Zwischensumme",+ "discount": "Rabatt",+ "tax": "USt.",+ "total": "Gesamt",+ "paid": "Bezahlt",+ "balance": "Offener Betrag",+ "paymentDetails": "Zahlungsinformationen",+ "notes": "Hinweise",+ },+ "it": {+ "invoice": "Fattura",+ "billTo": "Cliente",+ "from": "Emittente",+ "number": "Numero",+ "issueDate": "Data emissione",+ "dueDate": "Scadenza",+ "description": "Descrizione",+ "quantity": "Qtà",+ "unitPrice": "Prezzo unit.",+ "amount": "Importo",+ "subtotal": "Subtotale",+ "discount": "Sconto",+ "tax": "IVA",+ "total": "Totale",+ "paid": "Incassato",+ "balance": "Saldo dovuto",+ "paymentDetails": "Dati per il pagamento",+ "notes": "Note",+ },+}+++def default_labels(locale: Optional[str]) -> dict[str, str]:+ """The label pack for the issuer's language, English if none ships.++ Keyed on the language subtag, so `pt-BR` and `pt-PT` share a pack —+ the two differ in vocabulary a translator would care about and not in+ the eighteen words on an invoice.+ """+ if not locale:+ return dict(DEFAULT_LABELS)+ language = locale.replace("_", "-").split("-")[0].lower()+ return dict(LABEL_PACKS.get(language, DEFAULT_LABELS))+++#: The default when a workspace has picked no colour. Deliberately a+#: neutral ink rather than the product's own brand: the document belongs+#: to the sender, not to the tool that printed it.+DEFAULT_ACCENT = "#111827"+++@dataclass+class DocumentParty:+ """One side of the document. Every field optional, because a workspace+ that has filled nothing in still gets a usable page."""++ name: Optional[str] = None+ legal_name: Optional[str] = None+ address: Optional[str] = None+ email: Optional[str] = None+ #: Rendered `(label, value)` pairs — already resolved through the+ #: fiscal pack, so no renderer needs to know what a CNPJ is.+ tax_ids: list[tuple[str, str]] = field(default_factory=list)+++@dataclass+class DocumentLine:+ description: str+ quantity: Decimal+ unit_price: Decimal+ total: Decimal+ tax_rate: Optional[Decimal] = None+ #: Printed beside the quantity: "12 hours", not "12". Last and+ #: defaulted so the positional constructions already in the tests+ #: keep meaning what they meant.+ unit: Optional[str] = None+++@dataclass+class InvoiceDocument:+ """Everything a renderer needs, and nothing it has to look up."""++ number: Optional[str]+ status: str+ state: str+ issue_date: _date+ due_date: _date+ currency: str+ subtotal: Decimal+ discount: Decimal+ tax_total: Decimal+ total: Decimal+ amount_paid: Decimal+ balance: Decimal+ issuer: DocumentParty+ client: DocumentParty+ lines: list[DocumentLine]+ labels: dict[str, str]+ accent_color: str+ logo_id: Optional[str]+ payment_details: Optional[str]+ notes: Optional[str]+ footer_note: Optional[str]+ custom_fields: list[tuple[str, str]]+ #: True when the invoice carries enough to be worth rendering as a+ #: document at all. An amount with no lines is a perfectly good+ #: receivable and a poor-looking fatura, so the UI asks first.+ has_line_items: bool+ #: Which side of the ledger. On a payable the parties are already+ #: swapped below, so a renderer never has to know — but it is carried+ #: so a screen can say "received" instead of "issued", which is the+ #: difference between showing a document and claiming to have written+ #: one.+ direction: str = "receivable"+++def _label_map(+ template: Optional[dict[str, Any]], locale: Optional[str] = None+) -> dict[str, str]:+ """The issuer's language pack, overridden only by keys that exist.++ A template is free-form jsonb by design, so it can hold anything a+ hand edit put there; unknown keys are ignored rather than rendered.+ """+ labels = default_labels(locale)+ overrides = (template or {}).get("labels")+ if isinstance(overrides, dict):+ for key, value in overrides.items():+ if key in DEFAULT_LABELS and isinstance(value, str) and value.strip():+ labels[key] = value.strip()+ return labels+++def _custom_field_pairs(+ template: Optional[dict[str, Any]], values: Optional[dict[str, Any]]+) -> list[tuple[str, str]]:+ """Only fields the workspace declared, in the order it declared them.++ Driven by the definitions rather than by the stored values, so a field+ removed from settings stops printing without anyone editing invoices.+ """+ defs = (template or {}).get("custom_fields")+ if not isinstance(defs, list) or not values:+ return []+ pairs: list[tuple[str, str]] = []+ for definition in defs:+ if not isinstance(definition, dict):+ continue+ key = definition.get("key")+ if not isinstance(key, str):+ continue+ value = values.get(key)+ if value in (None, ""):+ continue+ pairs.append((str(definition.get("label") or key), str(value)))+ return pairs+++def _format_tax_id(kind_value: str, value: str) -> tuple[str, str]:+ """A document as a person reads it, resolved through the pack.++ An unrecognised kind still renders — a stored value must never become+ unprintable because a pack changed underneath it.+ """+ try:+ kind = TaxIdKind(kind_value)+ except ValueError:+ return kind_value.upper(), value+ spec = spec_for(kind)+ # `label_key` is an i18n key; its last segment is a usable fallback for+ # a server-rendered PDF, which has no translator.+ label = spec.label_key.rsplit(".", 1)[-1].upper()+ # Masked here rather than by the reader: this structure feeds a PDF as+ # well as a screen, and the PDF has nobody to ask.+ return label, format_for_display(kind, value)+++async def build_document(+ session: AsyncSession,+ invoice: Invoice,+ settings: InvoiceSettings,+ workspace: Workspace,+) -> InvoiceDocument:+ from app.services import invoice_service++ snapshot = invoice.snapshot or {}+ snap_issuer = snapshot.get("issuer") or {}+ snap_client = snapshot.get("counterparty") or {}++ # Live settings are the fallback, never the override: an issued+ # document keeps what it captured.+ def issued_or_live(key: str, live: Any) -> Any:+ if snapshot and key in snap_issuer:+ return snap_issuer.get(key)+ return live++ # The issuer's documents, frozen like the rest of the issuer's+ # identity. Reading the live rows here was the one thing the snapshot+ # did not cover, so correcting a CNPJ next month silently rewrote the+ # CNPJ on an invoice a client received last month — the exact thing+ # freezing exists to prevent.+ #+ # Live rows still answer for a draft, and for a snapshot written+ # before this field existed, where the alternative is a document with+ # no tax id at all.+ snap_tax_ids = snap_issuer.get("tax_ids") if snapshot else None+ if snap_tax_ids is not None:+ issuer_tax_ids = [+ _format_tax_id(t["kind"], t["value"])+ for t in snap_tax_ids+ if isinstance(t, dict) and t.get("kind") and t.get("value")+ ]+ else:+ tax_rows = await session.execute(+ select(WorkspaceTaxId).where(WorkspaceTaxId.workspace_id == workspace.id)+ )+ issuer_tax_ids = [+ _format_tax_id(row.kind, row.value) for row in tax_rows.scalars().all()+ ]++ workspace_party = DocumentParty(+ name=issued_or_live("display_name", settings.issuer_display_name) or workspace.name,+ legal_name=issued_or_live("legal_name", workspace.legal_name),+ address=issued_or_live("address", workspace.address),+ tax_ids=issuer_tax_ids,+ )++ payee = invoice.payee+ counterparty = DocumentParty(+ name=snap_client.get("name") if snapshot else (payee.name if payee else None),+ address=snap_client.get("address") if snapshot else (payee.address if payee else None),+ email=snap_client.get("email") if snapshot else (payee.email if payee else None),+ tax_ids=[+ _format_tax_id(t["kind"], t["value"])+ for t in (snap_client.get("tax_ids") or [])+ if isinstance(t, dict) and t.get("kind") and t.get("value")+ ]+ if snapshot+ else [_format_tax_id(t.kind, t.value) for t in (payee.tax_ids if payee else [])],+ )++ # On a payable the supplier wrote the document and we received it, so+ # the blocks swap. Doing it once here rather than in each renderer is+ # what keeps the PDF and the screen from disagreeing about who is who+ # — and stops the product printing a supplier's bill under our own+ # name, which is the wrong claim to make on paper.+ payable = invoice.direction == "payable"+ issuer = counterparty if payable else workspace_party+ client = workspace_party if payable else counterparty++ template = snapshot.get("template") if snapshot else settings.template++ # An import arrives already named, and that name is reproduced+ # verbatim. Only a document we wrote takes our prefix: putting it on+ # someone else's reference would restyle their document into our+ # numbering.+ if invoice.origin == "imported":+ number = invoice.external_number or None+ elif invoice.number is not None:+ prefix = (snapshot.get("number_prefix") if snapshot else settings.number_prefix) or ""+ number = f"{prefix}{invoice.number}"+ else:+ number = None++ return InvoiceDocument(+ number=number,+ status=invoice.status,+ state=invoice_service.derive_state(invoice),+ issue_date=invoice.issue_date,+ due_date=invoice.due_date,+ 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),+ balance=invoice_service.balance(invoice),+ issuer=issuer,+ client=client,+ lines=[+ DocumentLine(+ description=line.description,+ quantity=line.quantity,+ unit=line.unit,++ unit_price=line.unit_price,+ total=line.total,+ tax_rate=line.tax_rate,+ )+ for line in invoice.lines+ ],+ # The workspace's own language, because the sender writes the+ # document. Once issued, the snapshot carries the resolved labels+ # and this is never consulted again — switching the interface to+ # English must not retitle a document already in a client's hands.+ labels=_label_map(template, snapshot.get("locale") if snapshot else workspace.locale),+ # Logo, accent, payment details and footer are the *issuer's*+ # identity, and on a payable the issuer is the supplier. Ours have+ # no business on their page: the logo would brand their document+ # with our mark, and payment details are worse than cosmetic —+ # printing our bank account under "pay to" on a bill we owe states+ # the opposite of what is true. We hold none of theirs, so the+ # blocks are simply left empty rather than filled with a stand-in.+ accent_color=(+ DEFAULT_ACCENT+ if payable+ else (issued_or_live("accent_color", settings.accent_color) or DEFAULT_ACCENT)+ ),+ # The id, not a URL: the two surfaces that draw this reach the+ # file by different routes — one authenticated, one behind a+ # share token — and neither should be hard-coded here.+ logo_id=(+ None+ if payable+ else (+ str(raw_logo)+ if (raw_logo := issued_or_live("logo_id", settings.logo_id))+ else None+ )+ ),+ payment_details=(+ None if payable else issued_or_live("payment_details", settings.payment_details)+ ),+ notes=invoice.notes,+ footer_note=None if payable else issued_or_live("footer_note", settings.footer_note),+ custom_fields=_custom_field_pairs(template, invoice.custom_fields),+ has_line_items=bool(invoice.lines),+ direction=invoice.direction,+ )+++def document_payload(document: InvoiceDocument) -> dict[str, Any]:+ """The document as JSON, for the on-screen renderer and the share page.++ Decimals become strings rather than floats: the frontend formats them+ with the workspace's locale, and a float would have already lost the+ cents by the time it got there.+ """+ return {+ "number": document.number,+ "status": document.status,+ "state": document.state,+ "issue_date": document.issue_date.isoformat(),+ "due_date": document.due_date.isoformat(),+ "currency": document.currency,+ "subtotal": str(document.subtotal),+ "discount": str(document.discount),+ "tax_total": str(document.tax_total),+ "total": str(document.total),+ "amount_paid": str(document.amount_paid),+ "balance": str(document.balance),+ "issuer": {+ "name": document.issuer.name,+ "legal_name": document.issuer.legal_name,+ "address": document.issuer.address,+ "tax_ids": [{"label": k, "value": v} for k, v in document.issuer.tax_ids],+ },+ "client": {+ "name": document.client.name,+ "address": document.client.address,+ "email": document.client.email,+ "tax_ids": [{"label": k, "value": v} for k, v in document.client.tax_ids],+ },+ "lines": [+ {+ "description": line.description,+ "quantity": str(line.quantity),+ "unit": line.unit,+ "unit_price": str(line.unit_price),+ "total": str(line.total),+ "tax_rate": str(line.tax_rate) if line.tax_rate is not None else None,+ }+ for line in document.lines+ ],+ "labels": document.labels,+ "accent_color": document.accent_color,+ "logo_id": document.logo_id,+ "payment_details": document.payment_details,+ "notes": document.notes,+ "footer_note": document.footer_note,+ "custom_fields": [{"label": k, "value": v} for k, v in document.custom_fields],+ "has_line_items": document.has_line_items,+ "direction": document.direction,+ }diff --git a/backend/app/services/invoice_logo_service.py b/backend/app/services/invoice_logo_service.pynew file mode 100644index 00000000..15a1c6d9--- /dev/null+++ b/backend/app/services/invoice_logo_service.py@@ -0,0 +1,135 @@+"""The workspace's mark, stored as a file it owns.++Three decisions, each of which removes a class of problem rather than+handling it:++ - **Uploaded, not linked.** A remote URL fetches the logo from a third+ party every time a document is drawn. On a self-hosted install that+ is a request leaving the building for an image the user already has,+ it breaks when that host does, and it lets a document's contents be+ changed by somebody who is not the user.++ - **Normalised to PNG.** Whatever arrives is decoded and re-encoded,+ which fixes the storage key's extension, gives the serving route one+ content type to answer with, and drops the metadata a photo carries+ (a logo exported from a phone can arrive with GPS coordinates in it).++ - **Bounded.** Scaled to fit a box no document needs to exceed. A+ 4000px mark makes every PDF heavier for a picture drawn 40px tall.+"""+import io+import uuid+from typing import Optional++from PIL import Image, UnidentifiedImageError+from PIL.Image import Resampling+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.invoice import InvoiceSettings+from app.providers import get_storage_provider++#: Roughly twice the largest box any renderer draws it in, so a screen at+#: two device pixels per CSS pixel still has real detail to show.+MAX_EDGE = 600++#: What a logo may cost to decode. Generous for a mark — a 6000 × 4000+#: photograph fits — and far below the point where one request can starve+#: the others.+MAX_PIXELS = 25_000_000++#: The formats a browser will render and Pillow will open. Anything else+#: is refused by name rather than failing later inside a decoder.+ACCEPTED = {"image/png", "image/jpeg", "image/webp", "image/gif"}+++def storage_key(workspace_id: uuid.UUID, logo_id: uuid.UUID) -> str:+ """Where a logo lives, derived rather than stored.++ Keeping the key computable from the id is what lets a snapshot freeze+ an id alone and still resolve to a file years later.+ """+ return f"{workspace_id}/invoices/logo/{logo_id}.png"+++def normalise(data: bytes, content_type: str) -> bytes:+ """Decode, bound and re-encode as PNG. Raises ValueError if unusable."""+ if content_type not in ACCEPTED:+ raise ValueError(+ f"'{content_type}' is not an image this can use. "+ "Use a PNG, JPEG, WebP or GIF."+ )+ try:+ image = Image.open(io.BytesIO(data))+ except (UnidentifiedImageError, OSError) as exc:+ raise ValueError("That file could not be read as an image.") from exc++ # Checked before `load`, which is what actually decodes. A 10,000 ×+ # 10,000 PNG of flat colour compresses to a few kilobytes and passes+ # every size limit above, then asks for hundreds of megabytes here —+ # and `thumbnail` only shrinks it afterwards, far too late.+ width, height = image.size+ if width * height > MAX_PIXELS:+ raise ValueError(+ f"That image is {width}×{height}. A logo may be at most "+ f"{MAX_PIXELS // 1_000_000} megapixels."+ )++ try:+ image.load()+ except (UnidentifiedImageError, OSError) as exc:+ raise ValueError("That file could not be read as an image.") from exc++ # RGBA throughout: a logo is normally transparent, and converting a+ # palette image without this flattens the transparency to black.+ if image.mode not in ("RGBA", "RGB"):+ image = image.convert("RGBA")+ image.thumbnail((MAX_EDGE, MAX_EDGE), Resampling.LANCZOS)++ out = io.BytesIO()+ # No EXIF is carried over: `save` writes only what is passed, and+ # nothing here passes the source's metadata.+ image.save(out, format="PNG", optimize=True)+ return out.getvalue()+++async def store(+ session: AsyncSession,+ settings: InvoiceSettings,+ workspace_id: uuid.UUID,+ data: bytes,+ content_type: str,+) -> uuid.UUID:+ """Put a new logo in place and return its id.++ The previous file is deliberately left where it is: invoices issued+ while it was current froze its id, and deleting it would repaint+ documents their recipients already hold.+ """+ png = normalise(data, content_type)+ logo_id = uuid.uuid4()+ storage = get_storage_provider()+ await storage.upload(storage_key(workspace_id, logo_id), png, "image/png")+ settings.logo_id = logo_id+ await session.flush()+ return logo_id+++async def read(workspace_id: uuid.UUID, logo_id: uuid.UUID) -> Optional[bytes]:+ """The bytes of one logo, or None if that id has no file."""+ storage = get_storage_provider()+ try:+ return await storage.download(storage_key(workspace_id, logo_id))+ except Exception:+ # A missing logo is a document without a mark on it, never a+ # failed render.+ return None+++async def clear(session: AsyncSession, settings: InvoiceSettings) -> None:+ """Stop using the current logo.++ The file stays for the same reason a replacement leaves it: documents+ issued under it still point at it.+ """+ settings.logo_id = None+ await session.flush()diff --git a/backend/app/services/invoice_pdf.py b/backend/app/services/invoice_pdf.pynew file mode 100644index 00000000..6d2d4a8e--- /dev/null+++ b/backend/app/services/invoice_pdf.py@@ -0,0 +1,506 @@+"""Lay out an `InvoiceDocument` as a PDF.++This module decides nothing about content. Everything it prints came+from `invoice_document.build_document`, which is the same structure the+web preview renders — so the two cannot drift into disagreeing about+what the invoice says.++ReportLab rather than an HTML-to-PDF engine: WeasyPrint and its peers+need pango, cairo and gdk-pixbuf present in the image, and this is a+self-hosted product where every native library is a cost paid by the+person running the server. ReportLab ships pure-Python wheels.++**The page has three bands, and that is the whole layout.**++ ┌──────────────────────────────┐+ │ header: title, number, rule │+ │ parties, dates │+ ├──────────────────────────────┤+ │ body: line items, totals │ ← grows, splits across pages+ │ │+ │ (whitespace) │+ ├──────────────────────────────┤+ │ footer: how to pay, notes │ ← pinned to the bottom margin+ │ footer note, page number │+ └──────────────────────────────┘++The footer is measured before the body is drawn and pinned to the bottom+margin, because that is where a reader looks for it on a real invoice.+Letting it follow the totals put "how to pay me" halfway up an otherwise+empty page, which is the layout this replaces.++The body splits when it does not fit. A long invoice is genuinely more+than one page, and the alternative — what this module did before — is+drawing line items off the bottom edge where nobody ever sees them.+"""+import io+from decimal import Decimal+from typing import Optional+from xml.sax.saxutils import escape++from reportlab.lib import colors+from reportlab.lib.enums import TA_RIGHT+from reportlab.lib.pagesizes import A4+from reportlab.lib.styles import ParagraphStyle+from reportlab.lib.units import mm+from reportlab.pdfgen import canvas as pdf_canvas+from reportlab.platypus import Paragraph, Table, TableStyle++from app.services.invoice_document import DEFAULT_ACCENT, InvoiceDocument++PAGE_WIDTH, PAGE_HEIGHT = A4+MARGIN = 18 * mm+CONTENT_WIDTH = PAGE_WIDTH - 2 * MARGIN+#: Breathing room between the body and the footer band. Without it a long+#: invoice's totals sit flush against the payment details.+FOOTER_GAP = 12 * mm++INK = colors.HexColor("#18181b")+MUTED = colors.HexColor("#71717a")+RULE = colors.HexColor("#e4e4e7")+++def _accent(value: Optional[str]) -> colors.Color:+ """The sender's colour, or the neutral ink when it is unusable.++ The value is user input reaching a PDF generator, so a malformed one+ must degrade rather than raise: an invoice that will not render is+ worse than an invoice in the wrong colour.+ """+ try:+ return colors.HexColor(value or DEFAULT_ACCENT)+ except Exception:+ return colors.HexColor(DEFAULT_ACCENT)+++def _money(amount: Decimal, currency: str) -> str:+ """Amount with its currency code.++ Deliberately not locale-formatted: the server has no reliable locale+ for the *reader*, who may be in a different country from the issuer,+ and a misplaced thousands separator on an invoice is worse than a+ plain one. The code is always shown so the number is unambiguous.+ """+ quantised = Decimal(amount).quantize(Decimal("0.01"))+ return f"{currency} {quantised:,.2f}"+++def _para(+ text: str,+ size: float = 9.5,+ color: colors.Color = INK,+ bold: bool = False,+ leading: Optional[float] = None,+ align: int = 0,+) -> Paragraph:+ style = ParagraphStyle(+ "cell",+ fontName="Helvetica-Bold" if bold else "Helvetica",+ fontSize=size,+ leading=leading or size * 1.45,+ textColor=color,+ alignment=align,+ )+ # Escaped, because everything reaching this function is somebody's+ # data — a client called "Alpha & Beta <Ltda>", a line reading+ # "R&D <phase 1>". ReportLab reads its argument as markup, so+ # unescaped text is not merely a crash risk: `<Ltda>` is silently+ # swallowed as an unknown tag and the client's name goes out on the+ # document truncated, with nothing to notice it by.+ #+ # The line break is applied after escaping, since it is the one piece+ # of markup this function means.+ return Paragraph(escape(text).replace("\n", "<br/>"), style)+++def _label(text: str) -> Paragraph:+ """A section label. Small, spaced, quiet — the same treatment the web+ preview gives it, so the two read as one design."""+ return _para(text.upper(), size=7, color=MUTED, bold=True, leading=9)+++def _stack(canvas, flowables: list, x: float, y: float, width: float) -> float:+ """Draw a stack of flowables downward from `y`, returning the new y."""+ for flowable in flowables:+ _, height = flowable.wrap(width, PAGE_HEIGHT)+ y -= height+ flowable.drawOn(canvas, x, y)+ return y+++def _stack_height(flowables: list, width: float) -> float:+ return sum(flowable.wrap(width, PAGE_HEIGHT)[1] for flowable in flowables)+++def _party_block(+ title: str,+ name: Optional[str],+ legal_name: Optional[str],+ address: Optional[str],+ email: Optional[str],+ tax_ids: list[tuple[str, str]],+) -> list:+ rows = [_label(title), _para("", size=3)]+ if name:+ rows.append(_para(name, size=10.5, bold=True))+ # Only when it differs: printing "Alpha ME / Alpha ME" reads as a bug.+ if legal_name and legal_name != name:+ rows.append(_para(legal_name, size=9, color=MUTED))+ for label, value in tax_ids:+ rows.append(_para(f"{label} {value}", size=9, color=MUTED))+ if address:+ rows.append(_para(address, size=9, color=MUTED))+ if email:+ rows.append(_para(email, size=9, color=MUTED))+ return rows+++# ---------------------------------------------------------------------------+# Bands+# ---------------------------------------------------------------------------+def _draw_header(canvas, document: InvoiceDocument, accent, logo_bytes) -> float:+ """Title, number and the accent rule. Returns the y below it."""+ y = PAGE_HEIGHT - MARGIN++ if logo_bytes:+ try:+ from reportlab.lib.utils import ImageReader++ image = ImageReader(io.BytesIO(logo_bytes))+ iw, ih = image.getSize()+ height = 13 * mm+ width = min(height * (iw / ih) if ih else height, 45 * mm)+ canvas.drawImage(+ image, MARGIN, y - height, width=width, height=height,+ mask="auto", preserveAspectRatio=True, anchor="sw",+ )+ y -= height + 5 * mm+ except Exception:+ # A broken image must not cost the whole document.+ pass++ canvas.setFont("Helvetica-Bold", 19)+ canvas.setFillColor(INK)+ canvas.drawString(MARGIN, y - 6.5 * mm, document.labels["invoice"])++ if document.number:+ canvas.setFont("Helvetica-Bold", 12.5)+ canvas.setFillColor(accent)+ canvas.drawRightString(PAGE_WIDTH - MARGIN, y - 6.5 * mm, document.number)++ y -= 10 * mm+ canvas.setStrokeColor(accent)+ canvas.setLineWidth(1.6)+ canvas.line(MARGIN, y, PAGE_WIDTH - MARGIN, y)+ return y - 9 * mm+++def _draw_parties_and_dates(canvas, document: InvoiceDocument, y: float) -> float:+ column = (CONTENT_WIDTH - 12 * mm) / 2+ left = _stack(+ canvas,+ _party_block(+ document.labels["from"], document.issuer.name, document.issuer.legal_name,+ document.issuer.address, None, document.issuer.tax_ids,+ ),+ MARGIN, y, column,+ )+ right = _stack(+ canvas,+ _party_block(+ document.labels["billTo"], document.client.name, None,+ document.client.address, document.client.email, document.client.tax_ids,+ ),+ MARGIN + column + 12 * mm, y, column,+ )+ y = min(left, right) - 9 * mm++ meta: list[tuple[str, str]] = [+ (document.labels["issueDate"], document.issue_date.isoformat()),+ (document.labels["dueDate"], document.due_date.isoformat()),+ *document.custom_fields,+ ]+ table = Table(+ [+ [_label(label) for label, _ in meta],+ [_para(value, size=9.5) for _, value in meta],+ ],+ colWidths=[CONTENT_WIDTH / len(meta)] * len(meta),+ )+ table.setStyle(TableStyle([+ ("VALIGN", (0, 0), (-1, -1), "TOP"),+ ("BOTTOMPADDING", (0, 0), (-1, 0), 3),+ ("TOPPADDING", (0, 0), (-1, -1), 0),+ ("LEFTPADDING", (0, 0), (-1, -1), 0),+ ("RIGHTPADDING", (0, 0), (-1, -1), 0),+ ]))+ _, height = table.wrap(CONTENT_WIDTH, PAGE_HEIGHT)+ y -= height+ table.drawOn(canvas, MARGIN, y)+ return y - 11 * mm+++def _lines_table(document: InvoiceDocument) -> Optional[Table]:+ if not document.lines:+ return None+ header = [+ _label(document.labels["description"]),+ _para(document.labels["quantity"].upper(), size=7, color=MUTED, bold=True, align=TA_RIGHT),+ _para(document.labels["unitPrice"].upper(), size=7, color=MUTED, bold=True, align=TA_RIGHT),+ _para(document.labels["amount"].upper(), size=7, color=MUTED, bold=True, align=TA_RIGHT),+ ]+ rows = [header]+ for line in document.lines:+ quantity = Decimal(line.quantity).normalize()+ # "12 hours", not "12": the unit is what lets the person paying+ # check the arithmetic against what they agreed to.+ counted = f"{quantity:f} {line.unit}" if line.unit else f"{quantity:f}"+ rows.append([+ _para(line.description),+ _para(counted, align=TA_RIGHT),+ _para(_money(line.unit_price, document.currency), align=TA_RIGHT),+ _para(_money(line.total, document.currency), align=TA_RIGHT),+ ])+ widths = [+ CONTENT_WIDTH * 0.46, CONTENT_WIDTH * 0.12,+ CONTENT_WIDTH * 0.21, CONTENT_WIDTH * 0.21,+ ]+ # `splitInRow` lets a single row break across pages. Without it a+ # description taller than one page cannot be split at all, and the+ # paginating loop below asks for a fresh page, fails again on the+ # empty page, and asks again — forever.+ table = Table(rows, colWidths=widths, 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), 6),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 6),+ ("LEFTPADDING", (0, 0), (-1, -1), 0),+ ("RIGHTPADDING", (0, 0), (-1, -1), 0),+ ]))+ return table+++def _totals_table(document: InvoiceDocument, accent) -> Table:+ rows: list[tuple[str, str, bool]] = []+ if document.lines:+ rows.append((document.labels["subtotal"], _money(document.subtotal, document.currency), False))+ if document.discount and document.discount > 0:+ rows.append((document.labels["discount"], f"-{_money(document.discount, document.currency)}", False))+ 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))+ rows.append((document.labels["balance"], _money(document.balance, document.currency), True))++ width = 74 * mm+ table = Table(+ [+ [+ _para(label, size=10 if strong else 9.5, bold=strong, color=INK if strong else MUTED),+ _para(+ value, size=11.5 if strong else 9.5, bold=strong,+ color=accent if strong else INK, align=TA_RIGHT,+ ),+ ]+ for label, value, strong in rows+ ],+ colWidths=[width * 0.5, width * 0.5],+ )+ style = [+ ("TOPPADDING", (0, 0), (-1, -1), 3.5),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 3.5),+ ("LEFTPADDING", (0, 0), (-1, -1), 0),+ ("RIGHTPADDING", (0, 0), (-1, -1), 0),+ ]+ for index, (_, _, strong) in enumerate(rows):+ if strong:+ style.append(("LINEABOVE", (0, index), (-1, index), 0.6, RULE))+ table.setStyle(TableStyle(style))+ return table+++def _footer_flowables(document: InvoiceDocument) -> tuple[Optional[Table], list]:+ """The bottom band: how to pay, notes, and the closing line.++ Payment details and notes sit side by side because they are read+ together and neither deserves the full width. Returns them separately+ from the closing note so the caller can rule between the two.+ """+ columns = []+ for title, body in (+ (document.labels["paymentDetails"], document.payment_details),+ (document.labels["notes"], document.notes),+ ):+ columns.append(+ [_label(title), _para("", size=2), _para(body, size=9.5)] if body else []+ )++ table = None+ if any(columns):+ width = (CONTENT_WIDTH - 10 * mm) / 2+ table = Table(+ [[columns[0] or "", columns[1] or ""]],+ colWidths=[width, width],+ )+ table.setStyle(TableStyle([+ ("VALIGN", (0, 0), (-1, -1), "TOP"),+ ("TOPPADDING", (0, 0), (-1, -1), 0),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 0),+ ("LEFTPADDING", (0, 0), (0, 0), 0),+ ("RIGHTPADDING", (-1, 0), (-1, 0), 0),+ ("LEFTPADDING", (-1, 0), (-1, 0), 10 * mm),+ ]))++ closing = [_para(document.footer_note, size=8.5, color=MUTED)] if document.footer_note else []+ return table, closing+++def _footer_height(footer: Optional[Table], closing: list) -> float:+ """How much the bottom band needs, so the body knows where to stop."""+ height = 0.0+ if footer is not None:+ height += footer.wrap(CONTENT_WIDTH, PAGE_HEIGHT)[1]+ if closing:+ if footer is not None:+ height += 6 * mm # the rule between the two+ height += _stack_height(closing, CONTENT_WIDTH)+ return height+++def _draw_footer(canvas, footer: Optional[Table], closing: list) -> None:+ """Pinned to the bottom margin, which is where a reader looks."""+ y = MARGIN+ if closing:+ y = _stack(canvas, closing, MARGIN, MARGIN + _stack_height(closing, CONTENT_WIDTH), CONTENT_WIDTH)+ y = MARGIN + _stack_height(closing, CONTENT_WIDTH) + 6 * mm+ if footer is not None:+ canvas.setStrokeColor(RULE)+ canvas.setLineWidth(0.5)+ canvas.line(MARGIN, y - 3 * mm, PAGE_WIDTH - MARGIN, y - 3 * mm)+ if footer is not None:+ footer.wrap(CONTENT_WIDTH, PAGE_HEIGHT)+ footer.drawOn(canvas, MARGIN, y)+++def _draw_page_number(canvas, page: int, total: int) -> None:+ """Only when there is more than one page. On a single-page invoice a+ "1 / 1" is noise that makes the document look generated."""+ if total <= 1:+ return+ canvas.setFont("Helvetica", 8)+ canvas.setFillColor(MUTED)+ canvas.drawRightString(PAGE_WIDTH - MARGIN, MARGIN - 5 * mm, f"{page} / {total}")+++# ---------------------------------------------------------------------------+# Render+# ---------------------------------------------------------------------------+def render_pdf(document: InvoiceDocument, logo_bytes: Optional[bytes] = None) -> bytes:+ """The document as PDF bytes.++ `logo_bytes` is passed in rather than fetched here: this function does+ no I/O, which keeps it trivially testable and keeps a slow or hostile+ URL from being reachable from inside a renderer.+ """+ 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())++ footer, closing = _footer_flowables(document)+ footer_height = _footer_height(footer, closing)+ floor = MARGIN + footer_height + FOOTER_GAP++ lines = _lines_table(document)+ totals = _totals_table(document, accent)+ totals_height = totals.wrap(74 * mm, PAGE_HEIGHT)[1]++ # Page 1 header is the full masthead; continuations get a slim one, so+ # a reader who picks up page 3 still knows what they are holding.+ 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++ y -= 8 * mm+ totals.drawOn(canvas, PAGE_WIDTH - MARGIN - 74 * mm, y - totals_height)++ _draw_footer(canvas, footer, closing)+ total_pages = len(pages) + 1+ _draw_page_number(canvas, total_pages, total_pages)+ canvas.showPage()++ canvas.save()+ return buffer.getvalue()+++def _draw_continuation_header(canvas, document: InvoiceDocument, accent) -> float:+ """A slim masthead for pages 2+.++ Enough to identify the document without repeating the whole party+ block, which on a continuation page is filler.+ """+ y = PAGE_HEIGHT - MARGIN+ canvas.setFont("Helvetica-Bold", 11)+ canvas.setFillColor(INK)+ canvas.drawString(MARGIN, y - 4 * mm, document.labels["invoice"])+ if document.number:+ canvas.setFont("Helvetica-Bold", 11)+ canvas.setFillColor(accent)+ canvas.drawRightString(PAGE_WIDTH - MARGIN, y - 4 * mm, document.number)+ y -= 7 * mm+ canvas.setStrokeColor(RULE)+ canvas.setLineWidth(0.6)+ canvas.line(MARGIN, y, PAGE_WIDTH - MARGIN, y)+ return y - 7 * mmdiff --git a/backend/app/services/invoice_service.py b/backend/app/services/invoice_service.pynew file mode 100644index 00000000..992b2857--- /dev/null+++ b/backend/app/services/invoice_service.py@@ -0,0 +1,1092 @@+"""Invoice ledger: issuing, settling, and reading what is owed.++The one rule this module exists to enforce: **stored status is a+decision, derived status is a fact**. Four stored values (`draft`,+`open`, `void`, `uncollectible`) record what a person did. Everything a+reader actually wants to know — is it paid, partly paid, late, how late+— is computed here, from allocations and the due date, every time it is+asked for.++The cost of the alternative is visible in every peer product that stores+`overdue`: a nightly job to set it, compensating SQL to unset it when a+due date moves, and a permanent tax on every query downstream that has+to remember the state is really two states.+"""+import secrets+import uuid+from datetime import date as _date, datetime, timedelta, timezone+from decimal import Decimal+from typing import Any, Literal, Optional++from sqlalchemy import Select, func, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import selectinload++from app.fiscal.registry import TaxIdKind, normalise_and_validate+from app.models.invoice import (+ MANUAL_METHOD,+ Invoice,+ InvoiceAllocation,+ InvoiceLine,+ InvoiceSettings,+)+from app.models.payee import Payee+from app.models.transaction import Transaction+from app.models.workspace import Workspace, WorkspaceTaxId+# Safe at module level: the attachment service reaches for models and the+# storage provider, never back into this one.+from app.services import invoice_attachment_service++ZERO = Decimal("0.00")+++class InvoiceError(Exception):+ """A rule of the ledger was broken.++ Carries a stable `code` so the API layer maps it to a status without+ matching on prose, and the frontend translates it without parsing+ English.+ """++ def __init__(self, code: str, message: str, status_code: int = 400) -> None:+ super().__init__(message)+ self.code = code+ self.message = message+ self.status_code = status_code+++# ---------------------------------------------------------------------------+# Settings+# ---------------------------------------------------------------------------+#: What each preset fills in. The preset is a starting point, not a mode:+#: after it is applied every field is individually overridable, and the+#: stored row is what the rest of the code reads.+PRESETS: dict[str, dict[str, Any]] = {+ # The NFS-e was issued at the prefeitura, the EU invoice will be+ # issued elsewhere, or there is no document at all — the user only+ # wants the money tracked.+ "tracking": {"document_required": False, "initial_state": "open", "tax_fields": "hidden"},+ # The invoice *is* the deliverable. Starts as a draft because a+ # document is written before it is sent, and an EU B2B invoice+ # without discriminated VAT is not a valid invoice.+ "document": {"document_required": True, "initial_state": "draft", "tax_fields": "optional"},+}+++async def _settings_for_update(+ session: AsyncSession, workspace_id: uuid.UUID+) -> InvoiceSettings:+ """The settings row, locked for the length of the transaction.++ Numbering has to be allocated by the database, not by application+ code: two invoices issued at the same instant would otherwise read+ the same `next_number` and one of them would die on the unique+ constraint. The row lock makes the second wait rather than fail.++ `with_for_update` renders nothing on SQLite, which the test suite+ uses. That is acceptable because the guarantee is still there in+ production, and the unique constraint remains the backstop in both.+ """+ await get_settings(session, workspace_id) # ensure the row exists+ result = await session.execute(+ select(InvoiceSettings)+ .where(InvoiceSettings.workspace_id == workspace_id)+ .with_for_update()+ )+ return result.scalar_one()+++async def get_settings(session: AsyncSession, workspace_id: uuid.UUID) -> InvoiceSettings:+ """This workspace's settings, creating the default row on first read.++ Lazily created rather than seeded at workspace creation: a personal+ workspace never opens this module, and a row it will never read is a+ row that still has to be migrated forever.+ """+ result = await session.execute(+ select(InvoiceSettings).where(InvoiceSettings.workspace_id == workspace_id)+ )+ settings = result.scalar_one_or_none()+ if settings is not None:+ return settings++ settings = InvoiceSettings(workspace_id=workspace_id, preset="tracking", **PRESETS["tracking"])+ session.add(settings)+ await session.flush()+ return settings+++#: Fields a caller may blank out deliberately. Everything else ignores a+#: null, so a partial update never wipes what it did not mention.+_NULLABLE_SETTINGS = (+ "issuer_display_name", "footer_note", "series", "number_prefix",+ "payment_details", "accent_color",+)+++async def update_settings(+ session: AsyncSession, workspace_id: uuid.UUID, data: dict[str, Any]+) -> InvoiceSettings:+ settings = await get_settings(session, workspace_id)++ # A preset change refills the three fields it owns, then any explicit+ # values in the same request win over it — so "switch to document but+ # keep tax hidden" is one call, not two.+ preset = data.get("preset")+ if preset and preset != settings.preset:+ for key, value in PRESETS[preset].items():+ setattr(settings, key, value)++ for key, value in data.items():+ if value is not None or key in _NULLABLE_SETTINGS:+ setattr(settings, key, value)++ await session.flush()+ return settings+++# ---------------------------------------------------------------------------+# Issuer identity — the workspace describing itself+# ---------------------------------------------------------------------------+async def get_issuer_tax_ids(+ session: AsyncSession, workspace_id: uuid.UUID+) -> list[WorkspaceTaxId]:+ result = await session.execute(+ select(WorkspaceTaxId)+ .where(WorkspaceTaxId.workspace_id == workspace_id)+ .order_by(WorkspaceTaxId.created_at)+ )+ return list(result.scalars().all())+++async def set_issuer_tax_ids(+ session: AsyncSession, workspace_id: uuid.UUID, incoming: list[dict[str, Any]]+) -> list[WorkspaceTaxId]:+ """Replace this workspace's fiscal documents with `incoming`.++ Replace rather than merge, exactly as the payee side does: the caller+ sends the set that should remain, which makes removing a document the+ same operation as changing one. Validation goes through the same named+ validators — one implementation, asserted from both call sites.+ """+ normalised: dict[TaxIdKind, str] = {}+ for item in incoming:+ kind = TaxIdKind(item["kind"])+ value, error = normalise_and_validate(kind, item["value"])+ # An emptied field means "drop this document", not "store nothing".+ if error == "empty":+ continue+ if error:+ raise InvoiceError(+ f"invalid_tax_id:{kind.value}:{error}",+ f"That does not look like a valid {kind.value.upper()}",+ )+ normalised[kind] = value++ existing = {row.kind: row for row in await get_issuer_tax_ids(session, workspace_id)}+ for kind_value, row in existing.items():+ if TaxIdKind(kind_value) not in normalised:+ await session.delete(row)+ for kind, value in normalised.items():+ row = existing.get(kind.value)+ if row is not None:+ row.value = value+ else:+ session.add(+ WorkspaceTaxId(workspace_id=workspace_id, kind=kind.value, value=value)+ )+ await session.flush()+ return await get_issuer_tax_ids(session, workspace_id)+++# ---------------------------------------------------------------------------+# Derived state — the whole point+# ---------------------------------------------------------------------------+def allocated_total(invoice: Invoice) -> Decimal:+ return sum((a.amount for a in invoice.allocations), ZERO)+++def balance(invoice: Invoice) -> Decimal:+ return (invoice.total or ZERO) - allocated_total(invoice)+++#: What a reader sees: the three terminal decisions, plus the four facts+#: computed from allocations and the due date. Mirrors `InvoiceState` in+#: `schemas/invoice.py`, which is what the API actually returns.+DerivedState = Literal[+ "draft", "open", "partial", "paid", "overdue", "void", "uncollectible"+]+++def derive_state(invoice: Invoice, today: Optional[_date] = None) -> DerivedState:+ """What a reader wants to know, computed rather than stored.++ Returns one of: `draft`, `void`, `uncollectible`, `paid`, `partial`,+ `overdue`, `open`. The first three are the stored decisions passing+ straight through; the rest are facts about money and time.++ Order matters. A decision always wins over a fact — a voided invoice+ is not overdue, and an uncollectible one is not "partial" just+ because something was received against it before the client went+ under.+ """+ if invoice.status == "draft":+ return "draft"+ if invoice.status == "void":+ return "void"+ if invoice.status == "uncollectible":+ return "uncollectible"++ remaining = balance(invoice)+ if remaining <= ZERO:+ return "paid"++ reference = today or datetime.now(timezone.utc).date()+ if invoice.due_date and invoice.due_date < reference:+ return "overdue"+ return "partial" if allocated_total(invoice) > ZERO else "open"+++def days_overdue(invoice: Invoice, today: Optional[_date] = None) -> int:+ reference = today or datetime.now(timezone.utc).date()+ if derive_state(invoice, reference) != "overdue":+ return 0+ return (reference - invoice.due_date).days+++# ---------------------------------------------------------------------------+# Reading+# ---------------------------------------------------------------------------+#: The side of the ledger everything currently written belongs to.+#: Every read narrows to one side: leaving it out would show a supplier's+#: bill inside "what clients owe me", which is not a filtering nicety but+#: a wrong number.+DEFAULT_DIRECTION = "receivable"+++def _base_query(direction: str = DEFAULT_DIRECTION) -> Select:+ return (+ select(Invoice)+ .where(Invoice.direction == direction)+ .options(+ selectinload(Invoice.lines),+ selectinload(Invoice.allocations),+ )+ )+++async def find_by_external_id(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ external_source: Optional[str],+ external_id: Optional[str],+) -> Optional[Invoice]:+ """The row that already holds this external document, if any.++ The lookup an importer does before writing, and the one the duplicate+ handler does after the database refuses. Both sides need it, which is+ why it is not buried in either.+ """+ if not external_source or not external_id:+ return None+ result = await session.execute(+ select(Invoice).where(+ Invoice.workspace_id == workspace_id,+ Invoice.external_source == external_source,+ Invoice.external_id == external_id,+ )+ )+ return result.scalar_one_or_none()+++async def get_invoice(+ session: AsyncSession, invoice_id: uuid.UUID, workspace_id: uuid.UUID+) -> Optional[Invoice]:+ # Not narrowed by direction: an id already identifies one row, and+ # scoping here would 404 a payable a caller legitimately asked for.+ result = await session.execute(+ select(Invoice)+ .options(selectinload(Invoice.lines), selectinload(Invoice.allocations))+ .where(Invoice.id == invoice_id, Invoice.workspace_id == workspace_id)+ )+ return result.unique().scalar_one_or_none()+++async def list_invoices(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ *,+ state: Optional[str] = None,+ year: Optional[int] = None,+ direction: str = DEFAULT_DIRECTION,+ payee_id: Optional[uuid.UUID] = None,+ q: Optional[str] = None,+ limit: int = 100,+ offset: int = 0,+) -> list[Invoice]:+ """Invoices, newest first, optionally filtered by *derived* state.++ The state filter is applied in Python rather than SQL. That is a+ deliberate trade for this slice: the derived states depend on summed+ allocations, and one honest pass over a workspace's invoices beats a+ correlated subquery that would have to be kept in sync with+ `derive_state` by hand. When a workspace grows past a few thousand+ invoices this becomes a materialized balance column — and the single+ definition here is what makes that change safe.+ """+ query = _base_query(direction).where(+ Invoice.workspace_id == workspace_id,+ Invoice.document_type == "invoice",+ )+ query = _apply_year(query, year)+ if payee_id:+ query = query.where(Invoice.payee_id == payee_id)+ if q:+ pattern = f"%{q.lower()}%"+ query = query.where(func.lower(Invoice.notes).like(pattern))++ query = query.order_by(Invoice.issue_date.desc(), Invoice.created_at.desc())+ result = await session.execute(query)+ invoices = list(result.unique().scalars().all())++ if state:+ invoices = [inv for inv in invoices if derive_state(inv) == state]+ return invoices[offset : offset + limit]+++def _apply_year(query: Select, year: Optional[int]) -> Select:+ """Narrow to one calendar year, by issue date.++ Issue date rather than competence: "the 2025 invoices" means the ones+ issued in 2025, which is what a person scanning a list is asking for.+ The accrual date is the accountant's axis and belongs in a report,+ not in a browse filter.+ """+ if year is None:+ return query+ return query.where(+ Invoice.issue_date >= _date(year, 1, 1),+ Invoice.issue_date <= _date(year, 12, 31),+ )+++#: What the filter bar offers, and what each one counts. `overdue` is a+#: subset of `open` on purpose — these are filters, not a partition, and+#: a freelancer wants to jump straight to the late ones.+FACET_STATES: dict[str, tuple[str, ...]] = {+ "all": (),+ "open": ("open", "partial", "overdue"),+ "overdue": ("overdue",),+ "paid": ("paid",),+ "draft": ("draft",),+}+++async def facets(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ year: Optional[int] = None,+ direction: str = DEFAULT_DIRECTION,+) -> dict[str, Any]:+ """What the filter bar needs: which years exist, and how many in each state.++ One call rather than one per chip. The counts come from the same+ derived state the list uses, so a chip that says 3 opens a list of+ exactly 3 — a count computed a second way is a count that eventually+ disagrees.+ """+ years_result = await session.execute(+ select(func.extract("year", Invoice.issue_date))+ .where(+ Invoice.workspace_id == workspace_id,+ Invoice.document_type == "invoice",+ Invoice.direction == direction,+ )+ .distinct()+ )+ years = sorted((int(row[0]) for row in years_result.all()), reverse=True)++ result = await session.execute(+ _apply_year(+ _base_query(direction).where(+ Invoice.workspace_id == workspace_id,+ Invoice.document_type == "invoice",+ ),+ year,+ )+ )+ invoices = list(result.unique().scalars().all())+ states = [derive_state(invoice) for invoice in invoices]++ counts = {+ facet: len(invoices) if not wanted else sum(1 for s in states if s in wanted)+ for facet, wanted in FACET_STATES.items()+ }+ return {"years": years, "counts": counts}+++async def aging_summary(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ today: Optional[_date] = None,+ direction: str = DEFAULT_DIRECTION,+) -> dict[str, Any]:+ """A receber · vencidas · recebido no mês · próximos vencimentos.++ Drafts are excluded from every figure — a document nobody has issued+ is not money anybody owes. Voided and uncollectible invoices are+ excluded for the same reason, one decision later.+ """+ reference = today or datetime.now(timezone.utc).date()+ result = await session.execute(+ _base_query(direction).where(+ Invoice.workspace_id == workspace_id,+ Invoice.document_type == "invoice",+ Invoice.status == "open",+ )+ )+ invoices = list(result.unique().scalars().all())++ outstanding = ZERO+ overdue_amount = ZERO+ overdue_count = 0+ upcoming: list[Invoice] = []+ # Aging buckets in days past due, the shape every accountant expects.+ buckets = {"current": ZERO, "d1_30": ZERO, "d31_60": ZERO, "d61_90": ZERO, "d90_plus": ZERO}++ for invoice in invoices:+ remaining = balance(invoice)+ if remaining <= ZERO:+ continue+ outstanding += remaining+ overdue_days = days_overdue(invoice, reference)+ if overdue_days > 0:+ overdue_amount += remaining+ overdue_count += 1+ if overdue_days <= 30:+ buckets["d1_30"] += remaining+ elif overdue_days <= 60:+ buckets["d31_60"] += remaining+ elif overdue_days <= 90:+ buckets["d61_90"] += remaining+ else:+ buckets["d90_plus"] += remaining+ else:+ buckets["current"] += remaining+ upcoming.append(invoice)++ # Money that actually arrived this month, by the date it arrived —+ # the cash view. The accrual view reads `competence_date` instead,+ # which is why both are stored.+ month_start = reference.replace(day=1)+ received_this_month = ZERO+ for invoice in invoices:+ for allocation in invoice.allocations:+ allocated_on = allocation.allocated_at.date()+ if month_start <= allocated_on <= reference:+ received_this_month += allocation.amount++ upcoming.sort(key=lambda i: i.due_date)+ return {+ "outstanding": outstanding,+ "overdue_amount": overdue_amount,+ "overdue_count": overdue_count,+ "received_this_month": received_this_month,+ "buckets": buckets,+ "upcoming": upcoming[:5],+ }+++# ---------------------------------------------------------------------------+# Writing+# ---------------------------------------------------------------------------+def _line_total(quantity: Decimal, unit_price: Decimal) -> Decimal:+ return (Decimal(quantity) * Decimal(unit_price)).quantize(Decimal("0.01"))+++def _recompute_totals(invoice: Invoice) -> None:+ """Totals follow the lines when there are lines, and the caller when+ there are not.++ Under the `tracking` preset an invoice is three fields — "Fulano me+ deve R$3.000" — and its total is simply what the user typed. Once+ lines exist they are the source of truth, because two places holding+ the same number is how they end up disagreeing.+ """+ if not invoice.lines:+ return+ subtotal = sum((line.total for line in invoice.lines), ZERO)+ tax_total = sum(+ (+ (line.total * (line.tax_rate or ZERO) / Decimal("100")).quantize(Decimal("0.01"))+ for line in invoice.lines+ ),+ ZERO,+ )+ invoice.subtotal = subtotal+ invoice.tax_total = tax_total+ total = subtotal - (invoice.discount or ZERO) + tax_total+ # Refused here rather than left to the CHECK. A discount larger than+ # what is being billed is a typo, and the database answering it with+ # an IntegrityError turns a correctable mistake into a 500 the client+ # cannot branch on.+ if total < ZERO:+ raise InvoiceError(+ "discount_exceeds_total",+ "The discount is larger than the amount being billed",+ )+ invoice.total = total+++async def _assert_payee(+ session: AsyncSession, payee_id: Optional[uuid.UUID], workspace_id: uuid.UUID+) -> Optional[Payee]:+ if payee_id is None:+ return None+ result = await session.execute(+ select(Payee).where(Payee.id == payee_id, Payee.workspace_id == workspace_id)+ )+ payee = result.scalar_one_or_none()+ if payee is None:+ raise InvoiceError("payee_not_found", "Payee not found in this workspace", 404)+ return payee+++def _build_line(invoice: Invoice, line: dict[str, Any], position: int) -> InvoiceLine:+ quantity = Decimal(str(line.get("quantity", 1)))+ unit_price = Decimal(str(line.get("unit_price", 0)))+ return InvoiceLine(+ invoice_id=invoice.id,+ workspace_id=invoice.workspace_id,+ description=line["description"],+ quantity=quantity,+ unit=(line.get("unit") or None),+ unit_price=unit_price,+ tax_rate=Decimal(str(line["tax_rate"])) if line.get("tax_rate") is not None else None,+ total=_line_total(quantity, unit_price),+ position=position,+ )+++async def create_invoice(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ user_id: uuid.UUID,+ data: dict[str, Any],+) -> Invoice:+ settings = await get_settings(session, workspace_id)+ await _assert_payee(session, data.get("payee_id"), workspace_id)++ lines_data = data.pop("lines", None) or []+ if settings.document_required and not lines_data:+ raise InvoiceError(+ "lines_required", "This workspace requires invoices to carry line items"+ )++ # Provenance is declared, never inferred: a row that says `imported`+ # has to say what it was imported from, or the pair that makes a+ # re-sync converge on one row is missing and the second sync creates+ # a duplicate instead of updating.+ origin = data.get("origin") or "local"+ if origin == "imported" and not data.get("external_source"):+ raise InvoiceError(+ "external_source_required",+ "An imported document must say where it came from",+ )++ issue_date = data.get("issue_date") or datetime.now(timezone.utc).date()+ due_date = data.get("due_date")+ if due_date is None:+ due_date = issue_date + timedelta(days=settings.default_payment_terms_days)+ if due_date < issue_date:+ raise InvoiceError("due_before_issue", "Due date cannot precede the issue date")++ invoice = Invoice(+ workspace_id=workspace_id,+ user_id=user_id,+ payee_id=data.get("payee_id"),+ issue_date=issue_date,+ due_date=due_date,+ # Defaults to the issue date, and stays its own field so an+ # accrual-basis report can disagree with the invoice date.+ competence_date=data.get("competence_date") or issue_date,+ currency=data.get("currency") or "USD",+ discount=data.get("discount") or ZERO,+ subtotal=data.get("subtotal") or ZERO,+ tax_total=data.get("tax_total") or ZERO,+ total=data.get("total") or ZERO,+ direction=data.get("direction") or DEFAULT_DIRECTION,+ origin=origin,+ external_source=data.get("external_source"),+ external_id=data.get("external_id"),+ # Only an import has one. On a local document our own counter+ # names it, and a second name would be a second answer to the+ # same question.+ external_number=(data.get("external_number") if origin == "imported" else None),+ notes=data.get("notes"),+ internal_notes=data.get("internal_notes"),+ custom_fields=data.get("custom_fields"),+ status="draft",+ )+ session.add(invoice)+ try:+ await session.flush()+ except IntegrityError:+ # The unique (workspace, source, external id) is what makes a+ # re-sync converge on one row instead of duplicating. Answer with+ # the row that already holds this document so a caller can update+ # it rather than guess, and so a retried import is a no-op rather+ # than a crash.+ await session.rollback()+ existing = await find_by_external_id(+ session, workspace_id, data.get("external_source"), data.get("external_id")+ )+ where = f" as {existing.number}" if existing and existing.number else ""+ raise InvoiceError(+ "already_imported",+ f"This document is already here{where}",+ status_code=409,+ ) from None++ for position, line in enumerate(lines_data):+ session.add(_build_line(invoice, line, position))+ await session.flush()+ await session.refresh(invoice, ["lines", "allocations", "payee"])+ _recompute_totals(invoice)++ # `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+ # self is ceremony.+ #+ # `as_draft` is the caller saying they are not finished — a document+ # half written, to be picked up later. It overrides the preset,+ # because the preset is a default about the common case and this is+ # someone stating the uncommon one.+ #+ # An import is exempt either way: somebody issued it elsewhere, and+ # `draft` would claim we are still writing a document we received.+ wants_draft = bool(data.get("as_draft"))+ if (settings.initial_state == "open" and not wants_draft) or invoice.origin == "imported":+ if (invoice.total or ZERO) <= ZERO:+ raise InvoiceError("empty_total", "An invoice with no value cannot be issued")+ locked = await _settings_for_update(session, workspace_id)+ workspace = await session.get(Workspace, workspace_id)+ _issue(invoice, locked, workspace, await _snapshot_tax_ids(session, workspace_id))++ await session.flush()+ return invoice+++#: Financial substance. Editable while a draft, frozen once issued: the+#: document has left the building, and a total that changes after the+#: client received it is not an edit, it is a second document.+_DRAFT_ONLY_FIELDS = (+ "payee_id", "issue_date", "due_date", "competence_date", "currency",+ "discount", "subtotal", "tax_total", "total",+)+#: The seller's own record, editable at any time.+_ALWAYS_EDITABLE = ("notes", "internal_notes", "custom_fields")+++async def update_invoice(session: AsyncSession, invoice: Invoice, data: dict[str, Any]) -> Invoice:+ if invoice.status in ("void", "uncollectible"):+ raise InvoiceError("terminal_status", f"A {invoice.status} invoice cannot be edited")++ if invoice.status == "draft":+ if data.get("payee_id") is not None:+ await _assert_payee(session, data["payee_id"], invoice.workspace_id)+ lines_data = data.pop("lines", None)+ for field in _DRAFT_ONLY_FIELDS:+ if data.get(field) is not None:+ setattr(invoice, field, data[field])++ if lines_data is not None:+ for line in list(invoice.lines):+ await session.delete(line)+ await session.flush()+ await session.refresh(invoice, ["lines"])+ for position, line in enumerate(lines_data):+ session.add(_build_line(invoice, line, position))+ await session.flush()+ await session.refresh(invoice, ["lines"])+ _recompute_totals(invoice)++ if invoice.due_date < invoice.issue_date:+ raise InvoiceError("due_before_issue", "Due date cannot precede the issue date")+ else:+ 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:+ raise InvoiceError(+ "issued_invoice_immutable",+ "An issued invoice's financial fields cannot change — void it and issue a new one",+ )++ for field in _ALWAYS_EDITABLE:+ if field in data:+ setattr(invoice, field, data[field])++ await session.flush()+ return invoice+++async def _snapshot_tax_ids(+ session: AsyncSession, workspace_id: uuid.UUID+) -> list[dict[str, str]]:+ """The issuer's tax documents, in the shape the snapshot stores.++ Read at issuance and frozen, for the same reason as the rest of the+ issuer block: correcting a CNPJ next month must not rewrite the CNPJ+ on an invoice a client received last month.+ """+ return [+ {"kind": row.kind, "value": row.value}+ for row in await get_issuer_tax_ids(session, workspace_id)+ ]+++def _build_snapshot(+ invoice: Invoice,+ settings: InvoiceSettings,+ workspace: Optional[Workspace] = None,+ issuer_tax_ids: Optional[list[dict[str, str]]] = None,+) -> dict[str, Any]:+ """Freeze what the document said about itself.++ Read at render time instead of the live settings and the live payee,+ so changing a logo in September leaves August's invoice exactly as+ the client received it.+ """+ payee = invoice.payee+ return {+ "issuer": {+ "display_name": settings.issuer_display_name,+ "legal_name": workspace.legal_name if workspace else None,+ "address": workspace.address if workspace else None,+ "tax_ids": issuer_tax_ids or [],+ "logo_id": str(settings.logo_id) if settings.logo_id else None,+ "footer_note": settings.footer_note,+ "payment_details": settings.payment_details,+ "accent_color": settings.accent_color,+ },+ "counterparty": {+ "name": payee.name if payee else None,+ "email": payee.email if payee else None,+ "address": payee.address if payee else None,+ # The client's documents as they stood on the day. A CNPJ+ # corrected next month must not appear on a document the+ # client already holds showing the old one.+ "tax_ids": [+ {"kind": t.kind, "value": t.value} for t in (payee.tax_ids if payee else [])+ ],+ },+ "template": settings.template or {},+ # The language the document was written in. Frozen with the rest:+ # a workspace that later switches its interface must not retitle+ # an invoice the client already holds.+ "locale": workspace.locale if workspace else None,+ "number_prefix": settings.number_prefix,+ "frozen_at": datetime.now(timezone.utc).isoformat(),+ }+++def _issue(+ invoice: Invoice,+ settings: InvoiceSettings,+ workspace: Optional[Workspace] = None,+ issuer_tax_ids: Optional[list[dict[str, str]]] = None,+) -> None:+ """Open the invoice, numbering and freezing it only if it is ours.++ **Numbering.** Our counter only ever moves forward, and a voided+ invoice keeps the number it consumed: reusing one would put two+ documents under a single identifier, which every jurisdiction that+ regulates numbering forbids and no other would thank us for.++ An **imported** document is exempt from all of that. It already has+ an identity — the source called it something — so taking a number+ from our sequence would burn one that is supposed to be gapless and+ rename a document its recipient already holds under another name. It+ keeps whatever number came with it, or none.++ **Snapshot.** Freezing our issuer identity is a record of what *we*+ put on a document at the moment we issued it. On an imported row+ somebody else issued it and we are keeping a record, so the same+ freeze would stamp our details onto a page we did not write and give+ it a date that means nothing. The attached file is that document; the+ snapshot is for ours.+ """+ local = invoice.origin == "local"+ if local:+ invoice.number = settings.next_number+ invoice.series = settings.series+ settings.next_number += 1+ invoice.snapshot = _build_snapshot(invoice, settings, workspace, issuer_tax_ids)+ invoice.status = "open"+++async def issue_invoice(session: AsyncSession, invoice: Invoice) -> Invoice:+ if invoice.status != "draft":+ raise InvoiceError("not_a_draft", "Only a draft can be issued")+ settings = await get_settings(session, invoice.workspace_id)+ if settings.document_required and not invoice.lines:+ raise InvoiceError("lines_required", "This workspace requires invoices to carry line items")+ if (invoice.total or ZERO) <= ZERO:+ raise InvoiceError("empty_total", "An invoice with no value cannot be issued")+ locked = await _settings_for_update(session, invoice.workspace_id)+ workspace = await session.get(Workspace, invoice.workspace_id)+ _issue(+ invoice, locked, workspace, await _snapshot_tax_ids(session, invoice.workspace_id)+ )+ await session.flush()+ return invoice+++async def void_invoice(session: AsyncSession, invoice: Invoice) -> Invoice:+ """Cancel an issued invoice, keeping its paper trail.++ Not a delete. The number stays taken, the row stays readable, and+ every total treats it as zero. Deleting it would leave a gap nobody+ could explain later — which is precisely what numbering rules exist+ to prevent.+ """+ if invoice.status == "draft":+ raise InvoiceError("draft_not_voidable", "Delete the draft instead of voiding it")+ if invoice.status == "void":+ return invoice+ if invoice.allocations:+ raise InvoiceError(+ "void_with_allocations", "Unlink the payments before voiding this invoice"+ )+ invoice.status = "void"+ await session.flush()+ return invoice+++async def mark_uncollectible(session: AsyncSession, invoice: Invoice) -> Invoice:+ """Give up on collecting. The whole-invoice decision.++ Distinct from a partial write-off, which is a deduction and arrives+ with the matching work. The two must never coexist on one invoice:+ one decision, one mechanism.+ """+ if invoice.status != "open":+ raise InvoiceError("not_open", "Only an open invoice can be written off")+ invoice.status = "uncollectible"+ await session.flush()+ return invoice+++async def reopen_invoice(session: AsyncSession, invoice: Invoice) -> Invoice:+ """Undo an uncollectible decision — the client paid after all."""+ if invoice.status != "uncollectible":+ raise InvoiceError("not_uncollectible", "Only an uncollectible invoice can be reopened")+ invoice.status = "open"+ await session.flush()+ return invoice+++async def delete_invoice(session: AsyncSession, invoice: Invoice) -> None:+ if invoice.status != "draft":+ raise InvoiceError(+ "only_drafts_deletable", "An issued invoice is never deleted — void it instead"+ )+ # The attachment rows go with the invoice through the cascade, but the+ # stored files have to be asked for by name — nothing in the database+ # reaches into the storage provider. Left out, every deleted draft+ # would leave its uploads behind forever.+ await invoice_attachment_service.cleanup_files(session, invoice.id)+ await session.delete(invoice)+ await session.flush()+++# ---------------------------------------------------------------------------+# Allocations+# ---------------------------------------------------------------------------+async def allocate(+ session: AsyncSession,+ invoice: Invoice,+ transaction_id: uuid.UUID,+ amount: Optional[Decimal] = None,+ method: str = MANUAL_METHOD,+) -> InvoiceAllocation:+ """Bind money to debt. **This is the apply step, never the deciding one.**++ Automatic matching will decide in a separate, pure function that reads+ the reconciliation policy and returns a decision plus a trace; this is+ what it calls once a human or that decision has settled the question.+ Keeping the two apart is what lets the matcher be dry-run and previewed+ later, which a step that writes can never be.++ `method` records *who or what* decided: `manual`, or the id of the+ strategy that fired. The guards below run either way — an automatic+ decision is not a trusted one.+ """+ if invoice.status != "open":+ raise InvoiceError("not_open", "Only an open invoice can be settled")++ result = await session.execute(+ select(Transaction).where(+ Transaction.id == transaction_id,+ Transaction.workspace_id == invoice.workspace_id,+ )+ )+ transaction = result.scalar_one_or_none()+ if transaction is None:+ # Same message whether it does not exist or belongs to another+ # workspace: the second case must not be distinguishable.+ raise InvoiceError("transaction_not_found", "Transaction not found in this workspace", 404)++ # Same-currency only in this slice, and it fails loudly rather than+ # silently binding a USD invoice to a BRL inflow at an implied rate+ # nobody chose. Multi-currency settlement is its own piece of work.+ if (transaction.currency or invoice.currency) != invoice.currency:+ raise InvoiceError(+ "currency_mismatch",+ f"This invoice is in {invoice.currency} and the transaction is in {transaction.currency}",+ )++ available = balance(invoice)+ if available <= ZERO:+ raise InvoiceError("already_settled", "This invoice is already fully settled")++ # Magnitude, not sign: a receivable is settled by money coming in and+ # a payable by money going out, and the allocation records how much of+ # that movement this document accounts for either way. Defaulting to+ # the smaller of "what is left" and "what moved" is what makes the+ # common case — one payment, one document — a single click.+ incoming = abs(transaction.amount)+ proposed = Decimal(amount) if amount is not None else min(available, incoming)+ if proposed <= ZERO:+ raise InvoiceError("amount_not_positive", "Allocation amount must be positive")+ if proposed > available:+ raise InvoiceError("over_allocation", f"Only {available} remains on this invoice")++ allocation = InvoiceAllocation(+ invoice_id=invoice.id,+ workspace_id=invoice.workspace_id,+ transaction_id=transaction_id,+ amount=proposed,+ method=method,+ )+ session.add(allocation)+ try:+ await session.flush()+ except IntegrityError:+ raise InvoiceError(+ "already_allocated", "This transaction is already linked to this invoice"+ )+ await session.refresh(invoice, ["allocations"])+ return allocation+++async def unallocate(session: AsyncSession, invoice: Invoice, allocation_id: uuid.UUID) -> None:+ result = await session.execute(+ select(InvoiceAllocation).where(+ InvoiceAllocation.id == allocation_id,+ InvoiceAllocation.invoice_id == invoice.id,+ )+ )+ allocation = result.scalar_one_or_none()+ if allocation is None:+ raise InvoiceError("allocation_not_found", "Allocation not found", 404)+ await session.delete(allocation)+ await session.flush()+ await session.refresh(invoice, ["allocations"])+++# ---------------------------------------------------------------------------+# Sharing+# ---------------------------------------------------------------------------+async def create_share_token(session: AsyncSession, invoice: Invoice) -> str:+ """A link anyone holding it can open, and nothing more.++ Only issued invoices get one: a draft is not a document, and handing+ out a link to something still being written invites the client to+ read a number that is about to change.++ The token is the credential, so it is generated with+ `secrets.token_urlsafe` and never derived from the invoice id — a+ guessable link would expose every client's document to anyone who+ could count.+ """+ if invoice.status == "draft":+ raise InvoiceError("draft_not_shareable", "Issue the invoice before sharing it")+ # A payable is the supplier's document, not ours. There is nobody to+ # send it to, and publishing someone else's invoice on a public link+ # is a leak with no upside.+ if invoice.direction != DEFAULT_DIRECTION:+ raise InvoiceError(+ "payable_not_shareable", "A bill you received cannot be shared"+ )+ token = invoice.share_token+ if not token:+ # Bound to a local so the return type is a `str`, not the+ # `str | None` the column is: the branch above guarantees it.+ token = secrets.token_urlsafe(32)+ invoice.share_token = token+ await session.flush()+ return token+++async def revoke_share_token(session: AsyncSession, invoice: Invoice) -> None:+ """Nulling the token is the revocation. Anyone holding the old link+ gets a 404, which is the same answer a link that never existed gets."""+ invoice.share_token = None+ await session.flush()+++async def get_invoice_by_share_token(session: AsyncSession, token: str) -> Optional[Invoice]:+ """The public lookup. Scoped to nothing — the token *is* the scope."""+ if not token:+ return None+ result = await session.execute(+ _base_query().where(+ Invoice.share_token == token,+ # A voided document must stop being reachable: it was+ # cancelled, and a link that keeps serving it says otherwise.+ Invoice.status.in_(("open", "uncollectible")),+ )+ )+ return result.unique().scalar_one_or_none()+++async def invoice_links_for_transactions(+ session: AsyncSession, workspace_id: uuid.UUID, transaction_ids: list[uuid.UUID]+) -> dict[uuid.UUID, list[dict[str, Any]]]:+ """Which invoices each of these transactions settles, for the badge.++ A **list** per transaction, because one is the whole point of the+ N:N: a gateway payout settles a dozen invoices at once, net of fees.+ Keying a single link by transaction id let the second allocation+ overwrite the first, so a transaction that paid three invoices+ advertised one and the ledger and the list disagreed.++ One query for a page of transactions rather than one per row: the+ transaction list is the hottest screen in the product and this must+ never become an N+1.+ """+ if not transaction_ids:+ return {}+ result = await session.execute(+ select(InvoiceAllocation, Invoice)+ .join(Invoice, Invoice.id == InvoiceAllocation.invoice_id)+ .where(+ InvoiceAllocation.workspace_id == workspace_id,+ InvoiceAllocation.transaction_id.in_(transaction_ids),+ )+ )+ links: dict[uuid.UUID, list[dict[str, Any]]] = {}+ for allocation, invoice in result.all():+ links.setdefault(allocation.transaction_id, []).append(+ {+ "invoice_id": invoice.id,+ "number": invoice.number,+ "series": invoice.series,+ # An imported invoice is named by the source, and without+ # this the badge for one would have nothing to show.+ "external_number": invoice.external_number,+ "amount": allocation.amount,+ }+ )+ return linksdiff --git a/backend/app/services/payee_service.py b/backend/app/services/payee_service.pyindex fb4b303e..2316623e 100644--- a/backend/app/services/payee_service.py+++ b/backend/app/services/payee_service.py@@ -260,11 +260,39 @@ async def update_payee(return payee+async def _invoice_count(session: AsyncSession, payee_ids: list[uuid.UUID]) -> int:+ """How many invoices name any of these counterparties.++ Reads the model rather than calling the invoicing service: this is+ the same layer, and a service-to-service call here would make the+ payee module depend on a module most workspaces never enable.+ """+ from app.models.invoice import Invoice++ result = await session.execute(+ select(func.count())+ .select_from(Invoice)+ .where(Invoice.payee_id.in_(payee_ids))+ )+ return int(result.scalar_one())++async def delete_payee(session: AsyncSession, payee_id: uuid.UUID, workspace_id: uuid.UUID) -> bool:payee = await get_payee(session, payee_id, workspace_id)if not payee:return False+ # Invoices hold this payee under a RESTRICT foreign key, deliberately:+ # deleting a client must never silently delete the record of money+ # they owed. Refuse in words rather than letting the constraint+ # surface as a 500, and point at the way out — merging keeps the+ # history, which is what someone deleting a duplicate actually wants.+ invoiced = await _invoice_count(session, [payee_id])+ if invoiced:+ raise ValueError(+ f"payee_has_invoices:{invoiced}"+ )+# Null out transaction referencesawait session.execute(update(Transaction)@@ -292,6 +320,10 @@ async def bulk_delete_payees(session: AsyncSession, workspace_id: uuid.UUID, payif not valid_ids:return 0+ invoiced = await _invoice_count(session, valid_ids)+ if invoiced:+ raise ValueError(f"payee_has_invoices:{invoiced}")+# Null out transaction referencesawait session.execute(update(Transaction)@@ -341,6 +373,22 @@ async def merge_payees()reassigned = cast(CursorResult, result).rowcount+ # Invoices follow the merge for the same reason transactions do: the+ # two rows were one counterparty all along, and leaving the invoices+ # behind would both strand them and trip the RESTRICT foreign key on+ # the delete below.+ #+ # The issued document is untouched by this. Its snapshot froze the+ # client's name and documents at issuance, so a merge changes who the+ # invoice is *linked to* without rewriting what the client received.+ from app.models.invoice import Invoice++ await session.execute(+ update(Invoice)+ .where(Invoice.payee_id.in_(source_ids))+ .values(payee_id=target_id)+ )+# Update mappings: point source mappings to targetfor source_id in source_ids:if source_id == target_id:diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex 4954a294..1bbd940b 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -30,6 +30,12 @@ dependencies = ["yfinance>=1.3.0","pgvector>=0.3.0","pypdf>=5.0.0",+ # Invoice PDF rendering. ReportLab rather than an HTML-to-PDF engine on+ # purpose: WeasyPrint and its peers need pango, cairo and gdk-pixbuf in+ # the image, and this is a self-hosted product where every megabyte and+ # every native library is paid for by the person running it. ReportLab+ # ships pure-Python wheels, and Pillow (already present) covers the logo.+ "reportlab>=4.2.0",# Password-protected backups. The stdlib zipfile can only *read* the# legacy ZipCrypto scheme and cannot write an encrypted archive at all,# so AES-256 zips need this fork of it.diff --git a/backend/tests/test_invoice_attachments.py b/backend/tests/test_invoice_attachments.pynew file mode 100644index 00000000..0af9107d--- /dev/null+++ b/backend/tests/test_invoice_attachments.py@@ -0,0 +1,360 @@+"""The paper an invoice gathers.++The rule under every test here: an invoice is often a folder, not a+document. What it holds may have been written by somebody else, and when+it was, that file is the invoice — not a page we would draw from our own+fields.+"""+import uuid+from datetime import date, timedelta++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++TODAY = date.today()+PDF = b"%PDF-1.4\n1 0 obj<</Type/Catalog>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF\n"+++@pytest_asyncio.fixture+async def personal_ws(session: AsyncSession, test_user):+ """The user's personal workspace, resolved by kind.++ Not the shared `test_workspace` fixture: that one takes the first row+ with no ORDER BY, so once these tests create a business workspace it+ can return either. Which workspace is which is the whole subject+ here, so it is pinned explicitly.+ """+ from sqlalchemy import select++ from app.models.workspace import Workspace, WorkspaceMember++ result = await session.execute(+ select(Workspace)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(WorkspaceMember.user_id == test_user.id, Workspace.kind == "personal")+ .order_by(Workspace.created_at.asc())+ .limit(1)+ )+ return result.scalar_one()+++@pytest_asyncio.fixture+async def business_ws(client: AsyncClient, auth_headers) -> dict:+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Studio", "kind": "business", "self_membership": True},+ )+ assert resp.status_code == 201, resp.text+ return resp.json()+++@pytest_asyncio.fixture+async def biz_headers(auth_headers, business_ws) -> dict:+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}+++async def make_invoice(client, headers, **overrides) -> dict:+ payload = {+ "total": "1200.00",+ "due_date": str(TODAY + timedelta(days=20)),+ "lines": [{"description": "Servico", "quantity": "1", "unit_price": "1200.00"}],+ }+ payload.update(overrides)+ resp = await client.post("/api/invoices", headers=headers, json=payload)+ assert resp.status_code == 201, resp.text+ return resp.json()+++async def upload(client, headers, invoice_id, *, filename="fatura.pdf", data=PDF, **fields):+ return await client.post(+ f"/api/invoices/{invoice_id}/attachments",+ headers=headers,+ files={"file": (filename, data, "application/pdf")},+ data={k: str(v) for k, v in fields.items()},+ )+++# ---------------------------------------------------------------------------+# Gathering+# ---------------------------------------------------------------------------+async def test_an_invoice_gathers_several_documents(client: AsyncClient, biz_headers):+ """The bill, the fiscal document and the receipt arrive at different+ times from different places, and all belong to one debt."""+ invoice = await make_invoice(client, biz_headers)+ for kind, name in (("bill", "fatura.pdf"), ("fiscal", "nfe.pdf"), ("receipt", "comprovante.pdf")):+ resp = await upload(client, biz_headers, invoice["id"], filename=name, kind=kind)+ assert resp.status_code == 201, resp.text++ listing = await client.get(+ f"/api/invoices/{invoice['id']}/attachments", headers=biz_headers+ )+ assert [row["kind"] for row in listing.json()] == ["bill", "fiscal", "receipt"]+++async def test_a_fiscal_document_keeps_its_own_reference(client: AsyncClient, biz_headers):+ """The key on a nota fiscal is 44 digits and is not our invoice+ number. It is stored on the file that carries it, not on the debt."""+ invoice = await make_invoice(client, biz_headers)+ key = "35260812345678000190550010000012341234567890"+ resp = await upload(+ client, biz_headers, invoice["id"], filename="nfe.pdf",+ kind="fiscal", document_number=key, issued_at=str(TODAY),+ )+ assert resp.status_code == 201+ body = resp.json()+ assert body["document_number"] == key+ assert body["issued_at"] == str(TODAY)+++async def test_an_unknown_kind_is_refused(client: AsyncClient, biz_headers):+ invoice = await make_invoice(client, biz_headers)+ resp = await upload(client, biz_headers, invoice["id"], kind="nota_fiscal_eletronica")+ assert resp.status_code == 400+++# ---------------------------------------------------------------------------+# Which file *is* the document+# ---------------------------------------------------------------------------+async def test_a_suppliers_bill_becomes_the_document_by_itself(+ client: AsyncClient, biz_headers+):+ """Nobody should have to tell us the supplier's own PDF outranks a+ page we would have drawn from our own fields."""+ invoice = await make_invoice(+ client, biz_headers, direction="payable", origin="imported",+ external_source="email", external_id="ax-1", external_number="2026/A/0031",+ )+ resp = await upload(client, biz_headers, invoice["id"], kind="bill")+ assert resp.json()["is_primary"] is True+++async def test_our_own_invoice_keeps_our_render_as_the_document(+ client: AsyncClient, biz_headers+):+ """We wrote it, so our page is the document and a file filed beside+ it is evidence, not a replacement."""+ invoice = await make_invoice(client, biz_headers)+ resp = await upload(client, biz_headers, invoice["id"], kind="bill")+ assert resp.json()["is_primary"] is False++ doc = await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ assert doc.json()["source_file"] is None+++async def test_only_one_file_can_be_the_document(client: AsyncClient, biz_headers):+ """Promoting a second one demotes the first rather than failing on the+ partial unique index."""+ invoice = await make_invoice(client, biz_headers)+ first = (await upload(client, biz_headers, invoice["id"], filename="a.pdf", is_primary=True)).json()+ second = (await upload(client, biz_headers, invoice["id"], filename="b.pdf")).json()++ resp = await client.patch(+ f"/api/invoices/{invoice['id']}/attachments/{second['id']}",+ headers=biz_headers,+ json={"is_primary": True},+ )+ assert resp.status_code == 200+ listing = (+ await client.get(f"/api/invoices/{invoice['id']}/attachments", headers=biz_headers)+ ).json()+ primaries = [row["id"] for row in listing if row["is_primary"]]+ assert primaries == [second["id"]]+ assert first["id"] not in primaries+++async def test_the_filed_document_is_what_downloading_hands_over(+ client: AsyncClient, biz_headers+):+ """The whole point of the aggregator: stop reconstructing a page we+ were handed. A render over the top of a real document looks official+ and is not."""+ invoice = await make_invoice(+ client, biz_headers, direction="payable", origin="imported",+ external_source="email", external_id="ax-2",+ )+ marker = PDF + b"%supplier-original\n"+ await upload(client, biz_headers, invoice["id"], filename="do-fornecedor.pdf",+ data=marker, kind="bill")++ doc = await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ assert doc.json()["source_file"]["filename"] == "do-fornecedor.pdf"++ pdf = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert pdf.content == marker+ assert "do-fornecedor.pdf" in pdf.headers["content-disposition"]+++async def test_without_a_filed_document_we_still_render_our_own(+ client: AsyncClient, biz_headers+):+ invoice = await make_invoice(client, biz_headers)+ pdf = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert pdf.status_code == 200+ assert pdf.content.startswith(b"%PDF")+ assert pdf.headers["content-type"] == "application/pdf"+++# ---------------------------------------------------------------------------+# Boundaries+# ---------------------------------------------------------------------------+async def test_files_are_scoped_to_their_workspace(+ client: AsyncClient, biz_headers, auth_headers, personal_ws+):+ """A workspace boundary is not a filter someone can forget."""+ invoice = await make_invoice(client, biz_headers)+ attachment = (await upload(client, biz_headers, invoice["id"])).json()++ other = {**auth_headers, "X-Workspace-Id": str(personal_ws.id)}+ resp = await client.get(+ f"/api/invoices/{invoice['id']}/attachments/{attachment['id']}", headers=other+ )+ # 404 rather than 403: a personal workspace has no invoicing module,+ # so the route does not exist for it at all.+ assert resp.status_code == 404+++async def test_an_unknown_invoice_is_not_found(client: AsyncClient, biz_headers):+ resp = await upload(client, biz_headers, uuid.uuid4())+ assert resp.status_code == 404+++async def test_deleting_a_file_removes_it(client: AsyncClient, biz_headers):+ invoice = await make_invoice(client, biz_headers)+ attachment = (await upload(client, biz_headers, invoice["id"])).json()++ resp = await client.delete(+ f"/api/invoices/{invoice['id']}/attachments/{attachment['id']}", headers=biz_headers+ )+ assert resp.status_code == 204++ listing = await client.get(+ f"/api/invoices/{invoice['id']}/attachments", headers=biz_headers+ )+ assert listing.json() == []+++async def test_a_download_returns_the_bytes_that_were_stored(+ client: AsyncClient, biz_headers+):+ invoice = await make_invoice(client, biz_headers)+ payload = PDF + b"%exactly-these-bytes\n"+ attachment = (+ await upload(client, biz_headers, invoice["id"], data=payload)+ ).json()++ resp = await client.get(+ f"/api/invoices/{invoice['id']}/attachments/{attachment['id']}", headers=biz_headers+ )+ assert resp.content == payload+++async def test_an_import_with_nothing_filed_has_no_pdf_to_give(+ client: AsyncClient, biz_headers+):+ """Refused at the API too, not only hidden in the UI: a rule enforced+ in a button is one the next caller does not know about."""+ invoice = await make_invoice(+ client, biz_headers, direction="payable", origin="imported",+ external_source="email", external_id="none-filed",+ )+ resp = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert resp.status_code == 409+ assert resp.json()["detail"]["code"] == "no_document_filed"++ # Once the real file is filed, it is served.+ await upload(client, biz_headers, invoice["id"], filename="recebida.pdf", kind="bill")+ resp = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert resp.status_code == 200+ assert "recebida.pdf" in resp.headers["content-disposition"]+++# ---------------------------------------------------------------------------+# Where each file came from+# ---------------------------------------------------------------------------+async def test_a_folder_records_which_system_produced_each_file(+ client: AsyncClient, biz_headers+):+ """The point of the column: an invoice assembled from three systems is+ otherwise a pile of files with no author."""+ invoice = await make_invoice(client, biz_headers)+ await upload(client, biz_headers, invoice["id"], filename="cobranca.pdf",+ kind="bill", source="stripe", external_id="in_1AbC")+ await upload(client, biz_headers, invoice["id"], filename="nfe.pdf",+ kind="fiscal", source="nfe-provider", external_id="35260812345678")+ await upload(client, biz_headers, invoice["id"], filename="anexo.pdf", kind="other")++ rows = (+ await client.get(f"/api/invoices/{invoice['id']}/attachments", headers=biz_headers)+ ).json()+ assert [(r["filename"], r["source"]) for r in rows] == [+ ("cobranca.pdf", "stripe"),+ ("nfe.pdf", "nfe-provider"),+ # A person uploaded this one, and no source is how that is said.+ ("anexo.pdf", None),+ ]+ # Every file records when it reached us, which is not the date on it.+ assert all(r["created_at"] for r in rows)+++async def test_two_hand_uploads_do_not_collide(client: AsyncClient, biz_headers):+ """The uniqueness is per source, and a null source is not a value two+ rows can collide on — otherwise a second manual upload would fail."""+ invoice = await make_invoice(client, biz_headers)+ first = await upload(client, biz_headers, invoice["id"], filename="a.pdf")+ second = await upload(client, biz_headers, invoice["id"], filename="b.pdf")+ assert first.status_code == 201 and second.status_code == 201+++async def test_a_source_can_be_corrected(client: AsyncClient, biz_headers):+ invoice = await make_invoice(client, biz_headers)+ filed = (await upload(client, biz_headers, invoice["id"])).json()+ resp = await client.patch(+ f"/api/invoices/{invoice['id']}/attachments/{filed['id']}",+ headers=biz_headers,+ json={"source": "email"},+ )+ assert resp.json()["source"] == "email"+++async def test_a_resync_of_the_same_file_lands_on_the_row_it_wrote(+ client: AsyncClient, biz_headers+):+ """`source` + `external_id` is unique per workspace, so the second+ sync used to be rejected by the index *after* its bytes were written,+ leaving a blob nothing could reach."""+ invoice = await make_invoice(client, biz_headers)+ first = await upload(+ client, biz_headers, invoice["id"], filename="nfe.pdf",+ kind="fiscal", source="nfe-provider", external_id="35260812345678",+ )+ again = await upload(+ client, biz_headers, invoice["id"], filename="nfe.pdf",+ kind="fiscal", source="nfe-provider", external_id="35260812345678",+ )+ assert again.status_code == 201+ assert again.json()["id"] == first.json()["id"]++ listing = await client.get(+ f"/api/invoices/{invoice['id']}/attachments", headers=biz_headers+ )+ assert len(listing.json()) == 1diff --git a/backend/tests/test_invoice_document.py b/backend/tests/test_invoice_document.pynew file mode 100644index 00000000..7f423fab--- /dev/null+++ b/backend/tests/test_invoice_document.py@@ -0,0 +1,1061 @@+"""The rendered document: resolution, PDF bytes, and the shared link.++Two properties matter most here and both are asserted directly:++ 1. **The snapshot wins.** A document already in a client's hands must+ not change when settings do.+ 2. **The screen and the PDF agree.** They consume one structure, and+ the tests read that structure rather than either renderer.+"""+import uuid+from datetime import date, timedelta+from decimal import Decimal++import pytest+import pytest_asyncio+from httpx import AsyncClient+from sqlalchemy.ext.asyncio import AsyncSession++from app.fiscal.registry import TaxIdKind, apply_mask, format_for_display+from app.models.payee import Payee, PayeeTaxId+from app.services import invoice_pdf++TODAY = date.today()+++@pytest_asyncio.fixture+async def business_ws(client: AsyncClient, auth_headers) -> dict:+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Consultoria", "kind": "business", "self_membership": True},+ )+ assert resp.status_code == 201, resp.text+ return resp.json()+++@pytest_asyncio.fixture+async def biz_headers(auth_headers, business_ws) -> dict:+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}+++@pytest_asyncio.fixture+async def client_payee(session: AsyncSession, business_ws, test_user) -> Payee:+ payee = Payee(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=uuid.UUID(business_ws["id"]),+ name="Beta Tecnologia LTDA", source="manual", address="Av Paulista, 1000",+ email="[email protected]",+ )+ session.add(payee)+ await session.flush()+ session.add(+ PayeeTaxId(+ payee_id=payee.id, workspace_id=uuid.UUID(business_ws["id"]),+ kind="cnpj", value="11222333000181",+ )+ )+ await session.commit()+ return payee+++async def make_invoice(client, headers, **overrides):+ payload = {+ "total": "3000.00",+ "due_date": str(TODAY + timedelta(days=15)),+ "lines": [{"description": "Consultoria", "quantity": "10", "unit_price": "300.00"}],+ }+ payload.update(overrides)+ resp = await client.post("/api/invoices", headers=headers, json=payload)+ assert resp.status_code == 201, resp.text+ return resp.json()+++# ---------------------------------------------------------------------------+# The mask, shared by the PDF and the screen+# ---------------------------------------------------------------------------+class TestMask:+ def test_formats_a_full_document(self):+ assert format_for_display(TaxIdKind.CNPJ, "11222333000181") == "11.222.333/0001-81"+ assert format_for_display(TaxIdKind.CPF, "52998224725") == "529.982.247-25"++ def test_shows_a_short_value_as_stored(self):+ """A half-masked document number ("12.3") reads as corruption. If+ the value does not fill the mask, it is shown as it is."""+ assert apply_mask("123", "##.###.###/####-##") == "123"++ def test_shows_a_long_value_as_stored(self):+ assert apply_mask("1122233300018199", "##.###.###/####-##") == "1122233300018199"++ def test_a_kind_with_no_mask_is_untouched(self):+ # Which is what keeps a jurisdiction nobody has described from+ # being mangled.+ assert apply_mask("DE811907980", None) == "DE811907980"+++# ---------------------------------------------------------------------------+# Document resolution+# ---------------------------------------------------------------------------+class TestDocument:+ async def test_carries_both_parties_and_the_lines(+ self, client: AsyncClient, biz_headers, client_payee+ ):+ await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={+ "legal_name": "Alpha Consultoria ME",+ "address": "Rua das Flores, 10",+ "tax_ids": [{"kind": "cnpj", "value": "11.222.333/0001-81"}],+ },+ )+ invoice = await make_invoice(client, biz_headers, payee_id=str(client_payee.id))+ resp = await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ assert resp.status_code == 200, resp.text+ doc = resp.json()++ assert doc["issuer"]["legal_name"] == "Alpha Consultoria ME"+ # Masked server-side: the PDF has no frontend to ask.+ assert doc["issuer"]["tax_ids"][0]["value"] == "11.222.333/0001-81"+ assert doc["client"]["name"] == "Beta Tecnologia LTDA"+ assert doc["client"]["tax_ids"][0]["value"] == "11.222.333/0001-81"+ assert doc["lines"][0]["description"] == "Consultoria"+ assert doc["total"] == "3000.00"+ assert doc["has_line_items"] is True++ async def test_an_invoice_with_no_lines_says_so(self, client: AsyncClient, biz_headers):+ """The majority Brazilian case: the NF was issued at the+ prefeitura and this is only tracking the money. It must not+ pretend to be a document."""+ invoice = await make_invoice(client, biz_headers, lines=[])+ resp = await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ assert resp.json()["has_line_items"] is False+ assert resp.json()["lines"] == []++ async def test_labels_default_and_can_be_overridden(+ self, client: AsyncClient, biz_headers+ ):+ # The conftest user reads pt-BR, so the workspace does too and the+ # document defaults to the Portuguese pack. Asserted against the+ # pack rather than a hardcoded word: the point is that the issuer's+ # language decides, not which language that happens to be.+ from app.services.invoice_document import default_labels++ default = await make_invoice(client, biz_headers)+ doc = (+ await client.get(f"/api/invoices/{default['id']}/document", headers=biz_headers)+ ).json()+ assert doc["labels"]["quantity"] == default_labels("pt-BR")["quantity"]++ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={"template": {"labels": {"quantity": "Horas", "invoice": "Fatura"}}},+ )+ customised = await make_invoice(client, biz_headers)+ doc = (+ await client.get(f"/api/invoices/{customised['id']}/document", headers=biz_headers)+ ).json()+ assert doc["labels"]["quantity"] == "Horas"+ assert doc["labels"]["invoice"] == "Fatura"+ # Untouched labels keep their default rather than disappearing.+ assert doc["labels"]["total"] == default_labels("pt-BR")["total"]++ async def test_an_unknown_label_key_is_ignored(self, client: AsyncClient, biz_headers):+ """The template is free-form jsonb, so it can hold anything a hand+ edit put there. Unknown keys must not become UI."""+ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={"template": {"labels": {"nonsense": "x", "quantity": "Horas"}}},+ )+ invoice = await make_invoice(client, biz_headers)+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ ).json()+ assert "nonsense" not in doc["labels"]+ assert doc["labels"]["quantity"] == "Horas"++ async def test_the_snapshot_beats_later_settings(+ self, client: AsyncClient, biz_headers, client_payee+ ):+ """The rule the whole design turns on: a document in a client's+ hands does not change when the sender edits their profile."""+ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={"issuer_display_name": "Alpha ME", "accent_color": "#4f46e5",+ "payment_details": "Pix: [email protected]"},+ )+ invoice = await make_invoice(client, biz_headers, payee_id=str(client_payee.id))++ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={"issuer_display_name": "Gamma LTDA", "accent_color": "#dc2626",+ "payment_details": "Pix: [email protected]"},+ )+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ ).json()+ assert doc["issuer"]["name"] == "Alpha ME"+ assert doc["accent_color"] == "#4f46e5"+ assert doc["payment_details"] == "Pix: [email protected]"++ async def test_renaming_a_client_does_not_rewrite_their_document(+ self, client: AsyncClient, biz_headers, client_payee, session: AsyncSession+ ):+ invoice = await make_invoice(client, biz_headers, payee_id=str(client_payee.id))+ await client.patch(+ f"/api/payees/{client_payee.id}", headers=biz_headers, json={"name": "Beta S.A."}+ )+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ ).json()+ assert doc["client"]["name"] == "Beta Tecnologia LTDA"++ async def test_custom_fields_follow_the_definitions(+ self, client: AsyncClient, biz_headers+ ):+ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={"template": {"custom_fields": [{"key": "po", "label": "PO number"}]}},+ )+ invoice = await make_invoice(+ client, biz_headers, custom_fields={"po": "PO-4471", "stray": "ignored"}+ )+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ ).json()+ # Driven by the definitions, so a value with no definition never+ # reaches the page.+ assert doc["custom_fields"] == [{"label": "PO number", "value": "PO-4471"}]+++# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+class TestPdf:+ async def test_downloads_a_real_pdf(self, client: AsyncClient, biz_headers, client_payee):+ invoice = await make_invoice(client, biz_headers, payee_id=str(client_payee.id))+ resp = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert resp.status_code == 200, resp.text+ assert resp.headers["content-type"] == "application/pdf"+ assert resp.content.startswith(b"%PDF-")+ assert "attachment" in resp.headers["content-disposition"]++ async def test_the_pdf_carries_what_the_document_says(+ self, client: AsyncClient, biz_headers, client_payee+ ):+ """Read back through pypdf rather than trusting the byte count:+ a PDF that renders blank is still a valid PDF."""+ import pypdf++ await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"legal_name": "Alpha Consultoria ME",+ "tax_ids": [{"kind": "cnpj", "value": "11222333000181"}]},+ )+ invoice = await make_invoice(client, biz_headers, payee_id=str(client_payee.id))+ resp = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)++ import io++ text = pypdf.PdfReader(io.BytesIO(resp.content)).pages[0].extract_text()+ assert "Beta Tecnologia LTDA" in text+ assert "Alpha Consultoria ME" in text+ assert "11.222.333/0001-81" in text+ assert "Consultoria" in text+ assert "3,000.00" in text+ assert invoice["due_date"] in text++ async def test_renders_without_a_client_or_any_profile(+ self, client: AsyncClient, biz_headers+ ):+ """A workspace that has filled nothing in still gets a usable+ page — every field on the document is optional by design."""+ invoice = await make_invoice(client, biz_headers, lines=[])+ resp = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert resp.status_code == 200+ assert resp.content.startswith(b"%PDF-")++ def test_a_broken_accent_colour_degrades_instead_of_raising(self):+ """User input reaching a renderer must never cost the document."""+ from app.services.invoice_pdf import _accent++ assert _accent("not-a-colour") is not None+ assert _accent(None) is not None+ assert _accent("#4f46e5") is not None++ async def test_a_broken_logo_does_not_cost_the_document(+ self, client: AsyncClient, biz_headers+ ):+ invoice = await make_invoice(client, biz_headers)+ settings = (await client.get("/api/invoices/settings", headers=biz_headers)).json()+ doc_resp = await client.get(+ f"/api/invoices/{invoice['id']}/document", headers=biz_headers+ )+ assert doc_resp.status_code == 200+ # Feed the renderer bytes that are not an image at all.+ from app.services.invoice_document import (+ DEFAULT_LABELS, DocumentParty, InvoiceDocument,+ )++ document = InvoiceDocument(+ 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"),+ 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,+ )+ pdf = invoice_pdf.render_pdf(document, logo_bytes=b"not an image")+ assert pdf.startswith(b"%PDF-")+ assert settings is not None+++# ---------------------------------------------------------------------------+# Sharing — the only unauthenticated surface+# ---------------------------------------------------------------------------+class TestSharing:+ async def test_a_link_serves_the_document_without_auth(+ self, client: AsyncClient, biz_headers, client_payee+ ):+ invoice = await make_invoice(client, biz_headers, payee_id=str(client_payee.id))+ created = await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ assert created.status_code == 201, created.text+ token = created.json()["token"]+ assert created.json()["path"] == f"/i/{token}"++ # No Authorization header at all.+ public = await client.get(f"/api/public/invoices/{token}")+ assert public.status_code == 200, public.text+ assert public.json()["client"]["name"] == "Beta Tecnologia LTDA"++ async def test_the_public_view_leaks_nothing_internal(+ self, client: AsyncClient, biz_headers, client_payee+ ):+ invoice = await make_invoice(+ client, biz_headers, payee_id=str(client_payee.id),+ internal_notes="cliente reclamou do prazo",+ )+ token = (+ await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ ).json()["token"]+ body = (await client.get(f"/api/public/invoices/{token}")).text+ assert "cliente reclamou" not in body+ assert "internal_notes" not in body+ assert "allocations" not in body+ assert "payee_id" not in body++ async def test_the_token_is_not_derived_from_the_id(+ self, client: AsyncClient, biz_headers+ ):+ invoice = await make_invoice(client, biz_headers)+ token = (+ await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ ).json()["token"]+ assert invoice["id"].replace("-", "") not in token+ assert len(token) >= 32++ async def test_asking_twice_returns_the_same_link(+ self, client: AsyncClient, biz_headers+ ):+ """Otherwise every visit to the invoice page would silently+ invalidate the link the client was already sent."""+ invoice = await make_invoice(client, biz_headers)+ first = await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ second = await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ assert first.json()["token"] == second.json()["token"]++ async def test_revoking_makes_the_link_a_404(self, client: AsyncClient, biz_headers):+ invoice = await make_invoice(client, biz_headers)+ token = (+ await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ ).json()["token"]+ assert (await client.get(f"/api/public/invoices/{token}")).status_code == 200++ revoked = await client.delete(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ assert revoked.status_code == 204+ # Indistinguishable from a link that never existed.+ assert (await client.get(f"/api/public/invoices/{token}")).status_code == 404++ async def test_voiding_takes_the_link_down(self, client: AsyncClient, biz_headers):+ """A cancelled document must stop being served: a link that keeps+ working says the invoice still stands."""+ invoice = await make_invoice(client, biz_headers)+ token = (+ await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ ).json()["token"]+ await client.post(f"/api/invoices/{invoice['id']}/void", headers=biz_headers)+ assert (await client.get(f"/api/public/invoices/{token}")).status_code == 404++ async def test_a_draft_cannot_be_shared(self, client: AsyncClient, biz_headers):+ await client.patch(+ "/api/invoices/settings", headers=biz_headers, json={"preset": "document"}+ )+ draft = await make_invoice(client, biz_headers)+ assert draft["status"] == "draft"+ resp = await client.post(f"/api/invoices/{draft['id']}/share", headers=biz_headers)+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "draft_not_shareable"++ async def test_an_unknown_token_is_a_404(self, client: AsyncClient):+ assert (await client.get("/api/public/invoices/nope")).status_code == 404++ async def test_the_public_pdf_opens_inline(self, client: AsyncClient, biz_headers):+ invoice = await make_invoice(client, biz_headers)+ token = (+ await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ ).json()["token"]+ resp = await client.get(f"/api/public/invoices/{token}/pdf")+ assert resp.status_code == 200+ assert resp.content.startswith(b"%PDF-")+ # Someone opening a link expects to see the document, not to+ # receive a download.+ assert "inline" in resp.headers["content-disposition"]+++# ---------------------------------------------------------------------------+# Issuer identity (T10)+# ---------------------------------------------------------------------------+class TestIssuerProfile:+ async def test_stores_and_normalises_a_document(self, client: AsyncClient, biz_headers):+ resp = await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"legal_name": "Alpha ME",+ "tax_ids": [{"kind": "cnpj", "value": "11.222.333/0001-81"}]},+ )+ assert resp.status_code == 200, resp.text+ # Stored normalised, exactly as the payee side stores it.+ assert resp.json()["tax_ids"][0]["value"] == "11222333000181"++ async def test_refuses_an_invalid_document_with_the_same_validator(+ self, client: AsyncClient, biz_headers+ ):+ """One implementation, asserted from both call sites."""+ resp = await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"tax_ids": [{"kind": "cnpj", "value": "11111111111111"}]},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"].startswith("invalid_tax_id:cnpj")++ async def test_sending_a_shorter_list_removes_a_document(+ self, client: AsyncClient, biz_headers+ ):+ await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"tax_ids": [{"kind": "cnpj", "value": "11222333000181"},+ {"kind": "cpf", "value": "529.982.247-25"}]},+ )+ resp = await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"tax_ids": [{"kind": "cnpj", "value": "11222333000181"}]},+ )+ assert [t["kind"] for t in resp.json()["tax_ids"]] == ["cnpj"]++ async def test_omitting_tax_ids_leaves_them_untouched(+ self, client: AsyncClient, biz_headers+ ):+ await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"tax_ids": [{"kind": "cnpj", "value": "11222333000181"}]},+ )+ resp = await client.patch(+ "/api/invoices/issuer", headers=biz_headers, json={"legal_name": "Alpha ME"}+ )+ assert len(resp.json()["tax_ids"]) == 1++ async def test_a_workspace_with_no_identity_still_works(+ self, client: AsyncClient, biz_headers+ ):+ """Nothing here is required until a document is rendered."""+ resp = await client.get("/api/invoices/issuer", headers=biz_headers)+ assert resp.status_code == 200+ assert resp.json()["legal_name"] is None+ assert resp.json()["tax_ids"] == []++ async def test_a_personal_workspace_cannot_reach_the_issuer_routes(+ self, client: AsyncClient, auth_headers, session: AsyncSession, test_user+ ):+ from sqlalchemy import select++ from app.models.workspace import Workspace, WorkspaceMember++ result = await session.execute(+ select(Workspace)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(WorkspaceMember.user_id == test_user.id, Workspace.kind == "personal")+ .limit(1)+ )+ personal = result.scalar_one()+ headers = {**auth_headers, "X-Workspace-Id": str(personal.id)}+ assert (await client.get("/api/invoices/issuer", headers=headers)).status_code == 404+ assert (+ await client.patch("/api/invoices/issuer", headers=headers, json={"legal_name": "x"})+ ).status_code == 404+++# ---------------------------------------------------------------------------+# Page structure — the band layout and its pagination+# ---------------------------------------------------------------------------+def _doc(n_lines: int, footer_note: str = "Alpha ME"):+ """A document with `n_lines` items, for exercising page breaks.++ Built field by field rather than from a dict: keyword-splatting a+ heterogeneous mapping loses every type on the way in, and this is the+ one fixture the PDF tests all lean on.+ """+ from app.services.invoice_document import (+ DEFAULT_LABELS, DocumentLine, DocumentParty, InvoiceDocument,+ )++ return InvoiceDocument(+ number="FAT-7",+ status="open",+ state="open",+ issue_date=date(2026, 8, 26),+ due_date=date(2026, 9, 20),+ currency="BRL",+ subtotal=Decimal("1200"),+ discount=Decimal("0"),+ tax_total=Decimal("0"),+ total=Decimal("1200"),+ amount_paid=Decimal("0"),+ balance=Decimal("1200"),+ issuer=DocumentParty(name="Alpha ME", tax_ids=[]),+ client=DocumentParty(name="Beta LTDA", address=None, tax_ids=[]),+ lines=[+ DocumentLine(f"Item {i + 1}", Decimal("1"), Decimal("100"), Decimal("100"))+ for i in range(n_lines)+ ],+ labels=dict(DEFAULT_LABELS),+ accent_color="#4f46e5",+ logo_id=None,+ payment_details="Pix: [email protected]",+ notes="Obrigado.",+ footer_note=footer_note,+ custom_fields=[],+ has_line_items=n_lines > 0,+ )+++def _pages(document):+ import io++ import pypdf++ return pypdf.PdfReader(io.BytesIO(invoice_pdf.render_pdf(document))).pages+++class TestPageStructure:+ def test_a_short_invoice_is_one_page(self):+ assert len(_pages(_doc(3))) == 1++ def test_a_long_invoice_paginates_instead_of_overflowing(self):+ """The regression this exists for.++ The renderer used to draw one page and let anything taller run off+ the bottom edge, where the line items were still in the file and+ invisible to every human who opened it.+ """+ pages = _pages(_doc(45))+ assert len(pages) > 1++ def test_no_line_item_is_lost_across_the_break(self):+ n = 45+ pages = _pages(_doc(n))+ text = "\n".join(p.extract_text() for p in pages)+ for i in range(n):+ assert f"Item {i + 1}" in text, f"line {i + 1} vanished"++ def test_every_page_identifies_the_document(self):+ """Someone holding page 3 has to know what it belongs to."""+ for page in _pages(_doc(45)):+ text = page.extract_text()+ assert "FAT-7" in text++ def test_the_payment_band_lands_on_the_last_page_only(self):+ pages = _pages(_doc(45))+ texts = [p.extract_text() for p in pages]+ assert "Pix: [email protected]" in texts[-1]+ for text in texts[:-1]:+ assert "Pix: [email protected]" not in text++ def test_totals_land_on_the_last_page_with_the_final_items(self):+ texts = [p.extract_text() for p in _pages(_doc(45))]+ assert "Item 45" in texts[-1]+ assert "1,200.00" in texts[-1]++ def test_page_numbers_appear_only_when_there_is_more_than_one(self):+ """"1 / 1" on a single-page invoice is noise that makes the+ document look machine-made."""+ single = _pages(_doc(3))[0].extract_text()+ assert "/ 1" not in single++ multi = _pages(_doc(45))+ assert f"/ {len(multi)}" in multi[-1].extract_text()++ def test_the_payment_band_sits_below_the_totals_on_the_page(self):+ """Position, not just presence: "how to pay me" halfway up an+ otherwise empty page is the layout this replaced."""+ import io++ import pypdf++ positions: dict[str, float] = {}++ def visitor(text, _cm, tm, *_args):+ stripped = text.strip()+ for needle in ("Total", "PAYMENT DETAILS"):+ if stripped.startswith(needle) and needle not in positions:+ positions[needle] = tm[5]++ page = pypdf.PdfReader(io.BytesIO(invoice_pdf.render_pdf(_doc(3)))).pages[0]+ page.extract_text(visitor_text=visitor)++ assert "Total" in positions and "PAYMENT DETAILS" in positions+ # PDF y grows upward, so lower on the page is a smaller number.+ assert positions["PAYMENT DETAILS"] < positions["Total"]++ def test_an_invoice_with_no_lines_still_renders_the_bands(self):+ page = _pages(_doc(0))[0].extract_text()+ assert "Beta LTDA" in page+ assert "Pix: [email protected]" in page+++# ---------------------------------------------------------------------------+# Default labels follow the issuer, not the reader+# ---------------------------------------------------------------------------+class TestLabelPacks:+ def test_a_shipped_language_gets_its_own_words(self):+ from app.services.invoice_document import default_labels++ assert default_labels("pt-BR")["invoice"] == "Fatura"+ assert default_labels("de")["dueDate"] == "Fällig am"+ assert default_labels("fr")["invoice"] == "Facture"++ def test_regional_variants_share_a_pack(self):+ """`pt-BR` and `pt-PT` differ in ways a translator cares about and+ not in the eighteen words on an invoice."""+ from app.services.invoice_document import default_labels++ assert default_labels("pt-PT") == default_labels("pt-BR")++ def test_an_unshipped_language_falls_back_to_english(self):+ from app.services.invoice_document import DEFAULT_LABELS, default_labels++ assert default_labels("ja") == DEFAULT_LABELS+ assert default_labels(None) == DEFAULT_LABELS++ def test_every_pack_covers_every_label(self):+ """A half-translated document reads worse than an English one."""+ from app.services.invoice_document import DEFAULT_LABELS, LABEL_PACKS++ for language, pack in LABEL_PACKS.items():+ assert set(pack) == set(DEFAULT_LABELS), language+++class TestIssuerLanguage:+ async def test_a_brazilian_workspace_gets_a_portuguese_document(+ self, client: AsyncClient, auth_headers+ ):+ created = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Consultoria BR", "kind": "business",+ "self_membership": True, "locale": "pt-BR"},+ )+ assert created.status_code == 201, created.text+ headers = {**auth_headers, "X-Workspace-Id": created.json()["id"]}++ invoice = await make_invoice(client, headers)+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=headers)+ ).json()+ assert doc["labels"]["invoice"] == "Fatura"+ assert doc["labels"]["billTo"] == "Cliente"++ async def test_an_explicit_label_still_wins_over_the_pack(+ self, client: AsyncClient, auth_headers+ ):+ created = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Consultoria BR2", "kind": "business",+ "self_membership": True, "locale": "pt-BR"},+ )+ headers = {**auth_headers, "X-Workspace-Id": created.json()["id"]}+ await client.patch(+ "/api/invoices/settings",+ headers=headers,+ json={"template": {"labels": {"invoice": "Recibo"}}},+ )+ invoice = await make_invoice(client, headers)+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=headers)+ ).json()+ assert doc["labels"]["invoice"] == "Recibo"+ # Untouched labels still come from the pack, not from English.+ assert doc["labels"]["dueDate"] == "Vencimento"++ async def test_switching_the_interface_never_retitles_an_issued_document(+ self, client: AsyncClient, auth_headers+ ):+ """The words were the sender's choice at issuance. Changing the+ workspace language afterwards must not rewrite a document the+ client already holds."""+ created = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Consultoria BR3", "kind": "business",+ "self_membership": True, "locale": "pt-BR"},+ )+ workspace_id = created.json()["id"]+ headers = {**auth_headers, "X-Workspace-Id": workspace_id}+ invoice = await make_invoice(client, headers)++ await client.patch(+ f"/api/workspaces/{workspace_id}", headers=headers, json={"locale": "en"}+ )+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=headers)+ ).json()+ assert doc["labels"]["invoice"] == "Fatura"+++async def test_an_imported_number_is_rendered_with_the_source_prefix(+ client: AsyncClient, biz_headers+):+ """Our prefix belongs on our paper. A supplier reference of FAT-9931+ must not come back as INV-9931 because that is what we call ours."""+ await client.patch(+ "/api/invoices/settings", headers=biz_headers, json={"number_prefix": "INV-"}+ )+ imported = await make_invoice(+ client, biz_headers, origin="imported",+ external_source="erp", external_id="FAT-9931", external_number="FAT-9931",+ )+ doc = await client.get(f"/api/invoices/{imported['id']}/document", headers=biz_headers)+ assert doc.json()["number"] == "FAT-9931"++ bare = await make_invoice(+ client, biz_headers, origin="imported",+ external_source="erp", external_id="7",+ )+ doc = await client.get(f"/api/invoices/{bare['id']}/document", headers=biz_headers)+ assert doc.json()["number"] is None++ ours = await make_invoice(client, biz_headers)+ doc = await client.get(f"/api/invoices/{ours['id']}/document", headers=biz_headers)+ assert doc.json()["number"] == "INV-1"+++async def test_our_identity_stays_off_a_supplier_document(client: AsyncClient, biz_headers):+ """Our bank details under "pay to" on a bill we owe state the opposite+ of what is true, and our logo brands a page we did not write."""+ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={+ "payment_details": "Banco 001 · Ag 1234 · CC 56789-0",+ "footer_note": "Obrigado pela preferencia!",+ "accent_color": "#FF0000",+ },+ )+ # The logo arrives as a file now, on its own route.+ logo_id = (await _put_logo(client, biz_headers)).json()["logo_id"]++ bill = await make_invoice(+ client, biz_headers, direction="payable", origin="imported",+ external_source="erp", external_id="FAT-1",+ )+ doc = (+ await client.get(f"/api/invoices/{bill['id']}/document", headers=biz_headers)+ ).json()+ assert doc["logo_id"] is None+ assert doc["payment_details"] is None+ assert doc["footer_note"] is None+ assert doc["accent_color"] != "#FF0000"++ # On our own invoice every one of them is still printed.+ ours = await make_invoice(client, biz_headers)+ doc = (+ await client.get(f"/api/invoices/{ours['id']}/document", headers=biz_headers)+ ).json()+ assert doc["logo_id"] == logo_id+ assert doc["payment_details"] == "Banco 001 \u00b7 Ag 1234 \u00b7 CC 56789-0"+ assert doc["footer_note"] == "Obrigado pela preferencia!"+ assert doc["accent_color"] == "#FF0000"+++# ---------------------------------------------------------------------------+# The logo is a file this workspace owns+# ---------------------------------------------------------------------------+def _png(width: int = 40, height: int = 20, colour: tuple = (79, 70, 229)) -> bytes:+ import io as _io++ from PIL import Image as _Image++ buf = _io.BytesIO()+ _Image.new("RGB", (width, height), colour).save(buf, format="PNG")+ return buf.getvalue()+++async def _put_logo(client, headers, data=None, content_type="image/png", name="logo.png"):+ return await client.post(+ "/api/invoices/settings/logo",+ headers=headers,+ files={"file": (name, data if data is not None else _png(), content_type)},+ )+++async def test_an_uploaded_logo_reaches_the_pdf(client: AsyncClient, biz_headers):+ """It never did: `render_pdf` took logo bytes and no caller passed+ any, so a workspace saw its mark on screen and got a file without."""+ resp = await _put_logo(client, biz_headers)+ assert resp.status_code == 200, resp.text+ assert resp.json()["logo_id"]++ invoice = await make_invoice(client, biz_headers)+ pdf = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ import io as _io++ import pypdf as _pypdf++ reader = _pypdf.PdfReader(_io.BytesIO(pdf.content))+ assert len(list(reader.pages[0].images)) == 1+++async def test_replacing_the_logo_leaves_issued_documents_alone(+ client: AsyncClient, biz_headers+):+ """The freeze rule, applied to a file. An invoice a client is holding+ does not change its letterhead because the issuer rebranded."""+ first = (await _put_logo(client, biz_headers)).json()["logo_id"]+ invoice = await make_invoice(client, biz_headers)++ second = (await _put_logo(client, biz_headers, data=_png(colour=(200, 30, 30)))).json()[+ "logo_id"+ ]+ assert second != first++ doc = await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ assert doc.json()["logo_url"] == f"/api/invoices/logo/{first}"++ # And the old file is still there to serve, because the document+ # still points at it.+ served = await client.get(f"/api/invoices/logo/{first}", headers=biz_headers)+ assert served.status_code == 200+ assert served.headers["content-type"] == "image/png"+++async def test_whatever_arrives_is_stored_as_a_bounded_png(+ client: AsyncClient, biz_headers+):+ """Re-encoding fixes the content type the route answers with, bounds+ the size every PDF carries, and drops the metadata a photo brings."""+ import io as _io++ from PIL import Image as _Image++ buf = _io.BytesIO()+ _Image.new("RGB", (3000, 1200), (10, 200, 90)).save(buf, format="JPEG")+ resp = await _put_logo(+ client, biz_headers, data=buf.getvalue(), content_type="image/jpeg", name="mark.jpg"+ )+ logo_id = resp.json()["logo_id"]++ served = await client.get(f"/api/invoices/logo/{logo_id}", headers=biz_headers)+ assert served.headers["content-type"] == "image/png"+ stored = _Image.open(_io.BytesIO(served.content))+ assert stored.format == "PNG"+ assert max(stored.size) <= 600+++async def test_a_file_that_is_not_an_image_is_refused(client: AsyncClient, biz_headers):+ resp = await _put_logo(+ client, biz_headers, data=b"%PDF-1.4 not an image", content_type="application/pdf",+ name="nope.pdf",+ )+ assert resp.status_code == 400+++async def test_removing_the_logo_leaves_documents_that_used_it(+ client: AsyncClient, biz_headers+):+ logo_id = (await _put_logo(client, biz_headers)).json()["logo_id"]+ invoice = await make_invoice(client, biz_headers)++ cleared = await client.delete("/api/invoices/settings/logo", headers=biz_headers)+ assert cleared.json()["logo_id"] is None++ # The invoice issued under it still draws it.+ doc = await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ assert doc.json()["logo_url"] == f"/api/invoices/logo/{logo_id}"+++async def test_the_shared_page_serves_the_logo_through_its_token(+ client: AsyncClient, biz_headers+):+ """The client opening a link has no session, so the mark has to be+ reachable by the token and by nothing else."""+ await _put_logo(client, biz_headers)+ invoice = await make_invoice(client, biz_headers)+ token = (+ await client.post(f"/api/invoices/{invoice['id']}/share", headers=biz_headers)+ ).json()["token"]++ shared = await client.get(f"/api/public/invoices/{token}")+ assert shared.json()["logo_url"] == f"/api/public/invoices/{token}/logo"+ # The workspace's internal handle for the file is not in the response.+ assert "logo_id" not in shared.json()++ served = await client.get(f"/api/public/invoices/{token}/logo")+ assert served.status_code == 200+ assert served.headers["content-type"] == "image/png"+++async def test_a_unit_is_printed_beside_the_quantity(client: AsyncClient, biz_headers):+ """"32 hours x 180.00" is a claim the payer can check. "32 x 180.00"+ is one they have to take on trust."""+ invoice = await make_invoice(+ client, biz_headers,+ lines=[{"description": "Desenvolvimento", "quantity": "32", "unit": "horas",+ "unit_price": "180.00"}],+ total="5760.00",+ )+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ ).json()+ assert doc["lines"][0]["unit"] == "horas"++ import io as _io++ import pypdf as _pypdf++ pdf = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ text = _pypdf.PdfReader(_io.BytesIO(pdf.content)).pages[0].extract_text()+ assert "32 horas" in text+++async def test_a_line_without_a_unit_reads_as_it_always_did(+ client: AsyncClient, biz_headers+):+ """Optional means optional: nothing is invented for a line that+ counts nothing in particular."""+ invoice = await make_invoice(+ client, biz_headers,+ lines=[{"description": "Projeto fechado", "quantity": "1", "unit_price": "900.00"}],+ total="900.00",+ )+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ ).json()+ assert doc["lines"][0]["unit"] is None+++async def test_a_client_name_with_markup_survives_the_pdf(+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws, test_user+):+ """ReportLab reads its argument as markup, so an unescaped `<Ltda>`+ was swallowed as an unknown tag: the client's name went out on the+ document truncated, with nothing to notice it by."""+ payee = Payee(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=uuid.UUID(business_ws["id"]),+ name="Alpha & Beta <Ltda>",+ )+ session.add(payee)+ await session.commit()++ invoice = await make_invoice(+ client, biz_headers, payee_id=str(payee.id),+ lines=[{"description": "R&D <phase 1>", "quantity": "1", "unit_price": "100.00"}],+ )+ pdf = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)+ assert pdf.status_code == 200++ import io as _io++ import pypdf as _pypdf++ text = _pypdf.PdfReader(_io.BytesIO(pdf.content)).pages[0].extract_text()+ assert "Alpha & Beta <Ltda>" in text+ assert "R&D <phase 1>" in text+++def test_an_oversized_raster_is_refused_before_it_is_decoded():+ """A 10,000 x 10,000 PNG of flat colour is a few hundred kilobytes and+ asks for hundreds of megabytes to decode. Every size limit above lets+ it through, and `thumbnail` only shrinks it long afterwards."""+ import io as _io++ from PIL import Image as _Image++ from app.services import invoice_logo_service++ buf = _io.BytesIO()+ _Image.new("RGB", (10000, 10000), (255, 0, 0)).save(buf, format="PNG")+ assert len(buf.getvalue()) < 1_000_000, "the point is that it is small"++ with pytest.raises(ValueError, match="megapixels"):+ invoice_logo_service.normalise(buf.getvalue(), "image/png")+++def test_a_line_taller_than_a_page_still_finishes():+ """It used to hang, not fail. `split` returned nothing for a row+ taller than the space, the loop asked for a fresh page, failed again+ on the empty page and asked again — holding the worker until+ something killed it, which is worse than an error the caller can see.++ Guarded twice: the table may now break inside a row, and a failure to+ split on an already-empty page draws the content instead of asking+ for one more."""+ import signal++ huge = ("Servico de consultoria detalhado " * 400).strip()++ def give_up(signum, frame):+ raise AssertionError("pagination did not terminate")++ signal.signal(signal.SIGALRM, give_up)+ signal.alarm(20)+ try:+ document = _doc(1)+ document.lines[0].description = huge+ pdf = invoice_pdf.render_pdf(document)+ finally:+ signal.alarm(0)++ import io as _io++ import pypdf as _pypdf++ assert pdf.startswith(b"%PDF")+ assert len(_pypdf.PdfReader(_io.BytesIO(pdf)).pages) >= 1diff --git a/backend/tests/test_invoice_service.py b/backend/tests/test_invoice_service.pynew file mode 100644index 00000000..7de238d6--- /dev/null+++ b/backend/tests/test_invoice_service.py@@ -0,0 +1,455 @@+"""Unit tests for the ledger's rules, below the HTTP layer.++The API tests cover the journeys. These cover the arithmetic and the+boundaries: which state wins when a decision and a fact disagree, where+one aging bucket ends and the next begins, and whether the N:N+allocation table really is N:N — the claim the whole schema rests on.+"""+import uuid+from datetime import date, datetime, timedelta, timezone+from decimal import Decimal++import pytest+import pytest_asyncio+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.account import Account+from app.models.invoice import Invoice, InvoiceAllocation+from app.models.transaction import Transaction+from app.models.workspace import Workspace, WorkspaceMember+from app.services import invoice_service as svc++TODAY = date(2026, 8, 26)+++def build_invoice(**overrides) -> Invoice:+ """An in-memory invoice. Not persisted: `derive_state` and friends are+ pure functions of the row plus its allocations."""+ invoice = Invoice(+ id=uuid.uuid4(),+ workspace_id=uuid.uuid4(),+ status="open",+ issue_date=TODAY - timedelta(days=10),+ due_date=TODAY + timedelta(days=10),+ currency="USD",+ total=Decimal("1000.00"),+ )+ for key, value in overrides.items():+ setattr(invoice, key, value)+ if not hasattr(invoice, "allocations") or invoice.allocations is None:+ invoice.allocations = []+ return invoice+++def allocation(amount: str) -> InvoiceAllocation:+ return InvoiceAllocation(+ id=uuid.uuid4(),+ amount=Decimal(amount),+ method="manual",+ allocated_at=datetime(2026, 8, 20, tzinfo=timezone.utc),+ )+++# ---------------------------------------------------------------------------+# derive_state — the rule the whole design rests on+# ---------------------------------------------------------------------------+class TestDeriveState:+ def test_stored_decisions_pass_straight_through(self):+ for status in ("draft", "void", "uncollectible"):+ assert svc.derive_state(build_invoice(status=status), TODAY) == status++ def test_a_decision_outranks_a_fact(self):+ """Voided and written-off invoices are never 'overdue' or 'partial'.++ This ordering is the reason the function exists: a stored status+ records what a person decided, and no amount of arithmetic may+ overrule it.+ """+ past_due = build_invoice(+ status="void", due_date=TODAY - timedelta(days=30), allocations=[allocation("400.00")]+ )+ assert svc.derive_state(past_due, TODAY) == "void"++ written_off = build_invoice(+ status="uncollectible",+ due_date=TODAY - timedelta(days=30),+ allocations=[allocation("400.00")],+ )+ assert svc.derive_state(written_off, TODAY) == "uncollectible"++ def test_open_with_nothing_received(self):+ assert svc.derive_state(build_invoice(), TODAY) == "open"++ def test_partial_once_some_money_is_bound(self):+ invoice = build_invoice(allocations=[allocation("250.00")])+ assert svc.derive_state(invoice, TODAY) == "partial"++ def test_paid_when_the_balance_reaches_zero(self):+ invoice = build_invoice(allocations=[allocation("600.00"), allocation("400.00")])+ assert svc.derive_state(invoice, TODAY) == "paid"++ def test_paid_wins_over_overdue(self):+ """A settled invoice is not late, however long it took."""+ invoice = build_invoice(+ due_date=TODAY - timedelta(days=90), allocations=[allocation("1000.00")]+ )+ assert svc.derive_state(invoice, TODAY) == "paid"++ def test_overdue_wins_over_partial(self):+ """A part-paid invoice past its date reads as late, not as partial —+ the thing the user needs to act on is the lateness."""+ invoice = build_invoice(+ due_date=TODAY - timedelta(days=1), allocations=[allocation("500.00")]+ )+ assert svc.derive_state(invoice, TODAY) == "overdue"++ def test_due_today_is_not_yet_overdue(self):+ assert svc.derive_state(build_invoice(due_date=TODAY), TODAY) == "open"++ def test_one_day_past_is_overdue(self):+ invoice = build_invoice(due_date=TODAY - timedelta(days=1))+ assert svc.derive_state(invoice, TODAY) == "overdue"+ assert svc.days_overdue(invoice, TODAY) == 1++ def test_over_allocation_still_reads_paid_rather_than_negative(self):+ """Defence in depth: the service refuses over-allocation, but if a+ row ever got in another way, the state must not become nonsense."""+ invoice = build_invoice(allocations=[allocation("1200.00")])+ assert svc.derive_state(invoice, TODAY) == "paid"+ assert svc.balance(invoice) == Decimal("-200.00")++ def test_days_overdue_is_zero_for_anything_not_overdue(self):+ for invoice in (+ build_invoice(),+ build_invoice(status="void", due_date=TODAY - timedelta(days=5)),+ build_invoice(allocations=[allocation("1000.00")], due_date=TODAY - timedelta(days=5)),+ ):+ assert svc.days_overdue(invoice, TODAY) == 0+++class TestBalanceMath:+ def test_sums_every_allocation(self):+ invoice = build_invoice(+ allocations=[allocation("100.00"), allocation("250.50"), allocation("49.50")]+ )+ assert svc.allocated_total(invoice) == Decimal("400.00")+ assert svc.balance(invoice) == Decimal("600.00")++ def test_zero_allocations_leaves_the_whole_total(self):+ assert svc.balance(build_invoice()) == Decimal("1000.00")++ def test_decimal_all_the_way_down(self):+ """Money is never a float here. Three payments of 333.33 against+ 1000.00 must leave exactly 0.01, not 0.010000000000047."""+ invoice = build_invoice(+ allocations=[allocation("333.33"), allocation("333.33"), allocation("333.33")]+ )+ assert svc.balance(invoice) == Decimal("0.01")+ assert isinstance(svc.balance(invoice), Decimal)+++# ---------------------------------------------------------------------------+# Presets and settings+# ---------------------------------------------------------------------------+class TestPresets:+ def test_tracking_opens_immediately_with_no_document(self):+ preset = svc.PRESETS["tracking"]+ assert preset["initial_state"] == "open"+ assert preset["document_required"] is False+ assert preset["tax_fields"] == "hidden"++ def test_document_starts_as_a_draft_and_needs_lines(self):+ preset = svc.PRESETS["document"]+ assert preset["initial_state"] == "draft"+ assert preset["document_required"] is True+ # At least optional: an EU B2B invoice without discriminated VAT+ # is not a valid invoice, so the fields have to be reachable.+ assert preset["tax_fields"] == "optional"++ def test_only_two_presets_exist(self):+ assert set(svc.PRESETS) == {"tracking", "document"}+++# ---------------------------------------------------------------------------+# Persistence-level behaviour+# ---------------------------------------------------------------------------+@pytest_asyncio.fixture+async def workspace(session: AsyncSession, test_user) -> Workspace:+ ws = Workspace(id=uuid.uuid4(), name="PJ", kind="business", created_by_user_id=test_user.id)+ session.add(ws)+ await session.flush()+ session.add(+ WorkspaceMember(id=uuid.uuid4(), workspace_id=ws.id, user_id=test_user.id, role="owner")+ )+ await session.commit()+ return ws+++@pytest_asyncio.fixture+async def credit(session: AsyncSession, workspace, test_user) -> Transaction:+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=workspace.id,+ name="Conta", 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=workspace.id,+ account_id=account.id, description="PAYOUT", amount=Decimal("2000.00"),+ currency="USD", date=TODAY, type="credit", source="manual",+ )+ session.add(tx)+ await session.commit()+ return tx+++async def create(session, workspace, user, **data):+ payload = {"total": Decimal("1000.00"), "due_date": TODAY + timedelta(days=10)}+ payload.update(data)+ invoice = await svc.create_invoice(session, workspace.id, user.id, payload)+ await session.commit()+ return invoice+++class TestAllocationTable:+ async def test_one_transaction_settles_several_invoices(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ """The N:N claim, exercised.++ A gateway payout is one bank credit covering many invoices. A+ foreign key on the transaction could not express this, which is+ why the relationship lives in its own table with an amount.+ """+ first = await create(session, workspace, test_user, total=Decimal("800.00"))+ second = await create(session, workspace, test_user, total=Decimal("1200.00"))++ await svc.allocate(session, first, credit.id, Decimal("800.00"))+ await svc.allocate(session, second, credit.id, Decimal("1200.00"))+ await session.commit()++ assert svc.derive_state(first, TODAY) == "paid"+ assert svc.derive_state(second, TODAY) == "paid"+ # Same transaction, two invoices, two rows.+ assert first.allocations[0].transaction_id == credit.id+ assert second.allocations[0].transaction_id == credit.id++ async def test_several_transactions_settle_one_invoice(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ """And the other direction: a Pix-first market pays in parts."""+ account_id = credit.account_id+ second_credit = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=workspace.id,+ account_id=account_id, description="PIX 2", amount=Decimal("400.00"),+ currency="USD", date=TODAY, type="credit", source="manual",+ )+ session.add(second_credit)+ await session.commit()++ invoice = await create(session, workspace, test_user, total=Decimal("1000.00"))+ await svc.allocate(session, invoice, credit.id, Decimal("600.00"))+ assert svc.derive_state(invoice, TODAY) == "partial"+ await svc.allocate(session, invoice, second_credit.id, Decimal("400.00"))+ await session.commit()+ assert svc.derive_state(invoice, TODAY) == "paid"+ assert len(invoice.allocations) == 2++ async def test_default_amount_applies_as_much_as_fits(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ """One payment closing one invoice must not require typing the+ number twice — and a larger inflow must not over-apply."""+ invoice = await create(session, workspace, test_user, total=Decimal("500.00"))+ await svc.allocate(session, invoice, credit.id) # credit carries 2000+ await session.commit()+ assert invoice.allocations[0].amount == Decimal("500.00")+ assert svc.balance(invoice) == Decimal("0.00")++ async def test_unallocating_restores_the_balance(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ invoice = await create(session, workspace, test_user)+ await svc.allocate(session, invoice, credit.id, Decimal("400.00"))+ await session.commit()+ await svc.unallocate(session, invoice, invoice.allocations[0].id)+ await session.commit()+ assert svc.balance(invoice) == Decimal("1000.00")+ assert svc.derive_state(invoice, TODAY) == "open"+++class TestNumbering:+ async def test_the_counter_never_moves_backwards(+ self, session: AsyncSession, workspace, test_user+ ):+ """A voided invoice keeps its number and the next one moves on.++ Reusing it would put two different documents under one+ identifier — forbidden where numbering is regulated, and+ confusing everywhere else.+ """+ first = await create(session, workspace, test_user)+ await svc.void_invoice(session, first)+ await session.commit()+ assert first.number == 1+ assert first.status == "void"++ second = await create(session, workspace, test_user)+ assert second.number == 2++ async def test_drafts_consume_no_number(self, session: AsyncSession, workspace, test_user):+ await svc.update_settings(session, workspace.id, {"preset": "document"})+ await session.commit()+ draft = await create(+ session, workspace, test_user,+ lines=[{"description": "Work", "quantity": 1, "unit_price": 900}],+ )+ assert draft.status == "draft"+ assert draft.number is None++ await svc.issue_invoice(session, draft)+ await session.commit()+ assert draft.number == 1+++class TestSnapshot:+ async def test_freezes_issuer_and_labels(self, session: AsyncSession, workspace, test_user):+ await svc.update_settings(+ session, workspace.id,+ {"issuer_display_name": "Alpha ME", "logo_url": "https://x/logo.png",+ "template": {"labels": {"quantity": "Hours"}}},+ )+ await session.commit()+ invoice = await create(session, workspace, test_user)+ assert invoice.snapshot["issuer"]["display_name"] == "Alpha ME"+ assert invoice.snapshot["template"]["labels"]["quantity"] == "Hours"++ # Changing settings afterwards must not rewrite the document.+ await svc.update_settings(session, workspace.id, {"issuer_display_name": "Beta LTDA"})+ await session.commit()+ await session.refresh(invoice)+ assert invoice.snapshot["issuer"]["display_name"] == "Alpha ME"++ async def test_records_the_absence_of_a_prefix_as_a_real_answer(+ self, session: AsyncSession, workspace, test_user+ ):+ """The snapshot says "no prefix", not "unknown".++ The frontend relies on this to keep an invoice issued as "1"+ reading as "1" after someone later sets a prefix.+ """+ invoice = await create(session, workspace, test_user)+ assert "number_prefix" in invoice.snapshot+ assert invoice.snapshot["number_prefix"] is None+++class TestAgingBuckets:+ async def test_bucket_boundaries(self, session: AsyncSession, workspace, test_user):+ """30/31 and 60/61 are where money moves bucket. Off-by-one here+ misreports every aging report the accountant reads."""+ cases = [+ (0, "current"), # due today+ (1, "d1_30"),+ (30, "d1_30"),+ (31, "d31_60"),+ (60, "d31_60"),+ (61, "d61_90"),+ (90, "d61_90"),+ (91, "d90_plus"),+ ]+ for days_late, _ in cases:+ await create(+ session, workspace, test_user,+ total=Decimal("100.00"),+ issue_date=TODAY - timedelta(days=days_late + 30),+ due_date=TODAY - timedelta(days=days_late),+ )+ summary = await svc.aging_summary(session, workspace.id, TODAY)+ counts = {}+ for _, bucket in cases:+ counts[bucket] = counts.get(bucket, 0) + 1+ for bucket, n in counts.items():+ assert summary["buckets"][bucket] == Decimal("100.00") * n, bucket++ async def test_drafts_and_terminal_states_are_excluded(+ self, session: AsyncSession, workspace, test_user+ ):+ live = await create(session, workspace, test_user, total=Decimal("500.00"))+ voided = await create(session, workspace, test_user, total=Decimal("700.00"))+ await svc.void_invoice(session, voided)+ written_off = await create(session, workspace, test_user, total=Decimal("300.00"))+ await svc.mark_uncollectible(session, written_off)+ await session.commit()++ summary = await svc.aging_summary(session, workspace.id, TODAY)+ assert summary["outstanding"] == Decimal("500.00")+ assert live.id in {i.id for i in summary["upcoming"]}+++class TestCompetenceDate:+ async def test_defaults_to_the_issue_date(self, session: AsyncSession, workspace, test_user):+ invoice = await create(session, workspace, test_user)+ assert invoice.competence_date == invoice.issue_date++ async def test_can_diverge_for_work_delivered_earlier(+ self, session: AsyncSession, workspace, test_user+ ):+ """Delivered in July, invoiced in August: accrual accounting books+ July. Both dates are stored so both reports are possible."""+ delivered = date(2026, 7, 31)+ invoice = await create(session, workspace, test_user, competence_date=delivered)+ assert invoice.competence_date == delivered+ assert invoice.issue_date != delivered+++class TestAllocationProvenance:+ """`method` records who or what decided, and it is not an enum.++ The ids come from the reconciliation policy — a document the user will+ eventually edit — so closing this set would mean a migration every time+ somebody adds a strategy.+ """++ async def test_a_strategy_id_round_trips(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ # The longest id in the shipped policy is 30 characters, which the+ # column was originally too narrow to hold.+ strategy = "same_client_net_of_withholding"+ assert len(strategy) > 20++ invoice = await create(session, workspace, test_user)+ await svc.allocate(session, invoice, credit.id, Decimal("100.00"), method=strategy)+ await session.commit()+ await session.refresh(invoice, ["allocations"])+ assert invoice.allocations[0].method == strategy++ async def test_manual_is_the_default(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ from app.models.invoice import MANUAL_METHOD++ invoice = await create(session, workspace, test_user)+ await svc.allocate(session, invoice, credit.id, Decimal("100.00"))+ await session.commit()+ await session.refresh(invoice, ["allocations"])+ assert invoice.allocations[0].method == MANUAL_METHOD++ async def test_an_automatic_decision_is_not_a_trusted_one(+ self, session: AsyncSession, workspace, test_user, credit+ ):+ """Every guard runs regardless of who decided. A matcher that could+ over-allocate by claiming to be automatic would be a matcher that+ can corrupt the ledger."""+ invoice = await create(session, workspace, test_user, total=Decimal("100.00"))+ with pytest.raises(svc.InvoiceError) as exc:+ await svc.allocate(+ session, invoice, credit.id, Decimal("500.00"), method="same_client_exact"+ )+ assert exc.value.code == "over_allocation"diff --git a/backend/tests/test_invoices_api.py b/backend/tests/test_invoices_api.pynew file mode 100644index 00000000..a0be0d5e--- /dev/null+++ b/backend/tests/test_invoices_api.py@@ -0,0 +1,1430 @@+"""The invoicing ledger, end to end.++Two things these tests exist to pin down, beyond the usual CRUD:++ 1. **A personal workspace cannot reach any of it.** Hiding the nav link+ is not enforcement; every route must 404 for a workspace without the+ module, or the "no impact on personal finance" promise is decoration.+ 2. **Derived state is derived.** No status column is ever written for+ paid/partial/overdue, so the assertions here read the same value the+ UI does, computed from allocations and the due date.+"""+import uuid+from datetime import date, timedelta+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.payee import Payee+from app.models.transaction import Transaction+++@pytest_asyncio.fixture+async def personal_ws(session: AsyncSession, test_user):+ """The user's personal workspace, resolved by kind.++ Not the shared `test_workspace` fixture: that one takes the first row+ with no ORDER BY, so once these tests create a business workspace it+ can return either. Which workspace is which is the whole subject+ here, so it is pinned explicitly.+ """+ from sqlalchemy import select++ from app.models.workspace import Workspace, WorkspaceMember++ result = await session.execute(+ select(Workspace)+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)+ .where(WorkspaceMember.user_id == test_user.id, Workspace.kind == "personal")+ .order_by(Workspace.created_at.asc())+ .limit(1)+ )+ return result.scalar_one()+++@pytest_asyncio.fixture+async def business_ws(client: AsyncClient, auth_headers) -> dict:+ """A business workspace — the only kind that has this module."""+ resp = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Consultoria", "kind": "business", "self_membership": True},+ )+ assert resp.status_code == 201, resp.text+ body = resp.json()+ assert "invoices" in body["enabled_modules"]+ return body+++@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 client_payee(session: AsyncSession, business_ws, test_user) -> Payee:+ payee = Payee(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=uuid.UUID(business_ws["id"]),+ name="Cliente Alpha",+ source="manual",+ )+ session.add(payee)+ await session.commit()+ return payee+++@pytest_asyncio.fixture+async def inflow(session: AsyncSession, business_ws, test_user) -> Transaction:+ """A credit that landed in the business workspace."""+ account = Account(+ id=uuid.uuid4(),+ user_id=test_user.id,+ workspace_id=uuid.UUID(business_ws["id"]),+ name="Conta 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=uuid.UUID(business_ws["id"]),+ account_id=account.id,+ description="PIX RECEBIDO ALPHA",+ amount=Decimal("3000.00"),+ currency="USD",+ date=date.today(),+ type="credit",+ source="manual",+ )+ session.add(tx)+ await session.commit()+ return tx+++async def _create(client, headers, **overrides):+ payload = {"total": "3000.00", "due_date": str(date.today() + timedelta(days=15))}+ payload.update(overrides)+ resp = await client.post("/api/invoices", headers=headers, json=payload)+ assert resp.status_code == 201, resp.text+ return resp.json()+++# ---------------------------------------------------------------------------+# Module isolation — the promise that personal users are untouched+# ---------------------------------------------------------------------------+async def test_personal_workspace_cannot_reach_any_invoice_route(+ client: AsyncClient, auth_headers, personal_ws+):+ """Every route, not a sample: one ungated route is the whole hole."""+ personal = {**auth_headers, "X-Workspace-Id": str(personal_ws.id)}+ fake = str(uuid.uuid4())+ routes = [+ ("get", "/api/invoices", None),+ ("post", "/api/invoices", {"total": "10.00"}),+ ("get", "/api/invoices/settings", None),+ ("patch", "/api/invoices/settings", {"preset": "document"}),+ ("get", "/api/invoices/summary", None),+ ("get", f"/api/invoices/{fake}", None),+ ("patch", f"/api/invoices/{fake}", {"notes": "x"}),+ ("delete", f"/api/invoices/{fake}", None),+ ("post", f"/api/invoices/{fake}/issue", None),+ ("post", f"/api/invoices/{fake}/void", None),+ ("post", f"/api/invoices/{fake}/uncollectible", None),+ ("post", f"/api/invoices/{fake}/reopen", None),+ ("post", f"/api/invoices/{fake}/allocations", {"transaction_id": fake}),+ ("delete", f"/api/invoices/{fake}/allocations/{fake}", None),+ ]+ for method, url, body in routes:+ call = getattr(client, method)+ resp = await call(url, headers=personal, **({"json": body} if body else {}))+ # 404 rather than 403: a workspace without the module should not+ # be able to tell the feature exists.+ assert resp.status_code == 404, f"{method.upper()} {url} -> {resp.status_code}"+++async def test_personal_workspace_never_lists_the_module(+ client: AsyncClient, auth_headers, personal_ws+):+ resp = await client.get(+ "/api/workspaces/current",+ headers={**auth_headers, "X-Workspace-Id": str(personal_ws.id)},+ )+ assert "invoices" not in resp.json()["enabled_modules"]+++async def test_invoice_in_one_workspace_is_invisible_in_another(+ client: AsyncClient, auth_headers, biz_headers, business_ws+):+ created = await _create(client, biz_headers)+ other = await client.post(+ "/api/workspaces",+ headers=auth_headers,+ json={"name": "Outra PJ", "kind": "business", "self_membership": True},+ )+ other_headers = {**auth_headers, "X-Workspace-Id": other.json()["id"]}+ resp = await client.get(f"/api/invoices/{created['id']}", headers=other_headers)+ assert resp.status_code == 404+ assert await (await client.get("/api/invoices", headers=other_headers)).aread() == b"[]" or (+ (await client.get("/api/invoices", headers=other_headers)).json() == []+ )+++# ---------------------------------------------------------------------------+# Lifecycle: the stored decisions+# ---------------------------------------------------------------------------+async def test_tracking_preset_opens_immediately_and_numbers(client: AsyncClient, biz_headers):+ """The three-field flow: money is already owed, so no ceremony."""+ invoice = await _create(client, biz_headers)+ assert invoice["status"] == "open"+ assert invoice["state"] == "open"+ assert invoice["number"] == 1+ second = await _create(client, biz_headers)+ assert second["number"] == 2+++async def test_document_preset_starts_as_draft_and_requires_lines(+ client: AsyncClient, biz_headers+):+ resp = await client.patch(+ "/api/invoices/settings", headers=biz_headers, json={"preset": "document"}+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["document_required"] is True+ assert resp.json()["initial_state"] == "draft"++ bare = await client.post(+ "/api/invoices", headers=biz_headers, json={"total": "100.00"}+ )+ assert bare.status_code == 400+ assert bare.json()["detail"]["code"] == "lines_required"++ withlines = await _create(+ client,+ biz_headers,+ lines=[{"description": "Consultoria", "quantity": "10", "unit_price": "150.00"}],+ )+ assert withlines["status"] == "draft"+ # A draft carries no number — the DB constraint says so too.+ assert withlines["number"] is None+ assert withlines["total"] == "1500.00"++ issued = await client.post(+ f"/api/invoices/{withlines['id']}/issue", headers=biz_headers+ )+ assert issued.status_code == 200, issued.text+ assert issued.json()["status"] == "open"+ assert issued.json()["number"] == 1+++async def test_language_never_changes_behaviour(client: AsyncClient, biz_headers):+ """Preset drives behaviour; the UI language drives labels. Never the reverse."""+ await client.patch(+ f"/api/workspaces/{biz_headers['X-Workspace-Id']}",+ headers=biz_headers,+ json={"locale": "pt-BR"},+ )+ invoice = await _create(client, biz_headers)+ assert invoice["status"] == "open", "pt-BR must not imply a different preset"+++async def test_only_drafts_are_deletable(client: AsyncClient, biz_headers):+ issued = await _create(client, biz_headers)+ resp = await client.delete(f"/api/invoices/{issued['id']}", headers=biz_headers)+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "only_drafts_deletable"+++async def test_void_keeps_the_number_and_never_reuses_it(client: AsyncClient, biz_headers):+ first = await _create(client, biz_headers)+ assert first["number"] == 1+ voided = await client.post(f"/api/invoices/{first['id']}/void", headers=biz_headers)+ assert voided.status_code == 200, voided.text+ assert voided.json()["state"] == "void"+ assert voided.json()["number"] == 1, "a voided invoice keeps its number"++ # The counter moved on. Reissuing 1 would put two documents under one+ # identifier, which is the thing numbering rules exist to prevent.+ nxt = await _create(client, biz_headers)+ assert nxt["number"] == 2+++async def test_issued_invoice_financials_are_frozen(client: AsyncClient, biz_headers):+ invoice = await _create(client, biz_headers)+ resp = await client.patch(+ f"/api/invoices/{invoice['id']}", headers=biz_headers, json={"total": "9999.00"}+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "issued_invoice_immutable"++ # Notes are the seller's own record and stay editable.+ ok = await client.patch(+ f"/api/invoices/{invoice['id']}", headers=biz_headers, json={"notes": "ligar quinta"}+ )+ assert ok.status_code == 200, ok.text+ assert ok.json()["notes"] == "ligar quinta"+++# ---------------------------------------------------------------------------+# Derived state: the facts about money and time+# ---------------------------------------------------------------------------+async def test_partial_then_paid_walks_without_any_status_write(+ client: AsyncClient, biz_headers, inflow+):+ invoice = await _create(client, biz_headers)++ half = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": "1500.00"},+ )+ assert half.status_code == 201, half.text+ body = half.json()+ assert body["state"] == "partial"+ assert body["status"] == "open", "the stored decision did not change"+ assert body["balance"] == "1500.00"+ assert body["amount_paid"] == "1500.00"+++async def test_full_allocation_reads_paid(client: AsyncClient, biz_headers, inflow):+ invoice = await _create(client, biz_headers)+ resp = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id)},+ )+ assert resp.status_code == 201, resp.text+ # No amount given: defaults to as much as fits, which is the whole+ # invoice here. One click for the common case.+ assert resp.json()["state"] == "paid"+ assert resp.json()["balance"] == "0.00"+++async def test_unlinking_restores_both_sides(client: AsyncClient, biz_headers, inflow):+ invoice = await _create(client, biz_headers)+ allocated = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id)},+ )+ allocation_id = allocated.json()["allocations"][0]["id"]+ removed = await client.delete(+ f"/api/invoices/{invoice['id']}/allocations/{allocation_id}", headers=biz_headers+ )+ assert removed.status_code == 200, removed.text+ assert removed.json()["state"] == "open"+ assert removed.json()["balance"] == "3000.00"+ assert removed.json()["allocations"] == []+++async def test_overdue_needs_no_job(client: AsyncClient, biz_headers):+ """The point of deriving: nothing ran, and it still reads overdue."""+ invoice = await _create(+ client,+ biz_headers,+ issue_date=str(date.today() - timedelta(days=40)),+ due_date=str(date.today() - timedelta(days=10)),+ )+ resp = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)+ assert resp.json()["state"] == "overdue"+ assert resp.json()["days_overdue"] == 10+++async def test_moving_the_due_date_undoes_overdue_with_no_compensating_write(+ client: AsyncClient, biz_headers+):+ """Peers that store `overdue` need SQL to unset it. We need nothing."""+ await client.patch("/api/invoices/settings", headers=biz_headers, json={"preset": "document"})+ invoice = await _create(+ client,+ biz_headers,+ issue_date=str(date.today() - timedelta(days=40)),+ due_date=str(date.today() - timedelta(days=10)),+ lines=[{"description": "Retainer", "quantity": "1", "unit_price": "500.00"}],+ )+ moved = await client.patch(+ f"/api/invoices/{invoice['id']}",+ headers=biz_headers,+ json={"due_date": str(date.today() + timedelta(days=10))},+ )+ assert moved.status_code == 200, moved.text+ assert moved.json()["state"] == "draft"+ issued = await client.post(f"/api/invoices/{invoice['id']}/issue", headers=biz_headers)+ assert issued.json()["state"] == "open"+ assert issued.json()["days_overdue"] == 0+++async def test_uncollectible_leaves_aging_and_is_never_paid(+ client: AsyncClient, biz_headers, inflow+):+ invoice = await _create(client, biz_headers)+ await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": "1000.00"},+ )+ written_off = await client.post(+ f"/api/invoices/{invoice['id']}/uncollectible", headers=biz_headers+ )+ assert written_off.status_code == 200, written_off.text+ # A decision outranks a fact: partly received, but given up on.+ assert written_off.json()["state"] == "uncollectible"++ summary = await client.get("/api/invoices/summary", headers=biz_headers)+ assert summary.json()["outstanding"] == "0.00"++ reopened = await client.post(f"/api/invoices/{invoice['id']}/reopen", headers=biz_headers)+ assert reopened.json()["state"] == "partial"+++# ---------------------------------------------------------------------------+# Allocation guards+# ---------------------------------------------------------------------------+async def test_cannot_over_allocate(client: AsyncClient, biz_headers, inflow):+ invoice = await _create(client, biz_headers, total="100.00")+ resp = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": "500.00"},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "over_allocation"+++async def test_same_transaction_twice_on_one_invoice_is_refused(+ client: AsyncClient, biz_headers, inflow+):+ invoice = await _create(client, biz_headers)+ first = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": "100.00"},+ )+ assert first.status_code == 201+ again = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": "100.00"},+ )+ assert again.status_code == 400+ assert again.json()["detail"]["code"] == "already_allocated"+++async def test_transaction_from_another_workspace_is_not_found(+ client: AsyncClient, auth_headers, biz_headers, session: AsyncSession, test_user, personal_ws+):+ """Cross-workspace binding must be impossible, and indistinguishable+ from a transaction that does not exist."""+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=personal_ws.id,+ name="Pessoal", type="checking", currency="USD", balance=Decimal("0"),+ )+ session.add(account)+ await session.flush()+ foreign = Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=personal_ws.id,+ account_id=account.id, description="pessoal", amount=Decimal("50.00"),+ currency="USD", date=date.today(), type="credit", source="manual",+ )+ session.add(foreign)+ await session.commit()++ invoice = await _create(client, biz_headers)+ resp = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(foreign.id)},+ )+ assert resp.status_code == 404+ assert resp.json()["detail"]["code"] == "transaction_not_found"+++async def test_void_refuses_while_money_is_linked(client: AsyncClient, biz_headers, inflow):+ invoice = await _create(client, biz_headers)+ await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": "100.00"},+ )+ resp = await client.post(f"/api/invoices/{invoice['id']}/void", headers=biz_headers)+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "void_with_allocations"+++# ---------------------------------------------------------------------------+# Aging + settings+# ---------------------------------------------------------------------------+async def test_summary_buckets_and_excludes_drafts(client: AsyncClient, biz_headers):+ await client.patch("/api/invoices/settings", headers=biz_headers, json={"preset": "document"})+ # A draft: written but never issued. Money nobody owes yet.+ await _create(+ client, biz_headers,+ lines=[{"description": "rascunho", "quantity": "1", "unit_price": "999.00"}],+ )+ await client.patch("/api/invoices/settings", headers=biz_headers, json={"preset": "tracking"})+ await _create(client, biz_headers, total="200.00",+ due_date=str(date.today() + timedelta(days=5)))+ await _create(client, biz_headers, total="300.00",+ issue_date=str(date.today() - timedelta(days=60)),+ due_date=str(date.today() - timedelta(days=45)))++ summary = (await client.get("/api/invoices/summary", headers=biz_headers)).json()+ assert summary["outstanding"] == "500.00", "the 999 draft must not appear"+ assert summary["overdue_amount"] == "300.00"+ assert summary["overdue_count"] == 1+ assert summary["buckets"]["current"] == "200.00"+ assert summary["buckets"]["d31_60"] == "300.00"+ assert len(summary["upcoming"]) == 1+++async def _upload_logo(client, headers):+ """A one-pixel PNG is enough: what is under test is the id it gets."""+ import io as _io++ from PIL import Image as _Image++ buf = _io.BytesIO()+ _Image.new("RGB", (8, 8), (79, 70, 229)).save(buf, format="PNG")+ return await client.post(+ "/api/invoices/settings/logo",+ headers=headers,+ files={"file": ("logo.png", buf.getvalue(), "image/png")},+ )+++async def test_settings_carry_presentation_and_survive_issuance(+ client: AsyncClient, biz_headers+):+ """Logo and labels are frozen at issuance — changing them later must+ not rewrite a document the client already received."""+ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={+ "issuer_display_name": "Alpha Consultoria ME",+ "footer_note": "Obrigado!",+ "number_prefix": "FAT-",+ "template": {"labels": {"quantity": "Horas"}, "custom_fields": [{"key": "po", "label": "PO"}]},+ },+ )+ first_logo = (await _upload_logo(client, biz_headers)).json()["logo_id"]++ invoice = await _create(client, biz_headers, custom_fields={"po": "PO-4471"})+ assert invoice["snapshot"]["issuer"]["logo_id"] == first_logo+ assert invoice["snapshot"]["template"]["labels"]["quantity"] == "Horas"+ assert invoice["custom_fields"]["po"] == "PO-4471"++ second = (await _upload_logo(client, biz_headers)).json()["logo_id"]+ assert second != first_logo+ after = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)+ assert after.json()["snapshot"]["issuer"]["logo_id"] == first_logo+++async def test_competence_date_defaults_to_issue_but_can_diverge(+ client: AsyncClient, biz_headers+):+ """Work delivered in one month, invoiced in the next: the accountant+ books the first. Both dates are stored so both reports are possible."""+ plain = await _create(client, biz_headers)+ assert plain["competence_date"] == plain["issue_date"]++ delivered = str(date.today() - timedelta(days=35))+ split = await _create(client, biz_headers, competence_date=delivered)+ assert split["competence_date"] == delivered+ assert split["issue_date"] != delivered+++async def test_due_date_defaults_to_payment_terms(client: AsyncClient, biz_headers):+ await client.patch(+ "/api/invoices/settings", headers=biz_headers, json={"default_payment_terms_days": 7}+ )+ resp = await client.post("/api/invoices", headers=biz_headers, json={"total": "10.00"})+ assert resp.status_code == 201, resp.text+ assert resp.json()["due_date"] == str(date.today() + timedelta(days=7))+++async def test_payee_from_another_workspace_is_refused(+ client: AsyncClient, biz_headers, session: AsyncSession, test_user, personal_ws+):+ stranger = Payee(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=personal_ws.id,+ name="Pessoal", source="manual",+ )+ session.add(stranger)+ await session.commit()+ resp = await client.post(+ "/api/invoices",+ headers=biz_headers,+ json={"total": "10.00", "payee_id": str(stranger.id)},+ )+ assert resp.status_code == 404+ assert resp.json()["detail"]["code"] == "payee_not_found"+++async def test_invoice_carries_its_client(client: AsyncClient, biz_headers, client_payee):+ invoice = await _create(client, biz_headers, payee_id=str(client_payee.id))+ assert invoice["payee"]["name"] == "Cliente Alpha"+ assert invoice["snapshot"]["counterparty"]["name"] == "Cliente Alpha"+++async def test_state_filter_uses_derived_values(client: AsyncClient, biz_headers, inflow):+ await _create(client, biz_headers, total="100.00")+ paid_one = await _create(client, biz_headers, total="50.00")+ await client.post(+ f"/api/invoices/{paid_one['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id)},+ )+ listed = await client.get("/api/invoices?state=paid", headers=biz_headers)+ assert [i["id"] for i in listed.json()] == [paid_one["id"]]+++# ---------------------------------------------------------------------------+# Role enforcement — the module gate and the role gate are separate questions+# ---------------------------------------------------------------------------+async def test_viewer_reads_but_never_writes(+ client: AsyncClient, auth_headers, biz_headers, business_ws, session: AsyncSession+):+ """A read-only member of a business workspace can see the ledger and+ change nothing in it.++ Both gates have to pass and they ask different questions: the module+ gate asks whether this workspace has invoicing, the role gate asks+ whether this member may write. This asserts the second one, on a+ workspace where the first already said yes.+ """+ import bcrypt as _bcrypt++ from app.models.user import User+ from app.models.workspace import WorkspaceMember++ invoice = await _create(client, biz_headers)++ viewer = 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(viewer)+ await session.flush()+ session.add(+ WorkspaceMember(+ id=uuid.uuid4(),+ workspace_id=uuid.UUID(business_ws["id"]),+ user_id=viewer.id,+ role="viewer",+ )+ )+ await session.commit()++ login = await client.post(+ "/api/auth/login",+ data={"username": "[email protected]", "password": "viewerpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ assert login.status_code == 200, login.text+ viewer_headers = {+ "Authorization": f"Bearer {login.json()['access_token']}",+ "X-Workspace-Id": business_ws["id"],+ }++ # Reads are fine.+ assert (await client.get("/api/invoices", headers=viewer_headers)).status_code == 200+ assert (await client.get("/api/invoices/summary", headers=viewer_headers)).status_code == 200+ assert (+ await client.get(f"/api/invoices/{invoice['id']}", headers=viewer_headers)+ ).status_code == 200++ # Every write is refused — 403 this time, not 404: the workspace does+ # have the module, so hiding its existence would be the wrong lie.+ writes = [+ ("post", "/api/invoices", {"total": "10.00"}),+ ("patch", f"/api/invoices/{invoice['id']}", {"notes": "x"}),+ ("delete", f"/api/invoices/{invoice['id']}", None),+ ("post", f"/api/invoices/{invoice['id']}/void", None),+ ("post", f"/api/invoices/{invoice['id']}/uncollectible", None),+ ("post", f"/api/invoices/{invoice['id']}/allocations", {"transaction_id": str(uuid.uuid4())}),+ ("patch", "/api/invoices/settings", {"preset": "document"}),+ ]+ for method, url, body in writes:+ call = getattr(client, method)+ resp = await call(url, headers=viewer_headers, **({"json": body} if body else {}))+ assert resp.status_code == 403, f"{method.upper()} {url} -> {resp.status_code}"+++# ---------------------------------------------------------------------------+# The filter bar: years and counts+# ---------------------------------------------------------------------------+async def test_facets_count_every_state_the_bar_offers(+ client: AsyncClient, biz_headers, inflow+):+ """A chip reading 3 must open a list of exactly 3.++ The counts come from the same derived state the list filter uses, so+ this asserts the two agree rather than that each is plausible on its+ own.+ """+ await _create(client, biz_headers, total="100.00") # open+ paid = await _create(client, biz_headers, total="50.00")+ await client.post(+ f"/api/invoices/{paid['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id)},+ )+ await _create(+ client, biz_headers, total="200.00",+ issue_date=str(date.today() - timedelta(days=40)),+ due_date=str(date.today() - timedelta(days=10)),+ ) # overdue++ facets = (await client.get("/api/invoices/facets", headers=biz_headers)).json()+ assert facets["counts"]["all"] == 3+ assert facets["counts"]["paid"] == 1+ assert facets["counts"]["overdue"] == 1+ # `open` means "still expected", which includes the overdue one.+ assert facets["counts"]["open"] == 2+ assert facets["counts"]["draft"] == 0++ for facet in ("paid", "overdue", "draft"):+ listed = await client.get(f"/api/invoices?state={facet}", headers=biz_headers)+ assert len(listed.json()) == facets["counts"][facet], facet+++async def test_facets_list_only_years_that_have_invoices(client: AsyncClient, biz_headers):+ await _create(client, biz_headers, issue_date="2024-06-10", due_date="2024-07-10")+ await _create(client, biz_headers, issue_date="2026-02-01", due_date="2026-03-01")+ facets = (await client.get("/api/invoices/facets", headers=biz_headers)).json()+ # Newest first: the picker opens on the year someone is most likely+ # to want, and an empty year is never offered.+ assert facets["years"] == [2026, 2024]+++async def test_facet_counts_respect_the_selected_year(client: AsyncClient, biz_headers):+ await _create(client, biz_headers, issue_date="2024-06-10", due_date="2024-07-10")+ await _create(client, biz_headers, issue_date="2026-02-01", due_date="2026-03-01")+ await _create(client, biz_headers, issue_date="2026-05-01", due_date="2026-06-01")++ scoped = (await client.get("/api/invoices/facets?year=2026", headers=biz_headers)).json()+ assert scoped["counts"]["all"] == 2+ # The year list itself is never narrowed, or picking a year would+ # remove every other year from the picker.+ assert scoped["years"] == [2026, 2024]++ assert (+ await client.get("/api/invoices/facets?year=2024", headers=biz_headers)+ ).json()["counts"]["all"] == 1+++async def test_the_year_filter_scopes_the_list(client: AsyncClient, biz_headers):+ old = await _create(client, biz_headers, issue_date="2024-06-10", due_date="2024-07-10")+ new = await _create(client, biz_headers, issue_date="2026-02-01", due_date="2026-03-01")++ listed = await client.get("/api/invoices?year=2024", headers=biz_headers)+ assert [i["id"] for i in listed.json()] == [old["id"]]++ listed = await client.get("/api/invoices?year=2026", headers=biz_headers)+ assert [i["id"] for i in listed.json()] == [new["id"]]++ # Omitting the year means every year, not the current one: the+ # default belongs to the UI, not to the API.+ assert len((await client.get("/api/invoices", headers=biz_headers)).json()) == 2+++async def test_the_year_filter_combines_with_state(client: AsyncClient, biz_headers):+ await _create(client, biz_headers, issue_date="2024-06-10", due_date="2024-07-10")+ await _create(client, biz_headers, issue_date="2026-02-01", due_date="2026-03-01")+ listed = await client.get("/api/invoices?year=2024&state=overdue", headers=biz_headers)+ assert len(listed.json()) == 1+++async def test_the_summary_is_not_scoped_by_year(client: AsyncClient, biz_headers):+ """An unpaid invoice from two years ago is still owed today, so+ "outstanding" has no year. Only the list is scoped."""+ await _create(client, biz_headers, total="900.00",+ issue_date="2024-06-10", due_date="2024-07-10")+ summary = (await client.get("/api/invoices/summary", headers=biz_headers)).json()+ assert summary["outstanding"] == "900.00"+++async def test_facets_are_gated_like_every_other_route(+ client: AsyncClient, auth_headers, personal_ws+):+ resp = await client.get(+ "/api/invoices/facets",+ headers={**auth_headers, "X-Workspace-Id": str(personal_ws.id)},+ )+ assert resp.status_code == 404+++# ---------------------------------------------------------------------------+# The payee lifecycle, which used to answer 500+# ---------------------------------------------------------------------------+async def test_deleting_a_client_with_invoices_is_refused_in_words(+ client: AsyncClient, biz_headers, client_payee+):+ """The RESTRICT foreign key is deliberate — deleting a client must+ never silently delete the record of money they owed — but it used to+ surface as a 500, which tells the user nothing."""+ await _create(client, biz_headers, payee_id=str(client_payee.id))++ resp = await client.delete(f"/api/payees/{client_payee.id}", headers=biz_headers)+ assert resp.status_code == 409, resp.text+ assert resp.json()["detail"]["code"] == "payee_has_invoices"+ assert resp.json()["detail"]["count"] == 1++ # And the client is still there afterwards.+ assert (+ await client.get(f"/api/payees/{client_payee.id}", headers=biz_headers)+ ).status_code == 200+++async def test_bulk_deleting_a_client_with_invoices_is_refused_too(+ client: AsyncClient, biz_headers, client_payee+):+ await _create(client, biz_headers, payee_id=str(client_payee.id))+ resp = await client.post(+ "/api/payees/bulk-delete", headers=biz_headers, json={"ids": [str(client_payee.id)]}+ )+ assert resp.status_code == 409+ assert resp.json()["detail"]["code"] == "payee_has_invoices"+++async def test_a_client_with_no_invoices_still_deletes(client: AsyncClient, biz_headers):+ created = await client.post(+ "/api/payees", headers=biz_headers, json={"name": "Sem cobranças"}+ )+ assert (+ await client.delete(f"/api/payees/{created.json()['id']}", headers=biz_headers)+ ).status_code == 204+++async def test_merging_clients_carries_their_invoices_across(+ client: AsyncClient, biz_headers, client_payee+):+ """Transactions already follow a merge; invoices have to as well.++ The two rows were one counterparty all along, and leaving the+ invoices behind would both strand them and trip the foreign key on+ the delete the merge performs.+ """+ duplicate = (+ await client.post("/api/payees", headers=biz_headers, json={"name": "Cliente Alpha (dup)"})+ ).json()+ invoice = await _create(client, biz_headers, payee_id=duplicate["id"])++ merged = await client.post(+ "/api/payees/merge",+ headers=biz_headers,+ json={"target_id": str(client_payee.id), "source_ids": [duplicate["id"]]},+ )+ assert merged.status_code == 200, merged.text++ moved = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)+ assert moved.json()["payee_id"] == str(client_payee.id)+ assert moved.json()["payee"]["name"] == "Cliente Alpha"+ # The duplicate is gone, which is the point of merging.+ assert (+ await client.get(f"/api/payees/{duplicate['id']}", headers=biz_headers)+ ).status_code == 404+++async def test_a_merge_does_not_rewrite_an_issued_document(+ client: AsyncClient, biz_headers, client_payee+):+ """The snapshot froze the client's name at issuance. Merging changes+ who the invoice is linked to, never what the client received."""+ duplicate = (+ await client.post("/api/payees", headers=biz_headers, json={"name": "Beta Dup LTDA"})+ ).json()+ invoice = await _create(client, biz_headers, payee_id=duplicate["id"])+ assert invoice["snapshot"]["counterparty"]["name"] == "Beta Dup LTDA"++ await client.post(+ "/api/payees/merge",+ headers=biz_headers,+ json={"target_id": str(client_payee.id), "source_ids": [duplicate["id"]]},+ )+ after = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)+ assert after.json()["snapshot"]["counterparty"]["name"] == "Beta Dup LTDA"+++# ---------------------------------------------------------------------------+# The badge on the transaction list+# ---------------------------------------------------------------------------+async def test_a_settling_transaction_carries_its_invoice(+ client: AsyncClient, biz_headers, inflow+):+ invoice = await _create(client, biz_headers)+ await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": "1000.00"},+ )++ listed = await client.get("/api/transactions?limit=50", headers=biz_headers)+ assert listed.status_code == 200, listed.text+ row = next(i for i in listed.json()["items"] if i["id"] == str(inflow.id))+ assert [link["invoice_id"] for link in row["invoice_links"]] == [invoice["id"]]+ assert row["invoice_links"][0]["number"] == invoice["number"]+ assert row["invoice_links"][0]["amount"] == "1000.00"+++async def test_an_unlinked_transaction_carries_nothing(+ client: AsyncClient, biz_headers, inflow+):+ listed = await client.get("/api/transactions?limit=50", headers=biz_headers)+ row = next(i for i in listed.json()["items"] if i["id"] == str(inflow.id))+ assert row["invoice_links"] == []+++async def test_a_personal_workspace_never_pays_for_the_badge(+ client: AsyncClient,+ auth_headers,+ personal_ws,+ session: AsyncSession,+ test_user,+ monkeypatch,+):+ """The query behind the badge never runs: a workspace without the+ module pays nothing for a feature it does not have.++ Asserted by watching the call rather than by reading the response.+ The field comes back as `[]` either way — that is its default — so an+ assertion on the value cannot tell a skipped query from one that ran+ and found nothing, which is the only thing this test is about."""+ account = Account(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=personal_ws.id,+ name="Pessoal", type="checking", currency="USD", balance=Decimal("0"),+ )+ session.add(account)+ await session.flush()+ session.add(+ Transaction(+ id=uuid.uuid4(), user_id=test_user.id, workspace_id=personal_ws.id,+ account_id=account.id, description="mercado", amount=Decimal("-50.00"),+ currency="USD", date=date.today(), type="debit", source="manual",+ )+ )+ await session.commit()++ headers = {**auth_headers, "X-Workspace-Id": str(personal_ws.id)}++ from app.services import invoice_service++ calls: list[uuid.UUID] = []+ real = invoice_service.invoice_links_for_transactions++ async def counting(+ session: AsyncSession, workspace_id: uuid.UUID, transaction_ids: list[uuid.UUID]+ ) -> dict[uuid.UUID, list[dict]]:+ calls.append(workspace_id)+ return await real(session, workspace_id, transaction_ids)++ monkeypatch.setattr(invoice_service, "invoice_links_for_transactions", counting)+ listed = await client.get("/api/transactions?limit=50", headers=headers)++ assert listed.status_code == 200+ assert calls == [], "the badge query ran in a workspace without the module"+ assert all(item["invoice_links"] == [] for item in listed.json()["items"])+++# ---------------------------------------------------------------------------+# Direction: two sides of one ledger, and neither leaks into the other+# ---------------------------------------------------------------------------+async def test_everything_written_today_is_a_receivable(client: AsyncClient, biz_headers):+ invoice = await _create(client, biz_headers)+ assert invoice["direction"] == "receivable"+++async def test_a_payable_never_appears_among_receivables(client: AsyncClient, biz_headers):+ """The whole reason the column exists. A supplier's bill inside+ "what my clients owe me" is not a filtering nicety, it is a wrong+ number on the screen someone makes decisions with."""+ receivable = await _create(client, biz_headers, total="1000.00")+ payable = await _create(client, biz_headers, total="400.00", direction="payable")+ assert payable["direction"] == "payable"++ listed = await client.get("/api/invoices", headers=biz_headers)+ assert [i["id"] for i in listed.json()] == [receivable["id"]]++ explicit = await client.get("/api/invoices?direction=payable", headers=biz_headers)+ assert [i["id"] for i in explicit.json()] == [payable["id"]]+++async def test_the_totals_are_per_side(client: AsyncClient, biz_headers):+ await _create(client, biz_headers, total="1000.00")+ await _create(client, biz_headers, total="400.00", direction="payable")++ receivables = (await client.get("/api/invoices/summary", headers=biz_headers)).json()+ assert receivables["outstanding"] == "1000.00"++ payables = (+ await client.get("/api/invoices/summary?direction=payable", headers=biz_headers)+ ).json()+ assert payables["outstanding"] == "400.00"+++async def test_the_counts_are_per_side(client: AsyncClient, biz_headers):+ await _create(client, biz_headers, total="1000.00")+ await _create(client, biz_headers, total="400.00", direction="payable")++ assert (+ await client.get("/api/invoices/facets", headers=biz_headers)+ ).json()["counts"]["all"] == 1+ assert (+ await client.get("/api/invoices/facets?direction=payable", headers=biz_headers)+ ).json()["counts"]["all"] == 1+++async def test_fetching_one_by_id_is_not_narrowed_by_side(client: AsyncClient, biz_headers):+ """An id already identifies one row. Scoping the lookup would 404 a+ payable a caller legitimately asked for."""+ payable = await _create(client, biz_headers, total="400.00", direction="payable")+ fetched = await client.get(f"/api/invoices/{payable['id']}", headers=biz_headers)+ assert fetched.status_code == 200+ assert fetched.json()["direction"] == "payable"+++async def test_an_unknown_side_is_refused(client: AsyncClient, biz_headers):+ resp = await client.get("/api/invoices?direction=sideways", headers=biz_headers)+ assert resp.status_code == 422+++# ---------------------------------------------------------------------------+# What a payable is, and what it is not+# ---------------------------------------------------------------------------+async def test_a_payable_document_names_the_supplier_as_the_issuer(+ client: AsyncClient, biz_headers, client_payee+):+ """We did not write this document; the supplier did. Rendering it+ under our own name would be the wrong claim to make on paper."""+ bill = await _create(client, biz_headers, direction="payable",+ payee_id=str(client_payee.id))+ doc = (+ await client.get(f"/api/invoices/{bill['id']}/document", headers=biz_headers)+ ).json()+ assert doc["issuer"]["name"] == "Cliente Alpha"+ assert doc["client"]["name"] != "Cliente Alpha"+ assert doc["direction"] == "payable"+++async def test_a_receivable_document_still_names_us_as_the_issuer(+ client: AsyncClient, biz_headers, client_payee+):+ invoice = await _create(client, biz_headers, payee_id=str(client_payee.id))+ doc = (+ await client.get(f"/api/invoices/{invoice['id']}/document", headers=biz_headers)+ ).json()+ assert doc["client"]["name"] == "Cliente Alpha"+ assert doc["issuer"]["name"] != "Cliente Alpha"+++async def test_a_payable_cannot_be_shared(client: AsyncClient, biz_headers):+ """Sharing sends your invoice to your client. A bill you received+ belongs to your supplier and has nobody to be sent to — publishing it+ is a leak with no upside."""+ bill = await _create(client, biz_headers, direction="payable")+ resp = await client.post(f"/api/invoices/{bill['id']}/share", headers=biz_headers)+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "payable_not_shareable"+++# ---------------------------------------------------------------------------+# Provenance — the seam every future intake writes through+# ---------------------------------------------------------------------------+async def test_an_imported_document_keeps_where_it_came_from(+ client: AsyncClient, biz_headers+):+ """Email, a photographed bill, a gateway sync: each arrives through+ these three fields, which is why they are accepted before any of+ those intakes exist."""+ bill = await _create(+ client, biz_headers, direction="payable", origin="imported",+ external_source="email", external_id="msg-42",+ )+ assert bill["origin"] == "imported"+ assert bill["external_source"] == "email"+ assert bill["external_id"] == "msg-42"+++async def test_an_import_must_say_where_it_came_from(client: AsyncClient, biz_headers):+ """Without the source there is no pair to converge on, so a re-sync+ creates a second row instead of updating the first."""+ resp = await client.post(+ "/api/invoices",+ headers=biz_headers,+ json={"total": "10.00", "origin": "imported"},+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "external_source_required"+++async def test_the_same_external_document_never_lands_twice(+ client: AsyncClient, biz_headers+):+ await _create(client, biz_headers, direction="payable", origin="imported",+ external_source="email", external_id="msg-42")+ second = await client.post(+ "/api/invoices",+ headers=biz_headers,+ json={"total": "10.00", "direction": "payable", "origin": "imported",+ "external_source": "email", "external_id": "msg-42"},+ )+ # The unique pair is what makes a re-sync converge rather than+ # duplicate, and the answer names the row that already holds the+ # document so a retried import can update it instead of guessing.+ assert second.status_code == 409+ assert second.json()["detail"]["code"] == "already_imported"+++async def test_a_locally_created_document_says_so(client: AsyncClient, biz_headers):+ invoice = await _create(client, biz_headers)+ assert invoice["origin"] == "local"+ assert invoice["external_source"] is None+++# ---------------------------------------------------------------------------+# Provenance decides numbering and the snapshot, not direction+# ---------------------------------------------------------------------------+async def test_an_import_never_takes_a_number_from_our_sequence(+ client: AsyncClient, biz_headers+):+ """The defect this exists for: a receivable imported as FAT-9931 came+ back numbered 4. That burns a number from a sequence meant to be+ gapless and renames a document its recipient already holds."""+ ours = await _create(client, biz_headers, total="100.00")+ assert ours["number"] == 1++ imported = await _create(+ client, biz_headers, total="1500.00", origin="imported",+ external_source="erp", external_id="FAT-9931", external_number="FAT-9931",+ )+ assert imported["external_number"] == "FAT-9931"+ assert imported["number"] is None++ # Our sequence did not move: the next document we write is 2.+ nxt = await _create(client, biz_headers, total="200.00")+ assert nxt["number"] == 2+++async def test_an_import_with_no_number_stays_unnumbered(+ client: AsyncClient, biz_headers+):+ """A source that numbers nothing leaves the column null rather than+ borrowing from ours."""+ imported = await _create(+ client, biz_headers, total="500.00", origin="imported",+ external_source="erp", external_id="no-number",+ )+ assert imported["number"] is None+ assert imported["external_number"] is None+ # And it is open, not draft: somebody issued it elsewhere, and a+ # draft state would claim we are still writing it.+ assert imported["status"] == "open"+++async def test_an_import_does_not_get_our_snapshot(client: AsyncClient, biz_headers):+ """Freezing our issuer identity at the moment we recorded someone+ else's document is a stamp with no meaning."""+ await client.patch(+ "/api/invoices/settings",+ headers=biz_headers,+ json={"issuer_display_name": "Alpha ME"},+ )+ imported = await _create(+ client, biz_headers, total="500.00", origin="imported",+ external_source="erp", external_id="abc",+ )+ assert imported["snapshot"] is None++ # A document we wrote still gets one.+ ours = await _create(client, biz_headers, total="100.00")+ assert ours["snapshot"]["issuer"]["display_name"] == "Alpha ME"+++async def test_the_rule_is_provenance_not_direction(client: AsyncClient, biz_headers):+ """An imported receivable is as much someone else's document as an+ imported payable. Direction has nothing to do with it."""+ for direction in ("receivable", "payable"):+ imported = await _create(+ client, biz_headers, total="120.00", direction=direction,+ origin="imported", external_source="erp", external_id=f"x-{direction}",+ )+ assert imported["snapshot"] is None, direction+ assert imported["number"] is None, direction++ for direction in ("receivable", "payable"):+ ours = await _create(client, biz_headers, total="120.00", direction=direction)+ assert ours["snapshot"] is not None, direction+ assert ours["number"] is not None, direction+++async def test_a_source_name_is_kept_verbatim(client: AsyncClient, biz_headers):+ """`2026/A/0031` is a name, not arithmetic. An integer column plus a+ series drops the padding and invents a sequence we do not own."""+ imported = await _create(+ client, biz_headers, total="500.00", origin="imported",+ external_source="erp", external_id="ax-1", external_number="2026/A/0031",+ )+ assert imported["external_number"] == "2026/A/0031"+ doc = await client.get(+ f"/api/invoices/{imported['id']}/document", headers=biz_headers+ )+ assert doc.json()["number"] == "2026/A/0031"+++async def test_a_document_we_wrote_ignores_a_source_name(client: AsyncClient, biz_headers):+ """Two names for one document is two answers to the same question."""+ ours = await _create(client, biz_headers, total="100.00", external_number="NOT-OURS")+ assert ours["external_number"] is None+ assert ours["number"] == 1+++# ---------------------------------------------------------------------------+# Saving something half written+# ---------------------------------------------------------------------------+async def test_a_draft_can_be_saved_where_the_preset_would_open_it(+ client: AsyncClient, biz_headers+):+ """The tracking preset opens everything on creation, which leaves no+ way to put down an invoice that is not finished. `as_draft` is the+ caller saying so."""+ settings = await client.get("/api/invoices/settings", headers=biz_headers)+ assert settings.json()["initial_state"] == "open"++ draft = await _create(client, biz_headers, total="500.00", as_draft=True)+ assert draft["status"] == "draft"+ # A draft carries no number: the sequence is spent at issuance, and+ # spending one on something that may never be sent leaves a gap.+ assert draft["number"] is None+++async def test_a_draft_stays_out_of_what_is_owed(client: AsyncClient, biz_headers):+ """Half a thought is not a receivable. It must not move the total the+ workspace reads as money it is waiting for."""+ before = (await client.get("/api/invoices/summary", headers=biz_headers)).json()+ await _create(client, biz_headers, total="9999.00", as_draft=True)+ after = (await client.get("/api/invoices/summary", headers=biz_headers)).json()+ assert after["outstanding"] == before["outstanding"]+++async def test_a_draft_is_picked_up_edited_and_issued(client: AsyncClient, biz_headers):+ """The whole point of putting it down: coming back to it. The number+ is assigned at that moment, not at the moment it was started."""+ draft = await _create(client, biz_headers, total="500.00", as_draft=True)++ edited = await client.patch(+ f"/api/invoices/{draft['id']}",+ headers=biz_headers,+ json={+ "lines": [+ {"description": "Consultoria", "quantity": "10", "unit": "horas",+ "unit_price": "150.00"}+ ]+ },+ )+ assert edited.status_code == 200+ assert edited.json()["total"] == "1500.00"+ assert edited.json()["status"] == "draft"++ issued = await client.post(f"/api/invoices/{draft['id']}/issue", headers=biz_headers)+ assert issued.status_code == 200+ body = issued.json()+ assert body["status"] == "open"+ assert body["number"] is not None+ assert body["snapshot"] is not None+++async def test_an_import_is_never_a_draft(client: AsyncClient, biz_headers):+ """Somebody else issued it. `draft` would claim we are still writing+ a document we received, so the flag is ignored there."""+ imported = await _create(+ client, biz_headers, total="300.00", as_draft=True, origin="imported",+ external_source="erp", external_id="d-1",+ )+ assert imported["status"] == "open"+++# ---------------------------------------------------------------------------+# Things review caught+# ---------------------------------------------------------------------------+async def test_a_discount_bigger_than_the_bill_is_refused_not_a_500(+ client: AsyncClient, biz_headers+):+ """The CHECK would answer this with an IntegrityError, which reaches+ the client as a 500 it cannot branch on. It is a typo, and a typo+ deserves a message."""+ resp = await client.post(+ "/api/invoices",+ headers=biz_headers,+ json={+ "as_draft": True,+ "due_date": str(date.today() + timedelta(days=10)),+ "discount": "500.00",+ "lines": [{"description": "Item", "quantity": "1", "unit_price": "100.00"}],+ },+ )+ assert resp.status_code == 400+ assert resp.json()["detail"]["code"] == "discount_exceeds_total"+++async def test_clearing_every_line_clears_them(client: AsyncClient, biz_headers):+ """Omitting the key means "leave them alone", so deleting every row+ used to save successfully and change nothing."""+ draft = await _create(+ client, biz_headers, as_draft=True, total="300.00",+ lines=[+ {"description": "A", "quantity": "1", "unit_price": "100.00"},+ {"description": "B", "quantity": "1", "unit_price": "200.00"},+ ],+ )+ assert len(draft["lines"]) == 2++ resp = await client.patch(+ f"/api/invoices/{draft['id']}",+ headers=biz_headers,+ json={"lines": [], "total": "150.00"},+ )+ assert resp.status_code == 200+ assert resp.json()["lines"] == []+ # With no lines the caller's total stands again.+ assert resp.json()["total"] == "150.00"+++async def test_an_issued_invoice_keeps_the_tax_id_it_was_issued_under(+ client: AsyncClient, biz_headers+):+ """The snapshot froze the issuer's name, address and logo, and read+ the tax ids live — so correcting a CNPJ rewrote a document a client+ was already holding."""+ await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"tax_ids": [{"kind": "cnpj", "value": "11.222.333/0001-81"}]},+ )+ invoice = await _create(client, biz_headers, total="100.00")+ doc = f"/api/invoices/{invoice['id']}/document"+ before = (await client.get(doc, headers=biz_headers)).json()["issuer"]["tax_ids"]++ await client.patch(+ "/api/invoices/issuer",+ headers=biz_headers,+ json={"tax_ids": [{"kind": "cnpj", "value": "45.997.418/0001-53"}]},+ )+ after = (await client.get(doc, headers=biz_headers)).json()["issuer"]["tax_ids"]+ assert after == before++ # A document issued from now on carries the corrected one. Asserted by+ # value: `fresh != before` also passes when a new snapshot loses every+ # tax id, which is the regression most worth catching here.+ later = await _create(client, biz_headers, total="100.00")+ fresh = (+ await client.get(f"/api/invoices/{later['id']}/document", headers=biz_headers)+ ).json()["issuer"]["tax_ids"]+ assert [t["value"] for t in fresh] == ["45.997.418/0001-53"]+++async def test_one_payment_advertises_every_invoice_it_settled(+ client: AsyncClient, biz_headers, inflow: Transaction+):+ """The N:N read back. A gateway payout settles a dozen invoices net of+ fees, and keying one link per transaction let the second overwrite the+ first — so the row advertised one and the ledger disagreed with the+ list about what had been paid."""+ first = await _create(client, biz_headers, total="300.00")+ second = await _create(client, biz_headers, total="700.00")++ for invoice, amount in ((first, "300.00"), (second, "700.00")):+ resp = await client.post(+ f"/api/invoices/{invoice['id']}/allocations",+ headers=biz_headers,+ json={"transaction_id": str(inflow.id), "amount": amount},+ )+ assert resp.status_code == 201, resp.text++ listed = await client.get("/api/transactions", headers=biz_headers)+ row = next(item for item in listed.json()["items"] if item["id"] == str(inflow.id))+ assert {link["invoice_id"] for link in row["invoice_links"]} == {+ first["id"], second["id"],+ }+ assert sum(Decimal(link["amount"]) for link in row["invoice_links"]) == Decimal("1000.00")diff --git a/backend/tests/test_module_gate.py b/backend/tests/test_module_gate.pynew file mode 100644index 00000000..d7519921--- /dev/null+++ b/backend/tests/test_module_gate.py@@ -0,0 +1,89 @@+"""The module gate: does this workspace have this module at all?++Separate from `require_write`, and deliberately so — they answer+different questions and both have to pass. This file pins the gate's+own behaviour, including the choice of 404 over 403.+"""+import uuid++import pytest+from fastapi import HTTPException++from app.core.module_gate import _assert_enabled, require_module, require_module_write+from app.core.workspace_context import WorkspaceContext+from app.models.user import User+from app.models.workspace import Workspace, WorkspaceMember+from app.services.module_service import ModuleId+++def context(kind: str, role: str = "owner") -> WorkspaceContext:+ """A context built by hand: the gate reads only the workspace's kind+ and never touches the database, which is the point of testing it+ here rather than through a route."""+ user = User(id=uuid.uuid4(), email="[email protected]", hashed_password="x")+ workspace = Workspace(id=uuid.uuid4(), name="ws", kind=kind)+ member = WorkspaceMember(+ id=uuid.uuid4(), workspace_id=workspace.id, user_id=user.id, role=role+ )+ return WorkspaceContext(workspace=workspace, member=member, user=user)+++class TestAssertEnabled:+ def test_business_workspace_passes_for_invoices(self):+ _assert_enabled(context("business"), ModuleId.INVOICES) # does not raise++ def test_personal_workspace_is_refused(self):+ with pytest.raises(HTTPException) as exc:+ _assert_enabled(context("personal"), ModuleId.INVOICES)+ assert exc.value.status_code == 404++ def test_refusal_says_nothing_about_the_feature(self):+ """404 rather than 403 on purpose: a workspace without the module+ should not be able to learn the feature exists."""+ with pytest.raises(HTTPException) as exc:+ _assert_enabled(context("personal"), ModuleId.INVOICES)+ assert exc.value.detail == "Not found"+ assert "invoice" not in str(exc.value.detail).lower()+ assert "module" not in str(exc.value.detail).lower()++ def test_a_module_every_workspace_has_passes_for_both_kinds(self):+ for kind in ("personal", "business"):+ _assert_enabled(context(kind), ModuleId.TRANSACTIONS)++ def test_an_unknown_kind_falls_back_to_the_catalog(self):+ """A workspace stored before a kind was retired still has to+ render something sane — and must not gain a business module."""+ _assert_enabled(context("legacy_kind"), ModuleId.TRANSACTIONS)+ with pytest.raises(HTTPException):+ _assert_enabled(context("legacy_kind"), ModuleId.INVOICES)+++class TestDependencyFactories:+ @pytest.mark.asyncio+ async def test_read_gate_returns_the_context_it_was_given(self):+ dependency = require_module(ModuleId.INVOICES)+ ctx = context("business")+ assert await dependency(ctx) is ctx++ @pytest.mark.asyncio+ async def test_read_gate_refuses_a_personal_workspace(self):+ dependency = require_module(ModuleId.INVOICES)+ with pytest.raises(HTTPException) as exc:+ await dependency(context("personal"))+ assert exc.value.status_code == 404++ @pytest.mark.asyncio+ async def test_write_gate_checks_the_module_too(self):+ """The write dependency wraps `current_writable_workspace`, so the+ role is already checked upstream; this asserts it still asks the+ module question rather than trusting the wrap."""+ dependency = require_module_write(ModuleId.INVOICES)+ with pytest.raises(HTTPException) as exc:+ await dependency(context("personal", role="owner"))+ assert exc.value.status_code == 404++ @pytest.mark.asyncio+ async def test_write_gate_lets_an_editor_through_on_a_business_workspace(self):+ dependency = require_module_write(ModuleId.INVOICES)+ ctx = context("business", role="editor")+ assert await dependency(ctx) is ctxdiff --git a/backend/uv.lock b/backend/uv.lockindex 482a6e3d..6bbff7a2 100644--- a/backend/uv.lock+++ b/backend/uv.lock@@ -2473,6 +2473,19 @@ hiredis = [{ name = "hiredis" },]+[[package]]+name = "reportlab"+version = "5.0.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "charset-normalizer" },+ { name = "pillow" },+]+sdist = { url = "https://files.pythonhosted.org/packages/4a/51/dbe28534ae12c852f61be91f039f343305fd1f34f1c66b8de75afae7a525/reportlab-5.0.1.tar.gz", hash = "sha256:ebd13154be1c8515e665de70bd2d303ae9ddc3ef47e44afd5116441ca0283a26", size = 3945711, upload-time = "2026-08-20T13:48:16.461Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/db/cb/dacbc268cb68d0428ea2cbd85266195a9ab3e677449589ddae59bd7542ac/reportlab-5.0.1-py3-none-any.whl", hash = "sha256:1c36e6bb0e71780c72331eba60da7f602e8d4389a8723825af71342e49d791e8", size = 1957258, upload-time = "2026-08-20T13:48:14.026Z" },+]+[[package]]name = "requests"version = "2.34.2"@@ -2550,6 +2563,7 @@ dependencies = [{ name = "python-multipart" },{ name = "pyzipper" },{ name = "redis", extra = ["hiredis"] },+ { name = "reportlab" },{ name = "sqlalchemy" },{ name = "uvicorn", extra = ["standard"] },{ name = "webauthn" },@@ -2596,6 +2610,7 @@ requires-dist = [{ name = "python-multipart", specifier = ">=0.0.6" },{ name = "pyzipper", specifier = ">=0.4.0" },{ name = "redis", extras = ["hiredis"], specifier = ">=5.0.0" },+ { name = "reportlab", specifier = ">=4.2.0" },{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.16.4,<0.17" },{ name = "sqlalchemy", specifier = ">=2.0.0" },{ name = "ty", marker = "extra == 'dev'", specifier = "==0.0.74" },diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex e383aef6..b73011c1 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -36,6 +36,8 @@ const AgentsListPage = lazy(() => import('@/pages/agents-list'))const AgentDetailPage = lazy(() => import('@/pages/agent-detail'))const AgentConnectionsPage = lazy(() => import('@/pages/agent-connections'))const InvoicesPage = lazy(() => import('@/pages/invoices'))+const InvoiceDetailPage = lazy(() => import('@/pages/invoice-detail'))+const SharedInvoicePage = lazy(() => import('@/pages/shared-invoice'))const WorkspaceSettingsPage = lazy(() => import('@/pages/workspace-settings'))const OAuthCallbackPage = lazy(() => import('@/pages/oauth-callback'))const OIDCCallbackPage = lazy(() => import('@/pages/oidc-callback'))@@ -70,6 +72,11 @@ function App() {<Route path="/login" element={<LoginPage />} /><Route path="/auth/oidc/callback" element={<OIDCCallbackPage />} /><Route path="/register" element={<RegisterPage />} />+ {/* A client opening a link the sender shared. Deliberately+ outside ProtectedRoute and outside AppLayout: the+ recipient has no account, and the token is the whole+ credential. */}+ <Route path="/i/:token" element={<SharedInvoicePage />} /><Routeelement={<ProtectedRoute>@@ -100,6 +107,7 @@ function App() {<Route path="/groups" element={<ModuleRoute module="split_groups"><GroupsPage /></ModuleRoute>} /><Route path="/groups/:id" element={<ModuleRoute module="split_groups"><GroupDetailPage /></ModuleRoute>} /><Route path="/invoices" element={<ModuleRoute module="invoices"><InvoicesPage /></ModuleRoute>} />+ <Route path="/invoices/:id" element={<ModuleRoute module="invoices"><InvoiceDetailPage /></ModuleRoute>} /><Route path="/workspace/settings" element={<WorkspaceSettingsPage />} /><Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} /><Route path="/agents" element={<AgentsRoute><AgentsListPage /></AgentsRoute>} />diff --git a/frontend/src/components/invoice-document.tsx b/frontend/src/components/invoice-document.tsxnew file mode 100644index 00000000..32d6919f--- /dev/null+++ b/frontend/src/components/invoice-document.tsx@@ -0,0 +1,370 @@+import { useTranslation } from 'react-i18next'+import { useDateLocale, useDisplayLocale } from '@/hooks/use-display-locale'+import { formatCurrency } from '@/lib/format'+import type { InvoiceDocumentPayload } from '@/types'++/**+ * The invoice as a document.+ *+ * Deliberately not a Securo card. This is the artifact the client+ * receives: a sheet of paper, presented on a recessed surface so it+ * reads as paper on a desk rather than as a panel that forgot the+ * theme. It is light in both themes because the printed thing is light+ * in both themes, and the inset around it is what makes that a decision+ * instead of a bug.+ *+ * A deliberate mirror of `services/invoice_pdf.py`: same blocks, same+ * order, same labels. It recomputes nothing — every value was resolved+ * by the server into one structure both renderers read, so the preview+ * and the file cannot drift apart into two opinions.+ *+ * Labels come from the document rather than from i18n. That reads+ * backwards until you remember whose document it is: the sender chose+ * these words, possibly in their client's language, and translating+ * them into the *viewer's* language would rewrite someone else's+ * invoice. The chrome around the sheet stays translated; the sheet+ * does not.+ */++/** Ink, fixed. The sheet does not follow the app theme, so its colours+ * cannot come from theme tokens. */+const INK = '#18181b'+const MUTED = '#71717a'+const RULE = '#e4e4e7'++/**+ * A4 at 96dpi, and the same 18mm margin the PDF renderer uses.+ *+ * The point is proportion, not pixel-accuracy: a sheet that is merely+ * "a wide card" reads as a web page, and the whole reason to preview a+ * document is to see the shape of the thing the client will hold. The+ * page keeps its full height even when the invoice is two lines long,+ * because that is what a real page does.+ */+const SHEET_WIDTH = 794+const SHEET_HEIGHT = 1123+const SHEET_MARGIN = 68++function Party({+ title,+ name,+ legalName,+ address,+ email,+ taxIds,+}: {+ title: string+ name: string | null+ legalName?: string | null+ address: string | null+ email?: string | null+ taxIds: { label: string; value: string }[]+}) {+ return (+ <div className="min-w-0">+ <div+ className="text-[10px] font-semibold uppercase tracking-[0.14em]"+ style={{ color: MUTED }}+ >+ {title}+ </div>+ {name && (+ <div className="mt-1.5 text-[15px] font-semibold leading-snug break-words">{name}</div>+ )}+ {/* Only when it differs — printing the same string twice reads as a bug. */}+ {legalName && legalName !== name && (+ <div className="text-[13px] leading-relaxed break-words" style={{ color: MUTED }}>+ {legalName}+ </div>+ )}+ {taxIds.map((doc) => (+ <div+ key={`${doc.label}-${doc.value}`}+ className="text-[13px] leading-relaxed tabular-nums"+ style={{ color: MUTED }}+ >+ {doc.label} {doc.value}+ </div>+ ))}+ {address && (+ <div+ className="text-[13px] leading-relaxed whitespace-pre-line break-words"+ style={{ color: MUTED }}+ >+ {address}+ </div>+ )}+ {email && (+ <div className="text-[13px] leading-relaxed break-all" style={{ color: MUTED }}>+ {email}+ </div>+ )}+ </div>+ )+}++function Field({ label, value }: { label: string; value: string }) {+ return (+ <div>+ <div+ className="text-[10px] font-semibold uppercase tracking-[0.14em]"+ style={{ color: MUTED }}+ >+ {label}+ </div>+ <div className="mt-0.5 text-[13px] tabular-nums">{value}</div>+ </div>+ )+}++export function InvoiceDocumentView({ document }: { document: InvoiceDocumentPayload }) {+ const { t } = useTranslation()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const L = document.labels+ const accent = document.accent_color+ const hasPaid = Number(document.amount_paid) > 0++ const money = (value: string) => formatCurrency(Number(value), document.currency, locale)+ const showDate = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)++ const totals: { label: string; value: string; strong?: boolean }[] = []+ if (document.lines.length > 0) {+ totals.push({ label: L.subtotal, value: money(document.subtotal) })+ }+ if (Number(document.discount) > 0) {+ totals.push({ label: L.discount, value: `-${money(document.discount)}` })+ }+ if (Number(document.tax_total) > 0) {+ totals.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) })+ totals.push({ label: L.balance, value: money(document.balance), strong: true })+ }++ const received = document.direction === 'payable'++ return (+ // The desk: a recessed surface that makes the sheet read as paper.+ <div className="rounded-xl border border-border bg-muted/50 p-3 sm:p-8 overflow-x-auto">+ {/* A payable was written by the supplier, not by us. Saying so+ above the sheet keeps the page from reading as a document we+ issued — the parties are already swapped server-side, but the+ claim needs words, not just an order. */}+ {received && (+ <div+ className="mx-auto mb-3 max-w-[794px] text-xs text-muted-foreground"+ data-testid="document-received-note"+ >+ <span className="font-medium text-foreground">+ {t('invoices.receivedDocument')}+ </span>{' '}+ {t('invoices.receivedDocumentHint')}+ </div>+ )}+ <div+ data-testid="invoice-document"+ className="mx-auto flex flex-col rounded-sm bg-white shadow-[0_1px_2px_rgba(0,0,0,0.08),0_12px_32px_-10px_rgba(0,0,0,0.22)]"+ style={{+ color: INK,+ width: '100%',+ maxWidth: SHEET_WIDTH,+ // Full page height from the small breakpoint up. On a phone a+ // sheet taller than the screen is theatre, so it collapses to+ // its content there.+ minHeight: `min(${SHEET_HEIGHT}px, 141.4vw)`,+ padding: `clamp(28px, 8.5vw, ${SHEET_MARGIN}px)`,+ }}+ >+ <header className="flex flex-wrap items-start justify-between gap-4">+ <div className="flex items-center gap-3 min-w-0">+ {document.logo_url && (+ <img+ src={document.logo_url}+ alt=""+ className="h-9 w-auto max-w-[132px] object-contain"+ data-testid="document-logo"+ />+ )}+ <h2 className="text-[26px] font-bold tracking-tight leading-none">{L.invoice}</h2>+ </div>+ {document.number && (+ <div+ className="text-[17px] font-bold tabular-nums leading-none pt-1"+ style={{ color: accent }}+ data-testid="document-number"+ >+ {document.number}+ </div>+ )}+ </header>++ <div className="mt-4 h-[2px] rounded-full" style={{ backgroundColor: accent }} />++ <div className="mt-8 grid gap-8 sm:grid-cols-2">+ <Party+ title={L.from}+ name={document.issuer.name}+ legalName={document.issuer.legal_name}+ address={document.issuer.address}+ taxIds={document.issuer.tax_ids}+ />+ <Party+ title={L.billTo}+ name={document.client.name}+ address={document.client.address}+ email={document.client.email}+ taxIds={document.client.tax_ids}+ />+ </div>++ <div className="mt-8 flex flex-wrap gap-x-12 gap-y-4">+ <Field label={L.issueDate} value={showDate(document.issue_date)} />+ <Field label={L.dueDate} value={showDate(document.due_date)} />+ {document.custom_fields.map((field) => (+ <Field key={field.label} label={field.label} value={field.value} />+ ))}+ </div>++ {document.lines.length > 0 ? (+ <table className="mt-9 w-full">+ <thead>+ <tr style={{ borderBottom: `1px solid ${RULE}` }}>+ <th+ className="pb-2 text-left text-[10px] font-semibold uppercase tracking-[0.14em]"+ style={{ color: MUTED }}+ >+ {L.description}+ </th>+ <th+ className="pb-2 text-right text-[10px] font-semibold uppercase tracking-[0.14em] w-20"+ style={{ color: MUTED }}+ >+ {L.quantity}+ </th>+ <th+ className="pb-2 text-right text-[10px] font-semibold uppercase tracking-[0.14em] w-28"+ style={{ color: MUTED }}+ >+ {L.unitPrice}+ </th>+ <th+ className="pb-2 text-right text-[10px] font-semibold uppercase tracking-[0.14em] w-28"+ style={{ color: MUTED }}+ >+ {L.amount}+ </th>+ </tr>+ </thead>+ <tbody>+ {document.lines.map((line, index) => (+ <tr key={index} style={{ borderBottom: `1px solid ${RULE}` }}>+ <td className="py-3 pr-4 text-[13.5px] leading-snug">{line.description}</td>+ <td className="py-3 text-right text-[13.5px] tabular-nums">+ {/* "12 hours", not "12": the unit is what lets the+ reader check the sum against what was agreed. */}+ {Number(line.quantity)}+ {line.unit ? ` ${line.unit}` : ''}+ </td>+ <td className="py-3 text-right text-[13.5px] tabular-nums">+ {money(line.unit_price)}+ </td>+ <td className="py-3 text-right text-[13.5px] tabular-nums">+ {money(line.total)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ ) : (+ // Not an error state: an invoice with no lines is the normal+ // case where the fiscal document was issued somewhere else and+ // this only tracks the money.+ <p+ className="mt-9 text-[13px] leading-relaxed"+ style={{ color: MUTED }}+ data-testid="document-no-lines"+ >+ {t('invoices.document.noLines')}+ </p>+ )}++ <div className="mt-7 flex justify-end">+ <dl className="w-full max-w-[300px]">+ {totals.map((row) => (+ <div+ key={row.label}+ className="flex items-baseline justify-between gap-8 py-1.5"+ style={row.strong ? { borderTop: `1px solid ${RULE}` } : undefined}+ >+ <dt+ className={row.strong ? 'text-[13px] font-semibold' : 'text-[13px]'}+ style={row.strong ? undefined : { color: MUTED }}+ >+ {row.label}+ </dt>+ <dd+ className="text-[13.5px] tabular-nums"+ style={+ row.strong ? { color: accent, fontWeight: 700, fontSize: '15px' } : undefined+ }+ >+ {row.value}+ </dd>+ </div>+ ))}+ </dl>+ </div>++ {/* Everything above is the body; from here down is the footer+ band, pushed to the foot of the page by `mt-auto` so it lands+ where the PDF pins it and where a reader looks for it. */}+ <div className="mt-auto pt-10">+ {(document.payment_details || document.notes) && (+ <div className="grid gap-6 sm:grid-cols-2">+ {document.payment_details && (+ <div>+ <div+ className="text-[10px] font-semibold uppercase tracking-[0.14em]"+ style={{ color: MUTED }}+ >+ {L.paymentDetails}+ </div>+ <p className="mt-1.5 text-[13px] leading-relaxed whitespace-pre-line">+ {document.payment_details}+ </p>+ </div>+ )}+ {document.notes && (+ <div>+ <div+ className="text-[10px] font-semibold uppercase tracking-[0.14em]"+ style={{ color: MUTED }}+ >+ {L.notes}+ </div>+ <p className="mt-1.5 text-[13px] leading-relaxed whitespace-pre-line">+ {document.notes}+ </p>+ </div>+ )}+ </div>+ )}++ {document.footer_note && (+ <p+ className="mt-6 pt-4 text-[11.5px] leading-relaxed"+ style={{ borderTop: `1px solid ${RULE}`, color: MUTED }}+ >+ {document.footer_note}+ </p>+ )}+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/components/invoice-documents.tsx b/frontend/src/components/invoice-documents.tsxnew file mode 100644index 00000000..4bc42d72--- /dev/null+++ b/frontend/src/components/invoice-documents.tsx@@ -0,0 +1,447 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { FileText, Image as ImageIcon, Plus, Star, Trash2 } from 'lucide-react'++import { Button } from '@/components/ui/button'+import { IconAction, SectionCard } from '@/components/invoice-ui'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { invoices as invoicesApi } from '@/lib/api'+import { documentProvenance, formatFileSize, previewKind } from '@/lib/invoice-utils'+import { useDateLocale } from '@/hooks/use-display-locale'+import { cn } from '@/lib/utils'+import type { InvoiceAttachment, InvoiceAttachmentKind } from '@/types'++/**+ * Everything that stands as this invoice's paperwork, in one place.+ *+ * An invoice is often a folder: the supplier's bill arrives by email, the+ * fiscal document follows from a portal, the receipt after that. Reading+ * any of them used to mean opening one browser tab per file, which is no+ * way to check whether the fiscal document matches the bill.+ *+ * So the files sit down the left and the selected one is rendered on the+ * right. The page we generate is an entry in that same list when we are+ * the ones who wrote the invoice: it is one of the documents, not a+ * different kind of thing living elsewhere on the screen.+ */++const KINDS: InvoiceAttachmentKind[] = ['bill', 'fiscal', 'receipt', 'contract', 'other']++/** The generated page is addressed by a reserved id, so selection stays a+ * single string instead of a union the whole component has to narrow. */+const OUR_PAGE = 'our-page'++export function InvoiceDocumentBrowser({+ invoiceId,+ origin,+ canWrite,+ ourPageLabel,+ ourPageDate,+ ourPage,+ onChanged,+}: {+ invoiceId: string+ origin: string+ canWrite: boolean+ /** The number the generated page carries, when it has one. */+ ourPageLabel?: string | null+ /** When the page came into being — the moment the invoice was issued,+ * which is also the date printed on it. The other entries say when+ * they arrived; this one says when it was made. */+ ourPageDate?: string | null+ /** The rendered invoice. Passed in so this component never learns how a+ * document is drawn — only that one exists. */+ ourPage: React.ReactNode | null+ onChanged?: () => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const dateLocale = useDateLocale()+ const fileInput = useRef<HTMLInputElement>(null)+ const [kind, setKind] = useState<InvoiceAttachmentKind>('bill')+ const [error, setError] = useState<string | null>(null)+ const [selected, setSelected] = useState<string | null>(null)++ const { data: attachments = [] } = useQuery({+ queryKey: ['invoice-attachments', invoiceId],+ queryFn: () => invoicesApi.attachments.list(invoiceId),+ })++ // An import with nothing filed has no page at all: drawing ours would+ // invent a document a supplier issued and we were never handed.+ const showOurPage = origin !== 'imported' && ourPage !== null++ const active = useMemo(() => {+ if (selected === OUR_PAGE && showOurPage) return OUR_PAGE+ if (selected && attachments.some((a) => a.id === selected)) return selected+ // Falls to the file that *is* the document, then to our own page,+ // then to whatever was filed first.+ const primary = attachments.find((a) => a.is_primary)+ if (primary) return primary.id+ if (showOurPage) return OUR_PAGE+ return attachments[0]?.id ?? null+ }, [selected, attachments, showOurPage])++ const refresh = () => {+ // Cleared on any success: a refused file leaves a message on screen,+ // and if it outlives the next working action it stops being true.+ setError(null)+ void queryClient.invalidateQueries({ queryKey: ['invoice-attachments', invoiceId] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-document', invoiceId] })+ onChanged?.()+ }++ const uploadMutation = useMutation({+ mutationFn: (file: File) => invoicesApi.attachments.upload(invoiceId, file, { kind }),+ onSuccess: (created: InvoiceAttachment) => {+ // Show what was just added. Uploading and then hunting for the file+ // in the list is a step the person did not ask for.+ setSelected(created.id)+ refresh()+ },+ onError: (err: unknown) => {+ const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail+ setError(detail ?? t('invoices.documents.uploadFailed'))+ },+ })++ const primaryMutation = useMutation({+ mutationFn: (id: string) =>+ invoicesApi.attachments.update(invoiceId, id, { is_primary: true }),+ onSuccess: refresh,+ })++ const removeMutation = useMutation({+ mutationFn: (id: string) => invoicesApi.attachments.remove(invoiceId, id),+ onSuccess: (_data, id) => {+ if (selected === id) setSelected(null)+ refresh()+ },+ })++ const longDate = (value: Date) =>+ value.toLocaleDateString(dateLocale, {+ day: '2-digit',+ month: 'short',+ year: 'numeric',+ })+ /** When the file reached us, which is rarely the date on the document+ * itself — an integration can deliver a fiscal document weeks late.+ * A full timestamp, so it is read in the reader's own zone. */+ const showArrival = (value: string) => longDate(new Date(value))+ /** A date with no time. Parsed at local midnight rather than handed to+ * `new Date`, which reads a bare `2026-08-28` as UTC and lands on the+ * 27th for anybody west of Greenwich. */+ const showPlainDate = (value: string) => longDate(new Date(`${value}T00:00:00`))++ const activeAttachment =+ active && active !== OUR_PAGE ? attachments.find((a) => a.id === active) : undefined+ const anyPrimary = attachments.some((a) => a.is_primary)++ return (+ <SectionCard>+ <div className="flex flex-col lg:flex-row">+ {/* The shelf */}+ <div className="lg:w-72 xl:w-80 shrink-0 border-b lg:border-b-0 lg:border-r border-border flex flex-col">+ <div className="px-3 py-3 border-b border-border flex items-center gap-2">+ {canWrite ? (+ <>+ <Select value={kind} onValueChange={(v) => setKind(v as InvoiceAttachmentKind)}>+ <SelectTrigger+ className="h-8 flex-1 text-xs"+ aria-label={t('invoices.documents.kindLabel')}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {KINDS.map((k) => (+ <SelectItem key={k} value={k} className="text-xs">+ {t(`invoices.documents.kind.${k}`)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button+ size="sm"+ variant="outline"+ className="h-8 shrink-0"+ disabled={uploadMutation.isPending}+ onClick={() => fileInput.current?.click()}+ >+ <Plus className="h-3.5 w-3.5 mr-1" />+ {t('invoices.documents.add')}+ </Button>+ <input+ ref={fileInput}+ type="file"+ className="hidden"+ data-testid="invoice-document-input"+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) uploadMutation.mutate(file)+ event.target.value = ''+ }}+ />+ </>+ ) : (+ <p className="text-xs font-medium text-muted-foreground py-1">+ {t('invoices.documents.title')}+ </p>+ )}+ </div>++ {error && <p className="px-3 pt-3 text-xs text-destructive">{error}</p>}++ <ul className="flex-1 p-2 space-y-0.5 lg:max-h-[880px] lg:overflow-y-auto">+ {showOurPage && (+ <li>+ <ShelfItem+ active={active === OUR_PAGE}+ onSelect={() => setSelected(OUR_PAGE)}+ icon={<FileText className="h-4 w-4" />}+ title={ourPageLabel || t('invoices.documents.ourPage')}+ subtitle={t('invoices.documents.rendered', {+ date: ourPageDate ? showPlainDate(ourPageDate) : '',+ })}+ isPrimary={!anyPrimary}+ />+ </li>+ )}++ {attachments.map((attachment) => (+ <li key={attachment.id}>+ <ShelfItem+ active={active === attachment.id}+ onSelect={() => setSelected(attachment.id)}+ icon={+ previewKind(attachment.content_type) === 'image' ? (+ <ImageIcon className="h-4 w-4" />+ ) : (+ <FileText className="h-4 w-4" />+ )+ }+ title={attachment.filename}+ subtitle={[+ t(`invoices.documents.kind.${attachment.kind}`),+ formatFileSize(attachment.size),+ attachment.issued_at ? showPlainDate(attachment.issued_at) : null,+ ]+ .filter(Boolean)+ .join(' · ')}+ reference={attachment.document_number}+ provenance={(() => {+ const from = documentProvenance(attachment.source)+ const arrived = showArrival(attachment.created_at)+ return from.kind === 'system'+ ? t('invoices.documents.fromSystem', { source: from.name, date: arrived })+ : t('invoices.documents.fromUpload', { date: arrived })+ })()}+ isPrimary={attachment.is_primary}+ actions={+ canWrite ? (+ <>+ {!attachment.is_primary && (+ <IconAction+ onClick={() => primaryMutation.mutate(attachment.id)}+ label={t('invoices.documents.makePrimary')}+ >+ <Star className="h-3.5 w-3.5" />+ </IconAction>+ )}+ <IconAction+ onClick={() => removeMutation.mutate(attachment.id)}+ label={t('invoices.documents.remove')}+ destructive+ >+ <Trash2 className="h-3.5 w-3.5" />+ </IconAction>+ </>+ ) : undefined+ }+ />+ </li>+ ))}++ {!showOurPage && attachments.length === 0 && (+ <li+ className="px-3 py-6 text-xs text-muted-foreground"+ data-testid="invoice-no-documents"+ >+ {t('invoices.documents.empty')}+ </li>+ )}+ </ul>+ </div>++ {/* The reading surface */}+ <div className="flex-1 min-w-0 bg-muted/40 p-3 sm:p-6 overflow-x-auto">+ {active === OUR_PAGE ? (+ ourPage+ ) : activeAttachment ? (+ // Keyed by file: selecting another one remounts rather than+ // reusing a component still holding the previous blob URL.+ <AttachmentView+ key={activeAttachment.id}+ invoiceId={invoiceId}+ attachment={activeAttachment}+ />+ ) : (+ <div className="py-20 text-center" data-testid="invoice-missing-source">+ <FileText className="h-6 w-6 mx-auto text-muted-foreground" />+ <p className="mt-3 text-sm font-medium text-foreground">+ {t('invoices.documents.notOurs')}+ </p>+ <p className="mt-1 text-sm text-muted-foreground max-w-md mx-auto">+ {t('invoices.documents.notOursHint')}+ </p>+ </div>+ )}+ </div>+ </div>+ </SectionCard>+ )+}++function ShelfItem({+ active,+ onSelect,+ icon,+ title,+ subtitle,+ reference,+ provenance,+ isPrimary,+ actions,+}: {+ active: boolean+ onSelect: () => void+ icon: React.ReactNode+ title: string+ subtitle: string+ reference?: string | null+ /** Which system delivered the file and when it arrived. Absent on our+ * own generated page, which was not delivered by anybody. */+ provenance?: string+ /** True on the file the download hands over. Shown as a filled star —+ * the same mark the button on the other rows sets, so the flag and the+ * way to move it read as one thing rather than two. */+ isPrimary?: boolean+ actions?: React.ReactNode+}) {+ const { t } = useTranslation()+ return (+ <div+ data-testid="invoice-document-row"+ className={cn(+ 'group flex items-start gap-2 rounded-lg px-2 py-2 transition-colors',+ active ? 'bg-primary/5 ring-1 ring-primary/20' : 'hover:bg-muted',+ )}+ >+ <button onClick={onSelect} className="flex items-start gap-2 min-w-0 flex-1 text-left">+ <span className={cn('mt-0.5 shrink-0', active ? 'text-primary' : 'text-muted-foreground')}>+ {icon}+ </span>+ <span className="min-w-0">+ <span className="block text-sm font-medium text-foreground truncate">{title}</span>+ <span className="block text-xs text-muted-foreground truncate mt-0.5">{subtitle}</span>+ {reference && (+ <span className="block text-[11px] text-muted-foreground/80 truncate mt-0.5 tabular-nums">+ {reference}+ </span>+ )}+ {provenance && (+ <span className="block text-[11px] text-muted-foreground/80 truncate mt-0.5">+ {provenance}+ </span>+ )}+ </span>+ </button>+ {isPrimary && (+ <span+ className="shrink-0 mt-0.5 text-primary"+ title={t('invoices.documents.primaryHint')}+ >+ <Star className="h-3.5 w-3.5 fill-current" />+ </span>+ )}+ {actions && (+ <span className="shrink-0 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">+ {actions}+ </span>+ )}+ </div>+ )+}++/** One filed file, rendered where it can be read rather than downloaded. */+function AttachmentView({+ invoiceId,+ attachment,+}: {+ invoiceId: string+ attachment: InvoiceAttachment+}) {+ const { t } = useTranslation()+ const [url, setUrl] = useState<string | null>(null)++ useEffect(() => {+ let created: string | null = null+ let cancelled = false+ void invoicesApi.attachments.blobUrl(invoiceId, attachment.id).then((next) => {+ if (cancelled) {+ URL.revokeObjectURL(next)+ return+ }+ created = next+ setUrl(next)+ })+ return () => {+ cancelled = true+ if (created) URL.revokeObjectURL(created)+ }+ }, [invoiceId, attachment.id])++ const preview = previewKind(attachment.content_type)++ return (+ <div className="mx-auto max-w-[794px]" data-testid="invoice-source-document">+ <div className="rounded-sm bg-white shadow-[0_1px_2px_rgba(0,0,0,0.08),0_12px_32px_-10px_rgba(0,0,0,0.22)] overflow-hidden">+ {!url ? (+ <div className="h-[560px]" />+ ) : preview === 'pdf' ? (+ // An <iframe>, not an <object>: both hand the file to Chrome's+ // PDF viewer, but the object element is replaced content the+ // plugin resizes past its box, taking the page layout with it.+ <iframe+ src={url}+ title={attachment.filename}+ className="w-full h-[1123px] max-h-[78vh] border-0 block"+ />+ ) : preview === 'image' ? (+ <img src={url} alt={attachment.filename} className="w-full block" />+ ) : (+ <div className="p-10 text-center">+ <p className="text-sm text-muted-foreground">+ {t('invoices.documents.cannotPreview')}+ </p>+ </div>+ )}+ </div>+ {url && (+ <div className="mt-3 text-center">+ <Button size="sm" variant="outline" onClick={() => window.open(url, '_blank', 'noopener')}>+ <FileText className="h-3.5 w-3.5 mr-1.5" />+ {t('invoices.documents.openOriginal')}+ </Button>+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/components/invoice-line-editor.tsx b/frontend/src/components/invoice-line-editor.tsxnew file mode 100644index 00000000..f30fc8f2--- /dev/null+++ b/frontend/src/components/invoice-line-editor.tsx@@ -0,0 +1,244 @@+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 { formatCurrency } from '@/lib/format'+import { useDisplayLocale } from '@/hooks/use-display-locale'+import { linesTotal } from '@/lib/invoice-utils'+import type { InvoiceLineInput } from '@/types'++/**+ * Line items on a draft.+ *+ * Optional by design, and the empty state says so: under the tracking+ * preset the fiscal document was issued elsewhere and an invoice with no+ * lines is the normal case, not an unfinished one.+ *+ * The layout is a table with real headers rather than a row of bare+ * boxes. A field holding `1` next to a field holding `0` tells the+ * person nothing about which is a quantity and which is a price, and a+ * placeholder disappears the moment they type. Each row also shows what+ * it comes to, because the arithmetic between a rate and a total is the+ * thing most worth checking before sending an invoice out.+ *+ * The running totals here are a convenience while typing; the server+ * recomputes on save from the same quantities and prices, and its answer+ * is the one that gets stored.+ */+const BLANK: InvoiceLineInput = { description: '', quantity: '1', unit_price: '0' }++/** Table header cell, matching the module's other tables. */+const TH = 'text-[11px] font-medium text-muted-foreground pb-1.5'++function lineAmount(line: InvoiceLineInput): number {+ const quantity = Number(line.quantity)+ const price = Number(line.unit_price)+ if (!Number.isFinite(quantity) || !Number.isFinite(price)) return 0+ return quantity * price+}++export function InvoiceLineEditor({+ lines,+ onChange,+ currency,+ showTax,+ required = false,+}: {+ lines: InvoiceLineInput[]+ onChange: (lines: InvoiceLineInput[]) => void+ currency: string+ showTax: boolean+ /** True when the workspace's preset makes the document mandatory. Shows+ * one empty row so the requirement is visible before the submit, not+ * after it. */+ required?: boolean+}) {+ const { t } = useTranslation()+ const locale = useDisplayLocale()++ // A render decision, not state: seeding the parent's array from an+ // effect would fight the parent for ownership of it.+ const rows = lines.length === 0 && required ? [BLANK] : lines++ const update = (index: number, patch: Partial<InvoiceLineInput>) => {+ onChange(rows.map((line, i) => (i === index ? { ...line, ...patch } : line)))+ }++ const add = () => onChange([...rows, { ...BLANK }])+ const money = (value: number) => formatCurrency(value, currency, locale)+ const total = linesTotal(rows)++ return (+ <div className="space-y-2" data-testid="invoice-line-editor">+ <div className="flex items-center justify-between">+ <Label>{t('invoices.field.lines')}</Label>+ {rows.length > 0 && (+ <Button size="sm" variant="ghost" onClick={add} data-testid="invoice-add-line">+ <Plus className="h-3.5 w-3.5 mr-1" />+ {t('invoices.field.addLine')}+ </Button>+ )}+ </div>++ {rows.length === 0 ? (+ <button+ type="button"+ onClick={add}+ data-testid="invoice-add-line"+ className="w-full rounded-lg border border-dashed border-border px-4 py-5 text-center hover:border-primary/40 hover:bg-primary/[0.02] transition-colors"+ >+ <span className="flex items-center justify-center gap-1.5 text-sm font-medium text-foreground">+ <Plus className="h-4 w-4" />+ {t('invoices.field.addLine')}+ </span>+ <span className="mt-1 block text-xs text-muted-foreground">+ {t('invoices.field.linesOptional')}+ </span>+ </button>+ ) : (+ <div className="rounded-lg border border-border overflow-hidden">+ {/* Headers on the wide layout only: on a narrow screen the rows+ stack and each field carries its own label instead. */}+ <div className="hidden sm:grid grid-cols-[1fr_4.5rem_5rem_7rem_6rem_2rem] gap-2 px-3 pt-2.5 bg-muted/40">+ <span className={TH}>{t('invoices.field.lineDescription')}</span>+ <span className={`${TH} text-right`}>{t('invoices.column.quantity')}</span>+ <span className={TH}>{t('invoices.field.unit')}</span>+ <span className={`${TH} text-right`}>{t('invoices.field.unitPrice')}</span>+ <span className={`${TH} text-right`}>{t('invoices.column.amount')}</span>+ <span className={TH} />+ </div>++ <div className="divide-y divide-border">+ {rows.map((line, index) => (+ <div+ key={index}+ data-testid="invoice-line-row"+ className="grid grid-cols-2 sm:grid-cols-[1fr_4.5rem_5rem_7rem_6rem_2rem] gap-2 px-3 py-2.5 items-center"+ >+ <div className="col-span-2 sm:col-span-1">+ <Input+ className="h-9"+ placeholder={t('invoices.field.lineDescription')}+ value={line.description}+ onChange={(e) => update(index, { description: e.target.value })}+ data-testid={`invoice-line-description-${index}`}+ aria-label={t('invoices.field.lineDescription')}+ />+ </div>++ <Field label={t('invoices.column.quantity')}>+ <Input+ className="h-9 text-right"+ inputMode="decimal"+ value={line.quantity}+ onChange={(e) => update(index, { quantity: e.target.value })}+ data-testid={`invoice-line-quantity-${index}`}+ aria-label={t('invoices.column.quantity')}+ />+ </Field>++ {/* Beside the number it qualifies, and optional: a line+ counting nothing in particular reads fine without. */}+ <Field label={t('invoices.field.unit')}>+ <Input+ className="h-9"+ placeholder={t('invoices.field.unitPlaceholder')}+ value={line.unit ?? ''}+ onChange={(e) => update(index, { unit: e.target.value || null })}+ data-testid={`invoice-line-unit-${index}`}+ aria-label={t('invoices.field.unit')}+ maxLength={20}+ />+ </Field>++ <Field label={t('invoices.field.unitPrice')}>+ <Input+ className="h-9 text-right"+ inputMode="decimal"+ value={line.unit_price}+ onChange={(e) => update(index, { unit_price: e.target.value })}+ data-testid={`invoice-line-price-${index}`}+ aria-label={t('invoices.field.unitPrice')}+ />+ </Field>++ {/* What this row comes to. Not an input: it is the product+ of the two fields beside it, and a place to type it+ would be a place for it to disagree with them. */}+ <div className="text-right">+ <span className="sm:hidden text-[11px] text-muted-foreground block">+ {t('invoices.column.amount')}+ </span>+ <span+ className="text-sm font-medium tabular-nums"+ data-testid={`invoice-line-amount-${index}`}+ >+ {money(lineAmount(line))}+ </span>+ </div>++ <div className="flex justify-end">+ <Button+ size="sm"+ variant="ghost"+ className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"+ onClick={() => onChange(rows.filter((_, i) => i !== index))}+ data-testid={`invoice-remove-line-${index}`}+ aria-label={t('common.delete')}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>++ {/* Only when the workspace shows tax at all — a rate field+ on a tracking-preset invoice is a question nobody+ asked. On its own row so the columns above stay put. */}+ {showTax && (+ <div className="col-span-2 sm:col-span-6 flex items-center gap-2 pt-1">+ <span className="text-[11px] text-muted-foreground">+ {t('invoices.field.taxRate')}+ </span>+ <Input+ className="h-8 w-20 text-right"+ inputMode="decimal"+ placeholder="%"+ value={line.tax_rate ?? ''}+ onChange={(e) => update(index, { tax_rate: e.target.value || null })}+ data-testid={`invoice-line-tax-${index}`}+ aria-label={t('invoices.field.taxRate')}+ />+ </div>+ )}+ </div>+ ))}+ </div>++ <div className="flex items-center justify-between px-3 py-2.5 bg-muted/40 border-t border-border">+ <span className="text-xs text-muted-foreground">+ {t('invoices.field.lineCount', { count: rows.length })}+ </span>+ <span className="text-sm">+ <span className="text-muted-foreground mr-2">{t('invoices.column.total')}</span>+ <span className="font-semibold tabular-nums" data-testid="invoice-lines-total">+ {money(total)}+ </span>+ </span>+ </div>+ </div>+ )}+ </div>+ )+}++/** A field whose label shows only on the stacked layout, where the table+ * header is not there to explain it. */+function Field({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div>+ <span className="sm:hidden text-[11px] text-muted-foreground block mb-0.5">{label}</span>+ {children}+ </div>+ )+}diff --git a/frontend/src/components/invoice-logo-field.tsx b/frontend/src/components/invoice-logo-field.tsxnew file mode 100644index 00000000..adac7c9a--- /dev/null+++ b/frontend/src/components/invoice-logo-field.tsx@@ -0,0 +1,135 @@+import { useEffect, useRef, useState } from 'react'+import { useMutation } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { ImagePlus, Trash2 } from 'lucide-react'++import { Button } from '@/components/ui/button'+import { invoices as invoicesApi } from '@/lib/api'++/**+ * The workspace's mark, as a file rather than an address.+ *+ * It used to be a text box for a URL, which asked the user to host their+ * own logo somewhere and made every rendered document fetch it from a+ * third party. On a self-hosted install that is a request leaving the+ * building for an image the user already owns.+ */+export function InvoiceLogoField({+ logoId,+ onChanged,+}: {+ logoId: string | null+ onChanged: () => void+}) {+ // Keyed by the id so a replaced logo mounts a fresh preview rather+ // than an effect having to blank the previous one.+ return <LogoField key={logoId ?? 'none'} logoId={logoId} onChanged={onChanged} />+}++function LogoField({+ logoId,+ onChanged,+}: {+ logoId: string | null+ onChanged: () => void+}) {+ const { t } = useTranslation()+ const fileInput = useRef<HTMLInputElement>(null)+ const [preview, setPreview] = useState<string | null>(null)+ const [error, setError] = useState<string | null>(null)++ useEffect(() => {+ if (!logoId) return+ let created: string | null = null+ let cancelled = false+ void invoicesApi.logoUrl(logoId).then((url) => {+ if (cancelled) {+ URL.revokeObjectURL(url)+ return+ }+ created = url+ setPreview(url)+ })+ return () => {+ cancelled = true+ if (created) URL.revokeObjectURL(created)+ }+ }, [logoId])++ const uploadMutation = useMutation({+ mutationFn: (file: File) => invoicesApi.uploadLogo(file),+ onSuccess: () => {+ setError(null)+ onChanged()+ },+ onError: (err: unknown) => {+ const detail = (err as { response?: { data?: { detail?: string } } })?.response?.data?.detail+ setError(detail ?? t('invoices.settings.logoFailed'))+ },+ })++ const removeMutation = useMutation({+ mutationFn: () => invoicesApi.removeLogo(),+ onSuccess: () => {+ setError(null)+ onChanged()+ },+ })++ const busy = uploadMutation.isPending || removeMutation.isPending++ return (+ <div className="space-y-2">+ <div className="flex items-center gap-3">+ <div className="h-14 w-24 shrink-0 rounded-md border border-border bg-muted/40 flex items-center justify-center overflow-hidden">+ {preview ? (+ <img+ src={preview}+ alt={t('invoices.settings.logo')}+ className="max-h-full max-w-full object-contain"+ data-testid="invoice-logo-preview"+ />+ ) : (+ <ImagePlus className="h-5 w-5 text-muted-foreground" />+ )}+ </div>+ <div className="flex items-center gap-2">+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={busy}+ onClick={() => fileInput.current?.click()}+ >+ {logoId ? t('invoices.settings.logoReplace') : t('invoices.settings.logoUpload')}+ </Button>+ {logoId && (+ <Button+ type="button"+ size="sm"+ variant="ghost"+ disabled={busy}+ onClick={() => removeMutation.mutate()}+ aria-label={t('invoices.settings.logoRemove')}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ )}+ </div>+ <input+ ref={fileInput}+ type="file"+ accept="image/png,image/jpeg,image/webp,image/gif"+ className="hidden"+ data-testid="invoice-logo-input"+ onChange={(event) => {+ const file = event.target.files?.[0]+ if (file) uploadMutation.mutate(file)+ event.target.value = ''+ }}+ />+ </div>+ {error && <p className="text-[11px] text-destructive">{error}</p>}+ </div>+ )+}diff --git a/frontend/src/components/invoice-ui.tsx b/frontend/src/components/invoice-ui.tsxnew file mode 100644index 00000000..5ddd6ab4--- /dev/null+++ b/frontend/src/components/invoice-ui.tsx@@ -0,0 +1,166 @@+import { useTranslation } from 'react-i18next'+import { cn } from '@/lib/utils'+import type { InvoiceState } from '@/types'++/**+ * Shared chrome for the invoicing screens.+ *+ * Everything here mirrors patterns already established elsewhere in+ * Securo (recurring, accounts, dashboard) rather than inventing a+ * parallel vocabulary. A module that looks like its own product inside+ * the product is the thing to avoid.+ */++/** The card every section sits in. Same shell as `recurring`. */+export function SectionCard({+ children,+ className = '',+}: {+ children: React.ReactNode+ className?: string+}) {+ return (+ <div+ className={cn(+ 'bg-card rounded-xl border border-border shadow-sm overflow-hidden',+ className,+ )}+ >+ {children}+ </div>+ )+}++export function SectionHeader({+ title,+ action,+}: {+ title: string+ action?: React.ReactNode+}) {+ return (+ <div className="px-4 sm:px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-2">+ <p className="text-sm font-semibold text-foreground">{title}</p>+ {action}+ </div>+ )+}++/** Table header cell. Byte-identical to the constant in `recurring`. */+export const TH = 'text-xs font-medium text-muted-foreground py-3'++/**+ * State pill, in the app's badge shape.+ *+ * The tones carry meaning and only three of them are loud: overdue is+ * the one thing on this screen a person has to act on, paid is the one+ * that closes a loop, and everything else stays quiet. A palette where+ * every row shouts is a palette where nothing does.+ */+const STATE_TONE: Record<InvoiceState, string> = {+ draft: 'bg-muted text-muted-foreground border-border',+ open: 'bg-muted text-foreground border-border',+ 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: 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20',+ overdue: 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20',+ void: 'bg-muted text-muted-foreground border-border line-through',+ uncollectible: 'bg-muted text-muted-foreground border-border',+}++export function StateBadge({ state }: { state: InvoiceState }) {+ const { t } = useTranslation()+ return (+ <span+ data-testid={`invoice-state-${state}`}+ className={cn(+ 'text-[11px] font-semibold px-2 py-0.5 rounded-full border whitespace-nowrap',+ STATE_TONE[state],+ )}+ >+ {t(`invoices.state.${state}`)}+ </span>+ )+}++/**+ * Segmented control, the shape `account-detail` already uses for its+ * currency switch. Serves both the state filter and the detail tabs, so+ * the two read as the same control doing the same job.+ */+export function Segmented<T extends string>({+ value,+ onChange,+ options,+ testIdPrefix,+}: {+ value: T+ onChange: (value: T) => void+ options: { value: T; label: React.ReactNode; count?: number }[]+ testIdPrefix: string+}) {+ return (+ <div className="inline-flex rounded-lg border border-border bg-muted p-0.5 text-xs font-medium">+ {options.map((option) => {+ const active = value === option.value+ return (+ <button+ key={option.value}+ onClick={() => onChange(option.value)}+ data-testid={`${testIdPrefix}-${option.value}`}+ className={cn(+ 'inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-colors whitespace-nowrap',+ active+ ? 'bg-card text-foreground shadow-sm'+ : 'text-muted-foreground hover:text-foreground',+ )}+ >+ {option.label}+ {/* A zero is worth showing: "Overdue 0" is the answer to the+ question, and hiding it makes the reader click to find+ out. `undefined` means the count is still loading. */}+ {option.count !== undefined && (+ <span+ data-testid={`${testIdPrefix}-${option.value}-count`}+ className={cn(+ 'tabular-nums text-[11px]',+ active ? 'text-muted-foreground' : 'text-muted-foreground/70',+ )}+ >+ {option.count}+ </span>+ )}+ </button>+ )+ })}+ </div>+ )+}++/** Icon-only row action, same affordance as the one in `recurring`. */+export function IconAction({+ onClick,+ label,+ children,+ destructive = false,+}: {+ onClick: () => void+ label: string+ children: React.ReactNode+ destructive?: boolean+}) {+ return (+ <button+ onClick={onClick}+ aria-label={label}+ title={label}+ className={cn(+ 'p-1.5 rounded-md text-muted-foreground transition-colors',+ destructive+ ? 'hover:text-destructive hover:bg-destructive/5'+ : 'hover:text-primary hover:bg-primary/5',+ )}+ >+ {children}+ </button>+ )+}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex a8d11cd7..51c3c141 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -19,6 +19,16 @@ import type {Transaction,Payee,PayeeSummary,+ Invoice,+ InvoiceDirection,+ InvoiceDocumentPayload,+ InvoiceFacets,+ InvoiceLineInput,+ InvoiceShareLink,+ IssuerProfile,+ IssuerTaxId,+ InvoiceSettings,+ InvoiceSummary,RecurringTransaction,ProjectedTransaction,TransactionCalendarResponse,@@ -65,6 +75,7 @@ import type {TransactionEditPayload,InstallmentSeriesInput,TransactionApplyScope,+ InvoiceAttachment,} from '@/types'const api = axios.create({@@ -1677,3 +1688,202 @@ export const agents = {}export default api++// Invoices — business workspaces only. Every route 404s for a workspace+// without the module, so these are never called from a personal one.+export interface InvoiceWritePayload {+ direction?: InvoiceDirection+ /** Keep it a draft even where the workspace would open it on creation.+ * Not a status field — only the difference between "still writing+ * this" and "this is owed". Ignored on update. */+ as_draft?: boolean+ /** Provenance, for anything that did not originate here: a gateway+ * sync, a forwarded email, a photographed supplier invoice. */+ origin?: 'local' | 'imported'+ external_source?: string+ external_id?: string+ payee_id?: string | null+ issue_date?: string+ due_date?: string+ competence_date?: string | null+ currency?: string+ total?: string+ discount?: string+ notes?: string | null+ internal_notes?: string | null+ custom_fields?: Record<string, string> | null+ lines?: InvoiceLineInput[]+}++export const invoices = {+ facets: async (year?: number, direction?: InvoiceDirection): Promise<InvoiceFacets> => {+ const { data } = await api.get('/invoices/facets', {+ params: { ...(year ? { year } : {}), ...(direction ? { direction } : {}) },+ })+ return data+ },+ list: async (params?: { state?: string; year?: number; direction?: InvoiceDirection; payee_id?: string; q?: string } | Record<string, unknown>): Promise<Invoice[]> => {+ const cleanParams = params && !('queryKey' in params) ? params : undefined+ const { data } = await api.get('/invoices', { params: cleanParams })+ return data+ },+ get: async (id: string): Promise<Invoice> => {+ const { data } = await api.get(`/invoices/${id}`)+ return data+ },+ summary: async (direction?: InvoiceDirection): Promise<InvoiceSummary> => {+ const { data } = await api.get('/invoices/summary', {+ params: direction ? { direction } : undefined,+ })+ return data+ },+ create: async (payload: InvoiceWritePayload): Promise<Invoice> => {+ const { data } = await api.post('/invoices', payload)+ return data+ },+ update: async (id: string, payload: InvoiceWritePayload): Promise<Invoice> => {+ const { data } = await api.patch(`/invoices/${id}`, payload)+ return data+ },+ remove: async (id: string): Promise<void> => {+ await api.delete(`/invoices/${id}`)+ },+ // The decisions. Each is its own call for the same reason it is its own+ // route on the server: a status change always has a cause.+ issue: async (id: string): Promise<Invoice> => {+ const { data } = await api.post(`/invoices/${id}/issue`)+ return data+ },+ void: async (id: string): Promise<Invoice> => {+ const { data } = await api.post(`/invoices/${id}/void`)+ return data+ },+ writeOff: async (id: string): Promise<Invoice> => {+ const { data } = await api.post(`/invoices/${id}/uncollectible`)+ return data+ },+ reopen: async (id: string): Promise<Invoice> => {+ const { data } = await api.post(`/invoices/${id}/reopen`)+ return data+ },+ allocate: async (id: string, transactionId: string, amount?: string): Promise<Invoice> => {+ const { data } = await api.post(`/invoices/${id}/allocations`, {+ transaction_id: transactionId,+ ...(amount ? { amount } : {}),+ })+ return data+ },+ unallocate: async (id: string, allocationId: string): Promise<Invoice> => {+ const { data } = await api.delete(`/invoices/${id}/allocations/${allocationId}`)+ return data+ },+ settings: async (): Promise<InvoiceSettings> => {+ const { data } = await api.get('/invoices/settings')+ return data+ },+ updateSettings: async (payload: Partial<InvoiceSettings>): Promise<InvoiceSettings> => {+ const { data } = await api.patch('/invoices/settings', payload)+ return data+ },+ issuer: async (): Promise<IssuerProfile> => {+ const { data } = await api.get('/invoices/issuer')+ return data+ },+ updateIssuer: async (payload: {+ legal_name?: string | null+ address?: string | null+ tax_ids?: IssuerTaxId[]+ }): Promise<IssuerProfile> => {+ const { data } = await api.patch('/invoices/issuer', payload)+ return data+ },+ document: async (id: string): Promise<InvoiceDocumentPayload> => {+ const { data } = await api.get(`/invoices/${id}/document`)+ return data+ },+ /** Fetched as a blob rather than linked directly: the PDF route needs+ * the Authorization header and the workspace header the interceptor+ * adds, which a plain <a href> would not carry. */+ pdf: async (id: string): Promise<Blob> => {+ const { data } = await api.get(`/invoices/${id}/pdf`, { responseType: 'blob' })+ return data+ },+ share: async (id: string): Promise<InvoiceShareLink> => {+ const { data } = await api.post(`/invoices/${id}/share`)+ return data+ },+ unshare: async (id: string): Promise<void> => {+ await api.delete(`/invoices/${id}/share`)+ },+ /** The workspace's mark. Uploaded rather than linked, so a rendered+ * document never fetches an image from somebody else's host. */+ uploadLogo: async (file: File): Promise<InvoiceSettings> => {+ const form = new FormData()+ form.append('file', file)+ const { data } = await api.post('/invoices/settings/logo', form)+ return data+ },+ removeLogo: async (): Promise<InvoiceSettings> => {+ const { data } = await api.delete('/invoices/settings/logo')+ return data+ },+ /** By id, not "the current one": a document issued under an older mark+ * froze that id, and asking for the current logo would repaint it. */+ logoUrl: async (logoId: string): Promise<string> => {+ const { data } = await api.get(`/invoices/logo/${logoId}`, { responseType: 'blob' })+ return URL.createObjectURL(data)+ },+ /** The paper gathered under an invoice: the bill, the fiscal document,+ * a receipt, the contract behind it. */+ attachments: {+ list: async (invoiceId: string): Promise<InvoiceAttachment[]> => {+ const { data } = await api.get(`/invoices/${invoiceId}/attachments`)+ return data+ },+ upload: async (+ invoiceId: string,+ file: File,+ fields: { kind?: string; document_number?: string; issued_at?: string; is_primary?: boolean } = {},+ ): Promise<InvoiceAttachment> => {+ const form = new FormData()+ form.append('file', file)+ Object.entries(fields).forEach(([key, value]) => {+ if (value !== undefined && value !== null && value !== '') form.append(key, String(value))+ })+ const { data } = await api.post(`/invoices/${invoiceId}/attachments`, form)+ return data+ },+ /** Same reason as `pdf` above: the route needs headers a plain+ * <a href> would not carry, so the bytes come back as a blob. */+ blobUrl: async (invoiceId: string, attachmentId: string): Promise<string> => {+ const { data } = await api.get(`/invoices/${invoiceId}/attachments/${attachmentId}`, {+ responseType: 'blob',+ })+ return URL.createObjectURL(data)+ },+ update: async (+ invoiceId: string,+ attachmentId: string,+ payload: Partial<Pick<InvoiceAttachment, 'kind' | 'document_number' | 'issued_at' | 'is_primary'>>,+ ): Promise<InvoiceAttachment> => {+ const { data } = await api.patch(`/invoices/${invoiceId}/attachments/${attachmentId}`, payload)+ return data+ },+ remove: async (invoiceId: string, attachmentId: string): Promise<void> => {+ await api.delete(`/invoices/${invoiceId}/attachments/${attachmentId}`)+ },+ },+}++/** The shared invoice. Unauthenticated by design — the token is the whole+ * credential — so these bypass the api instance and its interceptors. */+export const publicInvoices = {+ get: async (token: string): Promise<InvoiceDocumentPayload> => {+ // Bare axios, not the shared instance: the interceptors would attach+ // an Authorization header and a workspace id, and this route must+ // work for someone who has neither.+ const { data } = await axios.get(`/api/public/invoices/${token}`)+ return data+ },+ pdfUrl: (token: string): string => `/api/public/invoices/${token}/pdf`,+}diff --git a/frontend/src/lib/invoice-utils.test.ts b/frontend/src/lib/invoice-utils.test.tsnew file mode 100644index 00000000..bf26cfd4--- /dev/null+++ b/frontend/src/lib/invoice-utils.test.ts@@ -0,0 +1,353 @@+import { describe, expect, it } from 'vitest'+import {+ OUTSTANDING_STATES,+ STATE_TONE,+ availableActions,+ customFieldDefs,+ daysUntilDue,+ displayNumber,+ documentProvenance,+ documentSource,+ formatFileSize,+ invoiceErrorKey,+ isOutstanding,+ linesTotal,+ previewKind,+ resolveTemplate,+} from './invoice-utils'+import type { Invoice, InvoiceState } from '@/types'++/** A minimal invoice, overridable per test. Defaults to the shape the+ * tracking preset produces: issued, unpaid, no document. */+function makeInvoice(overrides: Partial<Invoice> = {}): Invoice {+ return {+ id: 'inv-1',+ payee_id: null,+ payee: null,+ document_type: 'invoice',+ direction: 'receivable',+ origin: 'local',+ external_source: null,+ external_id: null,+ number: 7,+ series: null,+ external_number: null,+ status: 'open',+ state: 'open',+ issue_date: '2026-08-01',+ due_date: '2026-08-31',+ competence_date: '2026-08-01',+ sent_at: null,+ currency: 'USD',+ subtotal: '0.00',+ discount: '0.00',+ tax_total: '0.00',+ total: '1000.00',+ amount_paid: '0.00',+ balance: '1000.00',+ days_overdue: 0,+ notes: null,+ internal_notes: null,+ custom_fields: null,+ snapshot: null,+ share_token: null,+ lines: [],+ allocations: [],+ created_at: '2026-08-01T00:00:00Z',+ ...overrides,+ }+}++describe('STATE_TONE', () => {+ it('styles every state the server can send', () => {+ // A state without a tone renders unstyled in production. Keeping the+ // list here means adding one is a failing test, not a silent gap.+ const states: InvoiceState[] = [+ 'draft', 'open', 'partial', 'paid', 'overdue', 'void', 'uncollectible',+ ]+ for (const state of states) expect(STATE_TONE[state]).toBeTruthy()+ })++ it('gives void a struck-through treatment', () => {+ expect(STATE_TONE.void).toContain('line-through')+ })+})++describe('isOutstanding', () => {+ it('counts the three states where money is still expected', () => {+ expect(OUTSTANDING_STATES).toEqual(['open', 'partial', 'overdue'])+ for (const state of OUTSTANDING_STATES) {+ expect(isOutstanding(makeInvoice({ state }))).toBe(true)+ }+ })++ it('excludes uncollectible — a decision to stop expecting', () => {+ expect(isOutstanding(makeInvoice({ state: 'uncollectible' }))).toBe(false)+ })++ it('excludes drafts, paid and void', () => {+ for (const state of ['draft', 'paid', 'void'] as InvoiceState[]) {+ expect(isOutstanding(makeInvoice({ state }))).toBe(false)+ }+ })+})++describe('availableActions', () => {+ it('lets a draft be edited, deleted and issued — and nothing else', () => {+ const actions = availableActions(makeInvoice({ status: 'draft', state: 'draft', number: null }))+ expect(actions).toEqual({+ canEdit: true, canDelete: true, canIssue: true,+ canVoid: false, canWriteOff: false, canReopen: false, canAllocate: false,+ })+ })++ it('freezes an issued invoice: no edit, no delete', () => {+ const actions = availableActions(makeInvoice())+ expect(actions.canEdit).toBe(false)+ // An issued invoice is never deleted — void keeps the paper trail.+ expect(actions.canDelete).toBe(false)+ expect(actions.canVoid).toBe(true)+ expect(actions.canWriteOff).toBe(true)+ expect(actions.canAllocate).toBe(true)+ })++ it('refuses to offer void once money is linked', () => {+ // Voiding would strand the allocation; the server refuses it too.+ const actions = availableActions(+ makeInvoice({+ balance: '500.00',+ allocations: [+ { id: 'a1', transaction_id: 't1', credit_note_id: null, amount: '500.00',+ method: 'manual', allocated_at: '2026-08-10T00:00:00Z', transaction: null },+ ],+ }),+ )+ expect(actions.canVoid).toBe(false)+ expect(actions.canAllocate).toBe(true)+ })++ it('stops offering allocation once the balance reaches zero', () => {+ const actions = availableActions(makeInvoice({ balance: '0.00', state: 'paid' }))+ expect(actions.canAllocate).toBe(false)+ })++ it('offers reopen only on an uncollectible invoice', () => {+ expect(availableActions(makeInvoice({ status: 'uncollectible' })).canReopen).toBe(true)+ expect(availableActions(makeInvoice({ status: 'open' })).canReopen).toBe(false)+ })++ it('offers nothing destructive on a voided invoice', () => {+ const actions = availableActions(makeInvoice({ status: 'void', state: 'void' }))+ expect(Object.values(actions).every((v) => v === false)).toBe(true)+ })+})++describe('displayNumber', () => {+ it('says a draft has no number rather than inventing one', () => {+ expect(displayNumber(makeInvoice({ number: null }))).toBeNull()+ })++ it('uses live settings while there is no snapshot', () => {+ expect(displayNumber(makeInvoice({ snapshot: null }), 'FAT-')).toBe('FAT-7')+ })++ it('prefers the prefix frozen into the document', () => {+ const invoice = makeInvoice({ snapshot: { number_prefix: 'INV/' } })+ expect(displayNumber(invoice, 'FAT-')).toBe('INV/7')+ })++ it('never puts our prefix on a document we did not write', () => {+ const imported = makeInvoice({+ origin: 'imported',+ external_number: 'FAT-9931',+ number: null,+ snapshot: null,+ })+ expect(displayNumber(imported, 'INV-')).toBe('FAT-9931')+ })++ it('reproduces a padded source name our own column could not hold', () => {+ const imported = makeInvoice({+ origin: 'imported',+ external_number: '2026/A/0031',+ number: null,+ snapshot: null,+ })+ expect(displayNumber(imported, 'INV-')).toBe('2026/A/0031')+ })++ it('says nothing when the source named the document nothing', () => {+ const imported = makeInvoice({ origin: 'imported', external_number: null, number: null })+ expect(displayNumber(imported, 'INV-')).toBeNull()+ })++ it('treats a snapshot with no prefix as a real answer, not a gap', () => {+ // The regression this exists for: an invoice issued as "7", before+ // anyone set a prefix, must not start reading as "FAT-7" afterwards.+ // The client already has a document numbered 7.+ const invoice = makeInvoice({ snapshot: { number_prefix: null } })+ expect(displayNumber(invoice, 'FAT-')).toBe('7')+ })++ it('renders bare when neither side has a prefix', () => {+ expect(displayNumber(makeInvoice({ snapshot: {} }), null)).toBe('7')+ })+})++describe('resolveTemplate', () => {+ const live = { labels: { quantity: 'Units' } }+ const frozen = { labels: { quantity: 'Hours' } }++ it('uses the frozen template once the document is issued', () => {+ const invoice = makeInvoice({ snapshot: { template: frozen } })+ expect(resolveTemplate(invoice, live).labels?.quantity).toBe('Hours')+ })++ it('falls back to live settings while the invoice is still a draft', () => {+ expect(resolveTemplate(makeInvoice({ snapshot: null }), live).labels?.quantity).toBe('Units')+ })++ it('returns an empty template rather than undefined', () => {+ expect(resolveTemplate(null, null)).toEqual({})+ })+})++describe('customFieldDefs', () => {+ it('reads the definitions a workspace declared', () => {+ const defs = customFieldDefs({ custom_fields: [{ key: 'po', label: 'PO number' }] })+ expect(defs).toHaveLength(1)+ expect(defs[0].key).toBe('po')+ })++ it('survives a template with no definitions', () => {+ expect(customFieldDefs(null)).toEqual([])+ expect(customFieldDefs({})).toEqual([])+ })++ it('drops malformed entries instead of rendering a broken field', () => {+ // The template is free-form jsonb by design, so it can contain+ // anything a previous version or a hand edit put there.+ const defs = customFieldDefs({+ custom_fields: [{ key: 'ok', label: 'Fine' }, null as never, { label: 'no key' } as never],+ })+ expect(defs.map((d) => d.key)).toEqual(['ok'])+ })+})++describe('linesTotal', () => {+ it('multiplies quantity by price across lines', () => {+ expect(linesTotal([+ { quantity: '10', unit_price: '150.00' },+ { quantity: '2', unit_price: '25.50' },+ ])).toBe(1551)+ })++ it('ignores lines that are still half-typed', () => {+ // The form calls this on every keystroke; "1." and "" are normal+ // intermediate states, not errors to surface.+ expect(linesTotal([{ quantity: '', unit_price: 'abc' }, { quantity: '2', unit_price: '10' }])).toBe(20)+ })++ it('is zero for no lines', () => {+ expect(linesTotal([])).toBe(0)+ })+})++describe('daysUntilDue', () => {+ const today = new Date(2026, 7, 26) // 2026-08-26, local++ it('counts forward to a future due date', () => {+ expect(daysUntilDue(makeInvoice({ due_date: '2026-08-31' }), today)).toBe(5)+ })++ it('goes negative once the date has passed', () => {+ expect(daysUntilDue(makeInvoice({ due_date: '2026-08-14' }), today)).toBe(-12)+ })++ it('is zero on the day itself', () => {+ expect(daysUntilDue(makeInvoice({ due_date: '2026-08-26' }), today)).toBe(0)+ })+})++describe('invoiceErrorKey', () => {+ it('maps the server code onto a translation key', () => {+ const error = { response: { data: { detail: { code: 'over_allocation' } } } }+ expect(invoiceErrorKey(error)).toBe('invoices.errors.over_allocation')+ })++ it('returns null for anything that is not a ledger rule', () => {+ // Matching on the English message would break the moment either+ // side is reworded, so an unrecognised shape must fall through to+ // the generic toast rather than guess.+ expect(invoiceErrorKey(new Error('network'))).toBeNull()+ expect(invoiceErrorKey({ response: { data: { detail: 'plain string' } } })).toBeNull()+ expect(invoiceErrorKey(undefined)).toBeNull()+ })+})+++describe('formatFileSize', () => {+ it('counts bytes below a kilobyte', () => {+ expect(formatFileSize(0)).toBe('0 B')+ expect(formatFileSize(976)).toBe('976 B')+ })++ it('rounds to whole kilobytes, then to a tenth of a megabyte', () => {+ expect(formatFileSize(2048)).toBe('2 KB')+ expect(formatFileSize(1024 * 1024 * 3.25)).toBe('3.3 MB')+ })++ it('does not print nonsense for a size that never arrived', () => {+ expect(formatFileSize(Number.NaN)).toBe('0 B')+ expect(formatFileSize(-1)).toBe('0 B')+ })+})++describe('previewKind', () => {+ it('renders a PDF and an image in place', () => {+ expect(previewKind('application/pdf')).toBe('pdf')+ expect(previewKind('image/png')).toBe('image')+ expect(previewKind('IMAGE/JPEG')).toBe('image')+ })++ it('offers no preview for a format the browser cannot draw', () => {+ // An empty frame is worse than a button that opens the file.+ expect(previewKind('application/xml')).toBe('none')+ expect(previewKind(null)).toBe('none')+ expect(previewKind(undefined)).toBe('none')+ })+})++describe('documentSource', () => {+ it('shows the filed file whenever there is one', () => {+ expect(documentSource('imported', { id: 'a' })).toBe('filed')+ expect(documentSource('local', { id: 'a' })).toBe('filed')+ })++ it('renders our own page only for a document we wrote', () => {+ expect(documentSource('local', null)).toBe('rendered')+ })++ it('draws nothing for an import with nothing filed', () => {+ // The case the aggregator exists for: a blank sheet in our layout,+ // standing in for a document a supplier issued, is an invention.+ expect(documentSource('imported', null)).toBe('missing')+ expect(documentSource('imported', undefined)).toBe('missing')+ })+})+++describe('documentProvenance', () => {+ it('names the system that delivered the file, as that system names itself', () => {+ // Not translated: renaming somebody's integration in our own words+ // helps nobody working out which one delivered which file.+ expect(documentProvenance('stripe')).toEqual({ kind: 'system', name: 'stripe' })+ expect(documentProvenance('nfe-provider')).toEqual({ kind: 'system', name: 'nfe-provider' })+ })++ it('treats no source as a person having uploaded it', () => {+ expect(documentProvenance(null)).toEqual({ kind: 'uploaded' })+ expect(documentProvenance(undefined)).toEqual({ kind: 'uploaded' })+ expect(documentProvenance(' ')).toEqual({ kind: 'uploaded' })+ })+})diff --git a/frontend/src/lib/invoice-utils.ts b/frontend/src/lib/invoice-utils.tsnew file mode 100644index 00000000..b3f58061--- /dev/null+++ b/frontend/src/lib/invoice-utils.ts@@ -0,0 +1,208 @@+import type { Invoice, InvoiceCustomFieldDef, InvoiceState, InvoiceTemplate } from '@/types'++/**+ * Pure helpers for the invoicing ledger.+ *+ * Everything here is a function of data the server already sent. In+ * particular, none of it recomputes `state`: the server derives it from+ * allocations and the due date, and a second implementation on this side+ * is exactly how the two would come to disagree. What lives here is+ * presentation — how a state looks, what may be done to it, and what the+ * document says its own labels are.+ */++/** How a derived state paints. Keyed by state so a new one is a compile+ * error here rather than an unstyled badge in production. */+export const STATE_TONE: Record<InvoiceState, string> = {+ draft: 'bg-muted text-muted-foreground border-border',+ open: 'bg-blue-500/10 text-blue-600 border-blue-500/20 dark:text-blue-400',+ partial: 'bg-amber-500/10 text-amber-600 border-amber-500/20 dark:text-amber-400',+ paid: 'bg-emerald-500/10 text-emerald-600 border-emerald-500/20 dark:text-emerald-400',+ overdue: 'bg-red-500/10 text-red-600 border-red-500/20 dark:text-red-400',+ void: 'bg-muted text-muted-foreground border-border line-through',+ uncollectible: 'bg-muted text-muted-foreground border-border',+}++/** The states that represent money still expected. Used for the "open"+ * filter and for anything that counts receivables. `uncollectible` is+ * deliberately absent — it is a decision to stop expecting. */+export const OUTSTANDING_STATES: InvoiceState[] = ['open', 'partial', 'overdue']++export function isOutstanding(invoice: Invoice): boolean {+ return OUTSTANDING_STATES.includes(invoice.state)+}++/** Which actions the UI should offer. Mirrors the server's rules so the+ * user is never shown a button that will come back 400 — the server+ * still enforces every one of these, this only avoids the dead end. */+export function availableActions(invoice: Invoice): {+ canEdit: boolean+ canDelete: boolean+ canIssue: boolean+ canVoid: boolean+ canWriteOff: boolean+ canReopen: boolean+ canAllocate: boolean+} {+ const isDraft = invoice.status === 'draft'+ const isOpen = invoice.status === 'open'+ const hasMoney = invoice.allocations.length > 0+ const settled = Number(invoice.balance) <= 0+ return {+ // Financial fields are frozen once issued; notes stay editable, which+ // is why the detail view keeps a notes field either way.+ canEdit: isDraft,+ // An issued invoice is never deleted. Void keeps the paper trail.+ canDelete: isDraft,+ canIssue: isDraft,+ // Voiding with money attached would strand the allocation.+ canVoid: isOpen && !hasMoney,+ canWriteOff: isOpen,+ canReopen: invoice.status === 'uncollectible',+ canAllocate: isOpen && !settled,+ }+}++/** The number as a person reads it: the prefix the document carried plus+ * the sequence. Drafts have no number at all, and saying so beats+ * printing a placeholder that looks like one.+ *+ * The snapshot is authoritative whenever it exists — including when it+ * recorded *no* prefix, which is a real answer and not a missing one.+ * An invoice issued as "2" must keep reading as "2" after someone sets+ * a prefix, or the app renames a document the client already has.+ * Live settings are consulted only when there is no snapshot at all.+ *+ * None of that applies to a document we did not write. An import arrives+ * already named, and that name is reproduced verbatim from+ * `external_number` — ours would rename a supplier's reference. */+export function displayNumber(invoice: Invoice, prefix?: string | null): string | null {+ if (invoice.origin === 'imported') return invoice.external_number || null+ if (invoice.number == null) return null+ const resolved = invoice.snapshot+ ? ((invoice.snapshot.number_prefix as string | null) ?? '')+ : (prefix ?? '')+ return `${resolved}${invoice.number}`+}++/** Labels come from the issued document when there is one, and from live+ * settings while it is still a draft. */+export function resolveTemplate(+ invoice: Invoice | null,+ settingsTemplate: InvoiceTemplate | null | undefined,+): InvoiceTemplate {+ const frozen = invoice?.snapshot?.template as InvoiceTemplate | undefined+ return frozen ?? settingsTemplate ?? {}+}++export function customFieldDefs(template: InvoiceTemplate | null | undefined): InvoiceCustomFieldDef[] {+ const defs = template?.custom_fields+ return Array.isArray(defs) ? defs.filter((d) => d && typeof d.key === 'string') : []+}++/** Total of the lines, computed client-side purely so the draft form can+ * show a running total while typing. The server recomputes on save and+ * its answer is the one that is stored. */+export function linesTotal(lines: { quantity: string; unit_price: string }[]): number {+ return lines.reduce((sum, line) => {+ const quantity = Number(line.quantity)+ const price = Number(line.unit_price)+ if (!Number.isFinite(quantity) || !Number.isFinite(price)) return sum+ return sum + quantity * price+ }, 0)+}++/** Days until due, negative once past. Used for the "vence em 3 dias"+ * hint; `days_overdue` from the server is the authority once it is+ * actually late. */+export function daysUntilDue(invoice: Invoice, today = new Date()): number {+ const due = new Date(`${invoice.due_date}T00:00:00`)+ const reference = new Date(today.getFullYear(), today.getMonth(), today.getDate())+ return Math.round((due.getTime() - reference.getTime()) / 86_400_000)+}++/** Map a server rule violation onto a translation key. The server sends+ * a stable `code`; matching on the English message would break the+ * moment either side is reworded. */+export function invoiceErrorKey(error: unknown): string | null {+ const detail = (error as { response?: { data?: { detail?: { code?: string } } } })?.response?.data+ ?.detail+ const code = detail && typeof detail === 'object' ? detail.code : undefined+ return code ? `invoices.errors.${code}` : null+}++/** A person, not a strategy. Mirrors `MANUAL_METHOD` on the server. */+export const MANUAL_METHOD = 'manual'++/**+ * How to describe the origin of an allocation.+ *+ * `method` is either `manual` or the **id of the matching strategy** that+ * produced the link — ids that come from the reconciliation policy, a+ * document that will eventually be user-editable. So this deliberately+ * does not switch on a closed list: it separates "a person did this" from+ * "a rule did this", and hands the id back so the caller can show *which*+ * rule once the policy is readable from the client.+ *+ * Until then an unknown id still reads as an explanation rather than as a+ * mystery, which is the whole reason the column stores it.+ */+export function allocationOrigin(method: string): {+ automatic: boolean+ strategyId: string | null+} {+ const automatic = method !== MANUAL_METHOD+ return { automatic, strategyId: automatic ? method : null }+}+++/** A file size as a person reads it. Bytes below a kilobyte, then whole+ * kilobytes, then one decimal of a megabyte — the precision stops where+ * it stops being information. */+export function formatFileSize(bytes: number): string {+ if (!Number.isFinite(bytes) || bytes < 0) return '0 B'+ if (bytes < 1024) return `${Math.round(bytes)} B`+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`+}++/** How a filed document can be shown in the page.+ *+ * `pdf` and `image` render in place; everything else has to be opened,+ * because guessing at a preview for a format the browser cannot draw+ * produces an empty frame rather than an answer. */+export function previewKind(contentType: string | null | undefined): 'pdf' | 'image' | 'none' {+ const type = (contentType ?? '').toLowerCase()+ if (type === 'application/pdf') return 'pdf'+ if (type.startsWith('image/')) return 'image'+ return 'none'+}++/** Whether the Document tab has a real page to show.+ *+ * Three outcomes, and the middle one is the point: an imported invoice+ * with nothing filed must show neither a file (there is none) nor our+ * own render (we did not write it, and drawing one invents a document+ * somebody else issued). */+export function documentSource(+ origin: string,+ sourceFile: unknown | null | undefined,+): 'filed' | 'missing' | 'rendered' {+ if (sourceFile) return 'filed'+ return origin === 'imported' ? 'missing' : 'rendered'+}++/** Where a filed document came from, as a person reads it.+ *+ * A source id is a machine name (`stripe`, `nfe`, `email`), so it is+ * shown as it is rather than translated — renaming somebody's system in+ * our own words helps nobody trying to work out which integration+ * delivered which file. Only the absence of one is our word: a file+ * with no source was uploaded here by hand.+ */+export function documentProvenance(+ source: string | null | undefined,+): { kind: 'uploaded' } | { kind: 'system'; name: string } {+ const name = (source ?? '').trim()+ return name ? { kind: 'system', name } : { kind: 'uploaded' }+}diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 207e5bc4..0596db32 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -129,8 +129,250 @@"aiAgents": "KI-Agenten"},"invoices": {- "title": "Rechnungen",- "comingNext": "Stelle deinen Kunden Rechnungen und behalte im Blick, was bezahlt ist und was offen bleibt. Das ist das Nächste, was gebaut wird."+ "title": "Invoices",+ "subtitle": "Was Ihre Kunden schulden und was eingegangen ist.",+ "new": "New invoice",+ "newDescription": "Stellen Sie einem Kunden das Gelieferte in Rechnung und verfolgen Sie sie bis zum Zahlungseingang.",+ "empty": "Noch keine Rechnungen. Erstellen Sie die erste und verfolgen Sie, was Ihnen zusteht.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "Auf diese Rechnung ist noch nichts eingegangen.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Wählen Sie das Geld, das diese Rechnung beglichen hat. Betrag leer lassen, um so viel zu verrechnen, wie passt.",+ "noCandidates": "Keine eingehenden Transaktionen in dieser Währung.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "Leistungsdatum {{competence}} weicht vom Rechnungsdatum {{issue}} ab",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Betrag"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Wann Sie mit der Zahlung rechnen. Ihre Frist: {{days}} Tage.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Leer lassen, um so viel zu verrechnen, wie diese Zahlung abdeckt.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Schlüsseln Sie auf, was Sie geliefert haben, damit der Kunde sieht, wofür er zahlt.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Einheit",+ "unitPlaceholder": "z. B. Stunden",+ "lineCount_one": "{{count}} Position",+ "lineCount_other": "{{count}} Positionen",+ "supplierPlaceholder": "Lieferant auswählen",+ "dueDateHintPayable": "Wann dies bezahlt werden muss."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Als Entwurf speichern"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Wie die Rechnungsstellung hier funktioniert und wie das Dokument aussieht.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Sie stellen anderswo Rechnungen. Hier verfolgen Sie, wer Ihnen was schuldet und ob es ankam.",+ "presetDocumentHint": "Securo schreibt die Rechnung, die Ihr Kunde erhält. Dafür braucht es die Positionen.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Gilt für ab jetzt ausgestellte Rechnungen. Bereits ausgestellte behalten ihr Logo.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Wie der Kunde zahlt — ein Pix-Schlüssel, eine IBAN, ein Bankkonto. Erscheint auf dem Dokument.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Erscheint als Absender auf jeder Rechnung, die Sie ab jetzt ausstellen.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Benennen Sie um, wie das Dokument die einzelnen Felder nennt.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Logo",+ "logoUpload": "Hochladen",+ "logoReplace": "Ersetzen",+ "logoRemove": "Logo entfernen",+ "logoFailed": "Dieses Bild konnte nicht verwendet werden."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Dieser Modus verlangt Positionen.",+ "due_before_issue": "Das Fälligkeitsdatum darf nicht vor dem Rechnungsdatum liegen.",+ "empty_total": "Eine Rechnung ohne Wert kann nicht ausgestellt werden.",+ "not_a_draft": "Nur ein Entwurf kann ausgestellt werden.",+ "not_open": "Nur eine offene Rechnung kann beglichen werden.",+ "draft_not_voidable": "Löschen Sie den Entwurf, statt ihn zu stornieren.",+ "void_with_allocations": "Lösen Sie die Zahlungen, bevor Sie diese Rechnung stornieren.",+ "only_drafts_deletable": "Eine ausgestellte Rechnung wird nie gelöscht — stornieren Sie sie.",+ "issued_invoice_immutable": "Eine ausgestellte Rechnung kann sich nicht ändern. Stornieren und neu ausstellen.",+ "over_allocation": "Das ist mehr, als diese Rechnung noch offen hat.",+ "already_allocated": "Diese Transaktion ist dieser Rechnung bereits zugeordnet.",+ "already_settled": "Diese Rechnung ist bereits vollständig beglichen.",+ "currency_mismatch": "Die Transaktion lautet auf eine andere Währung.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Diese Rechnung kann nicht mehr bearbeitet werden.",+ "not_uncollectible": "Nur eine uneinbringliche Rechnung kann wieder geöffnet werden.",+ "amount_not_positive": "Der Betrag muss größer als null sein.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Stellen Sie die Rechnung aus, bevor Sie sie teilen.",+ "external_source_required": "Ein importiertes Dokument muss angeben, woher es stammt.",+ "payable_not_shareable": "Eine erhaltene Rechnung kann nicht geteilt werden.",+ "discount_exceeds_total": "Der Rabatt ist größer als der berechnete Betrag.",+ "no_document_filed": "Dieses Dokument wurde anderswo ausgestellt. Hängen Sie die erhaltene Datei an.",+ "already_imported": "Dieses Dokument wurde bereits importiert."+ },+ "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": {+ "noLines": "Diese Rechnung hat keine Positionen — sie hält fest, was geschuldet wird, und das Dokument wurde anderswo ausgestellt."+ },+ "tab": {+ "details": "Details",+ "document": "Dokumente"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Jeder mit diesem Link kann die Rechnung sehen:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Dieser Link gilt nicht mehr. Bitten Sie den Absender um einen neuen."+ },+ "section": "Business",+ "emptyFiltered": "Zu diesem Filter passt nichts.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "In {{year}} wurde nichts ausgestellt.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Ein Entwurf lässt sich noch ändern. Sobald der Kunde sie hat, stornieren und neu ausstellen.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Erfassen Sie, was ein Lieferant berechnet, damit nichts zu spät oder doppelt bezahlt wird.",+ "emptyPayable": "Noch keine erhaltenen Rechnungen. Fügen Sie eine hinzu, um zu verfolgen, was Sie schulden.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "Ihr Lieferant hat sie ausgestellt. Angezeigt, wie erfasst, nicht als etwas, das Sie gesendet haben.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Dokumente",+ "add": "Hinzufügen",+ "empty": "Noch keine Dokumente abgelegt. Die Rechnung, das Steuerdokument und der Beleg gehören hierher.",+ "primaryHint": "Beim Herunterladen dieser Rechnung wird diese Datei ausgegeben",+ "makePrimary": "Als das Dokument verwenden",+ "remove": "Dokument entfernen",+ "uploadFailed": "Diese Datei konnte nicht hinzugefügt werden.",+ "openOriginal": "Original öffnen",+ "cannotPreview": "Diese Datei kann hier nicht angezeigt werden. Zum Ansehen bitte öffnen.",+ "kind": {+ "bill": "Rechnung",+ "fiscal": "Steuerdokument",+ "receipt": "Beleg",+ "contract": "Vertrag",+ "other": "Sonstiges"+ },+ "notOurs": "Das Dokument wurde anderswo ausgestellt",+ "notOursHint": "Hängen Sie die erhaltene Datei an, dann wird sie hier genau so angezeigt, wie sie eingegangen ist.",+ "ourPage": "Rechnung",+ "rendered": "Von Securo erzeugt · {{date}}",+ "kindLabel": "Dokumenttyp",+ "fromSystem": "Von {{source}} · {{date}}",+ "fromUpload": "Hochgeladen · {{date}}"+ },+ "draftSaved": "Entwurf gespeichert"},"collections": {"title": "Sammlungen",@@ -554,7 +796,10 @@"calendarNoActivity": "Keine Aktivität in diesem Monat","calendarNoMovements": "Keine Bewegungen","calendarActualNet": "Tatsächliches Netto",- "calendarTransfersExcluded": "Umbuchungen zählen nicht als Einnahmen oder Ausgaben"+ "calendarTransfersExcluded": "Umbuchungen zählen nicht als Einnahmen oder Ausgaben",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Konten",@@ -1445,7 +1690,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Andere Länder",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 0b12f95b..d7521e55 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -130,7 +130,249 @@},"invoices": {"title": "Invoices",- "comingNext": "Bill your clients and keep track of what has been paid and what is still open. This is the next thing being built."+ "subtitle": "What your clients owe, and what has landed.",+ "new": "New invoice",+ "newDescription": "Charge a client for what you delivered, and follow it until the money lands.",+ "empty": "No invoices yet. Create the first one to start tracking what you are owed.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "Nothing received against this invoice yet.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Pick the money that settled this invoice. Leave the amount blank to apply as much as fits.",+ "noCandidates": "No incoming transactions in this currency.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "Accrual date {{competence}} differs from the issue date {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Amount"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "When you expect to be paid. Your terms: {{days}} days.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Leave blank to settle as much of the invoice as this payment covers.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Break down what you delivered, so the client sees what they are paying for.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Unit",+ "unitPlaceholder": "e.g. hours",+ "lineCount_one": "{{count}} line",+ "lineCount_other": "{{count}} lines",+ "supplierPlaceholder": "Select a supplier",+ "dueDateHintPayable": "When this has to be paid."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Save as draft"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "How invoicing behaves here, and how the document looks.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "You invoice somewhere else. Here you follow who owes you and whether it arrived.",+ "presetDocumentHint": "Securo writes the invoice your client receives. It needs what you are charging for.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Applies to invoices issued from now on. Documents already issued keep the logo they carried.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "How the client pays you — a Pix key, an IBAN, a bank account. Shown on the document.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Appears as the sender on every invoice you issue from now on.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Rename what the document calls each field.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Logo",+ "logoUpload": "Upload",+ "logoReplace": "Replace",+ "logoRemove": "Remove logo",+ "logoFailed": "That image could not be used."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "This mode requires line items.",+ "due_before_issue": "The due date cannot come before the issue date.",+ "empty_total": "An invoice with no value cannot be issued.",+ "not_a_draft": "Only a draft can be issued.",+ "not_open": "Only an open invoice can be settled.",+ "draft_not_voidable": "Delete the draft instead of voiding it.",+ "void_with_allocations": "Unlink the payments before voiding this invoice.",+ "only_drafts_deletable": "An issued invoice is never deleted — void it instead.",+ "issued_invoice_immutable": "An issued invoice cannot change. Void it and issue a new one.",+ "over_allocation": "That is more than this invoice still owes.",+ "already_allocated": "This transaction is already linked to this invoice.",+ "already_settled": "This invoice is already fully settled.",+ "currency_mismatch": "The transaction is in a different currency.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "This invoice can no longer be edited.",+ "not_uncollectible": "Only an uncollectible invoice can be reopened.",+ "amount_not_positive": "The amount must be greater than zero.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Issue the invoice before sharing it.",+ "external_source_required": "An imported document must say where it came from.",+ "payable_not_shareable": "A bill you received cannot be shared.",+ "discount_exceeds_total": "The discount is larger than the amount being billed.",+ "no_document_filed": "This document was issued elsewhere. Attach the file that was received.",+ "already_imported": "This document has already been imported."+ },+ "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": {+ "noLines": "This invoice has no line items — it records what is owed, and the document was issued elsewhere."+ },+ "tab": {+ "details": "Details",+ "document": "Documents"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Anyone with this link can view the invoice:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "This link is no longer valid. Ask the sender for a new one."+ },+ "section": "Business",+ "emptyFiltered": "Nothing matches this filter.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "Nothing issued in {{year}}.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "A draft can still change. Once the client has it, cancel it and issue a new one.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Record what a supplier is charging you, so nothing is paid late or twice.",+ "emptyPayable": "No bills yet. Add one to track what you owe.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "Your supplier issued this. Shown as recorded, not as something you sent.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Documents",+ "add": "Add",+ "empty": "No documents filed yet. The bill, the fiscal document and the receipt all belong here.",+ "primaryHint": "Downloading this invoice hands over this file",+ "makePrimary": "Use as the document",+ "remove": "Remove document",+ "uploadFailed": "That file could not be added.",+ "openOriginal": "Open the original",+ "cannotPreview": "This file cannot be previewed here. Open it to view it.",+ "kind": {+ "bill": "Bill",+ "fiscal": "Fiscal document",+ "receipt": "Receipt",+ "contract": "Contract",+ "other": "Other"+ },+ "notOurs": "The document was issued elsewhere",+ "notOursHint": "Attach the file you received and it will be shown here, exactly as it arrived.",+ "ourPage": "Invoice",+ "rendered": "Generated by Securo · {{date}}",+ "kindLabel": "Document type",+ "fromSystem": "From {{source}} · {{date}}",+ "fromUpload": "Uploaded · {{date}}"+ },+ "draftSaved": "Draft saved"},"collections": {"title": "Collections",@@ -554,7 +796,10 @@"calendarNoActivity": "No activity this month","calendarNoMovements": "No movements","calendarActualNet": "Actual net",- "calendarTransfersExcluded": "Transfers are not counted as income or expenses"+ "calendarTransfersExcluded": "Transfers are not counted as income or expenses",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Accounts",@@ -1444,7 +1689,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Other countries",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 1b4f3223..9c62f98e 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -129,8 +129,250 @@"aiAgents": "Agentes IA"},"invoices": {- "title": "Facturas",- "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."+ "title": "Invoices",+ "subtitle": "Lo que te deben tus clientes y lo que ya entró.",+ "new": "New invoice",+ "newDescription": "Cobra a un cliente por lo que entregaste y sigue la factura hasta que entre el dinero.",+ "empty": "Aún no hay facturas. Crea la primera y empieza a seguir lo que te deben.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "Todavía no ha entrado nada contra esta factura.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Elige el dinero que saldó esta factura. Deja el importe en blanco para aplicar todo lo que quepa.",+ "noCandidates": "No hay transacciones entrantes en esta moneda.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "La fecha de devengo {{competence}} difiere de la fecha de emisión {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Importe"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Cuándo esperas cobrar. Tu plazo: {{days}} días.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Déjalo en blanco para aplicar todo lo que cubra este pago.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Detalla lo que entregaste, para que el cliente vea por qué está pagando.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Unidad",+ "unitPlaceholder": "p. ej. horas",+ "lineCount_one": "{{count}} línea",+ "lineCount_other": "{{count}} líneas",+ "supplierPlaceholder": "Selecciona un proveedor",+ "dueDateHintPayable": "Cuándo hay que pagarlo."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Guardar borrador"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Cómo funciona la facturación aquí y cómo se ve el documento.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Facturas en otro sitio. Aquí sigues quién te debe y si el dinero llegó.",+ "presetDocumentHint": "Securo escribe la factura que recibe tu cliente. Necesita saber qué estás cobrando.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Se aplica a las facturas emitidas de ahora en adelante. Las ya emitidas conservan su logo.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Cómo te paga el cliente — una clave Pix, un IBAN, una cuenta bancaria. Se muestra en el documento.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Aparece como remitente en cada factura que emitas de ahora en adelante.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Renombra cómo llama el documento a cada campo.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Logo",+ "logoUpload": "Subir",+ "logoReplace": "Reemplazar",+ "logoRemove": "Quitar logo",+ "logoFailed": "No se pudo usar esa imagen."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Este modo requiere líneas de detalle.",+ "due_before_issue": "La fecha de vencimiento no puede ser anterior a la de emisión.",+ "empty_total": "No se puede emitir una factura sin valor.",+ "not_a_draft": "Solo se puede emitir un borrador.",+ "not_open": "Solo se puede saldar una factura abierta.",+ "draft_not_voidable": "Elimina el borrador en lugar de anularlo.",+ "void_with_allocations": "Desvincula los pagos antes de anular esta factura.",+ "only_drafts_deletable": "Una factura emitida nunca se elimina — anúlala.",+ "issued_invoice_immutable": "Una factura emitida no puede cambiar. Anúlala y emite otra.",+ "over_allocation": "Eso es más de lo que esta factura aún debe.",+ "already_allocated": "Esta transacción ya está vinculada a esta factura.",+ "already_settled": "Esta factura ya está totalmente saldada.",+ "currency_mismatch": "La transacción está en otra moneda.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Esta factura ya no se puede editar.",+ "not_uncollectible": "Solo se puede reabrir una factura incobrable.",+ "amount_not_positive": "El importe debe ser mayor que cero.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Emite la factura antes de compartirla.",+ "external_source_required": "Un documento importado debe indicar de dónde viene.",+ "payable_not_shareable": "Una factura recibida no se puede compartir.",+ "discount_exceeds_total": "El descuento es mayor que el importe facturado.",+ "no_document_filed": "Este documento se emitió en otro lugar. Adjunta el archivo recibido.",+ "already_imported": "Este documento ya fue importado."+ },+ "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": {+ "noLines": "Esta factura no tiene líneas — registra lo que se debe, y el documento se emitió en otro lugar."+ },+ "tab": {+ "details": "Details",+ "document": "Documentos"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Cualquiera con este enlace puede ver la factura:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Este enlace ya no es válido. Pide uno nuevo al remitente."+ },+ "section": "Business",+ "emptyFiltered": "Nada coincide con este filtro.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "No se emitió nada en {{year}}.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Un borrador todavía cambia. Una vez que el cliente la tiene, anúlala y emite otra.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Registra lo que un proveedor te está cobrando, para no pagar tarde ni dos veces.",+ "emptyPayable": "Aún no hay facturas recibidas. Añade una para seguir lo que debes.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "La emitió tu proveedor. Se muestra tal como se registró, no como algo que enviaste.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Documentos",+ "add": "Añadir",+ "empty": "Aún no hay documentos archivados. La factura, el documento fiscal y el recibo van aquí.",+ "primaryHint": "Al descargar esta factura se entrega este archivo",+ "makePrimary": "Usar como el documento",+ "remove": "Eliminar documento",+ "uploadFailed": "No se pudo añadir ese archivo.",+ "openOriginal": "Abrir el original",+ "cannotPreview": "Este archivo no se puede previsualizar aquí. Ábrelo para verlo.",+ "kind": {+ "bill": "Factura",+ "fiscal": "Documento fiscal",+ "receipt": "Recibo",+ "contract": "Contrato",+ "other": "Otro"+ },+ "notOurs": "El documento se emitió en otro lugar",+ "notOursHint": "Adjunta el archivo que recibiste y se mostrará aquí, tal como llegó.",+ "ourPage": "Factura",+ "rendered": "Generada por Securo · {{date}}",+ "kindLabel": "Tipo de documento",+ "fromSystem": "De {{source}} · {{date}}",+ "fromUpload": "Subido · {{date}}"+ },+ "draftSaved": "Borrador guardado"},"collections": {"title": "Colecciones",@@ -554,7 +796,10 @@"calendarNoActivity": "Sin actividad este mes","calendarNoMovements": "Sin movimientos","calendarActualNet": "Neto real",- "calendarTransfersExcluded": "Las transferencias no cuentan como ingresos ni gastos"+ "calendarTransfersExcluded": "Las transferencias no cuentan como ingresos ni gastos",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Cuentas",@@ -1445,7 +1690,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Otros países",diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 83d6f470..22d31b9d 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -129,8 +129,250 @@"aiAgents": "Agents IA"},"invoices": {- "title": "Factures",- "comingNext": "Facturez vos clients et suivez ce qui a été payé et ce qui reste ouvert. C'est la prochaine chose en construction."+ "title": "Invoices",+ "subtitle": "Ce que vos clients doivent, et ce qui est arrivé.",+ "new": "New invoice",+ "newDescription": "Facturez un client pour ce que vous avez livré et suivez-la jusqu'au paiement.",+ "empty": "Aucune facture pour l'instant. Créez la première et suivez ce qu'on vous doit.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "Rien n'est encore arrivé sur cette facture.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Choisissez l'argent qui a réglé cette facture. Laissez le montant vide pour imputer tout ce qui rentre.",+ "noCandidates": "Aucune transaction entrante dans cette devise.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "Le fait générateur {{competence}} diffère de la date d'émission {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Montant"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Quand vous attendez le paiement. Votre délai : {{days}} jours.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Laissez vide pour imputer tout ce que ce paiement couvre.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Détaillez ce que vous avez livré, pour que le client voie ce qu'il paie.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Unité",+ "unitPlaceholder": "ex. heures",+ "lineCount_one": "{{count}} ligne",+ "lineCount_other": "{{count}} lignes",+ "supplierPlaceholder": "Sélectionner un fournisseur",+ "dueDateHintPayable": "Quand cette facture doit être payée."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Enregistrer le brouillon"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Comment la facturation fonctionne ici, et à quoi ressemble le document.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Vous facturez ailleurs. Ici vous suivez qui vous doit et si l'argent est arrivé.",+ "presetDocumentHint": "Securo rédige la facture que votre client reçoit. Il lui faut ce que vous facturez.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "S'applique aux factures émises à partir de maintenant. Celles déjà émises gardent leur logo.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Comment le client vous paie — une clé Pix, un IBAN, un compte bancaire. Affiché sur le document.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Apparaît comme expéditeur sur chaque facture que vous émettez à partir de maintenant.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Renommez la façon dont le document appelle chaque champ.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Logo",+ "logoUpload": "Importer",+ "logoReplace": "Remplacer",+ "logoRemove": "Retirer le logo",+ "logoFailed": "Cette image n'a pas pu être utilisée."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Ce mode exige des lignes.",+ "due_before_issue": "La date d'échéance ne peut pas précéder la date d'émission.",+ "empty_total": "Une facture sans valeur ne peut pas être émise.",+ "not_a_draft": "Seul un brouillon peut être émis.",+ "not_open": "Seule une facture ouverte peut être réglée.",+ "draft_not_voidable": "Supprimez le brouillon au lieu de l'annuler.",+ "void_with_allocations": "Détachez les paiements avant d'annuler cette facture.",+ "only_drafts_deletable": "Une facture émise ne se supprime jamais — annulez-la.",+ "issued_invoice_immutable": "Une facture émise ne peut pas changer. Annulez-la et émettez-en une autre.",+ "over_allocation": "C'est plus que ce que cette facture doit encore.",+ "already_allocated": "Cette transaction est déjà liée à cette facture.",+ "already_settled": "Cette facture est déjà entièrement réglée.",+ "currency_mismatch": "La transaction est dans une autre devise.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Cette facture ne peut plus être modifiée.",+ "not_uncollectible": "Seule une facture irrécouvrable peut être rouverte.",+ "amount_not_positive": "Le montant doit être supérieur à zéro.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Émettez la facture avant de la partager.",+ "external_source_required": "Un document importé doit indiquer d'où il vient.",+ "payable_not_shareable": "Une facture reçue ne peut pas être partagée.",+ "discount_exceeds_total": "La remise dépasse le montant facturé.",+ "no_document_filed": "Ce document a été émis ailleurs. Joignez le fichier reçu.",+ "already_imported": "Ce document a déjà été importé."+ },+ "comingNext": "Facturez vos clients et suivez ce qui a été payé et ce qui reste ouvert. C'est la prochaine chose en construction.",+ "document": {+ "noLines": "Cette facture n'a pas de lignes — elle enregistre ce qui est dû, et le document a été émis ailleurs."+ },+ "tab": {+ "details": "Details",+ "document": "Documents"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Toute personne disposant de ce lien peut voir la facture :",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Ce lien n'est plus valide. Demandez-en un nouveau à l'expéditeur."+ },+ "section": "Business",+ "emptyFiltered": "Rien ne correspond à ce filtre.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "Rien n'a été émis en {{year}}.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Un brouillon peut encore changer. Une fois chez le client, annulez-la et émettez-en une autre.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Enregistrez ce qu'un fournisseur vous facture, pour ne rien payer en retard ni deux fois.",+ "emptyPayable": "Aucune facture reçue. Ajoutez-en une pour suivre ce que vous devez.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "Votre fournisseur l'a émise. Affichée telle qu'enregistrée, pas comme quelque chose que vous avez envoyé.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Documents",+ "add": "Ajouter",+ "empty": "Aucun document classé pour l'instant. La facture, le document fiscal et le reçu ont leur place ici.",+ "primaryHint": "Télécharger cette facture remet ce fichier",+ "makePrimary": "Utiliser comme le document",+ "remove": "Supprimer le document",+ "uploadFailed": "Ce fichier n'a pas pu être ajouté.",+ "openOriginal": "Ouvrir l'original",+ "cannotPreview": "Ce fichier ne peut pas être prévisualisé ici. Ouvrez-le pour le consulter.",+ "kind": {+ "bill": "Facture",+ "fiscal": "Document fiscal",+ "receipt": "Reçu",+ "contract": "Contrat",+ "other": "Autre"+ },+ "notOurs": "Le document a été émis ailleurs",+ "notOursHint": "Joignez le fichier que vous avez reçu et il s'affichera ici, tel qu'il est arrivé.",+ "ourPage": "Facture",+ "rendered": "Générée par Securo · {{date}}",+ "kindLabel": "Type de document",+ "fromSystem": "De {{source}} · {{date}}",+ "fromUpload": "Importé · {{date}}"+ },+ "draftSaved": "Brouillon enregistré"},"collections": {"title": "Collections",@@ -554,7 +796,10 @@"calendarNoActivity": "Aucune activité ce mois-ci","calendarNoMovements": "Aucun mouvement","calendarActualNet": "Net réel",- "calendarTransfersExcluded": "Les virements ne comptent pas comme revenus ou dépenses"+ "calendarTransfersExcluded": "Les virements ne comptent pas comme revenus ou dépenses",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Comptes",@@ -1445,7 +1690,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Autres pays",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 360ca3e8..2290f712 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -129,8 +129,250 @@"aiAgents": "Agenti IA"},"invoices": {- "title": "Fatture",- "comingNext": "Fattura i tuoi clienti e tieni traccia di cosa è stato pagato e cosa è ancora aperto. È la prossima cosa in costruzione."+ "title": "Invoices",+ "subtitle": "Quello che i clienti ti devono e quello che è arrivato.",+ "new": "New invoice",+ "newDescription": "Fattura a un cliente quello che hai consegnato e seguila fino all'incasso.",+ "empty": "Ancora nessuna fattura. Creane una e inizia a seguire quello che ti devono.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "Su questa fattura non è ancora arrivato nulla.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Scegli il denaro che ha saldato questa fattura. Lascia l'importo vuoto per applicare quanto ci sta.",+ "noCandidates": "Nessuna transazione in entrata in questa valuta.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "La data di competenza {{competence}} differisce dalla data di emissione {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Importo"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Quando prevedi di incassare. Il tuo termine: {{days}} giorni.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Lascia vuoto per compensare quanto questo pagamento copre.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Dettaglia quello che hai consegnato, così il cliente vede per cosa sta pagando.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Unità",+ "unitPlaceholder": "es. ore",+ "lineCount_one": "{{count}} riga",+ "lineCount_other": "{{count}} righe",+ "supplierPlaceholder": "Seleziona un fornitore",+ "dueDateHintPayable": "Quando va pagata."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Salva bozza"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Come funziona la fatturazione qui e come appare il documento.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Fatturi altrove. Qui segui chi ti deve e se il denaro è arrivato.",+ "presetDocumentHint": "Securo scrive la fattura che il cliente riceve. Gli serve sapere cosa stai fatturando.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Vale per le fatture emesse d'ora in poi. Quelle già emesse mantengono il loro logo.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Come il cliente ti paga — una chiave Pix, un IBAN, un conto bancario. Mostrato sul documento.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Appare come mittente su ogni fattura che emetti d'ora in poi.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Rinomina come il documento chiama ogni campo.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Logo",+ "logoUpload": "Carica",+ "logoReplace": "Sostituisci",+ "logoRemove": "Rimuovi logo",+ "logoFailed": "Non è stato possibile usare questa immagine."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Questa modalità richiede le righe.",+ "due_before_issue": "La data di scadenza non può precedere quella di emissione.",+ "empty_total": "Una fattura senza valore non può essere emessa.",+ "not_a_draft": "Solo una bozza può essere emessa.",+ "not_open": "Solo una fattura aperta può essere saldata.",+ "draft_not_voidable": "Elimina la bozza invece di annullarla.",+ "void_with_allocations": "Scollega i pagamenti prima di annullare questa fattura.",+ "only_drafts_deletable": "Una fattura emessa non si elimina mai — annullala.",+ "issued_invoice_immutable": "Una fattura emessa non può cambiare. Annullala ed emettine un'altra.",+ "over_allocation": "È più di quanto questa fattura deve ancora.",+ "already_allocated": "Questa transazione è già collegata a questa fattura.",+ "already_settled": "Questa fattura è già completamente saldata.",+ "currency_mismatch": "La transazione è in un'altra valuta.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Questa fattura non può più essere modificata.",+ "not_uncollectible": "Solo una fattura inesigibile può essere riaperta.",+ "amount_not_positive": "L'importo deve essere maggiore di zero.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Emetti la fattura prima di condividerla.",+ "external_source_required": "Un documento importato deve dire da dove viene.",+ "payable_not_shareable": "Una fattura ricevuta non può essere condivisa.",+ "discount_exceeds_total": "Lo sconto è maggiore dell'importo fatturato.",+ "no_document_filed": "Questo documento è stato emesso altrove. Allega il file ricevuto.",+ "already_imported": "Questo documento è già stato importato."+ },+ "comingNext": "Fattura i tuoi clienti e tieni traccia di cosa è stato pagato e cosa è ancora aperto. È la prossima cosa in costruzione.",+ "document": {+ "noLines": "Questa fattura non ha righe — registra quanto è dovuto, e il documento è stato emesso altrove."+ },+ "tab": {+ "details": "Details",+ "document": "Documenti"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Chiunque abbia questo link può vedere la fattura:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Questo link non è più valido. Chiedine uno nuovo al mittente."+ },+ "section": "Business",+ "emptyFiltered": "Nulla corrisponde a questo filtro.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "Nel {{year}} non è stato emesso nulla.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Una bozza si può ancora cambiare. Quando il cliente ce l'ha, annullala ed emettine un'altra.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Registra quello che un fornitore ti sta addebitando, per non pagare in ritardo né due volte.",+ "emptyPayable": "Ancora nessuna fattura ricevuta. Aggiungine una per seguire quello che devi.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "L'ha emessa il tuo fornitore. Mostrata così com'è stata registrata, non come qualcosa che hai inviato.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Documenti",+ "add": "Aggiungi",+ "empty": "Nessun documento archiviato. La fattura, il documento fiscale e la ricevuta vanno qui.",+ "primaryHint": "Scaricando questa fattura viene consegnato questo file",+ "makePrimary": "Usa come il documento",+ "remove": "Rimuovi documento",+ "uploadFailed": "Non è stato possibile aggiungere questo file.",+ "openOriginal": "Apri l'originale",+ "cannotPreview": "Questo file non può essere visualizzato qui. Aprilo per vederlo.",+ "kind": {+ "bill": "Fattura",+ "fiscal": "Documento fiscale",+ "receipt": "Ricevuta",+ "contract": "Contratto",+ "other": "Altro"+ },+ "notOurs": "Il documento è stato emesso altrove",+ "notOursHint": "Allega il file che hai ricevuto e verrà mostrato qui, esattamente come è arrivato.",+ "ourPage": "Fattura",+ "rendered": "Generata da Securo · {{date}}",+ "kindLabel": "Tipo di documento",+ "fromSystem": "Da {{source}} · {{date}}",+ "fromUpload": "Caricato · {{date}}"+ },+ "draftSaved": "Bozza salvata"},"collections": {"title": "Collezioni",@@ -554,7 +796,10 @@"calendarNoActivity": "Nessuna attività questo mese","calendarNoMovements": "Nessun movimento","calendarActualNet": "Netto effettivo",- "calendarTransfersExcluded": "I trasferimenti non contano come entrate o spese"+ "calendarTransfersExcluded": "I trasferimenti non contano come entrate o spese",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Conti",@@ -1445,7 +1690,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Altri paesi",diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex 7ae49588..b0ace2c6 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -129,8 +129,250 @@"aiAgents": "AI-agents"},"invoices": {- "title": "Facturen",- "comingNext": "Factureer uw klanten en houd bij wat er is betaald en wat er nog open staat. Dit is het volgende dat gebouwd wordt."+ "title": "Invoices",+ "subtitle": "Wat je klanten je schuldig zijn en wat er binnen is.",+ "new": "New invoice",+ "newDescription": "Factureer een klant voor wat je hebt geleverd en volg het tot het geld binnen is.",+ "empty": "Nog geen facturen. Maak de eerste en volg wat men je verschuldigd is.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "Er is nog niets op deze factuur binnengekomen.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Kies het geld dat deze factuur heeft voldaan. Laat het bedrag leeg om te verrekenen wat erin past.",+ "noCandidates": "Geen inkomende transacties in deze valuta.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "Prestatiedatum {{competence}} wijkt af van de factuurdatum {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Bedrag"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Wanneer je betaling verwacht. Jouw termijn: {{days}} dagen.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Laat leeg om te verrekenen wat deze betaling dekt.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Specificeer wat je hebt geleverd, zodat de klant ziet waarvoor hij betaalt.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Eenheid",+ "unitPlaceholder": "bijv. uren",+ "lineCount_one": "{{count}} regel",+ "lineCount_other": "{{count}} regels",+ "supplierPlaceholder": "Selecteer een leverancier",+ "dueDateHintPayable": "Wanneer dit betaald moet worden."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Opslaan als concept"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Hoe facturering hier werkt en hoe het document eruitziet.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Je factureert elders. Hier volg je wie je nog moet betalen en of het geld binnen is.",+ "presetDocumentHint": "Securo schrijft de factuur die je klant ontvangt. Daarvoor is nodig wat je in rekening brengt.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Geldt voor facturen die vanaf nu worden uitgegeven. Reeds uitgegeven documenten houden hun logo.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Hoe de klant je betaalt — een Pix-sleutel, een IBAN, een bankrekening. Wordt op het document getoond.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Verschijnt als afzender op elke factuur die je vanaf nu uitgeeft.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Hernoem hoe het document elk veld noemt.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Logo",+ "logoUpload": "Uploaden",+ "logoReplace": "Vervangen",+ "logoRemove": "Logo verwijderen",+ "logoFailed": "Deze afbeelding kon niet worden gebruikt."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Deze modus vereist regels.",+ "due_before_issue": "De vervaldatum kan niet vóór de factuurdatum liggen.",+ "empty_total": "Een factuur zonder waarde kan niet worden uitgegeven.",+ "not_a_draft": "Alleen een concept kan worden uitgegeven.",+ "not_open": "Alleen een openstaande factuur kan worden voldaan.",+ "draft_not_voidable": "Verwijder het concept in plaats van het te annuleren.",+ "void_with_allocations": "Ontkoppel de betalingen voordat je deze factuur annuleert.",+ "only_drafts_deletable": "Een uitgegeven factuur wordt nooit verwijderd — annuleer hem.",+ "issued_invoice_immutable": "Een uitgegeven factuur kan niet veranderen. Annuleer hem en geef een nieuwe uit.",+ "over_allocation": "Dat is meer dan deze factuur nog openstaat.",+ "already_allocated": "Deze transactie is al aan deze factuur gekoppeld.",+ "already_settled": "Deze factuur is al volledig voldaan.",+ "currency_mismatch": "De transactie is in een andere valuta.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Deze factuur kan niet meer worden bewerkt.",+ "not_uncollectible": "Alleen een oninbare factuur kan opnieuw worden geopend.",+ "amount_not_positive": "Het bedrag moet groter zijn dan nul.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Geef de factuur uit voordat je hem deelt.",+ "external_source_required": "Een geïmporteerd document moet zeggen waar het vandaan komt.",+ "payable_not_shareable": "Een ontvangen factuur kan niet worden gedeeld.",+ "discount_exceeds_total": "De korting is groter dan het gefactureerde bedrag.",+ "no_document_filed": "Dit document is elders uitgegeven. Voeg het ontvangen bestand toe.",+ "already_imported": "Dit document is al geïmporteerd."+ },+ "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": {+ "noLines": "Deze factuur heeft geen regels — hij legt vast wat verschuldigd is, en het document is elders uitgegeven."+ },+ "tab": {+ "details": "Details",+ "document": "Documenten"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Iedereen met deze link kan de factuur bekijken:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Deze link is niet meer geldig. Vraag de afzender om een nieuwe."+ },+ "section": "Business",+ "emptyFiltered": "Niets komt overeen met dit filter.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "In {{year}} is niets uitgegeven.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Een concept kan nog veranderen. Zodra de klant hem heeft, annuleer je hem en maak je een nieuwe.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Leg vast wat een leverancier in rekening brengt, zodat niets te laat of dubbel wordt betaald.",+ "emptyPayable": "Nog geen ontvangen facturen. Voeg er een toe om te volgen wat je verschuldigd bent.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "Je leverancier heeft hem uitgegeven. Getoond zoals vastgelegd, niet als iets dat jij hebt verstuurd.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Documenten",+ "add": "Toevoegen",+ "empty": "Nog geen documenten opgeslagen. De factuur, het fiscale document en het betaalbewijs horen hier.",+ "primaryHint": "Bij het downloaden van deze factuur wordt dit bestand geleverd",+ "makePrimary": "Gebruiken als het document",+ "remove": "Document verwijderen",+ "uploadFailed": "Dat bestand kon niet worden toegevoegd.",+ "openOriginal": "Open het origineel",+ "cannotPreview": "Dit bestand kan hier niet worden weergegeven. Open het om het te bekijken.",+ "kind": {+ "bill": "Factuur",+ "fiscal": "Fiscaal document",+ "receipt": "Betaalbewijs",+ "contract": "Contract",+ "other": "Overig"+ },+ "notOurs": "Het document is elders uitgegeven",+ "notOursHint": "Voeg het ontvangen bestand toe, dan wordt het hier getoond zoals het binnenkwam.",+ "ourPage": "Factuur",+ "rendered": "Gegenereerd door Securo · {{date}}",+ "kindLabel": "Documenttype",+ "fromSystem": "Van {{source}} · {{date}}",+ "fromUpload": "Geüpload · {{date}}"+ },+ "draftSaved": "Concept opgeslagen"},"collections": {"title": "Collecties",@@ -554,7 +796,10 @@"calendarNoActivity": "Geen activiteit deze maand","calendarNoMovements": "Geen bewegingen","calendarActualNet": "Werkelijk netto",- "calendarTransfersExcluded": "Overdrachten worden niet meegeteld als inkomsten of uitgaven"+ "calendarTransfersExcluded": "Overdrachten worden niet meegeteld als inkomsten of uitgaven",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Rekeningen",@@ -1445,7 +1690,7 @@"ph_tin": "FIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Andere landen",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex 45d1e563..fb3a7d34 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -129,8 +129,250 @@"collections": "Kolekcje"},"invoices": {- "title": "Faktury",- "comingNext": "Wystawiaj faktury klientom i śledź, co zostało zapłacone, a co wciąż jest otwarte. To następna rzecz w budowie."+ "title": "Invoices",+ "subtitle": "Ile są ci winni klienci i co już wpłynęło.",+ "new": "New invoice",+ "newDescription": "Wystaw klientowi rachunek za to, co dostarczyłeś, i śledź go aż do wpływu pieniędzy.",+ "empty": "Jeszcze nie ma faktur. Utwórz pierwszą i zacznij śledzić, ile ci się należy.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "Na tę fakturę jeszcze nic nie wpłynęło.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Wybierz pieniądze, które rozliczyły tę fakturę. Zostaw kwotę pustą, aby rozliczyć tyle, ile się zmieści.",+ "noCandidates": "Brak transakcji przychodzących w tej walucie.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "Data powstania obowiązku {{competence}} różni się od daty wystawienia {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Kwota"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Kiedy spodziewasz się zapłaty. Twój termin: {{days}} dni.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Zostaw puste, aby rozliczyć tyle, ile pokrywa ta płatność.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Rozpisz, co dostarczyłeś, żeby klient widział, za co płaci.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Jednostka",+ "unitPlaceholder": "np. godziny",+ "lineCount_one": "{{count}} pozycja",+ "lineCount_other": "{{count}} pozycji",+ "supplierPlaceholder": "Wybierz dostawcę",+ "dueDateHintPayable": "Kiedy trzeba to zapłacić."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Zapisz szkic"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Jak działa tu fakturowanie i jak wygląda dokument.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Fakturujesz gdzie indziej. Tutaj śledzisz, kto ci zalega i czy pieniądze dotarły.",+ "presetDocumentHint": "Securo pisze fakturę, którą dostaje klient. Potrzebuje tego, za co wystawiasz rachunek.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Dotyczy faktur wystawionych od teraz. Już wystawione zachowują swoje logo.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Jak klient ci płaci — klucz Pix, IBAN, konto bankowe. Pokazywane na dokumencie.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Pojawia się jako nadawca na każdej fakturze wystawionej od teraz.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Zmień nazwy pól używane przez dokument.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Logo",+ "logoUpload": "Prześlij",+ "logoReplace": "Zamień",+ "logoRemove": "Usuń logo",+ "logoFailed": "Nie udało się użyć tego obrazu."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Ten tryb wymaga pozycji.",+ "due_before_issue": "Termin płatności nie może poprzedzać daty wystawienia.",+ "empty_total": "Nie można wystawić faktury o zerowej wartości.",+ "not_a_draft": "Wystawić można tylko szkic.",+ "not_open": "Rozliczyć można tylko otwartą fakturę.",+ "draft_not_voidable": "Usuń szkic zamiast go anulować.",+ "void_with_allocations": "Odłącz płatności przed anulowaniem tej faktury.",+ "only_drafts_deletable": "Wystawionej faktury nigdy się nie usuwa — anuluj ją.",+ "issued_invoice_immutable": "Wystawiona faktura nie może się zmienić. Anuluj ją i wystaw nową.",+ "over_allocation": "To więcej, niż ta faktura jeszcze wynosi.",+ "already_allocated": "Ta transakcja jest już powiązana z tą fakturą.",+ "already_settled": "Ta faktura jest już w pełni rozliczona.",+ "currency_mismatch": "Transakcja jest w innej walucie.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Tej faktury nie można już edytować.",+ "not_uncollectible": "Ponownie otworzyć można tylko fakturę nieściągalną.",+ "amount_not_positive": "Kwota musi być większa niż zero.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Wystaw fakturę przed jej udostępnieniem.",+ "external_source_required": "Zaimportowany dokument musi wskazać, skąd pochodzi.",+ "payable_not_shareable": "Otrzymanej faktury nie można udostępnić.",+ "discount_exceeds_total": "Rabat jest większy niż kwota do zapłaty.",+ "no_document_filed": "Ten dokument został wystawiony gdzie indziej. Dołącz otrzymany plik.",+ "already_imported": "Ten dokument został już zaimportowany."+ },+ "comingNext": "Wystawiaj faktury klientom i śledź, co zostało zapłacone, a co wciąż jest otwarte. To następna rzecz w budowie.",+ "document": {+ "noLines": "Ta faktura nie ma pozycji — zapisuje, ile się należy, a dokument wystawiono gdzie indziej."+ },+ "tab": {+ "details": "Details",+ "document": "Dokumenty"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Każdy z tym linkiem może zobaczyć fakturę:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Ten link już nie działa. Poproś nadawcę o nowy."+ },+ "section": "Business",+ "emptyFiltered": "Nic nie pasuje do tego filtra.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "W roku {{year}} nic nie wystawiono.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Szkic wciąż można zmienić. Gdy klient go dostanie, anuluj i wystaw nowy.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Zapisz, co obciąża cię dostawca, żeby nic nie zostało zapłacone po terminie ani dwa razy.",+ "emptyPayable": "Jeszcze nie ma otrzymanych faktur. Dodaj jedną, aby śledzić, ile jesteś winien.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "Wystawił ją twój dostawca. Pokazana tak, jak ją zapisano, nie jako coś, co wysłałeś.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Dokumenty",+ "add": "Dodaj",+ "empty": "Nie dodano jeszcze żadnych dokumentów. Faktura, dokument fiskalny i potwierdzenie należą tutaj.",+ "primaryHint": "Pobranie tej faktury zwraca ten plik",+ "makePrimary": "Ustaw jako dokument",+ "remove": "Usuń dokument",+ "uploadFailed": "Nie udało się dodać tego pliku.",+ "openOriginal": "Otwórz oryginał",+ "cannotPreview": "Tego pliku nie można tu wyświetlić. Otwórz go, aby zobaczyć.",+ "kind": {+ "bill": "Faktura",+ "fiscal": "Dokument fiskalny",+ "receipt": "Potwierdzenie",+ "contract": "Umowa",+ "other": "Inne"+ },+ "notOurs": "Dokument został wystawiony gdzie indziej",+ "notOursHint": "Dołącz otrzymany plik, a zostanie pokazany tutaj dokładnie w takiej postaci, w jakiej dotarł.",+ "ourPage": "Faktura",+ "rendered": "Wygenerowana przez Securo · {{date}}",+ "kindLabel": "Typ dokumentu",+ "fromSystem": "Z {{source}} · {{date}}",+ "fromUpload": "Przesłano · {{date}}"+ },+ "draftSaved": "Szkic zapisany"},"collections": {"title": "Kolekcje",@@ -587,7 +829,10 @@"calendarNoActivity": "Brak aktywności w tym miesiącu","calendarNoMovements": "Brak operacji","calendarActualNet": "Rzeczywiste netto",- "calendarTransfersExcluded": "Transfery nie liczą się jako przychody ani wydatki"+ "calendarTransfersExcluded": "Transfery nie liczą się jako przychody ani wydatki",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Konta",@@ -1531,7 +1776,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Inne kraje",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex cc131ad7..f5241c70 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -130,7 +130,249 @@},"invoices": {"title": "Cobranças",- "comingNext": "Cobre seus clientes e acompanhe o que já foi pago e o que continua em aberto. É a próxima coisa sendo construída."+ "subtitle": "O que os seus clientes devem, e o que já entrou.",+ "new": "Nova cobrança",+ "newDescription": "Cobre um cliente pelo que você entregou e acompanhe até o dinheiro cair.",+ "empty": "Nenhuma cobrança ainda. Crie a primeira para acompanhar o que você tem a receber.",+ "noNumber": "Rascunho",+ "noClient": "Sem cliente",+ "draftTitle": "Rascunho",+ "created": "Cobrança criada",+ "issued": "Cobrança emitida",+ "voided": "Cobrança cancelada",+ "writtenOff": "Marcada como incobrável",+ "reopened": "Cobrança reaberta",+ "deleted": "Rascunho excluído",+ "linked": "Pagamento vinculado",+ "unlinked": "Vínculo desfeito",+ "backToList": "Voltar para cobranças",+ "payments": "Recebimentos",+ "noPayments": "Nada recebido nesta cobrança ainda.",+ "linkedPayment": "Pagamento vinculado",+ "linkedManually": "Vinculado manualmente",+ "linkedAutomatically": "Conciliado automaticamente",+ "linkDescription": "Escolha o dinheiro que quitou esta cobrança. Deixe o valor em branco para aplicar o que couber.",+ "noCandidates": "Nenhuma entrada nesta moeda.",+ "daysLate": "{{count}}d de atraso",+ "competenceDiverges": "Competência {{competence}} diferente da emissão {{issue}}",+ "state": {+ "draft": "Rascunho",+ "open": "Em aberto",+ "partial": "Parcial",+ "paid": "Recebida",+ "overdue": "Vencida",+ "void": "Cancelada",+ "uncollectible": "Incobrável"+ },+ "filter": {+ "all": "Todas",+ "open": "Em aberto",+ "overdue": "Vencidas",+ "paid": "Recebidas",+ "draft": "Rascunhos"+ },+ "column": {+ "number": "Número",+ "client": "Cliente",+ "due": "Vencimento",+ "total": "Total",+ "balance": "Saldo",+ "state": "Situação",+ "quantity": "Quantidade",+ "supplier": "Fornecedor",+ "amount": "Valor"+ },+ "summary": {+ "outstanding": "A receber",+ "overdue": "Vencido",+ "receivedThisMonth": "Recebido no mês",+ "upcoming": "A vencer",+ "aging": "Por idade",+ "nothingDue": "Nada a receber.",+ "overdueCount_one": "em {{count}} cobrança",+ "overdueCount_other": "em {{count}} cobranças",+ "owed": "A pagar",+ "paidThisMonth": "Pago no mês"+ },+ "field": {+ "client": "Cliente",+ "clientPlaceholder": "Selecione um cliente",+ "total": "Valor",+ "dueDate": "Vencimento",+ "dueDateHint": "Quando você espera receber. Seu prazo: {{days}} dias.",+ "notes": "Observações",+ "paid": "Recebido",+ "amountToApply": "Valor a aplicar",+ "amountHint": "Deixe em branco para abater o quanto este pagamento cobrir.",+ "lines": "Itens",+ "addLine": "Adicionar item",+ "unitPrice": "Valor unitário",+ "taxRate": "Alíquota",+ "lineDescription": "Descrição",+ "linesOptional": "Detalhe o que você entregou, para o cliente ver pelo que está pagando.",+ "supplier": "Fornecedor",+ "paidOut": "Pago",+ "unit": "Unidade",+ "unitPlaceholder": "ex.: horas",+ "lineCount_one": "{{count}} linha",+ "lineCount_other": "{{count}} linhas",+ "supplierPlaceholder": "Selecione um fornecedor",+ "dueDateHintPayable": "Quando isto precisa ser pago."+ },+ "action": {+ "issue": "Emitir",+ "markPaid": "Marcar como recebida",+ "void": "Cancelar",+ "writeOff": "Dar baixa como perda",+ "reopen": "Reabrir",+ "unlink": "Desvincular",+ "link": "Vincular pagamento",+ "downloadPdf": "Baixar PDF",+ "share": "Compartilhar",+ "revokeLink": "Revogar link",+ "saveDraft": "Salvar rascunho"+ },+ "settings": {+ "title": "Configurações de cobrança",+ "description": "Como a cobrança funciona aqui, e como o documento aparece.",+ "preset": "Modo",+ "presetTracking": "Acompanhar recebimentos",+ "presetDocument": "Emitir documentos",+ "presetTrackingHint": "Você emite a fatura em outro lugar. Aqui acompanha quem te deve e se o dinheiro chegou.",+ "presetDocumentHint": "O Securo escreve a fatura que o cliente recebe. Precisa do que está sendo cobrado.",+ "numberPrefix": "Prefixo da numeração",+ "paymentTerms": "Prazo de pagamento (dias)",+ "issuerName": "Nome do seu negócio",+ "logoHint": "Vale para as cobranças emitidas de agora em diante. As já emitidas mantêm o logo que levaram.",+ "footerNote": "Rodapé",+ "saved": "Configurações salvas",+ "paymentDetails": "Dados para pagamento",+ "paymentDetailsHint": "Como o cliente paga você — chave Pix, IBAN, conta bancária. Aparece no documento.",+ "accentColor": "Cor de destaque",+ "issuer": "Dados do seu negócio",+ "issuerHint": "Aparece como remetente nas cobranças emitidas de agora em diante.",+ "legalName": "Razão social",+ "addressLabel": "Endereço",+ "labels": "Rótulos do documento",+ "labelsHint": "Renomeie como o documento chama cada campo.",+ "saveIssuer": "Salvar dados",+ "groupBehaviour": "Como a cobrança funciona",+ "groupDocument": "Como o documento aparece",+ "logo": "Logo",+ "logoUpload": "Enviar",+ "logoReplace": "Substituir",+ "logoRemove": "Remover logo",+ "logoFailed": "Não foi possível usar essa imagem."+ },+ "errors": {+ "generic": "Algo deu errado.",+ "lines_required": "Este modo exige itens na cobrança.",+ "due_before_issue": "O vencimento não pode ser antes da emissão.",+ "empty_total": "Uma cobrança sem valor não pode ser emitida.",+ "not_a_draft": "Só um rascunho pode ser emitido.",+ "not_open": "Só uma cobrança em aberto pode ser quitada.",+ "draft_not_voidable": "Exclua o rascunho em vez de cancelar.",+ "void_with_allocations": "Desvincule os pagamentos antes de cancelar.",+ "only_drafts_deletable": "Uma cobrança emitida nunca é excluída — cancele-a.",+ "issued_invoice_immutable": "Uma cobrança emitida não muda. Cancele e emita outra.",+ "over_allocation": "Isso é mais do que esta cobrança ainda deve.",+ "already_allocated": "Esta transação já está vinculada a esta cobrança.",+ "already_settled": "Esta cobrança já está totalmente quitada.",+ "currency_mismatch": "A transação está em outra moeda.",+ "transaction_not_found": "Transação não encontrada.",+ "payee_not_found": "Cliente não encontrado.",+ "terminal_status": "Esta cobrança não pode mais ser editada.",+ "not_uncollectible": "Só uma cobrança incobrável pode ser reaberta.",+ "amount_not_positive": "O valor deve ser maior que zero.",+ "allocation_not_found": "Vínculo não encontrado.",+ "draft_not_shareable": "Emita a cobrança antes de compartilhar.",+ "external_source_required": "Um documento importado precisa dizer de onde veio.",+ "payable_not_shareable": "Uma conta a pagar não pode ser compartilhada.",+ "discount_exceeds_total": "O desconto é maior do que o valor cobrado.",+ "no_document_filed": "Este documento foi emitido em outro lugar. Anexe o arquivo recebido.",+ "already_imported": "Este documento já foi importado."+ },+ "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": {+ "noLines": "Esta cobrança não tem itens — ela registra o que é devido, e o documento foi emitido em outro lugar."+ },+ "tab": {+ "details": "Detalhes",+ "document": "Documentos"+ },+ "shareCopied": "Link copiado",+ "shareRevoked": "Link revogado",+ "shareActive": "Qualquer pessoa com este link vê a cobrança:",+ "shared": {+ "notFoundTitle": "Cobrança indisponível",+ "notFoundBody": "Este link não vale mais. Peça um novo a quem enviou."+ },+ "section": "Negócio",+ "emptyFiltered": "Nada corresponde a este filtro.",+ "detailsTitle": "Detalhes",+ "shareCopy": "Copiar link",+ "bucket": {+ "current": "A vencer",+ "d1_30": "1–30 dias",+ "d31_60": "31–60 dias",+ "d61_90": "61–90 dias",+ "d90_plus": "90+ dias"+ },+ "moreActions": "Mais ações",+ "allYears": "Todos os exercícios",+ "emptyYear": "Nenhuma cobrança emitida no {{year}}.",+ "showAllYears": "Ver todos os anos",+ "label": {+ "invoice": "Fatura",+ "billTo": "Cliente",+ "from": "Emitente",+ "description": "Descrição",+ "quantity": "Qtd",+ "unitPrice": "Valor unit.",+ "total": "Total",+ "paymentDetails": "Dados para pagamento",+ "notes": "Observações"+ },+ "editDraft": "Editar rascunho",+ "updated": "Cobrança atualizada",+ "editDraftDescription": "Um rascunho ainda muda. Depois que o cliente recebe, cancele e emita outra.",+ "direction": {+ "receivable": "A receber",+ "payable": "A pagar"+ },+ "newPayable": "Nova conta a pagar",+ "newPayableDescription": "Registre o que um fornecedor está cobrando, para nada ser pago em atraso ou duas vezes.",+ "emptyPayable": "Nenhuma conta a pagar ainda. Adicione uma para acompanhar o que você deve.",+ "noSupplier": "Sem fornecedor",+ "receivedDocument": "Documento recebido",+ "receivedDocumentHint": "Emitido pelo seu fornecedor. Exibido como registrado, não como algo que você enviou.",+ "fiscalYear": "Exercício {{year}}",+ "documents": {+ "title": "Documentos",+ "add": "Adicionar",+ "empty": "Nenhum documento anexado ainda. A fatura, a nota fiscal e o comprovante ficam aqui.",+ "primaryHint": "Ao baixar esta fatura, é este arquivo que é entregue",+ "makePrimary": "Usar como o documento",+ "remove": "Remover documento",+ "uploadFailed": "Não foi possível adicionar esse arquivo.",+ "openOriginal": "Abrir o original",+ "cannotPreview": "Este arquivo não pode ser visualizado aqui. Abra-o para ver.",+ "kind": {+ "bill": "Fatura",+ "fiscal": "Nota fiscal",+ "receipt": "Comprovante",+ "contract": "Contrato",+ "other": "Outro"+ },+ "notOurs": "O documento foi emitido em outro lugar",+ "notOursHint": "Anexe o arquivo que você recebeu e ele será mostrado aqui, exatamente como chegou.",+ "ourPage": "Fatura",+ "rendered": "Gerada pelo Securo · {{date}}",+ "kindLabel": "Tipo de documento",+ "fromSystem": "De {{source}} · {{date}}",+ "fromUpload": "Enviado · {{date}}"+ },+ "draftSaved": "Rascunho salvo"},"collections": {"title": "Coleções",@@ -554,7 +796,10 @@"calendarNoActivity": "Sem atividade neste mês","calendarNoMovements": "Sem movimentações","calendarActualNet": "Líquido real",- "calendarTransfersExcluded": "Transferências não contam como receitas ou despesas"+ "calendarTransfersExcluded": "Transferências não contam como receitas ou despesas",+ "invoiceBadge": "Cobrança {{number}}",+ "invoiceBadgeNoNumber": "Cobrança",+ "invoiceBadgeTooltip": "Esta transação quita uma cobrança. Abrir."},"accounts": {"title": "Contas",@@ -1445,7 +1690,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Outros países",diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 080166f7..d48b9b71 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -130,7 +130,249 @@},"invoices": {"title": "Cobranças",- "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."+ "subtitle": "O que os seus clientes devem, e o que já entrou.",+ "new": "Nova cobrança",+ "newDescription": "Cobre um cliente pelo que entregou e acompanhe até o dinheiro entrar.",+ "empty": "Nenhuma cobrança ainda. Crie a primeira para acompanhar o que você tem a receber.",+ "noNumber": "Rascunho",+ "noClient": "Sem cliente",+ "draftTitle": "Rascunho",+ "created": "Cobrança criada",+ "issued": "Cobrança emitida",+ "voided": "Cobrança cancelada",+ "writtenOff": "Marcada como incobrável",+ "reopened": "Cobrança reaberta",+ "deleted": "Rascunho excluído",+ "linked": "Pagamento vinculado",+ "unlinked": "Vínculo desfeito",+ "backToList": "Voltar para cobranças",+ "payments": "Recebimentos",+ "noPayments": "Nada recebido nesta cobrança ainda.",+ "linkedPayment": "Pagamento vinculado",+ "linkedManually": "Vinculado manualmente",+ "linkedAutomatically": "Conciliado automaticamente",+ "linkDescription": "Escolha o dinheiro que quitou esta cobrança. Deixe o valor em branco para aplicar o que couber.",+ "noCandidates": "Nenhuma entrada nesta moeda.",+ "daysLate": "{{count}}d de atraso",+ "competenceDiverges": "Competência {{competence}} diferente da emissão {{issue}}",+ "state": {+ "draft": "Rascunho",+ "open": "Em aberto",+ "partial": "Parcial",+ "paid": "Recebida",+ "overdue": "Vencida",+ "void": "Cancelada",+ "uncollectible": "Incobrável"+ },+ "filter": {+ "all": "Todas",+ "open": "Em aberto",+ "overdue": "Vencidas",+ "paid": "Recebidas",+ "draft": "Rascunhos"+ },+ "column": {+ "number": "Número",+ "client": "Cliente",+ "due": "Vencimento",+ "total": "Total",+ "balance": "Saldo",+ "state": "Situação",+ "quantity": "Quantidade",+ "supplier": "Fornecedor",+ "amount": "Valor"+ },+ "summary": {+ "outstanding": "A receber",+ "overdue": "Vencido",+ "receivedThisMonth": "Recebido no mês",+ "upcoming": "A vencer",+ "aging": "Por idade",+ "nothingDue": "Nada a receber.",+ "overdueCount_one": "em {{count}} cobrança",+ "overdueCount_other": "em {{count}} cobranças",+ "owed": "A pagar",+ "paidThisMonth": "Pago no mês"+ },+ "field": {+ "client": "Cliente",+ "clientPlaceholder": "Selecione um cliente",+ "total": "Valor",+ "dueDate": "Vencimento",+ "dueDateHint": "Quando espera receber. O seu prazo: {{days}} dias.",+ "notes": "Observações",+ "paid": "Recebido",+ "amountToApply": "Valor a aplicar",+ "amountHint": "Deixe em branco para abater o que este pagamento cobrir.",+ "lines": "Itens",+ "addLine": "Adicionar item",+ "unitPrice": "Valor unitário",+ "taxRate": "Alíquota",+ "lineDescription": "Descrição",+ "linesOptional": "Detalhe o que entregou, para o cliente ver pelo que está a pagar.",+ "supplier": "Fornecedor",+ "paidOut": "Pago",+ "unit": "Unidade",+ "unitPlaceholder": "ex.: horas",+ "lineCount_one": "{{count}} linha",+ "lineCount_other": "{{count}} linhas",+ "supplierPlaceholder": "Selecione um fornecedor",+ "dueDateHintPayable": "Quando isto tem de ser pago."+ },+ "action": {+ "issue": "Emitir",+ "markPaid": "Marcar como recebida",+ "void": "Cancelar",+ "writeOff": "Dar baixa como perda",+ "reopen": "Reabrir",+ "unlink": "Desvincular",+ "link": "Vincular pagamento",+ "downloadPdf": "Baixar PDF",+ "share": "Compartilhar",+ "revokeLink": "Revogar link",+ "saveDraft": "Guardar rascunho"+ },+ "settings": {+ "title": "Configurações de cobrança",+ "description": "Como a cobrança funciona aqui, e como o documento aparece.",+ "preset": "Modo",+ "presetTracking": "Acompanhar recebimentos",+ "presetDocument": "Emitir documentos",+ "presetTrackingHint": "Emite a fatura noutro lado. Aqui acompanha quem lhe deve e se o dinheiro chegou.",+ "presetDocumentHint": "O Securo escreve a fatura que o cliente recebe. Precisa do que está a ser cobrado.",+ "numberPrefix": "Prefixo da numeração",+ "paymentTerms": "Prazo de pagamento (dias)",+ "issuerName": "Nome do seu negócio",+ "logoHint": "Vale para as cobranças emitidas de agora em diante. As já emitidas mantêm o logo que levaram.",+ "footerNote": "Rodapé",+ "saved": "Configurações salvas",+ "paymentDetails": "Dados para pagamento",+ "paymentDetailsHint": "Como o cliente paga você — chave Pix, IBAN, conta bancária. Aparece no documento.",+ "accentColor": "Cor de destaque",+ "issuer": "Dados do seu negócio",+ "issuerHint": "Aparece como remetente nas cobranças emitidas de agora em diante.",+ "legalName": "Razão social",+ "addressLabel": "Endereço",+ "labels": "Rótulos do documento",+ "labelsHint": "Renomeie como o documento chama cada campo.",+ "saveIssuer": "Salvar dados",+ "groupBehaviour": "Como a cobrança funciona",+ "groupDocument": "Como o documento aparece",+ "logo": "Logótipo",+ "logoUpload": "Carregar",+ "logoReplace": "Substituir",+ "logoRemove": "Remover logótipo",+ "logoFailed": "Não foi possível usar essa imagem."+ },+ "errors": {+ "generic": "Algo deu errado.",+ "lines_required": "Este modo exige itens na cobrança.",+ "due_before_issue": "O vencimento não pode ser antes da emissão.",+ "empty_total": "Uma cobrança sem valor não pode ser emitida.",+ "not_a_draft": "Só um rascunho pode ser emitido.",+ "not_open": "Só uma cobrança em aberto pode ser quitada.",+ "draft_not_voidable": "Exclua o rascunho em vez de cancelar.",+ "void_with_allocations": "Desvincule os pagamentos antes de cancelar.",+ "only_drafts_deletable": "Uma cobrança emitida nunca é excluída — cancele-a.",+ "issued_invoice_immutable": "Uma cobrança emitida não muda. Cancele e emita outra.",+ "over_allocation": "Isso é mais do que esta cobrança ainda deve.",+ "already_allocated": "Esta transação já está vinculada a esta cobrança.",+ "already_settled": "Esta cobrança já está totalmente quitada.",+ "currency_mismatch": "A transação está em outra moeda.",+ "transaction_not_found": "Transação não encontrada.",+ "payee_not_found": "Cliente não encontrado.",+ "terminal_status": "Esta cobrança não pode mais ser editada.",+ "not_uncollectible": "Só uma cobrança incobrável pode ser reaberta.",+ "amount_not_positive": "O valor deve ser maior que zero.",+ "allocation_not_found": "Vínculo não encontrado.",+ "draft_not_shareable": "Emita a cobrança antes de compartilhar.",+ "external_source_required": "Um documento importado precisa dizer de onde veio.",+ "payable_not_shareable": "Uma conta a pagar não pode ser compartilhada.",+ "discount_exceeds_total": "O desconto é maior do que o valor cobrado.",+ "no_document_filed": "Este documento foi emitido noutro lugar. Anexe o ficheiro recebido.",+ "already_imported": "Este documento já foi importado."+ },+ "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": {+ "noLines": "Esta cobrança não tem itens — ela registra o que é devido, e o documento foi emitido em outro lugar."+ },+ "tab": {+ "details": "Detalhes",+ "document": "Documentos"+ },+ "shareCopied": "Link copiado",+ "shareRevoked": "Link revogado",+ "shareActive": "Qualquer pessoa com este link vê a cobrança:",+ "shared": {+ "notFoundTitle": "Cobrança indisponível",+ "notFoundBody": "Este link não vale mais. Peça um novo a quem enviou."+ },+ "section": "Negócio",+ "emptyFiltered": "Nada corresponde a este filtro.",+ "detailsTitle": "Detalhes",+ "shareCopy": "Copiar link",+ "bucket": {+ "current": "A vencer",+ "d1_30": "1–30 dias",+ "d31_60": "31–60 dias",+ "d61_90": "61–90 dias",+ "d90_plus": "90+ dias"+ },+ "moreActions": "Mais ações",+ "allYears": "Todos os exercícios",+ "emptyYear": "Nenhuma cobrança emitida no {{year}}.",+ "showAllYears": "Ver todos os anos",+ "label": {+ "invoice": "Fatura",+ "billTo": "Cliente",+ "from": "Emitente",+ "description": "Descrição",+ "quantity": "Qtd",+ "unitPrice": "Valor unit.",+ "total": "Total",+ "paymentDetails": "Dados para pagamento",+ "notes": "Observações"+ },+ "editDraft": "Editar rascunho",+ "updated": "Cobrança atualizada",+ "editDraftDescription": "Um rascunho ainda muda. Depois de o cliente o ter, anule e emita outro.",+ "direction": {+ "receivable": "A receber",+ "payable": "A pagar"+ },+ "newPayable": "Nova conta a pagar",+ "newPayableDescription": "Registe o que um fornecedor está a cobrar, para nada ser pago com atraso ou duas vezes.",+ "emptyPayable": "Nenhuma conta a pagar ainda. Adicione uma para acompanhar o que você deve.",+ "noSupplier": "Sem fornecedor",+ "receivedDocument": "Documento recebido",+ "receivedDocumentHint": "Emitido pelo seu fornecedor. Exibido como registrado, não como algo que você enviou.",+ "fiscalYear": "Exercício {{year}}",+ "documents": {+ "title": "Documentos",+ "add": "Adicionar",+ "empty": "Ainda não há documentos anexados. A fatura, o documento fiscal e o recibo pertencem aqui.",+ "primaryHint": "Ao transferir esta fatura, é este ficheiro que é entregue",+ "makePrimary": "Usar como o documento",+ "remove": "Remover documento",+ "uploadFailed": "Não foi possível adicionar esse ficheiro.",+ "openOriginal": "Abrir o original",+ "cannotPreview": "Este ficheiro não pode ser pré-visualizado aqui. Abra-o para o ver.",+ "kind": {+ "bill": "Fatura",+ "fiscal": "Documento fiscal",+ "receipt": "Recibo",+ "contract": "Contrato",+ "other": "Outro"+ },+ "notOurs": "O documento foi emitido noutro lugar",+ "notOursHint": "Anexe o ficheiro que recebeu e será mostrado aqui, exatamente como chegou.",+ "ourPage": "Fatura",+ "rendered": "Gerada pelo Securo · {{date}}",+ "kindLabel": "Tipo de documento",+ "fromSystem": "De {{source}} · {{date}}",+ "fromUpload": "Carregado · {{date}}"+ },+ "draftSaved": "Rascunho guardado"},"collections": {"title": "Coleções",@@ -554,7 +796,10 @@"bulkAddTags": "Adicionar tags","bulkRemoveTags": "Remover tags","addTagsPlaceholder": "#tag…",- "clearOverride": "Limpar substituição"+ "clearOverride": "Limpar substituição",+ "invoiceBadge": "Cobrança {{number}}",+ "invoiceBadgeNoNumber": "Cobrança",+ "invoiceBadgeTooltip": "Esta transação quita uma cobrança. Abrir."},"accounts": {"title": "Contas",@@ -1445,7 +1690,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Outros países",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 1f2c3a51..9fc8e91a 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -129,8 +129,250 @@"aiAgents": "ИИ-агенты"},"invoices": {- "title": "Счета",- "comingNext": "Выставляйте счета клиентам и следите за тем, что оплачено, а что остаётся открытым. Это следующее, что будет сделано."+ "title": "Invoices",+ "subtitle": "Сколько вам должны клиенты и что уже поступило.",+ "new": "New invoice",+ "newDescription": "Выставьте клиенту счёт за то, что вы сделали, и следите за ним до поступления денег.",+ "empty": "Счетов пока нет. Создайте первый и начните следить за тем, что вам должны.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "По этому счёту пока ничего не поступило.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Выберите деньги, которыми оплачен этот счёт. Оставьте сумму пустой, чтобы зачесть столько, сколько поместится.",+ "noCandidates": "Нет входящих операций в этой валюте.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "Дата признания {{competence}} отличается от даты выставления {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Сумма"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Когда вы ждёте оплату. Ваш срок: {{days}} дн.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Оставьте пустым, чтобы зачесть столько, сколько покрывает этот платёж.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Распишите, что вы сделали, чтобы клиент видел, за что платит.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Единица",+ "unitPlaceholder": "напр. часы",+ "lineCount_one": "{{count}} строка",+ "lineCount_other": "{{count}} строк",+ "supplierPlaceholder": "Выберите поставщика",+ "dueDateHintPayable": "Когда это нужно оплатить."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Сохранить черновик"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Как здесь работает выставление счетов и как выглядит документ.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Счета вы выставляете в другом месте. Здесь следите, кто должен и дошли ли деньги.",+ "presetDocumentHint": "Securo пишет счёт, который получит клиент. Для этого нужно, за что вы выставляете.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Действует для счетов, выставленных с этого момента. Уже выставленные сохраняют свой логотип.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Как клиент вам платит — ключ Pix, IBAN, банковский счёт. Показывается на документе.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "Появляется как отправитель на каждом счёте, который вы выставите с этого момента.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Переименуйте то, как документ называет каждое поле.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Логотип",+ "logoUpload": "Загрузить",+ "logoReplace": "Заменить",+ "logoRemove": "Убрать логотип",+ "logoFailed": "Не удалось использовать это изображение."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Этот режим требует позиций.",+ "due_before_issue": "Срок оплаты не может быть раньше даты выставления.",+ "empty_total": "Счёт с нулевой суммой выставить нельзя.",+ "not_a_draft": "Выставить можно только черновик.",+ "not_open": "Оплатить можно только открытый счёт.",+ "draft_not_voidable": "Удалите черновик вместо того, чтобы аннулировать его.",+ "void_with_allocations": "Отвяжите платежи, прежде чем аннулировать этот счёт.",+ "only_drafts_deletable": "Выставленный счёт никогда не удаляют — аннулируйте его.",+ "issued_invoice_immutable": "Выставленный счёт нельзя изменить. Аннулируйте его и выставьте новый.",+ "over_allocation": "Это больше, чем по этому счёту ещё осталось.",+ "already_allocated": "Эта операция уже привязана к этому счёту.",+ "already_settled": "Этот счёт уже полностью оплачен.",+ "currency_mismatch": "Операция в другой валюте.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Этот счёт больше нельзя редактировать.",+ "not_uncollectible": "Возобновить можно только безнадёжный счёт.",+ "amount_not_positive": "Сумма должна быть больше нуля.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Выставьте счёт, прежде чем делиться им.",+ "external_source_required": "Импортированный документ должен указывать, откуда он.",+ "payable_not_shareable": "Полученный счёт нельзя опубликовать по ссылке.",+ "discount_exceeds_total": "Скидка больше выставленной суммы.",+ "no_document_filed": "Документ выпущен в другом месте. Прикрепите полученный файл.",+ "already_imported": "Этот документ уже импортирован."+ },+ "comingNext": "Выставляйте счета клиентам и следите за тем, что оплачено, а что остаётся открытым. Это следующее, что будет сделано.",+ "document": {+ "noLines": "У этого счёта нет позиций — он фиксирует долг, а документ выставлен в другом месте."+ },+ "tab": {+ "details": "Details",+ "document": "Документы"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Любой, у кого есть эта ссылка, может посмотреть счёт:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Эта ссылка больше не действует. Попросите у отправителя новую."+ },+ "section": "Business",+ "emptyFiltered": "Ничего не соответствует этому фильтру.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "В {{year}} ничего не выставлено.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Черновик ещё можно менять. Как только счёт у клиента — аннулируйте и выставьте новый.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Запишите, что выставил поставщик, чтобы ничего не оплатить с опозданием или дважды.",+ "emptyPayable": "Полученных счетов пока нет. Добавьте один, чтобы следить за тем, что вы должны.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "Его выставил ваш поставщик. Показан так, как записан, а не как отправленный вами.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Документы",+ "add": "Добавить",+ "empty": "Документов пока нет. Счёт, налоговый документ и квитанция хранятся здесь.",+ "primaryHint": "При скачивании этого счёта выдаётся именно этот файл",+ "makePrimary": "Сделать основным документом",+ "remove": "Удалить документ",+ "uploadFailed": "Не удалось добавить этот файл.",+ "openOriginal": "Открыть оригинал",+ "cannotPreview": "Этот файл нельзя просмотреть здесь. Откройте его, чтобы увидеть.",+ "kind": {+ "bill": "Счёт",+ "fiscal": "Налоговый документ",+ "receipt": "Квитанция",+ "contract": "Договор",+ "other": "Другое"+ },+ "notOurs": "Документ выпущен в другом месте",+ "notOursHint": "Прикрепите полученный файл — он будет показан здесь ровно в том виде, в каком пришёл.",+ "ourPage": "Счёт",+ "rendered": "Сформирована в Securo · {{date}}",+ "kindLabel": "Тип документа",+ "fromSystem": "Из {{source}} · {{date}}",+ "fromUpload": "Загружено · {{date}}"+ },+ "draftSaved": "Черновик сохранён"},"collections": {"title": "Коллекции",@@ -560,7 +802,10 @@"calendarNoActivity": "В этом месяце нет активности","calendarNoMovements": "Нет операций","calendarActualNet": "Фактический итог",- "calendarTransfersExcluded": "Переводы не учитываются как приход или расходы"+ "calendarTransfersExcluded": "Переводы не учитываются как приход или расходы",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Счета",@@ -1453,7 +1698,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Другие страны",diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex a25620f7..9e010efa 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -130,7 +130,249 @@},"invoices": {"title": "Faktúry",- "comingNext": "Fakturuj klientom a sleduj, čo už je zaplatené a čo je ešte otvorené. Toto je ďalšia funkcia, na ktorej sa pracuje."+ "subtitle": "Čo vám klienti dlžia a čo už prišlo.",+ "new": "Nová faktúra",+ "newDescription": "Vyfakturujte klientovi to, čo ste dodali, a sledujte ju až do zaplatenia.",+ "empty": "Zatiaľ žiadne faktúry. Vytvorte prvú a začnite sledovať, čo vám dlžia.",+ "noNumber": "Koncept",+ "noClient": "Bez klienta",+ "draftTitle": "Koncept",+ "created": "Faktúra vytvorená",+ "issued": "Faktúra vystavená",+ "voided": "Faktúra stornovaná",+ "writtenOff": "Označené ako nevymožiteľné",+ "reopened": "Faktúra znovu otvorená",+ "deleted": "Koncept zmazaný",+ "linked": "Platba priradená",+ "unlinked": "Priradenie zrušené",+ "backToList": "Späť na faktúry",+ "payments": "Platby",+ "noPayments": "Na túto faktúru zatiaľ nič neprišlo.",+ "linkedPayment": "Priradená platba",+ "linkedManually": "Priradené ručne",+ "linkedAutomatically": "Spárované automaticky",+ "linkDescription": "Vyberte platbu, ktorá vyrovnala túto faktúru. Sumu nechajte prázdnu, aby sa použilo, koľko sa zmestí.",+ "noCandidates": "Žiadne prichádzajúce transakcie v tejto mene.",+ "daysLate": "{{count}} d po splatnosti",+ "competenceDiverges": "Dátum zdaniteľného plnenia {{competence}} sa líši od dátumu vystavenia {{issue}}",+ "state": {+ "draft": "Koncept",+ "open": "Otvorená",+ "partial": "Čiastočne uhradená",+ "paid": "Uhradená",+ "overdue": "Po splatnosti",+ "void": "Stornovaná",+ "uncollectible": "Nevymožiteľná"+ },+ "filter": {+ "all": "Všetky",+ "open": "Otvorené",+ "overdue": "Po splatnosti",+ "paid": "Uhradené",+ "draft": "Koncepty"+ },+ "column": {+ "number": "Číslo",+ "client": "Klient",+ "due": "Splatnosť",+ "total": "Celkom",+ "balance": "Zostatok",+ "state": "Stav",+ "quantity": "Množstvo",+ "supplier": "Dodávateľ",+ "amount": "Suma"+ },+ "summary": {+ "outstanding": "Nezaplatené",+ "overdue": "Po splatnosti",+ "receivedThisMonth": "Prijaté tento mesiac",+ "upcoming": "Čoskoro splatné",+ "aging": "Podľa veku",+ "nothingDue": "Nič nezaplatené.",+ "overdueCount_one": "na {{count}} faktúre",+ "overdueCount_other": "na {{count}} faktúrach",+ "owed": "Dlžné",+ "paidThisMonth": "Zaplatené tento mesiac"+ },+ "field": {+ "client": "Klient",+ "clientPlaceholder": "Vyberte klienta",+ "total": "Suma",+ "dueDate": "Dátum splatnosti",+ "dueDateHint": "Kedy očakávate platbu. Vaša lehota: {{days}} dní.",+ "notes": "Poznámky",+ "paid": "Prijaté",+ "amountToApply": "Suma na použitie",+ "amountHint": "Nechajte prázdne, aby sa vyrovnalo toľko, koľko táto platba pokryje.",+ "lines": "Položky",+ "addLine": "Pridať položku",+ "unitPrice": "Jednotková cena",+ "taxRate": "Sadzba dane",+ "lineDescription": "Popis",+ "linesOptional": "Rozpíšte, čo ste dodali, aby klient videl, za čo platí.",+ "supplier": "Dodávateľ",+ "paidOut": "Vyplatené",+ "unit": "Jednotka",+ "unitPlaceholder": "napr. hodiny",+ "lineCount_one": "{{count}} položka",+ "lineCount_other": "{{count}} položiek",+ "supplierPlaceholder": "Vyberte dodávateľa",+ "dueDateHintPayable": "Dokedy to treba zaplatiť."+ },+ "action": {+ "issue": "Vystaviť",+ "markPaid": "Označiť ako uhradené",+ "void": "Stornovať",+ "writeOff": "Odpísať",+ "reopen": "Znovu otvoriť",+ "unlink": "Zrušiť priradenie",+ "link": "Priradiť platbu",+ "downloadPdf": "Stiahnuť PDF",+ "share": "Zdieľať odkaz",+ "revokeLink": "Zrušiť odkaz",+ "saveDraft": "Uložiť ako koncept"+ },+ "settings": {+ "title": "Nastavenia faktúr",+ "description": "Ako tu funguje fakturácia a ako vyzerá dokument.",+ "preset": "Režim",+ "presetTracking": "Sledovať platby",+ "presetDocument": "Vystavovať dokumenty",+ "presetTrackingHint": "Fakturujete inde. Tu sledujete, kto vám dlží a či peniaze prišli.",+ "presetDocumentHint": "Securo píše faktúru, ktorú klient dostane. Potrebuje vedieť, čo účtujete.",+ "numberPrefix": "Predpona čísla",+ "paymentTerms": "Splatnosť (dni)",+ "issuerName": "Názov vašej firmy",+ "logoHint": "Platí pre faktúry vystavené odteraz. Už vystavené dokumenty si nechávajú logo, ktoré niesli.",+ "footerNote": "Poznámka v päte",+ "saved": "Nastavenia uložené",+ "paymentDetails": "Platobné údaje",+ "paymentDetailsHint": "Ako vám klient zaplatí — Pix kľúč, IBAN, bankový účet. Zobrazí sa na dokumente.",+ "accentColor": "Akcentová farba",+ "issuer": "Údaje vašej firmy",+ "issuerHint": "Objaví sa ako odosielateľ na každej faktúre, ktorú odteraz vystavíte.",+ "legalName": "Obchodné meno",+ "addressLabel": "Adresa",+ "labels": "Popisy dokumentu",+ "labelsHint": "Premenujte, ako dokument nazýva jednotlivé polia.",+ "saveIssuer": "Uložiť údaje",+ "groupBehaviour": "Ako funguje fakturácia",+ "groupDocument": "Ako vyzerá dokument",+ "logo": "Logo",+ "logoUpload": "Nahrať",+ "logoReplace": "Nahradiť",+ "logoRemove": "Odstrániť logo",+ "logoFailed": "Tento obrázok sa nepodarilo použiť."+ },+ "errors": {+ "generic": "Niečo sa pokazilo.",+ "lines_required": "Tento režim vyžaduje položky.",+ "due_before_issue": "Dátum splatnosti nemôže predchádzať dátumu vystavenia.",+ "empty_total": "Faktúru s nulovou hodnotou nemožno vystaviť.",+ "not_a_draft": "Vystaviť možno len koncept.",+ "not_open": "Vyrovnať možno len otvorenú faktúru.",+ "draft_not_voidable": "Koncept zmažte, nestornujte ho.",+ "void_with_allocations": "Pred stornovaním zrušte priradenie platieb.",+ "only_drafts_deletable": "Vystavená faktúra sa nikdy nemaže — stornujte ju.",+ "issued_invoice_immutable": "Vystavenú faktúru nemožno meniť. Stornujte ju a vystavte novú.",+ "over_allocation": "To je viac, než táto faktúra ešte dlží.",+ "already_allocated": "Táto transakcia je už k tejto faktúre priradená.",+ "already_settled": "Táto faktúra je už úplne vyrovnaná.",+ "currency_mismatch": "Transakcia je v inej mene.",+ "transaction_not_found": "Transakcia sa nenašla.",+ "payee_not_found": "Klient sa nenašiel.",+ "terminal_status": "Túto faktúru už nemožno upravovať.",+ "not_uncollectible": "Znovu otvoriť možno len nevymožiteľnú faktúru.",+ "amount_not_positive": "Suma musí byť väčšia ako nula.",+ "allocation_not_found": "Priradenie platby sa nenašlo.",+ "draft_not_shareable": "Pred zdieľaním faktúru vystavte.",+ "external_source_required": "Importovaný dokument musí uviesť, odkiaľ pochádza.",+ "payable_not_shareable": "Prijatú faktúru nemožno zdieľať.",+ "discount_exceeds_total": "Zľava je vyššia než účtovaná suma.",+ "no_document_filed": "Tento dokument bol vystavený inde. Priložte prijatý súbor.",+ "already_imported": "Tento dokument už bol importovaný."+ },+ "comingNext": "Fakturujte klientom a majte prehľad o tom, čo je zaplatené a čo ešte otvorené. Toto sa práve stavia.",+ "document": {+ "noLines": "Táto faktúra nemá položky — zaznamenáva, čo sa dlží, a dokument bol vystavený inde."+ },+ "tab": {+ "details": "Detaily",+ "document": "Dokumenty"+ },+ "shareCopied": "Odkaz skopírovaný",+ "shareRevoked": "Odkaz zrušený",+ "shareActive": "Ktokoľvek s týmto odkazom si môže faktúru pozrieť:",+ "shared": {+ "notFoundTitle": "Faktúra nie je dostupná",+ "notFoundBody": "Tento odkaz už neplatí. Vyžiadajte si od odosielateľa nový."+ },+ "section": "Firma",+ "emptyFiltered": "Tomuto filtru nič nezodpovedá.",+ "detailsTitle": "Detaily",+ "shareCopy": "Kopírovať odkaz",+ "bucket": {+ "current": "Ešte nesplatné",+ "d1_30": "1–30 dní po splatnosti",+ "d31_60": "31–60 dní po splatnosti",+ "d61_90": "61–90 dní po splatnosti",+ "d90_plus": "90+ dní po splatnosti"+ },+ "moreActions": "Ďalšie akcie",+ "allYears": "Všetky roky",+ "emptyYear": "V roku {{year}} nebolo nič vystavené.",+ "showAllYears": "Zobraziť všetky roky",+ "label": {+ "invoice": "Faktúra",+ "billTo": "Odberateľ",+ "from": "Dodávateľ",+ "description": "Popis",+ "quantity": "Množ.",+ "unitPrice": "Jedn. cena",+ "total": "Celkom",+ "paymentDetails": "Platobné údaje",+ "notes": "Poznámky"+ },+ "editDraft": "Upraviť koncept",+ "updated": "Faktúra aktualizovaná",+ "editDraftDescription": "Koncept sa dá ešte meniť. Keď ho klient dostane, stornujte ho a vystavte nový.",+ "direction": {+ "receivable": "Pohľadávka",+ "payable": "Záväzok"+ },+ "newPayable": "Nová prijatá faktúra",+ "newPayableDescription": "Zaznamenajte, čo vám dodávateľ účtuje, aby sa nič nezaplatilo neskoro ani dvakrát.",+ "emptyPayable": "Zatiaľ žiadne prijaté faktúry. Pridajte jednu a sledujte, čo dlžíte.",+ "noSupplier": "Bez dodávateľa",+ "receivedDocument": "Prijatý dokument",+ "receivedDocumentHint": "Vystavil ho váš dodávateľ. Zobrazuje sa tak, ako bol zaznamenaný, nie ako niečo, čo ste poslali.",+ "fiscalYear": "Rok {{year}}",+ "documents": {+ "title": "Dokumenty",+ "add": "Pridať",+ "empty": "Zatiaľ žiadne dokumenty. Patrí sem faktúra, daňový doklad aj potvrdenie o platbe.",+ "primaryHint": "Pri stiahnutí tejto faktúry sa odovzdá tento súbor",+ "makePrimary": "Použiť ako dokument",+ "remove": "Odstrániť dokument",+ "uploadFailed": "Tento súbor sa nepodarilo pridať.",+ "openOriginal": "Otvoriť originál",+ "cannotPreview": "Tento súbor tu nemožno zobraziť. Otvorte ho.",+ "kind": {+ "bill": "Faktúra",+ "fiscal": "Daňový doklad",+ "receipt": "Potvrdenie",+ "contract": "Zmluva",+ "other": "Iné"+ },+ "notOurs": "Dokument bol vystavený inde",+ "notOursHint": "Priložte prijatý súbor a zobrazí sa tu presne tak, ako prišiel.",+ "ourPage": "Faktúra",+ "rendered": "Vygenerované Securom · {{date}}",+ "kindLabel": "Typ dokumentu",+ "fromSystem": "Z {{source}} · {{date}}",+ "fromUpload": "Nahrané · {{date}}"+ },+ "draftSaved": "Koncept uložený"},"collections": {"title": "Zbierky",@@ -598,7 +840,10 @@"calendarNoActivity": "Tento mesiac žiadna aktivita","calendarNoMovements": "Žiadne pohyby","calendarActualNet": "Skutočné netto",- "calendarTransfersExcluded": "Prevody sa nepočítajú ako príjem ani výdavok"+ "calendarTransfersExcluded": "Prevody sa nepočítajú ako príjem ani výdavok",+ "invoiceBadge": "Faktúra {{number}}",+ "invoiceBadgeNoNumber": "Faktúra",+ "invoiceBadgeTooltip": "Táto transakcia vyrovnáva faktúru. Otvorte ju."},"accounts": {"title": "Účty",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 1a31367f..dd71c4c5 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -129,8 +129,250 @@"aiAgents": "ШІ-агенти"},"invoices": {- "title": "Рахунки",- "comingNext": "Виставляйте рахунки клієнтам і стежте за тим, що оплачено, а що залишається відкритим. Це наступне, що буде зроблено."+ "title": "Invoices",+ "subtitle": "Скільки вам винні клієнти і що вже надійшло.",+ "new": "New invoice",+ "newDescription": "Виставте клієнту рахунок за те, що ви зробили, і стежте за ним до надходження грошей.",+ "empty": "Рахунків поки немає. Створіть перший і почніть стежити за тим, що вам винні.",+ "noNumber": "Draft",+ "noClient": "No client",+ "draftTitle": "Draft",+ "created": "Invoice created",+ "issued": "Invoice issued",+ "voided": "Invoice voided",+ "writtenOff": "Marked as uncollectible",+ "reopened": "Invoice reopened",+ "deleted": "Draft deleted",+ "linked": "Payment linked",+ "unlinked": "Payment unlinked",+ "backToList": "Back to invoices",+ "payments": "Payments",+ "noPayments": "За цим рахунком поки нічого не надійшло.",+ "linkedPayment": "Linked payment",+ "linkedManually": "Linked manually",+ "linkedAutomatically": "Matched automatically",+ "linkDescription": "Виберіть гроші, якими оплачено цей рахунок. Залиште суму порожньою, щоб зарахувати стільки, скільки поміститься.",+ "noCandidates": "Немає вхідних операцій у цій валюті.",+ "daysLate": "{{count}}d late",+ "competenceDiverges": "Дата визнання {{competence}} відрізняється від дати виставлення {{issue}}",+ "state": {+ "draft": "Draft",+ "open": "Open",+ "partial": "Partly paid",+ "paid": "Paid",+ "overdue": "Overdue",+ "void": "Void",+ "uncollectible": "Uncollectible"+ },+ "filter": {+ "all": "All",+ "open": "Open",+ "overdue": "Overdue",+ "paid": "Paid",+ "draft": "Drafts"+ },+ "column": {+ "number": "Number",+ "client": "Client",+ "due": "Due",+ "total": "Total",+ "balance": "Balance",+ "state": "Status",+ "quantity": "Quantity",+ "supplier": "Supplier",+ "amount": "Сума"+ },+ "summary": {+ "outstanding": "Outstanding",+ "overdue": "Overdue",+ "receivedThisMonth": "Received this month",+ "upcoming": "Due soon",+ "aging": "By age",+ "nothingDue": "Nothing outstanding.",+ "overdueCount_one": "on {{count}} invoice",+ "overdueCount_other": "on {{count}} invoices",+ "owed": "Owed",+ "paidThisMonth": "Paid this month"+ },+ "field": {+ "client": "Client",+ "clientPlaceholder": "Select a client",+ "total": "Amount",+ "dueDate": "Due date",+ "dueDateHint": "Коли ви очікуєте оплату. Ваш строк: {{days}} дн.",+ "notes": "Notes",+ "paid": "Received",+ "amountToApply": "Amount to apply",+ "amountHint": "Залиште порожнім, щоб зарахувати стільки, скільки покриває цей платіж.",+ "lines": "Line items",+ "addLine": "Add line",+ "unitPrice": "Unit price",+ "taxRate": "Tax rate",+ "lineDescription": "Description",+ "linesOptional": "Розпишіть, що ви зробили, щоб клієнт бачив, за що платить.",+ "supplier": "Supplier",+ "paidOut": "Paid out",+ "unit": "Одиниця",+ "unitPlaceholder": "напр. години",+ "lineCount_one": "{{count}} рядок",+ "lineCount_other": "{{count}} рядків",+ "supplierPlaceholder": "Виберіть постачальника",+ "dueDateHintPayable": "Коли це потрібно сплатити."+ },+ "action": {+ "issue": "Issue",+ "markPaid": "Mark as paid",+ "void": "Void",+ "writeOff": "Write off",+ "reopen": "Reopen",+ "unlink": "Unlink",+ "link": "Link payment",+ "downloadPdf": "Download PDF",+ "share": "Share link",+ "revokeLink": "Revoke link",+ "saveDraft": "Зберегти чернетку"+ },+ "settings": {+ "title": "Invoice settings",+ "description": "Як тут працює виставлення рахунків і який вигляд має документ.",+ "preset": "Mode",+ "presetTracking": "Track payments",+ "presetDocument": "Issue documents",+ "presetTrackingHint": "Рахунки ви виставляєте деінде. Тут стежите, хто винен і чи надійшли гроші.",+ "presetDocumentHint": "Securo пише рахунок, який отримає клієнт. Для цього потрібно, за що ви виставляєте.",+ "numberPrefix": "Number prefix",+ "paymentTerms": "Payment terms (days)",+ "issuerName": "Your business name",+ "logoHint": "Діє для рахунків, виставлених відтепер. Уже виставлені зберігають свій логотип.",+ "footerNote": "Footer note",+ "saved": "Settings saved",+ "paymentDetails": "Payment details",+ "paymentDetailsHint": "Як клієнт вам платить — ключ Pix, IBAN, банківський рахунок. Показується на документі.",+ "accentColor": "Accent colour",+ "issuer": "Your business details",+ "issuerHint": "З'являється як відправник на кожному рахунку, який ви виставите відтепер.",+ "legalName": "Legal name",+ "addressLabel": "Address",+ "labels": "Document labels",+ "labelsHint": "Перейменуйте те, як документ називає кожне поле.",+ "saveIssuer": "Save details",+ "groupBehaviour": "How invoicing behaves",+ "groupDocument": "How the document looks",+ "logo": "Логотип",+ "logoUpload": "Завантажити",+ "logoReplace": "Замінити",+ "logoRemove": "Прибрати логотип",+ "logoFailed": "Не вдалося використати це зображення."+ },+ "errors": {+ "generic": "Something went wrong.",+ "lines_required": "Цей режим потребує позицій.",+ "due_before_issue": "Термін оплати не може передувати даті виставлення.",+ "empty_total": "Рахунок із нульовою сумою виставити не можна.",+ "not_a_draft": "Виставити можна лише чернетку.",+ "not_open": "Оплатити можна лише відкритий рахунок.",+ "draft_not_voidable": "Видаліть чернетку замість того, щоб анулювати її.",+ "void_with_allocations": "Відв'яжіть платежі, перш ніж анулювати цей рахунок.",+ "only_drafts_deletable": "Виставлений рахунок ніколи не видаляють — анулюйте його.",+ "issued_invoice_immutable": "Виставлений рахунок не можна змінити. Анулюйте його і виставте новий.",+ "over_allocation": "Це більше, ніж за цим рахунком ще залишилося.",+ "already_allocated": "Ця операція вже прив'язана до цього рахунку.",+ "already_settled": "Цей рахунок уже повністю оплачено.",+ "currency_mismatch": "Операція в іншій валюті.",+ "transaction_not_found": "Transaction not found.",+ "payee_not_found": "Client not found.",+ "terminal_status": "Цей рахунок більше не можна редагувати.",+ "not_uncollectible": "Поновити можна лише безнадійний рахунок.",+ "amount_not_positive": "Сума має бути більшою за нуль.",+ "allocation_not_found": "Payment link not found.",+ "draft_not_shareable": "Виставте рахунок, перш ніж ділитися ним.",+ "external_source_required": "Імпортований документ має вказувати, звідки він.",+ "payable_not_shareable": "Отриманий рахунок не можна поширити за посиланням.",+ "discount_exceeds_total": "Знижка більша за виставлену суму.",+ "no_document_filed": "Документ виписано в іншому місці. Прикріпіть отриманий файл.",+ "already_imported": "Цей документ уже імпортовано."+ },+ "comingNext": "Виставляйте рахунки клієнтам і стежте за тим, що оплачено, а що залишається відкритим. Це наступне, що буде зроблено.",+ "document": {+ "noLines": "У цього рахунку немає позицій — він фіксує борг, а документ виставлено в іншому місці."+ },+ "tab": {+ "details": "Details",+ "document": "Документи"+ },+ "shareCopied": "Link copied",+ "shareRevoked": "Link revoked",+ "shareActive": "Будь-хто з цим посиланням може переглянути рахунок:",+ "shared": {+ "notFoundTitle": "Invoice not available",+ "notFoundBody": "Це посилання більше не дійсне. Попросіть у відправника нове."+ },+ "section": "Business",+ "emptyFiltered": "Ніщо не відповідає цьому фільтру.",+ "detailsTitle": "Details",+ "shareCopy": "Copy link",+ "bucket": {+ "current": "Not due yet",+ "d1_30": "1–30 days late",+ "d31_60": "31–60 days late",+ "d61_90": "61–90 days late",+ "d90_plus": "90+ days late"+ },+ "moreActions": "More actions",+ "allYears": "All years",+ "emptyYear": "У {{year}} нічого не виставлено.",+ "showAllYears": "Show all years",+ "label": {+ "invoice": "Invoice",+ "billTo": "Bill to",+ "from": "From",+ "description": "Description",+ "quantity": "Qty",+ "unitPrice": "Unit price",+ "total": "Total",+ "paymentDetails": "Payment details",+ "notes": "Notes"+ },+ "editDraft": "Edit draft",+ "updated": "Invoice updated",+ "editDraftDescription": "Чернетку ще можна змінити. Щойно рахунок у клієнта — анулюйте і виставте новий.",+ "direction": {+ "receivable": "Receivable",+ "payable": "Payable"+ },+ "newPayable": "New bill",+ "newPayableDescription": "Запишіть, що виставив постачальник, щоб нічого не сплатити із запізненням або двічі.",+ "emptyPayable": "Отриманих рахунків поки немає. Додайте один, щоб стежити за тим, що ви винні.",+ "noSupplier": "No supplier",+ "receivedDocument": "Received document",+ "receivedDocumentHint": "Його виставив ваш постачальник. Показано так, як записано, а не як щось, що ви надіслали.",+ "fiscalYear": "FY {{year}}",+ "documents": {+ "title": "Документи",+ "add": "Додати",+ "empty": "Документів ще немає. Рахунок, податковий документ і квитанція зберігаються тут.",+ "primaryHint": "Під час завантаження цього рахунка видається саме цей файл",+ "makePrimary": "Зробити основним документом",+ "remove": "Видалити документ",+ "uploadFailed": "Не вдалося додати цей файл.",+ "openOriginal": "Відкрити оригінал",+ "cannotPreview": "Цей файл не можна переглянути тут. Відкрийте його, щоб побачити.",+ "kind": {+ "bill": "Рахунок",+ "fiscal": "Податковий документ",+ "receipt": "Квитанція",+ "contract": "Договір",+ "other": "Інше"+ },+ "notOurs": "Документ виписано в іншому місці",+ "notOursHint": "Прикріпіть отриманий файл — його буде показано тут саме в тому вигляді, у якому він надійшов.",+ "ourPage": "Рахунок",+ "rendered": "Сформована в Securo · {{date}}",+ "kindLabel": "Тип документа",+ "fromSystem": "Із {{source}} · {{date}}",+ "fromUpload": "Завантажено · {{date}}"+ },+ "draftSaved": "Чернетку збережено"},"collections": {"title": "Колекції",@@ -560,7 +802,10 @@"calendarNoActivity": "Цього місяця немає активності","calendarNoMovements": "Немає операцій","calendarActualNet": "Фактичний підсумок",- "calendarTransfersExcluded": "Перекази не враховуються як надходження чи витрати"+ "calendarTransfersExcluded": "Перекази не враховуються як надходження чи витрати",+ "invoiceBadge": "Invoice {{number}}",+ "invoiceBadgeNoNumber": "Invoice",+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."},"accounts": {"title": "Рахунки",@@ -1453,7 +1698,7 @@"ph_tin": "TIN","vn_mst": "MST","sg_uen": "UEN",- "az_voen": "VÖEN",+ "az_voen": "VÖEN","uscc": "USCC"},"otherCountries": "Інші країни",diff --git a/frontend/src/pages/invoice-detail.tsx b/frontend/src/pages/invoice-detail.tsxnew file mode 100644index 00000000..799e77dd--- /dev/null+++ b/frontend/src/pages/invoice-detail.tsx@@ -0,0 +1,937 @@+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useNavigate, useParams } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import {+ ArrowLeft, Ban, Check, CheckCircle2, CircleSlash, Copy, Download, Link2,+ MoreHorizontal, Pencil, RotateCcw, Send, Share2, Trash2, Unlink,+} from 'lucide-react'+import { toast } from 'sonner'++import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import { PageHeader } from '@/components/page-header'+import {+ IconAction,+ SectionCard,+ SectionHeader,+ Segmented,+ StateBadge,+} from '@/components/invoice-ui'+import { InvoiceDocumentView } from '@/components/invoice-document'+import { InvoiceDocumentBrowser } from '@/components/invoice-documents'+import { InvoiceLineEditor } from '@/components/invoice-line-editor'+import type { Invoice, InvoiceDirection, InvoiceLineInput } from '@/types'+import { cn } from '@/lib/utils'+import { formatCurrency } from '@/lib/format'+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'+import { usePrivacyMode } from '@/hooks/use-privacy-mode'+import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'+import {+ invoices as invoicesApi,+ payees as payeesApi,+ transactions as transactionsApi,+} from '@/lib/api'+import {+ allocationOrigin,+ availableActions,+ customFieldDefs,+ displayNumber,+ invoiceErrorKey,+ linesTotal,+} from '@/lib/invoice-utils'++/**+ * One invoice: what is owed, the money bound to it, and the document.+ *+ * The tab split is the point. "Details" is the operator's view — the+ * ledger side, where money gets linked. "Document" is what the client+ * receives, rendered from the same structure the PDF is. Mixing the two+ * on one screen is what made the first version feel like neither.+ */+type Tab = 'details' | 'document'++export default function InvoiceDetailPage() {+ const { t } = useTranslation()+ const { id = '' } = useParams()+ const navigate = useNavigate()+ const queryClient = useQueryClient()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const { mask } = usePrivacyMode()+ const { user } = useAuth()+ const { canWrite } = useWorkspace()+ const fallbackCurrency = user?.preferences?.currency_display ?? 'USD'++ const [linkOpen, setLinkOpen] = useState(false)+ const [editOpen, setEditOpen] = useState(false)+ const [tab, setTab] = useState<Tab>('details')+ const [copied, setCopied] = useState(false)++ const { data: invoice, isLoading } = useQuery({+ queryKey: ['invoice', id],+ queryFn: () => invoicesApi.get(id),+ enabled: Boolean(id),+ })+ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ })+ // Only when the tab is open: it resolves the snapshot and builds the+ // whole page server-side, and the ledger view has no use for any of it.+ // Fetched here rather than only inside the Documents section: the+ // header has to know whether a real document exists before it offers+ // to download one. Same query key as the section, so this is one+ // request shared through the cache, not two.+ const { data: attachments = [] } = useQuery({+ queryKey: ['invoice-attachments', id],+ queryFn: () => invoicesApi.attachments.list(id!),+ enabled: Boolean(id),+ })+ const hasFiledDocument = attachments.some((a) => a.is_primary)++ const { data: documentPayload } = useQuery({+ queryKey: ['invoice-document', id],+ queryFn: () => invoicesApi.document(id),+ enabled: Boolean(id) && tab === 'document',+ })++ const refresh = () => {+ void queryClient.invalidateQueries({ queryKey: ['invoice', id] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-document', id] })+ void queryClient.invalidateQueries({ queryKey: ['invoices'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-summary'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-facets'] })+ }++ const onError = (error: unknown) => {+ const key = invoiceErrorKey(error)+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ }++ const decision = (run: () => Promise<unknown>, successKey: string) => ({+ mutationFn: run,+ onSuccess: () => {+ toast.success(t(successKey))+ refresh()+ },+ onError,+ })++ const issueMutation = useMutation(decision(() => invoicesApi.issue(id), 'invoices.issued'))+ const voidMutation = useMutation(decision(() => invoicesApi.void(id), 'invoices.voided'))+ const writeOffMutation = useMutation(+ decision(() => invoicesApi.writeOff(id), 'invoices.writtenOff'),+ )+ const reopenMutation = useMutation(decision(() => invoicesApi.reopen(id), 'invoices.reopened'))+ const deleteMutation = useMutation({+ mutationFn: () => invoicesApi.remove(id),+ onSuccess: () => {+ toast.success(t('invoices.deleted'))+ refresh()+ navigate('/invoices')+ },+ onError,+ })+ const unlinkMutation = useMutation({+ mutationFn: (allocationId: string) => invoicesApi.unallocate(id, allocationId),+ onSuccess: () => {+ toast.success(t('invoices.unlinked'))+ refresh()+ },+ onError,+ })++ // Fetched as a blob rather than opened as a link: the PDF route needs+ // the auth and workspace headers the axios interceptor adds, which a+ // plain anchor would not carry.+ const downloadMutation = useMutation({+ mutationFn: async () => {+ const blob = await invoicesApi.pdf(id)+ const url = URL.createObjectURL(blob)+ const anchor = window.document.createElement('a')+ anchor.href = url+ anchor.download = `${invoice?.number ?? 'invoice'}.pdf`+ anchor.click()+ URL.revokeObjectURL(url)+ },+ onError,+ })++ const shareMutation = useMutation({+ mutationFn: () => invoicesApi.share(id),+ onSuccess: async (link) => {+ const url = `${window.location.origin}${link.path}`+ try {+ await navigator.clipboard.writeText(url)+ setCopied(true)+ setTimeout(() => setCopied(false), 2500)+ toast.success(t('invoices.shareCopied'))+ } catch {+ // A blocked clipboard is not a failed share — the link exists.+ toast.success(url)+ }+ refresh()+ },+ onError,+ })++ const unshareMutation = useMutation({+ mutationFn: () => invoicesApi.unshare(id),+ onSuccess: () => {+ toast.success(t('invoices.shareRevoked'))+ refresh()+ },+ onError,+ })++ if (isLoading || !invoice) {+ return (+ <div>+ <Skeleton className="h-4 w-28 mb-6" />+ <Skeleton className="h-40 w-full rounded-xl" />+ </div>+ )+ }++ const actions = availableActions(invoice)+ const currency = invoice.currency || fallbackCurrency+ const money = (value: string | number | null | undefined) =>+ mask(formatCurrency(Number(value ?? 0), currency, locale))+ const showDate = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)+ const number = displayNumber(invoice, settings?.number_prefix)+ const customFields = customFieldDefs(settings?.template)+ .map((def) => ({ ...def, value: invoice.custom_fields?.[def.key] }))+ .filter((field): field is typeof field & { value: string } => Boolean(field.value))+ const shareUrl = invoice.share_token+ ? `${window.location.origin}/i/${invoice.share_token}`+ : null++ return (+ <div>+ <button+ onClick={() => navigate('/invoices')}+ className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors mb-3"+ >+ <ArrowLeft className="h-3.5 w-3.5" />+ {t('invoices.backToList')}+ </button>++ <PageHeader+ section={+ invoice.payee?.name ??+ t(invoice.direction === 'payable' ? 'invoices.noSupplier' : 'invoices.noClient')+ }+ title={number ?? t('invoices.draftTitle')}+ action={+ canWrite ? (+ <div className="flex flex-wrap items-center gap-2">+ {actions.canEdit && (+ <Button+ size="sm"+ variant="outline"+ onClick={() => setEditOpen(true)}+ data-testid="invoice-edit"+ >+ <Pencil className="h-4 w-4 mr-1.5" />+ {t('common.edit')}+ </Button>+ )}+ {actions.canIssue && (+ <Button size="sm" onClick={() => issueMutation.mutate()} data-testid="invoice-issue">+ <Send className="h-4 w-4 mr-1.5" />+ {t('invoices.action.issue')}+ </Button>+ )}+ {actions.canAllocate && (+ <Button size="sm" onClick={() => setLinkOpen(true)} data-testid="invoice-link-payment">+ <Link2 className="h-4 w-4 mr-1.5" />+ {t('invoices.action.markPaid')}+ </Button>+ )}+ {invoice.status !== 'draft' && (+ <>+ {/* Downloading an imported invoice with nothing filed+ would hand over a page we drew for a document+ somebody else issued — the same invention the+ Document tab refuses to make. Nothing to download+ until the real file arrives. */}+ {(invoice.origin !== 'imported' || hasFiledDocument) && (+ <Button+ size="sm"+ variant="outline"+ onClick={() => downloadMutation.mutate()}+ disabled={downloadMutation.isPending}+ data-testid="invoice-download-pdf"+ >+ <Download className="h-4 w-4 mr-1.5" />+ {t('invoices.action.downloadPdf')}+ </Button>+ )}+ {/* Sharing is for sending your invoice to your client.+ A bill you received belongs to your supplier and has+ nobody to be sent to. */}+ {invoice.direction === 'receivable' && (+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ invoice.share_token ? unshareMutation.mutate() : shareMutation.mutate()+ }+ data-testid={invoice.share_token ? 'invoice-unshare' : 'invoice-share'}+ >+ {copied ? (+ <Check className="h-4 w-4 mr-1.5" />+ ) : (+ <Share2 className="h-4 w-4 mr-1.5" />+ )}+ {invoice.share_token+ ? t('invoices.action.revokeLink')+ : t('invoices.action.share')}+ </Button>+ )}+ </>+ )}+ {/* The rare and irreversible decisions live behind an+ overflow menu, with words. Two bare icons side by side+ were indistinguishable, and giving "void" the same+ weight as "mark as paid" is how someone voids by+ reflex. */}+ {(actions.canWriteOff ||+ actions.canReopen ||+ actions.canVoid ||+ actions.canDelete) && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ aria-label={t('invoices.moreActions')}+ data-testid="invoice-more-actions"+ className="inline-flex h-8 w-8 items-center justify-center rounded-md border border-border/80 bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ >+ <MoreHorizontal className="h-4 w-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-[220px] p-1 bg-card border border-border rounded-xl shadow-md"+ >+ {actions.canWriteOff && (+ <DropdownMenuItem+ onClick={() => writeOffMutation.mutate()}+ data-testid="invoice-writeoff"+ className="gap-2 text-sm"+ >+ <Ban className="h-4 w-4 text-muted-foreground" />+ {t('invoices.action.writeOff')}+ </DropdownMenuItem>+ )}+ {actions.canReopen && (+ <DropdownMenuItem+ onClick={() => reopenMutation.mutate()}+ data-testid="invoice-reopen"+ className="gap-2 text-sm"+ >+ <RotateCcw className="h-4 w-4 text-muted-foreground" />+ {t('invoices.action.reopen')}+ </DropdownMenuItem>+ )}+ {actions.canVoid && (+ <DropdownMenuItem+ onClick={() => voidMutation.mutate()}+ data-testid="invoice-void"+ className="gap-2 text-sm text-destructive focus:text-destructive"+ >+ <CircleSlash className="h-4 w-4" />+ {t('invoices.action.void')}+ </DropdownMenuItem>+ )}+ {actions.canDelete && (+ <DropdownMenuItem+ onClick={() => deleteMutation.mutate()}+ data-testid="invoice-delete"+ className="gap-2 text-sm text-destructive focus:text-destructive"+ >+ <Trash2 className="h-4 w-4" />+ {t('common.delete')}+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ ) : undefined+ }+ />++ <div className="flex flex-wrap items-center gap-x-4 gap-y-2 mb-5">+ <Segmented<Tab>+ value={tab}+ onChange={setTab}+ testIdPrefix="invoice-tab"+ options={[+ { value: 'details', label: t('invoices.tab.details') },+ { value: 'document', label: t('invoices.tab.document') },+ ]}+ />+ <StateBadge state={invoice.state} />+ {invoice.days_overdue > 0 && (+ <span className="text-xs font-medium text-rose-500">+ {t('invoices.daysLate', { count: invoice.days_overdue })}+ </span>+ )}+ </div>++ {tab === 'document' ? (+ <div className="space-y-4">+ {shareUrl && (+ <SectionCard>+ <div+ className="flex flex-wrap items-center gap-2 px-4 sm:px-5 py-3 text-xs"+ data-testid="invoice-share-banner"+ >+ <Share2 className="h-3.5 w-3.5 text-muted-foreground shrink-0" />+ <span className="text-muted-foreground">{t('invoices.shareActive')}</span>+ <code className="truncate font-mono text-[11px] text-foreground">{shareUrl}</code>+ <div className="ml-auto">+ <IconAction+ onClick={() => {+ void navigator.clipboard.writeText(shareUrl)+ toast.success(t('invoices.shareCopied'))+ }}+ label={t('invoices.shareCopy')}+ >+ <Copy className="h-3.5 w-3.5" />+ </IconAction>+ </div>+ </div>+ </SectionCard>+ )}+ {documentPayload ? (+ // Every page this invoice has, in one browser: the files down+ // the left, the selected one read on the right. Our own+ // render is one entry among them — and not offered at all on+ // an import, where drawing it would invent a document+ // somebody else issued.+ <InvoiceDocumentBrowser+ invoiceId={invoice.id}+ origin={invoice.origin}+ canWrite={canWrite}+ ourPageLabel={number}+ ourPageDate={invoice.issue_date}+ ourPage={<InvoiceDocumentView document={documentPayload} />}+ onChanged={refresh}+ />+ ) : (+ <Skeleton className="h-[520px] w-full rounded-xl" />+ )}+ </div>+ ) : (+ <div className="space-y-5">+ <SectionCard>+ <div className="grid grid-cols-2 sm:grid-cols-4 divide-x divide-border">+ {[+ { label: t('invoices.column.total'), value: money(invoice.total) },+ {+ label:+ invoice.direction === 'payable'+ ? t('invoices.field.paidOut')+ : t('invoices.field.paid'),+ value: money(invoice.amount_paid),+ },+ {+ label: t('invoices.column.balance'),+ value: money(invoice.balance),+ tone:+ Number(invoice.balance) > 0+ ? 'text-foreground'+ : 'text-emerald-600',+ testId: 'invoice-balance',+ },+ { label: t('invoices.column.due'), value: showDate(invoice.due_date) },+ ].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>+ <p+ className={cn(+ 'text-lg font-bold tabular-nums',+ figure.tone ?? 'text-foreground',+ )}+ >+ {figure.value}+ </p>+ </div>+ ))}+ </div>+ </SectionCard>++ {(invoice.lines.length > 0 || invoice.notes || customFields.length > 0) && (+ <SectionCard>+ <SectionHeader title={t('invoices.detailsTitle')} />+ <div className="px-4 sm:px-5 py-4 space-y-4">+ {/* Competence only earns a row when it disagrees with the+ issue date; otherwise it is noise on every invoice. */}+ {invoice.competence_date && invoice.competence_date !== invoice.issue_date && (+ <p className="text-xs text-muted-foreground" data-testid="invoice-competence">+ {t('invoices.competenceDiverges', {+ competence: showDate(invoice.competence_date),+ issue: showDate(invoice.issue_date),+ })}+ </p>+ )}++ {/* Driven by the workspace's definitions, so the label+ the sender chose is what shows — never the raw key —+ and a field removed from settings stops appearing. */}+ {customFields.length > 0 && (+ <div className="flex flex-wrap gap-x-8 gap-y-2">+ {customFields.map((field) => (+ <div key={field.key}>+ <p className="text-xs font-medium text-muted-foreground mb-0.5">+ {field.label}+ </p>+ <p className="text-sm">{field.value}</p>+ </div>+ ))}+ </div>+ )}++ {invoice.lines.length > 0 && (+ <table className="w-full">+ <tbody>+ {invoice.lines.map((line) => (+ <tr key={line.id} className="border-b border-border last:border-0">+ <td className="py-2.5 text-sm text-foreground">{line.description}</td>+ <td className="py-2.5 text-right text-xs text-muted-foreground tabular-nums">+ {Number(line.quantity)} × {money(line.unit_price)}+ </td>+ <td className="py-2.5 text-right text-sm font-medium tabular-nums w-32">+ {money(line.total)}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}++ {invoice.notes && (+ <p className="text-sm text-muted-foreground">{invoice.notes}</p>+ )}+ </div>+ </SectionCard>+ )}++ <SectionCard>+ <SectionHeader+ 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>+ ) : undefined+ }+ />+ {invoice.allocations.length === 0 ? (+ <p+ className="px-4 sm:px-5 py-8 text-center text-sm text-muted-foreground"+ data-testid="invoice-no-payments"+ >+ {t('invoices.noPayments')}+ </p>+ ) : (+ <table className="w-full">+ <tbody>+ {invoice.allocations.map((allocation) => (+ <tr+ key={allocation.id}+ data-testid="invoice-allocation"+ className="border-b border-border last:border-0"+ >+ <td className="py-3 pl-4 sm:pl-5">+ <div className="text-sm font-medium text-foreground truncate">+ {allocation.transaction?.description ?? t('invoices.linkedPayment')}+ </div>+ <div className="text-xs text-muted-foreground tabular-nums mt-0.5">+ {allocation.transaction?.date+ ? showDate(allocation.transaction.date)+ : ''}+ {' · '}+ {(() => {+ const origin = allocationOrigin(allocation.method)+ if (!origin.automatic) return t('invoices.linkedManually')+ // The strategy id is shown as the title rather+ // than the label: it is a machine name today+ // and becomes a readable one when the policy+ // is fetchable, without this line changing.+ return (+ <span title={origin.strategyId ?? undefined}>+ {t('invoices.linkedAutomatically')}+ </span>+ )+ })()}+ </div>+ </td>+ <td className="py-3 text-right text-sm font-bold tabular-nums text-emerald-600">+ {money(allocation.amount)}+ </td>+ <td className="py-3 pr-4 sm:pr-5 text-right w-16">+ {canWrite && (+ <IconAction+ onClick={() => unlinkMutation.mutate(allocation.id)}+ label={t('invoices.action.unlink')}+ destructive+ >+ <Unlink className="h-4 w-4" />+ </IconAction>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ )}+ </SectionCard>+ </div>+ )}++ <EditDraftDialog+ open={editOpen}+ onOpenChange={setEditOpen}+ invoice={invoice}+ showTax={(settings?.tax_fields ?? 'hidden') !== 'hidden'}+ currency={currency}+ onSaved={refresh}+ />++ <LinkPaymentDialog+ open={linkOpen}+ onOpenChange={setLinkOpen}+ invoiceId={id}+ direction={invoice.direction}+ balance={invoice.balance}+ currency={currency}+ onLinked={refresh}+ />+ </div>+ )+}++function LinkPaymentDialog({+ open,+ onOpenChange,+ invoiceId,+ direction,+ balance,+ currency,+ onLinked,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ invoiceId: string+ direction: InvoiceDirection+ balance: string+ currency: string+ onLinked: () => void+}) {+ const { t } = useTranslation()+ const [selected, setSelected] = useState<string>('')+ const [amount, setAmount] = useState('')++ // Money moving the way this invoice is settled: a receivable by money+ // coming in, a payable by money going out. Asking for credits either+ // way — which this did — means the payment that actually settled a+ // supplier's bill is never in the list, and the bill stays open+ // forever with no way to close it.+ const settlingType = direction === 'payable' ? 'debit' : 'credit'+ const { data } = useQuery({+ queryKey: ['transactions', 'for-invoice', settlingType],+ queryFn: () => transactionsApi.list({ type: settlingType, limit: 50 }),+ enabled: open,+ })++ // 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.+ const candidates = useMemo(+ () => (data?.items ?? []).filter((tx) => (tx.currency ?? currency) === currency),+ [data, currency],+ )++ const mutation = useMutation({+ mutationFn: () => invoicesApi.allocate(invoiceId, selected, amount || undefined),+ onSuccess: () => {+ toast.success(t('invoices.linked'))+ onOpenChange(false)+ setSelected('')+ setAmount('')+ onLinked()+ },+ 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-lg">+ <DialogHeader>+ <DialogTitle>{t('invoices.action.markPaid')}</DialogTitle>+ <DialogDescription>{t('invoices.linkDescription')}</DialogDescription>+ </DialogHeader>++ <div className="space-y-3 max-h-72 overflow-y-auto">+ {candidates.length === 0 && (+ <p className="text-sm text-muted-foreground">{t('invoices.noCandidates')}</p>+ )}+ {candidates.map((tx) => (+ <button+ key={tx.id}+ onClick={() => setSelected(tx.id)}+ data-testid="invoice-candidate"+ className={cn(+ 'w-full flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-left transition-colors',+ selected === tx.id ? 'border-primary bg-primary/5' : 'hover:bg-muted/40',+ )}+ >+ <div className="min-w-0">+ <div className="text-sm truncate">{tx.description}</div>+ <div className="text-xs text-muted-foreground tabular-nums">{tx.date}</div>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <span className="text-sm tabular-nums">+ {formatCurrency(Number(tx.amount), tx.currency ?? currency, 'en')}+ </span>+ {selected === tx.id && <CheckCircle2 className="h-4 w-4 text-primary" />}+ </div>+ </button>+ ))}+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="allocation-amount">{t('invoices.field.amountToApply')}</Label>+ <Input+ id="allocation-amount"+ data-testid="invoice-allocation-amount"+ inputMode="decimal"+ value={amount}+ onChange={(e) => setAmount(e.target.value)}+ placeholder={balance}+ />+ {/* Leaving it blank is the common case — one payment closing one+ invoice should not require typing the number twice. */}+ <p className="text-[11px] text-muted-foreground">{t('invoices.field.amountHint')}</p>+ </div>++ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={() => mutation.mutate()}+ disabled={!selected || mutation.isPending}+ data-testid="invoice-allocation-submit"+ >+ {t('invoices.action.link')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/**+ * Editing a draft.+ *+ * Only a draft: once issued, the financial substance is frozen and the+ * server refuses the change, because a document that changes after the+ * client received it is not an edit, it is a second document. The button+ * that opens this disappears at the same moment.+ *+ * Notes stay editable after issuance through the detail view, since they+ * are the seller's own record and never left the building.+ */+function EditDraftDialog({+ open,+ onOpenChange,+ invoice,+ showTax,+ currency,+ onSaved,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ invoice: Invoice+ showTax: boolean+ currency: string+ onSaved: () => void+}) {+ const { t } = useTranslation()+ const { data: clients = [] } = useQuery({+ queryKey: ['payees', 'for-invoice'],+ queryFn: () => payeesApi.list({}),+ enabled: open,+ })++ // Seeded from the invoice each time the dialog opens, keyed so a+ // reopen after a save starts from what was saved.+ const [payeeId, setPayeeId] = useState(invoice.payee_id ?? '')+ const [total, setTotal] = useState(invoice.total)+ const [dueDate, setDueDate] = useState(invoice.due_date)+ const [notes, setNotes] = useState(invoice.notes ?? '')+ const [lines, setLines] = useState<InvoiceLineInput[]>(() =>+ invoice.lines.map((line) => ({+ description: line.description,+ quantity: String(Number(line.quantity)),+ unit_price: line.unit_price,+ tax_rate: line.tax_rate,+ })),+ )++ const mutation = useMutation({+ mutationFn: () =>+ invoicesApi.update(invoice.id, {+ payee_id: payeeId || null,+ due_date: dueDate,+ notes: notes || null,+ // Lines are the source of truth once they exist: the server+ // recomputes the total from them and ignores what was typed.+ //+ // An empty list is sent when the draft had lines and no longer+ // does, because omitting the key means "leave them alone" — so+ // deleting every row used to save successfully and change+ // nothing, and the rows came back on the next read.+ ...(lines.length+ ? { lines }+ : invoice.lines.length+ ? { lines: [], total }+ : { total }),+ }),+ onSuccess: () => {+ toast.success(t('invoices.updated'))+ onOpenChange(false)+ onSaved()+ },+ 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}>+ {/* Same rule as the create dialog: the line-item table needs the+ room, and without it the row overflows and the remove button+ falls off the right edge. */}+ <DialogContent+ className={cn(+ 'flex flex-col max-h-[calc(100dvh-2rem)]',+ lines.length ? 'sm:max-w-3xl' : 'sm:max-w-lg',+ )}+ >+ <DialogHeader>+ <DialogTitle>{t('invoices.editDraft')}</DialogTitle>+ <DialogDescription>{t('invoices.editDraftDescription')}</DialogDescription>+ </DialogHeader>++ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label>{t('invoices.field.client')}</Label>+ <Select value={payeeId} onValueChange={setPayeeId}>+ <SelectTrigger data-testid="edit-client-select">+ <SelectValue placeholder={t('invoices.field.clientPlaceholder')} />+ </SelectTrigger>+ <SelectContent>+ {clients.map((client) => (+ <SelectItem key={client.id} value={client.id}>+ {client.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label htmlFor="edit-total">{t('invoices.field.total')}</Label>+ <Input+ id="edit-total"+ data-testid="edit-total-input"+ inputMode="decimal"+ value={lines.length ? linesTotal(lines).toFixed(2) : total}+ onChange={(e) => setTotal(e.target.value)}+ disabled={lines.length > 0}+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="edit-due">{t('invoices.field.dueDate')}</Label>+ <Input+ id="edit-due"+ data-testid="edit-due-input"+ type="date"+ value={dueDate}+ onChange={(e) => setDueDate(e.target.value)}+ />+ </div>+ </div>++ <InvoiceLineEditor+ lines={lines}+ onChange={setLines}+ currency={currency}+ showTax={showTax}+ />++ <div className="space-y-1.5">+ <Label htmlFor="edit-notes">{t('invoices.field.notes')}</Label>+ <Input+ id="edit-notes"+ data-testid="edit-notes-input"+ value={notes}+ onChange={(e) => setNotes(e.target.value)}+ />+ </div>+ </div>++ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={() => mutation.mutate()}+ disabled={mutation.isPending}+ data-testid="edit-submit"+ >+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/pages/invoices.tsx b/frontend/src/pages/invoices.tsxindex f1b99ac4..9b77ede0 100644--- a/frontend/src/pages/invoices.tsx+++ b/frontend/src/pages/invoices.tsx@@ -1,30 +1,1098 @@+import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { Receipt } from 'lucide-react'+import { useNavigate } from 'react-router-dom'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import {+ Calendar as CalendarIcon,+ ChevronDown,+ Plus,+ Receipt,+ Settings2,+} from 'lucide-react'+import { toast } from 'sonner'++import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Skeleton } from '@/components/ui/skeleton'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import { PageHeader } from '@/components/page-header'+import { SectionCard, Segmented, StateBadge, TH } from '@/components/invoice-ui'+import { InvoiceLineEditor } from '@/components/invoice-line-editor'+import { InvoiceLogoField } from '@/components/invoice-logo-field'+import { CurrencySelect } from '@/components/currency-select'+import { cn } from '@/lib/utils'+import { formatCurrency } from '@/lib/format'+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'+import { usePrivacyMode } from '@/hooks/use-privacy-mode'+import { useAuth } from '@/contexts/auth-context'+import { useWorkspace } from '@/contexts/workspace-context'+import { fiscal as fiscalApi, invoices as invoicesApi, payees as payeesApi } from '@/lib/api'+import {+ customFieldDefs,+ displayNumber,+ invoiceErrorKey,+ linesTotal,+} from '@/lib/invoice-utils'+import type {+ Invoice,+ InvoiceDirection,+ InvoiceLineInput,+ InvoiceTemplate,+ IssuerTaxId,+} from '@/types'/**- * Placeholder until the invoices ledger lands. Deliberately honest- * about being empty rather than showing a fake table: the nav entry- * exists so the module boundary is real and testable.+ * Receivables: what is owed, what is late, what landed.+ *+ * Reachable only from a business workspace — the module resolver leaves+ * `invoices` out of a personal one, so nothing here is ever rendered+ * there.*/++type Filter = 'all' | 'open' | 'overdue' | 'paid' | 'draft'++/** The three derived states where money is still expected. `open` in the+ * filter bar means all of them, which is why it is not a server query. */+const OUTSTANDING: string[] = ['open', 'partial', 'overdue']++/** Aging buckets, oldest last. The tone runs from quiet to loud with the+ * age, so the bar reads as a temperature without needing its legend. */+const BUCKETS = [+ { key: 'current', tone: 'bg-emerald-500/70' },+ { key: 'd1_30', tone: 'bg-amber-400/80' },+ { key: 'd31_60', tone: 'bg-orange-500/80' },+ { key: 'd61_90', tone: 'bg-rose-500/80' },+ { key: 'd90_plus', tone: 'bg-rose-700/80' },+] as const+export default function InvoicesPage() {const { t } = useTranslation()+ const navigate = useNavigate()+ const locale = useDisplayLocale()+ const dateLocale = useDateLocale()+ const { mask } = usePrivacyMode()+ const { user } = useAuth()+ const { canWrite } = useWorkspace()+ const currency = user?.preferences?.currency_display ?? 'USD'++ // `null` is "every year". The default is the current one, which is+ // what someone opening the page is almost always asking about.+ // Which ledger is on screen. A bigger axis than the state filter — the+ // totals above the list change with it — so it sits above the summary+ // rather than among the filters.+ const [direction, setDirection] = useState<InvoiceDirection>('receivable')+ const [year, setYear] = useState<number | null>(() => new Date().getFullYear())+ const [filter, setFilter] = useState<Filter>('all')+ const [createOpen, setCreateOpen] = useState(false)+ const [settingsOpen, setSettingsOpen] = useState(false)++ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ })+ const { data: summary, isLoading: summaryLoading } = useQuery({+ queryKey: ['invoice-summary', direction],+ queryFn: () => invoicesApi.summary(direction),+ })+ const { data: facets } = useQuery({+ queryKey: ['invoice-facets', year, direction],+ queryFn: () => invoicesApi.facets(year ?? undefined, direction),+ })+ const { data: list, isLoading } = useQuery({+ queryKey: ['invoices', filter, year, direction],+ queryFn: () =>+ invoicesApi.list({+ direction,+ // `open` spans three derived states, so it is filtered here+ // rather than asked for three times.+ ...(filter === 'all' || filter === 'open' ? {} : { state: filter }),+ ...(year ? { year } : {}),+ }),+ })++ const visible = useMemo(() => {+ if (!list) return []+ return filter === 'open' ? list.filter((i) => OUTSTANDING.includes(i.state)) : list+ }, [list, filter])++ const money = (value: string | number | null | undefined, code?: string) =>+ mask(formatCurrency(Number(value ?? 0), code ?? currency, locale))++ const showDate = (iso: string) =>+ new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)++ const outstanding = Number(summary?.outstanding ?? 0)+ const overdue = Number(summary?.overdue_amount ?? 0)+ const bucketTotal = BUCKETS.reduce(+ (sum, b) => sum + Number(summary?.buckets[b.key] ?? 0),+ 0,+ )++ return (+ <div>+ <PageHeader+ section={t('invoices.section')}+ title={t('invoices.title')}+ action={+ <div className="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={() => setSettingsOpen(true)}+ data-testid="invoice-settings-button"+ >+ <Settings2 className="h-4 w-4 mr-1.5" />+ {t('invoices.settings.title')}+ </Button>+ {canWrite && (+ <Button size="sm" onClick={() => setCreateOpen(true)} data-testid="invoice-new-button">+ <Plus className="h-4 w-4 mr-1.5" />+ {direction === 'payable' ? t('invoices.newPayable') : t('invoices.new')}+ </Button>+ )}+ </div>+ }+ />++ <div className="mb-4">+ <Segmented<InvoiceDirection>+ value={direction}+ onChange={setDirection}+ testIdPrefix="invoice-direction"+ options={[+ { value: 'receivable', label: t('invoices.direction.receivable') },+ { value: 'payable', label: t('invoices.direction.payable') },+ ]}+ />+ </div>++ {/* One block, in the dashboard's shape: a headline figure with its+ supporting numbers beside it, and the accountant's view of the+ same money to the right. Four identical stat cards say less. */}+ <div className="bg-card rounded-xl border border-border shadow-sm mb-5">+ <div className="grid grid-cols-1 lg:grid-cols-3">+ <div className="lg:col-span-2 px-5 py-4">+ <p className="text-xs font-medium text-muted-foreground mb-0.5">+ {direction === 'payable'+ ? t('invoices.summary.owed')+ : t('invoices.summary.outstanding')}+ </p>+ {summaryLoading ? (+ <Skeleton className="h-10 w-40" />+ ) : (+ <p className="text-4xl font-bold tabular-nums leading-tight text-foreground">+ {money(outstanding)}+ </p>+ )}++ <div className="flex flex-wrap gap-6 mt-4">+ <div>+ <p className="text-xs font-medium text-muted-foreground mb-0.5">+ {t('invoices.summary.overdue')}+ </p>+ <p+ className={cn(+ 'text-sm font-bold tabular-nums',+ overdue > 0 ? 'text-rose-500' : 'text-muted-foreground',+ )}+ data-testid="summary-overdue"+ >+ {money(overdue)}+ {summary && summary.overdue_count > 0 && (+ <span className="ml-1.5 font-medium text-muted-foreground">+ {t('invoices.summary.overdueCount', { count: summary.overdue_count })}+ </span>+ )}+ </p>+ </div>+ <div>+ <p className="text-xs font-medium text-muted-foreground mb-0.5">+ {direction === 'payable'+ ? t('invoices.summary.paidThisMonth')+ : t('invoices.summary.receivedThisMonth')}+ </p>+ <p className="text-sm font-bold tabular-nums text-emerald-600" data-testid="summary-received">+ {money(summary?.received_this_month)}+ </p>+ </div>+ <div>+ <p className="text-xs font-medium text-muted-foreground mb-0.5">+ {t('invoices.summary.upcoming')}+ </p>+ <p className="text-sm font-bold tabular-nums text-foreground" data-testid="summary-upcoming">+ {summary?.upcoming.length ?? 0}+ </p>+ </div>+ </div>+ </div>++ <div className="px-5 py-4 border-t border-border lg:border-t-0 lg:border-l">+ <p className="text-xs font-medium text-muted-foreground mb-2">+ {t('invoices.summary.aging')}+ </p>+ {bucketTotal > 0 ? (+ <>+ <div+ className="flex h-2 w-full overflow-hidden rounded-full bg-muted"+ data-testid="aging-bar"+ >+ {BUCKETS.map((bucket) => {+ const amount = Number(summary?.buckets[bucket.key] ?? 0)+ if (amount <= 0) return null+ return (+ <div+ key={bucket.key}+ className={bucket.tone}+ style={{ width: `${(amount / bucketTotal) * 100}%` }}+ title={t(`invoices.bucket.${bucket.key}`)}+ />+ )+ })}+ </div>+ <dl className="mt-3 space-y-1">+ {BUCKETS.map((bucket) => {+ const amount = Number(summary?.buckets[bucket.key] ?? 0)+ if (amount <= 0) return null+ return (+ <div key={bucket.key} className="flex items-center gap-2 text-xs">+ <span className={cn('h-2 w-2 rounded-full shrink-0', bucket.tone)} />+ <dt className="text-muted-foreground">+ {t(`invoices.bucket.${bucket.key}`)}+ </dt>+ <dd className="ml-auto tabular-nums font-medium">{money(amount)}</dd>+ </div>+ )+ })}+ </dl>+ </>+ ) : (+ <p className="text-xs text-muted-foreground">{t('invoices.summary.nothingDue')}</p>+ )}+ </div>+ </div>+ </div>++ <div className="mb-4 flex flex-wrap items-center justify-between gap-3">+ <Segmented<Filter>+ value={filter}+ onChange={setFilter}+ testIdPrefix="invoice-filter"+ options={(['all', 'open', 'overdue', 'paid', 'draft'] as const).map((value) => ({+ value,+ label: t(`invoices.filter.${value}`),+ count: facets?.counts[value],+ }))}+ />++ {/* The year sits with the list's own controls, not with the+ summary: it scopes what is listed, and the summary above+ deliberately has no year — an unpaid 2024 invoice is still+ owed today. */}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ {/* Same trigger the dashboard uses for its period: a+ dropdown rather than the dashboard's arrows because only+ years that have a document are worth stepping to, and+ arrows would walk into empty ones. */}+ <button+ type="button"+ data-testid="invoice-year-trigger"+ className="inline-flex items-center justify-center gap-2 border border-border rounded-lg px-3 py-1.5 text-sm bg-card text-foreground hover:bg-muted/50 transition-all cursor-pointer min-w-[180px]"+ >+ <CalendarIcon className="size-3.5 text-muted-foreground" />+ {year ? t('invoices.fiscalYear', { year }) : t('invoices.allYears')}+ <ChevronDown className="size-3.5 text-muted-foreground ml-auto" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ className="w-[180px] p-1 bg-card border border-border rounded-xl shadow-md"+ >+ <DropdownMenuItem+ onClick={() => setYear(null)}+ data-testid="invoice-year-all"+ className="text-sm"+ >+ {t('invoices.allYears')}+ </DropdownMenuItem>+ {/* Only years that actually have an invoice. Offering an+ empty year is offering a dead end. */}+ {(facets?.years ?? []).map((option) => (+ <DropdownMenuItem+ key={option}+ onClick={() => setYear(option)}+ data-testid={`invoice-year-${option}`}+ className="text-sm tabular-nums"+ >+ {t('invoices.fiscalYear', { year: option })}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>++ <SectionCard>+ {isLoading ? (+ <div className="p-5 space-y-3">+ {[0, 1, 2].map((i) => (+ <Skeleton key={i} className="h-9 w-full" />+ ))}+ </div>+ ) : visible.length === 0 ? (+ <div className="px-5 py-14 text-center" data-testid="invoices-empty">+ <Receipt className="h-8 w-8 mx-auto text-muted-foreground/50" />+ <p className="mt-3 text-sm text-muted-foreground max-w-sm mx-auto">+ {filter !== 'all'+ ? t('invoices.emptyFiltered')+ : year+ ? t('invoices.emptyYear', { year: t('invoices.fiscalYear', { year }) })+ : t('invoices.empty')}+ </p>+ {/* When a year emptied the list, the useful next move is to+ widen it — not to create an invoice in a year nobody is+ looking at. */}+ {filter === 'all' && year && facets && facets.years.length > 0 ? (+ <Button size="sm" variant="outline" className="mt-4" onClick={() => setYear(null)}>+ {t('invoices.showAllYears')}+ </Button>+ ) : (+ filter === 'all' &&+ canWrite && (+ <Button size="sm" className="mt-4" onClick={() => setCreateOpen(true)}>+ <Plus className="h-4 w-4 mr-1.5" />+ {t('invoices.new')}+ </Button>+ )+ )}+ </div>+ ) : (+ <div className="overflow-x-auto">+ <table className="w-full">+ <thead>+ <tr className="border-b border-border">+ <th className={`${TH} pl-4 sm:pl-5 text-left`}>+ {direction === 'payable'+ ? t('invoices.column.supplier')+ : t('invoices.column.client')}+ </th>+ <th className={`${TH} text-left w-24 hidden sm:table-cell`}>+ {t('invoices.column.number')}+ </th>+ <th className={`${TH} text-left w-32 hidden md:table-cell`}>+ {t('invoices.column.due')}+ </th>+ <th className={`${TH} text-right w-32`}>{t('invoices.column.total')}</th>+ <th className={`${TH} text-right w-32 hidden sm:table-cell`}>+ {t('invoices.column.balance')}+ </th>+ <th className={`${TH} pr-4 sm:pr-5 text-right w-28`}>+ {t('invoices.column.state')}+ </th>+ </tr>+ </thead>+ <tbody>+ {visible.map((invoice) => (+ <tr+ key={invoice.id}+ onClick={() => navigate(`/invoices/${invoice.id}`)}+ data-testid="invoice-row"+ className="border-b border-border last:border-0 hover:bg-muted transition-colors cursor-pointer"+ >+ <td className="py-3 pl-4 sm:pl-5">+ <div className="text-sm font-medium text-foreground truncate">+ {invoice.payee?.name ?? (+ <span className="text-muted-foreground">+ {direction === 'payable'+ ? t('invoices.noSupplier')+ : t('invoices.noClient')}+ </span>+ )}+ </div>+ {/* The number and date fold in here on small screens+ rather than disappearing with their columns. */}+ <div className="sm:hidden text-xs text-muted-foreground tabular-nums mt-0.5">+ {displayNumber(invoice, settings?.number_prefix) ?? t('invoices.noNumber')}+ {' · '}+ {showDate(invoice.due_date)}+ </div>+ </td>+ <td className="py-3 text-xs text-muted-foreground tabular-nums hidden sm:table-cell">+ {displayNumber(invoice, settings?.number_prefix) ?? (+ <span className="text-muted-foreground/60">{t('invoices.noNumber')}</span>+ )}+ </td>+ <td className="py-3 hidden md:table-cell">+ <span className="text-xs text-muted-foreground tabular-nums">+ {showDate(invoice.due_date)}+ </span>+ {invoice.days_overdue > 0 && (+ <span className="ml-1.5 text-[11px] font-medium text-rose-500">+ {t('invoices.daysLate', { count: invoice.days_overdue })}+ </span>+ )}+ </td>+ <td className="py-3 text-right text-xs sm:text-sm tabular-nums text-muted-foreground">+ {money(invoice.total, invoice.currency)}+ </td>+ <td className="py-3 text-right text-xs sm:text-sm font-bold tabular-nums hidden sm:table-cell">+ {Number(invoice.balance) > 0 ? (+ money(invoice.balance, invoice.currency)+ ) : (+ <span className="text-muted-foreground font-medium">—</span>+ )}+ </td>+ <td className="py-3 pr-4 sm:pr-5 text-right">+ <StateBadge state={invoice.state} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ </SectionCard>++ <CreateInvoiceDialog+ open={createOpen}+ onOpenChange={setCreateOpen}+ direction={direction}+ onCreated={(invoice) => navigate(`/invoices/${invoice.id}`)}+ />+ {/* Keyed on `open`: the dialog is mounted either way, so without+ this its draft state outlives a Cancel — reopening showed the+ edits back, and Save wrote the change the user had rejected. */}+ <InvoiceSettingsDialog+ key={settingsOpen ? 'open' : 'closed'}+ open={settingsOpen}+ onOpenChange={setSettingsOpen}+ />+ </div>+ )+}++function CreateInvoiceDialog({+ open,+ onOpenChange,+ direction,+ onCreated,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ /** Taken from the list rather than asked again: the user already chose+ * a ledger to be looking at, and asking twice is asking them to repeat+ * themselves. */+ direction: InvoiceDirection+ onCreated: (invoice: Invoice) => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ enabled: open,+ })+ const { data: clients = [] } = useQuery({+ queryKey: ['payees', 'for-invoice'],+ queryFn: () => payeesApi.list({}),+ enabled: open,+ })++ const [payeeId, setPayeeId] = useState<string>('')+ const [total, setTotal] = useState('')+ const [dueDate, setDueDate] = useState('')+ const [notes, setNotes] = useState('')+ const [custom, setCustom] = useState<Record<string, string>>({})+ const [lines, setLines] = useState<InvoiceLineInput[]>([])++ const defs = customFieldDefs(settings?.template)+ const { user } = useAuth()+ // An invoice is denominated in one currency, and it is not necessarily+ // the one this user reads the app in — a freelancer in São Paulo bills+ // a client in New York in USD and is paid into a BRL account. The+ // display preference is only the starting guess.+ const [currencyCode, setCurrencyCode] = useState(+ user?.preferences?.currency_display ?? 'USD',+ )++ const mutation = useMutation({+ mutationFn: (asDraft: boolean) =>+ invoicesApi.create({+ direction,+ as_draft: asDraft,+ payee_id: payeeId || null,+ // Lines are the source of truth once they exist: the server+ // recomputes the total from them and ignores what was typed.+ ...(lines.length ? { lines } : { total }),+ ...(dueDate ? { due_date: dueDate } : {}),+ currency: currencyCode,+ notes: notes || null,+ ...(Object.keys(custom).length ? { custom_fields: custom } : {}),+ }),+ onSuccess: (invoice) => {+ toast.success(+ invoice.status === 'draft' ? t('invoices.draftSaved') : t('invoices.created'),+ )+ // The dialog owns the mutation, so it owns the invalidation: the+ // parent navigates away and would otherwise leave a stale list+ // behind for whenever the user comes back to it.+ void queryClient.invalidateQueries({ queryKey: ['invoices'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-summary'] })+ void queryClient.invalidateQueries({ queryKey: ['invoice-facets'] })+ onOpenChange(false)+ setPayeeId('')+ setTotal('')+ setDueDate('')+ setNotes('')+ setCurrencyCode(user?.preferences?.currency_display ?? 'USD')+ setCustom({})+ setLines([])+ onCreated(invoice)+ },+ 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}>+ {/* Widens once there are line items: a table of five columns in a+ narrow dialog is the cramped row of boxes this used to be. */}+ <DialogContent+ className={cn(+ 'flex flex-col max-h-[calc(100dvh-2rem)]',+ lines.length ? 'sm:max-w-3xl' : 'sm:max-w-lg',+ )}+ >+ <DialogHeader>+ <DialogTitle>+ {direction === 'payable' ? t('invoices.newPayable') : t('invoices.new')}+ </DialogTitle>+ {/* Three fields is the whole point under the tracking preset:+ the money is already owed, and the document lives elsewhere. */}+ <DialogDescription>+ {direction === 'payable'+ ? t('invoices.newPayableDescription')+ : t('invoices.newDescription')}+ </DialogDescription>+ </DialogHeader>++ <div className="space-y-4">+ <div className="space-y-1.5">+ <Label>+ {direction === 'payable'+ ? t('invoices.field.supplier')+ : t('invoices.field.client')}+ </Label>+ <Select value={payeeId} onValueChange={setPayeeId}>+ <SelectTrigger data-testid="invoice-client-select">+ <SelectValue+ placeholder={t(+ direction === 'payable'+ ? 'invoices.field.supplierPlaceholder'+ : 'invoices.field.clientPlaceholder',+ )}+ />+ </SelectTrigger>+ <SelectContent>+ {clients.map((client) => (+ <SelectItem key={client.id} value={client.id}>+ {client.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>++ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label htmlFor="invoice-total">{t('invoices.field.total')}</Label>+ <div className="flex gap-2">+ <Input+ id="invoice-total"+ data-testid="invoice-total-input"+ inputMode="decimal"+ value={lines.length ? linesTotal(lines).toFixed(2) : total}+ onChange={(e) => setTotal(e.target.value)}+ // Derived once lines exist, so the two can never disagree.+ disabled={lines.length > 0}+ placeholder="0.00"+ />+ <CurrencySelect+ id="invoice-currency"+ value={currencyCode}+ onChange={setCurrencyCode}+ className="w-28 shrink-0"+ />+ </div>+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="invoice-due">{t('invoices.field.dueDate')}</Label>+ <Input+ id="invoice-due"+ data-testid="invoice-due-input"+ type="date"+ value={dueDate}+ onChange={(e) => setDueDate(e.target.value)}+ />+ <p className="text-[11px] text-muted-foreground">+ {t(+ direction === 'payable'+ ? 'invoices.field.dueDateHintPayable'+ : 'invoices.field.dueDateHint',+ { days: settings?.default_payment_terms_days ?? 30 },+ )}+ </p>+ </div>+ </div>++ {defs.map((def) => (+ <div key={def.key} className="space-y-1.5">+ <Label htmlFor={`custom-${def.key}`}>{def.label}</Label>+ <Input+ id={`custom-${def.key}`}+ data-testid={`invoice-custom-${def.key}`}+ value={custom[def.key] ?? ''}+ onChange={(e) => setCustom({ ...custom, [def.key]: e.target.value })}+ />+ </div>+ ))}++ <InvoiceLineEditor+ lines={lines}+ onChange={setLines}+ currency={currencyCode}+ showTax={(settings?.tax_fields ?? 'hidden') !== 'hidden'}+ // Under the document preset the server requires line items,+ // so the editor opens with an empty row rather than letting+ // the user discover the rule from a rejected submit.+ required={settings?.document_required ?? false}+ />++ <div className="space-y-1.5">+ <Label htmlFor="invoice-notes">{t('invoices.field.notes')}</Label>+ <Input+ id="invoice-notes"+ data-testid="invoice-notes-input"+ value={notes}+ onChange={(e) => setNotes(e.target.value)}+ />+ </div>+ </div>++ <DialogFooter className="sm:justify-between gap-2">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>+ {t('common.cancel')}+ </Button>+ <div className="flex gap-2">+ {/* A draft costs nothing to leave lying around: it carries no+ number, counts in no total, and is the only state an+ invoice can still be edited in. Under the tracking preset+ the button is the only way to reach it, since that preset+ opens everything on creation. */}+ <Button+ variant="outline"+ onClick={() => mutation.mutate(true)}+ disabled={mutation.isPending}+ data-testid="invoice-save-draft"+ >+ {t('invoices.action.saveDraft')}+ </Button>+ <Button+ onClick={() => mutation.mutate(false)}+ disabled={(lines.length ? linesTotal(lines) <= 0 : !total) || mutation.isPending}+ data-testid="invoice-create-submit"+ >+ {t('common.create')}+ </Button>+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++function InvoiceSettingsDialog({+ open,+ onOpenChange,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const { data: settings } = useQuery({+ queryKey: ['invoice-settings'],+ queryFn: invoicesApi.settings,+ enabled: open,+ })++ const [draft, setDraft] = useState<Record<string, unknown>>({})+ const value = <K extends keyof NonNullable<typeof settings>>(key: K) =>+ (draft[key as string] as NonNullable<typeof settings>[K]) ?? settings?.[key]++ const mutation = useMutation({+ mutationFn: () => invoicesApi.updateSettings(draft),+ onSuccess: () => {+ toast.success(t('invoices.settings.saved'))+ void queryClient.invalidateQueries({ queryKey: ['invoice-settings'] })+ setDraft({})+ onOpenChange(false)+ },+ })return (- <div className="container max-w-5xl py-8">- <div className="rounded-xl border bg-card p-10 flex flex-col items-center text-center gap-3">- <div className="h-12 w-12 rounded-xl bg-primary/10 flex items-center justify-center">- <Receipt className="h-6 w-6 text-primary" />+ <Dialog open={open} onOpenChange={onOpenChange}>+ {/* Capped and scrolled internally, the way every other tall dialog+ in the app is: a modal taller than the viewport pushes its own+ close button off screen, which is how someone ends up trapped+ in it. Header and footer stay put; only the body moves. */}+ <DialogContent className="sm:max-w-3xl flex flex-col max-h-[calc(100dvh-2rem)]">+ <DialogHeader>+ <DialogTitle>{t('invoices.settings.title')}</DialogTitle>+ <DialogDescription>{t('invoices.settings.description')}</DialogDescription>+ </DialogHeader>++ <div className="overflow-y-auto flex-1 -mx-1 px-1 grid gap-x-8 gap-y-5 sm:grid-cols-2">+ <div className="space-y-4">+ <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {t('invoices.settings.groupBehaviour')}+ </p>+ <div className="space-y-1.5">+ <Label>{t('invoices.settings.preset')}</Label>+ <Select+ value={String(value('preset') ?? 'tracking')}+ onValueChange={(v) => setDraft({ ...draft, preset: v })}+ >+ <SelectTrigger data-testid="invoice-preset-select">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="tracking">{t('invoices.settings.presetTracking')}</SelectItem>+ <SelectItem value="document">{t('invoices.settings.presetDocument')}</SelectItem>+ </SelectContent>+ </Select>+ {/* Says what the choice does, because "tracking vs document"+ means nothing until you know which one issues the paper. */}+ <p className="text-[11px] text-muted-foreground">+ {value('preset') === 'document'+ ? t('invoices.settings.presetDocumentHint')+ : t('invoices.settings.presetTrackingHint')}+ </p>+ </div>++ <div className="grid grid-cols-2 gap-3">+ <div className="space-y-1.5">+ <Label htmlFor="settings-prefix">{t('invoices.settings.numberPrefix')}</Label>+ <Input+ id="settings-prefix"+ data-testid="invoice-prefix-input"+ value={String(value('number_prefix') ?? '')}+ onChange={(e) => setDraft({ ...draft, number_prefix: e.target.value })}+ placeholder="FAT-"+ />+ </div>+ <div className="space-y-1.5">+ <Label htmlFor="settings-terms">{t('invoices.settings.paymentTerms')}</Label>+ <Input+ id="settings-terms"+ data-testid="invoice-terms-input"+ type="number"+ min={0}+ value={String(value('default_payment_terms_days') ?? 30)}+ onChange={(e) =>+ setDraft({ ...draft, default_payment_terms_days: Number(e.target.value) })+ }+ />+ </div>+ </div>++ <IssuerSection />+ </div>++ <div className="space-y-4">+ <p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {t('invoices.settings.groupDocument')}+ </p>+ <div className="space-y-1.5">+ <Label htmlFor="settings-issuer">{t('invoices.settings.issuerName')}</Label>+ <Input+ id="settings-issuer"+ data-testid="invoice-issuer-input"+ value={String(value('issuer_display_name') ?? '')}+ onChange={(e) => setDraft({ ...draft, issuer_display_name: e.target.value })}+ />+ </div>++ <div className="space-y-1.5">+ <Label>{t('invoices.settings.logo')}</Label>+ <InvoiceLogoField+ logoId={settings?.logo_id ?? null}+ onChanged={() => {+ void queryClient.invalidateQueries({ queryKey: ['invoice-settings'] })+ }}+ />+ {/* The freeze rule, said out loud: people expect a logo change+ to be retroactive, and it deliberately is not. */}+ <p className="text-[11px] text-muted-foreground">{t('invoices.settings.logoHint')}</p>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="settings-payment">{t('invoices.settings.paymentDetails')}</Label>+ <Input+ id="settings-payment"+ data-testid="invoice-payment-details-input"+ value={String(value('payment_details') ?? '')}+ onChange={(e) => setDraft({ ...draft, payment_details: e.target.value })}+ placeholder="Pix: …"+ />+ <p className="text-[11px] text-muted-foreground">+ {t('invoices.settings.paymentDetailsHint')}+ </p>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="settings-accent">{t('invoices.settings.accentColor')}</Label>+ <div className="flex items-center gap-2">+ <input+ id="settings-accent"+ type="color"+ data-testid="invoice-accent-input"+ className="h-9 w-12 rounded border bg-transparent p-1"+ value={String(value('accent_color') ?? '#111827')}+ onChange={(e) => setDraft({ ...draft, accent_color: e.target.value })}+ />+ <span className="font-mono text-xs text-muted-foreground">+ {String(value('accent_color') ?? '#111827')}+ </span>+ </div>+ </div>++ <div className="space-y-1.5">+ <Label htmlFor="settings-footer">{t('invoices.settings.footerNote')}</Label>+ <Input+ id="settings-footer"+ data-testid="invoice-footer-input"+ value={String(value('footer_note') ?? '')}+ onChange={(e) => setDraft({ ...draft, footer_note: e.target.value })}+ />+ </div>++ </div>++ <div className="sm:col-span-2">+ <LabelSection+ template={(value('template') as InvoiceTemplate | null) ?? null}+ onChange={(template) => setDraft({ ...draft, template })}+ />++ </div></div>- <h1 className="text-xl font-semibold">- {t('invoices.title', 'Invoices')}- </h1>- <p className="text-sm text-muted-foreground max-w-md leading-relaxed">- {t(- 'invoices.comingNext',- 'Bill your clients and keep track of what has been paid and what is still open. This is the next thing being built.',- )}- </p>++ <DialogFooter>+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ {t('common.cancel')}+ </Button>+ <Button+ onClick={() => mutation.mutate()}+ disabled={Object.keys(draft).length === 0 || mutation.isPending}+ data-testid="invoice-settings-save"+ >+ {t('common.save')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}++/**+ * The workspace describing itself: what appears as the sender on every+ * document issued from now on.+ *+ * Which fiscal documents are offered comes from the workspace's own+ * jurisdiction pack, so a Brazilian workspace is asked for a CNPJ and a+ * German one for a VAT number without this component knowing either+ * exists. It also never *restricts* the choice — a company can hold a+ * document its country's pack never anticipated.+ */+function IssuerSection() {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const { data: issuer } = useQuery({ queryKey: ['invoice-issuer'], queryFn: invoicesApi.issuer })+ const { data: kinds } = useQuery({ queryKey: ['tax-id-kinds'], queryFn: fiscalApi.taxIdKinds })++ const [draft, setDraft] = useState<Record<string, string>>({})+ const [docs, setDocs] = useState<IssuerTaxId[] | null>(null)++ const rows = docs ?? issuer?.tax_ids ?? []+ const offered = (kinds?.kinds ?? []).filter((k) => k.offered)++ const mutation = useMutation({+ mutationFn: () =>+ invoicesApi.updateIssuer({+ ...(draft.legal_name !== undefined ? { legal_name: draft.legal_name } : {}),+ ...(draft.address !== undefined ? { address: draft.address } : {}),+ ...(docs ? { tax_ids: docs.filter((d) => d.value.trim()) } : {}),+ }),+ onSuccess: () => {+ toast.success(t('invoices.settings.saved'))+ void queryClient.invalidateQueries({ queryKey: ['invoice-issuer'] })+ setDraft({})+ setDocs(null)+ },+ onError: (error) => {+ const key = invoiceErrorKey(error)+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))+ },+ })++ return (+ <div className="border-t pt-4 space-y-3" data-testid="invoice-issuer-section">+ <div>+ <Label>{t('invoices.settings.issuer')}</Label>+ <p className="text-[11px] text-muted-foreground">{t('invoices.settings.issuerHint')}</p></div>++ <Input+ data-testid="issuer-legal-name"+ placeholder={t('invoices.settings.legalName')}+ value={draft.legal_name ?? issuer?.legal_name ?? ''}+ onChange={(e) => setDraft({ ...draft, legal_name: e.target.value })}+ />+ <Input+ data-testid="issuer-address"+ placeholder={t('invoices.settings.addressLabel')}+ value={draft.address ?? issuer?.address ?? ''}+ onChange={(e) => setDraft({ ...draft, address: e.target.value })}+ />++ {offered.map((kind) => {+ const existing = rows.find((r) => r.kind === kind.kind)+ return (+ <Input+ key={kind.kind}+ data-testid={`issuer-tax-${kind.kind}`}+ placeholder={t(kind.label_key, kind.kind.toUpperCase())}+ value={existing?.value ?? ''}+ onChange={(e) => {+ const next = rows.filter((r) => r.kind !== kind.kind)+ if (e.target.value.trim()) next.push({ kind: kind.kind, value: e.target.value })+ setDocs(next)+ }}+ />+ )+ })}++ <Button+ size="sm"+ variant="outline"+ onClick={() => mutation.mutate()}+ disabled={mutation.isPending || (Object.keys(draft).length === 0 && docs === null)}+ data-testid="issuer-save"+ >+ {t('invoices.settings.saveIssuer')}+ </Button>+ </div>+ )+}++/**+ * Renaming what the document calls each field.+ *+ * Only the fields a sender actually renames are offered. The full set is+ * eighteen, and a settings dialog with eighteen text inputs is a wall+ * nobody reads; the rest stay editable through the API for the rare+ * workspace that wants them.+ *+ * Placeholders show the pack for the workspace's language, so an empty+ * box reads as "this is what it will say" rather than as a missing+ * value. Clearing a box returns that label to the pack.+ */+const EDITABLE_LABELS = [+ 'invoice',+ 'billTo',+ 'from',+ 'description',+ 'quantity',+ 'unitPrice',+ 'total',+ 'paymentDetails',+ 'notes',+] as const++function LabelSection({+ template,+ onChange,+}: {+ template: InvoiceTemplate | null+ onChange: (template: InvoiceTemplate) => void+}) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const labels = template?.labels ?? {}++ const set = (key: string, value: string) => {+ const next = { ...labels }+ // An empty box means "use the default", not "print nothing".+ if (value.trim()) next[key] = value+ else delete next[key]+ onChange({ ...(template ?? {}), labels: next })+ }++ return (+ <div className="border-t pt-4">+ <button+ type="button"+ onClick={() => setOpen(!open)}+ data-testid="invoice-labels-toggle"+ className="flex w-full items-center justify-between text-left"+ >+ <div>+ <Label className="cursor-pointer">{t('invoices.settings.labels')}</Label>+ <p className="text-[11px] text-muted-foreground">+ {t('invoices.settings.labelsHint')}+ </p>+ </div>+ <ChevronDown+ className={cn('h-4 w-4 text-muted-foreground transition-transform', open && 'rotate-180')}+ />+ </button>++ {open && (+ <div className="mt-3 grid gap-2 sm:grid-cols-2">+ {EDITABLE_LABELS.map((key) => (+ <Input+ key={key}+ data-testid={`invoice-label-${key}`}+ value={labels[key] ?? ''}+ placeholder={t(`invoices.label.${key}`)}+ onChange={(e) => set(key, e.target.value)}+ />+ ))}+ </div>+ )}</div>)}diff --git a/frontend/src/pages/shared-invoice.tsx b/frontend/src/pages/shared-invoice.tsxnew file mode 100644index 00000000..12196e66--- /dev/null+++ b/frontend/src/pages/shared-invoice.tsx@@ -0,0 +1,66 @@+import { useQuery } from '@tanstack/react-query'+import { useParams } from 'react-router-dom'+import { useTranslation } from 'react-i18next'+import { Download } from 'lucide-react'++import { Button } from '@/components/ui/button'+import { InvoiceDocumentView } from '@/components/invoice-document'+import { publicInvoices } from '@/lib/api'++/**+ * An invoice someone was sent a link to.+ *+ * Outside the app shell entirely: no sidebar, no workspace, no session.+ * The recipient is a client, not a user, and the page shows them one+ * document and a way to save it. A bad or revoked token is a plain+ * not-found — the same answer a link that never existed gets, because+ * "this used to be here" is itself information.+ */+export default function SharedInvoicePage() {+ const { token = '' } = useParams()+ const { t } = useTranslation()++ const { data, isLoading, isError } = useQuery({+ queryKey: ['shared-invoice', token],+ queryFn: () => publicInvoices.get(token),+ enabled: Boolean(token),+ retry: false,+ })++ if (isLoading) {+ return (+ <div className="min-h-screen grid place-items-center text-sm text-muted-foreground">+ {t('common.loading')}+ </div>+ )+ }++ if (isError || !data) {+ return (+ <div className="min-h-screen grid place-items-center px-6">+ <div className="text-center space-y-2">+ <h1 className="text-lg font-semibold">{t('invoices.shared.notFoundTitle')}</h1>+ <p className="text-sm text-muted-foreground max-w-sm">+ {t('invoices.shared.notFoundBody')}+ </p>+ </div>+ </div>+ )+ }++ return (+ <div className="min-h-screen bg-background py-8 px-4">+ <div className="mx-auto max-w-3xl space-y-3">+ <div className="flex justify-end">+ <Button asChild size="sm" variant="outline" data-testid="shared-download">+ <a href={publicInvoices.pdfUrl(token)} target="_blank" rel="noopener noreferrer">+ <Download className="h-4 w-4 mr-1.5" />+ {t('invoices.action.downloadPdf')}+ </a>+ </Button>+ </div>+ <InvoiceDocumentView document={data} />+ </div>+ </div>+ )+}diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex a8ccac06..fbcb2dc6 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -3,7 +3,7 @@ import { useRegisterPageChatContext } from '@/lib/page-chat-context'import { getAccountName } from '@/lib/account-utils'import { AccountIcon } from '@/components/account-icon'import { currentMonth, monthRange, monthFromRange } from '@/lib/month-utils'-import { useNavigate, useSearchParams } from 'react-router-dom'+import { Link, useNavigate, useSearchParams } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'@@ -35,7 +35,7 @@ import {TableRow,} from '@/components/ui/table'import { Skeleton } from '@/components/ui/skeleton'-import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Clock, HelpCircle, Info, Paperclip, Trash2, Users, X, EyeClosed, SlidersHorizontal } from 'lucide-react'+import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Clock, HelpCircle, Info, Paperclip, Trash2, Users, X, EyeClosed, SlidersHorizontal, Receipt } from 'lucide-react'import type { Transaction, Rule, InstallmentSeriesInput, TransactionApplyScope, TransactionEditPayload } from '@/types'import { RuleDialog, type RuleDialogInitialData } from '@/components/rule-dialog'import { PageHeader } from '@/components/page-header'@@ -1110,6 +1110,29 @@ export default function TransactionsPage() {})}</span>)}+ {/* The invoice this settles. Same badge shape as the split+ and transfer markers beside it, and absent entirely in a+ workspace without the invoicing module — the server does+ not send the field there. */}+ {/* One badge per invoice this row settles: a payout net of+ fees settles several, and showing only the last one read+ as if the others had never been paid. */}+ {(tx.invoice_links ?? []).map((link) => (+ <Link+ key={link.invoice_id}+ to={`/invoices/${link.invoice_id}`}+ onClick={(e) => e.stopPropagation()}+ title={t('transactions.invoiceBadgeTooltip')}+ className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-emerald-700 bg-emerald-50 border border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-900 px-1.5 py-0.5 rounded-full hover:bg-emerald-100 dark:hover:bg-emerald-950/70 transition-colors"+ >+ <Receipt className="h-3 w-3" />+ {link.external_number+ ? t('transactions.invoiceBadge', { number: link.external_number })+ : link.number != null+ ? t('transactions.invoiceBadge', { number: link.number })+ : t('transactions.invoiceBadgeNoNumber')}+ </Link>+ ))}{!!tx.transfer_pair_id && (<span className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-blue-600 bg-blue-50 border border-blue-200 px-1.5 py-0.5 rounded-full"><ArrowLeftRight className="h-3 w-3" />diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex f50036db..54614832 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -217,7 +217,22 @@ export interface AccountSummary {projected_expenses_primary?: number | null}+/** Set when this transaction settles an invoice. Absent in workspaces+ * without the invoicing module — the query behind it does not run there. */+export interface TransactionInvoiceLink {+ invoice_id: string+ number: number | null+ series: string | null+ /** The name an imported invoice arrived with; it carries no number of+ * ours, so the badge reads this instead. */+ external_number: string | null+ amount: string+}+export interface Transaction {+ /** Every invoice this transaction settles — a payout net of fees+ * settles several. Absent in a workspace without the module. */+ invoice_links?: TransactionInvoiceLink[] | nullid: stringuser_id: stringaccount_id: string | null@@ -1007,3 +1022,282 @@ export interface ReportResponse {composition: ReportCompositionItem[]category_trend: CategoryTrendItem[]}++// --- Invoices -------------------------------------------------------------+// The ledger of what clients owe. Only reachable from a business+// workspace: the module resolver leaves `invoices` out of a personal+// workspace's `enabled_modules`, so nothing below is ever fetched there.++/** A decision a human took. Never PATCHed directly — each one has its own+ * endpoint, because a status that changed always has a reason. */+export type InvoiceStatus = 'draft' | 'open' | 'void' | 'uncollectible'++/** Which side of the ledger a document sits on. Everything the UI writes+ * today is a receivable; `payable` exists so supplier documents have+ * somewhere to land without a migration when that path arrives. */+export type InvoiceDirection = 'receivable' | 'payable'++/** What the UI renders. The three terminal decisions above, plus the four+ * facts the server computes from allocations and the due date. Nothing+ * here is stored in a column. */+export type InvoiceState =+ | 'draft'+ | 'open'+ | 'partial'+ | 'paid'+ | 'overdue'+ | 'void'+ | 'uncollectible'++export interface InvoiceLine {+ id: string+ description: string+ quantity: string+ unit: string | null+ unit_price: string+ tax_rate: string | null+ total: string+ position: number+}++export interface InvoiceLineInput {+ description: string+ quantity: string+ /** What the quantity counts — hours, words, pieces. Free text, because+ * a list here would be a guess about somebody else's trade. */+ unit?: string | null+ unit_price: string+ tax_rate?: string | null+}++export interface InvoiceAllocation {+ id: string+ transaction_id: string | null+ credit_note_id: string | null+ amount: string+ method: string+ allocated_at: string+ transaction: {+ id: string+ description: string | null+ date: string | null+ amount: string | null+ } | null+}++/** What a filed document proves. Roles, not file types — a nota fiscal,+ * a facture and a Rechnung are all `fiscal`, and each locale names it. */+export type InvoiceAttachmentKind = 'bill' | 'fiscal' | 'receipt' | 'contract' | 'other'++export interface InvoiceAttachment {+ id: string+ invoice_id: string+ /** The system that produced or delivered the file — a payment+ * provider, a fiscal-document integration, a mailbox. Null when a+ * person uploaded it here. */+ source: string | null+ /** Its id in that system, when it has one. */+ external_id: string | null+ kind: InvoiceAttachmentKind+ /** True on the one file that *is* the document. Downloading the invoice+ * hands this file over instead of a page drawn from our own fields. */+ is_primary: boolean+ document_number: string | null+ issued_at: string | null+ filename: string+ content_type: string+ size: number+ created_at: string+}++export interface Invoice {+ id: string+ payee_id: string | null+ payee: { id: string; name: string } | null+ document_type: string+ direction: InvoiceDirection+ origin: string+ external_source: string | null+ external_id: string | null+ number: number | null+ series: string | null+ /** The name an imported document arrived with, reproduced verbatim.+ * Null on anything we wrote, which our own counter names instead. */+ external_number: string | null+ status: InvoiceStatus+ state: InvoiceState+ issue_date: string+ due_date: string+ /** The accrual date — competência / fait générateur / Leistungsdatum.+ * Defaults to `issue_date` and diverges when work was delivered in a+ * different period from the one it was billed in. */+ competence_date: string | null+ sent_at: string | null+ currency: string+ subtotal: string+ discount: string+ tax_total: string+ total: string+ amount_paid: string+ balance: string+ days_overdue: number+ notes: string | null+ internal_notes: string | null+ custom_fields: Record<string, string> | null+ /** Frozen at issuance: issuer, counterparty and labels as they were.+ * Rendered instead of live settings so changing a logo never rewrites+ * a document the client already received.+ *+ * `unknown` rather than `any`: the shape is the server's and it grows+ * (locale and payment details joined it after the first version), so+ * every reader asserts the one field it wants instead of the type+ * quietly promising all of them. */+ snapshot: Record<string, unknown> | null+ /** Present once a shareable link exists. Null until someone asks for+ * one, and null again once revoked. */+ share_token: string | null+ lines: InvoiceLine[]+ allocations: InvoiceAllocation[]+ created_at: string+}++export interface InvoiceAgingBuckets {+ current: string+ d1_30: string+ d31_60: string+ d61_90: string+ d90_plus: string+}++export interface InvoiceSummary {+ outstanding: string+ overdue_amount: string+ overdue_count: number+ received_this_month: string+ buckets: InvoiceAgingBuckets+ upcoming: Invoice[]+}++export interface InvoiceCustomFieldDef {+ key: string+ label: string+ required?: boolean+}++export interface InvoiceTemplate {+ /** Overrides only. Anything left out falls back to the pack for the+ * issuer's language, resolved server-side. */+ labels?: Record<string, string>+ custom_fields?: InvoiceCustomFieldDef[]+}++export interface InvoiceSettings {+ /** A starting point that fills the next three fields, not a mode: each+ * one stays individually overridable afterwards. */+ preset: 'tracking' | 'document'+ document_required: boolean+ initial_state: 'draft' | 'open'+ tax_fields: 'hidden' | 'optional' | 'required'+ default_payment_terms_days: number+ number_prefix: string | null+ series: string | null+ next_number: number+ /** The uploaded mark, addressed by an id that never changes for a+ * given file. Null when none was uploaded. */+ logo_id: string | null+ issuer_display_name: string | null+ footer_note: string | null+ /** Free text: a Pix key, an IBAN, a routing number. Shown on the+ * document; never parsed. */+ payment_details: string | null+ accent_color: string | null+ template: InvoiceTemplate | null+}++/** The invoice resolved into a document: what the PDF prints and what the+ * preview shows, from one definition on the server. Nothing here is+ * recomputed on this side — a second implementation is how the two+ * would come to disagree. */+export interface InvoiceDocumentParty {+ name: string | null+ legal_name?: string | null+ address: string | null+ email?: string | null+ /** Already masked server-side, because the PDF has no frontend to ask. */+ tax_ids: { label: string; value: string }[]+}++export interface InvoiceDocumentLine {+ description: string+ quantity: string+ unit: string | null+ unit_price: string+ total: string+ tax_rate: string | null+}++export interface InvoiceDocumentPayload {+ number: string | null+ status: InvoiceStatus+ state: InvoiceState+ issue_date: string+ due_date: string+ currency: string+ subtotal: string+ discount: string+ tax_total: string+ total: string+ amount_paid: string+ balance: string+ issuer: InvoiceDocumentParty+ client: InvoiceDocumentParty+ lines: InvoiceDocumentLine[]+ labels: Record<string, string>+ accent_color: string+ logo_url: string | null+ payment_details: string | null+ notes: string | null+ footer_note: string | null+ custom_fields: { label: string; value: string }[]+ /** On a payable the parties are already swapped server-side; this is+ * carried so the page can say "received" instead of "issued". */+ direction: InvoiceDirection+ /** False when the invoice is only tracking money — the common case+ * where the fiscal document was issued somewhere else entirely. */+ has_line_items: boolean+ /** Set when a real document was filed under this invoice. When it is,+ * 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+}++export interface IssuerTaxId {+ kind: string+ value: string+}++export interface IssuerProfile {+ legal_name: string | null+ address: string | null+ tax_jurisdiction: string | null+ tax_ids: IssuerTaxId[]+}++export interface InvoiceShareLink {+ token: string+ /** A path, not a URL: only the browser reliably knows the public origin. */+ path: string+}++/** What the filter bar needs to render itself: which years have+ * invoices, and how many sit in each state for the selected year. */+export interface InvoiceFacets {+ years: number[]+ counts: {+ all: number+ open: number+ overdue: number+ paid: number+ draft: number+ }+}