Skip to content

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

feat(invoices): product catalog that fills invoice lines (#1014)

Tássio Noronhaf475d9f895dc
diff --git a/backend/alembic/versions/094_products.py b/backend/alembic/versions/094_products.py
new file mode 100644
index 00000000..48ae4b77
--- /dev/null
+++ b/backend/alembic/versions/094_products.py
@@ -0,0 +1,139 @@
+"""the catalog: products, their prices, and the link from an invoice line
+
+ - `products` is what a workspace sells: a name, a kind (service or
+ goods), a default unit, an active flag, and the external identity a
+ gateway import converges on.
+ - `product_prices` is how each one is charged: currency, amount, an
+ optional tax rate, and an optional cadence. One product, many prices.
+ - `invoice_lines.product_id` / `price_id` say where a line came from,
+ and `fiscal_refs` is the product's fiscal references (a goods or
+ service classification) as copied at that moment. Provenance and a
+ copy: the line keeps its own values, so nothing about existing
+ invoices changes and every new column starts null.
+
+Revision ID: 094
+Revises: 093
+"""
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+revision = "094"
+down_revision = "093"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "products",
+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=True),
+ sa.Column("name", sa.String(length=200), nullable=False),
+ sa.Column("description", sa.Text(), nullable=True),
+ sa.Column("kind", sa.String(length=20), server_default="service", nullable=False),
+ sa.Column("unit", sa.String(length=20), nullable=True),
+ sa.Column("active", sa.Boolean(), server_default="true", nullable=False),
+ sa.Column("origin", sa.String(length=20), server_default="local", nullable=False),
+ sa.Column("external_source", sa.String(length=50), nullable=True),
+ sa.Column("external_id", sa.String(length=255), nullable=True),
+ sa.Column("custom_fields", sa.JSON(), nullable=True),
+ sa.Column("fiscal_refs", sa.JSON(), nullable=True),
+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="SET NULL"),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "workspace_id", "external_source", "external_id", name="uq_products_workspace_external"
+ ),
+ sa.CheckConstraint("kind IN ('service', 'product')", name="ck_products_kind"),
+ sa.CheckConstraint("origin IN ('local', 'imported')", name="ck_products_origin"),
+ )
+ op.create_index("ix_products_workspace_id", "products", ["workspace_id"])
+ op.create_index("ix_products_workspace_active", "products", ["workspace_id", "active"])
+
+ op.create_table(
+ "product_prices",
+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("product_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("currency", sa.String(length=3), nullable=False),
+ sa.Column("unit_price", sa.Numeric(precision=15, scale=2), nullable=False),
+ sa.Column("tax_rate", sa.Numeric(precision=7, scale=4), nullable=True),
+ sa.Column("billing", sa.String(length=20), server_default="one_time", nullable=False),
+ sa.Column("interval", sa.String(length=20), nullable=True),
+ sa.Column("nickname", sa.String(length=100), nullable=True),
+ sa.Column("lookup_key", sa.String(length=200), nullable=True),
+ sa.Column("active", sa.Boolean(), server_default="true", nullable=False),
+ sa.Column("external_source", sa.String(length=50), nullable=True),
+ sa.Column("external_id", sa.String(length=255), nullable=True),
+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
+ sa.ForeignKeyConstraint(["product_id"], ["products.id"], ondelete="CASCADE"),
+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "workspace_id",
+ "external_source",
+ "external_id",
+ name="uq_product_prices_workspace_external",
+ ),
+ sa.UniqueConstraint("workspace_id", "lookup_key", name="uq_product_prices_lookup_key"),
+ sa.CheckConstraint("unit_price >= 0", name="ck_product_prices_unit_price"),
+ sa.CheckConstraint(
+ "billing IN ('one_time', 'recurring')", name="ck_product_prices_billing"
+ ),
+ sa.CheckConstraint(
+ "(billing = 'one_time' AND interval IS NULL)"
+ " OR (billing = 'recurring' AND interval IN"
+ " ('weekly', 'biweekly', 'monthly', 'quarterly', 'semiannual', 'yearly'))",
+ name="ck_product_prices_interval",
+ ),
+ )
+ op.create_index("ix_product_prices_product", "product_prices", ["product_id"])
+ op.create_index("ix_product_prices_workspace_id", "product_prices", ["workspace_id"])
+
+ op.add_column(
+ "invoice_lines", sa.Column("product_id", postgresql.UUID(as_uuid=True), nullable=True)
+ )
+ op.add_column(
+ "invoice_lines", sa.Column("price_id", postgresql.UUID(as_uuid=True), nullable=True)
+ )
+ op.add_column("invoice_lines", sa.Column("fiscal_refs", sa.JSON(), nullable=True))
+ op.create_foreign_key(
+ "fk_invoice_lines_product_id",
+ "invoice_lines",
+ "products",
+ ["product_id"],
+ ["id"],
+ ondelete="SET NULL",
+ )
+ op.create_foreign_key(
+ "fk_invoice_lines_price_id",
+ "invoice_lines",
+ "product_prices",
+ ["price_id"],
+ ["id"],
+ ondelete="SET NULL",
+ )
+ op.create_index("ix_invoice_lines_product_id", "invoice_lines", ["product_id"])
+
+
+def downgrade() -> None:
+ # The lines keep every value they were given; only the memory of
+ # which catalog entry they came from is lost.
+ op.drop_index("ix_invoice_lines_product_id", table_name="invoice_lines")
+ op.drop_constraint("fk_invoice_lines_price_id", "invoice_lines", type_="foreignkey")
+ op.drop_constraint("fk_invoice_lines_product_id", "invoice_lines", type_="foreignkey")
+ op.drop_column("invoice_lines", "fiscal_refs")
+ op.drop_column("invoice_lines", "price_id")
+ op.drop_column("invoice_lines", "product_id")
+
+ op.drop_index("ix_product_prices_workspace_id", table_name="product_prices")
+ op.drop_index("ix_product_prices_product", table_name="product_prices")
+ op.drop_table("product_prices")
+
+ op.drop_index("ix_products_workspace_active", table_name="products")
+ op.drop_index("ix_products_workspace_id", table_name="products")
+ op.drop_table("products")
diff --git a/backend/app/api/fiscal.py b/backend/app/api/fiscal.py
index dd8330bf..0f9454ed 100644
--- a/backend/app/api/fiscal.py
+++ b/backend/app/api/fiscal.py
@@ -45,6 +45,25 @@ async def list_jurisdictions():
return {"jurisdictions": available_jurisdictions()}
[email protected]("/product-fields")
+async def list_product_fields(ctx: WorkspaceContext = Depends(current_workspace)):
+ """Fiscal references this jurisdiction asks for on a catalog item.
+
+ Suggestions for the product form: which keys to offer, under which
+ label, for which kind of product. A workspace may store any key it
+ likes on top of these; an empty list is a valid answer for a country
+ whose pack has no opinion yet.
+ """
+ pack = pack_for(ctx.workspace.tax_jurisdiction)
+ return {
+ "jurisdiction": pack.code or None,
+ "fields": [
+ {"key": f.key, "label_key": f.label_key, "kinds": list(f.kinds)}
+ for f in pack.product_fields
+ ],
+ }
+
+
@router.get("/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.
diff --git a/backend/app/api/products.py b/backend/app/api/products.py
new file mode 100644
index 00000000..b745f489
--- /dev/null
+++ b/backend/app/api/products.py
@@ -0,0 +1,179 @@
+"""Catalog routes.
+
+Gated like `/api/invoices`: the catalog exists to write invoice lines,
+so a workspace without the invoices module has no catalog, and gets the
+same 404 the invoice routes give it.
+"""
+import uuid
+from typing import Optional
+
+from fastapi import APIRouter, Depends, HTTPException, Query, status
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.invoices import _http
+from app.core.database import get_async_session
+from app.core.module_gate import require_module, require_module_write
+from app.core.workspace_context import WorkspaceContext
+from app.models.product import Product
+from app.schemas.product import (
+ PriceInput,
+ PriceRead,
+ PriceUpdate,
+ ProductCreate,
+ ProductRead,
+ ProductUpdate,
+)
+from app.services import product_service as svc
+from app.services.invoice_service import InvoiceError
+from app.services.module_service import ModuleId
+
+router = APIRouter(prefix="/api/products", tags=["products"])
+
+read_ctx = require_module(ModuleId.INVOICES)
+write_ctx = require_module_write(ModuleId.INVOICES)
+
+
+def _serialize(product: Product, invoice_count: int = 0) -> ProductRead:
+ payload = ProductRead.model_validate(product, from_attributes=True)
+ payload.invoice_count = invoice_count
+ return payload
+
+
+async def _load(session: AsyncSession, product_id: uuid.UUID, workspace_id: uuid.UUID) -> Product:
+ product = await svc.get_product(session, product_id, workspace_id)
+ if product is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Product not found")
+ return product
+
+
+async def _read(session: AsyncSession, product_id: uuid.UUID, workspace_id: uuid.UUID) -> ProductRead:
+ product = await _load(session, product_id, workspace_id)
+ counts = await svc.usage_counts(session, workspace_id, [product.id])
+ return _serialize(product, counts.get(product.id, 0))
+
+
[email protected]("", response_model=list[ProductRead])
+async def list_products(
+ active: Optional[bool] = Query(True, description="None for every product, archived included"),
+ kind: Optional[str] = Query(None),
+ q: Optional[str] = Query(None),
+ ctx: WorkspaceContext = Depends(read_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ products = await svc.list_products(session, ctx.workspace.id, active=active, kind=kind, q=q)
+ counts = await svc.usage_counts(session, ctx.workspace.id, [p.id for p in products])
+ return [_serialize(p, counts.get(p.id, 0)) for p in products]
+
+
[email protected]("", response_model=ProductRead, status_code=status.HTTP_201_CREATED)
+async def create_product(
+ payload: ProductCreate,
+ ctx: WorkspaceContext = Depends(write_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ data = payload.model_dump(exclude_unset=True)
+ data["prices"] = [dict(p) for p in data.get("prices") or []]
+ try:
+ product = await svc.create_product(session, ctx.workspace.id, ctx.user_id, data)
+ except InvoiceError as exc:
+ raise _http(exc)
+ await session.commit()
+ return await _read(session, product.id, ctx.workspace.id)
+
+
[email protected]("/{product_id}", response_model=ProductRead)
+async def get_product(
+ product_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(read_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ return await _read(session, product_id, ctx.workspace.id)
+
+
[email protected]("/{product_id}", response_model=ProductRead)
+async def update_product(
+ product_id: uuid.UUID,
+ payload: ProductUpdate,
+ ctx: WorkspaceContext = Depends(write_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ product = await _load(session, product_id, ctx.workspace.id)
+ try:
+ await svc.update_product(session, product, payload.model_dump(exclude_unset=True))
+ except InvoiceError as exc:
+ raise _http(exc)
+ await session.commit()
+ return await _read(session, product_id, ctx.workspace.id)
+
+
[email protected]("/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_product(
+ product_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(write_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ product = await _load(session, product_id, ctx.workspace.id)
+ try:
+ await svc.delete_product(session, product)
+ except InvoiceError as exc:
+ raise _http(exc)
+ await session.commit()
+
+
[email protected]("/{product_id}/prices", response_model=ProductRead, status_code=status.HTTP_201_CREATED)
+async def add_price(
+ product_id: uuid.UUID,
+ payload: PriceInput,
+ ctx: WorkspaceContext = Depends(write_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ product = await _load(session, product_id, ctx.workspace.id)
+ try:
+ await svc.add_price(session, product, payload.model_dump(exclude_unset=True))
+ except InvoiceError as exc:
+ raise _http(exc)
+ await session.commit()
+ return await _read(session, product_id, ctx.workspace.id)
+
+
[email protected]("/{product_id}/prices/{price_id}", response_model=ProductRead)
+async def update_price(
+ product_id: uuid.UUID,
+ price_id: uuid.UUID,
+ payload: PriceUpdate,
+ ctx: WorkspaceContext = Depends(write_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ product = await _load(session, product_id, ctx.workspace.id)
+ price = next((p for p in product.prices if p.id == price_id), None)
+ if price is None:
+ raise HTTPException(status_code=404, detail="Price not found")
+ try:
+ await svc.update_price(session, product, price, payload.model_dump(exclude_unset=True))
+ except InvoiceError as exc:
+ raise _http(exc)
+ await session.commit()
+ return await _read(session, product_id, ctx.workspace.id)
+
+
[email protected]("/{product_id}/prices/{price_id}", response_model=ProductRead)
+async def delete_price(
+ product_id: uuid.UUID,
+ price_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(write_ctx),
+ session: AsyncSession = Depends(get_async_session),
+):
+ product = await _load(session, product_id, ctx.workspace.id)
+ price = next((p for p in product.prices if p.id == price_id), None)
+ if price is None:
+ raise HTTPException(status_code=404, detail="Price not found")
+ try:
+ await svc.delete_price(session, product, price)
+ except InvoiceError as exc:
+ raise _http(exc)
+ await session.commit()
+ return await _read(session, product_id, ctx.workspace.id)
+
+
+# `PriceRead` is exported for the OpenAPI schema of the nested list.
+__all__ = ["router", "PriceRead"]
diff --git a/backend/app/fiscal/jurisdictions/at.toml b/backend/app/fiscal/jurisdictions/at.toml
index dfc80711..b921bf5e 100644
--- a/backend/app/fiscal/jurisdictions/at.toml
+++ b/backend/app/fiscal/jurisdictions/at.toml
@@ -2,3 +2,12 @@
# does not go on an invoice.
code = "AT"
kinds = ["vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/au.toml b/backend/app/fiscal/jurisdictions/au.toml
index 4e4a171e..c0017b50 100644
--- a/backend/app/fiscal/jurisdictions/au.toml
+++ b/backend/app/fiscal/jurisdictions/au.toml
@@ -2,3 +2,12 @@
# identifies the company at ASIC.
code = "AU"
kinds = ["abn"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/be.toml b/backend/app/fiscal/jurisdictions/be.toml
index 2c5b4a84..38b7918f 100644
--- a/backend/app/fiscal/jurisdictions/be.toml
+++ b/backend/app/fiscal/jurisdictions/be.toml
@@ -2,3 +2,12 @@
# prefix.
code = "BE"
kinds = ["vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/br.toml b/backend/app/fiscal/jurisdictions/br.toml
index 298ae237..99e2c3b3 100644
--- a/backend/app/fiscal/jurisdictions/br.toml
+++ b/backend/app/fiscal/jurisdictions/br.toml
@@ -2,3 +2,25 @@
# registrations that NFS-e asks for.
code = "BR"
kinds = ["cnpj", "cpf", "ie", "im"]
+
+# What a fiscal document needs per line and the invoice cannot invent.
+# NCM classifies goods, NBS and the LC 116 service code classify services,
+# and the municipal code is what each city's NFS-e system actually keys on.
+[[product_fields]]
+key = "ncm"
+kinds = ["product"]
+[[product_fields]]
+key = "cest"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
+[[product_fields]]
+key = "service_code"
+kinds = ["service"]
+[[product_fields]]
+key = "nbs"
+kinds = ["service"]
+[[product_fields]]
+key = "municipal_service_code"
+kinds = ["service"]
diff --git a/backend/app/fiscal/jurisdictions/ca.toml b/backend/app/fiscal/jurisdictions/ca.toml
index 79ab8898..a9a55ef5 100644
--- a/backend/app/fiscal/jurisdictions/ca.toml
+++ b/backend/app/fiscal/jurisdictions/ca.toml
@@ -2,3 +2,12 @@
# suffix to it.
code = "CA"
kinds = ["ca_bn"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/de.toml b/backend/app/fiscal/jurisdictions/de.toml
index e0ce0e89..960ec4fa 100644
--- a/backend/app/fiscal/jurisdictions/de.toml
+++ b/backend/app/fiscal/jurisdictions/de.toml
@@ -2,3 +2,12 @@
# intra-EU VAT id, the Steuernummer is the domestic one.
code = "DE"
kinds = ["vat", "steuernummer"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/es.toml b/backend/app/fiscal/jurisdictions/es.toml
index 27a30dd8..1d91928b 100644
--- a/backend/app/fiscal/jurisdictions/es.toml
+++ b/backend/app/fiscal/jurisdictions/es.toml
@@ -1,3 +1,12 @@
# Spain. NIF covers the DNI and NIE shapes.
code = "ES"
kinds = ["es_nif", "vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/fr.toml b/backend/app/fiscal/jurisdictions/fr.toml
index 9f10935c..ab5a7a82 100644
--- a/backend/app/fiscal/jurisdictions/fr.toml
+++ b/backend/app/fiscal/jurisdictions/fr.toml
@@ -1,3 +1,12 @@
# France. SIRET identifies the establishment.
code = "FR"
kinds = ["siret", "vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/gb.toml b/backend/app/fiscal/jurisdictions/gb.toml
index 3a01f89f..e78aaece 100644
--- a/backend/app/fiscal/jurisdictions/gb.toml
+++ b/backend/app/fiscal/jurisdictions/gb.toml
@@ -2,3 +2,12 @@
# same kind; only the country prefix differs.
code = "GB"
kinds = ["vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/ie.toml b/backend/app/fiscal/jurisdictions/ie.toml
index 5b9a6d79..ab87a2ab 100644
--- a/backend/app/fiscal/jurisdictions/ie.toml
+++ b/backend/app/fiscal/jurisdictions/ie.toml
@@ -1,3 +1,12 @@
# Ireland. The VAT number doubles as the tax reference for companies.
code = "IE"
kinds = ["vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/it.toml b/backend/app/fiscal/jurisdictions/it.toml
index b4c1ca71..ddaf28a1 100644
--- a/backend/app/fiscal/jurisdictions/it.toml
+++ b/backend/app/fiscal/jurisdictions/it.toml
@@ -2,3 +2,12 @@
# SDI destination code that e-invoicing routes on.
code = "IT"
kinds = ["partita_iva", "codice_fiscale", "sdi", "vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/mx.toml b/backend/app/fiscal/jurisdictions/mx.toml
index 806e624c..6869b442 100644
--- a/backend/app/fiscal/jurisdictions/mx.toml
+++ b/backend/app/fiscal/jurisdictions/mx.toml
@@ -2,3 +2,10 @@
# being what distinguishes two taxpayers with the same name and birth date.
code = "MX"
kinds = ["rfc"]
+
+# The SAT catalog keys every CFDI line: a product or service code and a
+# unit code, both from the official lists.
+[[product_fields]]
+key = "sat_product_code"
+[[product_fields]]
+key = "sat_unit_code"
diff --git a/backend/app/fiscal/jurisdictions/nl.toml b/backend/app/fiscal/jurisdictions/nl.toml
index f1dc4544..9070fa9c 100644
--- a/backend/app/fiscal/jurisdictions/nl.toml
+++ b/backend/app/fiscal/jurisdictions/nl.toml
@@ -2,3 +2,12 @@
# used on invoices any more.
code = "NL"
kinds = ["vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/pl.toml b/backend/app/fiscal/jurisdictions/pl.toml
index fce5611c..a135554a 100644
--- a/backend/app/fiscal/jurisdictions/pl.toml
+++ b/backend/app/fiscal/jurisdictions/pl.toml
@@ -2,3 +2,12 @@
# digits behind a PL prefix.
code = "PL"
kinds = ["nip", "vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/pt.toml b/backend/app/fiscal/jurisdictions/pt.toml
index 52c113df..fb492f43 100644
--- a/backend/app/fiscal/jurisdictions/pt.toml
+++ b/backend/app/fiscal/jurisdictions/pt.toml
@@ -2,3 +2,12 @@
# intra-EU number for cross-border invoicing.
code = "PT"
kinds = ["pt_nif", "vat"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/jurisdictions/us.toml b/backend/app/fiscal/jurisdictions/us.toml
index c60fa75a..99d2be8e 100644
--- a/backend/app/fiscal/jurisdictions/us.toml
+++ b/backend/app/fiscal/jurisdictions/us.toml
@@ -2,3 +2,12 @@
# individual equivalent that belongs on an invoice.
code = "US"
kinds = ["ein"]
+
+# Goods crossing a border carry a Harmonized System code; a barcode is
+# what most catalogs already have.
+[[product_fields]]
+key = "hs_code"
+kinds = ["product"]
+[[product_fields]]
+key = "gtin"
+kinds = ["product"]
diff --git a/backend/app/fiscal/registry.py b/backend/app/fiscal/registry.py
index e569f4db..f5c723d2 100644
--- a/backend/app/fiscal/registry.py
+++ b/backend/app/fiscal/registry.py
@@ -35,6 +35,7 @@ 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 re
import tomllib
from dataclasses import dataclass
from enum import Enum
@@ -221,17 +222,39 @@ def spec_for(kind: TaxIdKind) -> KindSpec:
return KIND_SPECS[kind]
+@dataclass(frozen=True)
+class ProductFieldSpec:
+ """A fiscal reference a jurisdiction asks for on a catalog item.
+
+ What the fiscal document will need per line and the invoice cannot
+ invent: a goods classification (NCM in Brazil, an HS code in the EU),
+ a service code, a barcode. Suggested by the pack, stored as free
+ text on the product, copied onto the line when the product fills
+ it. Any key stays storable in any workspace, for the same reason as
+ tax ids: the pack suggests, it never restricts.
+ """
+
+ key: str
+ label_key: str
+ #: Which kinds of product it applies to. Empty means both.
+ kinds: tuple[str, ...] = ()
+
+
@dataclass(frozen=True)
class JurisdictionPack:
code: str
#: Ordered. The first is what the UI defaults to; `other` is always last.
kinds: tuple[TaxIdKind, ...]
+ product_fields: tuple[ProductFieldSpec, ...] = ()
#: 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,))
+_PRODUCT_KINDS = ("service", "product")
+_FIELD_KEY = re.compile(r"^[a-z][a-z0-9_]{0,39}$")
+
def _load_pack(path: Path) -> JurisdictionPack:
raw = tomllib.loads(path.read_text(encoding="utf-8"))
@@ -244,7 +267,18 @@ def _load_pack(path: Path) -> JurisdictionPack:
# its pack never anticipated.
if TaxIdKind.OTHER not in kinds:
kinds.append(TaxIdKind.OTHER)
- return JurisdictionPack(code=code, kinds=tuple(kinds))
+ fields = []
+ for raw_field in raw.get("product_fields", []):
+ key = str(raw_field["key"])
+ if not _FIELD_KEY.match(key):
+ raise ValueError(f"{path.name}: product field key {key!r} is not a valid key")
+ applies = tuple(str(k) for k in raw_field.get("kinds", ()))
+ if any(k not in _PRODUCT_KINDS for k in applies):
+ raise ValueError(f"{path.name}: product field {key} names an unknown product kind")
+ fields.append(
+ ProductFieldSpec(key=key, label_key=f"fiscal.productField.{key}", kinds=applies)
+ )
+ return JurisdictionPack(code=code, kinds=tuple(kinds), product_fields=tuple(fields))
@lru_cache(maxsize=1)
diff --git a/backend/app/main.py b/backend/app/main.py
index de565e0b..bad681ea 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -37,6 +37,7 @@ from app.api.fiscal import router as fiscal_router
from app.api.invoice_attachments import router as invoice_attachments_router
from app.api.invoice_schedules import router as invoice_schedules_router
from app.api.invoices import router as invoices_router
+from app.api.products import router as products_router
from app.api.public_invoices import router as public_invoices_router
from app.api.payees import router as payees_router
from app.api.settings import router as settings_router
@@ -200,6 +201,7 @@ app.include_router(invoices_router)
app.include_router(invoice_attachments_router)
app.include_router(invoice_schedules_router)
app.include_router(public_invoices_router)
+app.include_router(products_router)
app.include_router(settings_router)
app.include_router(workspaces_router)
app.include_router(admin_router)
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 08cedfc7..20107828 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -28,6 +28,7 @@ from app.models.collection import Collection, collection_accounts, collection_as
from app.models.invoice import Invoice, InvoiceAllocation, InvoiceLine, InvoiceSettings
from app.models.invoice_attachment import InvoiceAttachment
from app.models.invoice_schedule import InvoiceSchedule, InvoiceScheduleTerm
+from app.models.product import Product, ProductPrice
from app.models.reconciliation import (
ReconciliationEvent,
ReconciliationRule,
@@ -79,6 +80,8 @@ __all__ = [
"InvoiceAttachment",
"InvoiceSchedule",
"InvoiceScheduleTerm",
+ "Product",
+ "ProductPrice",
"ReconciliationEvent",
"ReconciliationRule",
"ReconciliationSuggestion",
diff --git a/backend/app/models/invoice.py b/backend/app/models/invoice.py
index 8853cb62..65a61a97 100644
--- a/backend/app/models/invoice.py
+++ b/backend/app/models/invoice.py
@@ -86,7 +86,7 @@ INVOICE_DOCUMENT_TYPES = ("invoice", "credit_note")
INVOICE_DIRECTIONS = ("receivable", "payable")
#: Who authored the document. `imported` rows are reconstructed from an
-#: external system (Stripe, Asaas, a CSV): that system owns the document,
+#: external system (a payment gateway, a CSV): that system owns the document,
#: and Securo owns the cash that settled it.
INVOICE_ORIGINS = ("local", "imported")
@@ -118,7 +118,7 @@ class Invoice(Base):
"workspace_id", "series", "number", name="uq_invoices_workspace_series_number"
),
# An imported document is identified by its source's own id, so
- # two syncs of the same Stripe invoice converge on one row.
+ # two syncs of the same gateway invoice converge on one row.
UniqueConstraint(
"workspace_id",
"external_source",
@@ -353,6 +353,20 @@ class InvoiceLine(Base):
tax_rate: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=7, scale=4), nullable=True)
total: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2), default=Decimal("0"))
position: Mapped[int] = mapped_column(Integer, default=0)
+ # Where the line came from, when it came from the catalog. Provenance
+ # only: the fields above are the line's own copy, and neither id
+ # takes part in the arithmetic. SET NULL because the line is part of
+ # a document and outlives the catalog entry.
+ product_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("products.id", ondelete="SET NULL"), nullable=True, index=True
+ )
+ price_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("product_prices.id", ondelete="SET NULL"), nullable=True
+ )
+ # The product's fiscal references as they stood when the line was
+ # written (NCM, service code, HS code...). The line's own copy, for
+ # the same reason as every other value on it.
+ fiscal_refs: Mapped[Optional[dict[str, str]]] = mapped_column(JSON, nullable=True)
invoice: Mapped["Invoice"] = relationship(back_populates="lines")
diff --git a/backend/app/models/invoice_schedule.py b/backend/app/models/invoice_schedule.py
index 608db2e0..6d4b9d51 100644
--- a/backend/app/models/invoice_schedule.py
+++ b/backend/app/models/invoice_schedule.py
@@ -89,7 +89,7 @@ SCHEDULE_FREQUENCIES = ("weekly", "biweekly", "monthly", "quarterly", "semiannua
SCHEDULE_END_TYPES = ("never", "on_date", "after_count")
#: Who authored the agreement. An `imported` schedule mirrors one a
-#: gateway holds (a Stripe subscription): that system owns the terms and
+#: gateway holds (a subscription on its side): that system owns the terms and
#: emits the invoices, Securo groups them and owns the cash. The job
#: never generates for an imported schedule.
SCHEDULE_ORIGINS = ("local", "imported")
diff --git a/backend/app/models/product.py b/backend/app/models/product.py
new file mode 100644
index 00000000..396e0b7b
--- /dev/null
+++ b/backend/app/models/product.py
@@ -0,0 +1,191 @@
+"""The catalog: what a workspace sells, and for how much.
+
+Two tables, shaped after the split that has served billing systems for a
+decade: a **product** is the thing (a name, what kind of thing it is,
+what its quantity counts), and a **price** is one way of charging for
+it (a currency, an amount, optionally a cadence). One product carries as
+many prices as it has currencies or plans.
+
+The rule that keeps the catalog optional: **an invoice line never
+depends on the catalog**. Picking a product fills the line's own
+fields and remembers which product it was; the line then stands on its
+own copy. Renaming a product in October does not touch September's
+invoice, archiving it does not blank a line, and a workspace that never
+creates a product writes lines exactly as before. `product_id` on a
+line is provenance and grouping, the same way `schedule_id` is.
+
+Deliberately not here: stock, SKUs, fiscal classification per product,
+tiered or metered pricing. Those are where an ERP begins.
+"""
+import uuid
+from datetime import datetime, timezone
+from decimal import Decimal
+from typing import TYPE_CHECKING, Any, Optional
+
+from sqlalchemy import (
+ Boolean,
+ CheckConstraint,
+ DateTime,
+ ForeignKey,
+ Index,
+ JSON,
+ Numeric,
+ String,
+ Text,
+ UniqueConstraint,
+)
+from sqlalchemy.dialects.postgresql import UUID
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+
+from app.core.database import Base
+
+if TYPE_CHECKING:
+ pass
+
+#: What kind of thing is sold. Free text would do for the document, but
+#: the fiscal layer will need to know (a service note and a goods note
+#: are different documents in more than one jurisdiction), and a column
+#: added later is a migration over every row in every install.
+PRODUCT_KINDS = ("service", "product")
+
+#: How a price charges. `one_time` is a unit price; `recurring` is the
+#: same unit price with a cadence, which the recurring-invoice form and
+#: a gateway import both read as a hint.
+PRICE_BILLINGS = ("one_time", "recurring")
+
+#: Same vocabulary as recurring invoices, so a recurring price can seed
+#: an agreement without translation.
+PRICE_INTERVALS = ("weekly", "biweekly", "monthly", "quarterly", "semiannual", "yearly")
+
+#: Who authored the row. `imported` mirrors a payment gateway's catalog:
+#: that system owns it, and a re-sync converges on the same row through
+#: the external id.
+PRODUCT_ORIGINS = ("local", "imported")
+
+
+class Product(Base):
+ """One thing this workspace sells."""
+
+ __tablename__ = "products"
+ __table_args__ = (
+ UniqueConstraint(
+ "workspace_id", "external_source", "external_id", name="uq_products_workspace_external"
+ ),
+ # Every list is "this workspace's live products", so the two
+ # columns index together.
+ Index("ix_products_workspace_active", "workspace_id", "active"),
+ CheckConstraint("kind IN ('service', 'product')", name="ck_products_kind"),
+ CheckConstraint("origin IN ('local', 'imported')", name="ck_products_origin"),
+ )
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ workspace_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True
+ )
+ # Who created it, not who owns it: the catalog belongs to the
+ # workspace, so a member leaving takes nothing with them.
+ user_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), nullable=True
+ )
+
+ name: Mapped[str] = mapped_column(String(200))
+ description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+ kind: Mapped[str] = mapped_column(String(20), default="service", server_default="service")
+ # The default unit a line for this product counts in: hours, words,
+ # pieces. Copied onto the line, where it stays editable.
+ unit: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
+ # Archived rather than deleted once an invoice names it: the line
+ # keeps its copy either way, but a product that disappears from the
+ # picker while its invoices still say "that one" is confusing, and
+ # a product that keeps being offered after it stopped being sold is
+ # worse.
+ active: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
+
+ origin: Mapped[str] = mapped_column(String(20), default="local", server_default="local")
+ external_source: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+
+ custom_fields: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
+ # What a fiscal document will need per line: a goods classification,
+ # a service code, a barcode. Keys are suggested by the jurisdiction
+ # pack (`ncm`, `hs_code`, `service_code`...), values are text, and
+ # any key is storable because a pack suggests and never restricts.
+ # Copied onto the invoice line when the product fills it, so the
+ # document is drawn from what the line says, not from what the
+ # product says today.
+ fiscal_refs: Mapped[Optional[dict[str, str]]] = mapped_column(JSON, nullable=True)
+
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(timezone.utc),
+ onupdate=lambda: datetime.now(timezone.utc),
+ )
+
+ prices: Mapped[list["ProductPrice"]] = relationship(
+ back_populates="product",
+ cascade="all, delete-orphan",
+ order_by="ProductPrice.created_at",
+ lazy="selectin",
+ )
+
+
+class ProductPrice(Base):
+ """One way of charging for a product: a currency and an amount."""
+
+ __tablename__ = "product_prices"
+ __table_args__ = (
+ UniqueConstraint(
+ "workspace_id",
+ "external_source",
+ "external_id",
+ name="uq_product_prices_workspace_external",
+ ),
+ # A name of the workspace's own choosing (`pro_monthly`), unique
+ # among its prices, so an import or a script can find a price
+ # without knowing its id.
+ UniqueConstraint("workspace_id", "lookup_key", name="uq_product_prices_lookup_key"),
+ Index("ix_product_prices_product", "product_id"),
+ CheckConstraint("unit_price >= 0", name="ck_product_prices_unit_price"),
+ CheckConstraint(
+ "billing IN ('one_time', 'recurring')", name="ck_product_prices_billing"
+ ),
+ # A cadence belongs to a recurring price and to nothing else.
+ CheckConstraint(
+ "(billing = 'one_time' AND interval IS NULL)"
+ " OR (billing = 'recurring' AND interval IN"
+ " ('weekly', 'biweekly', 'monthly', 'quarterly', 'semiannual', 'yearly'))",
+ name="ck_product_prices_interval",
+ ),
+ )
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ product_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("products.id", ondelete="CASCADE")
+ )
+ workspace_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("workspaces.id", ondelete="CASCADE"), index=True
+ )
+
+ currency: Mapped[str] = mapped_column(String(3))
+ unit_price: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))
+ # A rate, nullable: most workspaces never fill it in.
+ tax_rate: Mapped[Optional[Decimal]] = mapped_column(Numeric(precision=7, scale=4), nullable=True)
+ billing: Mapped[str] = mapped_column(String(20), default="one_time", server_default="one_time")
+ interval: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
+ # "Monthly", "Annual, 2 months free": a name for the picker when a
+ # product has more than one price in a currency.
+ nickname: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
+ lookup_key: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
+ active: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
+
+ external_source: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
+ external_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
+
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
+ )
+
+ product: Mapped["Product"] = relationship(back_populates="prices")
diff --git a/backend/app/schemas/invoice.py b/backend/app/schemas/invoice.py
index dc71b961..86a28528 100644
--- a/backend/app/schemas/invoice.py
+++ b/backend/app/schemas/invoice.py
@@ -35,10 +35,20 @@ class InvoiceLineInput(BaseModel):
# A percentage, not an amount — and only meaningful when the
# workspace shows tax fields at all.
tax_rate: Optional[Decimal] = Field(default=None, ge=0, le=100)
+ #: Where the line came from, when it came from the catalog. The
+ #: values above are still the line's own; these only remember.
+ product_id: Optional[uuid.UUID] = None
+ price_id: Optional[uuid.UUID] = None
+ #: Fiscal references for this line (a goods or service code). Filled
+ #: from the product when omitted; a line may bring its own.
+ fiscal_refs: Optional[dict[str, str]] = None
class InvoiceLineRead(BaseModel):
id: uuid.UUID
+ product_id: Optional[uuid.UUID] = None
+ price_id: Optional[uuid.UUID] = None
+ fiscal_refs: Optional[dict[str, str]] = None
description: str
quantity: Decimal
unit: Optional[str] = None
diff --git a/backend/app/schemas/product.py b/backend/app/schemas/product.py
new file mode 100644
index 00000000..53ffb3d1
--- /dev/null
+++ b/backend/app/schemas/product.py
@@ -0,0 +1,102 @@
+import uuid
+from datetime import datetime
+from decimal import Decimal
+from typing import Any, Literal, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+ProductKind = Literal["service", "product"]
+PriceBilling = Literal["one_time", "recurring"]
+PriceInterval = Literal["weekly", "biweekly", "monthly", "quarterly", "semiannual", "yearly"]
+ProductOrigin = Literal["local", "imported"]
+
+
+class PriceInput(BaseModel):
+ currency: str = Field(..., min_length=3, max_length=3)
+ unit_price: Decimal = Field(..., ge=0)
+ tax_rate: Optional[Decimal] = Field(default=None, ge=0, le=100)
+ billing: PriceBilling = "one_time"
+ #: Required when `billing` is recurring, refused otherwise.
+ interval: Optional[PriceInterval] = None
+ nickname: Optional[str] = Field(default=None, max_length=100)
+ #: A name of the workspace's own choosing, unique among its prices.
+ lookup_key: Optional[str] = Field(default=None, max_length=200)
+ external_source: Optional[str] = Field(default=None, max_length=50)
+ external_id: Optional[str] = Field(default=None, max_length=255)
+
+
+class PriceUpdate(BaseModel):
+ currency: Optional[str] = Field(default=None, min_length=3, max_length=3)
+ unit_price: Optional[Decimal] = Field(default=None, ge=0)
+ tax_rate: Optional[Decimal] = Field(default=None, ge=0, le=100)
+ billing: Optional[PriceBilling] = None
+ interval: Optional[PriceInterval] = None
+ nickname: Optional[str] = Field(default=None, max_length=100)
+ lookup_key: Optional[str] = Field(default=None, max_length=200)
+ active: Optional[bool] = None
+
+
+class PriceRead(BaseModel):
+ id: uuid.UUID
+ product_id: uuid.UUID
+ currency: str
+ unit_price: Decimal
+ tax_rate: Optional[Decimal] = None
+ billing: PriceBilling
+ interval: Optional[PriceInterval] = None
+ nickname: Optional[str] = None
+ lookup_key: Optional[str] = None
+ active: bool
+ external_source: Optional[str] = None
+ external_id: Optional[str] = None
+ created_at: datetime
+
+ model_config = ConfigDict(from_attributes=True)
+
+
+class ProductCreate(BaseModel):
+ name: str = Field(..., min_length=1, max_length=200)
+ description: Optional[str] = None
+ kind: ProductKind = "service"
+ unit: Optional[str] = Field(default=None, max_length=20)
+ custom_fields: Optional[dict[str, Any]] = None
+ #: Fiscal references keyed as the jurisdiction pack suggests
+ #: (`ncm`, `service_code`, `hs_code`...), any key accepted.
+ fiscal_refs: Optional[dict[str, str]] = None
+ #: Created with the product, so "a product with a price" is one call.
+ prices: list[PriceInput] = []
+ origin: Optional[ProductOrigin] = None
+ external_source: Optional[str] = Field(default=None, max_length=50)
+ external_id: Optional[str] = Field(default=None, max_length=255)
+
+
+class ProductUpdate(BaseModel):
+ name: Optional[str] = Field(default=None, min_length=1, max_length=200)
+ description: Optional[str] = None
+ kind: Optional[ProductKind] = None
+ unit: Optional[str] = Field(default=None, max_length=20)
+ custom_fields: Optional[dict[str, Any]] = None
+ fiscal_refs: Optional[dict[str, str]] = None
+ #: False archives: gone from the picker, still readable on invoices.
+ active: Optional[bool] = None
+
+
+class ProductRead(BaseModel):
+ id: uuid.UUID
+ name: str
+ description: Optional[str] = None
+ kind: ProductKind
+ unit: Optional[str] = None
+ active: bool
+ origin: str
+ external_source: Optional[str] = None
+ external_id: Optional[str] = None
+ custom_fields: Optional[dict[str, Any]] = None
+ fiscal_refs: Optional[dict[str, str]] = None
+ prices: list[PriceRead] = []
+ created_at: datetime
+ #: Derived: how many invoices name this product. Filled by the
+ #: router from one grouped query, never stored.
+ invoice_count: int = 0
+
+ model_config = ConfigDict(from_attributes=True)
diff --git a/backend/app/services/invoice_schedule_service.py b/backend/app/services/invoice_schedule_service.py
index 1a755a9e..4ffe3bea 100644
--- a/backend/app/services/invoice_schedule_service.py
+++ b/backend/app/services/invoice_schedule_service.py
@@ -201,7 +201,16 @@ def _term_totals(lines: list[dict[str, Any]], discount: Decimal) -> tuple[Decima
def _normalise_lines(lines: Any) -> list[dict[str, Any]]:
- """Lines as they will be stored: plain JSON, decimals as strings."""
+ """Lines as they will be stored: plain JSON, decimals as strings.
+
+ Fiscal references are cleaned here, when a person can fix them, and
+ not only at emission: a bad key stored on a term would fail every
+ period until the job paused the agreement.
+ """
+ # Lazy: the catalog reads this module's neighbours, and a top-level
+ # import each way would be a cycle.
+ from app.services.product_service import clean_fiscal_refs
+
if not lines:
raise InvoiceError("term_lines_required", "A term needs at least one line")
out: list[dict[str, Any]] = []
@@ -218,6 +227,12 @@ def _normalise_lines(lines: Any) -> list[dict[str, Any]]:
"tax_rate": (
str(Decimal(str(line["tax_rate"]))) if line.get("tax_rate") is not None else None
),
+ # Catalog provenance, kept as text. Checked when the
+ # period is emitted, not here: a product archived or
+ # deleted later must not stop the agreement from billing.
+ "product_id": str(line["product_id"]) if line.get("product_id") else None,
+ "price_id": str(line["price_id"]) if line.get("price_id") else None,
+ "fiscal_refs": clean_fiscal_refs(line.get("fiscal_refs")),
}
)
return out
@@ -815,7 +830,7 @@ async def link_invoice(
The retroactive door: someone who billed a retainer by hand from
March to August and only now created the schedule gets their
- history, and a Stripe import lands its invoices the same way. The
+ history, and a gateway import lands its invoices the same way. The
date has to be a real period boundary, the period has to be free,
and the invoice has to be the same money (currency, and client when
both say one).
@@ -880,6 +895,9 @@ def _lines_from_invoice(invoice: Invoice, fallback_description: str) -> list[dic
"unit": line.unit,
"unit_price": line.unit_price,
"tax_rate": line.tax_rate,
+ "product_id": line.product_id,
+ "price_id": line.price_id,
+ "fiscal_refs": line.fiscal_refs,
}
for line in invoice.lines
]
@@ -983,6 +1001,13 @@ async def _emit(
if term is None:
raise InvoiceError("no_term", "No term is in force for this period")
terms_days = await _payment_terms(session, schedule)
+ # The term may name a product that has since been deleted. The line
+ # has its own values, so the id is dropped and the period is billed.
+ from app.services import product_service
+
+ lines = await product_service.resolve_lines(
+ session, schedule.workspace_id, [dict(line) for line in term.lines], strict=False
+ )
if schedule.user_id is None:
# The ledger stamps who created each invoice. An agreement whose
# author left the workspace keeps emitting, and the invoice is
@@ -999,7 +1024,7 @@ async def _emit(
"competence_date": start,
"currency": schedule.currency,
"discount": Decimal(term.discount),
- "lines": [dict(line) for line in term.lines],
+ "lines": lines,
"notes": schedule.notes,
"custom_fields": schedule.custom_fields,
},
diff --git a/backend/app/services/invoice_service.py b/backend/app/services/invoice_service.py
index 37d627a4..ea2b2920 100644
--- a/backend/app/services/invoice_service.py
+++ b/backend/app/services/invoice_service.py
@@ -574,9 +574,27 @@ def _build_line(invoice: Invoice, line: dict[str, Any], position: int) -> Invoic
tax_rate=Decimal(str(line["tax_rate"])) if line.get("tax_rate") is not None else None,
total=_line_total(quantity, unit_price),
position=position,
+ # Provenance, checked by `product_service.resolve_lines` before
+ # this is called. Null on a line typed by hand.
+ product_id=line.get("product_id"),
+ price_id=line.get("price_id"),
+ fiscal_refs=line.get("fiscal_refs") or None,
)
+async def _resolved_lines(
+ session: AsyncSession, workspace_id: uuid.UUID, lines: list[dict[str, Any]]
+) -> list[dict[str, Any]]:
+ """Lines with their catalog ids checked against this workspace.
+
+ Imported lazily: the catalog reads this module's error type, and a
+ top-level import each way would be a cycle.
+ """
+ from app.services import product_service
+
+ return await product_service.resolve_lines(session, workspace_id, lines)
+
+
async def create_invoice(
session: AsyncSession,
workspace_id: uuid.UUID,
@@ -586,7 +604,7 @@ async def create_invoice(
settings = await get_settings(session, workspace_id)
await _assert_payee(session, data.get("payee_id"), workspace_id)
- lines_data = data.pop("lines", None) or []
+ lines_data = await _resolved_lines(session, workspace_id, data.pop("lines", None) or [])
if settings.document_required and not lines_data:
raise InvoiceError(
"lines_required", "This workspace requires invoices to carry line items"
@@ -710,6 +728,7 @@ async def update_invoice(session: AsyncSession, invoice: Invoice, data: dict[str
setattr(invoice, field, data[field])
if lines_data is not None:
+ lines_data = await _resolved_lines(session, invoice.workspace_id, lines_data)
for line in list(invoice.lines):
await session.delete(line)
await session.flush()
diff --git a/backend/app/services/product_service.py b/backend/app/services/product_service.py
new file mode 100644
index 00000000..a2f3ba80
--- /dev/null
+++ b/backend/app/services/product_service.py
@@ -0,0 +1,437 @@
+"""The catalog: products, prices, and what an invoice line takes from them.
+
+Two rules hold this module together.
+
+**A line owns its values.** `resolve_line` is the only bridge between
+the catalog and an invoice: it checks that the ids a line names belong
+to this workspace and to each other, and hands them back. It never
+fills a price in. The client that picked the product already copied
+the values into the line, and a copy the server rewrote on save would
+be a line the person did not write.
+
+**Archive beats delete once anything names the row.** A product an
+invoice line points at can be archived (gone from the picker, still
+readable on the invoice) but not deleted, because the line would then
+say "from the catalog" about nothing. A product nothing names yet can
+simply go.
+"""
+from __future__ import annotations
+
+import re
+import uuid
+from decimal import Decimal
+from typing import Any, Optional
+
+from sqlalchemy import func, or_, select
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.invoice import InvoiceLine
+from app.models.product import (
+ PRICE_BILLINGS,
+ PRICE_INTERVALS,
+ PRODUCT_KINDS,
+ Product,
+ ProductPrice,
+)
+from app.services.invoice_service import InvoiceError
+
+ZERO = Decimal("0.00")
+
+_REF_KEY = re.compile(r"^[a-z][a-z0-9_]{0,39}$")
+
+
+def clean_fiscal_refs(value: Any) -> Optional[dict[str, str]]:
+ """Fiscal references as stored: lowercase keys, trimmed text values,
+ empty values dropped. Any key is accepted (the pack suggests, it
+ never restricts); a key that is not a key is refused."""
+ if value is None:
+ return None
+ if not isinstance(value, dict):
+ raise InvoiceError("invalid_fiscal_refs", "Fiscal references must be a map of text values")
+ out: dict[str, str] = {}
+ for key, raw in value.items():
+ k = str(key).strip().lower()
+ if not _REF_KEY.match(k):
+ raise InvoiceError("invalid_fiscal_refs", f"{key!r} is not a valid reference key")
+ text = "" if raw is None else str(raw).strip()
+ if len(text) > 100:
+ raise InvoiceError("invalid_fiscal_refs", f"The value for {k} is too long")
+ if text:
+ out[k] = text
+ return out or None
+
+
+# ---------------------------------------------------------------------------
+# Reading
+# ---------------------------------------------------------------------------
+async def get_product(
+ session: AsyncSession, product_id: uuid.UUID, workspace_id: uuid.UUID
+) -> Optional[Product]:
+ result = await session.execute(
+ select(Product).where(Product.id == product_id, Product.workspace_id == workspace_id)
+ )
+ return result.unique().scalar_one_or_none()
+
+
+async def find_by_external_id(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ external_source: Optional[str],
+ external_id: Optional[str],
+) -> Optional[Product]:
+ if not external_source or not external_id:
+ return None
+ result = await session.execute(
+ select(Product).where(
+ Product.workspace_id == workspace_id,
+ Product.external_source == external_source,
+ Product.external_id == external_id,
+ )
+ )
+ return result.unique().scalar_one_or_none()
+
+
+async def list_products(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ *,
+ active: Optional[bool] = True,
+ kind: Optional[str] = None,
+ q: Optional[str] = None,
+) -> list[Product]:
+ """The catalog, live rows by default, by name."""
+ query = select(Product).where(Product.workspace_id == workspace_id)
+ if active is not None:
+ query = query.where(Product.active.is_(active))
+ if kind:
+ query = query.where(Product.kind == kind)
+ if q:
+ pattern = f"%{q.lower()}%"
+ query = query.where(
+ or_(func.lower(Product.name).like(pattern), func.lower(Product.description).like(pattern))
+ )
+ query = query.order_by(func.lower(Product.name))
+ result = await session.execute(query)
+ return list(result.unique().scalars().all())
+
+
+async def usage_counts(
+ session: AsyncSession, workspace_id: uuid.UUID, product_ids: list[uuid.UUID]
+) -> dict[uuid.UUID, int]:
+ """How many invoices name each product. Derived, for the list."""
+ if not product_ids:
+ return {}
+ rows = (
+ await session.execute(
+ select(InvoiceLine.product_id, func.count(func.distinct(InvoiceLine.invoice_id)))
+ .where(
+ InvoiceLine.workspace_id == workspace_id,
+ InvoiceLine.product_id.in_(product_ids),
+ )
+ .group_by(InvoiceLine.product_id)
+ )
+ ).all()
+ counts = {pid: 0 for pid in product_ids}
+ for product_id, n in rows:
+ counts[product_id] = n
+ return counts
+
+
+def price_for(product: Product, currency: str) -> Optional[ProductPrice]:
+ """The live price in a currency, one-time first. What the picker
+ fills a line with; None means "fill the name, type the price"."""
+ candidates = [p for p in product.prices if p.active and p.currency == currency.upper()]
+ candidates.sort(key=lambda p: (p.billing != "one_time", p.created_at))
+ return candidates[0] if candidates else None
+
+
+# ---------------------------------------------------------------------------
+# Writing products
+# ---------------------------------------------------------------------------
+def _clean_name(value: Any) -> str:
+ name = (value or "").strip()
+ if not name:
+ raise InvoiceError("name_required", "Give the product a name")
+ return name
+
+
+async def create_product(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: Optional[uuid.UUID],
+ data: dict[str, Any],
+) -> Product:
+ kind = data.get("kind") or "service"
+ if kind not in PRODUCT_KINDS:
+ raise InvoiceError("invalid_kind", "Unknown product kind")
+ origin = data.get("origin") or "local"
+ if origin == "imported" and not data.get("external_source"):
+ raise InvoiceError(
+ "external_source_required", "An imported product must say where it came from"
+ )
+
+ product = Product(
+ workspace_id=workspace_id,
+ user_id=user_id,
+ name=_clean_name(data.get("name")),
+ description=data.get("description"),
+ kind=kind,
+ unit=(data.get("unit") or None),
+ active=data.get("active", True),
+ origin=origin,
+ external_source=data.get("external_source"),
+ external_id=data.get("external_id"),
+ custom_fields=data.get("custom_fields"),
+ fiscal_refs=clean_fiscal_refs(data.get("fiscal_refs")),
+ )
+ product.prices = []
+ session.add(product)
+ try:
+ await session.flush()
+ except IntegrityError:
+ # The unique external pair: a re-sync converges on the row that
+ # already holds this product instead of duplicating it.
+ await session.rollback()
+ raise InvoiceError(
+ "already_imported", "This product is already here", status_code=409
+ ) from None
+
+ for raw in data.get("prices") or []:
+ await add_price(session, product, raw)
+ return product
+
+
+async def update_product(session: AsyncSession, product: Product, data: dict[str, Any]) -> Product:
+ if "name" in data:
+ product.name = _clean_name(data["name"])
+ if "kind" in data and data["kind"] is not None:
+ if data["kind"] not in PRODUCT_KINDS:
+ raise InvoiceError("invalid_kind", "Unknown product kind")
+ product.kind = data["kind"]
+ for field in ("description", "unit", "custom_fields"):
+ if field in data:
+ setattr(product, field, data[field] or None)
+ if "fiscal_refs" in data:
+ product.fiscal_refs = clean_fiscal_refs(data["fiscal_refs"])
+ if "active" in data and data["active"] is not None:
+ product.active = bool(data["active"])
+ await session.flush()
+ return product
+
+
+async def _named_by_lines(session: AsyncSession, product: Product) -> bool:
+ result = await session.execute(
+ select(InvoiceLine.id).where(InvoiceLine.product_id == product.id).limit(1)
+ )
+ return result.scalar_one_or_none() is not None
+
+
+async def delete_product(session: AsyncSession, product: Product) -> None:
+ """Only a product no invoice names. Anything else is archived."""
+ if await _named_by_lines(session, product):
+ raise InvoiceError(
+ "product_in_use", "Invoices name this product; archive it instead of deleting it"
+ )
+ await session.delete(product)
+ await session.flush()
+
+
+# ---------------------------------------------------------------------------
+# Prices
+# ---------------------------------------------------------------------------
+def _fill_price(price: ProductPrice, data: dict[str, Any]) -> None:
+ if "currency" in data and data["currency"]:
+ price.currency = str(data["currency"]).upper()
+ if "unit_price" in data and data["unit_price"] is not None:
+ # Quantised on the way in, so the row reads the same before and
+ # after a round trip through the database.
+ price.unit_price = Decimal(str(data["unit_price"])).quantize(Decimal("0.01"))
+ if price.unit_price < ZERO:
+ raise InvoiceError("negative_price", "A price cannot be negative")
+ if "tax_rate" in data:
+ price.tax_rate = (
+ Decimal(str(data["tax_rate"])).quantize(Decimal("0.0001"))
+ if data["tax_rate"] is not None
+ else None
+ )
+ if "billing" in data and data["billing"] is not None:
+ if data["billing"] not in PRICE_BILLINGS:
+ raise InvoiceError("invalid_billing", "Unknown billing kind")
+ price.billing = data["billing"]
+ if "interval" in data:
+ price.interval = data["interval"] or None
+ if "nickname" in data:
+ price.nickname = (data["nickname"] or "").strip() or None
+ if "lookup_key" in data:
+ price.lookup_key = (data["lookup_key"] or "").strip() or None
+ if "active" in data and data["active"] is not None:
+ price.active = bool(data["active"])
+
+ # Refused here, where the client can branch on a code, rather than by
+ # the CHECK that would answer with a 500.
+ if price.billing == "recurring":
+ if price.interval not in PRICE_INTERVALS:
+ raise InvoiceError("interval_required", "A recurring price needs a cadence")
+ else:
+ price.interval = None
+
+
+async def add_price(session: AsyncSession, product: Product, data: dict[str, Any]) -> ProductPrice:
+ if not data.get("currency"):
+ raise InvoiceError("currency_required", "A price needs a currency")
+ if data.get("unit_price") is None:
+ raise InvoiceError("unit_price_required", "A price needs an amount")
+ price = ProductPrice(
+ product_id=product.id,
+ workspace_id=product.workspace_id,
+ currency=str(data["currency"]).upper(),
+ unit_price=ZERO,
+ billing=data.get("billing") or "one_time",
+ external_source=data.get("external_source"),
+ external_id=data.get("external_id"),
+ )
+ _fill_price(price, data)
+ session.add(price)
+ product.prices.append(price)
+ try:
+ await session.flush()
+ except IntegrityError:
+ await session.rollback()
+ raise InvoiceError(
+ "price_key_taken",
+ "A price with this external id or lookup key is already here",
+ status_code=409,
+ ) from None
+ return price
+
+
+async def update_price(
+ session: AsyncSession, product: Product, price: ProductPrice, data: dict[str, Any]
+) -> ProductPrice:
+ if price.product_id != product.id:
+ raise InvoiceError("price_not_found", "Price not found on this product", 404)
+ _fill_price(price, data)
+ try:
+ await session.flush()
+ except IntegrityError:
+ await session.rollback()
+ raise InvoiceError(
+ "price_key_taken", "Another price already uses this lookup key", status_code=409
+ ) from None
+ return price
+
+
+async def find_price_by_lookup_key(
+ session: AsyncSession, workspace_id: uuid.UUID, lookup_key: str
+) -> Optional[ProductPrice]:
+ result = await session.execute(
+ select(ProductPrice).where(
+ ProductPrice.workspace_id == workspace_id, ProductPrice.lookup_key == lookup_key
+ )
+ )
+ return result.scalar_one_or_none()
+
+
+async def delete_price(session: AsyncSession, product: Product, price: ProductPrice) -> None:
+ """Only a price no line names. A price an invoice was billed at is
+ archived, so the invoice can still say which one."""
+ if price.product_id != product.id:
+ raise InvoiceError("price_not_found", "Price not found on this product", 404)
+ named = await session.execute(
+ select(InvoiceLine.id).where(InvoiceLine.price_id == price.id).limit(1)
+ )
+ if named.scalar_one_or_none() is not None:
+ raise InvoiceError(
+ "price_in_use", "Invoices were billed at this price; archive it instead of deleting it"
+ )
+ product.prices.remove(price)
+ await session.delete(price)
+ await session.flush()
+
+
+# ---------------------------------------------------------------------------
+# The bridge to invoice lines
+# ---------------------------------------------------------------------------
+def _as_uuid(value: Any) -> Optional[uuid.UUID]:
+ if value is None or value == "":
+ return None
+ if isinstance(value, uuid.UUID):
+ return value
+ try:
+ return uuid.UUID(str(value))
+ except (ValueError, TypeError):
+ return None
+
+
+async def resolve_lines(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ lines: list[dict[str, Any]],
+ *,
+ strict: bool = True,
+) -> list[dict[str, Any]]:
+ """Check the catalog ids a set of lines names, in one query.
+
+ Returns the lines with `product_id` / `price_id` as UUIDs or None.
+ A product must be this workspace's; a price must be that product's.
+ `strict` (a person writing an invoice) answers a bad id with an
+ error. Not strict (the job emitting from a recurring agreement whose
+ term was written before a product was deleted) drops the id and
+ keeps the line: the line has its own values and the invoice is owed
+ either way.
+ """
+ wanted_products = {p for p in (_as_uuid(line.get("product_id")) for line in lines) if p}
+ wanted_prices = {p for p in (_as_uuid(line.get("price_id")) for line in lines) if p}
+
+ prices: dict[uuid.UUID, ProductPrice] = {}
+ if wanted_prices:
+ rows = await session.execute(
+ select(ProductPrice).where(
+ ProductPrice.workspace_id == workspace_id, ProductPrice.id.in_(wanted_prices)
+ )
+ )
+ prices = {p.id: p for p in rows.scalars().all()}
+ # A line that only named a price still came from that product.
+ wanted_products |= {p.product_id for p in prices.values()}
+ products: dict[uuid.UUID, Product] = {}
+ if wanted_products:
+ rows = await session.execute(
+ select(Product).where(
+ Product.workspace_id == workspace_id, Product.id.in_(wanted_products)
+ )
+ )
+ products = {p.id: p for p in rows.unique().scalars().all()}
+
+ out: list[dict[str, Any]] = []
+ for raw in lines:
+ line = dict(raw)
+ product_id = _as_uuid(line.get("product_id"))
+ price_id = _as_uuid(line.get("price_id"))
+ if product_id and product_id not in products:
+ if strict:
+ raise InvoiceError("product_not_found", "Product not found in this workspace", 404)
+ product_id = None
+ if price_id:
+ price = prices.get(price_id)
+ if price is None or (product_id and price.product_id != product_id):
+ if strict:
+ raise InvoiceError("price_not_found", "Price not found on this product", 404)
+ price_id = None
+ elif product_id is None:
+ # A price names its product; a line that only knew the
+ # price still came from that product.
+ product_id = price.product_id
+ line["product_id"] = product_id
+ line["price_id"] = price_id
+ # The product's fiscal references travel with the line, copied
+ # now so the document later reads what the line says. A line
+ # that brought its own keeps them.
+ if line.get("fiscal_refs"):
+ line["fiscal_refs"] = clean_fiscal_refs(line["fiscal_refs"])
+ elif product_id and product_id in products:
+ line["fiscal_refs"] = dict(products[product_id].fiscal_refs or {}) or None
+ else:
+ line["fiscal_refs"] = None
+ out.append(line)
+ return out
diff --git a/backend/tests/test_invoice_schedule_service.py b/backend/tests/test_invoice_schedule_service.py
index 76042b05..6ec8a3d6 100644
--- a/backend/tests/test_invoice_schedule_service.py
+++ b/backend/tests/test_invoice_schedule_service.py
@@ -282,9 +282,9 @@ class TestCreate:
await make_schedule(session, ws_id, test_user.id, origin="imported")
assert exc.value.code == "external_source_required"
s = await make_schedule(
- session, ws_id, test_user.id, origin="imported", external_source="stripe", external_id="sub_1"
+ session, ws_id, test_user.id, origin="imported", external_source="gateway", external_id="sub_1"
)
- found = await svc.find_by_external_id(session, ws_id, "stripe", "sub_1")
+ found = await svc.find_by_external_id(session, ws_id, "gateway", "sub_1")
assert found is not None and found.id == s.id
@pytest.mark.asyncio
@@ -439,7 +439,7 @@ class TestGeneration:
await svc.end_schedule(session, ended, reason="canceled_by_client", today=TODAY)
imported = await make_schedule(
session, ws_id, test_user.id, start_date=date(2026, 10, 5),
- origin="imported", external_source="stripe", external_id="sub_x",
+ origin="imported", external_source="gateway", external_id="sub_x",
)
for s in (paused, ended, imported):
assert await svc.generate_due(session, s, today=date(2027, 1, 1)) == []
@@ -689,7 +689,10 @@ class TestLinking:
session, inv, test_user.id, {"frequency": "quarterly", "name": "Hosting"}, today=TODAY
)
assert s.terms[0].lines == [
- {"description": "Hosting", "quantity": "1", "unit": None, "unit_price": "1500.00", "tax_rate": None}
+ {
+ "description": "Hosting", "quantity": "1", "unit": None, "unit_price": "1500.00",
+ "tax_rate": None, "product_id": None, "price_id": None, "fiscal_refs": None,
+ }
]
assert s.terms[0].total == Decimal("1500.00")
diff --git a/backend/tests/test_products.py b/backend/tests/test_products.py
new file mode 100644
index 00000000..5d70a54c
--- /dev/null
+++ b/backend/tests/test_products.py
@@ -0,0 +1,632 @@
+"""The catalog and the one rule it lives by: a line owns its values.
+
+Products fill lines; they never own them. So the tests below care most
+about what happens at the edges: a product renamed, archived or deleted
+after an invoice named it, a term written before a product went away,
+and an id that belongs to somebody else's workspace.
+"""
+import uuid
+from datetime import date
+from decimal import Decimal
+
+import pytest
+import pytest_asyncio
+from httpx import AsyncClient
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.invoice import Invoice
+from app.models.product import Product
+from app.models.workspace import WorkspaceMember
+from app.services import invoice_schedule_service as schedules
+from app.services import invoice_service
+from app.services import product_service as svc
+from app.services.invoice_service import InvoiceError
+
+TODAY = date(2026, 9, 23)
+
+
+@pytest_asyncio.fixture
+async def business_ws(client: AsyncClient, auth_headers) -> dict:
+ resp = await client.post(
+ "/api/workspaces",
+ headers=auth_headers,
+ json={"name": "Estudio", "kind": "business", "self_membership": True},
+ )
+ assert resp.status_code == 201, resp.text
+ return resp.json()
+
+
+@pytest_asyncio.fixture
+async def ws_id(business_ws) -> uuid.UUID:
+ return uuid.UUID(business_ws["id"])
+
+
+@pytest_asyncio.fixture
+async def biz_headers(auth_headers, business_ws) -> dict:
+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}
+
+
+async def make_product(session, ws_id, user_id, **overrides) -> Product:
+ data = {
+ "name": "Consulting hour",
+ "unit": "h",
+ "prices": [{"currency": "USD", "unit_price": "200.00"}],
+ }
+ data.update(overrides)
+ product = await svc.create_product(session, ws_id, user_id, data)
+ await session.commit()
+ return product
+
+
+# ---------------------------------------------------------------------------
+# The catalog itself
+# ---------------------------------------------------------------------------
+class TestCatalog:
+ @pytest.mark.asyncio
+ async def test_a_product_is_created_with_its_prices(self, session, ws_id, test_user):
+ p = await make_product(
+ session, ws_id, test_user.id,
+ prices=[
+ {"currency": "USD", "unit_price": "200.00", "tax_rate": "10"},
+ {"currency": "eur", "unit_price": "180.00", "billing": "recurring", "interval": "monthly", "nickname": "Monthly"},
+ ],
+ )
+ assert p.kind == "service" and p.active
+ assert [(x.currency, x.unit_price, x.billing, x.interval) for x in p.prices] == [
+ ("USD", Decimal("200.00"), "one_time", None),
+ ("EUR", Decimal("180.00"), "recurring", "monthly"),
+ ]
+
+ @pytest.mark.asyncio
+ async def test_a_recurring_price_needs_a_cadence_and_a_one_time_price_drops_it(self, session, ws_id, test_user):
+ with pytest.raises(InvoiceError) as exc:
+ await make_product(session, ws_id, test_user.id, prices=[{"currency": "USD", "unit_price": "1", "billing": "recurring"}])
+ assert exc.value.code == "interval_required"
+ p = await make_product(session, ws_id, test_user.id, prices=[{"currency": "USD", "unit_price": "1", "billing": "one_time", "interval": "monthly"}])
+ assert p.prices[0].interval is None
+
+ @pytest.mark.asyncio
+ async def test_prices_are_validated(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ for bad, code in (
+ ({"unit_price": "1"}, "currency_required"),
+ ({"currency": "USD"}, "unit_price_required"),
+ ({"currency": "USD", "unit_price": "-1"}, "negative_price"),
+ ({"currency": "USD", "unit_price": "1", "billing": "weird"}, "invalid_billing"),
+ ):
+ with pytest.raises(InvoiceError) as exc:
+ await svc.add_price(session, p, bad)
+ assert exc.value.code == code
+
+ @pytest.mark.asyncio
+ async def test_imported_rows_converge_on_their_external_id(self, session, ws_id, test_user):
+ with pytest.raises(InvoiceError) as exc:
+ await make_product(session, ws_id, test_user.id, origin="imported")
+ assert exc.value.code == "external_source_required"
+ p = await make_product(
+ session, ws_id, test_user.id, origin="imported", external_source="gateway", external_id="prod_1",
+ prices=[{"currency": "USD", "unit_price": "10", "external_source": "gateway", "external_id": "price_1"}],
+ )
+ found = await svc.find_by_external_id(session, ws_id, "gateway", "prod_1")
+ assert found is not None and found.id == p.id
+ with pytest.raises(InvoiceError) as exc:
+ await make_product(session, ws_id, test_user.id, origin="imported", external_source="gateway", external_id="prod_1", prices=[])
+ assert exc.value.code == "already_imported" and exc.value.status_code == 409
+
+ @pytest.mark.asyncio
+ async def test_list_defaults_to_live_products_and_searches_by_name(self, session, ws_id, test_user):
+ a = await make_product(session, ws_id, test_user.id, name="Zeta hosting", description="servers")
+ b = await make_product(session, ws_id, test_user.id, name="Alpha design")
+ await svc.update_product(session, b, {"active": False})
+ await session.commit()
+ assert [p.id for p in await svc.list_products(session, ws_id)] == [a.id]
+ assert {p.id for p in await svc.list_products(session, ws_id, active=None)} == {a.id, b.id}
+ assert [p.id for p in await svc.list_products(session, ws_id, active=None, q="alpha")] == [b.id]
+ assert [p.id for p in await svc.list_products(session, ws_id, q="SERVERS")] == [a.id]
+
+ @pytest.mark.asyncio
+ async def test_price_for_prefers_a_live_one_time_price_in_the_currency(self, session, ws_id, test_user):
+ p = await make_product(
+ session, ws_id, test_user.id,
+ prices=[
+ {"currency": "USD", "unit_price": "1", "billing": "recurring", "interval": "monthly"},
+ {"currency": "USD", "unit_price": "2"},
+ {"currency": "EUR", "unit_price": "3"},
+ ],
+ )
+ def amount(currency: str) -> Decimal | None:
+ price = svc.price_for(p, currency)
+ return price.unit_price if price else None
+
+ assert amount("usd") == Decimal("2.00")
+ assert amount("EUR") == Decimal("3.00")
+ assert amount("BRL") is None
+ await svc.update_price(session, p, p.prices[1], {"active": False})
+ assert amount("USD") == Decimal("1.00")
+
+
+# ---------------------------------------------------------------------------
+# The bridge to invoice lines
+# ---------------------------------------------------------------------------
+async def an_invoice(session, ws_id, user_id, lines) -> Invoice:
+ invoice = await invoice_service.create_invoice(
+ session, ws_id, user_id,
+ {"issue_date": TODAY, "due_date": date(2026, 10, 8), "currency": "USD", "lines": lines},
+ )
+ await session.commit()
+ return invoice
+
+
+class TestLines:
+ @pytest.mark.asyncio
+ async def test_a_line_remembers_its_product_and_keeps_its_own_values(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ price = p.prices[0]
+ inv = await an_invoice(session, ws_id, test_user.id, [
+ {"description": "Consulting hour", "quantity": 3, "unit": "h", "unit_price": "180.00",
+ "product_id": p.id, "price_id": price.id},
+ {"description": "Travel", "unit_price": "50.00"},
+ ])
+ catalog, free = inv.lines
+ assert catalog.product_id == p.id and catalog.price_id == price.id
+ assert catalog.unit_price == Decimal("180.00") # the typed value, not the catalog's 200
+ assert free.product_id is None and free.price_id is None
+ assert inv.total == Decimal("590.00")
+
+ # Renaming and archiving the product changes nothing on the line.
+ await svc.update_product(session, p, {"name": "Senior hour", "active": False})
+ await session.commit()
+ await session.refresh(catalog)
+ assert catalog.description == "Consulting hour" and catalog.product_id == p.id
+
+ @pytest.mark.asyncio
+ async def test_a_price_alone_names_its_product(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ inv = await an_invoice(session, ws_id, test_user.id, [
+ {"description": "x", "unit_price": "1", "price_id": p.prices[0].id},
+ ])
+ assert inv.lines[0].product_id == p.id
+
+ @pytest.mark.asyncio
+ async def test_ids_from_another_workspace_or_another_product_are_refused(self, session, ws_id, test_user, client, auth_headers):
+ resp = await client.post(
+ "/api/workspaces", headers=auth_headers,
+ json={"name": "Outra", "kind": "business", "self_membership": True},
+ )
+ other_ws = uuid.UUID(resp.json()["id"])
+ foreign = await make_product(session, other_ws, test_user.id)
+ mine = await make_product(session, ws_id, test_user.id)
+
+ with pytest.raises(InvoiceError) as exc:
+ await an_invoice(session, ws_id, test_user.id, [{"description": "x", "unit_price": "1", "product_id": foreign.id}])
+ assert exc.value.code == "product_not_found"
+ with pytest.raises(InvoiceError) as exc:
+ await an_invoice(session, ws_id, test_user.id, [{"description": "x", "unit_price": "1", "product_id": mine.id, "price_id": foreign.prices[0].id}])
+ assert exc.value.code == "price_not_found"
+ with pytest.raises(InvoiceError) as exc:
+ await an_invoice(session, ws_id, test_user.id, [{"description": "x", "unit_price": "1", "product_id": uuid.uuid4()}])
+ assert exc.value.code == "product_not_found"
+
+ @pytest.mark.asyncio
+ async def test_a_named_product_is_archived_not_deleted(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ price = p.prices[0]
+ await an_invoice(session, ws_id, test_user.id, [{"description": "x", "unit_price": "1", "product_id": p.id, "price_id": price.id}])
+ with pytest.raises(InvoiceError) as exc:
+ await svc.delete_product(session, p)
+ assert exc.value.code == "product_in_use"
+ with pytest.raises(InvoiceError) as exc:
+ await svc.delete_price(session, p, price)
+ assert exc.value.code == "price_in_use"
+ assert (await svc.usage_counts(session, ws_id, [p.id]))[p.id] == 1
+
+ unused = await make_product(session, ws_id, test_user.id, name="Unused")
+ await svc.delete_price(session, unused, unused.prices[0])
+ await svc.delete_product(session, unused)
+ assert await svc.get_product(session, unused.id, ws_id) is None
+
+
+class TestFiscalRefs:
+ @pytest.mark.asyncio
+ async def test_refs_are_cleaned_and_any_key_is_accepted(self, session, ws_id, test_user):
+ p = await make_product(
+ session, ws_id, test_user.id,
+ fiscal_refs={"NCM": " 8471.30.12 ", "service_code": "", "my_own_key": "x", "gtin": None},
+ )
+ assert p.fiscal_refs == {"ncm": "8471.30.12", "my_own_key": "x"}
+ await svc.update_product(session, p, {"fiscal_refs": {}})
+ assert p.fiscal_refs is None
+
+ @pytest.mark.asyncio
+ async def test_a_key_that_is_not_a_key_is_refused(self, session, ws_id, test_user):
+ for bad in ({"has space": "1"}, {"": "1"}, {"a" * 41: "1"}, ["ncm"], {"ncm": "x" * 101}):
+ with pytest.raises(InvoiceError) as exc:
+ await make_product(session, ws_id, test_user.id, fiscal_refs=bad)
+ assert exc.value.code == "invalid_fiscal_refs"
+
+ @pytest.mark.asyncio
+ async def test_the_line_takes_a_copy_and_keeps_its_own(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id, fiscal_refs={"service_code": "1.05", "nbs": "1.1401"})
+ inv = await an_invoice(session, ws_id, test_user.id, [
+ {"description": "Hour", "unit_price": "200", "product_id": p.id},
+ {"description": "Hour, own refs", "unit_price": "200", "price_id": p.prices[0].id, "fiscal_refs": {"service_code": "1.07"}},
+ {"description": "Typed", "unit_price": "1"},
+ ])
+ copied, own, typed = inv.lines
+ assert copied.fiscal_refs == {"service_code": "1.05", "nbs": "1.1401"}
+ assert own.fiscal_refs == {"service_code": "1.07"} and own.product_id == p.id
+ assert typed.fiscal_refs is None
+ # Changing the product later changes nothing on the line.
+ await svc.update_product(session, p, {"fiscal_refs": {"service_code": "9.99"}})
+ await session.commit()
+ await session.refresh(copied)
+ assert copied.fiscal_refs == {"service_code": "1.05", "nbs": "1.1401"}
+
+ @pytest.mark.asyncio
+ async def test_the_pack_suggests_by_kind_and_never_restricts(self, client, biz_headers, auth_headers, business_ws):
+ resp = await client.patch(f"/api/workspaces/{business_ws['id']}", headers=biz_headers, json={"tax_jurisdiction": "BR"})
+ assert resp.status_code == 200, resp.text
+ fields = (await client.get("/api/fiscal/product-fields", headers=biz_headers)).json()
+ assert fields["jurisdiction"] == "BR"
+ by_key = {f["key"]: f for f in fields["fields"]}
+ assert by_key["ncm"]["kinds"] == ["product"] and by_key["service_code"]["kinds"] == ["service"]
+ assert by_key["ncm"]["label_key"] == "fiscal.productField.ncm"
+ # A key the pack never mentions is stored all the same.
+ resp = await client.post("/api/products", headers=biz_headers, json={"name": "x", "fiscal_refs": {"hs_code": "8471"}})
+ assert resp.status_code == 201 and resp.json()["fiscal_refs"] == {"hs_code": "8471"}
+ # No jurisdiction: no opinion, not an error.
+ await client.patch(f"/api/workspaces/{business_ws['id']}", headers=biz_headers, json={"tax_jurisdiction": None})
+ fields = (await client.get("/api/fiscal/product-fields", headers=biz_headers)).json()
+ assert fields == {"jurisdiction": None, "fields": []}
+
+
+class TestLookupKeys:
+ @pytest.mark.asyncio
+ async def test_a_lookup_key_finds_a_price_and_is_unique_per_workspace(self, session, ws_id, test_user, client, auth_headers):
+ # Read before the refused add below rolls the session back and
+ # expires every loaded row.
+ uid = test_user.id
+ p = await make_product(session, ws_id, uid, prices=[{"currency": "USD", "unit_price": "10", "lookup_key": "pro_monthly"}])
+ found = await svc.find_price_by_lookup_key(session, ws_id, "pro_monthly")
+ assert found is not None and found.id == p.prices[0].id
+ with pytest.raises(InvoiceError) as exc:
+ await svc.add_price(session, p, {"currency": "EUR", "unit_price": "9", "lookup_key": "pro_monthly"})
+ assert exc.value.code == "price_key_taken" and exc.value.status_code == 409
+ # Another workspace may use the same key.
+ resp = await client.post("/api/workspaces", headers=auth_headers, json={"name": "Outra", "kind": "business", "self_membership": True})
+ other = await make_product(session, uuid.UUID(resp.json()["id"]), uid, prices=[{"currency": "USD", "unit_price": "1", "lookup_key": "pro_monthly"}])
+ assert other.prices[0].lookup_key == "pro_monthly"
+
+ @pytest.mark.asyncio
+ async def test_a_cleared_lookup_key_is_null_not_empty(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id, prices=[{"currency": "USD", "unit_price": "10", "lookup_key": "k"}])
+ await svc.update_price(session, p, p.prices[0], {"lookup_key": " "})
+ assert p.prices[0].lookup_key is None
+ q = await make_product(session, ws_id, test_user.id, prices=[{"currency": "USD", "unit_price": "10", "lookup_key": ""}])
+ assert q.prices[0].lookup_key is None
+
+
+# ---------------------------------------------------------------------------
+# Recurring agreements
+# ---------------------------------------------------------------------------
+class TestSchedules:
+ @pytest.mark.asyncio
+ async def test_a_term_carries_the_product_into_every_period(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ s = await schedules.create_schedule(
+ session, ws_id, test_user.id,
+ {"name": "Retainer", "frequency": "monthly", "start_date": date(2026, 10, 5), "currency": "USD",
+ "lines": [{"description": "Consulting hour", "quantity": 10, "unit_price": "200", "product_id": p.id, "price_id": p.prices[0].id}]},
+ today=TODAY,
+ )
+ await session.commit()
+ assert s.terms[0].lines[0]["product_id"] == str(p.id)
+ [inv] = await schedules.generate_due(session, s, today=date(2026, 10, 5))
+ assert inv.lines[0].product_id == p.id and inv.lines[0].price_id == p.prices[0].id
+
+ @pytest.mark.asyncio
+ async def test_a_product_deleted_after_the_term_does_not_stop_the_agreement(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ s = await schedules.create_schedule(
+ session, ws_id, test_user.id,
+ {"name": "Retainer", "frequency": "monthly", "start_date": date(2026, 10, 5), "currency": "USD",
+ "lines": [{"description": "Hour", "unit_price": "200", "product_id": p.id}]},
+ today=TODAY,
+ )
+ await session.commit()
+ await session.delete(p)
+ await session.commit()
+ [inv] = await schedules.generate_due(session, s, today=date(2026, 10, 5))
+ assert inv.lines[0].product_id is None and inv.total == Decimal("200.00")
+
+ @pytest.mark.asyncio
+ async def test_a_term_refuses_bad_fiscal_refs_when_written_not_when_emitted(self, session, ws_id, test_user):
+ """A bad key on a term would fail every period until the job paused
+ the agreement. It is refused at the door, and a good one is stored
+ clean."""
+ with pytest.raises(InvoiceError) as exc:
+ await schedules.create_schedule(
+ session, ws_id, test_user.id,
+ {"name": "R", "frequency": "monthly", "start_date": date(2026, 10, 5), "currency": "USD",
+ "lines": [{"description": "Hour", "unit_price": "200", "fiscal_refs": {"bad key": "1"}}]},
+ today=TODAY,
+ )
+ assert exc.value.code == "invalid_fiscal_refs"
+ s = await schedules.create_schedule(
+ session, ws_id, test_user.id,
+ {"name": "R", "frequency": "monthly", "start_date": date(2026, 10, 5), "currency": "USD",
+ "lines": [{"description": "Hour", "unit_price": "200", "fiscal_refs": {"Service_Code": " 1.05 ", "empty": ""}}]},
+ today=TODAY,
+ )
+ await session.commit()
+ assert s.terms[0].lines[0]["fiscal_refs"] == {"service_code": "1.05"}
+ [inv] = await schedules.generate_due(session, s, today=date(2026, 10, 5))
+ assert inv.lines[0].fiscal_refs == {"service_code": "1.05"}
+
+ @pytest.mark.asyncio
+ async def test_make_recurring_keeps_the_provenance(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ inv = await an_invoice(session, ws_id, test_user.id, [{"description": "Hour", "unit_price": "200", "product_id": p.id}])
+ s = await schedules.make_recurring(session, inv, test_user.id, {"frequency": "monthly", "name": "R"}, today=TODAY)
+ assert s.terms[0].lines[0]["product_id"] == str(p.id)
+
+
+# ---------------------------------------------------------------------------
+# Over HTTP
+# ---------------------------------------------------------------------------
+@pytest_asyncio.fixture
+async def personal_headers(session: AsyncSession, auth_headers, test_user) -> dict:
+ from app.models.workspace import Workspace
+
+ result = await session.execute(
+ select(Workspace)
+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)
+ .where(WorkspaceMember.user_id == test_user.id, Workspace.kind == "personal")
+ .limit(1)
+ )
+ return {**auth_headers, "X-Workspace-Id": str(result.scalar_one().id)}
+
+
+@pytest_asyncio.fixture
+async def viewer_headers(session: AsyncSession, client: AsyncClient, business_ws) -> dict:
+ import bcrypt
+
+ from app.models.user import User
+
+ user = User(
+ id=uuid.uuid4(),
+ hashed_password=bcrypt.hashpw(b"viewerpass123", bcrypt.gensalt()).decode(),
+ is_active=True,
+ is_superuser=False,
+ is_verified=True,
+ )
+ session.add(user)
+ await session.flush()
+ session.add(WorkspaceMember(id=uuid.uuid4(), workspace_id=uuid.UUID(business_ws["id"]), user_id=user.id, role="viewer"))
+ await session.commit()
+ resp = await client.post(
+ "/api/auth/login",
+ data={"username": "[email protected]", "password": "viewerpass123"},
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ assert resp.status_code == 200, resp.text
+ return {"Authorization": f"Bearer {resp.json()['access_token']}", "X-Workspace-Id": business_ws["id"]}
+
+
+PAYLOAD = {"name": "Consulting hour", "unit": "h", "prices": [{"currency": "USD", "unit_price": "200.00"}]}
+
+
+async def test_personal_workspace_cannot_reach_the_catalog(client: AsyncClient, personal_headers):
+ fake = str(uuid.uuid4())
+ routes = [
+ ("get", "/api/products", None),
+ ("post", "/api/products", PAYLOAD),
+ ("get", f"/api/products/{fake}", None),
+ ("patch", f"/api/products/{fake}", {"name": "x"}),
+ ("delete", f"/api/products/{fake}", None),
+ ("post", f"/api/products/{fake}/prices", {"currency": "USD", "unit_price": "1"}),
+ ("patch", f"/api/products/{fake}/prices/{fake}", {"active": False}),
+ ("delete", f"/api/products/{fake}/prices/{fake}", None),
+ ]
+ for method, url, body in routes:
+ resp = await getattr(client, method)(url, headers=personal_headers, **({"json": body} if body else {}))
+ assert resp.status_code == 404, f"{method.upper()} {url} -> {resp.status_code}"
+
+
+async def test_viewer_reads_and_never_writes(client: AsyncClient, biz_headers, viewer_headers):
+ created = (await client.post("/api/products", headers=biz_headers, json=PAYLOAD)).json()
+ pid, price_id = created["id"], created["prices"][0]["id"]
+ assert (await client.get("/api/products", headers=viewer_headers)).status_code == 200
+ assert (await client.get(f"/api/products/{pid}", headers=viewer_headers)).status_code == 200
+ writes = [
+ ("post", "/api/products", PAYLOAD),
+ ("patch", f"/api/products/{pid}", {"name": "x"}),
+ ("delete", f"/api/products/{pid}", None),
+ ("post", f"/api/products/{pid}/prices", {"currency": "EUR", "unit_price": "1"}),
+ ("patch", f"/api/products/{pid}/prices/{price_id}", {"active": False}),
+ ("delete", f"/api/products/{pid}/prices/{price_id}", None),
+ ]
+ for method, url, body in writes:
+ resp = await getattr(client, method)(url, headers=viewer_headers, **({"json": body} if body else {}))
+ assert resp.status_code == 403, f"{method.upper()} {url} -> {resp.status_code}"
+
+
+async def test_catalog_journey_over_http(client: AsyncClient, biz_headers, auth_headers):
+ resp = await client.post("/api/products", headers=biz_headers, json=PAYLOAD)
+ assert resp.status_code == 201, resp.text
+ product = resp.json()
+ assert product["kind"] == "service" and product["active"] and product["invoice_count"] == 0
+ assert product["prices"][0]["unit_price"] == "200.00"
+ pid = product["id"]
+
+ # A second price, then a bad one.
+ resp = await client.post(f"/api/products/{pid}/prices", headers=biz_headers, json={"currency": "EUR", "unit_price": "180", "billing": "recurring", "interval": "monthly"})
+ assert resp.status_code == 201 and len(resp.json()["prices"]) == 2
+ resp = await client.post(f"/api/products/{pid}/prices", headers=biz_headers, json={"currency": "EUR", "unit_price": "1", "billing": "recurring"})
+ assert resp.status_code == 400 and resp.json()["detail"]["code"] == "interval_required"
+
+ # An invoice from the catalog counts on the product and refuses deletion.
+ resp = await client.post(
+ "/api/invoices", headers=biz_headers,
+ json={"currency": "USD", "lines": [{"description": "Consulting hour", "quantity": 2, "unit_price": "200.00", "product_id": pid, "price_id": product["prices"][0]["id"]}]},
+ )
+ assert resp.status_code == 201, resp.text
+ assert resp.json()["lines"][0]["product_id"] == pid
+ assert (await client.get(f"/api/products/{pid}", headers=biz_headers)).json()["invoice_count"] == 1
+ resp = await client.delete(f"/api/products/{pid}", headers=biz_headers)
+ assert resp.status_code == 400 and resp.json()["detail"]["code"] == "product_in_use"
+
+ # Archived: gone from the default list, back with active=false.
+ resp = await client.patch(f"/api/products/{pid}", headers=biz_headers, json={"active": False})
+ assert resp.status_code == 200 and resp.json()["active"] is False
+ assert (await client.get("/api/products", headers=biz_headers)).json() == []
+ assert [p["id"] for p in (await client.get("/api/products", headers=biz_headers, params={"active": "false"})).json()] == [pid]
+
+ # Another workspace never sees it.
+ other = await client.post("/api/workspaces", headers=auth_headers, json={"name": "Outra", "kind": "business", "self_membership": True})
+ other_headers = {**auth_headers, "X-Workspace-Id": other.json()["id"]}
+ assert (await client.get(f"/api/products/{pid}", headers=other_headers)).status_code == 404
+ resp = await client.post("/api/invoices", headers=other_headers, json={"currency": "USD", "lines": [{"description": "x", "unit_price": "1", "product_id": pid}]})
+ assert resp.status_code == 404 and resp.json()["detail"]["code"] == "product_not_found"
+
+ # Unused products simply go.
+ resp = await client.post("/api/products", headers=biz_headers, json={"name": "Nothing yet"})
+ assert (await client.delete(f"/api/products/{resp.json()['id']}", headers=biz_headers)).status_code == 204
+
+
+# ---------------------------------------------------------------------------
+# More edges: the paths a real catalog walks every week
+# ---------------------------------------------------------------------------
+class TestMoreEdges:
+ @pytest.mark.asyncio
+ async def test_editing_a_draft_re_resolves_its_lines(self, session, ws_id, test_user):
+ """A draft's lines are replaced on edit, so the catalog check and
+ the fiscal copy run again, against the workspace, every time."""
+ p = await make_product(session, ws_id, test_user.id, fiscal_refs={"ncm": "1"})
+ inv = await invoice_service.create_invoice(
+ session, ws_id, test_user.id,
+ {"issue_date": TODAY, "due_date": date(2026, 10, 8), "currency": "USD", "as_draft": True,
+ "lines": [{"description": "Typed", "unit_price": "1"}]},
+ )
+ await session.commit()
+ assert inv.status == "draft" and inv.lines[0].product_id is None
+ await invoice_service.update_invoice(session, inv, {"lines": [{"description": "Hour", "unit_price": "200", "product_id": p.id}]})
+ await session.commit()
+ assert inv.lines[0].product_id == p.id and inv.lines[0].fiscal_refs == {"ncm": "1"}
+ with pytest.raises(InvoiceError) as exc:
+ await invoice_service.update_invoice(session, inv, {"lines": [{"description": "x", "unit_price": "1", "product_id": uuid.uuid4()}]})
+ assert exc.value.code == "product_not_found"
+
+ @pytest.mark.asyncio
+ async def test_a_price_from_another_workspace_is_dropped_when_not_strict(self, session, ws_id, test_user, client, auth_headers):
+ uid = test_user.id
+ resp = await client.post("/api/workspaces", headers=auth_headers, json={"name": "Outra", "kind": "business", "self_membership": True})
+ foreign = await make_product(session, uuid.UUID(resp.json()["id"]), uid)
+ mine = await make_product(session, ws_id, uid)
+ lines = await svc.resolve_lines(
+ session, ws_id,
+ [{"description": "a", "product_id": foreign.id, "price_id": foreign.prices[0].id},
+ {"description": "b", "product_id": mine.id, "price_id": foreign.prices[0].id},
+ {"description": "c", "price_id": mine.prices[0].id}],
+ strict=False,
+ )
+ assert (lines[0]["product_id"], lines[0]["price_id"]) == (None, None)
+ assert (lines[1]["product_id"], lines[1]["price_id"]) == (mine.id, None)
+ assert (lines[2]["product_id"], lines[2]["price_id"]) == (mine.id, mine.prices[0].id)
+
+ @pytest.mark.asyncio
+ async def test_usage_counts_one_invoice_once_and_include_voided_ones(self, session, ws_id, test_user):
+ """Two lines of one invoice are one invoice; a voided invoice still
+ named the product, so the product still cannot be deleted."""
+ p = await make_product(session, ws_id, test_user.id)
+ inv = await an_invoice(session, ws_id, test_user.id, [
+ {"description": "a", "unit_price": "1", "product_id": p.id},
+ {"description": "b", "unit_price": "1", "product_id": p.id},
+ ])
+ assert (await svc.usage_counts(session, ws_id, [p.id]))[p.id] == 1
+ await invoice_service.void_invoice(session, inv)
+ await session.commit()
+ assert (await svc.usage_counts(session, ws_id, [p.id]))[p.id] == 1
+ with pytest.raises(InvoiceError):
+ await svc.delete_product(session, p)
+
+ @pytest.mark.asyncio
+ async def test_kind_filter_and_archived_prices_stay_out_of_the_picker(self, session, ws_id, test_user):
+ goods = await make_product(session, ws_id, test_user.id, name="Cable", kind="product")
+ await make_product(session, ws_id, test_user.id, name="Support")
+ assert [p.id for p in await svc.list_products(session, ws_id, kind="product")] == [goods.id]
+ with pytest.raises(InvoiceError) as exc:
+ await make_product(session, ws_id, test_user.id, kind="subscription")
+ assert exc.value.code == "invalid_kind"
+ await svc.update_price(session, goods, goods.prices[0], {"active": False})
+ assert svc.price_for(goods, "USD") is None
+ # An archived price can still be named by a line, on purpose: the
+ # invoice was billed at it, and that is what the line records.
+ inv = await an_invoice(session, ws_id, test_user.id, [{"description": "c", "unit_price": "1", "price_id": goods.prices[0].id}])
+ assert inv.lines[0].price_id == goods.prices[0].id
+
+ @pytest.mark.asyncio
+ async def test_a_recurring_price_seeds_nothing_by_itself(self, session, ws_id, test_user):
+ """A cadence on a price is a hint. No agreement, no invoice and no
+ job appears because a price says monthly."""
+ p = await make_product(session, ws_id, test_user.id, prices=[{"currency": "USD", "unit_price": "99", "billing": "recurring", "interval": "monthly"}])
+ assert await schedules.list_schedules(session, ws_id) == []
+ assert svc.price_for(p, "USD") is not None
+
+ @pytest.mark.asyncio
+ async def test_update_product_validates_and_trims(self, session, ws_id, test_user):
+ p = await make_product(session, ws_id, test_user.id)
+ with pytest.raises(InvoiceError) as exc:
+ await svc.update_product(session, p, {"name": " "})
+ assert exc.value.code == "name_required"
+ with pytest.raises(InvoiceError) as exc:
+ await svc.update_product(session, p, {"kind": "thing"})
+ assert exc.value.code == "invalid_kind"
+ await svc.update_product(session, p, {"name": " Senior hour ", "unit": "", "description": ""})
+ assert (p.name, p.unit, p.description) == ("Senior hour", None, None)
+
+
+async def test_prices_over_http(client: AsyncClient, biz_headers):
+ created = (await client.post("/api/products", headers=biz_headers, json={**PAYLOAD, "prices": [{"currency": "USD", "unit_price": "200.00", "lookup_key": "hour_usd"}]})).json()
+ pid, price_id = created["id"], created["prices"][0]["id"]
+ assert created["prices"][0]["lookup_key"] == "hour_usd"
+
+ # The same lookup key twice is a 409 the client can branch on.
+ resp = await client.post(f"/api/products/{pid}/prices", headers=biz_headers, json={"currency": "EUR", "unit_price": "180", "lookup_key": "hour_usd"})
+ assert resp.status_code == 409 and resp.json()["detail"]["code"] == "price_key_taken"
+
+ # Update, archive, and a bad update.
+ resp = await client.patch(f"/api/products/{pid}/prices/{price_id}", headers=biz_headers, json={"unit_price": "210", "nickname": " Standard "})
+ assert resp.status_code == 200
+ assert resp.json()["prices"][0]["unit_price"] == "210.00" and resp.json()["prices"][0]["nickname"] == "Standard"
+ resp = await client.patch(f"/api/products/{pid}/prices/{price_id}", headers=biz_headers, json={"billing": "recurring"})
+ assert resp.status_code == 400 and resp.json()["detail"]["code"] == "interval_required"
+ resp = await client.patch(f"/api/products/{pid}/prices/{price_id}", headers=biz_headers, json={"active": False})
+ assert resp.json()["prices"][0]["active"] is False
+
+ # An unknown price on a known product is a 404, not a 500.
+ assert (await client.patch(f"/api/products/{pid}/prices/{uuid.uuid4()}", headers=biz_headers, json={"active": True})).status_code == 404
+ assert (await client.delete(f"/api/products/{pid}/prices/{uuid.uuid4()}", headers=biz_headers)).status_code == 404
+
+ # Deleting an unused price works; a used one is refused.
+ resp = await client.delete(f"/api/products/{pid}/prices/{price_id}", headers=biz_headers)
+ assert resp.status_code == 200 and resp.json()["prices"] == []
+
+
+async def test_fiscal_refs_over_http(client: AsyncClient, biz_headers):
+ resp = await client.post("/api/products", headers=biz_headers, json={"name": "Design", "fiscal_refs": {"Service_Code": " 1.05 ", "empty": ""}})
+ assert resp.status_code == 201 and resp.json()["fiscal_refs"] == {"service_code": "1.05"}
+ pid = resp.json()["id"]
+ resp = await client.post("/api/products", headers=biz_headers, json={"name": "Bad", "fiscal_refs": {"bad key": "1"}})
+ assert resp.status_code == 400 and resp.json()["detail"]["code"] == "invalid_fiscal_refs"
+ resp = await client.post("/api/invoices", headers=biz_headers, json={"currency": "USD", "lines": [{"description": "Design", "unit_price": "10", "product_id": pid}]})
+ assert resp.status_code == 201 and resp.json()["lines"][0]["fiscal_refs"] == {"service_code": "1.05"}
+ resp = await client.patch(f"/api/products/{pid}", headers=biz_headers, json={"fiscal_refs": None})
+ assert resp.status_code == 200 and resp.json()["fiscal_refs"] is None
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index df93d483..558746be 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -39,6 +39,7 @@ const AgentConnectionsPage = lazy(() => import('@/pages/agent-connections'))
const InvoicesPage = lazy(() => import('@/pages/invoices'))
const InvoiceSchedulesPage = lazy(() => import('@/pages/invoice-schedules'))
const InvoiceScheduleDetailPage = lazy(() => import('@/pages/invoice-schedule-detail'))
+const ProductsPage = lazy(() => import('@/pages/products'))
const InvoiceDetailPage = lazy(() => import('@/pages/invoice-detail'))
const SharedInvoicePage = lazy(() => import('@/pages/shared-invoice'))
const WorkspaceSettingsPage = lazy(() => import('@/pages/workspace-settings'))
@@ -114,6 +115,7 @@ function App() {
{/* Declared before `/invoices/:id`, which would otherwise take "schedules" for an id. */}
<Route path="/invoices/schedules" element={<ModuleRoute module="invoices"><InvoiceSchedulesPage /></ModuleRoute>} />
<Route path="/invoices/schedules/:id" element={<ModuleRoute module="invoices"><InvoiceScheduleDetailPage /></ModuleRoute>} />
+ <Route path="/invoices/products" element={<ModuleRoute module="invoices"><ProductsPage /></ModuleRoute>} />
<Route path="/invoices/:id" element={<ModuleRoute module="invoices"><InvoiceDetailPage /></ModuleRoute>} />
<Route path="/workspace/settings" element={<WorkspaceSettingsPage />} />
<Route path="/admin" element={<AdminRoute><AdminSettingsPage /></AdminRoute>} />
diff --git a/frontend/src/components/invoice-line-editor.tsx b/frontend/src/components/invoice-line-editor.tsx
index f30fc8f2..336d37c3 100644
--- a/frontend/src/components/invoice-line-editor.tsx
+++ b/frontend/src/components/invoice-line-editor.tsx
@@ -1,5 +1,5 @@
import { useTranslation } from 'react-i18next'
-import { Plus, Trash2 } from 'lucide-react'
+import { Package, Plus, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
@@ -7,6 +7,8 @@ import { Label } from '@/components/ui/label'
import { formatCurrency } from '@/lib/format'
import { useDisplayLocale } from '@/hooks/use-display-locale'
import { linesTotal } from '@/lib/invoice-utils'
+import { lineFromProduct } from '@/lib/product-utils'
+import { ProductPicker } from '@/components/product-picker'
import type { InvoiceLineInput } from '@/types'
/**
@@ -117,7 +119,18 @@ export function InvoiceLineEditor({
data-testid="invoice-line-row"
className="grid grid-cols-2 sm:grid-cols-[1fr_4.5rem_5rem_7rem_6rem_2rem] gap-2 px-3 py-2.5 items-center"
>
- <div className="col-span-2 sm:col-span-1">
+ <div className="col-span-2 sm:col-span-1 flex items-center gap-1.5">
+ {/* The catalog, one click away and never in the way: the
+ description stays a plain input, and a product fills
+ it (and the unit and price) when picked. */}
+ <ProductPicker
+ currency={currency}
+ onPick={(product, price) =>
+ onChange(
+ rows.map((row, i) => (i === index ? lineFromProduct(row, product, price) : row)),
+ )
+ }
+ />
<Input
className="h-9"
placeholder={t('invoices.field.lineDescription')}
@@ -126,6 +139,16 @@ export function InvoiceLineEditor({
data-testid={`invoice-line-description-${index}`}
aria-label={t('invoices.field.lineDescription')}
/>
+ {line.product_id && (
+ <span
+ className="inline-flex shrink-0 items-center text-muted-foreground"
+ title={t('invoices.products.fromCatalog')}
+ aria-label={t('invoices.products.fromCatalog')}
+ data-testid={`invoice-line-from-catalog-${index}`}
+ >
+ <Package className="h-3.5 w-3.5" />
+ </span>
+ )}
</div>
<Field label={t('invoices.column.quantity')}>
diff --git a/frontend/src/components/product-picker.tsx b/frontend/src/components/product-picker.tsx
new file mode 100644
index 00000000..2bd9f3c2
--- /dev/null
+++ b/frontend/src/components/product-picker.tsx
@@ -0,0 +1,141 @@
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery } from '@tanstack/react-query'
+import { PackageSearch } from 'lucide-react'
+
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from '@/components/ui/command'
+import { products as productsApi } from '@/lib/api'
+import { formatCurrency } from '@/lib/format'
+import { priceFor } from '@/lib/product-utils'
+import { useDisplayLocale } from '@/hooks/use-display-locale'
+import { cn, normalizeText } from '@/lib/utils'
+import type { Product, ProductPrice } from '@/types'
+
+/**
+ * The catalog, as a button beside a line's description.
+ *
+ * A button rather than a combobox replacing the description field: the
+ * field has to stay a plain input, because most lines are typed and a
+ * dropdown that opens on every keystroke would get in the way of the
+ * common case. The catalog is one click away for the lines that come
+ * from it, and invisible to a workspace that never made a product.
+ */
+export function ProductPicker({
+ currency,
+ onPick,
+ disabled = false,
+ className,
+}: {
+ /** The invoice's currency: decides which of a product's prices is offered. */
+ currency: string
+ onPick: (product: Product, price: ProductPrice | null) => void
+ disabled?: boolean
+ className?: string
+}) {
+ const { t } = useTranslation()
+ const locale = useDisplayLocale()
+ const [open, setOpen] = useState(false)
+ const [search, setSearch] = useState('')
+ // Only once opened: a workspace without a catalog never asks for one.
+ const { data: products = [] } = useQuery({
+ queryKey: ['products', 'active'],
+ queryFn: () => productsApi.list({ active: true }),
+ enabled: open,
+ })
+
+ const rows = useMemo(
+ () =>
+ [...products]
+ .sort((a, b) => a.name.localeCompare(b.name))
+ .map((product) => ({ product, price: priceFor(product, currency) })),
+ [products, currency],
+ )
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next)
+ if (!next) setSearch('')
+ }}
+ >
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ disabled={disabled}
+ aria-label={t('invoices.products.pick')}
+ title={t('invoices.products.pick')}
+ data-testid="invoice-line-pick-product"
+ className={cn(
+ 'inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-input bg-card text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50',
+ className,
+ )}
+ >
+ <PackageSearch className="h-4 w-4" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[340px] p-0 overflow-hidden">
+ <Command
+ filter={(itemValue, query, keywords) => {
+ const text = keywords?.length ? keywords.join(' ') : itemValue
+ return normalizeText(text).includes(normalizeText(query)) ? 1 : 0
+ }}
+ >
+ <CommandInput
+ placeholder={t('invoices.products.searchPlaceholder')}
+ value={search}
+ onValueChange={setSearch}
+ />
+ <CommandList>
+ <CommandEmpty>
+ {products.length === 0
+ ? t('invoices.products.emptyPicker')
+ : t('invoices.products.noneFound')}
+ </CommandEmpty>
+ <CommandGroup>
+ {rows.map(({ product, price }) => (
+ <CommandItem
+ key={product.id}
+ value={product.id}
+ keywords={[product.name, product.description ?? '']}
+ onSelect={() => {
+ onPick(product, price)
+ setOpen(false)
+ setSearch('')
+ }}
+ className="cursor-pointer"
+ data-testid={`product-option-${product.id}`}
+ >
+ <span className="flex-1 min-w-0">
+ <span className="block truncate">{product.name}</span>
+ {product.description && (
+ <span className="block truncate text-[11px] text-muted-foreground">
+ {product.description}
+ </span>
+ )}
+ </span>
+ {/* The price in this invoice's currency, or a quiet
+ note that there is none and the amount is typed. */}
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
+ {price
+ ? formatCurrency(Number(price.unit_price), price.currency, locale) +
+ (price.interval ? ` / ${t(`invoices.products.per.${price.interval}`)}` : '')
+ : t('invoices.products.noPriceIn', { currency })}
+ </span>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ )
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index e8b3c9b0..793ad9aa 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -30,6 +30,10 @@ import type {
InvoiceSchedulePeriod,
InvoiceScheduleStatus,
InvoiceScheduleSummary,
+ Product,
+ ProductFieldSpec,
+ ProductKind,
+ PriceBilling,
InvoiceLineInput,
InvoiceShareLink,
IssuerProfile,
@@ -763,6 +767,11 @@ export const fiscal = {
const { data } = await api.get('/fiscal/tax-id-kinds')
return data
},
+ /** Fiscal references the workspace's jurisdiction suggests on a product. */
+ productFields: async (): Promise<{ jurisdiction: string | null; fields: ProductFieldSpec[] }> => {
+ const { data } = await api.get('/fiscal/product-fields')
+ return data
+ },
}
export interface PayeeWritePayload {
@@ -779,6 +788,67 @@ export interface PayeeWritePayload {
tax_ids?: PayeeTaxId[]
}
+export interface PricePayload {
+ currency: string
+ unit_price: string
+ tax_rate?: string | null
+ billing?: PriceBilling
+ interval?: InvoiceScheduleFrequency | null
+ nickname?: string | null
+ lookup_key?: string | null
+}
+
+export interface ProductPayload {
+ name?: string
+ description?: string | null
+ kind?: ProductKind
+ unit?: string | null
+ active?: boolean
+ fiscal_refs?: Record<string, string> | null
+ prices?: PricePayload[]
+}
+
+/** The catalog: what the workspace sells. Gated like invoices. */
+export const products = {
+ list: async (params?: { active?: boolean | null; kind?: ProductKind; q?: string }): Promise<Product[]> => {
+ const { data } = await api.get('/products', {
+ params: {
+ ...(params?.active === undefined ? {} : { active: params.active }),
+ ...(params?.kind ? { kind: params.kind } : {}),
+ ...(params?.q ? { q: params.q } : {}),
+ },
+ })
+ return data
+ },
+ get: async (id: string): Promise<Product> => {
+ const { data } = await api.get(`/products/${id}`)
+ return data
+ },
+ create: async (payload: ProductPayload): Promise<Product> => {
+ const { data } = await api.post('/products', payload)
+ return data
+ },
+ update: async (id: string, payload: ProductPayload): Promise<Product> => {
+ const { data } = await api.patch(`/products/${id}`, payload)
+ return data
+ },
+ remove: async (id: string): Promise<void> => {
+ await api.delete(`/products/${id}`)
+ },
+ addPrice: async (id: string, payload: PricePayload): Promise<Product> => {
+ const { data } = await api.post(`/products/${id}/prices`, payload)
+ return data
+ },
+ updatePrice: async (id: string, priceId: string, payload: Partial<PricePayload> & { active?: boolean }): Promise<Product> => {
+ const { data } = await api.patch(`/products/${id}/prices/${priceId}`, payload)
+ return data
+ },
+ removePrice: async (id: string, priceId: string): Promise<Product> => {
+ const { data } = await api.delete(`/products/${id}/prices/${priceId}`)
+ return data
+ },
+}
+
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
diff --git a/frontend/src/lib/invoice-utils.ts b/frontend/src/lib/invoice-utils.ts
index f25dd452..510706c8 100644
--- a/frontend/src/lib/invoice-utils.ts
+++ b/frontend/src/lib/invoice-utils.ts
@@ -198,7 +198,7 @@ export const ISSUED_BY_US = 'issued'
/** Where a filed document came from, as a person reads it.
*
- * A source id is a machine name (`stripe`, `nfe`, `email`), so it is
+ * A source id is a machine name (`gateway`, `nfe`, `email`), so it is
* shown as it is rather than translated — renaming somebody's system in
* our own words helps nobody trying to work out which integration
* delivered which file. Two sources are our word rather than theirs: a
diff --git a/frontend/src/lib/product-utils.test.ts b/frontend/src/lib/product-utils.test.ts
new file mode 100644
index 00000000..cd7d2f33
--- /dev/null
+++ b/frontend/src/lib/product-utils.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from 'vitest'
+
+import { lineFromProduct, priceFor, productActions } from './product-utils'
+import type { Product, ProductPrice } from '@/types'
+
+function price(overrides: Partial<ProductPrice>): ProductPrice {
+ return {
+ id: 'p',
+ product_id: 'prod',
+ currency: 'USD',
+ unit_price: '100.00',
+ tax_rate: null,
+ billing: 'one_time',
+ interval: null,
+ nickname: null,
+ lookup_key: null,
+ active: true,
+ external_source: null,
+ external_id: null,
+ created_at: '2026-01-01T00:00:00Z',
+ ...overrides,
+ }
+}
+
+function product(prices: ProductPrice[], overrides: Partial<Product> = {}): Product {
+ return {
+ id: 'prod',
+ name: 'Consulting hour',
+ description: null,
+ kind: 'service',
+ unit: 'h',
+ active: true,
+ origin: 'local',
+ external_source: null,
+ external_id: null,
+ custom_fields: null,
+ fiscal_refs: null,
+ prices,
+ created_at: '2026-01-01T00:00:00Z',
+ invoice_count: 0,
+ ...overrides,
+ }
+}
+
+describe('priceFor', () => {
+ it('offers a live price in the currency, one-time before recurring, oldest first', () => {
+ const p = product([
+ price({ id: 'monthly', billing: 'recurring', interval: 'monthly', created_at: '2026-01-01T00:00:00Z' }),
+ price({ id: 'later', unit_price: '120.00', created_at: '2026-03-01T00:00:00Z' }),
+ price({ id: 'first', unit_price: '110.00', created_at: '2026-02-01T00:00:00Z' }),
+ price({ id: 'eur', currency: 'EUR' }),
+ price({ id: 'dead', active: false, created_at: '2025-01-01T00:00:00Z' }),
+ ])
+ expect(priceFor(p, 'usd')?.id).toBe('first')
+ expect(priceFor(p, 'EUR')?.id).toBe('eur')
+ expect(priceFor(p, 'BRL')).toBeNull()
+ })
+})
+
+describe('lineFromProduct', () => {
+ const current = { description: 'typed', quantity: '3', unit_price: '9', unit: 'day', tax_rate: '5' }
+
+ it('copies the product in and remembers where it came from', () => {
+ const p = product([price({ id: 'usd', unit_price: '200.00', tax_rate: '10' })])
+ expect(lineFromProduct(current, p, p.prices[0])).toEqual({
+ description: 'Consulting hour',
+ quantity: '3',
+ unit: 'h',
+ unit_price: '200.00',
+ tax_rate: '10',
+ product_id: 'prod',
+ price_id: 'usd',
+ })
+ })
+
+ it('leaves the amount for the person when there is no price in the currency', () => {
+ const p = product([], { unit: null })
+ expect(lineFromProduct(current, p, null)).toEqual({
+ ...current,
+ description: 'Consulting hour',
+ product_id: 'prod',
+ price_id: null,
+ })
+ })
+})
+
+describe('productActions', () => {
+ it('archives what invoices name and deletes only what nothing names', () => {
+ expect(productActions({ active: true, invoice_count: 2 })).toEqual({ canArchive: true, canRestore: false, canDelete: false })
+ expect(productActions({ active: false, invoice_count: 0 })).toEqual({ canArchive: false, canRestore: true, canDelete: true })
+ })
+})
diff --git a/frontend/src/lib/product-utils.ts b/frontend/src/lib/product-utils.ts
new file mode 100644
index 00000000..bd1d3e7f
--- /dev/null
+++ b/frontend/src/lib/product-utils.ts
@@ -0,0 +1,58 @@
+import type { InvoiceLineInput, Product, ProductPrice } from '@/types'
+
+/**
+ * Pure helpers for the catalog. The one rule they encode: a product
+ * fills a line, it never owns it. `lineFromProduct` copies values in
+ * and remembers where they came from; everything after that is the
+ * line's own.
+ */
+
+/** The price to offer for a product in a currency: a live one in that
+ * currency, one-time before recurring, oldest first. Mirrors
+ * `product_service.price_for` on the server. */
+export function priceFor(product: Product, currency: string): ProductPrice | null {
+ const code = currency.toUpperCase()
+ const candidates = product.prices
+ .filter((p) => p.active && p.currency === code)
+ .sort((a, b) => {
+ if ((a.billing === 'one_time') !== (b.billing === 'one_time')) {
+ return a.billing === 'one_time' ? -1 : 1
+ }
+ return a.created_at.localeCompare(b.created_at)
+ })
+ return candidates[0] ?? null
+}
+
+/** A line filled from a product. Keeps the row's quantity; a price in
+ * the invoice's currency fills the amount and the tax rate, and no
+ * price leaves them for the person to type. */
+export function lineFromProduct(
+ current: InvoiceLineInput,
+ product: Product,
+ price: ProductPrice | null,
+): InvoiceLineInput {
+ return {
+ ...current,
+ description: product.name,
+ unit: product.unit ?? current.unit ?? null,
+ unit_price: price ? price.unit_price : current.unit_price,
+ tax_rate: price ? price.tax_rate : current.tax_rate,
+ product_id: product.id,
+ price_id: price?.id ?? null,
+ }
+}
+
+/** Which actions a product offers. A product an invoice names is
+ * archived, never deleted; the server refuses the delete either way,
+ * so the button is not offered. */
+export function productActions(product: Pick<Product, 'active' | 'invoice_count'>): {
+ canArchive: boolean
+ canRestore: boolean
+ canDelete: boolean
+} {
+ return {
+ canArchive: product.active,
+ canRestore: !product.active,
+ canDelete: product.invoice_count === 0,
+ }
+}
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index e98bc50f..d7e48fb2 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -329,7 +329,19 @@
"negative_discount": "Ein Rabatt kann nicht negativ sein.",
"first_term": "Der Preis, der ab Beginn gilt, kann weder verschoben noch entfernt werden. Ändern Sie ihn oder fügen Sie einen neuen Preis ab einem späteren Datum hinzu.",
"not_receivable": "Nur eine von Ihnen ausgestellte Rechnung kann zu einer Vereinbarung gehören.",
- "period_already_issued": "Dieser Zeitraum wurde gerade ausgestellt. Aktualisieren Sie die Seite, um ihn zu sehen."
+ "period_already_issued": "Dieser Zeitraum wurde gerade ausgestellt. Aktualisieren Sie die Seite, um ihn zu sehen.",
+ "product_not_found": "Produkt nicht gefunden.",
+ "price_not_found": "Preis bei diesem Produkt nicht gefunden.",
+ "product_in_use": "Rechnungen nennen dieses Produkt. Archivieren Sie es, statt es zu löschen.",
+ "price_in_use": "Rechnungen wurden zu diesem Preis gestellt. Archivieren Sie ihn, statt ihn zu löschen.",
+ "invalid_kind": "Unbekannte Produktart.",
+ "invalid_billing": "Unbekannte Abrechnungsart.",
+ "interval_required": "Ein wiederkehrender Preis braucht einen Rhythmus.",
+ "currency_required": "Ein Preis braucht eine Währung.",
+ "unit_price_required": "Ein Preis braucht einen Betrag.",
+ "negative_price": "Ein Preis kann nicht negativ sein.",
+ "invalid_fiscal_refs": "Steuerliche Referenzen müssen kurze Textwerte unter einfachen Schlüsseln sein (Buchstaben, Ziffern, Unterstrich).",
+ "price_key_taken": "Ein anderer Preis verwendet diesen Suchschlüssel oder diese externe ID bereits."
},
"comingNext": "Stelle deinen Kunden Rechnungen und behalte im Blick, was bezahlt ist und was offen bleibt. Das ist das Nächste, was gebaut wird.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Noch keine Rechnung unter dieser Vereinbarung.",
"emptyNext": "Noch keine Rechnung. Die erste wird am {{date}} erstellt."
}
+ },
+ "products": {
+ "title": "Produkte",
+ "new": "Neues Produkt",
+ "newDescription": "Etwas, das Sie verkaufen, mit einem Preis pro Währung. Die Auswahl füllt eine Rechnungsposition aus; die Position können Sie danach frei ändern.",
+ "editTitle": "Produkt bearbeiten",
+ "empty": "Noch keine Produkte. Legen Sie an, was Sie verkaufen, und jede Rechnungsposition ist nur einen Klick entfernt.",
+ "emptyArchived": "Nichts archiviert.",
+ "emptyPicker": "Noch keine Produkte. Legen Sie sie unter Produkte an.",
+ "noneFound": "Kein Produkt passt.",
+ "searchPlaceholder": "Produkte suchen",
+ "pick": "Aus dem Katalog wählen",
+ "fromCatalog": "Aus dem Katalog",
+ "noPrice": "Kein Preis",
+ "noPriceIn": "kein Preis in {{currency}}",
+ "perUnit": "pro {{unit}}",
+ "created": "Produkt erstellt",
+ "saved": "Produkt gespeichert",
+ "archived": "Produkt archiviert. Rechnungen, die es nennen, bleiben unverändert.",
+ "restored": "Produkt wiederhergestellt",
+ "deleted": "Produkt gelöscht",
+ "filter": {
+ "active": "Aktiv",
+ "archived": "Archiviert"
+ },
+ "kind": {
+ "service": "Dienstleistung",
+ "product": "Produkt"
+ },
+ "billing": {
+ "one_time": "Einmalig",
+ "every": "Pro {{interval}}"
+ },
+ "per": {
+ "weekly": "Woche",
+ "biweekly": "2 Wochen",
+ "monthly": "Monat",
+ "quarterly": "Quartal",
+ "semiannual": "6 Monate",
+ "yearly": "Jahr"
+ },
+ "column": {
+ "name": "Name",
+ "kind": "Art",
+ "prices": "Preise",
+ "invoices": "Rechnungen"
+ },
+ "field": {
+ "name": "Name",
+ "namePlaceholder": "Beratungsstunde, Pro-Tarif, Logo-Design",
+ "kind": "Art",
+ "description": "Beschreibung",
+ "prices": "Preise",
+ "pricesHint": "Einer pro Währung. Ein wiederkehrender Preis gibt an, wie oft; er ist ein Hinweis für wiederkehrende Rechnungen, von selbst wird nichts berechnet.",
+ "addPrice": "Preis hinzufügen",
+ "noPrices": "Keine Preise. Der Name füllt die Position trotzdem aus; der Betrag wird eingetippt.",
+ "nickname": "Bezeichnung (optional)",
+ "fiscalRefs": "Steuerliche Referenzen",
+ "fiscalRefsHint": "Was ein Steuerbeleg pro Position braucht. Von Ihrer Steuerzone vorgeschlagen; fügen Sie jeden weiteren Schlüssel hinzu, den Sie brauchen.",
+ "customRefKey": "anderer Schlüssel (z. B. hs_code)",
+ "addRef": "Hinzufügen",
+ "fiscalRefsNone": "Für diese Art wird hier nichts vorgeschlagen. Fügen Sie jeden Schlüssel hinzu, den Ihre Steuerbelege benötigen."
+ },
+ "action": {
+ "archive": "Archivieren",
+ "restore": "Wiederherstellen"
+ }
}
},
"collections": {
@@ -1944,7 +2023,18 @@
"uscc": "USCC"
},
"otherCountries": "Andere Länder",
- "anyCountry": "Anderswo"
+ "anyCountry": "Anderswo",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / Barcode",
+ "service_code": "Dienstleistungscode (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Kommunaler Dienstleistungscode",
+ "hs_code": "HS-Code",
+ "sat_product_code": "SAT-Produkt-/Dienstleistungscode",
+ "sat_unit_code": "SAT-Einheitencode"
+ }
},
"common": {
"selectTimezone": "Zeitzone wählen",
diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.json
index bff2d9c9..e3afcd27 100644
--- a/frontend/src/locales/el.json
+++ b/frontend/src/locales/el.json
@@ -329,7 +329,19 @@
"negative_discount": "Μια έκπτωση δεν μπορεί να είναι αρνητική.",
"first_term": "Η τιμή που ισχύει από την αρχή δεν μπορεί να μετακινηθεί ή να αφαιρεθεί. Αλλάξτε την ή προσθέστε νέα τιμή από μεταγενέστερη ημερομηνία.",
"not_receivable": "Μόνο ένα τιμολόγιο που εκδώσατε εσείς μπορεί να ανήκει σε μια συμφωνία.",
- "period_already_issued": "Αυτή η περίοδος μόλις εκδόθηκε. Ανανεώστε τη σελίδα για να τη δείτε."
+ "period_already_issued": "Αυτή η περίοδος μόλις εκδόθηκε. Ανανεώστε τη σελίδα για να τη δείτε.",
+ "product_not_found": "Το προϊόν δεν βρέθηκε.",
+ "price_not_found": "Η τιμή δεν βρέθηκε σε αυτό το προϊόν.",
+ "product_in_use": "Υπάρχουν τιμολόγια που αναφέρουν αυτό το προϊόν. Αρχειοθετήστε το αντί να το διαγράψετε.",
+ "price_in_use": "Υπάρχουν τιμολόγια που χρεώθηκαν με αυτή την τιμή. Αρχειοθετήστε την αντί να τη διαγράψετε.",
+ "invalid_kind": "Άγνωστο είδος προϊόντος.",
+ "invalid_billing": "Άγνωστο είδος χρέωσης.",
+ "interval_required": "Μια επαναλαμβανόμενη τιμή χρειάζεται συχνότητα.",
+ "currency_required": "Μια τιμή χρειάζεται νόμισμα.",
+ "unit_price_required": "Μια τιμή χρειάζεται ποσό.",
+ "negative_price": "Μια τιμή δεν μπορεί να είναι αρνητική.",
+ "invalid_fiscal_refs": "Οι φορολογικές αναφορές πρέπει να είναι σύντομες τιμές κειμένου κάτω από απλά κλειδιά (γράμματα, ψηφία, κάτω παύλα).",
+ "price_key_taken": "Μια άλλη τιμή χρησιμοποιεί ήδη αυτό το κλειδί αναζήτησης ή εξωτερικό αναγνωριστικό."
},
"comingNext": "Τιμολογήστε τους πελάτες σας και παρακολουθήστε τι έχει πληρωθεί και τι εκκρεμεί. Αυτή είναι η επόμενη λειτουργία που αναπτύσσεται.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Κανένα τιμολόγιο βάσει αυτής της συμφωνίας ακόμη.",
"emptyNext": "Κανένα τιμολόγιο ακόμη. Το πρώτο θα συνταχθεί στις {{date}}."
}
+ },
+ "products": {
+ "title": "Προϊόντα",
+ "new": "Νέο προϊόν",
+ "newDescription": "Κάτι που πουλάτε, με μία τιμή ανά νόμισμα. Η επιλογή του συμπληρώνει μια γραμμή τιμολογίου· η γραμμή παραμένει δική σας για να την αλλάξετε μετά.",
+ "editTitle": "Επεξεργασία προϊόντος",
+ "empty": "Δεν υπάρχουν προϊόντα ακόμη. Προσθέστε ό,τι πουλάτε, και κάθε γραμμή τιμολογίου απέχει ένα κλικ.",
+ "emptyArchived": "Τίποτα στο αρχείο.",
+ "emptyPicker": "Δεν υπάρχουν προϊόντα ακόμη. Προσθέστε τα στα Προϊόντα.",
+ "noneFound": "Κανένα προϊόν δεν ταιριάζει.",
+ "searchPlaceholder": "Αναζήτηση προϊόντων",
+ "pick": "Επιλογή από τον κατάλογο",
+ "fromCatalog": "Από τον κατάλογο",
+ "noPrice": "Χωρίς τιμή",
+ "noPriceIn": "χωρίς τιμή σε {{currency}}",
+ "perUnit": "ανά {{unit}}",
+ "created": "Το προϊόν δημιουργήθηκε",
+ "saved": "Το προϊόν αποθηκεύτηκε",
+ "archived": "Το προϊόν αρχειοθετήθηκε. Τα τιμολόγια που το αναφέρουν δεν αλλάζουν.",
+ "restored": "Το προϊόν επαναφέρθηκε",
+ "deleted": "Το προϊόν διαγράφηκε",
+ "filter": {
+ "active": "Ενεργά",
+ "archived": "Αρχειοθετημένα"
+ },
+ "kind": {
+ "service": "Υπηρεσία",
+ "product": "Προϊόν"
+ },
+ "billing": {
+ "one_time": "Εφάπαξ",
+ "every": "Κάθε {{interval}}"
+ },
+ "per": {
+ "weekly": "εβδομάδα",
+ "biweekly": "2 εβδομάδες",
+ "monthly": "μήνα",
+ "quarterly": "τρίμηνο",
+ "semiannual": "6 μήνες",
+ "yearly": "έτος"
+ },
+ "column": {
+ "name": "Όνομα",
+ "kind": "Είδος",
+ "prices": "Τιμές",
+ "invoices": "Τιμολόγια"
+ },
+ "field": {
+ "name": "Όνομα",
+ "namePlaceholder": "Ώρα συμβουλευτικής, Πλάνο Pro, Σχεδιασμός λογότυπου",
+ "kind": "Είδος",
+ "description": "Περιγραφή",
+ "prices": "Τιμές",
+ "pricesHint": "Μία ανά νόμισμα. Μια επαναλαμβανόμενη τιμή δηλώνει τη συχνότητα· είναι υπόδειξη για επαναλαμβανόμενα τιμολόγια, τίποτα δεν χρεώνεται από μόνο του.",
+ "addPrice": "Προσθήκη τιμής",
+ "noPrices": "Χωρίς τιμές. Το όνομα συμπληρώνει τη γραμμή ούτως ή άλλως· το ποσό πληκτρολογείται.",
+ "nickname": "Ετικέτα (προαιρετικό)",
+ "fiscalRefs": "Φορολογικές αναφορές",
+ "fiscalRefsHint": "Τι χρειάζεται ένα φορολογικό παραστατικό ανά γραμμή. Προτείνεται από τη δικαιοδοσία σας· προσθέστε όποιο άλλο κλειδί χρειάζεστε.",
+ "customRefKey": "άλλο κλειδί (π.χ. hs_code)",
+ "addRef": "Προσθήκη",
+ "fiscalRefsNone": "Δεν προτείνεται τίποτα για αυτό το είδος εδώ. Προσθέστε όποιο κλειδί χρειάζονται τα φορολογικά σας έγγραφα."
+ },
+ "action": {
+ "archive": "Αρχειοθέτηση",
+ "restore": "Επαναφορά"
+ }
}
},
"collections": {
@@ -1943,7 +2022,18 @@
"uscc": "USCC"
},
"otherCountries": "Άλλες χώρες",
- "anyCountry": "Οπουδήποτε αλλού"
+ "anyCountry": "Οπουδήποτε αλλού",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / γραμμωτός κώδικας",
+ "service_code": "Κωδικός υπηρεσίας (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Δημοτικός κωδικός υπηρεσίας",
+ "hs_code": "Κωδικός HS",
+ "sat_product_code": "Κωδικός προϊόντος/υπηρεσίας SAT",
+ "sat_unit_code": "Κωδικός μονάδας SAT"
+ }
},
"common": {
"selectTimezone": "Επιλογή ζώνης ώρας",
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index e4bef688..2fd5ff30 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -329,7 +329,19 @@
"negative_discount": "A discount cannot be negative.",
"first_term": "The price in force from the start cannot be moved or removed. Change it, or add a new price from a later date.",
"not_receivable": "Only an invoice you issued can belong to an agreement.",
- "period_already_issued": "This period was just issued. Refresh to see it."
+ "period_already_issued": "This period was just issued. Refresh to see it.",
+ "product_not_found": "Product not found.",
+ "price_not_found": "Price not found on this product.",
+ "product_in_use": "Invoices name this product. Archive it instead of deleting it.",
+ "price_in_use": "Invoices were billed at this price. Archive it instead of deleting it.",
+ "invalid_kind": "Unknown product kind.",
+ "invalid_billing": "Unknown billing kind.",
+ "interval_required": "A recurring price needs a cadence.",
+ "currency_required": "A price needs a currency.",
+ "unit_price_required": "A price needs an amount.",
+ "negative_price": "A price cannot be negative.",
+ "invalid_fiscal_refs": "Fiscal references must be short text values under simple keys (letters, digits, underscore).",
+ "price_key_taken": "Another price already uses this lookup key or external id."
},
"comingNext": "Bill your clients and keep track of what has been paid and what is still open. This is the next thing being built.",
"document": {
@@ -564,6 +576,73 @@
"empty": "No invoice under this agreement yet.",
"emptyNext": "No invoice yet. The first one is written on {{date}}."
}
+ },
+ "products": {
+ "title": "Products",
+ "new": "New product",
+ "newDescription": "Something you sell, with a price per currency. Picking it fills an invoice line; the line is yours to change after.",
+ "editTitle": "Edit product",
+ "empty": "No products yet. Add what you sell, and every invoice line is one click from it.",
+ "emptyArchived": "Nothing archived.",
+ "emptyPicker": "No products yet. Add them under Products.",
+ "noneFound": "No product matches.",
+ "searchPlaceholder": "Search products",
+ "pick": "Pick from the catalog",
+ "fromCatalog": "From the catalog",
+ "noPrice": "No price",
+ "noPriceIn": "no price in {{currency}}",
+ "perUnit": "per {{unit}}",
+ "created": "Product created",
+ "saved": "Product saved",
+ "archived": "Product archived. Invoices that name it are unchanged.",
+ "restored": "Product restored",
+ "deleted": "Product deleted",
+ "filter": {
+ "active": "Active",
+ "archived": "Archived"
+ },
+ "kind": {
+ "service": "Service",
+ "product": "Product"
+ },
+ "billing": {
+ "one_time": "One-time",
+ "every": "Every {{interval}}"
+ },
+ "per": {
+ "weekly": "week",
+ "biweekly": "2 weeks",
+ "monthly": "month",
+ "quarterly": "quarter",
+ "semiannual": "6 months",
+ "yearly": "year"
+ },
+ "column": {
+ "name": "Name",
+ "kind": "Kind",
+ "prices": "Prices",
+ "invoices": "Invoices"
+ },
+ "field": {
+ "name": "Name",
+ "namePlaceholder": "Consulting hour, Pro plan, Logo design",
+ "kind": "Kind",
+ "description": "Description",
+ "prices": "Prices",
+ "pricesHint": "One per currency. A recurring price says how often; it is a hint for recurring invoices, nothing is charged by itself.",
+ "addPrice": "Add price",
+ "noPrices": "No prices. The name still fills a line; the amount is typed.",
+ "nickname": "Label (optional)",
+ "fiscalRefs": "Fiscal references",
+ "fiscalRefsHint": "What a fiscal document needs per line. Suggested by your jurisdiction; add any other key you need.",
+ "customRefKey": "other key (e.g. hs_code)",
+ "addRef": "Add",
+ "fiscalRefsNone": "Nothing suggested for this kind here. Add any key your fiscal documents need."
+ },
+ "action": {
+ "archive": "Archive",
+ "restore": "Restore"
+ }
}
},
"collections": {
@@ -1943,7 +2022,18 @@
"uscc": "USCC"
},
"otherCountries": "Other countries",
- "anyCountry": "Anywhere else"
+ "anyCountry": "Anywhere else",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / barcode",
+ "service_code": "Service code (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Municipal service code",
+ "hs_code": "HS code",
+ "sat_product_code": "SAT product/service code",
+ "sat_unit_code": "SAT unit code"
+ }
},
"common": {
"selectTimezone": "Select timezone",
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 4ae684a1..22117757 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -329,7 +329,19 @@
"negative_discount": "Un descuento no puede ser negativo.",
"first_term": "El precio vigente desde el inicio no se puede mover ni eliminar. Cámbialo o añade un nuevo precio a partir de una fecha posterior.",
"not_receivable": "Solo una factura emitida por ti puede pertenecer a un acuerdo.",
- "period_already_issued": "Este período se acaba de emitir. Actualiza para verlo."
+ "period_already_issued": "Este período se acaba de emitir. Actualiza para verlo.",
+ "product_not_found": "Producto no encontrado.",
+ "price_not_found": "Precio no encontrado en este producto.",
+ "product_in_use": "Hay facturas que mencionan este producto. Archívalo en lugar de eliminarlo.",
+ "price_in_use": "Hay facturas emitidas con este precio. Archívalo en lugar de eliminarlo.",
+ "invalid_kind": "Tipo de producto desconocido.",
+ "invalid_billing": "Tipo de facturación desconocido.",
+ "interval_required": "Un precio recurrente necesita una frecuencia.",
+ "currency_required": "Un precio necesita una moneda.",
+ "unit_price_required": "Un precio necesita un importe.",
+ "negative_price": "Un precio no puede ser negativo.",
+ "invalid_fiscal_refs": "Las referencias fiscales deben ser textos cortos bajo claves simples (letras, dígitos, guion bajo).",
+ "price_key_taken": "Otro precio ya usa esta clave de búsqueda o id externo."
},
"comingNext": "Cobra a tus clientes y controla lo que ya se pagó y lo que sigue pendiente. Es lo próximo que se está construyendo.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Aún no hay facturas bajo este acuerdo.",
"emptyNext": "Aún no hay facturas. La primera se generará el {{date}}."
}
+ },
+ "products": {
+ "title": "Productos",
+ "new": "Nuevo producto",
+ "newDescription": "Algo que vendes, con un precio por moneda. Al elegirlo se rellena una línea de la factura; la línea sigue siendo tuya para cambiarla después.",
+ "editTitle": "Editar producto",
+ "empty": "Aún no hay productos. Añade lo que vendes y cada línea de factura estará a un clic.",
+ "emptyArchived": "Nada archivado.",
+ "emptyPicker": "Aún no hay productos. Añádelos en Productos.",
+ "noneFound": "Ningún producto coincide.",
+ "searchPlaceholder": "Buscar productos",
+ "pick": "Elegir del catálogo",
+ "fromCatalog": "Del catálogo",
+ "noPrice": "Sin precio",
+ "noPriceIn": "sin precio en {{currency}}",
+ "perUnit": "por {{unit}}",
+ "created": "Producto creado",
+ "saved": "Producto guardado",
+ "archived": "Producto archivado. Las facturas que lo mencionan no cambian.",
+ "restored": "Producto restaurado",
+ "deleted": "Producto eliminado",
+ "filter": {
+ "active": "Activos",
+ "archived": "Archivados"
+ },
+ "kind": {
+ "service": "Servicio",
+ "product": "Producto"
+ },
+ "billing": {
+ "one_time": "Pago único",
+ "every": "Cada {{interval}}"
+ },
+ "per": {
+ "weekly": "semana",
+ "biweekly": "2 semanas",
+ "monthly": "mes",
+ "quarterly": "trimestre",
+ "semiannual": "6 meses",
+ "yearly": "año"
+ },
+ "column": {
+ "name": "Nombre",
+ "kind": "Tipo",
+ "prices": "Precios",
+ "invoices": "Facturas"
+ },
+ "field": {
+ "name": "Nombre",
+ "namePlaceholder": "Hora de consultoría, Plan Pro, Diseño de logo",
+ "kind": "Tipo",
+ "description": "Descripción",
+ "prices": "Precios",
+ "pricesHint": "Uno por moneda. Un precio recurrente indica la frecuencia; es una sugerencia para facturas recurrentes, nada se cobra por sí solo.",
+ "addPrice": "Añadir precio",
+ "noPrices": "Sin precios. El nombre rellena la línea igualmente; el importe se escribe a mano.",
+ "nickname": "Etiqueta (opcional)",
+ "fiscalRefs": "Referencias fiscales",
+ "fiscalRefsHint": "Lo que un documento fiscal necesita por línea. Sugerido por tu jurisdicción; añade cualquier otra clave que necesites.",
+ "customRefKey": "otra clave (p. ej. hs_code)",
+ "addRef": "Añadir",
+ "fiscalRefsNone": "Nada sugerido para este tipo aquí. Añade cualquier clave que necesiten tus documentos fiscales."
+ },
+ "action": {
+ "archive": "Archivar",
+ "restore": "Restaurar"
+ }
}
},
"collections": {
@@ -1944,7 +2023,18 @@
"uscc": "USCC"
},
"otherCountries": "Otros países",
- "anyCountry": "Cualquier otro lugar"
+ "anyCountry": "Cualquier otro lugar",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / código de barras",
+ "service_code": "Código de servicio (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Código de servicio municipal",
+ "hs_code": "Código HS",
+ "sat_product_code": "Clave de producto/servicio SAT",
+ "sat_unit_code": "Clave de unidad SAT"
+ }
},
"common": {
"selectTimezone": "Seleccionar zona horaria",
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 144bf325..eb9f5023 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -329,7 +329,19 @@
"negative_discount": "Une remise ne peut pas être négative.",
"first_term": "Le prix en vigueur depuis le début ne peut être ni déplacé ni supprimé. Modifiez-le, ou ajoutez un nouveau prix à partir d'une date ultérieure.",
"not_receivable": "Seule une facture que vous avez émise peut appartenir à un accord.",
- "period_already_issued": "Cette période vient d'être émise. Actualisez pour la voir."
+ "period_already_issued": "Cette période vient d'être émise. Actualisez pour la voir.",
+ "product_not_found": "Produit introuvable.",
+ "price_not_found": "Prix introuvable sur ce produit.",
+ "product_in_use": "Des factures mentionnent ce produit. Archivez-le plutôt que de le supprimer.",
+ "price_in_use": "Des factures ont été émises à ce prix. Archivez-le plutôt que de le supprimer.",
+ "invalid_kind": "Type de produit inconnu.",
+ "invalid_billing": "Type de facturation inconnu.",
+ "interval_required": "Un prix récurrent a besoin d'une fréquence.",
+ "currency_required": "Un prix a besoin d'une devise.",
+ "unit_price_required": "Un prix a besoin d'un montant.",
+ "negative_price": "Un prix ne peut pas être négatif.",
+ "invalid_fiscal_refs": "Les références fiscales doivent être de courtes valeurs texte sous des clés simples (lettres, chiffres, tiret bas).",
+ "price_key_taken": "Un autre prix utilise déjà cette clé de recherche ou cet identifiant externe."
},
"comingNext": "Facturez vos clients et suivez ce qui a été payé et ce qui reste ouvert. C'est la prochaine chose en construction.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Aucune facture sous cet accord pour l'instant.",
"emptyNext": "Aucune facture pour l'instant. La première sera rédigée le {{date}}."
}
+ },
+ "products": {
+ "title": "Produits",
+ "new": "Nouveau produit",
+ "newDescription": "Quelque chose que vous vendez, avec un prix par devise. Le choisir remplit une ligne de facture ; la ligne reste à vous pour la modifier ensuite.",
+ "editTitle": "Modifier le produit",
+ "empty": "Aucun produit pour l'instant. Ajoutez ce que vous vendez, et chaque ligne de facture sera à un clic.",
+ "emptyArchived": "Rien d'archivé.",
+ "emptyPicker": "Aucun produit pour l'instant. Ajoutez-les dans Produits.",
+ "noneFound": "Aucun produit ne correspond.",
+ "searchPlaceholder": "Rechercher des produits",
+ "pick": "Choisir dans le catalogue",
+ "fromCatalog": "Depuis le catalogue",
+ "noPrice": "Aucun prix",
+ "noPriceIn": "aucun prix en {{currency}}",
+ "perUnit": "par {{unit}}",
+ "created": "Produit créé",
+ "saved": "Produit enregistré",
+ "archived": "Produit archivé. Les factures qui le mentionnent restent inchangées.",
+ "restored": "Produit restauré",
+ "deleted": "Produit supprimé",
+ "filter": {
+ "active": "Actifs",
+ "archived": "Archivés"
+ },
+ "kind": {
+ "service": "Service",
+ "product": "Produit"
+ },
+ "billing": {
+ "one_time": "Ponctuel",
+ "every": "Chaque {{interval}}"
+ },
+ "per": {
+ "weekly": "semaine",
+ "biweekly": "2 semaines",
+ "monthly": "mois",
+ "quarterly": "trimestre",
+ "semiannual": "6 mois",
+ "yearly": "an"
+ },
+ "column": {
+ "name": "Nom",
+ "kind": "Type",
+ "prices": "Prix",
+ "invoices": "Factures"
+ },
+ "field": {
+ "name": "Nom",
+ "namePlaceholder": "Heure de conseil, Forfait Pro, Création de logo",
+ "kind": "Type",
+ "description": "Description",
+ "prices": "Prix",
+ "pricesHint": "Un par devise. Un prix récurrent indique la fréquence ; c'est une indication pour les factures récurrentes, rien n'est facturé tout seul.",
+ "addPrice": "Ajouter un prix",
+ "noPrices": "Aucun prix. Le nom remplit quand même la ligne ; le montant est saisi à la main.",
+ "nickname": "Libellé (facultatif)",
+ "fiscalRefs": "Références fiscales",
+ "fiscalRefsHint": "Ce qu'un document fiscal exige par ligne. Suggéré par votre juridiction ; ajoutez toute autre clé dont vous avez besoin.",
+ "customRefKey": "autre clé (ex. hs_code)",
+ "addRef": "Ajouter",
+ "fiscalRefsNone": "Rien n'est suggéré pour ce type ici. Ajoutez toute clé dont vos documents fiscaux ont besoin."
+ },
+ "action": {
+ "archive": "Archiver",
+ "restore": "Restaurer"
+ }
}
},
"collections": {
@@ -1944,7 +2023,18 @@
"uscc": "USCC"
},
"otherCountries": "Autres pays",
- "anyCountry": "Ailleurs"
+ "anyCountry": "Ailleurs",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / code-barres",
+ "service_code": "Code de service (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Code de service municipal",
+ "hs_code": "Code SH (HS)",
+ "sat_product_code": "Code produit/service SAT",
+ "sat_unit_code": "Code d'unité SAT"
+ }
},
"common": {
"selectTimezone": "Choisir un fuseau horaire",
diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.json
index a1437204..e2f15bcd 100644
--- a/frontend/src/locales/hi.json
+++ b/frontend/src/locales/hi.json
@@ -329,7 +329,19 @@
"negative_discount": "छूट ऋणात्मक नहीं हो सकती।",
"first_term": "शुरुआत से लागू मूल्य को न तो खिसकाया जा सकता है और न ही हटाया जा सकता है। इसे बदलें, या किसी बाद की तारीख से नया मूल्य जोड़ें।",
"not_receivable": "समझौते में केवल आपके द्वारा जारी किया गया इनवॉइस ही शामिल हो सकता है।",
- "period_already_issued": "यह अवधि अभी-अभी जारी की गई है। देखने के लिए पेज रीफ़्रेश करें।"
+ "period_already_issued": "यह अवधि अभी-अभी जारी की गई है। देखने के लिए पेज रीफ़्रेश करें।",
+ "product_not_found": "उत्पाद नहीं मिला।",
+ "price_not_found": "इस उत्पाद में यह कीमत नहीं मिली।",
+ "product_in_use": "कुछ इनवॉइस में यह उत्पाद है। इसे हटाने के बजाय संग्रहीत करें।",
+ "price_in_use": "कुछ इनवॉइस इस कीमत पर बनाई गई थीं। इसे हटाने के बजाय संग्रहीत करें।",
+ "invalid_kind": "अज्ञात उत्पाद प्रकार।",
+ "invalid_billing": "अज्ञात बिलिंग प्रकार।",
+ "interval_required": "आवर्ती कीमत के लिए आवृत्ति ज़रूरी है।",
+ "currency_required": "कीमत के लिए मुद्रा ज़रूरी है।",
+ "unit_price_required": "कीमत के लिए राशि ज़रूरी है।",
+ "negative_price": "कीमत ऋणात्मक नहीं हो सकती।",
+ "invalid_fiscal_refs": "कर संदर्भ सरल कुंजियों (अक्षर, अंक, अंडरस्कोर) के अंतर्गत छोटे टेक्स्ट मान होने चाहिए।",
+ "price_key_taken": "कोई अन्य मूल्य पहले से इस खोज कुंजी या बाहरी आईडी का उपयोग कर रहा है।"
},
"comingNext": "अपने क्लाइंट को बिल भेजें और ट्रैक रखें कि क्या चुकाया गया और क्या अब भी बकाया है। यह अगली चीज़ है जो बनाई जा रही है।",
"document": {
@@ -564,6 +576,73 @@
"empty": "इस समझौते के तहत अभी कोई इनवॉइस नहीं है।",
"emptyNext": "अभी कोई इनवॉइस नहीं है। पहला {{date}} को बनेगा।"
}
+ },
+ "products": {
+ "title": "उत्पाद",
+ "new": "नया उत्पाद",
+ "newDescription": "कुछ ऐसा जो आप बेचते हैं, हर मुद्रा में एक कीमत के साथ। इसे चुनने से इनवॉइस की एक मद भर जाती है; मद को आप बाद में बदल सकते हैं।",
+ "editTitle": "उत्पाद संपादित करें",
+ "empty": "अभी कोई उत्पाद नहीं है। जो आप बेचते हैं उसे जोड़ें, और इनवॉइस की हर मद एक क्लिक दूर होगी।",
+ "emptyArchived": "कुछ भी संग्रहीत नहीं है।",
+ "emptyPicker": "अभी कोई उत्पाद नहीं है। उन्हें उत्पाद में जोड़ें।",
+ "noneFound": "कोई उत्पाद मेल नहीं खाता।",
+ "searchPlaceholder": "उत्पाद खोजें",
+ "pick": "कैटलॉग से चुनें",
+ "fromCatalog": "कैटलॉग से",
+ "noPrice": "कोई कीमत नहीं",
+ "noPriceIn": "{{currency}} में कोई कीमत नहीं",
+ "perUnit": "प्रति {{unit}}",
+ "created": "उत्पाद बनाया गया",
+ "saved": "उत्पाद सहेजा गया",
+ "archived": "उत्पाद संग्रहीत किया गया। जिन इनवॉइस में यह है, वे नहीं बदलतीं।",
+ "restored": "उत्पाद बहाल किया गया",
+ "deleted": "उत्पाद हटाया गया",
+ "filter": {
+ "active": "सक्रिय",
+ "archived": "संग्रहीत"
+ },
+ "kind": {
+ "service": "सेवा",
+ "product": "उत्पाद"
+ },
+ "billing": {
+ "one_time": "एक बार",
+ "every": "हर {{interval}}"
+ },
+ "per": {
+ "weekly": "सप्ताह",
+ "biweekly": "2 सप्ताह",
+ "monthly": "महीना",
+ "quarterly": "तिमाही",
+ "semiannual": "6 महीने",
+ "yearly": "साल"
+ },
+ "column": {
+ "name": "नाम",
+ "kind": "प्रकार",
+ "prices": "कीमतें",
+ "invoices": "इनवॉइस"
+ },
+ "field": {
+ "name": "नाम",
+ "namePlaceholder": "परामर्श का एक घंटा, प्रो प्लान, लोगो डिज़ाइन",
+ "kind": "प्रकार",
+ "description": "विवरण",
+ "prices": "कीमतें",
+ "pricesHint": "हर मुद्रा के लिए एक। आवर्ती कीमत बताती है कितनी बार; यह आवर्ती इनवॉइस के लिए एक संकेत है, अपने आप कुछ भी वसूला नहीं जाता।",
+ "addPrice": "कीमत जोड़ें",
+ "noPrices": "कोई कीमत नहीं। नाम फिर भी मद भर देता है; राशि हाथ से लिखी जाती है।",
+ "nickname": "लेबल (वैकल्पिक)",
+ "fiscalRefs": "कर संदर्भ",
+ "fiscalRefsHint": "कर दस्तावेज़ को हर पंक्ति के लिए क्या चाहिए। आपके क्षेत्राधिकार के अनुसार सुझाया गया; ज़रूरत की कोई भी अन्य कुंजी जोड़ें।",
+ "customRefKey": "अन्य कुंजी (जैसे hs_code)",
+ "addRef": "जोड़ें",
+ "fiscalRefsNone": "इस प्रकार के लिए यहाँ कुछ सुझाया नहीं गया है। अपने कर दस्तावेज़ों के लिए ज़रूरी कोई भी कुंजी जोड़ें।"
+ },
+ "action": {
+ "archive": "संग्रहीत करें",
+ "restore": "बहाल करें"
+ }
}
},
"collections": {
@@ -1943,7 +2022,18 @@
"uscc": "USCC"
},
"otherCountries": "अन्य देश",
- "anyCountry": "और कहीं भी"
+ "anyCountry": "और कहीं भी",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / बारकोड",
+ "service_code": "सेवा कोड (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "नगरपालिका सेवा कोड",
+ "hs_code": "HS कोड",
+ "sat_product_code": "SAT उत्पाद/सेवा कोड",
+ "sat_unit_code": "SAT इकाई कोड"
+ }
},
"common": {
"selectTimezone": "समय क्षेत्र चुनें",
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 1c6783b2..90cab7c3 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -329,7 +329,19 @@
"negative_discount": "Uno sconto non può essere negativo.",
"first_term": "Il prezzo in vigore dall'inizio non può essere spostato né rimosso. Modificalo o aggiungi un nuovo prezzo da una data successiva.",
"not_receivable": "Solo una fattura emessa da te può appartenere a un accordo.",
- "period_already_issued": "Questo periodo è appena stato emesso. Aggiorna per vederlo."
+ "period_already_issued": "Questo periodo è appena stato emesso. Aggiorna per vederlo.",
+ "product_not_found": "Prodotto non trovato.",
+ "price_not_found": "Prezzo non trovato su questo prodotto.",
+ "product_in_use": "Alcune fatture citano questo prodotto. Archivialo invece di eliminarlo.",
+ "price_in_use": "Alcune fatture sono state emesse a questo prezzo. Archivialo invece di eliminarlo.",
+ "invalid_kind": "Tipo di prodotto sconosciuto.",
+ "invalid_billing": "Tipo di fatturazione sconosciuto.",
+ "interval_required": "Un prezzo ricorrente ha bisogno di una frequenza.",
+ "currency_required": "Un prezzo ha bisogno di una valuta.",
+ "unit_price_required": "Un prezzo ha bisogno di un importo.",
+ "negative_price": "Un prezzo non può essere negativo.",
+ "invalid_fiscal_refs": "I riferimenti fiscali devono essere brevi valori di testo sotto chiavi semplici (lettere, cifre, trattino basso).",
+ "price_key_taken": "Un altro prezzo usa già questa chiave di ricerca o id esterno."
},
"comingNext": "Fattura i tuoi clienti e tieni traccia di cosa è stato pagato e cosa è ancora aperto. È la prossima cosa in costruzione.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Nessuna fattura in questo accordo ancora.",
"emptyNext": "Nessuna fattura ancora. La prima verrà scritta il {{date}}."
}
+ },
+ "products": {
+ "title": "Prodotti",
+ "new": "Nuovo prodotto",
+ "newDescription": "Qualcosa che vendi, con un prezzo per valuta. Sceglierlo compila una riga della fattura; la riga resta tua da modificare dopo.",
+ "editTitle": "Modifica prodotto",
+ "empty": "Ancora nessun prodotto. Aggiungi ciò che vendi e ogni riga di fattura sarà a un clic di distanza.",
+ "emptyArchived": "Niente in archivio.",
+ "emptyPicker": "Ancora nessun prodotto. Aggiungili in Prodotti.",
+ "noneFound": "Nessun prodotto corrisponde.",
+ "searchPlaceholder": "Cerca prodotti",
+ "pick": "Scegli dal catalogo",
+ "fromCatalog": "Dal catalogo",
+ "noPrice": "Nessun prezzo",
+ "noPriceIn": "nessun prezzo in {{currency}}",
+ "perUnit": "per {{unit}}",
+ "created": "Prodotto creato",
+ "saved": "Prodotto salvato",
+ "archived": "Prodotto archiviato. Le fatture che lo citano non cambiano.",
+ "restored": "Prodotto ripristinato",
+ "deleted": "Prodotto eliminato",
+ "filter": {
+ "active": "Attivi",
+ "archived": "Archiviati"
+ },
+ "kind": {
+ "service": "Servizio",
+ "product": "Prodotto"
+ },
+ "billing": {
+ "one_time": "Una tantum",
+ "every": "Ogni {{interval}}"
+ },
+ "per": {
+ "weekly": "settimana",
+ "biweekly": "2 settimane",
+ "monthly": "mese",
+ "quarterly": "trimestre",
+ "semiannual": "6 mesi",
+ "yearly": "anno"
+ },
+ "column": {
+ "name": "Nome",
+ "kind": "Tipo",
+ "prices": "Prezzi",
+ "invoices": "Fatture"
+ },
+ "field": {
+ "name": "Nome",
+ "namePlaceholder": "Ora di consulenza, Piano Pro, Design del logo",
+ "kind": "Tipo",
+ "description": "Descrizione",
+ "prices": "Prezzi",
+ "pricesHint": "Uno per valuta. Un prezzo ricorrente indica la frequenza; è un suggerimento per le fatture ricorrenti, nulla viene addebitato da solo.",
+ "addPrice": "Aggiungi prezzo",
+ "noPrices": "Nessun prezzo. Il nome compila comunque la riga; l'importo va digitato.",
+ "nickname": "Etichetta (facoltativa)",
+ "fiscalRefs": "Riferimenti fiscali",
+ "fiscalRefsHint": "Ciò che un documento fiscale richiede per riga. Suggerito dalla tua giurisdizione; aggiungi qualsiasi altra chiave ti serva.",
+ "customRefKey": "altra chiave (es. hs_code)",
+ "addRef": "Aggiungi",
+ "fiscalRefsNone": "Nulla di suggerito per questo tipo qui. Aggiungi qualsiasi chiave di cui i tuoi documenti fiscali hanno bisogno."
+ },
+ "action": {
+ "archive": "Archivia",
+ "restore": "Ripristina"
+ }
}
},
"collections": {
@@ -1944,7 +2023,18 @@
"uscc": "USCC"
},
"otherCountries": "Altri paesi",
- "anyCountry": "Qualsiasi altro luogo"
+ "anyCountry": "Qualsiasi altro luogo",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / codice a barre",
+ "service_code": "Codice servizio (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Codice servizio comunale",
+ "hs_code": "Codice HS",
+ "sat_product_code": "Codice prodotto/servizio SAT",
+ "sat_unit_code": "Codice unità SAT"
+ }
},
"common": {
"selectTimezone": "Seleziona fuso orario",
diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json
index 8a86a48f..95019dee 100644
--- a/frontend/src/locales/ja.json
+++ b/frontend/src/locales/ja.json
@@ -329,7 +329,19 @@
"negative_discount": "割引を負の値にすることはできません。",
"first_term": "開始時から有効な料金は移動も削除もできません。変更するか、より後の日付から新しい料金を追加してください。",
"not_receivable": "契約に含められるのは、あなたが発行した請求書のみです。",
- "period_already_issued": "この期間はたった今発行されました。更新して確認してください。"
+ "period_already_issued": "この期間はたった今発行されました。更新して確認してください。",
+ "product_not_found": "商品が見つかりません。",
+ "price_not_found": "この商品にその価格はありません。",
+ "product_in_use": "この商品を含む請求書があります。削除する代わりにアーカイブしてください。",
+ "price_in_use": "この価格で発行された請求書があります。削除する代わりにアーカイブしてください。",
+ "invalid_kind": "不明な商品の種類です。",
+ "invalid_billing": "不明な請求の種類です。",
+ "interval_required": "定期価格には頻度が必要です。",
+ "currency_required": "価格には通貨が必要です。",
+ "unit_price_required": "価格には金額が必要です。",
+ "negative_price": "価格をマイナスにはできません。",
+ "invalid_fiscal_refs": "税務参照コードは、シンプルなキー(英字、数字、アンダースコア)の下にある短いテキスト値である必要があります。",
+ "price_key_taken": "別の価格がすでにこの検索キーまたは外部IDを使用しています。"
},
"comingNext": "クライアントに請求し、支払い済みのものと未払いのものを管理します。現在開発中の次の機能です。",
"document": {
@@ -564,6 +576,73 @@
"empty": "この契約の請求書はまだありません。",
"emptyNext": "請求書はまだありません。最初の請求書は{{date}}に作成されます。"
}
+ },
+ "products": {
+ "title": "商品",
+ "new": "新しい商品",
+ "newDescription": "販売しているもので、通貨ごとに価格を持ちます。選ぶと請求書の明細行が埋まり、その後は自由に変更できます。",
+ "editTitle": "商品を編集",
+ "empty": "まだ商品がありません。販売しているものを登録すると、請求書の明細行はワンクリックで入力できます。",
+ "emptyArchived": "アーカイブはありません。",
+ "emptyPicker": "まだ商品がありません。「商品」で登録してください。",
+ "noneFound": "一致する商品がありません。",
+ "searchPlaceholder": "商品を検索",
+ "pick": "カタログから選ぶ",
+ "fromCatalog": "カタログから",
+ "noPrice": "価格なし",
+ "noPriceIn": "{{currency}}の価格なし",
+ "perUnit": "{{unit}}あたり",
+ "created": "商品を作成しました",
+ "saved": "商品を保存しました",
+ "archived": "商品をアーカイブしました。この商品を含む請求書は変わりません。",
+ "restored": "商品を復元しました",
+ "deleted": "商品を削除しました",
+ "filter": {
+ "active": "有効",
+ "archived": "アーカイブ済み"
+ },
+ "kind": {
+ "service": "サービス",
+ "product": "商品"
+ },
+ "billing": {
+ "one_time": "単発",
+ "every": "{{interval}}ごと"
+ },
+ "per": {
+ "weekly": "週",
+ "biweekly": "2週間",
+ "monthly": "月",
+ "quarterly": "四半期",
+ "semiannual": "6か月",
+ "yearly": "年"
+ },
+ "column": {
+ "name": "名前",
+ "kind": "種類",
+ "prices": "価格",
+ "invoices": "請求書"
+ },
+ "field": {
+ "name": "名前",
+ "namePlaceholder": "コンサルティング1時間、Proプラン、ロゴデザイン",
+ "kind": "種類",
+ "description": "説明",
+ "prices": "価格",
+ "pricesHint": "通貨ごとに1つ。定期価格は頻度を示します。定期請求書のためのヒントであり、それだけで請求されることはありません。",
+ "addPrice": "価格を追加",
+ "noPrices": "価格がありません。名前は明細行に入りますが、金額は手入力になります。",
+ "nickname": "ラベル(任意)",
+ "fiscalRefs": "税務参照コード",
+ "fiscalRefsHint": "税務書類が明細ごとに必要とする項目です。お住まいの管轄区域に基づいて提案されます。必要な他のキーも追加できます。",
+ "customRefKey": "その他のキー(例: hs_code)",
+ "addRef": "追加",
+ "fiscalRefsNone": "この種類にはここでの提案はありません。税務書類に必要なキーを追加してください。"
+ },
+ "action": {
+ "archive": "アーカイブ",
+ "restore": "復元"
+ }
}
},
"collections": {
@@ -1943,7 +2022,18 @@
"uscc": "USCC"
},
"otherCountries": "その他の国",
- "anyCountry": "その他すべての国"
+ "anyCountry": "その他すべての国",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / バーコード",
+ "service_code": "サービスコード(LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "市町村サービスコード",
+ "hs_code": "HSコード",
+ "sat_product_code": "SAT製品/サービスコード",
+ "sat_unit_code": "SAT単位コード"
+ }
},
"common": {
"selectTimezone": "タイムゾーンを選択",
diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json
index 9d27aeb0..92d198bd 100644
--- a/frontend/src/locales/nl.json
+++ b/frontend/src/locales/nl.json
@@ -329,7 +329,19 @@
"negative_discount": "Een korting kan niet negatief zijn.",
"first_term": "De prijs die vanaf het begin geldt, kan niet worden verplaatst of verwijderd. Wijzig hem, of voeg een nieuwe prijs toe vanaf een latere datum.",
"not_receivable": "Alleen een factuur die u hebt uitgegeven kan bij een afspraak horen.",
- "period_already_issued": "Deze periode is zojuist uitgegeven. Vernieuw om hem te zien."
+ "period_already_issued": "Deze periode is zojuist uitgegeven. Vernieuw om hem te zien.",
+ "product_not_found": "Product niet gevonden.",
+ "price_not_found": "Prijs niet gevonden bij dit product.",
+ "product_in_use": "Er zijn facturen die dit product noemen. Archiveer het in plaats van het te verwijderen.",
+ "price_in_use": "Er zijn facturen gemaakt met deze prijs. Archiveer hem in plaats van hem te verwijderen.",
+ "invalid_kind": "Onbekend productsoort.",
+ "invalid_billing": "Onbekend factureringstype.",
+ "interval_required": "Een terugkerende prijs heeft een frequentie nodig.",
+ "currency_required": "Een prijs heeft een valuta nodig.",
+ "unit_price_required": "Een prijs heeft een bedrag nodig.",
+ "negative_price": "Een prijs kan niet negatief zijn.",
+ "invalid_fiscal_refs": "Fiscale referenties moeten korte tekstwaarden zijn onder eenvoudige sleutels (letters, cijfers, underscore).",
+ "price_key_taken": "Een andere prijs gebruikt deze zoeksleutel of externe id al."
},
"comingNext": "Factureer uw klanten en houd bij wat er is betaald en wat er nog open staat. Dit is het volgende dat gebouwd wordt.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Nog geen factuur onder deze afspraak.",
"emptyNext": "Nog geen factuur. De eerste wordt opgesteld op {{date}}."
}
+ },
+ "products": {
+ "title": "Producten",
+ "new": "Nieuw product",
+ "newDescription": "Iets wat je verkoopt, met een prijs per valuta. Kies je het, dan vult het een factuurregel in; de regel blijft daarna van jou om aan te passen.",
+ "editTitle": "Product bewerken",
+ "empty": "Nog geen producten. Voeg toe wat je verkoopt, en elke factuurregel is één klik verwijderd.",
+ "emptyArchived": "Niets gearchiveerd.",
+ "emptyPicker": "Nog geen producten. Voeg ze toe onder Producten.",
+ "noneFound": "Geen product komt overeen.",
+ "searchPlaceholder": "Producten zoeken",
+ "pick": "Kies uit de catalogus",
+ "fromCatalog": "Uit de catalogus",
+ "noPrice": "Geen prijs",
+ "noPriceIn": "geen prijs in {{currency}}",
+ "perUnit": "per {{unit}}",
+ "created": "Product aangemaakt",
+ "saved": "Product opgeslagen",
+ "archived": "Product gearchiveerd. Facturen die het noemen blijven ongewijzigd.",
+ "restored": "Product hersteld",
+ "deleted": "Product verwijderd",
+ "filter": {
+ "active": "Actief",
+ "archived": "Gearchiveerd"
+ },
+ "kind": {
+ "service": "Dienst",
+ "product": "Product"
+ },
+ "billing": {
+ "one_time": "Eenmalig",
+ "every": "Elke {{interval}}"
+ },
+ "per": {
+ "weekly": "week",
+ "biweekly": "2 weken",
+ "monthly": "maand",
+ "quarterly": "kwartaal",
+ "semiannual": "6 maanden",
+ "yearly": "jaar"
+ },
+ "column": {
+ "name": "Naam",
+ "kind": "Soort",
+ "prices": "Prijzen",
+ "invoices": "Facturen"
+ },
+ "field": {
+ "name": "Naam",
+ "namePlaceholder": "Adviesuur, Pro-abonnement, Logo-ontwerp",
+ "kind": "Soort",
+ "description": "Omschrijving",
+ "prices": "Prijzen",
+ "pricesHint": "Eén per valuta. Een terugkerende prijs geeft aan hoe vaak; het is een hint voor terugkerende facturen, er wordt uit zichzelf niets in rekening gebracht.",
+ "addPrice": "Prijs toevoegen",
+ "noPrices": "Geen prijzen. De naam vult de regel toch in; het bedrag typ je zelf.",
+ "nickname": "Label (optioneel)",
+ "fiscalRefs": "Fiscale referenties",
+ "fiscalRefsHint": "Wat een fiscaal document per regel nodig heeft. Voorgesteld op basis van uw jurisdictie; voeg elke andere sleutel toe die u nodig heeft.",
+ "customRefKey": "andere sleutel (bijv. hs_code)",
+ "addRef": "Toevoegen",
+ "fiscalRefsNone": "Niets voorgesteld voor dit type hier. Voeg elke sleutel toe die uw fiscale documenten nodig hebben."
+ },
+ "action": {
+ "archive": "Archiveren",
+ "restore": "Herstellen"
+ }
}
},
"collections": {
@@ -1945,7 +2024,18 @@
"uscc": "USCC"
},
"otherCountries": "Andere landen",
- "anyCountry": "Ergens anders"
+ "anyCountry": "Ergens anders",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / barcode",
+ "service_code": "Dienstcode (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Gemeentelijke dienstcode",
+ "hs_code": "HS-code",
+ "sat_product_code": "SAT product-/dienstcode",
+ "sat_unit_code": "SAT eenheidscode"
+ }
},
"common": {
"selectTimezone": "Tijdzone kiezen",
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 95e05f2c..39b4304d 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -329,7 +329,19 @@
"negative_discount": "Rabat nie może być ujemny.",
"first_term": "Ceny obowiązującej od początku nie można przesunąć ani usunąć. Zmień ją lub dodaj nową cenę od późniejszej daty.",
"not_receivable": "Do umowy może należeć tylko faktura wystawiona przez Ciebie.",
- "period_already_issued": "Ten okres został właśnie wystawiony. Odśwież, aby go zobaczyć."
+ "period_already_issued": "Ten okres został właśnie wystawiony. Odśwież, aby go zobaczyć.",
+ "product_not_found": "Nie znaleziono produktu.",
+ "price_not_found": "Nie znaleziono ceny w tym produkcie.",
+ "product_in_use": "Faktury wymieniają ten produkt. Zarchiwizuj go zamiast usuwać.",
+ "price_in_use": "Faktury zostały wystawione po tej cenie. Zarchiwizuj ją zamiast usuwać.",
+ "invalid_kind": "Nieznany rodzaj produktu.",
+ "invalid_billing": "Nieznany rodzaj rozliczenia.",
+ "interval_required": "Cena cykliczna wymaga częstotliwości.",
+ "currency_required": "Cena wymaga waluty.",
+ "unit_price_required": "Cena wymaga kwoty.",
+ "negative_price": "Cena nie może być ujemna.",
+ "invalid_fiscal_refs": "Odniesienia podatkowe muszą być krótkimi wartościami tekstowymi pod prostymi kluczami (litery, cyfry, podkreślenie).",
+ "price_key_taken": "Inna cena już używa tego klucza wyszukiwania lub zewnętrznego identyfikatora."
},
"comingNext": "Wystawiaj faktury klientom i śledź, co zostało zapłacone, a co wciąż jest otwarte. To następna rzecz w budowie.",
"document": {
@@ -568,6 +580,73 @@
"empty": "W tej umowie nie ma jeszcze faktury.",
"emptyNext": "Nie ma jeszcze faktury. Pierwsza zostanie wystawiona {{date}}."
}
+ },
+ "products": {
+ "title": "Produkty",
+ "new": "Nowy produkt",
+ "newDescription": "Coś, co sprzedajesz, z ceną dla każdej waluty. Wybranie go wypełnia pozycję faktury; pozycję można potem dowolnie zmienić.",
+ "editTitle": "Edytuj produkt",
+ "empty": "Nie ma jeszcze produktów. Dodaj to, co sprzedajesz, a każda pozycja faktury będzie o jedno kliknięcie.",
+ "emptyArchived": "Nic nie zarchiwizowano.",
+ "emptyPicker": "Nie ma jeszcze produktów. Dodaj je w sekcji Produkty.",
+ "noneFound": "Żaden produkt nie pasuje.",
+ "searchPlaceholder": "Szukaj produktów",
+ "pick": "Wybierz z katalogu",
+ "fromCatalog": "Z katalogu",
+ "noPrice": "Brak ceny",
+ "noPriceIn": "brak ceny w {{currency}}",
+ "perUnit": "za {{unit}}",
+ "created": "Produkt utworzony",
+ "saved": "Produkt zapisany",
+ "archived": "Produkt zarchiwizowany. Faktury, które go wymieniają, pozostają bez zmian.",
+ "restored": "Produkt przywrócony",
+ "deleted": "Produkt usunięty",
+ "filter": {
+ "active": "Aktywne",
+ "archived": "Zarchiwizowane"
+ },
+ "kind": {
+ "service": "Usługa",
+ "product": "Produkt"
+ },
+ "billing": {
+ "one_time": "Jednorazowo",
+ "every": "Co {{interval}}"
+ },
+ "per": {
+ "weekly": "tydzień",
+ "biweekly": "2 tygodnie",
+ "monthly": "miesiąc",
+ "quarterly": "kwartał",
+ "semiannual": "6 miesięcy",
+ "yearly": "rok"
+ },
+ "column": {
+ "name": "Nazwa",
+ "kind": "Rodzaj",
+ "prices": "Ceny",
+ "invoices": "Faktury"
+ },
+ "field": {
+ "name": "Nazwa",
+ "namePlaceholder": "Godzina konsultacji, Plan Pro, Projekt logo",
+ "kind": "Rodzaj",
+ "description": "Opis",
+ "prices": "Ceny",
+ "pricesHint": "Jedna na walutę. Cena cykliczna określa, jak często; to podpowiedź dla faktur cyklicznych, nic nie jest naliczane samo z siebie.",
+ "addPrice": "Dodaj cenę",
+ "noPrices": "Brak cen. Nazwa i tak wypełni pozycję; kwotę wpisuje się ręcznie.",
+ "nickname": "Etykieta (opcjonalnie)",
+ "fiscalRefs": "Odniesienia podatkowe",
+ "fiscalRefsHint": "Czego dokument podatkowy wymaga w każdej pozycji. Sugerowane przez Twoją jurysdykcję; dodaj dowolny inny potrzebny klucz.",
+ "customRefKey": "inny klucz (np. hs_code)",
+ "addRef": "Dodaj",
+ "fiscalRefsNone": "Brak sugestii dla tego rodzaju. Dodaj dowolny klucz, którego potrzebują Twoje dokumenty podatkowe."
+ },
+ "action": {
+ "archive": "Archiwizuj",
+ "restore": "Przywróć"
+ }
}
},
"collections": {
@@ -2034,7 +2113,18 @@
"uscc": "USCC"
},
"otherCountries": "Inne kraje",
- "anyCountry": "Gdziekolwiek indziej"
+ "anyCountry": "Gdziekolwiek indziej",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / kod kreskowy",
+ "service_code": "Kod usługi (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Gminny kod usługi",
+ "hs_code": "Kod HS",
+ "sat_product_code": "Kod produktu/usługi SAT",
+ "sat_unit_code": "Kod jednostki SAT"
+ }
},
"common": {
"selectTimezone": "Wybierz strefę czasową",
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 6acb691e..c67e81fd 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -329,7 +329,19 @@
"negative_discount": "Um desconto não pode ser negativo.",
"first_term": "O preço vigente desde o início não pode ser movido nem removido. Altere-o ou adicione um novo preço a partir de uma data posterior.",
"not_receivable": "Só uma cobrança emitida por você pode pertencer a um acordo.",
- "period_already_issued": "Este período acabou de ser emitido. Atualize a página para vê-lo."
+ "period_already_issued": "Este período acabou de ser emitido. Atualize a página para vê-lo.",
+ "product_not_found": "Produto não encontrado.",
+ "price_not_found": "Preço não encontrado neste produto.",
+ "product_in_use": "Há cobranças que citam este produto. Arquive-o em vez de excluir.",
+ "price_in_use": "Há cobranças emitidas com este preço. Arquive-o em vez de excluir.",
+ "invalid_kind": "Tipo de produto desconhecido.",
+ "invalid_billing": "Tipo de cobrança desconhecido.",
+ "interval_required": "Um preço recorrente precisa de uma frequência.",
+ "currency_required": "Um preço precisa de uma moeda.",
+ "unit_price_required": "Um preço precisa de um valor.",
+ "negative_price": "Um preço não pode ser negativo.",
+ "invalid_fiscal_refs": "Referências fiscais devem ser textos curtos sob chaves simples (letras, dígitos, sublinhado).",
+ "price_key_taken": "Outro preço já usa essa chave de busca ou id externo."
},
"comingNext": "Cobre seus clientes e acompanhe o que já foi pago e o que continua em aberto. É a próxima coisa sendo construída.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Nenhuma cobrança neste acordo ainda.",
"emptyNext": "Nenhuma cobrança ainda. A primeira será gerada em {{date}}."
}
+ },
+ "products": {
+ "title": "Produtos",
+ "new": "Novo produto",
+ "newDescription": "Algo que você vende, com um preço por moeda. Escolher preenche a linha da cobrança; a linha continua sua para alterar depois.",
+ "editTitle": "Editar produto",
+ "empty": "Nenhum produto ainda. Cadastre o que você vende, e cada linha de cobrança fica a um clique dele.",
+ "emptyArchived": "Nada arquivado.",
+ "emptyPicker": "Nenhum produto ainda. Cadastre em Produtos.",
+ "noneFound": "Nenhum produto corresponde.",
+ "searchPlaceholder": "Buscar produtos",
+ "pick": "Escolher do catálogo",
+ "fromCatalog": "Do catálogo",
+ "noPrice": "Sem preço",
+ "noPriceIn": "sem preço em {{currency}}",
+ "perUnit": "por {{unit}}",
+ "created": "Produto criado",
+ "saved": "Produto salvo",
+ "archived": "Produto arquivado. As cobranças que o citam não mudam.",
+ "restored": "Produto restaurado",
+ "deleted": "Produto excluído",
+ "filter": {
+ "active": "Ativos",
+ "archived": "Arquivados"
+ },
+ "kind": {
+ "service": "Serviço",
+ "product": "Produto"
+ },
+ "billing": {
+ "one_time": "Avulso",
+ "every": "A cada {{interval}}"
+ },
+ "per": {
+ "weekly": "semana",
+ "biweekly": "2 semanas",
+ "monthly": "mês",
+ "quarterly": "trimestre",
+ "semiannual": "6 meses",
+ "yearly": "ano"
+ },
+ "column": {
+ "name": "Nome",
+ "kind": "Tipo",
+ "prices": "Preços",
+ "invoices": "Cobranças"
+ },
+ "field": {
+ "name": "Nome",
+ "namePlaceholder": "Hora de consultoria, Plano Pro, Criação de logo",
+ "kind": "Tipo",
+ "description": "Descrição",
+ "prices": "Preços",
+ "pricesHint": "Um por moeda. Um preço recorrente diz a frequência; é uma sugestão para cobranças recorrentes, nada é cobrado sozinho.",
+ "addPrice": "Adicionar preço",
+ "noPrices": "Sem preços. O nome ainda preenche a linha; o valor é digitado.",
+ "nickname": "Rótulo (opcional)",
+ "fiscalRefs": "Referências fiscais",
+ "fiscalRefsHint": "O que um documento fiscal precisa por item. Sugerido pela sua jurisdição; adicione qualquer outra chave que precisar.",
+ "customRefKey": "outra chave (ex.: hs_code)",
+ "addRef": "Adicionar",
+ "fiscalRefsNone": "Nada sugerido para este tipo aqui. Adicione qualquer chave que seus documentos fiscais precisem."
+ },
+ "action": {
+ "archive": "Arquivar",
+ "restore": "Restaurar"
+ }
}
},
"collections": {
@@ -1944,7 +2023,18 @@
"uscc": "USCC"
},
"otherCountries": "Outros países",
- "anyCountry": "Qualquer outro lugar"
+ "anyCountry": "Qualquer outro lugar",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / código de barras",
+ "service_code": "Código de serviço (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Código de serviço municipal",
+ "hs_code": "Código HS",
+ "sat_product_code": "Código de produto/serviço SAT",
+ "sat_unit_code": "Código de unidade SAT"
+ }
},
"common": {
"selectTimezone": "Selecionar fuso horário",
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 1bff7e42..8fc7eb0c 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -329,7 +329,19 @@
"negative_discount": "Um desconto não pode ser negativo.",
"first_term": "O preço em vigor desde o início não pode ser movido nem removido. Altere-o ou adicione um novo preço a partir de uma data posterior.",
"not_receivable": "Só uma cobrança emitida por si pode pertencer a um acordo.",
- "period_already_issued": "Este período acabou de ser emitido. Atualize a página para o ver."
+ "period_already_issued": "Este período acabou de ser emitido. Atualize a página para o ver.",
+ "product_not_found": "Produto não encontrado.",
+ "price_not_found": "Preço não encontrado neste produto.",
+ "product_in_use": "Há cobranças que mencionam este produto. Arquive-o em vez de o excluir.",
+ "price_in_use": "Há cobranças emitidas com este preço. Arquive-o em vez de o excluir.",
+ "invalid_kind": "Tipo de produto desconhecido.",
+ "invalid_billing": "Tipo de cobrança desconhecido.",
+ "interval_required": "Um preço recorrente precisa de uma frequência.",
+ "currency_required": "Um preço precisa de uma moeda.",
+ "unit_price_required": "Um preço precisa de um valor.",
+ "negative_price": "Um preço não pode ser negativo.",
+ "invalid_fiscal_refs": "As referências fiscais devem ser textos curtos sob chaves simples (letras, dígitos, sublinhado).",
+ "price_key_taken": "Outro preço já usa esta chave de pesquisa ou id externo."
},
"comingNext": "Cobra os teus clientes e acompanha o que já foi pago e o que continua em aberto. É a próxima coisa a ser construída.",
"document": {
@@ -564,6 +576,73 @@
"empty": "Ainda não há cobranças neste acordo.",
"emptyNext": "Ainda não há cobranças. A primeira será gerada a {{date}}."
}
+ },
+ "products": {
+ "title": "Produtos",
+ "new": "Novo produto",
+ "newDescription": "Algo que você vende, com um preço por moeda. Escolhê-lo preenche uma linha da cobrança; a linha continua sua para alterar depois.",
+ "editTitle": "Editar produto",
+ "empty": "Ainda não há produtos. Adicione o que você vende, e cada linha de cobrança fica a um clique.",
+ "emptyArchived": "Nada arquivado.",
+ "emptyPicker": "Ainda não há produtos. Adicione-os em Produtos.",
+ "noneFound": "Nenhum produto corresponde.",
+ "searchPlaceholder": "Pesquisar produtos",
+ "pick": "Escolher do catálogo",
+ "fromCatalog": "Do catálogo",
+ "noPrice": "Sem preço",
+ "noPriceIn": "sem preço em {{currency}}",
+ "perUnit": "por {{unit}}",
+ "created": "Produto criado",
+ "saved": "Produto guardado",
+ "archived": "Produto arquivado. As cobranças que o mencionam não mudam.",
+ "restored": "Produto restaurado",
+ "deleted": "Produto excluído",
+ "filter": {
+ "active": "Ativos",
+ "archived": "Arquivados"
+ },
+ "kind": {
+ "service": "Serviço",
+ "product": "Produto"
+ },
+ "billing": {
+ "one_time": "Pontual",
+ "every": "A cada {{interval}}"
+ },
+ "per": {
+ "weekly": "semana",
+ "biweekly": "2 semanas",
+ "monthly": "mês",
+ "quarterly": "trimestre",
+ "semiannual": "6 meses",
+ "yearly": "ano"
+ },
+ "column": {
+ "name": "Nome",
+ "kind": "Tipo",
+ "prices": "Preços",
+ "invoices": "Cobranças"
+ },
+ "field": {
+ "name": "Nome",
+ "namePlaceholder": "Hora de consultoria, Plano Pro, Criação de logótipo",
+ "kind": "Tipo",
+ "description": "Descrição",
+ "prices": "Preços",
+ "pricesHint": "Um por moeda. Um preço recorrente indica a frequência; é uma sugestão para cobranças recorrentes, nada é cobrado por si só.",
+ "addPrice": "Adicionar preço",
+ "noPrices": "Sem preços. O nome preenche a linha na mesma; o valor é escrito à mão.",
+ "nickname": "Rótulo (opcional)",
+ "fiscalRefs": "Referências fiscais",
+ "fiscalRefsHint": "O que um documento fiscal precisa por linha. Sugerido pela sua jurisdição; adicione qualquer outra chave de que precise.",
+ "customRefKey": "outra chave (ex.: hs_code)",
+ "addRef": "Adicionar",
+ "fiscalRefsNone": "Nada sugerido para este tipo aqui. Adicione qualquer chave de que os seus documentos fiscais precisem."
+ },
+ "action": {
+ "archive": "Arquivar",
+ "restore": "Restaurar"
+ }
}
},
"collections": {
@@ -1944,7 +2023,18 @@
"uscc": "USCC"
},
"otherCountries": "Outros países",
- "anyCountry": "Qualquer outro lugar"
+ "anyCountry": "Qualquer outro lugar",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / código de barras",
+ "service_code": "Código de serviço (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Código de serviço municipal",
+ "hs_code": "Código HS",
+ "sat_product_code": "Código de produto/serviço SAT",
+ "sat_unit_code": "Código de unidade SAT"
+ }
},
"common": {
"selectTimezone": "Selecionar fuso horário",
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 6894b9ff..f77082e2 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -329,7 +329,19 @@
"negative_discount": "Скидка не может быть отрицательной.",
"first_term": "Цену, действующую с начала, нельзя перенести или удалить. Измените её или добавьте новую цену с более поздней даты.",
"not_receivable": "К договорённости может относиться только выставленный вами счёт.",
- "period_already_issued": "Этот период только что выставлен. Обновите страницу, чтобы его увидеть."
+ "period_already_issued": "Этот период только что выставлен. Обновите страницу, чтобы его увидеть.",
+ "product_not_found": "Товар не найден.",
+ "price_not_found": "У этого товара нет такой цены.",
+ "product_in_use": "Этот товар указан в счетах. Отправьте его в архив вместо удаления.",
+ "price_in_use": "По этой цене уже выставлены счета. Отправьте её в архив вместо удаления.",
+ "invalid_kind": "Неизвестный вид товара.",
+ "invalid_billing": "Неизвестный вид оплаты.",
+ "interval_required": "Регулярной цене нужна периодичность.",
+ "currency_required": "Цене нужна валюта.",
+ "unit_price_required": "Цене нужна сумма.",
+ "negative_price": "Цена не может быть отрицательной.",
+ "invalid_fiscal_refs": "Налоговые ссылки должны быть короткими текстовыми значениями под простыми ключами (буквы, цифры, подчёркивание).",
+ "price_key_taken": "Другая цена уже использует этот ключ поиска или внешний идентификатор."
},
"comingNext": "Выставляйте счета клиентам и следите за тем, что оплачено, а что остаётся открытым. Это следующее, что будет сделано.",
"document": {
@@ -568,6 +580,73 @@
"empty": "По этой договорённости пока нет счетов.",
"emptyNext": "Счетов пока нет. Первый будет выставлен {{date}}."
}
+ },
+ "products": {
+ "title": "Товары",
+ "new": "Новый товар",
+ "newDescription": "То, что вы продаёте, с ценой в каждой валюте. Выбор заполняет строку счёта; после этого строку можно свободно менять.",
+ "editTitle": "Изменить товар",
+ "empty": "Товаров пока нет. Добавьте то, что продаёте, и каждая строка счёта будет в одном клике.",
+ "emptyArchived": "В архиве ничего нет.",
+ "emptyPicker": "Товаров пока нет. Добавьте их в разделе «Товары».",
+ "noneFound": "Ни один товар не подходит.",
+ "searchPlaceholder": "Поиск товаров",
+ "pick": "Выбрать из каталога",
+ "fromCatalog": "Из каталога",
+ "noPrice": "Без цены",
+ "noPriceIn": "нет цены в {{currency}}",
+ "perUnit": "за {{unit}}",
+ "created": "Товар создан",
+ "saved": "Товар сохранён",
+ "archived": "Товар в архиве. Счета, в которых он указан, не меняются.",
+ "restored": "Товар восстановлен",
+ "deleted": "Товар удалён",
+ "filter": {
+ "active": "Активные",
+ "archived": "В архиве"
+ },
+ "kind": {
+ "service": "Услуга",
+ "product": "Товар"
+ },
+ "billing": {
+ "one_time": "Разово",
+ "every": "Раз в {{interval}}"
+ },
+ "per": {
+ "weekly": "неделю",
+ "biweekly": "2 недели",
+ "monthly": "месяц",
+ "quarterly": "квартал",
+ "semiannual": "6 месяцев",
+ "yearly": "год"
+ },
+ "column": {
+ "name": "Название",
+ "kind": "Вид",
+ "prices": "Цены",
+ "invoices": "Счета"
+ },
+ "field": {
+ "name": "Название",
+ "namePlaceholder": "Час консультации, Тариф Pro, Дизайн логотипа",
+ "kind": "Вид",
+ "description": "Описание",
+ "prices": "Цены",
+ "pricesHint": "По одной на валюту. Регулярная цена задаёт периодичность; это подсказка для регулярных счетов, сама по себе она ничего не списывает.",
+ "addPrice": "Добавить цену",
+ "noPrices": "Цен нет. Название всё равно заполнит строку; сумму нужно ввести вручную.",
+ "nickname": "Метка (необязательно)",
+ "fiscalRefs": "Налоговые ссылки",
+ "fiscalRefsHint": "Что нужно налоговому документу для каждой строки. Предлагается вашей юрисдикцией; добавьте любой другой нужный ключ.",
+ "customRefKey": "другой ключ (напр. hs_code)",
+ "addRef": "Добавить",
+ "fiscalRefsNone": "Для этого типа здесь ничего не предлагается. Добавьте любой ключ, который нужен вашим налоговым документам."
+ },
+ "action": {
+ "archive": "В архив",
+ "restore": "Восстановить"
+ }
}
},
"collections": {
@@ -1956,7 +2035,18 @@
"uscc": "USCC"
},
"otherCountries": "Другие страны",
- "anyCountry": "Где-либо ещё"
+ "anyCountry": "Где-либо ещё",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / штрихкод",
+ "service_code": "Код услуги (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Муниципальный код услуги",
+ "hs_code": "Код HS",
+ "sat_product_code": "Код товара/услуги SAT",
+ "sat_unit_code": "Код единицы SAT"
+ }
},
"common": {
"selectTimezone": "Выберите часовой пояс",
diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.json
index c4deefe2..3a72d192 100644
--- a/frontend/src/locales/sk.json
+++ b/frontend/src/locales/sk.json
@@ -329,7 +329,19 @@
"negative_discount": "Zľava nemôže byť záporná.",
"first_term": "Cenu platnú od začiatku nemožno presunúť ani odstrániť. Zmeňte ju alebo pridajte novú cenu od neskoršieho dátumu.",
"not_receivable": "K dohode môže patriť iba faktúra, ktorú ste vystavili vy.",
- "period_already_issued": "Toto obdobie bolo práve vystavené. Obnovte stránku, aby ste ho videli."
+ "period_already_issued": "Toto obdobie bolo práve vystavené. Obnovte stránku, aby ste ho videli.",
+ "product_not_found": "Produkt sa nenašiel.",
+ "price_not_found": "Cena sa pri tomto produkte nenašla.",
+ "product_in_use": "Tento produkt je uvedený vo faktúrach. Namiesto zmazania ho archivujte.",
+ "price_in_use": "Za túto cenu už boli vystavené faktúry. Namiesto zmazania ju archivujte.",
+ "invalid_kind": "Neznámy druh produktu.",
+ "invalid_billing": "Neznámy druh účtovania.",
+ "interval_required": "Opakovaná cena potrebuje frekvenciu.",
+ "currency_required": "Cena potrebuje menu.",
+ "unit_price_required": "Cena potrebuje sumu.",
+ "negative_price": "Cena nemôže byť záporná.",
+ "invalid_fiscal_refs": "Daňové referencie musia byť krátke textové hodnoty pod jednoduchými kľúčmi (písmená, číslice, podčiarknutie).",
+ "price_key_taken": "Iná cena už používa tento vyhľadávací kľúč alebo externé id."
},
"comingNext": "Fakturujte klientom a majte prehľad o tom, čo je zaplatené a čo ešte otvorené. Toto sa práve stavia.",
"document": {
@@ -568,6 +580,73 @@
"empty": "V tejto dohode zatiaľ nie je žiadna faktúra.",
"emptyNext": "Zatiaľ žiadna faktúra. Prvá sa vystaví {{date}}."
}
+ },
+ "products": {
+ "title": "Produkty",
+ "new": "Nový produkt",
+ "newDescription": "Niečo, čo predávate, s cenou pre každú menu. Výber vyplní položku faktúry; položku môžete potom ľubovoľne upraviť.",
+ "editTitle": "Upraviť produkt",
+ "empty": "Zatiaľ žiadne produkty. Pridajte, čo predávate, a každá položka faktúry bude na jedno kliknutie.",
+ "emptyArchived": "Nič nie je archivované.",
+ "emptyPicker": "Zatiaľ žiadne produkty. Pridajte ich v sekcii Produkty.",
+ "noneFound": "Žiadny produkt nezodpovedá.",
+ "searchPlaceholder": "Hľadať produkty",
+ "pick": "Vybrať z katalógu",
+ "fromCatalog": "Z katalógu",
+ "noPrice": "Bez ceny",
+ "noPriceIn": "bez ceny v {{currency}}",
+ "perUnit": "za {{unit}}",
+ "created": "Produkt vytvorený",
+ "saved": "Produkt uložený",
+ "archived": "Produkt archivovaný. Faktúry, ktoré ho uvádzajú, sa nemenia.",
+ "restored": "Produkt obnovený",
+ "deleted": "Produkt zmazaný",
+ "filter": {
+ "active": "Aktívne",
+ "archived": "Archivované"
+ },
+ "kind": {
+ "service": "Služba",
+ "product": "Produkt"
+ },
+ "billing": {
+ "one_time": "Jednorazovo",
+ "every": "Každý {{interval}}"
+ },
+ "per": {
+ "weekly": "týždeň",
+ "biweekly": "2 týždne",
+ "monthly": "mesiac",
+ "quarterly": "štvrťrok",
+ "semiannual": "6 mesiacov",
+ "yearly": "rok"
+ },
+ "column": {
+ "name": "Názov",
+ "kind": "Druh",
+ "prices": "Ceny",
+ "invoices": "Faktúry"
+ },
+ "field": {
+ "name": "Názov",
+ "namePlaceholder": "Hodina konzultácie, Plán Pro, Návrh loga",
+ "kind": "Druh",
+ "description": "Popis",
+ "prices": "Ceny",
+ "pricesHint": "Jedna na menu. Opakovaná cena určuje, ako často; je to nápoveda pre opakované faktúry, nič sa neúčtuje samo od seba.",
+ "addPrice": "Pridať cenu",
+ "noPrices": "Žiadne ceny. Názov aj tak vyplní položku; suma sa zadáva ručne.",
+ "nickname": "Označenie (voliteľné)",
+ "fiscalRefs": "Daňové referencie",
+ "fiscalRefsHint": "Čo daňový doklad potrebuje pre každú položku. Navrhnuté podľa vašej jurisdikcie; pridajte akýkoľvek ďalší kľúč, ktorý potrebujete.",
+ "customRefKey": "iný kľúč (napr. hs_code)",
+ "addRef": "Pridať",
+ "fiscalRefsNone": "Pre tento druh tu nie je nič navrhnuté. Pridajte akýkoľvek kľúč, ktorý vaše daňové doklady potrebujú."
+ },
+ "action": {
+ "archive": "Archivovať",
+ "restore": "Obnoviť"
+ }
}
},
"collections": {
@@ -2063,7 +2142,18 @@
"uscc": "USCC"
},
"otherCountries": "Ostatné krajiny",
- "anyCountry": "Kdekoľvek inde"
+ "anyCountry": "Kdekoľvek inde",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / čiarový kód",
+ "service_code": "Kód služby (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Obecný kód služby",
+ "hs_code": "Kód HS",
+ "sat_product_code": "Kód produktu/služby SAT",
+ "sat_unit_code": "Kód jednotky SAT"
+ }
},
"common": {
"selectTimezone": "Vyberte časové pásmo",
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 7ac384a7..d58370af 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -329,7 +329,19 @@
"negative_discount": "Знижка не може бути від'ємною.",
"first_term": "Ціну, що діє від початку, не можна перенести чи видалити. Змініть її або додайте нову ціну з пізнішої дати.",
"not_receivable": "До домовленості може належати лише рахунок, виставлений вами.",
- "period_already_issued": "Цей період щойно виставлено. Оновіть сторінку, щоб його побачити."
+ "period_already_issued": "Цей період щойно виставлено. Оновіть сторінку, щоб його побачити.",
+ "product_not_found": "Товар не знайдено.",
+ "price_not_found": "У цього товару немає такої ціни.",
+ "product_in_use": "Цей товар зазначено в рахунках. Відправте його в архів замість видалення.",
+ "price_in_use": "За цією ціною вже виставлено рахунки. Відправте її в архів замість видалення.",
+ "invalid_kind": "Невідомий вид товару.",
+ "invalid_billing": "Невідомий вид оплати.",
+ "interval_required": "Регулярній ціні потрібна періодичність.",
+ "currency_required": "Ціні потрібна валюта.",
+ "unit_price_required": "Ціні потрібна сума.",
+ "negative_price": "Ціна не може бути від'ємною.",
+ "invalid_fiscal_refs": "Податкові посилання мають бути короткими текстовими значеннями під простими ключами (літери, цифри, підкреслення).",
+ "price_key_taken": "Інша ціна вже використовує цей ключ пошуку або зовнішній ідентифікатор."
},
"comingNext": "Виставляйте рахунки клієнтам і стежте за тим, що оплачено, а що залишається відкритим. Це наступне, що буде зроблено.",
"document": {
@@ -568,6 +580,73 @@
"empty": "За цією домовленістю поки немає рахунків.",
"emptyNext": "Рахунків поки немає. Перший буде виставлено {{date}}."
}
+ },
+ "products": {
+ "title": "Товари",
+ "new": "Новий товар",
+ "newDescription": "Те, що ви продаєте, з ціною в кожній валюті. Вибір заповнює рядок рахунку; після цього рядок можна вільно змінювати.",
+ "editTitle": "Редагувати товар",
+ "empty": "Товарів поки немає. Додайте те, що продаєте, і кожен рядок рахунку буде за один клік.",
+ "emptyArchived": "В архіві нічого немає.",
+ "emptyPicker": "Товарів поки немає. Додайте їх у розділі «Товари».",
+ "noneFound": "Жоден товар не підходить.",
+ "searchPlaceholder": "Пошук товарів",
+ "pick": "Вибрати з каталогу",
+ "fromCatalog": "З каталогу",
+ "noPrice": "Без ціни",
+ "noPriceIn": "немає ціни в {{currency}}",
+ "perUnit": "за {{unit}}",
+ "created": "Товар створено",
+ "saved": "Товар збережено",
+ "archived": "Товар в архіві. Рахунки, в яких він зазначений, не змінюються.",
+ "restored": "Товар відновлено",
+ "deleted": "Товар видалено",
+ "filter": {
+ "active": "Активні",
+ "archived": "В архіві"
+ },
+ "kind": {
+ "service": "Послуга",
+ "product": "Товар"
+ },
+ "billing": {
+ "one_time": "Разово",
+ "every": "Раз на {{interval}}"
+ },
+ "per": {
+ "weekly": "тиждень",
+ "biweekly": "2 тижні",
+ "monthly": "місяць",
+ "quarterly": "квартал",
+ "semiannual": "6 місяців",
+ "yearly": "рік"
+ },
+ "column": {
+ "name": "Назва",
+ "kind": "Вид",
+ "prices": "Ціни",
+ "invoices": "Рахунки"
+ },
+ "field": {
+ "name": "Назва",
+ "namePlaceholder": "Година консультації, Тариф Pro, Дизайн логотипа",
+ "kind": "Вид",
+ "description": "Опис",
+ "prices": "Ціни",
+ "pricesHint": "По одній на валюту. Регулярна ціна задає періодичність; це підказка для регулярних рахунків, сама по собі вона нічого не списує.",
+ "addPrice": "Додати ціну",
+ "noPrices": "Цін немає. Назва все одно заповнить рядок; суму потрібно ввести вручну.",
+ "nickname": "Мітка (необов'язково)",
+ "fiscalRefs": "Податкові посилання",
+ "fiscalRefsHint": "Що потрібно податковому документу для кожного рядка. Пропонується вашою юрисдикцією; додайте будь-який інший потрібний ключ.",
+ "customRefKey": "інший ключ (напр. hs_code)",
+ "addRef": "Додати",
+ "fiscalRefsNone": "Для цього типу тут нічого не запропоновано. Додайте будь-який ключ, потрібний вашим податковим документам."
+ },
+ "action": {
+ "archive": "В архів",
+ "restore": "Відновити"
+ }
}
},
"collections": {
@@ -1956,7 +2035,18 @@
"uscc": "USCC"
},
"otherCountries": "Інші країни",
- "anyCountry": "Будь-де інде"
+ "anyCountry": "Будь-де інде",
+ "productField": {
+ "ncm": "NCM",
+ "cest": "CEST",
+ "gtin": "GTIN / штрихкод",
+ "service_code": "Код послуги (LC 116)",
+ "nbs": "NBS",
+ "municipal_service_code": "Муніципальний код послуги",
+ "hs_code": "Код HS",
+ "sat_product_code": "Код товару/послуги SAT",
+ "sat_unit_code": "Код одиниці SAT"
+ }
},
"common": {
"selectTimezone": "Виберіть часовий пояс",
diff --git a/frontend/src/pages/invoices.tsx b/frontend/src/pages/invoices.tsx
index 73717b2e..80e04d36 100644
--- a/frontend/src/pages/invoices.tsx
+++ b/frontend/src/pages/invoices.tsx
@@ -5,6 +5,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
Calendar as CalendarIcon,
ChevronDown,
+ Package,
Plus,
Receipt,
Repeat,
@@ -160,15 +161,26 @@ export default function InvoicesPage() {
{/* Only on the receivable side: an agreement is something we
bill, and the payable ledger has nothing to emit. */}
{direction === 'receivable' && (
- <Button
- variant="outline"
- size="sm"
- onClick={() => navigate('/invoices/schedules')}
- data-testid="invoice-schedules-button"
- >
- <Repeat className="h-4 w-4 mr-1.5" />
- {t('invoices.schedules.title')}
- </Button>
+ <>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => navigate('/invoices/products')}
+ data-testid="invoice-products-button"
+ >
+ <Package className="h-4 w-4 mr-1.5" />
+ {t('invoices.products.title')}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => navigate('/invoices/schedules')}
+ data-testid="invoice-schedules-button"
+ >
+ <Repeat className="h-4 w-4 mr-1.5" />
+ {t('invoices.schedules.title')}
+ </Button>
+ </>
)}
<Button
variant="outline"
@@ -602,11 +614,13 @@ function CreateInvoiceDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
{/* Widens once there are line items: a table of five columns in a
- narrow dialog is the cramped row of boxes this used to be. */}
+ narrow dialog is the cramped row of boxes this used to be. The
+ document preset opens with a line row already showing, so it
+ starts wide. */}
<DialogContent
className={cn(
'flex flex-col max-h-[calc(100dvh-2rem)]',
- lines.length ? 'sm:max-w-3xl' : 'sm:max-w-lg',
+ lines.length || settings?.document_required ? 'sm:max-w-3xl' : 'sm:max-w-lg',
)}
>
<DialogHeader>
diff --git a/frontend/src/pages/products.test.tsx b/frontend/src/pages/products.test.tsx
new file mode 100644
index 00000000..aa877db9
--- /dev/null
+++ b/frontend/src/pages/products.test.tsx
@@ -0,0 +1,279 @@
+import { useState } from 'react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { screen, within } from '@testing-library/react'
+
+import ProductsPage from '@/pages/products'
+import { InvoiceLineEditor } from '@/components/invoice-line-editor'
+import { renderWithProviders, t } from '@/test/utils'
+import type { InvoiceLineInput, Product } from '@/types'
+
+const api = vi.hoisted(() => ({
+ products: {
+ list: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ remove: vi.fn(),
+ addPrice: vi.fn(),
+ updatePrice: vi.fn(),
+ removePrice: vi.fn(),
+ },
+ invoices: { settings: vi.fn() },
+ fiscal: { productFields: vi.fn() },
+}))
+
+vi.mock('@/lib/api', () => ({
+ products: api.products,
+ invoices: api.invoices,
+ fiscal: api.fiscal,
+}))
+
+vi.mock('@/hooks/use-display-locale', () => ({
+ useDisplayLocale: () => 'en-US',
+ useDateLocale: () => 'en-US',
+}))
+
+vi.mock('@/contexts/auth-context', () => ({
+ useAuth: () => ({ user: { preferences: { currency_display: 'USD' } } }),
+}))
+
+let canWrite = true
+vi.mock('@/contexts/workspace-context', () => ({
+ useWorkspace: () => ({ canWrite }),
+}))
+
+vi.mock('@/hooks/use-privacy-mode', () => ({
+ usePrivacyMode: () => ({ mask: (value: string) => value }),
+}))
+
+function product(overrides: Partial<Product> = {}): Product {
+ return {
+ id: 'hour',
+ name: 'Consulting hour',
+ description: 'Senior engineer',
+ kind: 'service',
+ unit: 'h',
+ active: true,
+ origin: 'local',
+ external_source: null,
+ external_id: null,
+ custom_fields: null,
+ fiscal_refs: null,
+ prices: [
+ {
+ id: 'usd', product_id: 'hour', currency: 'USD', unit_price: '200.00', tax_rate: null,
+ billing: 'one_time', interval: null, nickname: null, lookup_key: null, active: true,
+ external_source: null, external_id: null, created_at: '2026-01-01T00:00:00Z',
+ },
+ {
+ id: 'eur', product_id: 'hour', currency: 'EUR', unit_price: '900.00', tax_rate: null,
+ billing: 'recurring', interval: 'monthly', nickname: 'Monthly', lookup_key: null, active: true,
+ external_source: null, external_id: null, created_at: '2026-01-02T00:00:00Z',
+ },
+ ],
+ created_at: '2026-01-01T00:00:00Z',
+ invoice_count: 3,
+ ...overrides,
+ }
+}
+
+describe('ProductsPage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ canWrite = true
+ api.products.list.mockResolvedValue([
+ product(),
+ product({ id: 'logo', name: 'Logo design', kind: 'product', description: null, unit: null, prices: [], invoice_count: 0 }),
+ ])
+ api.invoices.settings.mockResolvedValue({ tax_fields: 'hidden' })
+ api.fiscal.productFields.mockResolvedValue({ jurisdiction: null, fields: [] })
+ })
+
+ it('lists the catalog with every live price and what each product is worth to invoices', async () => {
+ renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ const rows = await screen.findAllByTestId('product-row')
+ expect(rows).toHaveLength(2)
+ expect(within(rows[0]).getByText('Consulting hour')).toBeInTheDocument()
+ expect(within(rows[0]).getByText(t('invoices.products.kind.service'))).toBeInTheDocument()
+ expect(within(rows[0]).getByText('$200.00 · €900.00 / month')).toBeInTheDocument()
+ expect(within(rows[0]).getByText('3')).toBeInTheDocument()
+ expect(within(rows[1]).getByText(t('invoices.products.noPrice'))).toBeInTheDocument()
+ expect(api.products.list).toHaveBeenLastCalledWith({ active: true })
+ })
+
+ it('offers archive to a named product and delete only to an unnamed one', async () => {
+ renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ const rows = await screen.findAllByTestId('product-row')
+ expect(within(rows[0]).getByLabelText(t('invoices.products.action.archive'))).toBeInTheDocument()
+ expect(within(rows[0]).queryByLabelText(t('common.delete'))).not.toBeInTheDocument()
+ expect(within(rows[1]).getByLabelText(t('common.delete'))).toBeInTheDocument()
+ })
+
+ it('switches to the archived list through the server', async () => {
+ const { user } = renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ await screen.findAllByTestId('product-row')
+ await user.click(screen.getByTestId('product-filter-archived'))
+ expect(api.products.list).toHaveBeenLastCalledWith({ active: false })
+ })
+
+ it('hides every write from a viewer', async () => {
+ canWrite = false
+ renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ await screen.findAllByTestId('product-row')
+ expect(screen.queryByTestId('product-new-button')).not.toBeInTheDocument()
+ expect(screen.queryByLabelText(t('common.edit'))).not.toBeInTheDocument()
+ })
+
+ it('creates a product with its prices in one call', async () => {
+ api.products.create.mockResolvedValue(product())
+ const { user } = renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ await screen.findAllByTestId('product-row')
+ await user.click(screen.getByTestId('product-new-button'))
+ await screen.findByTestId('product-name-input')
+ expect(screen.getByTestId('product-save')).toBeDisabled()
+ await user.type(screen.getByTestId('product-name-input'), 'Retainer')
+ await user.type(screen.getByTestId('product-unit-input'), 'month')
+ await user.type(screen.getByTestId('price-amount-0'), '3000')
+ await user.click(screen.getByTestId('product-save'))
+ expect(api.products.create).toHaveBeenCalledWith({
+ name: 'Retainer',
+ kind: 'service',
+ unit: 'month',
+ description: null,
+ fiscal_refs: null,
+ prices: [{ currency: 'USD', unit_price: '3000', tax_rate: null, billing: 'one_time', interval: null, nickname: null }],
+ })
+ })
+})
+
+describe('ProductsPage editing', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ canWrite = true
+ api.products.list.mockResolvedValue([product()])
+ api.invoices.settings.mockResolvedValue({ tax_fields: 'hidden' })
+ api.products.update.mockResolvedValue(product())
+ api.products.updatePrice.mockResolvedValue(product())
+ api.fiscal.productFields.mockResolvedValue({ jurisdiction: null, fields: [] })
+ })
+
+ it('archives an existing price instead of deleting it, and never deletes from the dialog', async () => {
+ const { user } = renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ const [row] = await screen.findAllByTestId('product-row')
+ await user.click(within(row).getByLabelText(t('common.edit')))
+ await screen.findByTestId('product-name-input')
+ await user.click(screen.getByTestId('price-archive-1'))
+ expect(screen.getByTestId('price-restore-1')).toBeInTheDocument()
+ await user.click(screen.getByTestId('product-save'))
+ expect(api.products.removePrice).not.toHaveBeenCalled()
+ expect(api.products.updatePrice).toHaveBeenCalledWith('hour', 'eur', expect.objectContaining({ active: false }))
+ expect(api.products.updatePrice).toHaveBeenCalledWith('hour', 'usd', expect.objectContaining({ active: true }))
+ })
+
+ it('closes on the server state when a request in the sequence fails', async () => {
+ // The product update commits, the price update fails: the list must
+ // then show what the server holds (the new name), and the dialog
+ // must be gone so a retry does not replay the committed part.
+ const updated = product({ name: 'Updated consulting hour' })
+ api.products.list.mockReset()
+ api.products.list.mockResolvedValueOnce([product()]).mockResolvedValue([updated])
+ api.products.update.mockResolvedValue(updated)
+ api.products.updatePrice.mockRejectedValueOnce({ response: { data: { detail: { code: 'negative_price' } } } })
+ const { user } = renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ const [row] = await screen.findAllByTestId('product-row')
+ await user.click(within(row).getByLabelText(t('common.edit')))
+ const nameInput = await screen.findByTestId('product-name-input')
+ await user.clear(nameInput)
+ await user.type(nameInput, updated.name)
+ await user.click(screen.getByTestId('product-save'))
+ await screen.findByText(updated.name)
+ expect(screen.queryByTestId('product-name-input')).not.toBeInTheDocument()
+ })
+})
+
+describe('ProductsPage fiscal references', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ canWrite = true
+ api.products.list.mockResolvedValue([])
+ api.invoices.settings.mockResolvedValue({ tax_fields: 'hidden' })
+ api.products.create.mockResolvedValue(product())
+ api.fiscal.productFields.mockResolvedValue({
+ jurisdiction: 'BR',
+ fields: [
+ { key: 'ncm', label_key: 'fiscal.productField.ncm', kinds: ['product'] },
+ { key: 'service_code', label_key: 'fiscal.productField.service_code', kinds: ['service'] },
+ ],
+ })
+ })
+
+ it('offers the keys the jurisdiction suggests for the kind, plus any key by hand', async () => {
+ const { user } = renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ await screen.findByTestId('products-empty')
+ await user.click(screen.getByTestId('product-new-button'))
+ // A service: the service code is offered, the goods code is not.
+ expect(await screen.findByTestId('product-ref-service_code')).toBeInTheDocument()
+ expect(screen.queryByTestId('product-ref-ncm')).not.toBeInTheDocument()
+ await user.type(screen.getByTestId('product-name-input'), 'Design')
+ await user.type(screen.getByTestId('product-ref-service_code'), ' 1.05 ')
+ // A key the pack never mentions, typed in any case.
+ await user.type(screen.getByTestId('product-ref-custom-key'), 'HS_code')
+ await user.click(screen.getByTestId('product-ref-add'))
+ await user.type(screen.getByTestId('product-ref-hs_code'), '8471')
+ await user.click(screen.getByTestId('product-save'))
+ expect(api.products.create).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'Design', fiscal_refs: { service_code: '1.05', hs_code: '8471' } }),
+ )
+ })
+
+ it('refuses a key that is not a key', async () => {
+ const { user } = renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ await screen.findByTestId('products-empty')
+ await user.click(screen.getByTestId('product-new-button'))
+ await screen.findByTestId('product-ref-custom-key')
+ await user.type(screen.getByTestId('product-ref-custom-key'), 'has space')
+ expect(screen.getByTestId('product-ref-add')).toBeDisabled()
+ })
+
+ it('shows the section with an add row when the jurisdiction suggests nothing', async () => {
+ api.fiscal.productFields.mockResolvedValue({ jurisdiction: null, fields: [] })
+ const { user } = renderWithProviders(<ProductsPage />, { route: '/invoices/products' })
+ await screen.findByTestId('products-empty')
+ await user.click(screen.getByTestId('product-new-button'))
+ expect(await screen.findByTestId('product-ref-custom-key')).toBeInTheDocument()
+ expect(screen.getByText(t('invoices.products.field.fiscalRefsNone'))).toBeInTheDocument()
+ })
+})
+
+describe('InvoiceLineEditor with the catalog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ api.products.list.mockResolvedValue([product()])
+ })
+
+ function Harness({ currency, initial }: { currency: string; initial: InvoiceLineInput[] }) {
+ const [lines, setLines] = useState<InvoiceLineInput[]>(initial)
+ return <InvoiceLineEditor lines={lines} onChange={setLines} currency={currency} showTax={false} required />
+ }
+
+ it('fills the line from the product at the price in the invoice currency, and marks it', async () => {
+ const { user } = renderWithProviders(<Harness currency="USD" initial={[{ description: '', quantity: '2', unit_price: '0' }]} />)
+ await user.click(screen.getByTestId('invoice-line-pick-product'))
+ await user.click(await screen.findByTestId('product-option-hour'))
+ expect(screen.getByTestId('invoice-line-description-0')).toHaveValue('Consulting hour')
+ expect(screen.getByTestId('invoice-line-unit-0')).toHaveValue('h')
+ expect(screen.getByTestId('invoice-line-price-0')).toHaveValue('200.00')
+ expect(screen.getByTestId('invoice-line-quantity-0')).toHaveValue('2')
+ expect(screen.getByTestId('invoice-line-amount-0')).toHaveTextContent('$400.00')
+ expect(screen.getByTestId('invoice-line-from-catalog-0')).toBeInTheDocument()
+ })
+
+ it('fills only the name when the product has no price in the currency', async () => {
+ const { user } = renderWithProviders(<Harness currency="BRL" initial={[{ description: '', quantity: '1', unit_price: '50' }]} />)
+ await user.click(screen.getByTestId('invoice-line-pick-product'))
+ const option = await screen.findByTestId('product-option-hour')
+ expect(option).toHaveTextContent(t('invoices.products.noPriceIn', { currency: 'BRL' }))
+ await user.click(option)
+ expect(screen.getByTestId('invoice-line-description-0')).toHaveValue('Consulting hour')
+ expect(screen.getByTestId('invoice-line-price-0')).toHaveValue('50')
+ })
+})
diff --git a/frontend/src/pages/products.tsx b/frontend/src/pages/products.tsx
new file mode 100644
index 00000000..892bf9c5
--- /dev/null
+++ b/frontend/src/pages/products.tsx
@@ -0,0 +1,623 @@
+import { useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useNavigate } from 'react-router-dom'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { Archive, ArchiveRestore, ArrowLeft, Package, Pencil, Plus, Trash2 } from 'lucide-react'
+import { toast } from 'sonner'
+
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { Skeleton } from '@/components/ui/skeleton'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
+import { PageHeader } from '@/components/page-header'
+import { IconAction, SectionCard, Segmented, TH } from '@/components/invoice-ui'
+import { CurrencySelect } from '@/components/currency-select'
+import { cn } from '@/lib/utils'
+import { formatCurrency } from '@/lib/format'
+import { useDisplayLocale } from '@/hooks/use-display-locale'
+import { usePrivacyMode } from '@/hooks/use-privacy-mode'
+import { useAuth } from '@/contexts/auth-context'
+import { useWorkspace } from '@/contexts/workspace-context'
+import { fiscal as fiscalApi, invoices as invoicesApi, products as productsApi, type PricePayload } from '@/lib/api'
+import { invoiceErrorKey } from '@/lib/invoice-utils'
+import { FREQUENCIES } from '@/lib/invoice-schedule-utils'
+import { productActions } from '@/lib/product-utils'
+import type { InvoiceScheduleFrequency, PriceBilling, Product, ProductKind } from '@/types'
+
+/**
+ * The catalog: what this workspace sells, and for how much.
+ *
+ * Optional by design. A workspace that never opens this page writes
+ * invoice lines exactly as before; one that does gets a picker beside
+ * every line. Archiving is the way out for a product an invoice names,
+ * because the invoice keeps pointing at it.
+ */
+type Filter = 'active' | 'archived'
+
+export default function ProductsPage() {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const locale = useDisplayLocale()
+ const { mask } = usePrivacyMode()
+ const { canWrite } = useWorkspace()
+ const queryClient = useQueryClient()
+
+ const [filter, setFilter] = useState<Filter>('active')
+ const [search, setSearch] = useState('')
+ const [editing, setEditing] = useState<Product | 'new' | null>(null)
+
+ const { data: list, isLoading } = useQuery({
+ queryKey: ['products', filter],
+ queryFn: () => productsApi.list({ active: filter === 'active' }),
+ })
+
+ const visible = useMemo(() => {
+ if (!list) return []
+ const q = search.trim().toLowerCase()
+ if (!q) return list
+ return list.filter(
+ (p) => p.name.toLowerCase().includes(q) || (p.description ?? '').toLowerCase().includes(q),
+ )
+ }, [list, search])
+
+ const refresh = () => {
+ void queryClient.invalidateQueries({ queryKey: ['products'] })
+ }
+ const onError = (error: unknown) => {
+ const key = invoiceErrorKey(error)
+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))
+ }
+ const archiveMutation = useMutation({
+ mutationFn: ({ id, active }: { id: string; active: boolean }) => productsApi.update(id, { active }),
+ onSuccess: (_, { active }) => {
+ toast.success(active ? t('invoices.products.restored') : t('invoices.products.archived'))
+ refresh()
+ },
+ onError,
+ })
+ const deleteMutation = useMutation({
+ mutationFn: (id: string) => productsApi.remove(id),
+ onSuccess: () => {
+ toast.success(t('invoices.products.deleted'))
+ refresh()
+ },
+ onError,
+ })
+
+ const money = (value: string, code: string) => mask(formatCurrency(Number(value), code, locale))
+ const priceLabel = (product: Product) => {
+ const live = product.prices.filter((p) => p.active)
+ if (live.length === 0) return t('invoices.products.noPrice')
+ return live
+ .map(
+ (p) =>
+ money(p.unit_price, p.currency) +
+ (p.interval ? ` / ${t(`invoices.products.per.${p.interval}`)}` : ''),
+ )
+ .join(' · ')
+ }
+
+ return (
+ <div>
+ <button
+ onClick={() => navigate('/invoices')}
+ className="inline-flex items-center gap-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors mb-3"
+ data-testid="products-back"
+ >
+ <ArrowLeft className="h-3.5 w-3.5" />
+ {t('invoices.backToList')}
+ </button>
+
+ <PageHeader
+ section={t('invoices.title')}
+ title={t('invoices.products.title')}
+ action={
+ canWrite ? (
+ <Button size="sm" onClick={() => setEditing('new')} data-testid="product-new-button">
+ <Plus className="h-4 w-4 mr-1.5" />
+ {t('invoices.products.new')}
+ </Button>
+ ) : undefined
+ }
+ />
+
+ <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
+ <Segmented<Filter>
+ value={filter}
+ onChange={setFilter}
+ testIdPrefix="product-filter"
+ options={(['active', 'archived'] as const).map((value) => ({
+ value,
+ label: t(`invoices.products.filter.${value}`),
+ }))}
+ />
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder={t('invoices.products.searchPlaceholder')}
+ className="h-9 w-full sm:w-64"
+ data-testid="product-search"
+ />
+ </div>
+
+ <SectionCard>
+ {isLoading ? (
+ <div className="p-5 space-y-3">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-9 w-full" />
+ ))}
+ </div>
+ ) : visible.length === 0 ? (
+ <div className="px-5 py-14 text-center" data-testid="products-empty">
+ <Package className="h-8 w-8 mx-auto text-muted-foreground/50" />
+ <p className="mt-3 text-sm text-muted-foreground max-w-sm mx-auto">
+ {search
+ ? t('invoices.products.noneFound')
+ : filter === 'archived'
+ ? t('invoices.products.emptyArchived')
+ : t('invoices.products.empty')}
+ </p>
+ {!search && filter === 'active' && canWrite && (
+ <Button size="sm" className="mt-4" onClick={() => setEditing('new')}>
+ <Plus className="h-4 w-4 mr-1.5" />
+ {t('invoices.products.new')}
+ </Button>
+ )}
+ </div>
+ ) : (
+ <div className="overflow-x-auto">
+ <table className="w-full">
+ <thead>
+ <tr className="border-b border-border">
+ <th className={`${TH} pl-4 sm:pl-5 text-left`}>{t('invoices.products.column.name')}</th>
+ <th className={`${TH} text-left w-24 hidden sm:table-cell`}>{t('invoices.products.column.kind')}</th>
+ <th className={`${TH} text-left hidden md:table-cell`}>{t('invoices.products.column.prices')}</th>
+ <th className={`${TH} text-right w-24 hidden lg:table-cell`}>{t('invoices.products.column.invoices')}</th>
+ {canWrite && (
+ <th className={`${TH} pr-4 sm:pr-5 w-28`}>
+ <span className="sr-only">{t('invoices.moreActions')}</span>
+ </th>
+ )}
+ </tr>
+ </thead>
+ <tbody>
+ {visible.map((product) => {
+ const actions = productActions(product)
+ return (
+ <tr key={product.id} data-testid="product-row" className="border-b border-border last:border-0">
+ <td className="py-3 pl-4 sm:pl-5">
+ <div className="text-sm font-medium text-foreground truncate">{product.name}</div>
+ <div className="text-xs text-muted-foreground truncate">
+ {product.description ?? (product.unit ? t('invoices.products.perUnit', { unit: product.unit }) : '')}
+ </div>
+ </td>
+ <td className="py-3 hidden sm:table-cell text-xs text-muted-foreground">
+ {t(`invoices.products.kind.${product.kind}`)}
+ </td>
+ <td className="py-3 hidden md:table-cell text-xs text-muted-foreground tabular-nums">
+ {priceLabel(product)}
+ </td>
+ <td className="py-3 text-right hidden lg:table-cell text-xs text-muted-foreground tabular-nums">
+ {product.invoice_count}
+ </td>
+ {canWrite && (
+ <td className="py-3 pr-4 sm:pr-5">
+ <div className="flex justify-end gap-1">
+ <IconAction onClick={() => setEditing(product)} label={t('common.edit')}>
+ <Pencil className="h-3.5 w-3.5" />
+ </IconAction>
+ {actions.canArchive && (
+ <IconAction
+ onClick={() => archiveMutation.mutate({ id: product.id, active: false })}
+ label={t('invoices.products.action.archive')}
+ >
+ <Archive className="h-3.5 w-3.5" />
+ </IconAction>
+ )}
+ {actions.canRestore && (
+ <IconAction
+ onClick={() => archiveMutation.mutate({ id: product.id, active: true })}
+ label={t('invoices.products.action.restore')}
+ >
+ <ArchiveRestore className="h-3.5 w-3.5" />
+ </IconAction>
+ )}
+ {actions.canDelete && (
+ <IconAction onClick={() => deleteMutation.mutate(product.id)} label={t('common.delete')}>
+ <Trash2 className="h-3.5 w-3.5" />
+ </IconAction>
+ )}
+ </div>
+ </td>
+ )}
+ </tr>
+ )
+ })}
+ </tbody>
+ </table>
+ </div>
+ )}
+ </SectionCard>
+
+ <ProductDialog
+ key={editing === null ? 'closed' : editing === 'new' ? 'new' : editing.id}
+ open={editing !== null}
+ onOpenChange={(open) => !open && setEditing(null)}
+ product={editing === 'new' ? null : editing}
+ onSaved={refresh}
+ />
+ </div>
+ )
+}
+
+interface PriceRow {
+ id: string | null
+ currency: string
+ unit_price: string
+ tax_rate: string
+ billing: PriceBilling
+ interval: InvoiceScheduleFrequency | ''
+ nickname: string
+ active: boolean
+}
+
+function blankPrice(currency: string): PriceRow {
+ return { id: null, currency, unit_price: '', tax_rate: '', billing: 'one_time', interval: '', nickname: '', active: true }
+}
+
+function toPayload(row: PriceRow): PricePayload {
+ return {
+ currency: row.currency,
+ unit_price: row.unit_price,
+ tax_rate: row.tax_rate || null,
+ billing: row.billing,
+ interval: row.billing === 'recurring' && row.interval ? row.interval : null,
+ nickname: row.nickname || null,
+ }
+}
+
+export function ProductDialog({
+ open,
+ onOpenChange,
+ product,
+ onSaved,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ /** Null creates. */
+ product: Product | null
+ onSaved: () => void
+}) {
+ const { t } = useTranslation()
+ const { user } = useAuth()
+ const { data: settings } = useQuery({
+ queryKey: ['invoice-settings'],
+ queryFn: invoicesApi.settings,
+ enabled: open,
+ })
+ const showTax = (settings?.tax_fields ?? 'hidden') !== 'hidden'
+ const defaultCurrency = user?.preferences?.currency_display ?? 'USD'
+ // What this workspace's jurisdiction asks for on a catalog item. A
+ // suggestion: the keys below are offered, and any other key can be
+ // added by hand, so a Brazilian studio selling to Berlin can carry an
+ // HS code beside its NCM.
+ const { data: suggested } = useQuery({
+ queryKey: ['fiscal', 'product-fields'],
+ queryFn: fiscalApi.productFields,
+ enabled: open,
+ })
+
+ const [name, setName] = useState(product?.name ?? '')
+ const [kind, setKind] = useState<ProductKind>(product?.kind ?? 'service')
+ const [unit, setUnit] = useState(product?.unit ?? '')
+ const [description, setDescription] = useState(product?.description ?? '')
+ const [refs, setRefs] = useState<{ key: string; value: string }[]>(() =>
+ Object.entries(product?.fiscal_refs ?? {}).map(([key, value]) => ({ key, value })),
+ )
+ const [customKey, setCustomKey] = useState('')
+ const [prices, setPrices] = useState<PriceRow[]>(
+ product
+ ? product.prices.map((p) => ({
+ id: p.id,
+ currency: p.currency,
+ unit_price: p.unit_price,
+ tax_rate: p.tax_rate ?? '',
+ billing: p.billing,
+ interval: p.interval ?? '',
+ nickname: p.nickname ?? '',
+ active: p.active,
+ }))
+ : [blankPrice(defaultCurrency)],
+ )
+
+ const updatePrice = (index: number, patch: Partial<PriceRow>) =>
+ setPrices(prices.map((row, i) => (i === index ? { ...row, ...patch } : row)))
+
+ const onError = (error: unknown) => {
+ const key = invoiceErrorKey(error)
+ toast.error(key ? t(key, t('invoices.errors.generic')) : t('invoices.errors.generic'))
+ }
+
+ const mutation = useMutation({
+ mutationFn: async () => {
+ const filled = prices.filter((row) => row.unit_price !== '')
+ const fiscal_refs = Object.fromEntries(
+ refs.filter((r) => r.key.trim() && r.value.trim()).map((r) => [r.key.trim().toLowerCase(), r.value.trim()]),
+ )
+ const base = {
+ name,
+ kind,
+ unit: unit || null,
+ description: description || null,
+ fiscal_refs: Object.keys(fiscal_refs).length ? fiscal_refs : null,
+ }
+ if (!product) {
+ return productsApi.create({ ...base, prices: filled.map(toPayload) })
+ }
+ // Product fields, then each price by what happened to it: new rows
+ // are added, existing rows updated. Nothing is deleted from here:
+ // an existing price the person no longer wants is archived, which
+ // is the only outcome the server allows once an invoice was billed
+ // at it, and the same outcome either way keeps the dialog honest.
+ let saved = await productsApi.update(product.id, base)
+ for (const row of prices) {
+ if (row.id) {
+ // A cleared amount on an existing price is not a change to it.
+ const patch = row.unit_price === '' ? {} : toPayload(row)
+ saved = await productsApi.updatePrice(product.id, row.id, { ...patch, active: row.active })
+ } else if (row.unit_price !== '') {
+ saved = await productsApi.addPrice(product.id, toPayload(row))
+ }
+ }
+ return saved
+ },
+ onSuccess: () => {
+ toast.success(product ? t('invoices.products.saved') : t('invoices.products.created'))
+ onOpenChange(false)
+ onSaved()
+ },
+ onError: (error) => {
+ onError(error)
+ // The edit path is several requests, and the ones before the
+ // failure have committed. Closing on the server's state means a
+ // retry starts from what is really there, instead of adding the
+ // same new price twice.
+ if (product) {
+ onSaved()
+ onOpenChange(false)
+ }
+ },
+ })
+
+ const ready = name.trim().length > 0 && prices.every((row) => row.billing !== 'recurring' || row.interval !== '' || row.unit_price === '')
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex flex-col max-h-[calc(100dvh-2rem)] sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{product ? t('invoices.products.editTitle') : t('invoices.products.new')}</DialogTitle>
+ <DialogDescription>{t('invoices.products.newDescription')}</DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ <div className="grid grid-cols-1 sm:grid-cols-[1fr_9rem_6rem] gap-3">
+ <div className="space-y-1.5">
+ <Label htmlFor="product-name">{t('invoices.products.field.name')}</Label>
+ <Input id="product-name" data-testid="product-name-input" value={name} onChange={(e) => setName(e.target.value)} placeholder={t('invoices.products.field.namePlaceholder')} />
+ </div>
+ <div className="space-y-1.5">
+ <Label>{t('invoices.products.field.kind')}</Label>
+ <Select value={kind} onValueChange={(v) => setKind(v as ProductKind)}>
+ <SelectTrigger data-testid="product-kind-select"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {(['service', 'product'] as const).map((value) => (
+ <SelectItem key={value} value={value}>{t(`invoices.products.kind.${value}`)}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="product-unit">{t('invoices.field.unit')}</Label>
+ <Input id="product-unit" data-testid="product-unit-input" value={unit} onChange={(e) => setUnit(e.target.value)} placeholder={t('invoices.field.unitPlaceholder')} maxLength={20} />
+ </div>
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="product-description">{t('invoices.products.field.description')}</Label>
+ <Input id="product-description" data-testid="product-description-input" value={description} onChange={(e) => setDescription(e.target.value)} />
+ </div>
+
+ {/* Fiscal references. The keys the jurisdiction suggests for
+ this kind are offered as fields; anything else is added by
+ key, and an empty value drops the key. With nothing
+ suggested the section is one line and an "add" row, so a
+ workspace whose country has no pack yet can still carry
+ what its documents need. */}
+ {(() => {
+ const offered = (suggested?.fields ?? []).filter(
+ (f) => f.kinds.length === 0 || f.kinds.includes(kind),
+ )
+ const offeredKeys = new Set(offered.map((f) => f.key))
+ const extra = refs.filter((r) => !offeredKeys.has(r.key))
+ const valueOf = (key: string) => refs.find((r) => r.key === key)?.value ?? ''
+ const setRef = (key: string, value: string) =>
+ setRefs((prev) =>
+ prev.some((r) => r.key === key)
+ ? prev.map((r) => (r.key === key ? { ...r, value } : r))
+ : [...prev, { key, value }],
+ )
+ const anyField = offered.length > 0 || extra.length > 0
+ return (
+ <div className="space-y-2" data-testid="product-fiscal-refs">
+ <Label>{t('invoices.products.field.fiscalRefs')}</Label>
+ <p className="text-[11px] text-muted-foreground">
+ {anyField
+ ? t('invoices.products.field.fiscalRefsHint')
+ : t('invoices.products.field.fiscalRefsNone')}
+ </p>
+ <div className={cn('grid grid-cols-2 sm:grid-cols-3 gap-3', !anyField && 'hidden')}>
+ {offered.map((f) => (
+ <div key={f.key} className="space-y-1.5">
+ <Label htmlFor={`ref-${f.key}`} className="text-xs">{t(f.label_key, f.key)}</Label>
+ <Input
+ id={`ref-${f.key}`}
+ data-testid={`product-ref-${f.key}`}
+ className="h-9"
+ value={valueOf(f.key)}
+ onChange={(e) => setRef(f.key, e.target.value)}
+ maxLength={100}
+ />
+ </div>
+ ))}
+ {extra.map((r) => (
+ <div key={r.key} className="space-y-1.5">
+ <Label htmlFor={`ref-${r.key}`} className="text-xs">{t(`fiscal.productField.${r.key}`, r.key)}</Label>
+ <Input
+ id={`ref-${r.key}`}
+ data-testid={`product-ref-${r.key}`}
+ className="h-9"
+ value={r.value}
+ onChange={(e) => setRef(r.key, e.target.value)}
+ maxLength={100}
+ />
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center gap-2">
+ <Input
+ className="h-8 w-48"
+ placeholder={t('invoices.products.field.customRefKey')}
+ value={customKey}
+ onChange={(e) => setCustomKey(e.target.value)}
+ data-testid="product-ref-custom-key"
+ maxLength={40}
+ />
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={!/^[a-z][a-z0-9_]*$/.test(customKey.trim().toLowerCase()) || refs.some((r) => r.key === customKey.trim().toLowerCase())}
+ onClick={() => {
+ setRef(customKey.trim().toLowerCase(), '')
+ setCustomKey('')
+ }}
+ data-testid="product-ref-add"
+ >
+ <Plus className="h-3.5 w-3.5 mr-1" />
+ {t('invoices.products.field.addRef')}
+ </Button>
+ </div>
+ </div>
+ )
+ })()}
+
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <Label>{t('invoices.products.field.prices')}</Label>
+ <Button size="sm" variant="ghost" onClick={() => setPrices([...prices, blankPrice(defaultCurrency)])} data-testid="product-add-price">
+ <Plus className="h-3.5 w-3.5 mr-1" />
+ {t('invoices.products.field.addPrice')}
+ </Button>
+ </div>
+ <p className="text-[11px] text-muted-foreground">{t('invoices.products.field.pricesHint')}</p>
+ <div className="rounded-lg border border-border divide-y divide-border">
+ {prices.map((row, index) => (
+ <div key={row.id ?? `new-${index}`} className={cn('grid grid-cols-2 sm:grid-cols-[7rem_1fr_9rem_8rem_2rem] gap-2 px-3 py-2.5 items-center', !row.active && 'opacity-60')} data-testid="product-price-row">
+ <CurrencySelect id={`price-currency-${index}`} value={row.currency} onChange={(code) => updatePrice(index, { currency: code })} />
+ <Input
+ className="h-9 text-right"
+ inputMode="decimal"
+ placeholder="0.00"
+ value={row.unit_price}
+ onChange={(e) => updatePrice(index, { unit_price: e.target.value })}
+ data-testid={`price-amount-${index}`}
+ aria-label={t('invoices.field.unitPrice')}
+ />
+ <Select
+ value={row.billing === 'recurring' ? row.interval || 'recurring' : 'one_time'}
+ onValueChange={(v) =>
+ v === 'one_time'
+ ? updatePrice(index, { billing: 'one_time', interval: '' })
+ : updatePrice(index, { billing: 'recurring', interval: v === 'recurring' ? '' : (v as InvoiceScheduleFrequency) })
+ }
+ >
+ <SelectTrigger data-testid={`price-billing-${index}`}><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="one_time">{t('invoices.products.billing.one_time')}</SelectItem>
+ {FREQUENCIES.map((f) => (
+ <SelectItem key={f} value={f}>{t('invoices.products.billing.every', { interval: t(`invoices.products.per.${f}`) })}</SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Input
+ className="h-9"
+ placeholder={t('invoices.products.field.nickname')}
+ value={row.nickname}
+ onChange={(e) => updatePrice(index, { nickname: e.target.value })}
+ data-testid={`price-nickname-${index}`}
+ maxLength={100}
+ />
+ {/* A new row is simply dropped. An existing price is
+ archived instead: invoices may already name it, and
+ the picker stops offering it either way. */}
+ {row.id ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
+ onClick={() => updatePrice(index, { active: !row.active })}
+ data-testid={`price-${row.active ? 'archive' : 'restore'}-${index}`}
+ aria-label={row.active ? t('invoices.products.action.archive') : t('invoices.products.action.restore')}
+ >
+ {row.active ? <Archive className="h-4 w-4" /> : <ArchiveRestore className="h-4 w-4" />}
+ </Button>
+ ) : (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive"
+ onClick={() => setPrices(prices.filter((_, i) => i !== index))}
+ data-testid={`price-remove-${index}`}
+ aria-label={t('common.delete')}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ )}
+ {showTax && (
+ <div className="col-span-2 sm:col-span-5 flex items-center gap-2">
+ <span className="text-[11px] text-muted-foreground">{t('invoices.field.taxRate')}</span>
+ <Input className="h-8 w-20 text-right" inputMode="decimal" placeholder="%" value={row.tax_rate} onChange={(e) => updatePrice(index, { tax_rate: e.target.value })} data-testid={`price-tax-${index}`} />
+ </div>
+ )}
+ </div>
+ ))}
+ {prices.length === 0 && (
+ <p className="px-3 py-3 text-xs text-muted-foreground">{t('invoices.products.field.noPrices')}</p>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <DialogFooter className="gap-2">
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>
+ <Button onClick={() => mutation.mutate()} disabled={!ready || mutation.isPending} data-testid="product-save">
+ {product ? t('common.save') : t('common.create')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 26884f4b..5356366d 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -1066,6 +1066,11 @@ export type InvoiceState =
export interface InvoiceLine {
id: string
+ /** Where the line came from, when it came from the catalog. The
+ * values below are still the line's own copy. */
+ product_id: string | null
+ price_id: string | null
+ fiscal_refs: Record<string, string> | null
description: string
quantity: string
unit: string | null
@@ -1083,6 +1088,65 @@ export interface InvoiceLineInput {
unit?: string | null
unit_price: string
tax_rate?: string | null
+ /** Set when the line was filled from a product. Kept when the person
+ * then edits the values: it is still that product, at their price. */
+ product_id?: string | null
+ price_id?: string | null
+ /** Fiscal references for the line. Filled from the product by the
+ * server when omitted. */
+ fiscal_refs?: Record<string, string> | null
+}
+
+// ---------------------------------------------------------------------------
+// Catalog
+// ---------------------------------------------------------------------------
+
+export type ProductKind = 'service' | 'product'
+export type PriceBilling = 'one_time' | 'recurring'
+
+export interface ProductPrice {
+ id: string
+ product_id: string
+ currency: string
+ unit_price: string
+ tax_rate: string | null
+ billing: PriceBilling
+ interval: InvoiceScheduleFrequency | null
+ nickname: string | null
+ /** A name of the workspace's own choosing, unique among its prices. */
+ lookup_key: string | null
+ active: boolean
+ external_source: string | null
+ external_id: string | null
+ created_at: string
+}
+
+/** A fiscal reference the workspace's jurisdiction suggests on a product. */
+export interface ProductFieldSpec {
+ key: string
+ label_key: string
+ /** Which product kinds it applies to; empty means both. */
+ kinds: ProductKind[]
+}
+
+export interface Product {
+ id: string
+ name: string
+ description: string | null
+ kind: ProductKind
+ unit: string | null
+ active: boolean
+ origin: string
+ external_source: string | null
+ external_id: string | null
+ custom_fields: Record<string, string> | null
+ /** Fiscal references keyed as the jurisdiction suggests (`ncm`,
+ * `service_code`, `hs_code`...); any key is accepted. */
+ fiscal_refs: Record<string, string> | null
+ prices: ProductPrice[]
+ created_at: string
+ /** Derived by the server: how many invoices name this product. */
+ invoice_count: number
}
export interface InvoiceAllocation {