Skip to content

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

feat: enrich payees with contact and fiscal data (#602)

Tássio Noronha0a7498b6b3fd
diff --git a/backend/alembic/versions/070_payee_fiscal_data.py b/backend/alembic/versions/070_payee_fiscal_data.py
new file mode 100644
index 00000000..b6fd6065
--- /dev/null
+++ b/backend/alembic/versions/070_payee_fiscal_data.py
@@ -0,0 +1,151 @@
+"""enrich payees with contact + fiscal data, and give workspaces a tax jurisdiction
+
+Revision ID: 070
+Revises: 069
+Create Date: 2026-08-14
+
+Three additive changes, none of them requiring a backfill:
+
+ - Contact columns on `payees`, all nullable. Sync creates a payee for
+ every merchant a card touches, and the overwhelming majority keep every
+ one of these null forever. That is the expected end state, not an
+ incomplete migration.
+ - `payee_tax_ids`, one row per fiscal document. Rows rather than columns
+ because a counterparty legitimately has several (CNPJ plus state and
+ municipal registrations in Brazil, Partita IVA plus Codice Fiscale plus
+ an SDI code in Italy), and keyed by `kind` rather than by position so a
+ stored value keeps its meaning regardless of which jurisdiction pack was
+ loaded when it was written.
+ - `workspaces.tax_jurisdiction`, which selects that pack. Nullable, and
+ null is a working configuration: the registry falls back to free-text
+ documents, so a country without a pack works on day one.
+
+Plus one change that is not additive, and is here rather than later because
+later is too late: `payees.source`, and the retirement of the `merchant`
+value from `payees.type`.
+
+`type` now holds a legal nature (`person` or `company`) or null. It used to
+also hold `merchant`, which is a *role* — something a counterparty does,
+not what it legally is. That value was the only thing distinguishing the
+hundreds of rows sync creates from card descriptors, so it is harvested
+into `source` before being dropped rather than discarded.
+
+`source` has to be added now: provenance is only knowable at the moment of
+insert, so any payee created before the column exists could never be
+classified afterwards. The seeding below is the one and only chance to
+recover it for existing rows, and it is an inference, not a record — a
+payee somebody typed in by hand and left at the old `merchant` default is
+indistinguishable from one sync created, and lands in `sync`.
+"""
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects import postgresql
+
+revision: str = "070"
+down_revision: Union[str, None] = "069"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.add_column("payees", sa.Column("email", sa.String(length=255), nullable=True))
+ op.add_column("payees", sa.Column("phone", sa.String(length=50), nullable=True))
+ op.add_column("payees", sa.Column("address", sa.String(length=500), nullable=True))
+ op.add_column("payees", sa.Column("website", sa.String(length=255), nullable=True))
+
+ op.add_column(
+ "workspaces",
+ sa.Column("tax_jurisdiction", sa.String(length=10), nullable=True),
+ )
+
+ op.create_table(
+ "payee_tax_ids",
+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("payee_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("kind", sa.String(length=30), nullable=False),
+ sa.Column("value", sa.String(length=60), nullable=False),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.ForeignKeyConstraint(["payee_id"], ["payees.id"], ondelete="CASCADE"),
+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),
+ sa.PrimaryKeyConstraint("id"),
+ # One document of a given kind per payee. A second CNPJ on the same
+ # counterparty is a data-entry mistake, not a valid state.
+ sa.UniqueConstraint("payee_id", "kind", name="uq_payee_tax_id_kind"),
+ )
+ op.create_index("ix_payee_tax_ids_payee_id", "payee_tax_ids", ["payee_id"])
+ op.create_index("ix_payee_tax_ids_workspace_id", "payee_tax_ids", ["workspace_id"])
+ # Matching a payment to a counterparty by document is the lookup this
+ # table exists to make cheap.
+ op.create_index(
+ "ix_payee_tax_ids_workspace_kind_value",
+ "payee_tax_ids",
+ ["workspace_id", "kind", "value"],
+ )
+
+ # Added with a default so existing rows are valid immediately, then the
+ # default is dropped: provenance must be stated by whoever inserts, never
+ # silently assumed for future writes.
+ op.add_column(
+ "payees",
+ sa.Column(
+ "source",
+ sa.String(length=20),
+ nullable=False,
+ server_default="manual",
+ ),
+ )
+ # Harvest the signal `merchant` was carrying before retiring it. This is
+ # the last moment it exists.
+ op.execute("UPDATE payees SET source = 'sync' WHERE type = 'merchant'")
+ op.alter_column("payees", "source", server_default=None)
+
+ # `merchant` is not a legal nature, and no honest one can be derived from
+ # a bank descriptor, so those rows become unknown rather than being
+ # guessed into `company`.
+ #
+ # The server default has to go with it. An insert that omits `type` —
+ # which is what the bulk sync path emits, since it never sets one —
+ # would otherwise be handed `merchant` by the database and quietly
+ # resurrect the value this migration exists to retire. Nothing in the
+ # test suite would notice: tests build their schema from the model,
+ # which never carried this default, so only the migrated database has
+ # it.
+ op.alter_column(
+ "payees",
+ "type",
+ existing_type=sa.String(length=20),
+ nullable=True,
+ server_default=None,
+ )
+ op.execute("UPDATE payees SET type = NULL WHERE type = 'merchant'")
+
+
+def downgrade() -> None:
+ # Restore `merchant` for the rows it was inferred from. Anything whose
+ # legal nature was set after this migration keeps it.
+ op.execute("UPDATE payees SET type = 'merchant' WHERE type IS NULL")
+ op.alter_column(
+ "payees",
+ "type",
+ existing_type=sa.String(length=20),
+ nullable=False,
+ server_default="merchant",
+ )
+ op.drop_column("payees", "source")
+ op.drop_index("ix_payee_tax_ids_workspace_kind_value", table_name="payee_tax_ids")
+ op.drop_index("ix_payee_tax_ids_workspace_id", table_name="payee_tax_ids")
+ op.drop_index("ix_payee_tax_ids_payee_id", table_name="payee_tax_ids")
+ op.drop_table("payee_tax_ids")
+ op.drop_column("workspaces", "tax_jurisdiction")
+ op.drop_column("payees", "website")
+ op.drop_column("payees", "address")
+ op.drop_column("payees", "phone")
+ op.drop_column("payees", "email")
diff --git a/backend/app/api/fiscal.py b/backend/app/api/fiscal.py
new file mode 100644
index 00000000..dd8330bf
--- /dev/null
+++ b/backend/app/api/fiscal.py
@@ -0,0 +1,82 @@
+"""What the active workspace's jurisdiction asks for.
+
+The frontend needs labels, masks and ordering to render a document field; the
+backend needs normalisation and validation to accept one. Both come from the
+same definition, served here, so the two cannot drift into disagreeing about
+what a CNPJ looks like.
+
+The response is presentation metadata only. It carries no workspace data and
+changes only when the deployment's packs change, so it caches like
+`/api/info`.
+"""
+from fastapi import APIRouter, Depends
+
+from app.core.workspace_context import WorkspaceContext, current_workspace
+from app.fiscal.registry import (
+ TaxIdKind,
+ available_jurisdictions,
+ pack_for,
+ spec_for,
+)
+
+router = APIRouter(prefix="/api/fiscal", tags=["fiscal"])
+
+
+def _kind_payload(kind: TaxIdKind, offered: bool) -> dict:
+ spec = spec_for(kind)
+ return {
+ "kind": kind.value,
+ "label_key": spec.label_key,
+ "mask": spec.mask,
+ # True when this jurisdiction asks for it. Everything else stays
+ # selectable: the counterparty's country is not the workspace's, so a
+ # BR workspace still has to be able to store a German VAT number.
+ "offered": offered,
+ }
+
+
[email protected]("/jurisdictions")
+async def list_jurisdictions():
+ """Codes a pack ships for, for the workspace settings selector.
+
+ An empty jurisdiction is a valid choice, not a missing one, so the
+ frontend offers it alongside these.
+ """
+ return {"jurisdictions": available_jurisdictions()}
+
+
[email protected]("/tax-id-kinds")
+async def list_tax_id_kinds(ctx: WorkspaceContext = Depends(current_workspace)):
+ """Document kinds for the active workspace, plus which country uses what.
+
+ Two lists, because the picker needs both:
+
+ - `kinds`: every document, with the ones this jurisdiction asks for
+ first and flagged `offered`. The rest stay selectable, since a
+ counterparty's country is not the workspace's.
+ - `jurisdictions`: the country-to-documents map, so the picker can
+ group by country and be searched by country name. It has to come
+ from here: which documents a country uses *is* the pack, and a
+ second copy in the frontend would drift from it.
+ """
+ pack = pack_for(ctx.workspace.tax_jurisdiction)
+ offered = list(pack.kinds)
+ rest = [kind for kind in TaxIdKind if kind not in offered]
+ return {
+ "jurisdiction": pack.code or None,
+ "kinds": [_kind_payload(kind, True) for kind in offered]
+ + [_kind_payload(kind, False) for kind in rest],
+ "jurisdictions": [
+ {
+ "code": code,
+ # `other` is appended to every pack and would be noise
+ # repeated under each country; the picker offers it once.
+ "kinds": [
+ kind.value
+ for kind in pack_for(code).kinds
+ if kind is not TaxIdKind.OTHER
+ ],
+ }
+ for code in available_jurisdictions()
+ ],
+ }
diff --git a/backend/app/api/workspaces.py b/backend/app/api/workspaces.py
index 68b81aac..947ee6c2 100644
--- a/backend/app/api/workspaces.py
+++ b/backend/app/api/workspaces.py
@@ -114,6 +114,7 @@ async def create_workspace_endpoint(
kind=body.kind,
default_currency=body.default_currency,
locale=body.locale,
+ tax_jurisdiction=body.tax_jurisdiction,
icon=body.icon,
color=body.color,
self_membership=body.self_membership,
diff --git a/backend/app/core/workspace_autostamp.py b/backend/app/core/workspace_autostamp.py
index 7213ec78..0b166b72 100644
--- a/backend/app/core/workspace_autostamp.py
+++ b/backend/app/core/workspace_autostamp.py
@@ -31,7 +31,7 @@ from app.models.goal import Goal
from app.models.group import Group, GroupMember
from app.models.group_settlement import GroupSettlement
from app.models.import_log import ImportLog
-from app.models.payee import Payee, PayeeMapping
+from app.models.payee import Payee, PayeeMapping, PayeeTaxId
from app.models.recurring_transaction import RecurringTransaction
from app.models.rule import Rule
from app.models.transaction import Transaction
@@ -57,6 +57,7 @@ _AUTOSTAMP_MODELS = (
ImportLog,
Payee,
PayeeMapping,
+ PayeeTaxId,
RecurringTransaction,
Rule,
Transaction,
@@ -106,6 +107,7 @@ _PARENT_LOOKUPS: tuple[tuple[str, str], ...] = (
("connection_id", "app.models.bank_connection:BankConnection"),
("asset_id", "app.models.asset:Asset"),
("group_id", "app.models.group:Group"),
+ ("payee_id", "app.models.payee:Payee"),
("transaction_id", "app.models.transaction:Transaction"),
("agent_id", "app.agents.models.agent:Agent"),
)
diff --git a/backend/app/fiscal/__init__.py b/backend/app/fiscal/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/backend/app/fiscal/jurisdictions/ar.toml b/backend/app/fiscal/jurisdictions/ar.toml
new file mode 100644
index 00000000..56f30f05
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ar.toml
@@ -0,0 +1,4 @@
+# Argentina. The CUIT identifies companies and the self-employed alike;
+# the CUIL is the same number issued to an employee.
+code = "AR"
+kinds = ["cuit"]
diff --git a/backend/app/fiscal/jurisdictions/at.toml b/backend/app/fiscal/jurisdictions/at.toml
new file mode 100644
index 00000000..dfc80711
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/at.toml
@@ -0,0 +1,4 @@
+# Austria. The UID-Nummer is the VAT number; the domestic Steuernummer
+# does not go on an invoice.
+code = "AT"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/au.toml b/backend/app/fiscal/jurisdictions/au.toml
new file mode 100644
index 00000000..4e4a171e
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/au.toml
@@ -0,0 +1,4 @@
+# Australia. The ABN goes on every tax invoice; the ACN it derives from
+# identifies the company at ASIC.
+code = "AU"
+kinds = ["abn"]
diff --git a/backend/app/fiscal/jurisdictions/be.toml b/backend/app/fiscal/jurisdictions/be.toml
new file mode 100644
index 00000000..2c5b4a84
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/be.toml
@@ -0,0 +1,4 @@
+# Belgium. One enterprise number, quoted as the VAT number with a BE
+# prefix.
+code = "BE"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/br.toml b/backend/app/fiscal/jurisdictions/br.toml
new file mode 100644
index 00000000..298ae237
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/br.toml
@@ -0,0 +1,4 @@
+# Brazil. CNPJ for companies, CPF for people, plus the state and municipal
+# registrations that NFS-e asks for.
+code = "BR"
+kinds = ["cnpj", "cpf", "ie", "im"]
diff --git a/backend/app/fiscal/jurisdictions/ca.toml b/backend/app/fiscal/jurisdictions/ca.toml
new file mode 100644
index 00000000..79ab8898
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ca.toml
@@ -0,0 +1,4 @@
+# Canada. The Business Number is the root; GST/HST adds an RT program
+# suffix to it.
+code = "CA"
+kinds = ["ca_bn"]
diff --git a/backend/app/fiscal/jurisdictions/ch.toml b/backend/app/fiscal/jurisdictions/ch.toml
new file mode 100644
index 00000000..e863f368
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ch.toml
@@ -0,0 +1,4 @@
+# Switzerland. One UID per company, reused as the VAT number with an MWST
+# suffix. Not in the EU, so no intra-EU VAT id.
+code = "CH"
+kinds = ["ch_uid"]
diff --git a/backend/app/fiscal/jurisdictions/cl.toml b/backend/app/fiscal/jurisdictions/cl.toml
new file mode 100644
index 00000000..4c17d1bb
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/cl.toml
@@ -0,0 +1,4 @@
+# Chile. One RUT per taxpayer, company or person. Its check character may
+# be a K, which is why it is stored as text and carries no mask.
+code = "CL"
+kinds = ["cl_rut"]
diff --git a/backend/app/fiscal/jurisdictions/cn.toml b/backend/app/fiscal/jurisdictions/cn.toml
new file mode 100644
index 00000000..881b1636
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/cn.toml
@@ -0,0 +1,4 @@
+# China. The USCC replaced the separate business, tax and organisation
+# codes with one eighteen-character identifier.
+code = "CN"
+kinds = ["uscc"]
diff --git a/backend/app/fiscal/jurisdictions/co.toml b/backend/app/fiscal/jurisdictions/co.toml
new file mode 100644
index 00000000..4baa9c2a
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/co.toml
@@ -0,0 +1,4 @@
+# Colombia. The NIT is written with a verification digit, but quoting it
+# without one is common and is not an error.
+code = "CO"
+kinds = ["co_nit"]
diff --git a/backend/app/fiscal/jurisdictions/cr.toml b/backend/app/fiscal/jurisdictions/cr.toml
new file mode 100644
index 00000000..4733f102
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/cr.toml
@@ -0,0 +1,3 @@
+# Costa Rica. One cedula, juridica for a company and fisica for a person.
+code = "CR"
+kinds = ["cr_cedula"]
diff --git a/backend/app/fiscal/jurisdictions/cz.toml b/backend/app/fiscal/jurisdictions/cz.toml
new file mode 100644
index 00000000..b43e7b98
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/cz.toml
@@ -0,0 +1,4 @@
+# Czechia. ICO is the company register id, DIC the tax one, which is the
+# ICO behind a CZ prefix.
+code = "CZ"
+kinds = ["ico", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/de.toml b/backend/app/fiscal/jurisdictions/de.toml
new file mode 100644
index 00000000..e0ce0e89
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/de.toml
@@ -0,0 +1,4 @@
+# Germany. Two numbers that get confused routinely: the USt-IdNr is the
+# intra-EU VAT id, the Steuernummer is the domestic one.
+code = "DE"
+kinds = ["vat", "steuernummer"]
diff --git a/backend/app/fiscal/jurisdictions/dk.toml b/backend/app/fiscal/jurisdictions/dk.toml
new file mode 100644
index 00000000..2d6f86da
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/dk.toml
@@ -0,0 +1,4 @@
+# Denmark. The CVR number is the company register id, and the VAT number
+# is the same digits behind a DK prefix.
+code = "DK"
+kinds = ["cvr", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/do.toml b/backend/app/fiscal/jurisdictions/do.toml
new file mode 100644
index 00000000..f38fff0d
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/do.toml
@@ -0,0 +1,4 @@
+# Dominican Republic. The RNC for companies; an individual is billed
+# against their cedula, which uses the same field.
+code = "DO"
+kinds = ["rnc"]
diff --git a/backend/app/fiscal/jurisdictions/es.toml b/backend/app/fiscal/jurisdictions/es.toml
new file mode 100644
index 00000000..27a30dd8
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/es.toml
@@ -0,0 +1,3 @@
+# Spain. NIF covers the DNI and NIE shapes.
+code = "ES"
+kinds = ["es_nif", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/fi.toml b/backend/app/fiscal/jurisdictions/fi.toml
new file mode 100644
index 00000000..c719e546
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/fi.toml
@@ -0,0 +1,3 @@
+# Finland. The Y-tunnus becomes the VAT number behind an FI prefix.
+code = "FI"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/fr.toml b/backend/app/fiscal/jurisdictions/fr.toml
new file mode 100644
index 00000000..9f10935c
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/fr.toml
@@ -0,0 +1,3 @@
+# France. SIRET identifies the establishment.
+code = "FR"
+kinds = ["siret", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/gb.toml b/backend/app/fiscal/jurisdictions/gb.toml
new file mode 100644
index 00000000..3a01f89f
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/gb.toml
@@ -0,0 +1,4 @@
+# United Kingdom. Its VAT numbers still fit the shared shape, so they use the
+# same kind; only the country prefix differs.
+code = "GB"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/gr.toml b/backend/app/fiscal/jurisdictions/gr.toml
new file mode 100644
index 00000000..4898e26a
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/gr.toml
@@ -0,0 +1,4 @@
+# Greece. The AFM is the tax number, quoted as the VAT number with an EL
+# prefix, which is why the prefix does not match the country code.
+code = "GR"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/gt.toml b/backend/app/fiscal/jurisdictions/gt.toml
new file mode 100644
index 00000000..64dd6fef
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/gt.toml
@@ -0,0 +1,3 @@
+# Guatemala. The NIT check character may be a K, so it is stored as text.
+code = "GT"
+kinds = ["gt_nit"]
diff --git a/backend/app/fiscal/jurisdictions/hu.toml b/backend/app/fiscal/jurisdictions/hu.toml
new file mode 100644
index 00000000..182f590a
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/hu.toml
@@ -0,0 +1,4 @@
+# Hungary. The adoszam carries the VAT and county codes as suffixes, so it
+# is quoted at either eight or eleven digits.
+code = "HU"
+kinds = ["adoszam", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/id.toml b/backend/app/fiscal/jurisdictions/id.toml
new file mode 100644
index 00000000..dd4e9861
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/id.toml
@@ -0,0 +1,4 @@
+# Indonesia. The NPWP moved to sixteen digits with the NIK migration, so
+# both lengths are in circulation.
+code = "ID"
+kinds = ["npwp"]
diff --git a/backend/app/fiscal/jurisdictions/ie.toml b/backend/app/fiscal/jurisdictions/ie.toml
new file mode 100644
index 00000000..5b9a6d79
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ie.toml
@@ -0,0 +1,3 @@
+# Ireland. The VAT number doubles as the tax reference for companies.
+code = "IE"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/in.toml b/backend/app/fiscal/jurisdictions/in.toml
new file mode 100644
index 00000000..589ac176
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/in.toml
@@ -0,0 +1,4 @@
+# India. The GSTIN is per state, so one company registered in several
+# states holds several. The PAN inside it is the entity-level id.
+code = "IN"
+kinds = ["gstin", "pan"]
diff --git a/backend/app/fiscal/jurisdictions/it.toml b/backend/app/fiscal/jurisdictions/it.toml
new file mode 100644
index 00000000..b4c1ca71
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/it.toml
@@ -0,0 +1,4 @@
+# Italy. Partita IVA for businesses, Codice Fiscale for individuals, and the
+# SDI destination code that e-invoicing routes on.
+code = "IT"
+kinds = ["partita_iva", "codice_fiscale", "sdi", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/jp.toml b/backend/app/fiscal/jurisdictions/jp.toml
new file mode 100644
index 00000000..f04d7adc
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/jp.toml
@@ -0,0 +1,4 @@
+# Japan. The corporate number is issued to registered entities; sole
+# proprietors have none and invoice under their qualified invoice number.
+code = "JP"
+kinds = ["jp_corporate"]
diff --git a/backend/app/fiscal/jurisdictions/lu.toml b/backend/app/fiscal/jurisdictions/lu.toml
new file mode 100644
index 00000000..1a04a2ae
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/lu.toml
@@ -0,0 +1,3 @@
+# Luxembourg.
+code = "LU"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/mx.toml b/backend/app/fiscal/jurisdictions/mx.toml
new file mode 100644
index 00000000..806e624c
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/mx.toml
@@ -0,0 +1,4 @@
+# Mexico. The RFC covers companies and individuals, the trailing homoclave
+# being what distinguishes two taxpayers with the same name and birth date.
+code = "MX"
+kinds = ["rfc"]
diff --git a/backend/app/fiscal/jurisdictions/nl.toml b/backend/app/fiscal/jurisdictions/nl.toml
new file mode 100644
index 00000000..f1dc4544
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/nl.toml
@@ -0,0 +1,4 @@
+# Netherlands. The BTW-id is the VAT number; the older BTW-nummer is not
+# used on invoices any more.
+code = "NL"
+kinds = ["vat"]
diff --git a/backend/app/fiscal/jurisdictions/no.toml b/backend/app/fiscal/jurisdictions/no.toml
new file mode 100644
index 00000000..11123b2e
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/no.toml
@@ -0,0 +1,4 @@
+# Norway. Outside the EU, so there is no intra-EU VAT id: a
+# VAT-registered company appends MVA to its organisasjonsnummer.
+code = "NO"
+kinds = ["no_orgnr"]
diff --git a/backend/app/fiscal/jurisdictions/nz.toml b/backend/app/fiscal/jurisdictions/nz.toml
new file mode 100644
index 00000000..b5ca08d1
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/nz.toml
@@ -0,0 +1,4 @@
+# New Zealand. The NZBN identifies the entity; GST registration uses the
+# IRD number, which is not a separate field on an invoice.
+code = "NZ"
+kinds = ["nzbn"]
diff --git a/backend/app/fiscal/jurisdictions/pe.toml b/backend/app/fiscal/jurisdictions/pe.toml
new file mode 100644
index 00000000..863395f2
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/pe.toml
@@ -0,0 +1,4 @@
+# Peru. The RUC prefix says what kind of taxpayer it is: 10 for a person,
+# 20 for a company.
+code = "PE"
+kinds = ["pe_ruc"]
diff --git a/backend/app/fiscal/jurisdictions/ph.toml b/backend/app/fiscal/jurisdictions/ph.toml
new file mode 100644
index 00000000..cb2d4803
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ph.toml
@@ -0,0 +1,4 @@
+# Philippines. The TIN gains a branch code suffix for each place of
+# business.
+code = "PH"
+kinds = ["ph_tin"]
diff --git a/backend/app/fiscal/jurisdictions/pl.toml b/backend/app/fiscal/jurisdictions/pl.toml
new file mode 100644
index 00000000..fce5611c
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/pl.toml
@@ -0,0 +1,4 @@
+# Poland. The NIP is the tax number; the intra-EU VAT id is the same
+# digits behind a PL prefix.
+code = "PL"
+kinds = ["nip", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/pt.toml b/backend/app/fiscal/jurisdictions/pt.toml
new file mode 100644
index 00000000..52c113df
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/pt.toml
@@ -0,0 +1,4 @@
+# Portugal. The NIF identifies companies and individuals alike; VAT is the
+# intra-EU number for cross-border invoicing.
+code = "PT"
+kinds = ["pt_nif", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/ro.toml b/backend/app/fiscal/jurisdictions/ro.toml
new file mode 100644
index 00000000..60dbaf58
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ro.toml
@@ -0,0 +1,4 @@
+# Romania. The CUI is the company id; prefixed with RO it becomes the VAT
+# number, and only VAT-registered companies have one.
+code = "RO"
+kinds = ["ro_cui", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/ru.toml b/backend/app/fiscal/jurisdictions/ru.toml
new file mode 100644
index 00000000..6fe71c22
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ru.toml
@@ -0,0 +1,4 @@
+# Russia. The INN is ten digits for an organisation and twelve for a
+# person; the KPP that accompanies it identifies the branch, not the entity.
+code = "RU"
+kinds = ["inn"]
diff --git a/backend/app/fiscal/jurisdictions/se.toml b/backend/app/fiscal/jurisdictions/se.toml
new file mode 100644
index 00000000..071429de
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/se.toml
@@ -0,0 +1,4 @@
+# Sweden. The organisationsnummer identifies the company; VAT adds the SE
+# prefix and a 01 suffix.
+code = "SE"
+kinds = ["se_orgnr", "vat"]
diff --git a/backend/app/fiscal/jurisdictions/ua.toml b/backend/app/fiscal/jurisdictions/ua.toml
new file mode 100644
index 00000000..da72cd9e
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/ua.toml
@@ -0,0 +1,3 @@
+# Ukraine. EDRPOU for legal entities.
+code = "UA"
+kinds = ["edrpou"]
diff --git a/backend/app/fiscal/jurisdictions/us.toml b/backend/app/fiscal/jurisdictions/us.toml
new file mode 100644
index 00000000..c60fa75a
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/us.toml
@@ -0,0 +1,4 @@
+# United States. The EIN is the business identifier; there is no nationwide
+# individual equivalent that belongs on an invoice.
+code = "US"
+kinds = ["ein"]
diff --git a/backend/app/fiscal/jurisdictions/uy.toml b/backend/app/fiscal/jurisdictions/uy.toml
new file mode 100644
index 00000000..cbd51786
--- /dev/null
+++ b/backend/app/fiscal/jurisdictions/uy.toml
@@ -0,0 +1,3 @@
+# Uruguay. The RUT is what DGI invoices are issued against.
+code = "UY"
+kinds = ["uy_rut"]
diff --git a/backend/app/fiscal/registry.py b/backend/app/fiscal/registry.py
new file mode 100644
index 00000000..709c473c
--- /dev/null
+++ b/backend/app/fiscal/registry.py
@@ -0,0 +1,270 @@
+"""Jurisdiction packs: which documents a country asks for, in what order.
+
+The split that makes this work, and the one thing to preserve if this file is
+ever refactored:
+
+ - **A kind defines the document.** How to normalise it, how to validate it,
+ how to mask it, what to call it. One definition, in code, used everywhere.
+ A CNPJ is fourteen digits with a check digit whether the workspace is set
+ to Brazil, to Germany, or to nothing at all, so a stored value stays
+ comparable and a document typed in one workspace means the same in the
+ next.
+ - **A jurisdiction chooses from them.** A pack is a country code and an
+ ordered list of kinds, nothing more. It cannot weaken a validator, cannot
+ rename a document, and cannot make the same kind behave differently than
+ it does elsewhere.
+
+That split is deliberate and was arrived at the hard way: an earlier version
+let packs carry their own `normalise`, and a German VAT number stored from a
+Brazilian workspace came out spaced differently than the same number stored
+from a German one.
+
+Two further properties:
+
+ - **A pack suggests; it never restricts.** It sets what a workspace is
+ *offered*. Every kind stays storable in every workspace, because the
+ counterparty's country is not the workspace's: a Brazilian consultancy
+ billing a Berlin client needs `vat`, and the BR pack must not forbid it.
+ - **No pack is a working configuration.** An unset or unknown
+ `tax_jurisdiction` resolves to FALLBACK: free text under `other`, no
+ mask, no validation. Packs are enhancement, never a prerequisite, so a
+ country nobody has contributed yet is usable today.
+
+Adding a country is one TOML file. Adding a *document* is a new `TaxIdKind`
+plus one entry in KIND_SPECS, and a named validator if its format is
+checkable. Both are pull requests, which is the point: a document that no
+code understands is a document no export can use.
+"""
+import tomllib
+from dataclasses import dataclass
+from enum import Enum
+from functools import lru_cache
+from pathlib import Path
+
+from app.fiscal.validators import NORMALISERS, VALIDATORS
+
+PACK_DIR = Path(__file__).parent / "jurisdictions"
+
+
+class TaxIdKind(str, Enum):
+ """Every document the product can store.
+
+ Closed on purpose. A free-form string would make the stored value
+ uninterpretable, which is the failure this whole design exists to avoid.
+
+ A kind names **one specific document**, never a category. Portugal's and
+ Spain's national numbers are both called NIF and are different documents
+ with different check rules, so they are different kinds. `vat` is the one
+ genuinely shared scheme: the country prefix is part of the value.
+ """
+
+ # Brazil
+ CNPJ = "cnpj"
+ CPF = "cpf"
+ IE = "ie"
+ IM = "im"
+ # Iberia
+ PT_NIF = "pt_nif"
+ ES_NIF = "es_nif"
+ # European VAT, including the UK, whose numbers still fit the shape
+ VAT = "vat"
+ # Germany's domestic number, distinct from its USt-IdNr
+ STEUERNUMMER = "steuernummer"
+ # Italy
+ PARTITA_IVA = "partita_iva"
+ CODICE_FISCALE = "codice_fiscale"
+ SDI = "sdi"
+ # France
+ SIRET = "siret"
+ # United States
+ EIN = "ein"
+ # Rest of Europe. Prefixed where the acronym is not unique: SE and NO both
+ # call theirs an organisasjons/organisationsnummer, and they check
+ # differently.
+ NIP = "nip"
+ SE_ORGNR = "se_orgnr"
+ NO_ORGNR = "no_orgnr"
+ CVR = "cvr"
+ ICO = "ico"
+ ADOSZAM = "adoszam"
+ RO_CUI = "ro_cui"
+ CH_UID = "ch_uid"
+ INN = "inn"
+ EDRPOU = "edrpou"
+ # Latin America
+ CUIT = "cuit"
+ RFC = "rfc"
+ CL_RUT = "cl_rut"
+ UY_RUT = "uy_rut"
+ CO_NIT = "co_nit"
+ GT_NIT = "gt_nit"
+ PE_RUC = "pe_ruc"
+ CR_CEDULA = "cr_cedula"
+ RNC = "rnc"
+ # Rest of the world
+ CA_BN = "ca_bn"
+ ABN = "abn"
+ NZBN = "nzbn"
+ JP_CORPORATE = "jp_corporate"
+ GSTIN = "gstin"
+ PAN = "pan"
+ NPWP = "npwp"
+ PH_TIN = "ph_tin"
+ USCC = "uscc"
+ # The escape hatch. Always offered, never validated.
+ OTHER = "other"
+
+
+@dataclass(frozen=True)
+class KindSpec:
+ """What one document is, independent of who asks for it."""
+
+ kind: TaxIdKind
+ label_key: str
+ # Presentation only: the frontend applies it, the backend ignores it.
+ mask: str | None = None
+ normalise: str = "trim"
+ validate: str = "none"
+
+ def normalised(self, value: str) -> str:
+ return NORMALISERS[self.normalise](value)
+
+ def error_for(self, value: str) -> str | None:
+ """None when acceptable, else a short machine-readable reason."""
+ if not value:
+ return "empty"
+ return VALIDATORS[self.validate](value)
+
+
+def _spec(
+ kind: TaxIdKind, normalise: str = "trim", validate: str = "none", mask: str | None = None
+) -> KindSpec:
+ return KindSpec(
+ kind=kind,
+ label_key=f"fiscal.kind.{kind.value}",
+ mask=mask,
+ normalise=normalise,
+ validate=validate,
+ )
+
+
+#: One definition per document. `ie` and `im` are unvalidated on purpose: the
+#: twenty-seven Brazilian state schemes disagree with each other, and "ISENTO"
+#: is a legitimate value.
+#:
+#: A mask is only given to a document of **fixed** length. Masks are applied as
+#: the user types and truncate at the template's width, so putting one on a
+#: variable-length document mangles the short form of it: a seven-digit Chilean
+#: RUT under an eight-digit mask reads back as `12.345.67-8`. Those kinds are
+#: shown as typed instead, which is correct if plainer.
+KIND_SPECS: dict[TaxIdKind, KindSpec] = {
+ TaxIdKind.CNPJ: _spec(TaxIdKind.CNPJ, "digits", "br_cnpj", "##.###.###/####-##"),
+ TaxIdKind.CPF: _spec(TaxIdKind.CPF, "digits", "br_cpf", "###.###.###-##"),
+ TaxIdKind.IE: _spec(TaxIdKind.IE, "upper_alnum"),
+ TaxIdKind.IM: _spec(TaxIdKind.IM, "upper_alnum"),
+ TaxIdKind.PT_NIF: _spec(TaxIdKind.PT_NIF, "digits", "pt_nif", "### ### ###"),
+ TaxIdKind.ES_NIF: _spec(TaxIdKind.ES_NIF, "upper_alnum", "es_nif"),
+ TaxIdKind.VAT: _spec(TaxIdKind.VAT, "upper_alnum", "eu_vat_format"),
+ TaxIdKind.STEUERNUMMER: _spec(TaxIdKind.STEUERNUMMER, "digits", "de_steuernummer"),
+ TaxIdKind.PARTITA_IVA: _spec(TaxIdKind.PARTITA_IVA, "digits", "it_partita_iva"),
+ TaxIdKind.CODICE_FISCALE: _spec(TaxIdKind.CODICE_FISCALE, "upper_alnum", "it_codice_fiscale"),
+ TaxIdKind.SDI: _spec(TaxIdKind.SDI, "upper_alnum"),
+ TaxIdKind.SIRET: _spec(TaxIdKind.SIRET, "digits", "fr_siret", "### ### ### #####"),
+ TaxIdKind.EIN: _spec(TaxIdKind.EIN, "digits", "us_ein", "##-#######"),
+ # Rest of Europe
+ TaxIdKind.NIP: _spec(TaxIdKind.NIP, "digits", "pl_nip", "###-###-##-##"),
+ TaxIdKind.SE_ORGNR: _spec(TaxIdKind.SE_ORGNR, "digits", "se_orgnr", "######-####"),
+ TaxIdKind.NO_ORGNR: _spec(TaxIdKind.NO_ORGNR, "digits", "no_orgnr", "### ### ###"),
+ TaxIdKind.CVR: _spec(TaxIdKind.CVR, "digits", "dk_cvr"),
+ TaxIdKind.ICO: _spec(TaxIdKind.ICO, "digits", "cz_ico"),
+ TaxIdKind.ADOSZAM: _spec(TaxIdKind.ADOSZAM, "digits", "hu_adoszam"),
+ TaxIdKind.RO_CUI: _spec(TaxIdKind.RO_CUI, "digits", "ro_cui"),
+ # The mask supplies the CHE prefix, so it reads back whole even when only
+ # the nine digits were typed.
+ TaxIdKind.CH_UID: _spec(TaxIdKind.CH_UID, "upper_alnum", "ch_uid", "CHE-###.###.###"),
+ TaxIdKind.INN: _spec(TaxIdKind.INN, "digits", "ru_inn"),
+ TaxIdKind.EDRPOU: _spec(TaxIdKind.EDRPOU, "digits", "ua_edrpou"),
+ # Latin America
+ TaxIdKind.CUIT: _spec(TaxIdKind.CUIT, "digits", "ar_cuit", "##-########-#"),
+ # `upper_compact` rather than `upper_alnum`: an RFC may contain `&`, which
+ # dropping would turn a valid document into a different one.
+ TaxIdKind.RFC: _spec(TaxIdKind.RFC, "upper_compact", "mx_rfc"),
+ TaxIdKind.CL_RUT: _spec(TaxIdKind.CL_RUT, "upper_alnum", "cl_rut"),
+ TaxIdKind.UY_RUT: _spec(TaxIdKind.UY_RUT, "digits", "uy_rut"),
+ TaxIdKind.CO_NIT: _spec(TaxIdKind.CO_NIT, "digits", "co_nit"),
+ TaxIdKind.GT_NIT: _spec(TaxIdKind.GT_NIT, "upper_alnum"),
+ TaxIdKind.PE_RUC: _spec(TaxIdKind.PE_RUC, "digits", "pe_ruc"),
+ TaxIdKind.CR_CEDULA: _spec(TaxIdKind.CR_CEDULA, "digits", "cr_cedula"),
+ TaxIdKind.RNC: _spec(TaxIdKind.RNC, "digits", "do_rnc"),
+ # Rest of the world
+ TaxIdKind.CA_BN: _spec(TaxIdKind.CA_BN, "digits", "ca_bn", "### ### ###"),
+ TaxIdKind.ABN: _spec(TaxIdKind.ABN, "digits", "au_abn", "## ### ### ###"),
+ TaxIdKind.NZBN: _spec(TaxIdKind.NZBN, "digits", "nz_nzbn"),
+ TaxIdKind.JP_CORPORATE: _spec(TaxIdKind.JP_CORPORATE, "digits", "jp_corporate"),
+ TaxIdKind.GSTIN: _spec(TaxIdKind.GSTIN, "upper_alnum", "in_gstin"),
+ TaxIdKind.PAN: _spec(TaxIdKind.PAN, "upper_alnum", "in_pan"),
+ TaxIdKind.NPWP: _spec(TaxIdKind.NPWP, "digits", "id_npwp"),
+ TaxIdKind.PH_TIN: _spec(TaxIdKind.PH_TIN, "digits", "ph_tin"),
+ TaxIdKind.USCC: _spec(TaxIdKind.USCC, "upper_alnum", "cn_uscc"),
+ TaxIdKind.OTHER: _spec(TaxIdKind.OTHER, "trim"),
+}
+
+
+def spec_for(kind: TaxIdKind) -> KindSpec:
+ """The definition of a document. Never jurisdiction-dependent."""
+ return KIND_SPECS[kind]
+
+
+@dataclass(frozen=True)
+class JurisdictionPack:
+ code: str
+ #: Ordered. The first is what the UI defaults to; `other` is always last.
+ kinds: tuple[TaxIdKind, ...]
+
+
+#: What a deployment with no jurisdiction set gets. Empty of opinions rather
+#: than quietly defaulting to somebody's country.
+FALLBACK = JurisdictionPack(code="", kinds=(TaxIdKind.OTHER,))
+
+
+def _load_pack(path: Path) -> JurisdictionPack:
+ raw = tomllib.loads(path.read_text(encoding="utf-8"))
+ code = str(raw["code"]).upper()
+ kinds = [TaxIdKind(name) for name in raw["kinds"]]
+ for kind in kinds:
+ if kind not in KIND_SPECS:
+ raise ValueError(f"{path.name}: {kind.value} has no spec")
+ # `other` is always available, so any jurisdiction can hold a document
+ # its pack never anticipated.
+ if TaxIdKind.OTHER not in kinds:
+ kinds.append(TaxIdKind.OTHER)
+ return JurisdictionPack(code=code, kinds=tuple(kinds))
+
+
+@lru_cache(maxsize=1)
+def _packs() -> dict[str, JurisdictionPack]:
+ """Parsed once per process. The files ship with the image."""
+ return {pack.code: pack for pack in (_load_pack(p) for p in sorted(PACK_DIR.glob("*.toml")))}
+
+
+def available_jurisdictions() -> list[str]:
+ """Codes a pack exists for, for the settings selector."""
+ return sorted(_packs())
+
+
+def pack_for(jurisdiction: str | None) -> JurisdictionPack:
+ """The pack for a workspace, or FALLBACK when unset or unshipped."""
+ if not jurisdiction:
+ return FALLBACK
+ return _packs().get(jurisdiction.strip().upper(), FALLBACK)
+
+
+def normalise_and_validate(kind: TaxIdKind, value: str) -> tuple[str, str | None]:
+ """Store-ready value, plus a reason when it should be refused.
+
+ Takes no jurisdiction: a document is checked by what it is, not by who
+ is holding it. The jurisdiction decides only what a workspace is offered.
+ """
+ spec = spec_for(kind)
+ normalised = spec.normalised(value)
+ return normalised, spec.error_for(normalised)
diff --git a/backend/app/fiscal/validators.py b/backend/app/fiscal/validators.py
new file mode 100644
index 00000000..28723ed2
--- /dev/null
+++ b/backend/app/fiscal/validators.py
@@ -0,0 +1,507 @@
+"""Named validators and normalisers for fiscal document values.
+
+A jurisdiction pack never carries code. It names a validator, and the name
+resolves here. That keeps a pack reviewable as data, keeps it safe to load
+from outside the repo one day, and keeps validation on the server where it
+belongs: the mask in the browser is a convenience, never the check.
+
+Two rules hold for everything in this file:
+
+ - **Nothing here touches the network.** Confirming a VAT number against
+ VIES would tell a third party who this workspace bills. A format check
+ that runs locally is worth less and costs nothing.
+ - **A validator only rejects what is certainly wrong.** These documents
+ end up on invoices, so catching a typo is worth it; guessing at a
+ format that varies by state or by year is not. Where the rule is not
+ globally defined, the validator is `none` and says so.
+"""
+from collections.abc import Callable
+
+# ---------------------------------------------------------------------------
+# normalisation — what gets stored
+# ---------------------------------------------------------------------------
+def normalise_digits(value: str) -> str:
+ """Keep digits only. For documents that are numbers wearing punctuation."""
+ return "".join(c for c in value if c.isdigit())
+
+
+def normalise_upper_alnum(value: str) -> str:
+ """Upper-case, drop separators. For VAT-shaped ids with a country prefix."""
+ return "".join(c for c in value.upper() if c.isalnum())
+
+
+def normalise_upper_compact(value: str) -> str:
+ """Upper-case, drop separators, keep every other character.
+
+ For documents where a symbol is part of the value: a Mexican RFC may
+ contain `&` and `Ñ`, and `upper_alnum` would silently delete the `&`,
+ turning a valid document into a different one.
+ """
+ return "".join(c for c in value.upper() if not c.isspace() and c not in "-./")
+
+
+def normalise_trim(value: str) -> str:
+ """Collapse surrounding whitespace and nothing else."""
+ return value.strip()
+
+
+NORMALISERS: dict[str, Callable[[str], str]] = {
+ "digits": normalise_digits,
+ "upper_alnum": normalise_upper_alnum,
+ "upper_compact": normalise_upper_compact,
+ "trim": normalise_trim,
+}
+
+
+# ---------------------------------------------------------------------------
+# helpers
+# ---------------------------------------------------------------------------
+def _mod11_check(digits: str, weights: list[int]) -> int:
+ """Weighted mod-11 check digit, the shape most BR/PT documents use."""
+ total = sum(int(d) * w for d, w in zip(digits, weights))
+ remainder = total % 11
+ return 0 if remainder < 2 else 11 - remainder
+
+
+def _weighted_sum(digits: str, weights: list[int]) -> int:
+ return sum(int(d) * w for d, w in zip(digits, weights))
+
+
+def _digits_len(value: str, *lengths: int) -> str | None:
+ """The check shared by every document whose only certain rule is its size."""
+ if not value.isdigit():
+ return "invalid"
+ return None if len(value) in lengths else "length"
+
+
+def _luhn_ok(digits: str) -> bool:
+ total = 0
+ for index, char in enumerate(reversed(digits)):
+ digit = int(char)
+ if index % 2 == 1:
+ digit *= 2
+ if digit > 9:
+ digit -= 9
+ total += digit
+ return total % 10 == 0
+
+
+# ---------------------------------------------------------------------------
+# validators — return None when valid, else a machine-readable reason
+# ---------------------------------------------------------------------------
+def validate_none(value: str) -> None:
+ """Accept anything non-empty.
+
+ Used by `other` and by every document whose format is not globally
+ defined. This is what lets a jurisdiction Securo has never shipped
+ store a real document today.
+ """
+ return None
+
+
+def validate_br_cpf(value: str) -> str | None:
+ if len(value) != 11:
+ return "length"
+ # Repdigits pass the check-digit maths but are never issued.
+ if value == value[0] * 11:
+ return "invalid"
+ first = _mod11_check(value[:9], list(range(10, 1, -1)))
+ second = _mod11_check(value[:10], list(range(11, 1, -1)))
+ if value[9] != str(first) or value[10] != str(second):
+ return "check_digit"
+ return None
+
+
+def validate_br_cnpj(value: str) -> str | None:
+ if len(value) != 14:
+ return "length"
+ if value == value[0] * 14:
+ return "invalid"
+ first = _mod11_check(value[:12], [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
+ second = _mod11_check(value[:13], [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2])
+ if value[12] != str(first) or value[13] != str(second):
+ return "check_digit"
+ return None
+
+
+def validate_pt_nif(value: str) -> str | None:
+ if len(value) != 9:
+ return "length"
+ check = _mod11_check(value[:8], list(range(9, 1, -1)))
+ # PT collapses both mod-11 remainders to 0 rather than to 0 and 1.
+ expected = 0 if check > 9 else check
+ if value[8] != str(expected):
+ return "check_digit"
+ return None
+
+
+def validate_es_nif(value: str) -> str | None:
+ """DNI/NIE shape: eight digits plus a check letter."""
+ if len(value) != 9:
+ return "length"
+ body, letter = value[:8], value[8]
+ # NIE starts with X/Y/Z, which stands in for a leading 0/1/2.
+ if body[0] in "XYZ":
+ body = str("XYZ".index(body[0])) + body[1:]
+ if not body.isdigit():
+ return "invalid"
+ if letter != "TRWAGMYFPDXBNJZSQVHLCKE"[int(body) % 23]:
+ return "check_digit"
+ return None
+
+
+def validate_it_partita_iva(value: str) -> str | None:
+ if len(value) != 11:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ return None if _luhn_ok(value) else "check_digit"
+
+
+def validate_it_codice_fiscale(value: str) -> str | None:
+ """Sixteen alphanumerics. The full check character needs a birth
+ registry, so only the shape is enforced."""
+ if len(value) != 16:
+ return "length"
+ return None if value.isalnum() else "invalid"
+
+
+def validate_fr_siret(value: str) -> str | None:
+ if len(value) != 14:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ return None if _luhn_ok(value) else "check_digit"
+
+
+def validate_de_steuernummer(value: str) -> str | None:
+ """Ten or eleven digits. The state-specific layouts differ and the
+ federal scheme is being rolled out, so length is all that is certain."""
+ if not value.isdigit():
+ return "invalid"
+ return None if len(value) in (10, 11) else "length"
+
+
+def validate_eu_vat_format(value: str) -> str | None:
+ """Two-letter country prefix plus 2 to 13 alphanumerics.
+
+ Format only. Each member state has its own check rule, and confirming
+ the number really exists means calling VIES, which would disclose the
+ workspace's client list to a third party.
+
+ Also covers UK numbers, which kept the same shape after Brexit.
+ """
+ if len(value) < 4 or len(value) > 15:
+ return "length"
+ if not value[:2].isalpha():
+ return "prefix"
+ if not value[2:].isalnum():
+ return "invalid"
+ return None
+
+
+def validate_us_ein(value: str) -> str | None:
+ if not value.isdigit():
+ return "invalid"
+ return None if len(value) == 9 else "length"
+
+
+# ---------------------------------------------------------------------------
+# Latin America
+# ---------------------------------------------------------------------------
+def validate_ar_cuit(value: str) -> str | None:
+ if len(value) != 11:
+ return "length"
+ check = 11 - (_weighted_sum(value[:10], [5, 4, 3, 2, 7, 6, 5, 4, 3, 2]) % 11)
+ # AR folds the two overflow remainders instead of rejecting them.
+ expected = {11: 0, 10: 9}.get(check, check)
+ return None if value[10] == str(expected) else "check_digit"
+
+
+def validate_cl_rut(value: str) -> str | None:
+ """Seven or eight digits plus a check character, which may be K."""
+ if len(value) not in (8, 9):
+ return "length"
+ body, check = value[:-1], value[-1]
+ if not body.isdigit():
+ return "invalid"
+ # Weights cycle 2..7 from the rightmost digit of the body.
+ total = sum(int(d) * (2 + i % 6) for i, d in enumerate(reversed(body)))
+ remainder = 11 - (total % 11)
+ expected = {11: "0", 10: "K"}.get(remainder, str(remainder))
+ return None if check == expected else "check_digit"
+
+
+def validate_co_nit(value: str) -> str | None:
+ """Nine digits, optionally followed by the verification digit.
+
+ The DV is checked only when it is present: writing a NIT without it is
+ common and is not an error.
+ """
+ if len(value) not in (9, 10):
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ if len(value) == 9:
+ return None
+ weights = [41, 37, 29, 23, 19, 17, 13, 7, 3]
+ remainder = _weighted_sum(value[:9], weights) % 11
+ expected = remainder if remainder < 2 else 11 - remainder
+ return None if value[9] == str(expected) else "check_digit"
+
+
+def validate_pe_ruc(value: str) -> str | None:
+ if len(value) != 11:
+ return "length"
+ total = _weighted_sum(value[:10], [5, 4, 3, 2, 7, 6, 5, 4, 3, 2])
+ expected = (11 - (total % 11)) % 10
+ return None if value[10] == str(expected) else "check_digit"
+
+
+def validate_uy_rut(value: str) -> str | None:
+ """Twelve digits. The check rule is not published, so size is the check."""
+ return _digits_len(value, 12)
+
+
+def validate_cr_cedula(value: str) -> str | None:
+ """Nine digits for a person, ten for a company. No published check digit."""
+ return _digits_len(value, 9, 10)
+
+
+def validate_do_rnc(value: str) -> str | None:
+ """Nine digits for a company, eleven for a person's cédula."""
+ return _digits_len(value, 9, 11)
+
+
+# ---------------------------------------------------------------------------
+# Europe outside the VAT-only packs
+# ---------------------------------------------------------------------------
+def validate_pl_nip(value: str) -> str | None:
+ if len(value) != 10:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ remainder = _weighted_sum(value[:9], [6, 5, 7, 2, 3, 4, 5, 6, 7]) % 11
+ # A remainder of 10 cannot be expressed in one digit, so no such NIP exists.
+ if remainder == 10:
+ return "check_digit"
+ return None if value[9] == str(remainder) else "check_digit"
+
+
+def validate_se_orgnr(value: str) -> str | None:
+ if len(value) != 10:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ return None if _luhn_ok(value) else "check_digit"
+
+
+def validate_dk_cvr(value: str) -> str | None:
+ if len(value) != 8:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ total = _weighted_sum(value, [2, 7, 6, 5, 4, 3, 2, 1])
+ return None if total % 11 == 0 else "check_digit"
+
+
+def validate_no_orgnr(value: str) -> str | None:
+ if len(value) != 9:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ remainder = _weighted_sum(value[:8], [3, 2, 7, 6, 5, 4, 3, 2]) % 11
+ if remainder == 1:
+ return "check_digit"
+ expected = 0 if remainder == 0 else 11 - remainder
+ return None if value[8] == str(expected) else "check_digit"
+
+
+def validate_cz_ico(value: str) -> str | None:
+ if len(value) != 8:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ remainder = _weighted_sum(value[:7], [8, 7, 6, 5, 4, 3, 2]) % 11
+ expected = {0: 1, 1: 0}.get(remainder, 11 - remainder)
+ return None if value[7] == str(expected) else "check_digit"
+
+
+def validate_hu_adoszam(value: str) -> str | None:
+ """Eight digits for the core number, eleven with the VAT and county
+ suffixes. The published check rule covers only some issuing years."""
+ return _digits_len(value, 8, 11)
+
+
+def validate_ro_cui(value: str) -> str | None:
+ if not value.isdigit():
+ return "invalid"
+ if not 2 <= len(value) <= 10:
+ return "length"
+ body, check = value[:-1], value[-1]
+ key = "753217532"[-len(body):]
+ expected = (_weighted_sum(body, [int(k) for k in key]) * 10) % 11 % 10
+ return None if check == str(expected) else "check_digit"
+
+
+def validate_ch_uid(value: str) -> str | None:
+ """CHE plus nine digits. The prefix is optional on input."""
+ body = value[3:] if value.startswith("CHE") else value
+ if len(body) != 9:
+ return "length"
+ if not body.isdigit():
+ return "invalid"
+ check = 11 - (_weighted_sum(body[:8], [5, 4, 3, 2, 7, 6, 5, 4]) % 11)
+ if check == 10:
+ return "check_digit"
+ expected = 0 if check == 11 else check
+ return None if body[8] == str(expected) else "check_digit"
+
+
+def validate_ru_inn(value: str) -> str | None:
+ """Ten digits for an organisation, twelve for a person."""
+ if not value.isdigit():
+ return "invalid"
+ if len(value) == 10:
+ expected = _weighted_sum(value[:9], [2, 4, 10, 3, 5, 9, 4, 6, 8]) % 11 % 10
+ return None if value[9] == str(expected) else "check_digit"
+ if len(value) == 12:
+ first = _weighted_sum(value[:10], [7, 2, 4, 10, 3, 5, 9, 4, 6, 8]) % 11 % 10
+ second = _weighted_sum(value[:11], [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]) % 11 % 10
+ if value[10] != str(first) or value[11] != str(second):
+ return "check_digit"
+ return None
+ return "length"
+
+
+def validate_ua_edrpou(value: str) -> str | None:
+ """Eight digits. The check rule differs by registration range, so size
+ is all that is certain."""
+ return _digits_len(value, 8)
+
+
+# ---------------------------------------------------------------------------
+# Rest of the world
+# ---------------------------------------------------------------------------
+def validate_ca_bn(value: str) -> str | None:
+ """Nine digits. The CRA does not publish its check rule, so rejecting on
+ one would risk refusing a real Business Number."""
+ return _digits_len(value, 9)
+
+
+def validate_au_abn(value: str) -> str | None:
+ if len(value) != 11:
+ return "length"
+ if not value.isdigit():
+ return "invalid"
+ weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
+ # The published algorithm subtracts one from the leading digit first.
+ total = (int(value[0]) - 1) * weights[0] + _weighted_sum(value[1:], weights[1:])
+ return None if total % 89 == 0 else "check_digit"
+
+
+def validate_nz_nzbn(value: str) -> str | None:
+ """Thirteen digits, GS1-issued. The check rule is not public."""
+ return _digits_len(value, 13)
+
+
+def validate_jp_corporate(value: str) -> str | None:
+ """Thirteen digits. The leading check digit's rule varies by issuing
+ batch, so only the size is enforced."""
+ return _digits_len(value, 13)
+
+
+def validate_ph_tin(value: str) -> str | None:
+ """Nine digits, or twelve to fifteen with the branch code."""
+ if not value.isdigit():
+ return "invalid"
+ return None if 9 <= len(value) <= 15 else "length"
+
+
+def validate_id_npwp(value: str) -> str | None:
+ """Fifteen digits, or sixteen since the NIK-based migration."""
+ return _digits_len(value, 15, 16)
+
+
+def validate_mx_rfc(value: str) -> str | None:
+ """Twelve characters for a company, thirteen for a person.
+
+ The trailing homoclave is assigned by the SAT and cannot be recomputed,
+ so the shape is the only available check.
+ """
+ if len(value) not in (12, 13):
+ return "length"
+ letters = 3 if len(value) == 12 else 4
+ if not all(c.isalpha() or c in "&Ñ" for c in value[:letters]):
+ return "invalid"
+ if not value[letters : letters + 6].isdigit():
+ return "invalid"
+ return None if value[letters + 6 :].isalnum() else "invalid"
+
+
+def validate_in_gstin(value: str) -> str | None:
+ """Two state digits, a PAN, an entity digit and two trailing characters."""
+ if len(value) != 15:
+ return "length"
+ if not value[:2].isdigit():
+ return "invalid"
+ return "invalid" if validate_in_pan(value[2:12]) else None
+
+
+def validate_in_pan(value: str) -> str | None:
+ if len(value) != 10:
+ return "length"
+ if not (value[:5].isalpha() and value[5:9].isdigit() and value[9].isalpha()):
+ return "invalid"
+ return None
+
+
+def validate_cn_uscc(value: str) -> str | None:
+ """Eighteen characters from a restricted alphabet: I, O, S, V and Z are
+ excluded to keep the code unambiguous when read aloud."""
+ if len(value) != 18:
+ return "length"
+ allowed = set("0123456789ABCDEFGHJKLMNPQRTUWXY")
+ return None if set(value) <= allowed else "invalid"
+
+
+VALIDATORS: dict[str, Callable[[str], str | None]] = {
+ "none": validate_none,
+ "br_cpf": validate_br_cpf,
+ "br_cnpj": validate_br_cnpj,
+ "pt_nif": validate_pt_nif,
+ "es_nif": validate_es_nif,
+ "it_partita_iva": validate_it_partita_iva,
+ "it_codice_fiscale": validate_it_codice_fiscale,
+ "fr_siret": validate_fr_siret,
+ "de_steuernummer": validate_de_steuernummer,
+ "eu_vat_format": validate_eu_vat_format,
+ "us_ein": validate_us_ein,
+ "ar_cuit": validate_ar_cuit,
+ "cl_rut": validate_cl_rut,
+ "co_nit": validate_co_nit,
+ "pe_ruc": validate_pe_ruc,
+ "uy_rut": validate_uy_rut,
+ "cr_cedula": validate_cr_cedula,
+ "do_rnc": validate_do_rnc,
+ "mx_rfc": validate_mx_rfc,
+ "pl_nip": validate_pl_nip,
+ "se_orgnr": validate_se_orgnr,
+ "dk_cvr": validate_dk_cvr,
+ "no_orgnr": validate_no_orgnr,
+ "cz_ico": validate_cz_ico,
+ "hu_adoszam": validate_hu_adoszam,
+ "ro_cui": validate_ro_cui,
+ "ch_uid": validate_ch_uid,
+ "ru_inn": validate_ru_inn,
+ "ua_edrpou": validate_ua_edrpou,
+ "ca_bn": validate_ca_bn,
+ "au_abn": validate_au_abn,
+ "nz_nzbn": validate_nz_nzbn,
+ "jp_corporate": validate_jp_corporate,
+ "ph_tin": validate_ph_tin,
+ "id_npwp": validate_id_npwp,
+ "in_gstin": validate_in_gstin,
+ "in_pan": validate_in_pan,
+ "cn_uscc": validate_cn_uscc,
+}
diff --git a/backend/app/main.py b/backend/app/main.py
index 91581248..983fce1b 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -32,6 +32,7 @@ from app.api.currencies import router as currencies_router
from app.api.export import router as export_router
from app.api.fx_rates import router as fx_rates_router
from app.api.attachments import router as attachments_router
+from app.api.fiscal import router as fiscal_router
from app.api.payees import router as payees_router
from app.api.settings import router as settings_router
from app.api.transactions import router as transactions_router
@@ -177,6 +178,7 @@ app.include_router(currencies_router)
app.include_router(fx_rates_router)
app.include_router(export_router)
app.include_router(attachments_router)
+app.include_router(fiscal_router)
app.include_router(payees_router)
app.include_router(settings_router)
app.include_router(workspaces_router)
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 14b8de34..501df3a8 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -16,7 +16,7 @@ from app.models.asset_transaction import AssetTransaction
from app.models.asset_value import AssetValue
from app.models.fx_rate import FxRate
from app.models.transaction_attachment import TransactionAttachment
-from app.models.payee import Payee, PayeeMapping
+from app.models.payee import Payee, PayeeMapping, PayeeTaxId
from app.models.app_settings import AppSetting
from app.models.goal import Goal
from app.models.credit_card_bill import CreditCardBill
@@ -52,6 +52,7 @@ __all__ = [
"TransactionAttachment",
"Payee",
"PayeeMapping",
+ "PayeeTaxId",
"AppSetting",
"Goal",
"CreditCardBill",
diff --git a/backend/app/models/payee.py b/backend/app/models/payee.py
index 6c97658e..911a5272 100644
--- a/backend/app/models/payee.py
+++ b/backend/app/models/payee.py
@@ -2,7 +2,7 @@ import uuid
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Optional, cast
-from sqlalchemy import Boolean, DateTime, ForeignKey, String
+from sqlalchemy import Boolean, DateTime, ForeignKey, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
@@ -22,9 +22,38 @@ class Payee(Base):
UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True
)
name: Mapped[str] = mapped_column(String(255))
- type: Mapped[str] = mapped_column(String(20), default="merchant")
+ # Legal nature: `person` or `company`, and null when unknown.
+ #
+ # Null is the common case and is not a gap to be filled: sync names a
+ # counterparty from a bank descriptor, and "UBER *TRIP" does not say
+ # whether it is an individual or a company. Guessing would stamp an
+ # inference as a fact, and the answer only matters once a document is
+ # attached — at which point the document itself settles it, a CNPJ
+ # meaning company and a CPF meaning person.
+ #
+ # What this deliberately is *not* is a role. There is no `merchant`
+ # value: being a merchant is something a counterparty does, not what it
+ # legally is, and mixing one role into an enum of two legal natures is
+ # the same category error this model already refuses for `client`.
+ type: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
+ # Where this row came from. Set once, at creation, and never updated:
+ # provenance is only knowable at the moment of insert, so a payee
+ # created before this column existed can never be classified.
+ #
+ # It exists because sync creates payees in bulk — hundreds of card
+ # descriptors — and anything that offers the user a list of
+ # counterparties to bill needs to tell those apart from the handful
+ # somebody typed in on purpose.
+ source: Mapped[str] = mapped_column(String(20), default="manual", nullable=False)
is_favorite: Mapped[bool] = mapped_column(Boolean, default=False)
notes: Mapped[Optional[str]] = mapped_column(String(1000), nullable=True)
+ # How to reach this counterparty. All nullable and all expected to stay
+ # null for the overwhelming majority of rows: sync creates a payee for
+ # every merchant a card touches, and none of them need an address.
+ email: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+ phone: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
+ address: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
+ website: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc))
# Dynamically set by payee_service; not a DB column
@@ -32,6 +61,55 @@ class Payee(Base):
user: Mapped["User"] = relationship()
transactions: Mapped[list["Transaction"]] = relationship(back_populates="payee_entity")
+ tax_ids: Mapped[list["PayeeTaxId"]] = relationship(
+ back_populates="payee", cascade="all, delete-orphan", lazy="selectin"
+ )
+
+
+class PayeeTaxId(Base):
+ """One fiscal document belonging to one payee.
+
+ Rows rather than columns, and keyed by `kind` rather than by position.
+ A stored value therefore keeps its meaning no matter which jurisdiction
+ the workspace is set to or which version of a pack wrote it, and a
+ consumer can ask for "this payee's CNPJ" without loading a pack first.
+
+ A counterparty legitimately carries more than one: Brazil wants CNPJ
+ plus state and municipal registrations for NFS-e, Italy wants Partita
+ IVA plus Codice Fiscale plus an SDI code. Which ones a workspace is
+ *offered* comes from `app.fiscal.registry`; which ones it may *store*
+ is deliberately unrestricted, because the counterparty's country is not
+ the workspace's.
+ """
+
+ __tablename__ = "payee_tax_ids"
+ __table_args__ = (
+ UniqueConstraint("payee_id", "kind", name="uq_payee_tax_id_kind"),
+ )
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ payee_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("payees.id", ondelete="CASCADE"), index=True
+ )
+ # Derivable from the payee, carried anyway: every financial table in
+ # this codebase is directly workspace-scoped, and T6 will filter
+ # documents without wanting a join to do it.
+ workspace_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True
+ )
+ # A value from `fiscal.registry.TaxIdKind`. Stored as a string so a new
+ # kind is a pull request and not a database migration, kept closed by
+ # validation on the way in.
+ kind: Mapped[str] = mapped_column(String(30))
+ # Normalised per kind on write: digits only for CPF/CNPJ, upper-cased
+ # and stripped of separators for VAT-shaped ids. Formatting for display
+ # is the frontend's job, driven by the pack's mask.
+ value: Mapped[str] = mapped_column(String(60))
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
+ )
+
+ payee: Mapped["Payee"] = relationship(back_populates="tax_ids")
class PayeeMapping(Base):
diff --git a/backend/app/models/workspace.py b/backend/app/models/workspace.py
index 7cb77f03..717c07d0 100644
--- a/backend/app/models/workspace.py
+++ b/backend/app/models/workspace.py
@@ -67,6 +67,19 @@ class Workspace(Base):
# `default_currency` etc. from here.
default_currency: Mapped[str] = mapped_column(String(3), default="USD", server_default="USD")
locale: Mapped[Optional[str]] = mapped_column(String(10), nullable=True)
+ # Where this workspace operates fiscally. Selects the jurisdiction pack
+ # that names and validates fiscal documents, and the axis any future
+ # threshold or tax date keys on.
+ #
+ # Emphatically NOT `locale`. A Brazilian who reads the interface in
+ # English still files in Brazil, and a German who prefers Portuguese
+ # does not inherit Brazilian invoicing. Anything fiscal that branches on
+ # `locale` is a bug.
+ #
+ # 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.
+ 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)
created_at: Mapped[datetime] = mapped_column(
diff --git a/backend/app/schemas/payee.py b/backend/app/schemas/payee.py
index 481d62db..2aaffbff 100644
--- a/backend/app/schemas/payee.py
+++ b/backend/app/schemas/payee.py
@@ -1,33 +1,87 @@
import uuid
from datetime import date as _Date, datetime
from decimal import Decimal
-from typing import Optional
+from typing import Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
+from app.fiscal.registry import TaxIdKind
from app.schemas.category import CategoryRead
+#: A counterparty's legal nature, or null when it is not known. Closed, and
+#: closed on *natures* only: a role like "merchant" is something a
+#: counterparty does, and belongs nowhere in this list.
+PayeeType = Literal["person", "company"]
+
+#: Where a row came from. Never accepted from a request body: the server
+#: knows which code path inserted the row, and a client claiming otherwise
+#: would defeat the point.
+PayeeSource = Literal["manual", "sync", "import"]
+
+
+class TaxIdInput(BaseModel):
+ """One fiscal document on the way in.
+
+ `kind` is the closed enum, so an unknown document type is a 422 rather
+ than an uninterpretable row. The value arrives however the user typed it
+ and is normalised per kind before storage; an empty value means "remove
+ this document".
+ """
+
+ kind: TaxIdKind
+ value: str = Field(..., max_length=120)
+
+
+class TaxIdRead(BaseModel):
+ kind: str
+ value: str
+
+ model_config = ConfigDict(from_attributes=True)
+
class PayeeCreate(BaseModel):
name: str = Field(..., max_length=255)
- type: str = "merchant"
+ # Unset by default. A caller who does not know the legal nature says so
+ # by omitting it, rather than being pushed into picking one.
+ type: Optional[PayeeType] = None
notes: Optional[str] = Field(None, max_length=1000)
+ email: Optional[str] = Field(None, max_length=255)
+ phone: Optional[str] = Field(None, max_length=50)
+ address: Optional[str] = Field(None, max_length=500)
+ website: Optional[str] = Field(None, max_length=255)
+ tax_ids: list[TaxIdInput] = []
class PayeeUpdate(BaseModel):
name: Optional[str] = Field(None, max_length=255)
- type: Optional[str] = None
+ type: Optional[PayeeType] = None
is_favorite: Optional[bool] = None
notes: Optional[str] = Field(None, max_length=1000)
+ email: Optional[str] = Field(None, max_length=255)
+ phone: Optional[str] = Field(None, max_length=50)
+ address: Optional[str] = Field(None, max_length=500)
+ website: Optional[str] = Field(None, max_length=255)
+ # Absent leaves the documents alone. Present replaces the whole set, so
+ # the caller sends what should remain rather than a diff.
+ tax_ids: Optional[list[TaxIdInput]] = None
class PayeeRead(BaseModel):
id: uuid.UUID
user_id: uuid.UUID
name: str
- type: str
+ type: Optional[PayeeType] = None
+ # Read-only. Exposed so a client picker can tell the handful of
+ # counterparties somebody entered on purpose from the hundreds sync
+ # created from card descriptors.
+ source: PayeeSource = "manual"
is_favorite: bool
notes: Optional[str] = None
+ email: Optional[str] = None
+ phone: Optional[str] = None
+ address: Optional[str] = None
+ website: Optional[str] = None
+ tax_ids: list[TaxIdRead] = []
created_at: datetime
transaction_count: int = 0
diff --git a/backend/app/schemas/workspace.py b/backend/app/schemas/workspace.py
index b8b0bf7b..d17e62ea 100644
--- a/backend/app/schemas/workspace.py
+++ b/backend/app/schemas/workspace.py
@@ -16,6 +16,9 @@ class WorkspaceRead(BaseModel):
is_archived: bool
default_currency: str
locale: Optional[str] = None
+ # Where the workspace operates fiscally. Never the UI language: see
+ # `models.workspace.Workspace.tax_jurisdiction`.
+ tax_jurisdiction: Optional[str] = None
icon: Optional[str] = None
color: Optional[str] = None
created_at: datetime
@@ -40,6 +43,9 @@ class WorkspaceCreate(BaseModel):
kind: WorkspaceKind = "personal"
default_currency: Optional[str] = Field(default=None, min_length=3, max_length=3)
locale: Optional[str] = Field(default=None, max_length=10)
+ # Configuration, unlike `kind`: a business can move, and a workspace set
+ # up before packs existed needs a way to say where it files.
+ tax_jurisdiction: Optional[str] = Field(default=None, max_length=10)
icon: Optional[str] = Field(default=None, max_length=50)
color: Optional[str] = Field(default=None, max_length=7)
# When True, also add the creator as an `owner` member. When False
@@ -57,6 +63,9 @@ class WorkspaceUpdate(BaseModel):
color: Optional[str] = Field(default=None, max_length=7)
default_currency: Optional[str] = Field(default=None, min_length=3, max_length=3)
locale: Optional[str] = Field(default=None, max_length=10)
+ # Editable, unlike `kind`: a business relocates, and every workspace that
+ # existed before jurisdictions did needs a way to say where it files.
+ tax_jurisdiction: Optional[str] = Field(default=None, max_length=10)
class MemberRead(BaseModel):
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index b9e17490..2e128f66 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -749,7 +749,8 @@ async def import_transactions(
import_payee_raw = getattr(txn_data, "payee_raw", None)
if import_payee_raw:
import_payee_entity = await get_or_create_payee(
- session, user_id, import_payee_raw, workspace_id=workspace_id
+ session, user_id, import_payee_raw, workspace_id=workspace_id,
+ source="import",
)
import_payee_id = import_payee_entity.id
diff --git a/backend/app/services/payee_service.py b/backend/app/services/payee_service.py
index 270fc9b5..c31be048 100644
--- a/backend/app/services/payee_service.py
+++ b/backend/app/services/payee_service.py
@@ -6,9 +6,10 @@ from typing import Optional, cast
from sqlalchemy import CursorResult, case, select, func, update, delete
from sqlalchemy.ext.asyncio import AsyncSession
-from app.models.payee import Payee, PayeeMapping
+from app.models.payee import Payee, PayeeMapping, PayeeTaxId
from app.models.transaction import Transaction
from app.models.category import Category
+from app.fiscal.registry import TaxIdKind, normalise_and_validate
from app.schemas.payee import PayeeCreate, PayeeUpdate
@@ -70,12 +71,22 @@ async def get_or_create_payee(
name: str,
*,
workspace_id: Optional[uuid.UUID] = None,
+ source: str = "sync",
) -> Payee:
"""Find a payee by name (case-insensitive) or create a new one.
`user_id` is kept first for backwards compatibility with import/connection
sync paths. When `workspace_id` is provided, the lookup scopes by workspace;
otherwise the autostamp listener fills it in on insert.
+
+ `source` is stamped only on rows this call creates. An existing payee is
+ returned untouched, so a counterparty somebody entered by hand keeps
+ saying so even after sync sees the same name — the same protection that
+ already keeps sync from overwriting manual edits.
+
+ Defaults to `sync` because that is what this function is for: the bulk
+ path that turns bank descriptors into rows. The CSV importer passes
+ `import` explicitly.
"""
name = name.strip()
if not name:
@@ -94,7 +105,7 @@ async def get_or_create_payee(
if payee:
return payee
- payee = Payee(user_id=user_id, name=name)
+ payee = Payee(user_id=user_id, name=name, source=source)
if workspace_id is not None:
payee.workspace_id = workspace_id
session.add(payee)
@@ -102,6 +113,64 @@ async def get_or_create_payee(
return payee
+async def _apply_tax_ids(
+ session: AsyncSession,
+ payee: Payee,
+ workspace_id: uuid.UUID,
+ incoming: list,
+) -> None:
+ """Replace this payee's fiscal documents with `incoming`.
+
+ Replace rather than merge: the caller sends the set that should remain,
+ which makes removing a document the same operation as changing one and
+ leaves no way to end up with a stale row nobody meant to keep.
+
+ Validation is by document kind and deliberately not by the workspace's
+ jurisdiction. A Brazilian consultancy billing a Berlin client stores a
+ German VAT number, and it is checked as a VAT number.
+ """
+ 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 ValueError(f"invalid_tax_id:{kind.value}:{error}")
+ # One document per kind, enforced by a unique constraint. Keeping the
+ # last silently would discard the caller's earlier value: two CNPJs on
+ # one counterparty is a mistake worth reporting, not resolving.
+ if kind in normalised:
+ raise ValueError(f"duplicate_tax_id:{kind.value}")
+ normalised[kind] = value
+
+ # Queried rather than read off `payee.tax_ids`: a freshly flushed payee
+ # would lazy-load the collection, and lazy IO inside an async session is
+ # exactly the MissingGreenlet this codebase must not hand a user.
+ rows = await session.execute(
+ select(PayeeTaxId).where(PayeeTaxId.payee_id == payee.id)
+ )
+ existing = {row.kind: row for row in rows.scalars().all()}
+ 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 None:
+ session.add(
+ PayeeTaxId(
+ payee_id=payee.id,
+ workspace_id=workspace_id,
+ kind=kind.value,
+ value=value,
+ )
+ )
+ elif row.value != value:
+ row.value = value
+ await session.flush()
+
+
async def create_payee(
session: AsyncSession,
workspace_id: uuid.UUID,
@@ -115,9 +184,13 @@ async def create_payee(
if existing.scalar_one_or_none():
raise ValueError("A payee with this name already exists")
- payee = Payee(user_id=user_id, workspace_id=workspace_id, **data.model_dump())
+ fields = data.model_dump(exclude={"tax_ids"})
+ # Stamped here rather than taken from the request: this is the path a
+ # person went through a form to reach.
+ payee = Payee(user_id=user_id, workspace_id=workspace_id, source="manual", **fields)
session.add(payee)
await session.flush()
+ await _apply_tax_ids(session, payee, workspace_id, data.tax_ids)
# Self-mapping for merge tracking
mapping = PayeeMapping(id=payee.id, user_id=user_id, workspace_id=workspace_id, target_id=payee.id)
@@ -137,6 +210,9 @@ async def update_payee(
return None
update_data = data.model_dump(exclude_unset=True)
+ # Documents are handled separately: they live in their own table and are
+ # replaced as a set, not assigned onto the payee row.
+ tax_ids = update_data.pop("tax_ids", None)
# Check name uniqueness if name is being changed
if "name" in update_data and update_data["name"]:
@@ -153,6 +229,9 @@ async def update_payee(
for key, value in update_data.items():
setattr(payee, key, value)
+ if tax_ids is not None:
+ await _apply_tax_ids(session, payee, workspace_id, data.tax_ids or [])
+
await session.commit()
await session.refresh(payee)
return payee
diff --git a/backend/app/services/workspace_service.py b/backend/app/services/workspace_service.py
index a7ddce7f..640e4ba3 100644
--- a/backend/app/services/workspace_service.py
+++ b/backend/app/services/workspace_service.py
@@ -215,6 +215,7 @@ async def create_workspace(
kind: str = "personal",
default_currency: Optional[str] = None,
locale: Optional[str] = None,
+ tax_jurisdiction: Optional[str] = None,
icon: Optional[str] = None,
color: Optional[str] = None,
self_membership: bool = False,
@@ -241,6 +242,7 @@ async def create_workspace(
managed_by_user_id=creator.id,
default_currency=default_currency or prefs.get("currency_display", "USD"),
locale=workspace_locale,
+ tax_jurisdiction=tax_jurisdiction,
icon=icon,
color=color,
)
diff --git a/backend/tests/test_fiscal_packs_intl.py b/backend/tests/test_fiscal_packs_intl.py
new file mode 100644
index 00000000..4a2080f5
--- /dev/null
+++ b/backend/tests/test_fiscal_packs_intl.py
@@ -0,0 +1,114 @@
+"""Invariants that must hold across every jurisdiction pack.
+
+These are the tests that keep adding a country cheap. Each one fails loudly on
+the mistake it describes, so a new pack is a two-line TOML file and not an
+archaeology exercise.
+"""
+import pytest
+
+from app.fiscal.registry import (
+ KIND_SPECS,
+ TaxIdKind,
+ available_jurisdictions,
+ normalise_and_validate,
+ pack_for,
+ spec_for,
+)
+
+ALL_JURISDICTIONS = available_jurisdictions()
+
+
+def test_every_kind_has_a_spec():
+ missing = [k.value for k in TaxIdKind if k not in KIND_SPECS]
+ assert missing == []
+
+
+def test_every_kind_is_offered_by_some_pack():
+ """A kind no pack lists is unreachable in the picker, so it is dead code
+ that still shows up in the API response."""
+ offered = {kind for code in ALL_JURISDICTIONS for kind in pack_for(code).kinds}
+ orphans = [k.value for k in TaxIdKind if k not in offered]
+ assert orphans == []
+
+
[email protected]("code", ALL_JURISDICTIONS)
+def test_a_pack_offers_at_least_one_document_besides_the_escape_hatch(code):
+ kinds = [k for k in pack_for(code).kinds if k is not TaxIdKind.OTHER]
+ assert kinds, f"{code} offers nothing but `other`, so the pack adds nothing"
+
+
[email protected]("code", ALL_JURISDICTIONS)
+def test_every_pack_ends_with_the_escape_hatch(code):
+ """So a document the pack never anticipated is always storable."""
+ assert pack_for(code).kinds[-1] is TaxIdKind.OTHER
+
+
[email protected]("kind", [k for k in TaxIdKind if KIND_SPECS[k].mask])
+def test_a_mask_is_only_given_to_a_fixed_length_document(kind):
+ """Masks truncate at the template's width when applied as the user types,
+ so a variable-length document under a mask reads back mangled: a
+ seven-digit Chilean RUT in an eight-digit mask becomes `12.345.67-8`.
+
+ The check: feed the mask's own width in digits, and the value must survive
+ validation. A validator that accepts a second, shorter length is the signal
+ that this kind should not carry a mask at all.
+ """
+ spec = spec_for(kind)
+ assert spec.mask is not None # the parametrize filters to masked kinds
+ slots = spec.mask.count("#")
+ # A CH UID's mask supplies its CHE prefix, which the value carries too.
+ filled = ("CHE" if kind is TaxIdKind.CH_UID else "") + "1" * slots
+ _, error = normalise_and_validate(kind, filled)
+ # Not asserting the digits pass the check maths, only that the *length*
+ # the mask produces is the length the validator expects.
+ assert error != "length", (
+ f"{kind.value}'s mask yields {slots} digits, which its validator "
+ f"refuses on length; it should carry no mask"
+ )
+
+
[email protected]("code", ALL_JURISDICTIONS)
+def test_a_pack_cannot_change_what_a_document_is(code):
+ """The load-bearing invariant: a jurisdiction chooses kinds, it never
+ redefines one. The same CNPJ stored from any workspace normalises and
+ validates identically."""
+ stored, error = normalise_and_validate(TaxIdKind.CNPJ, "11.222.333/0001-81")
+ assert stored == "11222333000181"
+ assert error is None
+ # And the pack's own primary document behaves the same regardless of who
+ # asks: `normalise_and_validate` takes no jurisdiction at all.
+ primary = pack_for(code).kinds[0]
+ assert spec_for(primary) is KIND_SPECS[primary]
+
+
+def test_an_unknown_jurisdiction_still_works():
+ """A country nobody has contributed a pack for is usable today."""
+ pack = pack_for("ZW")
+ assert pack.kinds == (TaxIdKind.OTHER,)
+ stored, error = normalise_and_validate(TaxIdKind.OTHER, " BP/1234/2024 ")
+ assert stored == "BP/1234/2024"
+ assert error is None
+
+
+def test_the_currencies_the_product_supports_have_a_pack():
+ """The packs were chosen to cover the currencies already supported, so a
+ workspace can bill in a currency and name the document that goes with it."""
+ from app.api.currencies import CURRENCY_META
+
+ # Currency to the country whose fiscal documents it implies. The euro and
+ # the dollar are shared by many, so they are covered by their members'
+ # own packs rather than mapped here.
+ country_of = {
+ "BRL": "BR", "GBP": "GB", "JPY": "JP", "CAD": "CA", "AUD": "AU",
+ "CHF": "CH", "CNY": "CN", "ARS": "AR", "MXN": "MX", "CLP": "CL",
+ "COP": "CO", "PEN": "PE", "UYU": "UY", "INR": "IN", "SEK": "SE",
+ "DKK": "DK", "NOK": "NO", "PLN": "PL", "CZK": "CZ", "HUF": "HU",
+ "RON": "RO", "CRC": "CR", "IDR": "ID", "DOP": "DO", "RUB": "RU",
+ "GTQ": "GT", "PHP": "PH", "UAH": "UA", "NZD": "NZ", "USD": "US",
+ }
+ uncovered = [
+ code
+ for currency, code in country_of.items()
+ if currency in CURRENCY_META and code not in ALL_JURISDICTIONS
+ ]
+ assert uncovered == []
diff --git a/backend/tests/test_fiscal_registry.py b/backend/tests/test_fiscal_registry.py
new file mode 100644
index 00000000..ebe39251
--- /dev/null
+++ b/backend/tests/test_fiscal_registry.py
@@ -0,0 +1,148 @@
+"""Jurisdiction packs: what they may decide, and what they must not.
+
+Two properties carry the whole design and each has a test that fails loudly
+if someone erodes it: a pack orders and labels but never forbids, and a
+workspace with no jurisdiction is a working configuration rather than a
+broken one.
+"""
+import pytest
+
+from app.fiscal.registry import (
+ FALLBACK,
+ KIND_SPECS,
+ PACK_DIR,
+ JurisdictionPack,
+ TaxIdKind,
+ available_jurisdictions,
+ normalise_and_validate,
+ pack_for,
+ spec_for,
+)
+from app.fiscal.validators import NORMALISERS, VALIDATORS
+
+
+# ---------------------------------------------------------------------------
+# the packs load and stay well-formed
+# ---------------------------------------------------------------------------
+def test_initial_jurisdictions_are_available():
+ """A subset check, not an equality one: pinning the full list would make
+ every contributed pack an edit to this test, which is exactly the friction
+ the pack format exists to remove. What matters is that the packs that
+ shipped first are still there."""
+ available = available_jurisdictions()
+ for code in ("BR", "DE", "ES", "FR", "GB", "IT", "PT", "US"):
+ assert code in available
+ # And the list stays sorted, since the settings selector reads it in order.
+ assert available == sorted(available)
+
+
+def test_every_pack_file_parses_and_only_names_known_kinds():
+ """A pack is data: a country code and an ordered list of kinds. It cannot
+ define a document, so the only way it breaks is naming one that has no
+ spec."""
+ for path in PACK_DIR.glob("*.toml"):
+ pack = pack_for(path.stem.upper())
+ assert isinstance(pack, JurisdictionPack), path.name
+ assert pack.code == path.stem.upper(), path.name
+ assert pack.kinds, path.name
+ for kind in pack.kinds:
+ assert kind in KIND_SPECS, (path.name, kind)
+
+
+def test_every_kind_has_exactly_one_definition():
+ """A document is defined once, in code, and used identically everywhere."""
+ assert set(KIND_SPECS) == set(TaxIdKind)
+ for kind, spec in KIND_SPECS.items():
+ assert spec.kind is kind
+ assert spec.normalise in NORMALISERS, kind
+ assert spec.validate in VALIDATORS, kind
+ assert spec.label_key == f"fiscal.kind.{kind.value}", kind
+
+
+def test_every_pack_offers_other_last():
+ """The escape hatch is always present, so any jurisdiction can hold a
+ document its pack never anticipated."""
+ for code in available_jurisdictions():
+ assert pack_for(code).kinds[-1] is TaxIdKind.OTHER, code
+
+
+def test_pack_order_drives_the_default():
+ assert pack_for("BR").kinds[0] is TaxIdKind.CNPJ
+ assert pack_for("US").kinds[0] is TaxIdKind.EIN
+ assert pack_for("DE").kinds[0] is TaxIdKind.VAT
+
+
+def test_a_pack_cannot_change_what_a_document_is():
+ """The invariant this design turns on: normalisation and validation come
+ from the kind, so the same document behaves identically no matter which
+ jurisdiction is holding it. An earlier version let packs carry their own
+ normaliser and a German VAT number came out spaced differently depending
+ on the workspace."""
+ for jurisdiction in ("BR", "DE", "GB", "ZZ", None):
+ stored, error = normalise_and_validate(TaxIdKind.VAT, "de 123 456 789")
+ assert (stored, error) == ("DE123456789", None), jurisdiction
+
+
+# ---------------------------------------------------------------------------
+# no pack is a working configuration
+# ---------------------------------------------------------------------------
[email protected]("jurisdiction", [None, "", "ZZ", "Atlantis"])
+def test_unset_or_unshipped_jurisdiction_falls_back(jurisdiction):
+ assert pack_for(jurisdiction) is FALLBACK
+
+
+def test_fallback_stores_free_text_without_validating():
+ stored, error = normalise_and_validate(TaxIdKind.OTHER, " ABC-123/x ")
+ assert stored == "ABC-123/x"
+ assert error is None
+
+
+def test_a_country_without_a_pack_can_still_hold_its_document():
+ """The point of the fallback: nobody waits for a pull request to use
+ the product."""
+ stored, error = normalise_and_validate(TaxIdKind.OTHER, "TIN 99-8877")
+ assert error is None and stored == "TIN 99-8877"
+
+
+# ---------------------------------------------------------------------------
+# a pack suggests, it never restricts
+# ---------------------------------------------------------------------------
+def test_a_kind_outside_the_pack_is_still_storable():
+ """A BR workspace billing a Berlin client needs `vat`, and the BR pack
+ must not be able to forbid it. This is the test that keeps the product
+ usable across borders."""
+ assert TaxIdKind.VAT not in pack_for("BR").kinds
+ stored, error = normalise_and_validate(TaxIdKind.VAT, "DE 123 456 789")
+ assert error is None
+ assert stored == "DE123456789"
+
+
+def test_a_kind_outside_the_pack_keeps_its_own_rules():
+ """Storable anywhere does not mean unchecked. A US workspace can hold a
+ Codice Fiscale, and it is still validated as one."""
+ assert TaxIdKind.CODICE_FISCALE not in pack_for("US").kinds
+ assert spec_for(TaxIdKind.CODICE_FISCALE).validate == "it_codice_fiscale"
+ _, error = normalise_and_validate(TaxIdKind.CODICE_FISCALE, "too short")
+ assert error == "length"
+
+
+# ---------------------------------------------------------------------------
+# normalisation is per kind, and it is what gets stored
+# ---------------------------------------------------------------------------
+ "kind,raw,expected",
+ [
+ (TaxIdKind.CNPJ, "11.222.333/0001-81", "11222333000181"),
+ (TaxIdKind.CPF, "529.982.247-25", "52998224725"),
+ (TaxIdKind.VAT, "de 123 456 789", "DE123456789"),
+ (TaxIdKind.EIN, "12-3456789", "123456789"),
+ ],
+)
+def test_values_are_stored_normalised(kind, raw, expected):
+ stored, error = normalise_and_validate(kind, raw)
+ assert (stored, error) == (expected, None)
+
+
+def test_empty_value_is_refused():
+ _, error = normalise_and_validate(TaxIdKind.OTHER, " ")
+ assert error == "empty"
diff --git a/backend/tests/test_fiscal_validators.py b/backend/tests/test_fiscal_validators.py
new file mode 100644
index 00000000..4ea1abc3
--- /dev/null
+++ b/backend/tests/test_fiscal_validators.py
@@ -0,0 +1,129 @@
+"""The named validators a jurisdiction pack points at.
+
+Real documents where a real one is safe to publish (the CNPJ/CPF values here
+are the canonical test numbers), and the failure modes are separated so a
+regression says which rule broke rather than just "invalid".
+"""
+import pytest
+
+from app.fiscal import validators as v
+
+
+# ---------------------------------------------------------------------------
+# Brazil — the only ones with check digits worth enforcing
+# ---------------------------------------------------------------------------
[email protected]("value", ["11222333000181", "34028316000103"])
+def test_valid_cnpj(value):
+ assert v.validate_br_cnpj(value) is None
+
+
+def test_cnpj_failure_modes():
+ assert v.validate_br_cnpj("1122233300018") == "length"
+ assert v.validate_br_cnpj("11222333000199") == "check_digit"
+ # Repdigits satisfy the arithmetic but are never issued.
+ assert v.validate_br_cnpj("11111111111111") == "invalid"
+
+
[email protected]("value", ["52998224725", "11144477735"])
+def test_valid_cpf(value):
+ assert v.validate_br_cpf(value) is None
+
+
+def test_cpf_failure_modes():
+ assert v.validate_br_cpf("5299822472") == "length"
+ assert v.validate_br_cpf("52998224724") == "check_digit"
+ assert v.validate_br_cpf("00000000000") == "invalid"
+
+
+def test_a_typo_in_one_digit_is_caught():
+ """The reason check digits are here at all: these values end up on an
+ invoice and in a contador export."""
+ good = "11222333000181"
+ for index in range(12):
+ broken = good[:index] + str((int(good[index]) + 1) % 10) + good[index + 1 :]
+ assert v.validate_br_cnpj(broken) is not None, broken
+
+
+# ---------------------------------------------------------------------------
+# Iberia
+# ---------------------------------------------------------------------------
+def test_pt_nif():
+ assert v.validate_pt_nif("501442600") is None
+ assert v.validate_pt_nif("501442601") == "check_digit"
+ assert v.validate_pt_nif("50144260") == "length"
+
+
+def test_es_nif_dni_and_nie():
+ assert v.validate_es_nif("12345678Z") is None
+ assert v.validate_es_nif("X1234567L") is None
+ assert v.validate_es_nif("12345678A") == "check_digit"
+ assert v.validate_es_nif("1234567Z") == "length"
+
+
+# ---------------------------------------------------------------------------
+# the rest are shape checks, and that is deliberate
+# ---------------------------------------------------------------------------
+def test_it_documents():
+ assert v.validate_it_partita_iva("00743110157") is None
+ assert v.validate_it_partita_iva("00743110158") == "check_digit"
+ assert v.validate_it_codice_fiscale("RSSMRA85M01H501Z") is None
+ assert v.validate_it_codice_fiscale("RSSMRA85M01H501") == "length"
+
+
+def test_fr_siret_uses_luhn():
+ assert v.validate_fr_siret("73282932000074") is None
+ assert v.validate_fr_siret("73282932000075") == "check_digit"
+
+
+def test_de_steuernummer_is_length_only():
+ """The state layouts disagree and the federal scheme is mid-rollout, so
+ anything stricter would reject real numbers."""
+ assert v.validate_de_steuernummer("1234567890") is None
+ assert v.validate_de_steuernummer("12345678901") is None
+ assert v.validate_de_steuernummer("123456789") == "length"
+ assert v.validate_de_steuernummer("12345abc90") == "invalid"
+
+
+def test_eu_vat_is_format_only():
+ """No VIES call: confirming the number exists would disclose the
+ workspace's client list to a third party."""
+ assert v.validate_eu_vat_format("DE123456789") is None
+ assert v.validate_eu_vat_format("FRAB123456789") is None
+ assert v.validate_eu_vat_format("123456789") == "prefix"
+ assert v.validate_eu_vat_format("DE1") == "length"
+
+
+def test_uk_numbers_use_the_same_shape_check():
+ """GB shares the `vat` kind: after Brexit the scheme differs but the
+ shape does not, and a separate validator would have been dead weight."""
+ assert v.validate_eu_vat_format("GB123456789") is None
+ assert v.validate_eu_vat_format("GB123456789012") is None
+
+
+def test_us_ein():
+ assert v.validate_us_ein("123456789") is None
+ assert v.validate_us_ein("12345678") == "length"
+
+
+def test_validate_none_accepts_anything():
+ """Used by `other` and by documents whose format varies by state, such
+ as the Brazilian Inscrição Estadual."""
+ for value in ("x", "ISENTO", "123.456.789/xyz"):
+ assert v.validate_none(value) is None
+
+
+# ---------------------------------------------------------------------------
+# registry integrity
+# ---------------------------------------------------------------------------
+def test_every_validator_is_reachable_by_name():
+ for name, fn in v.VALIDATORS.items():
+ assert callable(fn), name
+ # A validator returns None or a short reason, never raises on a
+ # plausible input.
+ assert fn("123") is None or isinstance(fn("123"), str), name
+
+
+def test_normalisers_are_idempotent():
+ for name, fn in v.NORMALISERS.items():
+ for value in (" a1-b2 ", "11.222.333/0001-81"):
+ assert fn(fn(value)) == fn(value), name
diff --git a/backend/tests/test_fiscal_validators_intl.py b/backend/tests/test_fiscal_validators_intl.py
new file mode 100644
index 00000000..b889d295
--- /dev/null
+++ b/backend/tests/test_fiscal_validators_intl.py
@@ -0,0 +1,144 @@
+"""Check-digit validators, tested against documents that really exist.
+
+Every case below is a public identifier of a well-known organisation, taken
+from its own filings. That matters more than it looks: a check-digit routine
+written from a prose description can be subtly wrong and still pass any test
+built from numbers the same routine generated. Only a real document proves the
+algorithm, and a wrong algorithm here silently refuses a real user's client.
+
+Where a document's check rule is not published, or varies by issuing year or
+state, the validator checks size and shape only. Those cases assert exactly
+that, so nobody later mistakes the gap for an oversight.
+"""
+import pytest
+
+from app.fiscal.registry import TaxIdKind, normalise_and_validate
+from app.fiscal.validators import VALIDATORS
+
+#: (validator, value, whose document it is)
+REAL_DOCUMENTS = [
+ ("ar_cuit", "30500003193", "Banco de la Nación Argentina"),
+ ("ar_cuit", "30546689979", "YPF"),
+ ("cl_rut", "970040005", "Banco de Chile"),
+ ("cl_rut", "609100001", "Fisco de Chile"),
+ ("co_nit", "8909039388", "Bancolombia, with the verification digit"),
+ ("co_nit", "890903938", "Bancolombia, without it"),
+ ("pe_ruc", "20131312955", "SUNAT"),
+ ("pl_nip", "5260250274", "a Polish company"),
+ ("se_orgnr", "5560360793", "Volvo"),
+ ("dk_cvr", "61126228", "Danske Bank"),
+ ("no_orgnr", "923609016", "Equinor"),
+ ("cz_ico", "45274649", "ČEZ"),
+ ("ch_uid", "CHE116281710", "Nestlé"),
+ ("ch_uid", "116281710", "Nestlé, prefix omitted"),
+ ("ru_inn", "7707083893", "Sberbank"),
+ ("au_abn", "51824753556", "the Australian Taxation Office"),
+ ("ro_cui", "14399840", "a Romanian company"),
+]
+
+#: Validators that verify a check digit, so a single altered digit must fail.
+CHECKED = {
+ "ar_cuit",
+ "cl_rut",
+ "pe_ruc",
+ "pl_nip",
+ "se_orgnr",
+ "dk_cvr",
+ "no_orgnr",
+ "cz_ico",
+ "ch_uid",
+ "ru_inn",
+ "au_abn",
+ "ro_cui",
+}
+
+
[email protected]("validator,value,whose", REAL_DOCUMENTS)
+def test_a_real_document_is_accepted(validator, value, whose):
+ assert VALIDATORS[validator](value) is None, f"refused {whose}'s document"
+
+
+ "validator,value,whose", [c for c in REAL_DOCUMENTS if c[0] in CHECKED]
+)
+def test_one_altered_digit_is_refused(validator, value, whose):
+ """The point of a check digit: a typo must not pass."""
+ altered = value[:-1] + ("1" if value[-1] != "1" else "2")
+ assert VALIDATORS[validator](altered) == "check_digit"
+
+
+def test_a_chilean_rut_check_character_may_be_k():
+ """The reason `cl_rut` is stored as text and carries no mask."""
+ assert VALIDATORS["cl_rut"]("11111112K") is None
+ # The same body with a digit in place of the K is a different, wrong RUT.
+ assert VALIDATORS["cl_rut"]("111111120") == "check_digit"
+
+
+def test_a_colombian_nit_may_omit_its_verification_digit():
+ """Quoting a NIT without the DV is normal practice, not an error."""
+ assert VALIDATORS["co_nit"]("890903938") is None
+ assert VALIDATORS["co_nit"]("8909039388") is None
+ assert VALIDATORS["co_nit"]("8909039380") == "check_digit"
+
+
+def test_a_russian_inn_has_two_lengths():
+ """Ten digits for an organisation, twelve for a person."""
+ assert VALIDATORS["ru_inn"]("7707083893") is None
+ assert VALIDATORS["ru_inn"]("77070838931") == "length"
+
+
+# ---------------------------------------------------------------------------
+# shape-only validators: assert the gap deliberately
+# ---------------------------------------------------------------------------
+SHAPE_ONLY = [
+ # validator, accepted, refused, why the check stops at the shape
+ ("ca_bn", "123456789", "12345678", "the CRA does not publish its check rule"),
+ ("nz_nzbn", "9429030000004", "942903000000", "the NZBN check rule is not public"),
+ ("jp_corporate", "7000012050002", "700001205000", "the leading digit's rule varies"),
+ ("uy_rut", "211003420011", "21100342001", "the DGI check rule is not published"),
+ # Nine digits is a person's cédula and ten a company's, so both pass; the
+ # refused case has to be shorter than either.
+ ("cr_cedula", "3101002771", "31010027", "no published check digit"),
+ ("do_rnc", "101010101", "10101010", "company and cédula lengths differ"),
+ ("ua_edrpou", "00032129", "0003212", "the rule differs by registration range"),
+ ("hu_adoszam", "12345678142", "1234567814", "the published rule covers some years"),
+ ("id_npwp", "012345678901234", "01234567890123", "15 and 16 both circulate"),
+]
+
+
[email protected]("validator,accepted,refused,why", SHAPE_ONLY)
+def test_a_shape_only_validator_checks_size_and_nothing_more(
+ validator, accepted, refused, why
+):
+ assert VALIDATORS[validator](accepted) is None, why
+ assert VALIDATORS[validator](refused) == "length", why
+ # And it does not pretend to verify a check digit.
+ altered = accepted[:-1] + ("1" if accepted[-1] != "1" else "2")
+ assert VALIDATORS[validator](altered) is None, (
+ f"{validator} appears to check a digit it was documented not to: {why}"
+ )
+
+
+def test_a_mexican_rfc_keeps_its_ampersand():
+ """`upper_alnum` would delete the `&`, storing a different document."""
+ stored, error = normalise_and_validate(TaxIdKind.RFC, "ab&940707ie1")
+ assert stored == "AB&940707IE1"
+ assert error is None
+
+
+def test_a_mexican_rfc_rejects_a_letter_where_the_date_goes():
+ # O for 0 is the classic transcription slip in an RFC.
+ assert VALIDATORS["mx_rfc"]("BBA94O707IE1") == "invalid"
+
+
+def test_an_indian_gstin_must_contain_a_well_formed_pan():
+ assert VALIDATORS["in_gstin"]("27AAACR5055K1Z2") is None
+ # Digits where the PAN's leading letters belong.
+ assert VALIDATORS["in_gstin"]("2712ACR5055K1Z2") == "invalid"
+ assert VALIDATORS["in_pan"]("AAAC15055K") == "invalid"
+
+
+def test_a_chinese_uscc_excludes_the_ambiguous_letters():
+ """I, O, S, V and Z are left out so the code survives being read aloud."""
+ assert VALIDATORS["cn_uscc"]("91310000MA1K35Y47B") is None
+ assert VALIDATORS["cn_uscc"]("91310000MA1K35Y47I") == "invalid"
diff --git a/backend/tests/test_payee_service.py b/backend/tests/test_payee_service.py
index 62b41f13..91ab8e3b 100644
--- a/backend/tests/test_payee_service.py
+++ b/backend/tests/test_payee_service.py
@@ -49,11 +49,13 @@ async def _make_account(session: AsyncSession, user: User) -> Account:
@pytest.mark.asyncio
async def test_create_payee(session: AsyncSession, test_user, test_workspace):
- data = PayeeCreate(name="Starbucks", type="merchant")
+ data = PayeeCreate(name="Starbucks", type="company")
payee = await create_payee(session, test_workspace.id, test_user.id, data)
assert payee.name == "Starbucks"
- assert payee.type == "merchant"
+ assert payee.type == "company"
+ # Stamped by the code path, not by the caller: this is the manual one.
+ assert payee.source == "manual"
assert payee.is_favorite is False
assert payee.transaction_count == 0 # type: ignore[attr-defined]
assert payee.user_id == test_user.id
@@ -61,7 +63,7 @@ async def test_create_payee(session: AsyncSession, test_user, test_workspace):
@pytest.mark.asyncio
async def test_create_payee_with_notes(session: AsyncSession, test_user, test_workspace):
- data = PayeeCreate(name="Coffee Shop", type="merchant", notes="Morning coffee")
+ data = PayeeCreate(name="Coffee Shop", type="company", notes="Morning coffee")
payee = await create_payee(session, test_workspace.id, test_user.id, data)
assert payee.notes == "Morning coffee"
@@ -226,7 +228,10 @@ async def test_update_payee(session: AsyncSession, test_user, test_workspace):
assert updated is not None
assert updated.name == "New Name"
assert updated.is_favorite is True
- assert updated.type == "merchant" # unchanged
+ # Unchanged, and unchanged means null: nothing ever stated a legal
+ # nature for this one, which is the resting state now that there is no
+ # catch-all default.
+ assert updated.type is None
@pytest.mark.asyncio
diff --git a/backend/tests/test_payee_tax_ids.py b/backend/tests/test_payee_tax_ids.py
new file mode 100644
index 00000000..9e62c0e9
--- /dev/null
+++ b/backend/tests/test_payee_tax_ids.py
@@ -0,0 +1,148 @@
+"""Fiscal documents on a payee: what is stored, and what is refused.
+
+The `other` kind gets its own attention here because it is the escape hatch:
+it has to accept a document no pack describes, which means it also has to be
+honest about what that costs.
+"""
+import pytest
+from httpx import AsyncClient
+
+
+async def test_other_stores_free_text_untouched(client: AsyncClient, auth_headers, test_workspace):
+ """No mask, no validation, only surrounding whitespace removed. This is
+ what makes a country nobody has contributed a pack for usable today."""
+ resp = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={
+ "name": "Tokyo KK",
+ "type": "company",
+ "tax_ids": [{"kind": "other", "value": " T1234567890123 (houjin bangou) "}],
+ },
+ )
+ assert resp.status_code == 201, resp.text
+ assert resp.json()["tax_ids"] == [
+ {"kind": "other", "value": "T1234567890123 (houjin bangou)"}
+ ]
+
+
+async def test_other_accepts_what_no_validator_understands(
+ client: AsyncClient, auth_headers, test_workspace
+):
+ resp = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={
+ "name": "Unknown Co",
+ "type": "company",
+ "tax_ids": [{"kind": "other", "value": "???-not-a-document-###"}],
+ },
+ )
+ assert resp.status_code == 201, resp.text
+
+
+async def test_duplicate_kind_is_refused_rather_than_silently_collapsed(
+ client: AsyncClient, auth_headers, test_workspace
+):
+ """One document per kind. An earlier version kept the last value and
+ dropped the first without a word, which loses a caller's data."""
+ resp = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={
+ "name": "Two Others",
+ "type": "company",
+ "tax_ids": [
+ {"kind": "other", "value": "AAA-111"},
+ {"kind": "other", "value": "BBB-222"},
+ ],
+ },
+ )
+ assert resp.status_code == 400, resp.text
+ assert "duplicate_tax_id:other" in resp.json()["detail"]
+
+
+async def test_documents_of_different_kinds_coexist(
+ client: AsyncClient, auth_headers, test_workspace
+):
+ resp = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={
+ "name": "Acme BR",
+ "type": "company",
+ "tax_ids": [
+ {"kind": "cnpj", "value": "11.222.333/0001-81"},
+ {"kind": "ie", "value": "ISENTO"},
+ ],
+ },
+ )
+ assert resp.status_code == 201, resp.text
+ stored = {t["kind"]: t["value"] for t in resp.json()["tax_ids"]}
+ assert stored == {"cnpj": "11222333000181", "ie": "ISENTO"}
+
+
+async def test_a_foreign_document_is_stored_and_still_validated(
+ client: AsyncClient, auth_headers, test_workspace
+):
+ """The workspace's jurisdiction does not gate the counterparty's country,
+ but the document is still checked as what it is."""
+ ok = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={"name": "Berlin GmbH", "type": "company",
+ "tax_ids": [{"kind": "vat", "value": "de 123 456 789"}]},
+ )
+ assert ok.status_code == 201, ok.text
+ assert ok.json()["tax_ids"] == [{"kind": "vat", "value": "DE123456789"}]
+
+ bad = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={"name": "Broken GmbH", "type": "company",
+ "tax_ids": [{"kind": "vat", "value": "1"}]},
+ )
+ assert bad.status_code == 400, bad.text
+ assert "invalid_tax_id:vat" in bad.json()["detail"]
+
+
+async def test_emptying_a_document_removes_it(client: AsyncClient, auth_headers, test_workspace):
+ created = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={"name": "Drop Doc", "type": "company",
+ "tax_ids": [{"kind": "cnpj", "value": "11222333000181"},
+ {"kind": "ie", "value": "110042490114"}]},
+ )
+ payee_id = created.json()["id"]
+ patched = await client.patch(
+ f"/api/payees/{payee_id}",
+ headers=auth_headers,
+ json={"tax_ids": [{"kind": "cnpj", "value": "11222333000181"},
+ {"kind": "ie", "value": ""}]},
+ )
+ assert patched.status_code == 200, patched.text
+ assert [t["kind"] for t in patched.json()["tax_ids"]] == ["cnpj"]
+
+
+async def test_omitting_tax_ids_leaves_them_alone(client: AsyncClient, auth_headers, test_workspace):
+ """`tax_ids` absent means "don't touch"; present means "this is the set"."""
+ created = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={"name": "Keep Doc", "type": "company",
+ "tax_ids": [{"kind": "cnpj", "value": "11222333000181"}]},
+ )
+ payee_id = created.json()["id"]
+ patched = await client.patch(
+ f"/api/payees/{payee_id}", headers=auth_headers, json={"name": "Keep Doc Renamed"}
+ )
+ assert patched.status_code == 200, patched.text
+ assert [t["kind"] for t in patched.json()["tax_ids"]] == ["cnpj"]
diff --git a/backend/tests/test_payee_type_and_source.py b/backend/tests/test_payee_type_and_source.py
new file mode 100644
index 00000000..8b705f89
--- /dev/null
+++ b/backend/tests/test_payee_type_and_source.py
@@ -0,0 +1,217 @@
+"""`type` holds a legal nature; `source` holds where the row came from.
+
+These were one field until this migration. `type` also carried `merchant`,
+which is a role rather than a nature, and it was the only thing telling the
+hundreds of rows sync creates apart from the handful somebody typed in. The
+two jobs are now separate, and these tests pin the part that is easy to
+undo by accident: `source` is set by the code path, never by the caller,
+and never rewritten afterwards.
+"""
+import pytest
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.payee import Payee
+from app.schemas.payee import PayeeCreate, PayeeUpdate
+from app.services.payee_service import (
+ create_payee,
+ get_or_create_payee,
+ update_payee,
+)
+
+
+# ---------------------------------------------------------------------------
+# schema shape
+# ---------------------------------------------------------------------------
+def test_no_column_default_hands_back_the_retired_value():
+ """The bulk sync path inserts without naming `type`, so anything the
+ schema fills in on its behalf becomes the effective default for every
+ row sync creates.
+
+ `type` used to carry `DEFAULT 'merchant'`, and leaving it there while
+ retiring the value would have quietly resurrected it on Postgres. This
+ assertion is on the model rather than on behaviour because the test
+ database is built from the model and never has server defaults at all,
+ so a behavioural test here proves nothing about production.
+ """
+ assert Payee.__table__.c.type.server_default is None
+ assert Payee.__table__.c.type.nullable is True
+
+
+def test_provenance_is_required():
+ """A row with no `source` cannot be told apart from one somebody typed
+ in, which is the whole distinction the column exists to make."""
+ assert Payee.__table__.c.source.nullable is False
+
+
+# ---------------------------------------------------------------------------
+# type: a legal nature, and null is a real answer
+# ---------------------------------------------------------------------------
+async def test_a_payee_may_have_no_legal_nature(
+ session: AsyncSession, test_user, test_workspace
+):
+ """The resting state. Sync names a counterparty from a bank descriptor,
+ and "UBER *TRIP" does not say whether it is a person or a company."""
+ payee = await create_payee(
+ session, test_workspace.id, test_user.id, PayeeCreate(name="Uber")
+ )
+ assert payee.type is None
+
+
+async def test_merchant_is_not_a_legal_nature(
+ session: AsyncSession, test_user, test_workspace
+):
+ """The value this migration retired. Being a merchant is something a
+ counterparty does, not what it legally is, so the schema refuses it
+ rather than storing an uninterpretable string."""
+ with pytest.raises(ValueError):
+ # Validated from a mapping rather than written as a keyword, because
+ # that is how the retired value would actually arrive: a JSON body
+ # from a caller still using the old vocabulary, where the type
+ # checker cannot help and only this runtime check stands.
+ PayeeCreate.model_validate({"name": "Padaria", "type": "merchant"})
+
+
+async def test_the_two_natures_round_trip(
+ session: AsyncSession, test_user, test_workspace
+):
+ for nature in ("person", "company"):
+ payee = await create_payee(
+ session,
+ test_workspace.id,
+ test_user.id,
+ PayeeCreate(name=f"Counterparty {nature}", type=nature),
+ )
+ assert payee.type == nature
+
+
+async def test_a_legal_nature_can_be_cleared(
+ session: AsyncSession, test_user, test_workspace
+):
+ """Setting it wrong has to be undoable, so null must be reachable
+ through an update and not only at creation."""
+ payee = await create_payee(
+ session,
+ test_workspace.id,
+ test_user.id,
+ PayeeCreate(name="Reclassify me", type="company"),
+ )
+ updated = await update_payee(
+ session, payee.id, test_workspace.id, PayeeUpdate(type=None, name="Kept")
+ )
+ assert updated is not None
+ assert updated.type is None
+
+
+# ---------------------------------------------------------------------------
+# source: stamped by the path that inserted the row
+# ---------------------------------------------------------------------------
+async def test_the_form_path_is_manual(
+ session: AsyncSession, test_user, test_workspace
+):
+ payee = await create_payee(
+ session, test_workspace.id, test_user.id, PayeeCreate(name="Typed in by hand")
+ )
+ assert payee.source == "manual"
+
+
+async def test_the_bulk_path_is_sync(
+ session: AsyncSession, test_user, test_workspace
+):
+ """What `get_or_create_payee` exists for: turning bank descriptors into
+ rows, hundreds at a time."""
+ payee = await get_or_create_payee(
+ session, test_user.id, "UBER *TRIP", workspace_id=test_workspace.id
+ )
+ assert payee.source == "sync"
+
+
+async def test_the_importer_says_so_explicitly(
+ session: AsyncSession, test_user, test_workspace
+):
+ payee = await get_or_create_payee(
+ session,
+ test_user.id,
+ "FROM A CSV",
+ workspace_id=test_workspace.id,
+ source="import",
+ )
+ assert payee.source == "import"
+
+
+async def test_sync_does_not_relabel_something_entered_by_hand(
+ session: AsyncSession, test_user, test_workspace
+):
+ """The protection that makes `source` worth having.
+
+ A counterparty somebody registered deliberately keeps saying so even
+ after sync meets the same name on a statement. Without this, one sync
+ run would reclassify every hand-entered client as noise and the client
+ picker would hide exactly the rows it exists to show.
+ """
+ typed = await create_payee(
+ session,
+ test_workspace.id,
+ test_user.id,
+ PayeeCreate(name="Acme Consulting", type="company"),
+ )
+ seen_by_sync = await get_or_create_payee(
+ session, test_user.id, "acme consulting", workspace_id=test_workspace.id
+ )
+ assert seen_by_sync.id == typed.id
+ assert seen_by_sync.source == "manual"
+ # And the nature the user stated survives too.
+ assert seen_by_sync.type == "company"
+
+
+async def test_source_is_not_writable_through_the_api(
+ client: AsyncClient, auth_headers
+):
+ """Provenance is a fact about how the row got here. A client that could
+ assert it could hide its own rows among the hand-entered ones."""
+ resp = await client.post(
+ "/api/payees",
+ headers=auth_headers,
+ json={"name": "Claims to be synced", "source": "sync"},
+ )
+ assert resp.status_code == 201
+ assert resp.json()["source"] == "manual"
+
+
+async def test_updating_a_payee_never_moves_its_source(
+ session: AsyncSession, test_user, test_workspace
+):
+ synced = await get_or_create_payee(
+ session, test_user.id, "NETFLIX.COM", workspace_id=test_workspace.id
+ )
+ updated = await update_payee(
+ session,
+ synced.id,
+ test_workspace.id,
+ PayeeUpdate(name="Netflix", type="company"),
+ )
+ assert updated is not None
+ assert updated.source == "sync"
+
+
+async def test_the_api_exposes_source_so_a_picker_can_filter_on_it(
+ client: AsyncClient, auth_headers
+):
+ resp = await client.post(
+ "/api/payees", headers=auth_headers, json={"name": "Visible provenance"}
+ )
+ assert resp.status_code == 201
+ body = resp.json()
+ assert body["source"] == "manual"
+ assert body["type"] is None
diff --git a/backend/tests/test_payees_api.py b/backend/tests/test_payees_api.py
index f15d6a9d..993b6a6e 100644
--- a/backend/tests/test_payees_api.py
+++ b/backend/tests/test_payees_api.py
@@ -80,7 +80,7 @@ async def test_list_payees(client: AsyncClient, auth_headers):
@pytest.mark.asyncio
async def test_list_payees_filters(client: AsyncClient, auth_headers):
- mcd = await _create_payee(client, auth_headers, "McDonalds", type="merchant", notes="Burgers")
+ mcd = await _create_payee(client, auth_headers, "McDonalds", type="company", notes="Burgers")
# Toggle favorite via PATCH since PayeeCreate doesn't take is_favorite
patch_resp = await client.patch(f"/api/payees/{mcd['id']}", headers=auth_headers, json={"is_favorite": True})
assert patch_resp.status_code == 200
@@ -132,12 +132,13 @@ async def test_list_payees_filters(client: AsyncClient, auth_headers):
async def test_create_payee(client: AsyncClient, auth_headers):
resp = await client.post(
"/api/payees", headers=auth_headers,
- json={"name": "Starbucks", "type": "merchant", "notes": "Coffee"},
+ json={"name": "Starbucks", "type": "company", "notes": "Coffee"},
)
assert resp.status_code == 201
data = resp.json()
assert data["name"] == "Starbucks"
- assert data["type"] == "merchant"
+ assert data["type"] == "company"
+ assert data["source"] == "manual"
assert data["notes"] == "Coffee"
assert data["is_favorite"] is False
assert data["transaction_count"] == 0
@@ -191,7 +192,7 @@ async def test_update_payee(client: AsyncClient, auth_headers):
data = resp.json()
assert data["name"] == "NewName"
assert data["is_favorite"] is True
- assert data["type"] == "merchant" # unchanged
+ assert data["type"] is None # unchanged, and never stated
@pytest.mark.asyncio
diff --git a/frontend/src/components/tax-id-kind-picker.tsx b/frontend/src/components/tax-id-kind-picker.tsx
new file mode 100644
index 00000000..91d0ae07
--- /dev/null
+++ b/frontend/src/components/tax-id-kind-picker.tsx
@@ -0,0 +1,217 @@
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Check, ChevronsUpDown } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from '@/components/ui/command'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import { countryFlag } from '@/lib/country-flag'
+import { countryName } from '@/lib/country-name'
+import { taxIdCountry, taxIdFlag } from '@/lib/tax-id-country'
+import type { TaxIdKindOption } from '@/types'
+
+/** Accent-insensitive, so "italia" finds "Itália" and "franca" finds "França". */
+function normalise(value: string): string {
+ return value
+ .normalize('NFD')
+ .replace(/\p{Diacritic}/gu, '')
+ .toLowerCase()
+}
+
+interface Props {
+ /** Every document kind, as served by /api/fiscal/tax-id-kinds. */
+ kinds: TaxIdKindOption[]
+ /** Country to documents, so the list can be grouped and searched by country. */
+ jurisdictions: { code: string; kinds: string[] }[]
+ /** The active workspace's country, listed first. Null when unset. */
+ activeJurisdiction: string | null
+ value: string
+ /**
+ * The document number this row holds. Only used to place a `vat` id, whose
+ * country lives inside the number rather than in the kind.
+ */
+ documentValue: string
+ /** Kinds already used on this payee; shown but not selectable. */
+ used: Set<string>
+ onChange: (kind: string) => void
+}
+
+/**
+ * Picks which fiscal document a row holds.
+ *
+ * Grouped by country and searchable, because the flat list it replaced asked
+ * the user to already know that Partita IVA is Italian and SIRET is French.
+ * Typing "Itália" now surfaces that country's documents, and typing "CNPJ"
+ * finds it directly.
+ *
+ * The grouping is not hardcoded here: which documents a country uses comes
+ * from the jurisdiction packs on the server. A copy in the browser would be a
+ * second source of truth for the same fact.
+ */
+export function TaxIdKindPicker({
+ kinds,
+ jurisdictions,
+ activeJurisdiction,
+ value,
+ documentValue,
+ used,
+ onChange,
+}: Props) {
+ const { t, i18n } = useTranslation()
+ const [open, setOpen] = useState(false)
+ const locale = i18n.language
+
+ const byKind = useMemo(
+ () => new Map(kinds.map((k) => [k.kind, k])),
+ [kinds],
+ )
+ const label = (kind: string) => {
+ const option = byKind.get(kind)
+ return option ? t(option.label_key, kind.toUpperCase()) : kind.toUpperCase()
+ }
+ // From the platform's own locale data rather than the translation files:
+ // forty-odd country names across ten locales would be pure restatement, and
+ // every new pack would add ten more strings to keep in sync.
+ const country = (code: string) => countryName(code, locale)
+ const selectedCountry = taxIdCountry(value, documentValue, jurisdictions)
+ const selectedFlag = taxIdFlag(value, documentValue, jurisdictions)
+ /**
+ * Where the tick goes. A kind is listed under every country that asks for
+ * it, so a Greek VAT id used to show as selected under Germany too, which
+ * reads as though Germany were the choice. When the value tells us the
+ * country, only that country is ticked; while the field is still empty
+ * nothing has narrowed it down, so every instance is.
+ */
+ const isSelected = (kind: string, jurisdiction: string) =>
+ kind === value && (!selectedCountry || selectedCountry === jurisdiction)
+ // JSX rather than a string so the flag can be given room: the group's own
+ // padding puts it flush against the edge otherwise.
+ const groupHeading = (label: string, flag?: string) => (
+ <span className="flex items-center gap-2 pl-1.5">
+ {flag ? <span aria-hidden>{flag}</span> : null}
+ <span>{label}</span>
+ </span>
+ )
+ // Scoped to this picker rather than to CommandGroup itself: the global search
+ // palette uses the same primitive and its headings are spaced as they are on
+ // purpose. Without this the country name sits flush against the first
+ // document under it, so the two read as one line.
+ const groupClass = '[&_[cmdk-group-heading]]:pb-2 [&_[cmdk-group-heading]]:pt-1'
+
+ // The workspace's own country first: it is what the overwhelming majority of
+ // rows will use, and scrolling past seven other countries to reach it would
+ // be the same mistake in a different shape.
+ const groups = useMemo(() => {
+ const ordered = [...jurisdictions].sort((a, b) => {
+ if (a.code === activeJurisdiction) return -1
+ if (b.code === activeJurisdiction) return 1
+ // Locale-aware, so the accented names sort where a reader expects them
+ // rather than after Z.
+ return country(a.code).localeCompare(country(b.code), locale)
+ })
+ return ordered.filter((j) => j.kinds.length > 0)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [jurisdictions, activeJurisdiction, locale])
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ className="w-48 shrink-0 justify-between font-normal"
+ // The longest labels ("Número de IVA") still truncate once the flag
+ // takes its share of the width, so the full one stays reachable.
+ title={label(value)}
+ >
+ {/* The flag stays once the list is closed and the country heading is
+ gone with it. It earns its place on `vat`, whose label nineteen
+ countries share: "VAT number" alone does not say whose. */}
+ <span className="flex min-w-0 items-center gap-1.5">
+ {selectedFlag ? (
+ <span aria-hidden className="shrink-0">
+ {selectedFlag}
+ </span>
+ ) : null}
+ <span className="truncate">{label(value)}</span>
+ </span>
+ <ChevronsUpDown size={13} className="ml-1 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-64 p-0" align="start">
+ {/* Substring rather than cmdk's default fuzzy scoring: these are
+ proper nouns, and fuzzy matching surfaced "Inscrição estadual" for
+ a search of "siret" (s-i-r-e-t as a subsequence), which is noise
+ exactly where the user is trying to be precise. */}
+ <Command
+ filter={(value, search, keywords) => {
+ const query = normalise(search)
+ if (!query) return 1
+ const haystack = normalise([value, ...(keywords ?? [])].join(' '))
+ return haystack.includes(query) ? 1 : 0
+ }}
+ >
+ {/* Searches document names and country names alike: `keywords`
+ carries the country so "Itália" matches Partita IVA. */}
+ <CommandInput placeholder={t('payees.searchTaxIdKind', 'Search document or country…')} />
+ <CommandList className="max-h-[280px]">
+ <CommandEmpty>{t('common.noResults', 'No results')}</CommandEmpty>
+ {groups.map((jurisdiction) => (
+ <CommandGroup
+ key={jurisdiction.code}
+ className={groupClass}
+ heading={groupHeading(country(jurisdiction.code), countryFlag(jurisdiction.code))}
+ >
+ {jurisdiction.kinds.map((kind) => (
+ <CommandItem
+ key={`${jurisdiction.code}-${kind}`}
+ value={`${jurisdiction.code}-${kind}`}
+ keywords={[label(kind), country(jurisdiction.code)]}
+ disabled={kind !== value && used.has(kind)}
+ onSelect={() => {
+ onChange(kind)
+ setOpen(false)
+ }}
+ >
+ <span className="flex-1">{label(kind)}</span>
+ {isSelected(kind, jurisdiction.code) && (
+ <Check size={13} className="text-primary" />
+ )}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ ))}
+ {/* Once, at the end: the escape hatch for a document no pack
+ describes, rather than repeated under every country. */}
+ {/* Same left padding as the country groups, so the headings line up
+ whether or not they carry a flag. */}
+ <CommandGroup
+ className={groupClass}
+ heading={groupHeading(t('fiscal.anyCountry', 'Anywhere else'))}
+ >
+ <CommandItem
+ value="other"
+ keywords={[label('other')]}
+ disabled={value !== 'other' && used.has('other')}
+ onSelect={() => {
+ onChange('other')
+ setOpen(false)
+ }}
+ >
+ <span className="flex-1">{label('other')}</span>
+ {value === 'other' && <Check size={13} className="text-primary" />}
+ </CommandItem>
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 0d3cec82..2e63526b 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -28,6 +28,8 @@ import type {
RuleImportResponse,
ImportLog,
ImportPreviewTransaction,
+ PayeeTaxId,
+ TaxIdKindOption,
Workspace,
WorkspaceKind,
WorkspaceMember,
@@ -107,6 +109,7 @@ export const workspaces = {
kind?: WorkspaceKind
default_currency?: string
locale?: string
+ tax_jurisdiction?: string | null
icon?: string
color?: string
self_membership?: boolean
@@ -115,7 +118,12 @@ export const workspaces = {
return data
},
// `kind` is absent on purpose: it is fixed when the workspace is created.
- update: async (id: string, payload: Partial<Pick<Workspace, 'name' | 'icon' | 'color' | 'default_currency' | 'locale'>>): Promise<Workspace> => {
+ update: async (
+ id: string,
+ payload: Partial<
+ Pick<Workspace, 'name' | 'icon' | 'color' | 'default_currency' | 'locale'>
+ > & { tax_jurisdiction?: string | null },
+ ): Promise<Workspace> => {
const { data } = await api.patch(`/workspaces/${id}`, payload)
return data
},
@@ -683,6 +691,38 @@ export const transactions = {
}
// Payees
+/** Jurisdiction metadata. Labels, masks and ordering come from the server so
+ * the browser cannot disagree with it about what a document looks like. */
+export const fiscal = {
+ jurisdictions: async (): Promise<string[]> => {
+ const { data } = await api.get('/fiscal/jurisdictions')
+ return data.jurisdictions
+ },
+ taxIdKinds: async (): Promise<{
+ jurisdiction: string | null
+ kinds: TaxIdKindOption[]
+ /** Country to documents, for grouping and searching the picker by country. */
+ jurisdictions: { code: string; kinds: string[] }[]
+ }> => {
+ const { data } = await api.get('/fiscal/tax-id-kinds')
+ return data
+ },
+}
+
+export interface PayeeWritePayload {
+ name?: string
+ /** Null clears the legal nature. `source` is never writable. */
+ type?: 'person' | 'company' | null
+ notes?: string
+ email?: string | null
+ phone?: string | null
+ address?: string | null
+ website?: string | null
+ is_favorite?: boolean
+ /** Replaces the whole set. Omit to leave documents untouched. */
+ tax_ids?: PayeeTaxId[]
+}
+
export const payees = {
list: async (params?: { q?: string; type?: string; is_favorite?: boolean } | Record<string, unknown>): Promise<Payee[]> => {
const cleanParams = params && !('queryKey' in params) ? params : undefined
@@ -697,11 +737,11 @@ export const payees = {
const { data } = await api.get(`/payees/${id}/summary`, { params: { from, to } })
return data
},
- create: async (payee: { name: string; type?: string; notes?: string }): Promise<Payee> => {
+ create: async (payee: PayeeWritePayload & { name: string }): Promise<Payee> => {
const { data } = await api.post('/payees', payee)
return data
},
- update: async (id: string, payee: Partial<Payee>): Promise<Payee> => {
+ update: async (id: string, payee: PayeeWritePayload): Promise<Payee> => {
const { data } = await api.patch(`/payees/${id}`, payee)
return data
},
diff --git a/frontend/src/lib/country-flag.test.ts b/frontend/src/lib/country-flag.test.ts
new file mode 100644
index 00000000..ed0d8307
--- /dev/null
+++ b/frontend/src/lib/country-flag.test.ts
@@ -0,0 +1,28 @@
+import { describe, it, expect } from 'vitest'
+import { countryFlag } from './country-flag'
+
+describe('countryFlag', () => {
+ it('derives the flag from the country code', () => {
+ expect(countryFlag('BR')).toBe('🇧🇷')
+ expect(countryFlag('DE')).toBe('🇩🇪')
+ expect(countryFlag('US')).toBe('🇺🇸')
+ })
+
+ it('accepts lowercase and surrounding space', () => {
+ expect(countryFlag('br')).toBe('🇧🇷')
+ expect(countryFlag(' gb ')).toBe('🇬🇧')
+ })
+
+ it('returns nothing for anything that is not a country code', () => {
+ // `tax_jurisdiction` may hold a regime code, which has no flag. Emitting
+ // one anyway would render as unrelated boxes.
+ for (const value of ['', 'MEI', 'B', 'BRA', '12', 'B1']) {
+ expect(countryFlag(value)).toBe('')
+ }
+ })
+
+ it('needs no lookup table, so a new pack gets a flag for free', () => {
+ expect(countryFlag('JP')).toBe('🇯🇵')
+ expect(countryFlag('ZA')).toBe('🇿🇦')
+ })
+})
diff --git a/frontend/src/lib/country-flag.ts b/frontend/src/lib/country-flag.ts
new file mode 100644
index 00000000..6080a110
--- /dev/null
+++ b/frontend/src/lib/country-flag.ts
@@ -0,0 +1,22 @@
+/**
+ * Emoji flag for an ISO 3166-1 alpha-2 country code.
+ *
+ * Derived from the code rather than stored in a lookup table: a flag is just
+ * the two letters shifted into Unicode's regional indicator block, so every
+ * country a jurisdiction pack is added for gets one without touching this
+ * file.
+ *
+ * Returns an empty string for anything that is not exactly two letters.
+ * `Workspace.tax_jurisdiction` accepts a regime code as well as a country
+ * code, and a regime has no flag.
+ */
+const REGIONAL_INDICATOR_A = 0x1f1e6
+const LETTER_A = 'A'.charCodeAt(0)
+
+export function countryFlag(code: string): string {
+ const upper = code.trim().toUpperCase()
+ if (!/^[A-Z]{2}$/.test(upper)) return ''
+ return String.fromCodePoint(
+ ...[...upper].map((letter) => REGIONAL_INDICATOR_A + letter.charCodeAt(0) - LETTER_A),
+ )
+}
diff --git a/frontend/src/lib/country-name.test.ts b/frontend/src/lib/country-name.test.ts
new file mode 100644
index 00000000..d320136c
--- /dev/null
+++ b/frontend/src/lib/country-name.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from 'vitest'
+import { countryName } from './country-name'
+
+describe('countryName', () => {
+ it('answers in the reader’s language', () => {
+ expect(countryName('BR', 'pt-BR')).toBe('Brasil')
+ expect(countryName('BR', 'en')).toBe('Brazil')
+ expect(countryName('JP', 'pt-BR')).toBe('Japão')
+ expect(countryName('JP', 'it')).toBe('Giappone')
+ })
+
+ it('gets the distinctions a hand-written table would miss', () => {
+ // pt-BR and pt-PT genuinely differ here, and so do the two Chinas' names
+ // across locales. This is the case for not maintaining the list ourselves.
+ expect(countryName('CZ', 'pt-BR')).toBe('Tchéquia')
+ expect(countryName('CZ', 'pt-PT')).toBe('Chéquia')
+ })
+
+ it('accepts a lowercase code', () => {
+ expect(countryName('cl', 'en')).toBe('Chile')
+ })
+
+ it('needs no entry per country, so a new pack costs nothing', () => {
+ // None of these are named anywhere in the codebase.
+ for (const code of ['UY', 'PH', 'UA', 'ID', 'NZ']) {
+ const name = countryName(code, 'en')
+ expect(name).not.toBe(code)
+ expect(name.length).toBeGreaterThan(2)
+ }
+ })
+
+ it('falls back to the value for anything that is not a country code', () => {
+ // `tax_jurisdiction` may hold a regime code, which no locale data names.
+ for (const value of ['', 'MEI', 'B', '12']) {
+ expect(countryName(value, 'en')).toBe(value)
+ }
+ })
+
+ it('never throws on an odd locale tag, whatever it can make of it', () => {
+ // A tag Intl cannot use resolves to the default locale rather than
+ // raising, so the reader still gets a name. The guarantee this asserts is
+ // that a bad tag never takes the picker down.
+ for (const tag of ['not-a-locale', '', 'zz-ZZ', 'x']) {
+ expect(() => countryName('BR', tag)).not.toThrow()
+ expect(countryName('BR', tag).length).toBeGreaterThan(0)
+ }
+ })
+})
diff --git a/frontend/src/lib/country-name.ts b/frontend/src/lib/country-name.ts
new file mode 100644
index 00000000..8fb5aaa4
--- /dev/null
+++ b/frontend/src/lib/country-name.ts
@@ -0,0 +1,75 @@
+/**
+ * Localised country name for an ISO 3166-1 alpha-2 code.
+ *
+ * Resolved through `Intl.DisplayNames`, which every supported browser ships
+ * with the CLDR data already loaded, rather than through the translation
+ * files. Two reasons:
+ *
+ * - Country names are not product copy. Hand-translating forty of them into
+ * ten locales would be four hundred strings that only restate what the
+ * platform already knows, and each new jurisdiction pack would add ten
+ * more.
+ * - It is correct in more locales than we translate into. The browser
+ * answers in the user's own language even where Securo has no locale
+ * file, and it declines and capitalises properly, which a flat string
+ * table cannot do.
+ *
+ * Falls back to the bare code, so a value `Intl` does not recognise still
+ * renders as something rather than as nothing. `Workspace.tax_jurisdiction`
+ * accepts a regime code as well as a country code, and no regime has a name
+ * here.
+ */
+const cache = new Map<string, Intl.DisplayNames | null>()
+
+function displayNames(locale: string): Intl.DisplayNames | null {
+ if (!cache.has(locale)) {
+ try {
+ cache.set(locale, new Intl.DisplayNames([locale], { type: 'region' }))
+ } catch {
+ // An unsupported locale tag, or an environment without the region data.
+ cache.set(locale, null)
+ }
+ }
+ return cache.get(locale) ?? null
+}
+
+/** CLDR's sentinel for "we do not know", which is a code but not a country. */
+const UNKNOWN_REGION = 'ZZ'
+
+let strict: Intl.DisplayNames | null | undefined
+
+/**
+ * Whether a two-letter code names a country at all.
+ *
+ * Uses `fallback: 'none'`, which answers `undefined` for a code the region
+ * data does not know, rather than echoing the code back the way `countryName`
+ * deliberately does. Needed wherever a code is *derived* rather than given —
+ * a VAT number's prefix, say — so a stray pair of letters does not get
+ * dressed up as a country.
+ */
+export function isKnownRegion(code: string): boolean {
+ const upper = code.trim().toUpperCase()
+ if (!/^[A-Z]{2}$/.test(upper) || upper === UNKNOWN_REGION) return false
+ if (strict === undefined) {
+ try {
+ strict = new Intl.DisplayNames(['en'], { type: 'region', fallback: 'none' })
+ } catch {
+ strict = null
+ }
+ }
+ // With no region data available, no claim can be made either way; treating
+ // the code as unknown keeps a wrong flag off the screen.
+ return strict ? strict.of(upper) !== undefined : false
+}
+
+export function countryName(code: string, locale: string): string {
+ const upper = code.trim().toUpperCase()
+ if (!/^[A-Z]{2}$/.test(upper)) return code
+ try {
+ return displayNames(locale)?.of(upper) ?? upper
+ } catch {
+ // `of` throws on a structurally invalid code rather than returning
+ // undefined.
+ return upper
+ }
+}
diff --git a/frontend/src/lib/tax-id-country.test.ts b/frontend/src/lib/tax-id-country.test.ts
new file mode 100644
index 00000000..a0b00a58
--- /dev/null
+++ b/frontend/src/lib/tax-id-country.test.ts
@@ -0,0 +1,81 @@
+import { describe, it, expect } from 'vitest'
+import { taxIdCountry, taxIdFlag } from './tax-id-country'
+
+// The shape the server sends in /api/fiscal/tax-id-kinds, trimmed to what
+// these cases need.
+const JURISDICTIONS = [
+ { code: 'BR', kinds: ['cnpj', 'cpf', 'ie', 'im'] },
+ { code: 'CL', kinds: ['cl_rut'] },
+ { code: 'UY', kinds: ['uy_rut'] },
+ { code: 'DE', kinds: ['vat', 'steuernummer'] },
+ { code: 'NL', kinds: ['vat'] },
+ { code: 'GR', kinds: ['vat'] },
+ { code: 'GB', kinds: ['vat'] },
+ { code: 'IN', kinds: ['gstin', 'pan'] },
+]
+
+describe('taxIdCountry', () => {
+ it('places a document that only one country asks for', () => {
+ expect(taxIdCountry('cnpj', '11222333000181', JURISDICTIONS)).toBe('BR')
+ expect(taxIdCountry('steuernummer', '1234567890', JURISDICTIONS)).toBe('DE')
+ expect(taxIdCountry('gstin', '27AAACR5055K1Z2', JURISDICTIONS)).toBe('IN')
+ })
+
+ it('tells the two RUTs apart, which share a name but not a country', () => {
+ expect(taxIdCountry('cl_rut', '609100001', JURISDICTIONS)).toBe('CL')
+ expect(taxIdCountry('uy_rut', '211003420011', JURISDICTIONS)).toBe('UY')
+ })
+
+ it('reads a VAT id’s country out of the number itself', () => {
+ // The case that motivated this: one kind, nineteen countries, so the
+ // label cannot say whose it is but the value can.
+ expect(taxIdCountry('vat', 'NL802225395B01', JURISDICTIONS)).toBe('NL')
+ expect(taxIdCountry('vat', 'DE123456789', JURISDICTIONS)).toBe('DE')
+ expect(taxIdCountry('vat', 'IT12345678901', JURISDICTIONS)).toBe('IT')
+ })
+
+ it('knows the VAT prefixes that are not the country code', () => {
+ // Greece bills under EL, and a naive two-letter read would emit a flag
+ // for a country that does not exist.
+ expect(taxIdCountry('vat', 'EL123456789', JURISDICTIONS)).toBe('GR')
+ // Northern Ireland kept an EU-facing prefix after Brexit.
+ expect(taxIdCountry('vat', 'XI123456789', JURISDICTIONS)).toBe('GB')
+ })
+
+ it('says nothing rather than guessing on a half-typed VAT id', () => {
+ for (const value of ['', 'D', '12345', '1234567890']) {
+ expect(taxIdCountry('vat', value, JURISDICTIONS)).toBeNull()
+ }
+ })
+
+ it('refuses a prefix that is not a real region', () => {
+ expect(taxIdCountry('vat', 'ZZ123456789', JURISDICTIONS)).toBeNull()
+ expect(taxIdCountry('vat', 'QQ999', JURISDICTIONS)).toBeNull()
+ })
+
+ it('never places an `other` document', () => {
+ // `other` means the product does not know what this is. Reading a country
+ // off the first two characters of an unknown string would look confident
+ // and be wrong.
+ expect(taxIdCountry('other', 'BP/1234/2024', JURISDICTIONS)).toBeNull()
+ expect(taxIdCountry('other', 'US-12345', JURISDICTIONS)).toBeNull()
+ })
+
+ it('says nothing for a kind no pack lists', () => {
+ expect(taxIdCountry('siret', '12345678901234', JURISDICTIONS)).toBeNull()
+ expect(taxIdCountry('', '', JURISDICTIONS)).toBeNull()
+ })
+})
+
+describe('taxIdFlag', () => {
+ it('renders the flag for a placed document', () => {
+ expect(taxIdFlag('cnpj', '11222333000181', JURISDICTIONS)).toBe('🇧🇷')
+ expect(taxIdFlag('vat', 'NL802225395B01', JURISDICTIONS)).toBe('🇳🇱')
+ expect(taxIdFlag('vat', 'EL123456789', JURISDICTIONS)).toBe('🇬🇷')
+ })
+
+ it('renders nothing rather than a placeholder when the country is unknown', () => {
+ expect(taxIdFlag('vat', '', JURISDICTIONS)).toBe('')
+ expect(taxIdFlag('other', 'anything', JURISDICTIONS)).toBe('')
+ })
+})
diff --git a/frontend/src/lib/tax-id-country.ts b/frontend/src/lib/tax-id-country.ts
new file mode 100644
index 00000000..ff9f5722
--- /dev/null
+++ b/frontend/src/lib/tax-id-country.ts
@@ -0,0 +1,64 @@
+/**
+ * Which country a stored fiscal document belongs to.
+ *
+ * Needed because a document's *name* is not always enough to place it. "VAT
+ * number" is the label nineteen jurisdictions share, so seeing it on a saved
+ * contact says nothing about which country's number it is. Every other
+ * document is asked for by exactly one country and needs no help.
+ *
+ * Two sources, in order:
+ *
+ * 1. **The packs.** A kind that only one jurisdiction lists can only be that
+ * country's document. This covers forty of the forty-two kinds. The map
+ * comes from the server with the kinds themselves, so it cannot disagree
+ * with what the picker offers.
+ * 2. **The value.** For `vat`, the country is *inside the number* — that is
+ * precisely why one kind can serve nineteen countries. `NL802225395B01`
+ * is Dutch because it says so.
+ *
+ * Returns null rather than guessing. `other` never resolves: it means the
+ * product does not know what the document is, and inferring a country from the
+ * first two characters of an unknown string would be a confident-looking lie.
+ */
+import { countryFlag } from './country-flag'
+import { isKnownRegion } from './country-name'
+
+/** VAT prefixes that are not the country's own ISO code. */
+const VAT_PREFIX_ALIASES: Record<string, string> = {
+ // Greece bills under EL, from Ελλάς, which predates the ISO code.
+ EL: 'GR',
+ // Northern Ireland, which kept an EU-facing prefix after Brexit.
+ XI: 'GB',
+}
+
+export interface JurisdictionKinds {
+ code: string
+ kinds: string[]
+}
+
+export function taxIdCountry(
+ kind: string,
+ value: string,
+ jurisdictions: JurisdictionKinds[],
+): string | null {
+ if (!kind || kind === 'other') return null
+
+ const owners = jurisdictions.filter((j) => j.kinds.includes(kind))
+ if (owners.length === 1) return owners[0].code
+
+ // Shared by several countries, so only the number itself can say which.
+ const prefix = value.trim().toUpperCase().slice(0, 2)
+ if (!/^[A-Z]{2}$/.test(prefix)) return null
+ const code = VAT_PREFIX_ALIASES[prefix] ?? prefix
+ return isKnownRegion(code) ? code : null
+}
+
+/** The flag to show beside a stored document, or an empty string for none. */
+export function taxIdFlag(
+ kind: string,
+ value: string,
+ jurisdictions: JurisdictionKinds[],
+): string {
+ const code = taxIdCountry(kind, value, jurisdictions)
+ return code ? countryFlag(code) : ''
+}
diff --git a/frontend/src/lib/tax-id.test.ts b/frontend/src/lib/tax-id.test.ts
new file mode 100644
index 00000000..28f77c5a
--- /dev/null
+++ b/frontend/src/lib/tax-id.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect } from 'vitest'
+import { applyMask, formatTaxId } from './tax-id'
+
+describe('applyMask', () => {
+ it('formats a CNPJ as the user types', () => {
+ const mask = '##.###.###/####-##'
+ expect(applyMask('1', mask)).toBe('1')
+ expect(applyMask('112', mask)).toBe('11.2')
+ expect(applyMask('11222333', mask)).toBe('11.222.333')
+ expect(applyMask('11222333000181', mask)).toBe('11.222.333/0001-81')
+ })
+
+ it('formats a CPF', () => {
+ expect(applyMask('52998224725', '###.###.###-##')).toBe('529.982.247-25')
+ })
+
+ it('ignores whatever the mask has no slot for', () => {
+ // Pasting an already-formatted value must not double up the separators.
+ expect(applyMask('11.222.333/0001-81', '##.###.###/####-##')).toBe('11.222.333/0001-81')
+ // And a value longer than the mask is truncated rather than mangled.
+ expect(applyMask('112223330001819999', '##.###.###/####-##')).toBe('11.222.333/0001-81')
+ })
+
+ it('leaves the value untouched when the kind has no mask', () => {
+ // The escape hatch: a document no pack describes must not be reformatted
+ // into something it is not.
+ expect(applyMask('T1234567890123 (houjin bangou)', null)).toBe(
+ 'T1234567890123 (houjin bangou)',
+ )
+ expect(applyMask('DE123456789', null)).toBe('DE123456789')
+ })
+
+ it('is idempotent, so re-rendering a stored value does not drift', () => {
+ const mask = '##-#######'
+ const once = applyMask('123456789', mask)
+ expect(applyMask(once, mask)).toBe(once)
+ })
+})
+
+describe('formatTaxId', () => {
+ it('renders a normalised value back through its mask', () => {
+ // What the backend stores is digits only; the browser is what puts the
+ // punctuation back.
+ expect(formatTaxId('11222333000181', '##.###.###/####-##')).toBe('11.222.333/0001-81')
+ expect(formatTaxId('ISENTO', null)).toBe('ISENTO')
+ })
+})
diff --git a/frontend/src/lib/tax-id.ts b/frontend/src/lib/tax-id.ts
new file mode 100644
index 00000000..9e0cd0fa
--- /dev/null
+++ b/frontend/src/lib/tax-id.ts
@@ -0,0 +1,36 @@
+/**
+ * Display formatting for fiscal documents.
+ *
+ * Masks come from the server (`/api/fiscal/tax-id-kinds`) rather than being
+ * duplicated here, because the same definition also drives validation. This
+ * file only knows how to *apply* a mask, never which mask a document uses.
+ *
+ * A mask is a template where `#` accepts one digit and every other character
+ * is a literal, so `##.###.###/####-##` turns 14 digits into a CNPJ. A kind
+ * with no mask is shown exactly as typed, which is what keeps a jurisdiction
+ * nobody has described from being mangled.
+ */
+
+/** Apply a mask as the user types, ignoring anything the mask has no slot for. */
+export function applyMask(raw: string, mask: string | null): string {
+ if (!mask) return raw
+ const digits = raw.replace(/\D/g, '')
+ let out = ''
+ let index = 0
+ for (const char of mask) {
+ if (index >= digits.length) break
+ if (char === '#') {
+ out += digits[index]
+ index += 1
+ } else {
+ out += char
+ }
+ }
+ return out
+}
+
+/** Format a stored (normalised) value for display. */
+export function formatTaxId(value: string, mask: string | null): string {
+ if (!mask) return value
+ return applyMask(value, mask)
+}
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 62dee31f..ed7eecd6 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -11,6 +11,8 @@
"kindHint": "Wähle, was dieser Workspace erfasst. Das lässt sich später nicht ändern.",
"defaultCurrency": "Standardwährung",
"locale": "Sprache",
+ "taxJurisdiction": "Steuerjurisdiktion",
+ "taxJurisdictionHint": "Bestimmt, welche steuerlichen Dokumente dieser Workspace anbietet. Unabhängig von der Sprache der Oberfläche.",
"members": "Mitglieder",
"addMember": "Mitglied hinzufügen",
"addMemberTitle": "Mitglied hinzufügen",
@@ -1241,6 +1243,15 @@
"name": "Name",
"type": "Typ",
"notes": "Notizen",
+ "email": "E-Mail",
+ "phone": "Telefon",
+ "address": "Adresse",
+ "taxIds": "Steuerdaten",
+ "addTaxId": "Hinzufügen",
+ "taxIdsEmpty": "Noch keines. Füge eines hinzu, wenn du es für steuerliche Zwecke brauchst.",
+ "taxIdKind": "Dokumentart",
+ "searchTaxIdKind": "Dokument oder Land suchen…",
+ "invalidTaxId": "Prüfe dieses Dokument: es sieht nicht gültig aus.",
"add": "Empfänger hinzufügen",
"edit": "Empfänger bearbeiten",
"created": "Zahlungsempfänger erstellt",
@@ -1260,7 +1271,6 @@
"mergeTarget": "Zusammenführen in",
"selectTarget": "Ziel-Empfänger auswählen...",
"merged": "Zahlungsempfänger zusammengeführt ({{count}} Transaktionen neu zugeordnet)",
- "typeMerchant": "Händler",
"typePerson": "Person",
"typeCompany": "Unternehmen",
"allTypes": "Alle Typen",
@@ -1270,7 +1280,57 @@
"deleteTitle": "Zahlungsempfänger löschen",
"deleteConfirm": "Möchten Sie diesen Zahlungsempfänger wirklich löschen? Dadurch wird der Zahlungsempfänger auch aus allen zugehörigen Transaktionen entfernt.",
"deleteMultipleTitle": "Zahlungsempfänger löschen",
- "deleteMultipleConfirm": "Möchten Sie die {{count}} ausgewählten Zahlungsempfänger wirklich löschen? Dadurch werden sie auch aus allen zugehörigen Transaktionen entfernt."
+ "deleteMultipleConfirm": "Möchten Sie die {{count}} ausgewählten Zahlungsempfänger wirklich löschen? Dadurch werden sie auch aus allen zugehörigen Transaktionen entfernt.",
+ "typeUnset": "Nicht angegeben",
+ "website": "Website"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Landesregistrierung",
+ "im": "Kommunale Registrierung",
+ "pt_nif": "NIF (Portugal)",
+ "es_nif": "NIF (Spanien)",
+ "vat": "USt-IdNr.",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "SDI-Code",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Anderes Dokument",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Andere Länder",
+ "anyCountry": "Anderswo"
},
"common": {
"view": "Ansehen",
@@ -1297,7 +1357,8 @@
"showMore": "+{{count}} weitere",
"previous": "Vorherige",
"next": "Nächste",
- "rowsPerPage": "Zeilen pro Seite"
+ "rowsPerPage": "Zeilen pro Seite",
+ "noResults": "Keine Ergebnisse"
},
"splitGroups": {
"title": "Gruppen",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index d241b8e4..d12d72bb 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -11,6 +11,8 @@
"kindHint": "Pick what this workspace tracks. This can't be changed later.",
"defaultCurrency": "Default currency",
"locale": "Language",
+ "taxJurisdiction": "Tax jurisdiction",
+ "taxJurisdictionHint": "Decides which fiscal documents this workspace is offered. Separate from the interface language.",
"members": "Members",
"addMember": "Add member",
"addMemberTitle": "Add member",
@@ -1241,6 +1243,15 @@
"name": "Name",
"type": "Type",
"notes": "Notes",
+ "email": "Email",
+ "phone": "Phone",
+ "address": "Address",
+ "taxIds": "Tax IDs",
+ "addTaxId": "Add",
+ "taxIdsEmpty": "None yet. Add one if you need it for tax purposes.",
+ "taxIdKind": "Document type",
+ "searchTaxIdKind": "Search document or country…",
+ "invalidTaxId": "Check this document: it does not look valid.",
"add": "Add Payee",
"edit": "Edit Payee",
"created": "Payee created",
@@ -1260,7 +1271,6 @@
"mergeTarget": "Merge into",
"selectTarget": "Select target payee...",
"merged": "Payees merged ({{count}} transactions reassigned)",
- "typeMerchant": "Merchant",
"typePerson": "Person",
"typeCompany": "Company",
"allTypes": "All Types",
@@ -1270,7 +1280,57 @@
"deleteConfirm": "Are you sure you want to delete this payee? This will also remove the payee from any associated transactions.",
"deleteMultipleTitle": "Delete Payees",
"deleteMultipleConfirm": "Are you sure you want to delete the {{count}} selected payees? This will also remove them from any associated transactions.",
- "deletedMultiple": "{{count}} payees deleted"
+ "deletedMultiple": "{{count}} payees deleted",
+ "typeUnset": "Not specified",
+ "website": "Website"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "State registration",
+ "im": "Municipal registration",
+ "pt_nif": "NIF (Portugal)",
+ "es_nif": "NIF (Spain)",
+ "vat": "VAT number",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "SDI code",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Other document",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Other countries",
+ "anyCountry": "Anywhere else"
},
"common": {
"view": "View",
@@ -1297,7 +1357,8 @@
"showMore": "+{{count}} more",
"previous": "Previous",
"next": "Next",
- "rowsPerPage": "Rows per page"
+ "rowsPerPage": "Rows per page",
+ "noResults": "No results"
},
"splitGroups": {
"title": "Groups",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index f44adea5..99cf5736 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -11,6 +11,8 @@
"kindHint": "Elige qué registra este espacio de trabajo. Esto no se puede cambiar después.",
"defaultCurrency": "Moneda por defecto",
"locale": "Idioma",
+ "taxJurisdiction": "Jurisdicción fiscal",
+ "taxJurisdictionHint": "Determina qué documentos fiscales ofrece este espacio de trabajo. Independiente del idioma de la interfaz.",
"members": "Miembros",
"addMember": "Añadir miembro",
"addMemberTitle": "Añadir miembro",
@@ -1241,6 +1243,15 @@
"name": "Nombre",
"type": "Tipo",
"notes": "Notas",
+ "email": "Email",
+ "phone": "Teléfono",
+ "address": "Dirección",
+ "taxIds": "Datos fiscales",
+ "addTaxId": "Añadir",
+ "taxIdsEmpty": "Ninguno todavía. Añade uno si lo necesitas a efectos fiscales.",
+ "taxIdKind": "Tipo de documento",
+ "searchTaxIdKind": "Buscar documento o país…",
+ "invalidTaxId": "Revisa este documento: no parece válido.",
"add": "Agregar beneficiario",
"edit": "Editar beneficiario",
"created": "Beneficiario creado",
@@ -1260,7 +1271,6 @@
"mergeTarget": "Fusionar en",
"selectTarget": "Seleccionar beneficiario destino...",
"merged": "Beneficiarios fusionados ({{count}} transacciones reasignadas)",
- "typeMerchant": "Comerciante",
"typePerson": "Persona",
"typeCompany": "Empresa",
"allTypes": "Todos los tipos",
@@ -1270,7 +1280,57 @@
"deleteTitle": "Eliminar beneficiario",
"deleteConfirm": "¿Estás seguro de que quieres eliminar este beneficiario? Esto también lo eliminará de cualquier transacción asociada.",
"deleteMultipleTitle": "Eliminar beneficiarios",
- "deleteMultipleConfirm": "¿Estás seguro de que quieres eliminar los {{count}} beneficiarios seleccionados? Esto también los eliminará de cualquier transacción asociada."
+ "deleteMultipleConfirm": "¿Estás seguro de que quieres eliminar los {{count}} beneficiarios seleccionados? Esto también los eliminará de cualquier transacción asociada.",
+ "typeUnset": "Sin especificar",
+ "website": "Sitio web"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Inscripción estatal",
+ "im": "Inscripción municipal",
+ "pt_nif": "NIF (Portugal)",
+ "es_nif": "NIF (España)",
+ "vat": "Número de IVA",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Código SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Otro documento",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Otros países",
+ "anyCountry": "Cualquier otro lugar"
},
"common": {
"view": "Ver",
@@ -1297,7 +1357,8 @@
"showMore": "+{{count}} más",
"previous": "Anterior",
"next": "Siguiente",
- "rowsPerPage": "Filas por página"
+ "rowsPerPage": "Filas por página",
+ "noResults": "Sin resultados"
},
"splitGroups": {
"title": "Grupos",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 45e41cf9..0d14a98d 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -11,6 +11,8 @@
"kindHint": "Choisissez ce que suit cet espace de travail. Ce choix est définitif.",
"defaultCurrency": "Devise par défaut",
"locale": "Langue",
+ "taxJurisdiction": "Juridiction fiscale",
+ "taxJurisdictionHint": "Détermine les documents fiscaux proposés dans cet espace de travail. Indépendant de la langue de l'interface.",
"members": "Membres",
"addMember": "Ajouter un membre",
"addMemberTitle": "Ajouter un membre",
@@ -1241,6 +1243,15 @@
"name": "Nom",
"type": "Type",
"notes": "Notes",
+ "email": "Email",
+ "phone": "Téléphone",
+ "address": "Adresse",
+ "taxIds": "Données fiscales",
+ "addTaxId": "Ajouter",
+ "taxIdsEmpty": "Aucun pour l'instant. Ajoutez-en un si vous en avez besoin à des fins fiscales.",
+ "taxIdKind": "Type de document",
+ "searchTaxIdKind": "Rechercher un document ou un pays…",
+ "invalidTaxId": "Vérifiez ce document : il ne semble pas valide.",
"add": "Ajouter un bénéficiaire",
"edit": "Modifier le bénéficiaire",
"created": "Bénéficiaire créé",
@@ -1260,7 +1271,6 @@
"mergeTarget": "Fusionner dans",
"selectTarget": "Sélectionner le bénéficiaire cible...",
"merged": "Bénéficiaires fusionnés ({{count}} transactions réattribuées)",
- "typeMerchant": "Commerçant",
"typePerson": "Personne",
"typeCompany": "Entreprise",
"allTypes": "Tous les types",
@@ -1270,7 +1280,57 @@
"deleteTitle": "Supprimer le bénéficiaire",
"deleteConfirm": "Êtes-vous sûr de vouloir supprimer ce bénéficiaire ? Cela le supprimera également de toutes les transactions associées.",
"deleteMultipleTitle": "Supprimer les bénéficiaires",
- "deleteMultipleConfirm": "Êtes-vous sûr de vouloir supprimer les {{count}} bénéficiaires sélectionnés ? Cela les supprimera également de toutes les transactions associées."
+ "deleteMultipleConfirm": "Êtes-vous sûr de vouloir supprimer les {{count}} bénéficiaires sélectionnés ? Cela les supprimera également de toutes les transactions associées.",
+ "typeUnset": "Non précisé",
+ "website": "Site web"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Immatriculation régionale",
+ "im": "Immatriculation municipale",
+ "pt_nif": "NIF (Portugal)",
+ "es_nif": "NIF (Espagne)",
+ "vat": "Numéro de TVA",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Code SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Autre document",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Autres pays",
+ "anyCountry": "Ailleurs"
},
"common": {
"view": "Voir",
@@ -1297,7 +1357,8 @@
"showMore": "+{{count}} de plus",
"previous": "Précédent",
"next": "Suivant",
- "rowsPerPage": "Lignes par page"
+ "rowsPerPage": "Lignes par page",
+ "noResults": "Aucun résultat"
},
"splitGroups": {
"title": "Groupes",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 455a270c..f7349d2e 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -11,6 +11,8 @@
"kindHint": "Scegli cosa traccia quest'area di lavoro. Non è modificabile in seguito.",
"defaultCurrency": "Valuta predefinita",
"locale": "Lingua",
+ "taxJurisdiction": "Giurisdizione fiscale",
+ "taxJurisdictionHint": "Determina quali documenti fiscali offre quest'area di lavoro. Indipendente dalla lingua dell'interfaccia.",
"members": "Membri",
"addMember": "Aggiungi membro",
"addMemberTitle": "Aggiungi membro",
@@ -1241,6 +1243,15 @@
"name": "Nome",
"type": "Tipo",
"notes": "Note",
+ "email": "Email",
+ "phone": "Telefono",
+ "address": "Indirizzo",
+ "taxIds": "Dati fiscali",
+ "addTaxId": "Aggiungi",
+ "taxIdsEmpty": "Nessuno ancora. Aggiungine uno se ti serve a fini fiscali.",
+ "taxIdKind": "Tipo di documento",
+ "searchTaxIdKind": "Cerca documento o paese…",
+ "invalidTaxId": "Controlla questo documento: non sembra valido.",
"add": "Aggiungi beneficiario",
"edit": "Modifica beneficiario",
"created": "Beneficiario creato",
@@ -1260,7 +1271,6 @@
"mergeTarget": "Unisci in",
"selectTarget": "Seleziona beneficiario di destinazione...",
"merged": "Beneficiari uniti ({{count}} transazioni riassegnate)",
- "typeMerchant": "Esercente",
"typePerson": "Persona",
"typeCompany": "Azienda",
"allTypes": "Tutti i tipi",
@@ -1270,7 +1280,57 @@
"deleteTitle": "Elimina beneficiario",
"deleteConfirm": "Sei sicuro di voler eliminare questo beneficiario? Questo lo rimuoverà anche da tutte le transazioni associate.",
"deleteMultipleTitle": "Elimina beneficiari",
- "deleteMultipleConfirm": "Sei sicuro di voler eliminare i {{count}} beneficiari selezionati? Questo li rimuoverà anche da tutte le transazioni associate."
+ "deleteMultipleConfirm": "Sei sicuro di voler eliminare i {{count}} beneficiari selezionati? Questo li rimuoverà anche da tutte le transazioni associate.",
+ "typeUnset": "Non specificato",
+ "website": "Sito web"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Registrazione statale",
+ "im": "Registrazione comunale",
+ "pt_nif": "NIF (Portogallo)",
+ "es_nif": "NIF (Spagna)",
+ "vat": "Partita IVA UE",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Codice SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Altro documento",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Altri paesi",
+ "anyCountry": "Qualsiasi altro luogo"
},
"common": {
"view": "Visualizza",
@@ -1297,7 +1357,8 @@
"showMore": "+{{count}} altri",
"previous": "Precedente",
"next": "Successivo",
- "rowsPerPage": "Righe per pagina"
+ "rowsPerPage": "Righe per pagina",
+ "noResults": "Nessun risultato"
},
"splitGroups": {
"title": "Gruppi",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 33b6e2f7..3f939e48 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -11,6 +11,8 @@
"kindHint": "Wybierz, co śledzi ten obszar roboczy. Tego nie można później zmienić.",
"defaultCurrency": "Waluta domyślna",
"locale": "Język",
+ "taxJurisdiction": "Jurysdykcja podatkowa",
+ "taxJurisdictionHint": "Decyduje, jakie dokumenty podatkowe oferuje ten obszar roboczy. Niezależnie od języka interfejsu.",
"members": "Członkowie",
"addMember": "Dodaj członka",
"addMemberTitle": "Dodaj członka",
@@ -1316,6 +1318,15 @@
"name": "Nazwa",
"type": "Typ",
"notes": "Notatki",
+ "email": "Email",
+ "phone": "Telefon",
+ "address": "Adres",
+ "taxIds": "Dane podatkowe",
+ "addTaxId": "Dodaj",
+ "taxIdsEmpty": "Jeszcze żadnego. Dodaj, jeśli potrzebujesz go do celów podatkowych.",
+ "taxIdKind": "Typ dokumentu",
+ "searchTaxIdKind": "Szukaj dokumentu lub kraju…",
+ "invalidTaxId": "Sprawdź ten dokument: nie wygląda na prawidłowy.",
"add": "Dodaj odbiorcę",
"edit": "Edytuj odbiorcę",
"created": "Utworzono odbiorcę",
@@ -1341,7 +1352,6 @@
"merged_few": "Scalono odbiorców (przypisano ponownie {{count}} transakcje)",
"merged_many": "Scalono odbiorców (przypisano ponownie {{count}} transakcji)",
"merged_other": "Scalono odbiorców (przypisano ponownie {{count}} transakcji)",
- "typeMerchant": "Sprzedawca",
"typePerson": "Osoba",
"typeCompany": "Firma",
"allTypes": "Wszystkie typy",
@@ -1351,7 +1361,57 @@
"deleteTitle": "Usuń odbiorcę",
"deleteConfirm": "Czy na pewno chcesz usunąć tego odbiorcę? Usunie to również odbiorcę ze wszystkich powiązanych transakcji.",
"deleteMultipleTitle": "Usuń odbiorców",
- "deleteMultipleConfirm": "Czy na pewno chcesz usunąć {{count}} wybranych odbiorców? Usunie to ich również ze wszystkich powiązanych transakcji."
+ "deleteMultipleConfirm": "Czy na pewno chcesz usunąć {{count}} wybranych odbiorców? Usunie to ich również ze wszystkich powiązanych transakcji.",
+ "typeUnset": "Nie określono",
+ "website": "Strona internetowa"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Rejestracja stanowa",
+ "im": "Rejestracja miejska",
+ "pt_nif": "NIF (Portugalia)",
+ "es_nif": "NIF (Hiszpania)",
+ "vat": "Numer VAT",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Kod SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Inny dokument",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Inne kraje",
+ "anyCountry": "Gdziekolwiek indziej"
},
"common": {
"view": "Zobacz",
@@ -1381,7 +1441,8 @@
"showMore_other": "+{{count}} więcej",
"previous": "Poprzedni",
"next": "Następny",
- "rowsPerPage": "Wierszy na stronę"
+ "rowsPerPage": "Wierszy na stronę",
+ "noResults": "Brak wyników"
},
"splitGroups": {
"title": "Grupy",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 075b43ec..e75de2fc 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -11,6 +11,8 @@
"kindHint": "Escolha o que este workspace vai acompanhar. Isso não pode ser alterado depois.",
"defaultCurrency": "Moeda padrão",
"locale": "Idioma",
+ "taxJurisdiction": "Jurisdição fiscal",
+ "taxJurisdictionHint": "Define quais documentos fiscais este workspace oferece. Independente do idioma da interface.",
"members": "Membros",
"addMember": "Adicionar membro",
"addMemberTitle": "Adicionar membro",
@@ -77,7 +79,7 @@
"navigation": "Ir para",
"transactions": "Transações",
"accounts": "Contas",
- "payees": "Beneficiários",
+ "payees": "Pessoas",
"categories": "Categorias",
"goals": "Metas",
"assets": "Patrimônio"
@@ -91,7 +93,7 @@
},
"empty": {
"title": "Nenhum resultado para \"{{query}}\"",
- "hint": "Tente outra palavra, um beneficiário, ou um valor."
+ "hint": "Tente outra palavra, o nome de uma pessoa, ou um valor."
},
"footer": {
"tagline": "controle total das suas finanças",
@@ -113,7 +115,7 @@
"settings": "Configurações",
"recurring": "Recorrentes",
"assets": "Patrimônio",
- "payees": "Beneficiários",
+ "payees": "Pessoas",
"splitGroups": "Grupos",
"goals": "Metas",
"reports": "Relatórios",
@@ -362,7 +364,7 @@
"colCategory": "Categoria",
"colAccount": "Conta",
"colAmount": "Valor",
- "colPayee": "Beneficiário",
+ "colPayee": "Pessoa",
"colNotes": "Notas",
"colTags": "Tags",
"colAttachments": "Arquivos",
@@ -691,12 +693,12 @@
"displayName": "Apelido",
"displayNamePlaceholder": "ex: Nubank Pessoal",
"displayNameHint": "Deixe vazio para usar o nome da instituição.",
- "payeeSource": "Origem do beneficiário",
+ "payeeSource": "Origem da pessoa",
"payeeAuto": "Automático (comerciante > dados de pagamento)",
"payeeMerchant": "Apenas nome do comerciante",
"payeePaymentData": "Nome do pagador/recebedor",
"payeeDescription": "Descrição da transação",
- "payeeNone": "Não definir beneficiário",
+ "payeeNone": "Não atribuir pessoa",
"importPending": "Importar transações pendentes",
"syncAssets": "Importar ativos de investimento",
"syncAssetsHint": "Quando desativado, esta conexão sincroniza contas e transações, mas não altera os investimentos do provedor.",
@@ -869,8 +871,8 @@
"blankConditionValue": "Toda condição precisa de um valor. Uma condição em branco corresponderia a todas as transações.",
"addAction": "Adicionar ação",
"setCategory": "Definir categoria",
- "setPayee": "Definir beneficiário",
- "selectPayee": "Selecionar beneficiário...",
+ "setPayee": "Atribuir pessoa",
+ "selectPayee": "Selecionar pessoa...",
"appendNotes": "Adicionar tags/notas",
"ignoreAction": "Ignorar transação",
"ignoreActionHint": "(sem valor necessário)",
@@ -884,7 +886,7 @@
"fieldAmount": "Valor",
"fieldType": "Tipo",
"fieldAccount": "Conta",
- "fieldPayee": "Beneficiário",
+ "fieldPayee": "Pessoa",
"fieldDate": "Data",
"opContains": "contém",
"opNotContains": "não contém",
@@ -1017,7 +1019,7 @@
"importedWithExcluded": "{{imported}} importadas, {{skipped}} ignoradas, {{excluded}} excluídas",
"suggested": "Sugerida",
"page": "Página {{current}} de {{total}}",
- "mapPayee": "Coluna de beneficiário",
+ "mapPayee": "Coluna da pessoa",
"mapExternalId": "Coluna de ID da transação",
"mapNotes": "Coluna de notas"
},
@@ -1233,21 +1235,30 @@
"payees": {
"addFavorite": "Adicionar aos favoritos",
"removeFavorite": "Remover dos favoritos",
- "title": "Beneficiários",
+ "title": "Pessoas",
"section": "Configuração",
- "payee": "Beneficiário",
- "noPayee": "Sem beneficiário",
- "rawPayee": "Beneficiário original",
+ "payee": "Pessoa",
+ "noPayee": "Sem pessoa vinculada",
+ "rawPayee": "Descrição original",
"name": "Nome",
"type": "Tipo",
"notes": "Notas",
- "add": "Adicionar Beneficiário",
- "edit": "Editar Beneficiário",
- "created": "Beneficiário criado",
- "updated": "Beneficiário atualizado",
- "deleted": "Beneficiário excluído",
- "empty": "Nenhum beneficiário ainda",
- "searchPlaceholder": "Buscar beneficiários...",
+ "email": "Email",
+ "phone": "Telefone",
+ "address": "Endereço",
+ "taxIds": "Dados fiscais",
+ "addTaxId": "Adicionar",
+ "taxIdsEmpty": "Nenhum ainda. Adicione se precisar para fins fiscais.",
+ "taxIdKind": "Tipo de documento",
+ "searchTaxIdKind": "Buscar documento ou país…",
+ "invalidTaxId": "Confira este documento: ele não parece válido.",
+ "add": "Adicionar Pessoa",
+ "edit": "Editar Pessoa",
+ "created": "Pessoa criada",
+ "updated": "Pessoa atualizada",
+ "deleted": "Pessoa excluída",
+ "empty": "Nenhuma pessoa ainda",
+ "searchPlaceholder": "Buscar pessoas...",
"transactionCount": "Transações",
"totalSpent": "Total Gasto",
"totalReceived": "Total Recebido",
@@ -1255,22 +1266,71 @@
"topCategory": "Categoria Principal",
"viewAllTransactions": "Ver todas as {{count}} transações",
"merge": "Mesclar",
- "mergeTitle": "Mesclar Beneficiários",
- "mergeDescription": "Todas as transações dos beneficiários selecionados serão reatribuídas ao beneficiário destino. Os demais serão excluídos.",
+ "mergeTitle": "Mesclar Pessoas",
+ "mergeDescription": "Todas as transações das pessoas selecionadas serão reatribuídas à pessoa de destino. As demais serão excluídas.",
"mergeTarget": "Mesclar em",
- "selectTarget": "Selecionar beneficiário destino...",
- "merged": "Beneficiários mesclados ({{count}} transações reatribuídas)",
- "typeMerchant": "Comerciante",
- "typePerson": "Pessoa",
- "typeCompany": "Empresa",
+ "selectTarget": "Selecionar pessoa de destino...",
+ "merged": "Pessoas mescladas ({{count}} transações reatribuídas)",
+ "typePerson": "Pessoa Física",
+ "typeCompany": "Pessoa Jurídica",
"allTypes": "Todos os tipos",
"filterByType": "Filtrar por tipo",
"favoritesOnly": "Apenas favoritos",
- "deletedMultiple": "{{count}} beneficiários excluídos",
- "deleteTitle": "Excluir beneficiário",
- "deleteConfirm": "Tem certeza de que deseja excluir este beneficiário? Isso também o removerá de todas as transações associadas.",
- "deleteMultipleTitle": "Excluir beneficiários",
- "deleteMultipleConfirm": "Tem certeza de que deseja excluir os {{count}} beneficiários selecionados? Isso também os removerá de todas as transações associadas."
+ "deletedMultiple": "{{count}} pessoas excluídas",
+ "deleteTitle": "Excluir pessoa",
+ "deleteConfirm": "Tem certeza de que deseja excluir esta pessoa? Isso também a removerá de todas as transações associadas.",
+ "deleteMultipleTitle": "Excluir pessoas",
+ "deleteMultipleConfirm": "Tem certeza de que deseja excluir as {{count}} pessoas selecionadas? Isso também as removerá de todas as transações associadas.",
+ "typeUnset": "Não informado",
+ "website": "Site"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Inscrição estadual",
+ "im": "Inscrição municipal",
+ "pt_nif": "NIF (Portugal)",
+ "es_nif": "NIF (Espanha)",
+ "vat": "Número de VAT",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Código SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Outro documento",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Outros países",
+ "anyCountry": "Qualquer outro lugar"
},
"common": {
"view": "Ver",
@@ -1297,7 +1357,8 @@
"showMore": "Mostrar +{{count}}",
"previous": "Anterior",
"next": "Próximo",
- "rowsPerPage": "Linhas por página"
+ "rowsPerPage": "Linhas por página",
+ "noResults": "Nenhum resultado"
},
"splitGroups": {
"title": "Grupos",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 99927761..afe6938e 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -11,6 +11,8 @@
"kindHint": "Escolhe o que este espaço de trabalho vai acompanhar. Isto não pode ser alterado depois.",
"defaultCurrency": "Moeda predefinida",
"locale": "Idioma",
+ "taxJurisdiction": "Jurisdição fiscal",
+ "taxJurisdictionHint": "Define quais documentos fiscais este espaço de trabalho oferece. Independente do idioma da interface.",
"members": "Membros",
"addMember": "Adicionar membro",
"addMemberTitle": "Adicionar membro",
@@ -77,7 +79,7 @@
"navigation": "Ir para",
"transactions": "Transações",
"accounts": "Contas",
- "payees": "Beneficiários",
+ "payees": "Entidades",
"categories": "Categorias",
"goals": "Objetivos",
"assets": "Património"
@@ -91,7 +93,7 @@
},
"empty": {
"title": "Nenhum resultado para \"{{query}}\"",
- "hint": "Experimenta outra palavra, um beneficiário ou um valor."
+ "hint": "Experimenta outra palavra, o nome de uma entidade, ou um valor."
},
"footer": {
"tagline": "controlo total das tuas finanças",
@@ -113,7 +115,7 @@
"settings": "Definições",
"recurring": "Recorrentes",
"assets": "Património",
- "payees": "Beneficiários",
+ "payees": "Entidades",
"splitGroups": "Grupos",
"goals": "Objetivos",
"reports": "Relatórios",
@@ -362,7 +364,7 @@
"colCategory": "Categoria",
"colAccount": "Conta",
"colAmount": "Valor",
- "colPayee": "Beneficiário",
+ "colPayee": "Entidade",
"colNotes": "Notas",
"colTags": "Tags",
"colAttachments": "Ficheiros",
@@ -691,12 +693,12 @@
"displayName": "Nome personalizado",
"displayNamePlaceholder": "ex: Nubank Pessoal",
"displayNameHint": "Deixa vazio para usar o nome da instituição.",
- "payeeSource": "Origem do beneficiário",
+ "payeeSource": "Origem da entidade",
"payeeAuto": "Automático (comerciante > dados de pagamento)",
"payeeMerchant": "Apenas nome do comerciante",
"payeePaymentData": "Nome do pagador/recebedor",
"payeeDescription": "Descrição da transação",
- "payeeNone": "Não definir beneficiário",
+ "payeeNone": "Não atribuir entidade",
"importPending": "Importar transações pendentes",
"syncAssets": "Importar ativos de investimento",
"syncAssetsHint": "Quando desativado, esta ligação sincroniza contas e transações, mas não altera os investimentos do fornecedor.",
@@ -869,8 +871,8 @@
"blankConditionValue": "Todas as condições precisam de um valor. Uma condição em branco corresponderia a todas as transações.",
"addAction": "Adicionar ação",
"setCategory": "Definir categoria",
- "setPayee": "Definir beneficiário",
- "selectPayee": "Selecionar beneficiário...",
+ "setPayee": "Atribuir entidade",
+ "selectPayee": "Selecionar entidade...",
"appendNotes": "Adicionar tags/notas",
"ignoreAction": "Ignorar transação",
"ignoreActionHint": "(sem valor necessário)",
@@ -884,7 +886,7 @@
"fieldAmount": "Valor",
"fieldType": "Tipo",
"fieldAccount": "Conta",
- "fieldPayee": "Beneficiário",
+ "fieldPayee": "Entidade",
"fieldDate": "Data",
"opContains": "contém",
"opNotContains": "não contém",
@@ -973,7 +975,7 @@
"mapCategory": "Coluna de categoria",
"mapCurrency": "Coluna de moeda",
"mapFxRate": "Coluna de câmbio",
- "mapPayee": "Coluna de beneficiário",
+ "mapPayee": "Coluna da entidade",
"mapExternalId": "Coluna de ID da transação",
"mapNotes": "Coluna de notas",
"title": "Importar",
@@ -1233,21 +1235,30 @@
"payees": {
"addFavorite": "Adicionar aos favoritos",
"removeFavorite": "Remover dos favoritos",
- "title": "Beneficiários",
+ "title": "Entidades",
"section": "Configuração",
- "payee": "Beneficiário",
- "noPayee": "Sem beneficiário",
- "rawPayee": "Beneficiário original",
+ "payee": "Entidade",
+ "noPayee": "Sem entidade associada",
+ "rawPayee": "Descrição original",
"name": "Nome",
"type": "Tipo",
"notes": "Notas",
- "add": "Adicionar Beneficiário",
- "edit": "Editar Beneficiário",
- "created": "Beneficiário criado",
- "updated": "Beneficiário atualizado",
- "deleted": "Beneficiário eliminado",
- "empty": "Nenhum beneficiário ainda",
- "searchPlaceholder": "Procurar beneficiários...",
+ "email": "Email",
+ "phone": "Telefone",
+ "address": "Endereço",
+ "taxIds": "Dados fiscais",
+ "addTaxId": "Adicionar",
+ "taxIdsEmpty": "Nenhum ainda. Adiciona se precisares para fins fiscais.",
+ "taxIdKind": "Tipo de documento",
+ "searchTaxIdKind": "Procurar documento ou país…",
+ "invalidTaxId": "Verifica este documento: não parece válido.",
+ "add": "Adicionar Entidade",
+ "edit": "Editar Entidade",
+ "created": "Entidade criada",
+ "updated": "Entidade atualizada",
+ "deleted": "Entidade eliminada",
+ "empty": "Nenhuma entidade ainda",
+ "searchPlaceholder": "Procurar entidades...",
"transactionCount": "Transações",
"totalSpent": "Total Gasto",
"totalReceived": "Total Recebido",
@@ -1255,22 +1266,71 @@
"topCategory": "Categoria Principal",
"viewAllTransactions": "Ver todas as {{count}} transações",
"merge": "Mesclar",
- "mergeTitle": "Mesclar Beneficiários",
- "mergeDescription": "Todas as transações dos beneficiários selecionados serão reatribuídas ao beneficiário destino. Os demais serão eliminados.",
+ "mergeTitle": "Mesclar Entidades",
+ "mergeDescription": "Todas as transações das entidades selecionadas serão reatribuídas à entidade de destino. As restantes serão eliminadas.",
"mergeTarget": "Mesclar em",
- "selectTarget": "Selecionar beneficiário destino...",
- "merged": "Beneficiários mesclados ({{count}} transações reatribuídas)",
- "typeMerchant": "Comerciante",
- "typePerson": "Pessoa",
- "typeCompany": "Empresa",
+ "selectTarget": "Selecionar entidade de destino...",
+ "merged": "Entidades mescladas ({{count}} transações reatribuídas)",
+ "typePerson": "Pessoa singular",
+ "typeCompany": "Pessoa coletiva",
"allTypes": "Todos os tipos",
"filterByType": "Filtrar por tipo",
"favoritesOnly": "Apenas favoritos",
- "deletedMultiple": "{{count}} beneficiários excluídos",
- "deleteTitle": "Eliminar beneficiário",
- "deleteConfirm": "Tem a certeza que deseja eliminar este beneficiário? Isto também o irá remover de quaisquer transações associadas.",
- "deleteMultipleTitle": "Eliminar beneficiários",
- "deleteMultipleConfirm": "Tem a certeza que deseja eliminar os {{count}} beneficiários selecionados? Isto também os irá remover de quaisquer transações associadas."
+ "deletedMultiple": "{{count}} entidades eliminadas",
+ "deleteTitle": "Eliminar entidade",
+ "deleteConfirm": "Tem a certeza que deseja eliminar esta entidade? Isto também a irá remover de quaisquer transações associadas.",
+ "deleteMultipleTitle": "Eliminar entidades",
+ "deleteMultipleConfirm": "Tem a certeza que deseja eliminar as {{count}} entidades selecionadas? Isto também as irá remover de quaisquer transações associadas.",
+ "typeUnset": "Não indicado",
+ "website": "Site"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Inscrição estadual",
+ "im": "Inscrição municipal",
+ "pt_nif": "NIF (Portugal)",
+ "es_nif": "NIF (Espanha)",
+ "vat": "Número de IVA",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Código SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Outro documento",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Outros países",
+ "anyCountry": "Qualquer outro lugar"
},
"common": {
"view": "Ver",
@@ -1297,7 +1357,8 @@
"showMore": "Mostrar +{{count}}",
"previous": "Anterior",
"next": "Próximo",
- "rowsPerPage": "Linhas por página"
+ "rowsPerPage": "Linhas por página",
+ "noResults": "Nenhum resultado"
},
"splitGroups": {
"title": "Grupos",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 44595e26..4ac4cf5f 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -11,6 +11,8 @@
"kindHint": "Выберите, что будет вести это рабочее пространство. Изменить позже нельзя.",
"defaultCurrency": "Валюта по умолчанию",
"locale": "Язык",
+ "taxJurisdiction": "Налоговая юрисдикция",
+ "taxJurisdictionHint": "Определяет, какие налоговые документы предлагает это рабочее пространство. Не зависит от языка интерфейса.",
"members": "Участники",
"addMember": "Добавить участника",
"addMemberTitle": "Добавить участника",
@@ -1247,6 +1249,15 @@
"name": "Название",
"type": "Тип",
"notes": "Примечания",
+ "email": "Email",
+ "phone": "Телефон",
+ "address": "Адрес",
+ "taxIds": "Налоговые данные",
+ "addTaxId": "Добавить",
+ "taxIdsEmpty": "Пока ни одного. Добавьте, если это нужно для налоговых целей.",
+ "taxIdKind": "Тип документа",
+ "searchTaxIdKind": "Поиск документа или страны…",
+ "invalidTaxId": "Проверьте этот документ: он выглядит недействительным.",
"add": "Добавить получателя",
"edit": "Редактировать получателя",
"created": "Получатель создан",
@@ -1266,7 +1277,6 @@
"mergeTarget": "Объединить в",
"selectTarget": "Выберите целевого получателя...",
"merged": "Получатели объединены ({{count}} транзакций переназначено)",
- "typeMerchant": "Продавец",
"typePerson": "Физлицо",
"typeCompany": "Компания",
"allTypes": "Все типы",
@@ -1276,7 +1286,57 @@
"deleteTitle": "Удалить получателя",
"deleteConfirm": "Вы уверены, что хотите удалить этого получателя? Это также удалит его из всех связанных транзакций.",
"deleteMultipleTitle": "Удалить получателей",
- "deleteMultipleConfirm": "Вы уверены, что хотите удалить {{count}} выбранных получателей? Это также удалит их из всех связанных транзакций."
+ "deleteMultipleConfirm": "Вы уверены, что хотите удалить {{count}} выбранных получателей? Это также удалит их из всех связанных транзакций.",
+ "typeUnset": "Не указано",
+ "website": "Сайт"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Региональная регистрация",
+ "im": "Муниципальная регистрация",
+ "pt_nif": "NIF (Португалия)",
+ "es_nif": "NIF (Испания)",
+ "vat": "Номер VAT",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Код SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Другой документ",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Другие страны",
+ "anyCountry": "Где-либо ещё"
},
"common": {
"view": "Просмотр",
@@ -1303,7 +1363,8 @@
"showMore": "+{{count}} ещё",
"previous": "Назад",
"next": "Далее",
- "rowsPerPage": "Строк на странице"
+ "rowsPerPage": "Строк на странице",
+ "noResults": "Нет результатов"
},
"splitGroups": {
"title": "Группы",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 7941faee..3ec2c516 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -11,6 +11,8 @@
"kindHint": "Виберіть, що вестиме цей робочий простір. Змінити пізніше не можна.",
"defaultCurrency": "Валюта за замовчуванням",
"locale": "Мова",
+ "taxJurisdiction": "Податкова юрисдикція",
+ "taxJurisdictionHint": "Визначає, які податкові документи пропонує цей робочий простір. Не залежить від мови інтерфейсу.",
"members": "Учасники",
"addMember": "Додати учасника",
"addMemberTitle": "Додати учасника",
@@ -1247,6 +1249,15 @@
"name": "Назва",
"type": "Тип",
"notes": "Примітки",
+ "email": "Email",
+ "phone": "Телефон",
+ "address": "Адреса",
+ "taxIds": "Податкові дані",
+ "addTaxId": "Додати",
+ "taxIdsEmpty": "Поки жодного. Додайте, якщо це потрібно для податкових цілей.",
+ "taxIdKind": "Тип документа",
+ "searchTaxIdKind": "Пошук документа або країни…",
+ "invalidTaxId": "Перевірте цей документ: він не виглядає дійсним.",
"add": "Додати отримувача",
"edit": "Редагувати отримувача",
"created": "Отримувача створено",
@@ -1266,7 +1277,6 @@
"mergeTarget": "Об'єднати в",
"selectTarget": "Оберіть цільового отримувача...",
"merged": "Отримувачів об'єднано ({{count}} транзакцій переназначено)",
- "typeMerchant": "Продавець",
"typePerson": "Фізособа",
"typeCompany": "Компанія",
"allTypes": "Всі типи",
@@ -1276,7 +1286,57 @@
"deleteTitle": "Видалити одержувача",
"deleteConfirm": "Ви впевнені, що хочете видалити цього одержувача? Це також видалить його з усіх пов'язаних транзакцій.",
"deleteMultipleTitle": "Видалити одержувачів",
- "deleteMultipleConfirm": "Ви впевнені, що хочете видалити {{count}} вибраних одержувачів? Це також видалить їх з усіх пов'язаних транзакцій."
+ "deleteMultipleConfirm": "Ви впевнені, що хочете видалити {{count}} вибраних одержувачів? Це також видалить їх з усіх пов'язаних транзакцій.",
+ "typeUnset": "Не вказано",
+ "website": "Сайт"
+ },
+ "fiscal": {
+ "kind": {
+ "cnpj": "CNPJ",
+ "cpf": "CPF",
+ "ie": "Регіональна реєстрація",
+ "im": "Муніципальна реєстрація",
+ "pt_nif": "NIF (Португалія)",
+ "es_nif": "NIF (Іспанія)",
+ "vat": "Номер VAT",
+ "steuernummer": "Steuernummer",
+ "partita_iva": "Partita IVA",
+ "codice_fiscale": "Codice Fiscale",
+ "sdi": "Код SDI",
+ "siret": "SIRET",
+ "ein": "EIN",
+ "other": "Інший документ",
+ "nip": "NIP",
+ "se_orgnr": "Organisationsnummer",
+ "no_orgnr": "Organisasjonsnummer",
+ "cvr": "CVR",
+ "ico": "IČO",
+ "adoszam": "Adószám",
+ "ro_cui": "CUI",
+ "ch_uid": "UID",
+ "inn": "INN",
+ "edrpou": "EDRPOU",
+ "cuit": "CUIT",
+ "rfc": "RFC",
+ "cl_rut": "RUT",
+ "uy_rut": "RUT",
+ "co_nit": "NIT",
+ "gt_nit": "NIT",
+ "pe_ruc": "RUC",
+ "cr_cedula": "Cédula",
+ "rnc": "RNC",
+ "ca_bn": "Business Number",
+ "abn": "ABN",
+ "nzbn": "NZBN",
+ "jp_corporate": "Corporate Number",
+ "gstin": "GSTIN",
+ "pan": "PAN",
+ "npwp": "NPWP",
+ "ph_tin": "TIN",
+ "uscc": "USCC"
+ },
+ "otherCountries": "Інші країни",
+ "anyCountry": "Будь-де інде"
},
"common": {
"view": "Переглянути",
@@ -1303,7 +1363,8 @@
"showMore": "+{{count}} ще",
"previous": "Назад",
"next": "Далі",
- "rowsPerPage": "Рядків на сторінці"
+ "rowsPerPage": "Рядків на сторінці",
+ "noResults": "Немає результатів"
},
"splitGroups": {
"title": "Групи",
diff --git a/frontend/src/pages/payees.tsx b/frontend/src/pages/payees.tsx
index 12dbf299..4c1dbb94 100644
--- a/frontend/src/pages/payees.tsx
+++ b/frontend/src/pages/payees.tsx
@@ -1,5 +1,6 @@
import { useState, useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import type { TFunction } from 'i18next'
import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate, useSearchParams } from 'react-router-dom'
@@ -8,6 +9,9 @@ import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
+import { fiscal as fiscalApi, type PayeeWritePayload } from '@/lib/api'
+import { applyMask, formatTaxId } from '@/lib/tax-id'
+import { TaxIdKindPicker } from '@/components/tax-id-kind-picker'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import {
@@ -41,13 +45,25 @@ import {
import { cn } from '@/lib/utils'
import { PageHeader } from '@/components/page-header'
import { calculateRangeSelection } from '@/lib/selection-utils'
-import { Search, Star, Merge, Trash2, ArrowRight, ListFilter, X, Check, Pencil } from 'lucide-react'
+import { Search, Star, Merge, Trash2, ArrowRight, ListFilter, X, Check, Pencil, Plus } from 'lucide-react'
import { usePrivacyMode } from '@/hooks/use-privacy-mode'
import { useAuth } from '@/contexts/auth-context'
import { useWorkspace } from '@/contexts/workspace-context'
import type { Payee } from '@/types'
import { formatCurrency } from '@/lib/format'
+
+/** Turn the server's machine-readable document error into something a person
+ * can act on. It arrives as `invalid_tax_id:<kind>:<reason>`; the reason is
+ * useful in logs, the document name is what the user needs to look at. */
+function taxIdErrorMessage(error: unknown, t: TFunction): string | null {
+ const detail = (error as { response?: { data?: { detail?: string } } })?.response?.data?.detail
+ if (typeof detail !== 'string' || !detail.startsWith('invalid_tax_id:')) return null
+ const kind = detail.split(':')[1] ?? ''
+ const name = t(`fiscal.kind.${kind}`, kind.toUpperCase())
+ return `${name}: ${t('payees.invalidTaxId')}`
+}
+
export default function PayeesPage() {
const { t } = useTranslation()
const [searchParams] = useSearchParams()
@@ -58,8 +74,10 @@ export default function PayeesPage() {
const { user } = useAuth()
const { canWrite } = useWorkspace()
const userCurrency = user?.preferences?.currency_display ?? 'USD'
+ // No entry for an unset type: most rows come from sync, which cannot know
+ // a legal nature from a bank descriptor, and a badge reading "unknown" on
+ // hundreds of rows is noise rather than information.
const typeLabels: Record<string, string> = {
- merchant: t('payees.typeMerchant'),
person: t('payees.typePerson'),
company: t('payees.typeCompany'),
}
@@ -128,8 +146,35 @@ export default function PayeesPage() {
// Form state
const [formName, setFormName] = useState('')
- const [formType, setFormType] = useState<string>('merchant')
+ // '' means the legal nature was not stated, which is the resting state for
+ // anything sync created and a legitimate answer, not a missing one.
+ type FormType = '' | 'person' | 'company'
+ const [formType, setFormType] = useState<FormType>('')
const [formNotes, setFormNotes] = useState('')
+ const [formEmail, setFormEmail] = useState('')
+ const [formPhone, setFormPhone] = useState('')
+ const [formAddress, setFormAddress] = useState('')
+ const [formWebsite, setFormWebsite] = useState('')
+ // Documents this payee has, as ordered rows. A list rather than a slot per
+ // possible kind: most cadastros need one document, and a column of empty
+ // boxes labelled with documents the user has never heard of reads as a
+ // form to fill rather than a fact to record.
+ const [taxIdRows, setTaxIdRows] = useState<{ kind: string; value: string }[]>([])
+
+ // Labels, masks and ordering come from the server: the jurisdiction that
+ // decides them lives on the workspace, and a second copy of the rule here
+ // would drift from it.
+ const { data: taxIdMeta } = useQuery({
+ queryKey: ['tax-id-kinds'],
+ queryFn: fiscalApi.taxIdKinds,
+ staleTime: 1000 * 60 * 60,
+ })
+ const allKinds = taxIdMeta?.kinds ?? []
+ const kindOption = (kind: string) => allKinds.find((k) => k.kind === kind)
+ // What this jurisdiction asks for, in pack order. Drives which document a
+ // new row starts on; the picker itself groups every country.
+ const localKinds = allKinds.filter((k) => k.offered)
+ const usedKinds = new Set(taxIdRows.map((r) => r.kind))
const { data: payeesList, isLoading } = useQuery({
queryKey: ['payees', searchQuery, filterType, filterFavorites],
@@ -153,24 +198,24 @@ export default function PayeesPage() {
})
const createMutation = useMutation({
- mutationFn: (data: { name: string; type?: string; notes?: string }) => payeesApi.create(data),
+ mutationFn: (data: PayeeWritePayload & { name: string }) => payeesApi.create(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['payees'] })
setDialogOpen(false)
toast.success(t('payees.created'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e: unknown) => toast.error(taxIdErrorMessage(e, t) ?? t('common.error')),
})
const updateMutation = useMutation({
- mutationFn: ({ id, ...data }: Partial<Payee> & { id: string }) => payeesApi.update(id, data),
+ mutationFn: ({ id, ...data }: PayeeWritePayload & { id: string }) => payeesApi.update(id, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['payees'] })
setDialogOpen(false)
setEditingPayee(null)
toast.success(t('payees.updated'))
},
- onError: () => toast.error(t('common.error')),
+ onError: (e: unknown) => toast.error(taxIdErrorMessage(e, t) ?? t('common.error')),
})
const deleteMutation = useMutation({
@@ -238,27 +283,74 @@ export default function PayeesPage() {
onError: () => toast.error(t('common.error')),
})
+
+ // A workspace that files somewhere gets its primary document ready to type
+ // into. A company whose clients are all local should never have to ask for
+ // the field it uses every single time.
+ //
+ // Only when a jurisdiction is set: with none, the only offered kind is the
+ // generic one, and a permanently empty "Other document" box is the confusing
+ // thing this replaced.
+ const seedTaxIdRows = (payee?: Payee | null): { kind: string; value: string }[] => {
+ const existing = (payee?.tax_ids ?? []).map((t) => ({
+ kind: t.kind,
+ value: formatTaxId(t.value, kindOption(t.kind)?.mask ?? null),
+ }))
+ if (existing.length > 0) return existing
+ const primary = taxIdMeta?.jurisdiction ? localKinds[0] : undefined
+ return primary ? [{ kind: primary.kind, value: '' }] : []
+ }
+
const openCreate = () => {
setEditingPayee(null)
setFormName('')
- setFormType('merchant')
+ setFormType('')
setFormNotes('')
+ setFormEmail('')
+ setFormPhone('')
+ setFormAddress('')
+ setFormWebsite('')
+ setTaxIdRows(seedTaxIdRows())
setDialogOpen(true)
}
const openEdit = (payee: Payee) => {
setEditingPayee(payee)
setFormName(payee.name)
- setFormType(payee.type)
+ setFormType(payee.type ?? '')
setFormNotes(payee.notes ?? '')
+ setFormEmail(payee.email ?? '')
+ setFormPhone(payee.phone ?? '')
+ setFormAddress(payee.address ?? '')
+ setFormWebsite(payee.website ?? '')
+ // Every stored document becomes a row, including kinds this jurisdiction
+ // does not ask for: a German VAT number on a Brazilian workspace is a
+ // normal state, and hiding it would be worse than showing it.
+ setTaxIdRows(seedTaxIdRows(payee))
setDialogOpen(true)
}
const handleSave = () => {
+ const payload = {
+ name: formName,
+ // Empty means the legal nature was not stated, which is a value, not a
+ // blank to be coerced into one.
+ type: formType || null,
+ notes: formNotes || undefined,
+ email: formEmail.trim() || null,
+ phone: formPhone.trim() || null,
+ address: formAddress.trim() || null,
+ website: formWebsite.trim() || null,
+ // An emptied field means "drop this document", so blanks are sent and
+ // the server treats them as removals.
+ tax_ids: taxIdRows
+ .filter((row) => row.value.trim() !== '')
+ .map((row) => ({ kind: row.kind, value: row.value })),
+ }
if (editingPayee) {
- updateMutation.mutate({ id: editingPayee.id, name: formName, type: formType as Payee['type'], notes: formNotes || undefined })
+ updateMutation.mutate({ id: editingPayee.id, ...payload })
} else {
- createMutation.mutate({ name: formName, type: formType, notes: formNotes || undefined })
+ createMutation.mutate(payload)
}
}
@@ -384,7 +476,6 @@ export default function PayeesPage() {
<DropdownMenuSubContent className="w-[180px] p-1 bg-card border border-border rounded-xl shadow-md">
{[
{ value: '', label: t('payees.allTypes', 'All Types') },
- { value: 'merchant', label: t('payees.typeMerchant') },
{ value: 'person', label: t('payees.typePerson') },
{ value: 'company', label: t('payees.typeCompany') },
].map((opt) => (
@@ -478,6 +569,91 @@ export default function PayeesPage() {
)}
</div>
+ {/* Summary panel, above the table on purpose: a workspace whose payees
+ were created by sync has hundreds of rows, and a panel rendered after
+ the table opens below the fold, which reads as the click doing nothing. */}
+ {summaryPayee && (
+ <div className="bg-card rounded-xl border border-border shadow-sm p-5 mb-4">
+ {summaryLoading ? (
+ <Skeleton className="h-24 w-full" />
+ ) : summaryData ? (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <h3 className="text-lg font-bold">{summaryData.payee.name}</h3>
+ <Button variant="ghost" size="sm" onClick={() => setSummaryPayee(null)}>
+ &times;
+ </Button>
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
+ <div>
+ <p className="text-xs text-muted-foreground">{t('payees.totalSpent')}</p>
+ <p className="text-lg font-bold text-rose-500 tabular-nums">
+ {mask(formatCurrency(summaryData.total_spent, userCurrency, locale))}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-muted-foreground">{t('payees.totalReceived')}</p>
+ <p className="text-lg font-bold text-emerald-600 tabular-nums">
+ {mask(formatCurrency(summaryData.total_received, userCurrency, locale))}
+ </p>
+ </div>
+ <div>
+ <p className="text-xs text-muted-foreground">{t('payees.transactionCount')}</p>
+ <p className="text-lg font-bold tabular-nums">{summaryData.transaction_count}</p>
+ </div>
+ <div>
+ <p className="text-xs text-muted-foreground">{t('payees.lastTransaction')}</p>
+ <p className="text-sm font-medium">
+ {summaryData.last_transaction_date
+ ? new Date(summaryData.last_transaction_date + 'T00:00:00').toLocaleDateString(dateLocale)
+ : '—'}
+ </p>
+ </div>
+ </div>
+ {summaryData.most_common_category && (
+ <p className="text-xs text-muted-foreground">
+ {t('payees.topCategory')}: <span className="font-medium text-foreground">{summaryData.most_common_category.name}</span>
+ </p>
+ )}
+
+ {/* Recent transactions */}
+ {recentTxData && recentTxData.items.length > 0 && (
+ <div className="pt-3 border-t border-border space-y-2">
+ <p className="text-xs font-medium text-muted-foreground">{t('dashboard.recentTransactions')}</p>
+ <div className="divide-y divide-border rounded-lg border border-border overflow-hidden">
+ {recentTxData.items.map((tx) => (
+ <div key={tx.id} className="flex items-center justify-between px-3 py-2 bg-background text-sm">
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium text-foreground truncate">{tx.description}</p>
+ <p className="text-xs text-muted-foreground">
+ {new Date(tx.date + 'T00:00:00').toLocaleDateString(dateLocale)}
+ {tx.category?.name && <> · {tx.category.name}</>}
+ </p>
+ </div>
+ <span className={`text-sm font-semibold tabular-nums ml-3 ${tx.type === 'debit' ? 'text-rose-500' : 'text-emerald-600'}`}>
+ {mask(formatCurrency(tx.amount, tx.currency, locale))}
+ </span>
+ </div>
+ ))}
+ </div>
+ {recentTxData.total > 5 && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-full text-xs text-muted-foreground hover:text-foreground gap-1"
+ onClick={() => navigate(`/transactions?payee_id=${summaryPayee}`)}
+ >
+ {t('payees.viewAllTransactions', { count: recentTxData.total })}
+ <ArrowRight size={12} />
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ ) : null}
+ </div>
+ )}
+
{/* Table */}
<div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden mb-4">
{isLoading ? (
@@ -562,7 +738,9 @@ export default function PayeesPage() {
)}
</TableCell>
<TableCell className="hidden md:table-cell py-2.5">
- <span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full capitalize">{typeLabels[payee.type] ?? payee.type}</span>
+ {payee.type && (
+ <span className="text-xs bg-muted text-muted-foreground px-2 py-0.5 rounded-full capitalize">{typeLabels[payee.type]}</span>
+ )}
</TableCell>
<TableCell className="py-2.5 text-right">
<span className="text-sm tabular-nums text-muted-foreground">{payee.transaction_count}</span>
@@ -606,96 +784,17 @@ export default function PayeesPage() {
)}
</div>
- {/* Summary panel */}
- {summaryPayee && (
- <div className="bg-card rounded-xl border border-border shadow-sm p-5 mb-4">
- {summaryLoading ? (
- <Skeleton className="h-24 w-full" />
- ) : summaryData ? (
- <div className="space-y-3">
- <div className="flex items-center justify-between">
- <h3 className="text-lg font-bold">{summaryData.payee.name}</h3>
- <Button variant="ghost" size="sm" onClick={() => setSummaryPayee(null)}>
- &times;
- </Button>
- </div>
- <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
- <div>
- <p className="text-xs text-muted-foreground">{t('payees.totalSpent')}</p>
- <p className="text-lg font-bold text-rose-500 tabular-nums">
- {mask(formatCurrency(summaryData.total_spent, userCurrency, locale))}
- </p>
- </div>
- <div>
- <p className="text-xs text-muted-foreground">{t('payees.totalReceived')}</p>
- <p className="text-lg font-bold text-emerald-600 tabular-nums">
- {mask(formatCurrency(summaryData.total_received, userCurrency, locale))}
- </p>
- </div>
- <div>
- <p className="text-xs text-muted-foreground">{t('payees.transactionCount')}</p>
- <p className="text-lg font-bold tabular-nums">{summaryData.transaction_count}</p>
- </div>
- <div>
- <p className="text-xs text-muted-foreground">{t('payees.lastTransaction')}</p>
- <p className="text-sm font-medium">
- {summaryData.last_transaction_date
- ? new Date(summaryData.last_transaction_date + 'T00:00:00').toLocaleDateString(dateLocale)
- : '—'}
- </p>
- </div>
- </div>
- {summaryData.most_common_category && (
- <p className="text-xs text-muted-foreground">
- {t('payees.topCategory')}: <span className="font-medium text-foreground">{summaryData.most_common_category.name}</span>
- </p>
- )}
-
- {/* Recent transactions */}
- {recentTxData && recentTxData.items.length > 0 && (
- <div className="pt-3 border-t border-border space-y-2">
- <p className="text-xs font-medium text-muted-foreground">{t('dashboard.recentTransactions')}</p>
- <div className="divide-y divide-border rounded-lg border border-border overflow-hidden">
- {recentTxData.items.map((tx) => (
- <div key={tx.id} className="flex items-center justify-between px-3 py-2 bg-background text-sm">
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium text-foreground truncate">{tx.description}</p>
- <p className="text-xs text-muted-foreground">
- {new Date(tx.date + 'T00:00:00').toLocaleDateString(dateLocale)}
- {tx.category?.name && <> · {tx.category.name}</>}
- </p>
- </div>
- <span className={`text-sm font-semibold tabular-nums ml-3 ${tx.type === 'debit' ? 'text-rose-500' : 'text-emerald-600'}`}>
- {mask(formatCurrency(tx.amount, tx.currency, locale))}
- </span>
- </div>
- ))}
- </div>
- {recentTxData.total > 5 && (
- <Button
- variant="ghost"
- size="sm"
- className="w-full text-xs text-muted-foreground hover:text-foreground gap-1"
- onClick={() => navigate(`/transactions?payee_id=${summaryPayee}`)}
- >
- {t('payees.viewAllTransactions', { count: recentTxData.total })}
- <ArrowRight size={12} />
- </Button>
- )}
- </div>
- )}
- </div>
- ) : null}
- </div>
- )}
-
{/* Create/Edit Dialog */}
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
- <DialogContent className="sm:max-w-md">
+ {/* The body scrolls, the footer does not: with contact details plus a
+ jurisdiction's worth of document fields this form is taller than a
+ laptop viewport, and a Save button below the fold is a Save button
+ nobody can reach. Mirrors transaction-dialog. */}
+ <DialogContent className="sm:max-w-md flex flex-col max-h-[calc(100dvh-2rem)]">
<DialogHeader>
<DialogTitle>{editingPayee ? t('payees.edit') : t('payees.add')}</DialogTitle>
</DialogHeader>
- <div className="space-y-4">
+ <div className="space-y-4 overflow-y-auto flex-1 -mx-1 px-1">
<div className="space-y-2">
<Label>{t('payees.name')}</Label>
<Input value={formName} onChange={(e) => setFormName(e.target.value)} required />
@@ -705,9 +804,12 @@ export default function PayeesPage() {
<select
className="w-full border border-border rounded-md px-3 py-2 text-sm bg-card focus:outline-none focus-visible:ring-ring/30 focus-visible:ring-[2px]"
value={formType}
- onChange={(e) => setFormType(e.target.value)}
+ onChange={(e) => setFormType(e.target.value as FormType)}
>
- <option value="merchant">{t('payees.typeMerchant')}</option>
+ {/* Unset first, and it is the default: the legal nature
+ only matters once a document is attached, and the
+ document settles it anyway. */}
+ <option value="">{t('payees.typeUnset', 'Not specified')}</option>
<option value="person">{t('payees.typePerson')}</option>
<option value="company">{t('payees.typeCompany')}</option>
</select>
@@ -721,6 +823,116 @@ export default function PayeesPage() {
onChange={(e) => setFormNotes(e.target.value)}
/>
</div>
+
+ {/* Contact and billing. Every field optional: most rows here were
+ created by sync for a card merchant and will never need any. */}
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-2">
+ <Label>{t('payees.email', 'Email')}</Label>
+ <Input
+ type="email"
+ value={formEmail}
+ onChange={(e) => setFormEmail(e.target.value)}
+ placeholder="[email protected]"
+ />
+ </div>
+ <div className="space-y-2">
+ <Label>{t('payees.phone', 'Phone')}</Label>
+ <Input value={formPhone} onChange={(e) => setFormPhone(e.target.value)} />
+ </div>
+ </div>
+ <div className="space-y-2">
+ <Label>{t('payees.address', 'Address')}</Label>
+ <Input value={formAddress} onChange={(e) => setFormAddress(e.target.value)} />
+ </div>
+ <div className="space-y-2">
+ <Label>{t('payees.website', 'Website')}</Label>
+ <Input
+ value={formWebsite}
+ onChange={(e) => setFormWebsite(e.target.value)}
+ placeholder="acme.com"
+ />
+ </div>
+
+ {/* Fiscal documents. Which ones appear comes from the workspace's
+ jurisdiction; the rest stay reachable through "other", since a
+ counterparty abroad has documents this jurisdiction never
+ asks for. */}
+ {allKinds.length > 0 && (
+ <div className="space-y-2">
+ <Label>{t('payees.taxIds', 'Tax IDs')}</Label>
+ {taxIdRows.length === 0 && (
+ <p className="text-[11px] text-muted-foreground leading-relaxed">
+ {t('payees.taxIdsEmpty', 'None yet. Add one if you need it for tax purposes.')}
+ </p>
+ )}
+ {taxIdRows.map((row, index) => {
+ const option = kindOption(row.kind)
+ return (
+ <div key={index} className="flex items-center gap-2">
+ <TaxIdKindPicker
+ kinds={allKinds}
+ jurisdictions={taxIdMeta?.jurisdictions ?? []}
+ activeJurisdiction={taxIdMeta?.jurisdiction ?? null}
+ value={row.kind}
+ documentValue={row.value}
+ used={usedKinds}
+ onChange={(kind) =>
+ setTaxIdRows((prev) =>
+ prev.map((r, i) =>
+ i === index
+ ? // Re-mask under the new kind: what the user typed
+ // for a CNPJ is not formatted like a VAT id.
+ { kind, value: applyMask(r.value, kindOption(kind)?.mask ?? null) }
+ : r,
+ ),
+ )
+ }
+ />
+ <Input
+ value={row.value}
+ onChange={(e) =>
+ setTaxIdRows((prev) =>
+ prev.map((r, i) =>
+ i === index
+ ? { ...r, value: applyMask(e.target.value, option?.mask ?? null) }
+ : r,
+ ),
+ )
+ }
+ placeholder={option?.mask ?? ''}
+ />
+ <Button
+ variant="ghost"
+ size="icon"
+ aria-label={t('common.remove', 'Remove')}
+ onClick={() => setTaxIdRows((prev) => prev.filter((_, i) => i !== index))}
+ >
+ <X size={14} className="text-muted-foreground" />
+ </Button>
+ </div>
+ )
+ })}
+ {usedKinds.size < allKinds.length && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-full"
+ onClick={() => {
+ // Default to the jurisdiction's primary document, which is
+ // the one the overwhelming majority of rows will use.
+ const next =
+ localKinds.find((k) => !usedKinds.has(k.kind)) ??
+ allKinds.find((k) => !usedKinds.has(k.kind))
+ if (next) setTaxIdRows((prev) => [...prev, { kind: next.kind, value: '' }])
+ }}
+ >
+ <Plus size={14} className="mr-1" />
+ {t('payees.addTaxId', 'Add')}
+ </Button>
+ )}
+ </div>
+ )}
</div>
<DialogFooter className={editingPayee ? 'flex justify-between sm:justify-between' : ''}>
{editingPayee && (
diff --git a/frontend/src/pages/workspace-settings.tsx b/frontend/src/pages/workspace-settings.tsx
index 0a246fd3..b0a84a80 100644
--- a/frontend/src/pages/workspace-settings.tsx
+++ b/frontend/src/pages/workspace-settings.tsx
@@ -1,10 +1,10 @@
-import { useEffect, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useDateLocale } from '@/hooks/use-display-locale'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
-import { auth as authApi, currencies as currenciesApi, workspaces as workspacesApi } from '@/lib/api'
+import { auth as authApi, currencies as currenciesApi, fiscal as fiscalApi, workspaces as workspacesApi } from '@/lib/api'
import { useAuth } from '@/contexts/auth-context'
import { useWorkspace } from '@/contexts/workspace-context'
import { Button } from '@/components/ui/button'
@@ -37,6 +37,8 @@ import {
} from '@/components/ui/dialog'
import { AlertTriangle, Archive, Plus, Save, Trash2, Users } from 'lucide-react'
import { WORKSPACE_KIND_LABEL_KEY } from '@/lib/workspace-kinds'
+import { countryFlag } from '@/lib/country-flag'
+import { countryName } from '@/lib/country-name'
import type { WorkspaceKind, WorkspaceMember, WorkspaceRole } from '@/types'
function labelForRole(role: WorkspaceRole, t: (key: string) => string): string {
@@ -73,7 +75,7 @@ const DEFAULT_WORKSPACE_COLOR = '#6366F1'
const DEFAULT_WORKSPACE_ICON = 'briefcase'
export default function WorkspaceSettingsPage() {
- const { t } = useTranslation()
+ const { t, i18n } = useTranslation()
const navigate = useNavigate()
const localeForFormat = useDateLocale()
const { current, canManage, workspaces: allWorkspaces, refresh, switchWorkspace } = useWorkspace()
@@ -83,6 +85,7 @@ export default function WorkspaceSettingsPage() {
const [editName, setEditName] = useState('')
const [editCurrency, setEditCurrency] = useState('')
const [editLocale, setEditLocale] = useState('')
+ const [editJurisdiction, setEditJurisdiction] = useState('')
const [editIcon, setEditIcon] = useState(DEFAULT_WORKSPACE_ICON)
const [editColor, setEditColor] = useState(DEFAULT_WORKSPACE_COLOR)
const [inviteOpen, setInviteOpen] = useState(false)
@@ -97,9 +100,18 @@ export default function WorkspaceSettingsPage() {
setEditName(current.name)
setEditCurrency(current.default_currency)
setEditLocale(current.locale ?? '')
+ setEditJurisdiction(current.tax_jurisdiction ?? '')
setEditIcon(current.icon ?? DEFAULT_WORKSPACE_ICON)
setEditColor(current.color ?? DEFAULT_WORKSPACE_COLOR)
- }, [current?.id, current?.name, current?.default_currency, current?.locale, current?.icon, current?.color])
+ }, [current?.id, current?.name, current?.default_currency, current?.locale, current?.tax_jurisdiction, current?.icon, current?.color])
+
+ // Which jurisdictions ship a pack. An empty choice is valid, not missing:
+ // with none set, documents are stored as free text with no mask.
+ const { data: jurisdictions } = useQuery({
+ queryKey: ['fiscal-jurisdictions'],
+ queryFn: fiscalApi.jurisdictions,
+ staleTime: Infinity,
+ })
const membersQuery = useQuery({
queryKey: ['workspace-members', current?.id],
@@ -113,6 +125,16 @@ export default function WorkspaceSettingsPage() {
staleTime: Infinity,
})
+ // The server lists codes; the user reads names. Sorted by the name actually
+ // shown, in the reader's own collation.
+ const sortedJurisdictions = useMemo(
+ () =>
+ [...(jurisdictions ?? [])].sort((a, b) =>
+ countryName(a, i18n.language).localeCompare(countryName(b, i18n.language), i18n.language),
+ ),
+ [jurisdictions, i18n.language],
+ )
+
const statsQuery = useQuery({
queryKey: ['workspace-stats', current?.id],
queryFn: () => (current ? workspacesApi.stats(current.id) : Promise.resolve({ members: 0, accounts: 0, transactions: 0 })),
@@ -126,6 +148,7 @@ export default function WorkspaceSettingsPage() {
name: editName,
default_currency: editCurrency,
locale: editLocale || (null as unknown as string),
+ tax_jurisdiction: editJurisdiction || null,
icon: editIcon,
color: editColor,
})
@@ -371,8 +394,8 @@ export default function WorkspaceSettingsPage() {
</div>
</div>
- {/* Region row — currency + locale */}
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ {/* Region row — currency, language, and where the workspace files */}
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div className="space-y-1.5">
<Label htmlFor="ws-currency" className="text-[13px]">
{t('workspace.defaultCurrency')}
@@ -422,6 +445,35 @@ export default function WorkspaceSettingsPage() {
</SelectContent>
</Select>
</div>
+ <div className="space-y-1.5">
+ <Label htmlFor="ws-jurisdiction" className="text-[13px]">
+ {t('workspace.taxJurisdiction', 'Tax jurisdiction')}
+ </Label>
+ <Select
+ value={editJurisdiction || '__none__'}
+ onValueChange={(v) => setEditJurisdiction(v === '__none__' ? '' : v)}
+ disabled={!canManage}
+ >
+ <SelectTrigger id="ws-jurisdiction" className="h-10 rounded-lg w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="__none__">—</SelectItem>
+ {sortedJurisdictions.map((code) => (
+ <SelectItem key={code} value={code}>
+ <span className="mr-2">{countryFlag(code)}</span>
+ {countryName(code, i18n.language)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-[11px] text-muted-foreground leading-relaxed">
+ {t(
+ 'workspace.taxJurisdictionHint',
+ 'Decides which fiscal documents this workspace is offered. Separate from the interface language.',
+ )}
+ </p>
+ </div>
</div>
</div>
</section>
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index ab3968ff..9ab444e3 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -56,6 +56,9 @@ export interface Workspace {
is_archived: boolean
default_currency: string
locale: string | null
+ /** Where the workspace files. Selects the fiscal document pack; never the
+ * interface language. */
+ tax_jurisdiction: string | null
icon: string | null
color: string | null
created_at: string
@@ -373,17 +376,42 @@ export interface GroupBalances {
lines: GroupBalanceLine[]
}
+/** A fiscal document belonging to a payee. `kind` mirrors the backend's
+ * closed TaxIdKind; the value arrives normalised. */
+export interface PayeeTaxId {
+ kind: string
+ value: string
+}
+
export interface Payee {
id: string
user_id: string
name: string
- type: 'merchant' | 'person' | 'company'
+ /** Legal nature, or null when unknown — the normal state for a row sync created. */
+ type: 'person' | 'company' | null
+ /** Where the row came from. Server-set at creation and never editable. */
+ source: 'manual' | 'sync' | 'import'
is_favorite: boolean
notes: string | null
+ email: string | null
+ phone: string | null
+ address: string | null
+ website: string | null
+ tax_ids: PayeeTaxId[]
created_at: string
transaction_count: number
}
+/** One document kind as the active workspace's jurisdiction describes it.
+ * `offered` marks the ones its pack asks for; the rest stay selectable,
+ * because a counterparty's country is not the workspace's. */
+export interface TaxIdKindOption {
+ kind: string
+ label_key: string
+ mask: string | null
+ offered: boolean
+}
+
export interface PayeeSummary {
payee: Payee
total_spent: number