Skip to content

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

Payment matching (#817)

Tássio Noronha6c8fe7e114ec
diff --git a/backend/alembic/versions/086_reconciliation_rules_and_suggestions.py b/backend/alembic/versions/086_reconciliation_rules_and_suggestions.py
new file mode 100644
index 00000000..1fda9080
--- /dev/null
+++ b/backend/alembic/versions/086_reconciliation_rules_and_suggestions.py
@@ -0,0 +1,150 @@
+"""matching rules a workspace can change, and the doubtful space
+
+Two tables that make reconciliation something a person can see and argue
+with rather than something the code decides on their behalf.
+
+ - `reconciliation_rules` stores **only what a workspace changed**. The
+ rules ship with the image; copying them in here at workspace creation
+ would freeze them, and a better default would never reach anyone who
+ had already opened the page.
+ - `reconciliation_suggestions` stores the matches that are plausible
+ without being certain. `declined` is a stored status on purpose:
+ without it, a suggestion somebody rejected returns on the next sync.
+
+Revision ID: 085
+Revises: 084
+"""
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+revision = "086"
+down_revision = "085"
+branch_labels = None
+depends_on = None
+
+#: jsonb where it exists, JSON elsewhere. Matching reads these on every
+#: transaction, so on Postgres they should be the queryable type.
+_JSON = sa.JSON().with_variant(postgresql.JSONB(), "postgresql")
+
+
+def upgrade() -> None:
+ op.create_table(
+ "reconciliation_rules",
+ 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("node", sa.String(length=64), nullable=False),
+ sa.Column("strategy_id", sa.String(length=64), nullable=False),
+ sa.Column(
+ "origin", sa.String(length=16), nullable=False, server_default="default"
+ ),
+ sa.Column("name", sa.String(length=120), nullable=True),
+ sa.Column("position", sa.Integer(), nullable=True),
+ sa.Column("config", _JSON, nullable=False, server_default="{}"),
+ sa.Column(
+ "policy_version", sa.Integer(), nullable=False, server_default="1"
+ ),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.Column(
+ "updated_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "workspace_id", "node", "strategy_id", name="uq_reconciliation_rule_strategy"
+ ),
+ sa.CheckConstraint(
+ "origin IN ('default', 'custom')", name="ck_reconciliation_rule_origin"
+ ),
+ )
+ op.create_index(
+ "ix_reconciliation_rules_workspace_id", "reconciliation_rules", ["workspace_id"]
+ )
+ op.create_index(
+ "ix_reconciliation_rules_workspace_node",
+ "reconciliation_rules",
+ ["workspace_id", "node"],
+ )
+
+ op.create_table(
+ "reconciliation_suggestions",
+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("transaction_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("expectation_kind", sa.String(length=16), nullable=False),
+ sa.Column("expectation_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("strategy_id", sa.String(length=64), nullable=False),
+ sa.Column("node", sa.String(length=64), nullable=False),
+ sa.Column("amount", sa.Numeric(precision=15, scale=2), nullable=False),
+ sa.Column("scores", _JSON, nullable=False, server_default="{}"),
+ sa.Column(
+ "status", sa.String(length=16), nullable=False, server_default="pending"
+ ),
+ sa.Column("resolved_at", sa.DateTime(timezone=True), nullable=True),
+ sa.Column("resolved_by", postgresql.UUID(as_uuid=True), nullable=True),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),
+ sa.ForeignKeyConstraint(
+ ["transaction_id"], ["transactions.id"], ondelete="CASCADE"
+ ),
+ sa.ForeignKeyConstraint(["resolved_by"], ["users.id"]),
+ sa.PrimaryKeyConstraint("id"),
+ sa.UniqueConstraint(
+ "workspace_id",
+ "transaction_id",
+ "expectation_kind",
+ "expectation_id",
+ name="uq_reconciliation_suggestion_pair",
+ ),
+ sa.CheckConstraint(
+ "status IN ('pending', 'accepted', 'declined', 'expired')",
+ name="ck_reconciliation_suggestion_status",
+ ),
+ sa.CheckConstraint(
+ "expectation_kind IN ('invoice', 'recurring')",
+ name="ck_reconciliation_suggestion_kind",
+ ),
+ )
+ op.create_index(
+ "ix_reconciliation_suggestions_workspace_id",
+ "reconciliation_suggestions",
+ ["workspace_id"],
+ )
+ op.create_index(
+ "ix_reconciliation_suggestions_transaction_id",
+ "reconciliation_suggestions",
+ ["transaction_id"],
+ )
+ op.create_index(
+ "ix_reconciliation_suggestions_expectation_id",
+ "reconciliation_suggestions",
+ ["expectation_id"],
+ )
+ op.create_index(
+ "ix_reconciliation_suggestions_status", "reconciliation_suggestions", ["status"]
+ )
+ op.create_index(
+ "ix_reconciliation_suggestions_open",
+ "reconciliation_suggestions",
+ ["workspace_id", "status", "created_at"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("reconciliation_suggestions")
+ op.drop_table("reconciliation_rules")
diff --git a/backend/alembic/versions/087_suggestion_groups.py b/backend/alembic/versions/087_suggestion_groups.py
new file mode 100644
index 00000000..8b780e3d
--- /dev/null
+++ b/backend/alembic/versions/087_suggestion_groups.py
@@ -0,0 +1,44 @@
+"""a suggestion that names several invoices at once
+
+One payment can settle several invoices: a client clearing three of
+their own in a transfer, a commercial arrangement paying a month at once.
+When the engine is sure, it writes them all. When it is not, the question
+it asks has to be the whole question: *does this payment cover these
+three?* Not three separate questions a person could answer inconsistently
+and end up with a payment spread across two debts and short on a third.
+
+So a suggestion may belong to a group, and a group is accepted or
+declined as one thing. Null for the ordinary single-invoice case, which
+is most of them.
+
+Revision ID: 086
+Revises: 085
+"""
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+revision = "087"
+down_revision = "086"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "reconciliation_suggestions",
+ sa.Column("group_id", postgresql.UUID(as_uuid=True), nullable=True),
+ )
+ # The queue reads a group whole, every time it reads one at all.
+ op.create_index(
+ "ix_reconciliation_suggestions_group",
+ "reconciliation_suggestions",
+ ["group_id"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index(
+ "ix_reconciliation_suggestions_group", table_name="reconciliation_suggestions"
+ )
+ op.drop_column("reconciliation_suggestions", "group_id")
diff --git a/backend/alembic/versions/088_reconciliation_events.py b/backend/alembic/versions/088_reconciliation_events.py
new file mode 100644
index 00000000..1353b896
--- /dev/null
+++ b/backend/alembic/versions/088_reconciliation_events.py
@@ -0,0 +1,88 @@
+"""a chronological record of what matching did
+
+Most of this is already stored, and that is the point of keeping the
+table small. An automatic link is an `invoice_allocations` row with the
+rule id in `method` and a timestamp; an answered suggestion is a
+`reconciliation_suggestions` row with a status and who resolved it.
+Reading a history out of the two means joining tables with different
+shapes and no common ordering, which is the friction rather than the
+missing data.
+
+One thing genuinely leaves no trace today: **undoing a link deletes the
+row**, so a match that was made and then reversed is indistinguishable
+from one that never happened. That is the event this table exists for
+first, and the reason the others are copied here is so the stream reads
+in one order rather than two.
+
+Deliberately **not** a log of everything the engine considered. A sync of
+three hundred transactions where two hundred and ninety match nothing
+would write two hundred and ninety rows saying so, and a history nobody
+can scan is the same as no history.
+
+Revision ID: 087
+Revises: 086
+"""
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects import postgresql
+
+revision = "088"
+down_revision = "087"
+branch_labels = None
+depends_on = None
+
+_JSON = sa.JSON().with_variant(postgresql.JSONB(), "postgresql")
+
+
+def upgrade() -> None:
+ op.create_table(
+ "reconciliation_events",
+ sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("workspace_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column(
+ "at",
+ sa.DateTime(timezone=True),
+ server_default=sa.text("now()"),
+ nullable=False,
+ ),
+ sa.Column("action", sa.String(length=16), nullable=False),
+ # SET NULL rather than CASCADE: a deleted transaction should not
+ # erase the record that something was once matched to it. The
+ # history is the one place that has to survive the tidying up.
+ sa.Column("transaction_id", postgresql.UUID(as_uuid=True), nullable=True),
+ sa.Column("expectation_kind", sa.String(length=16), nullable=False),
+ sa.Column("expectation_id", postgresql.UUID(as_uuid=True), nullable=False),
+ sa.Column("amount", sa.Numeric(precision=15, scale=2), nullable=False),
+ sa.Column("strategy_id", sa.String(length=64), nullable=True),
+ # Null means the system did it on its own, which is the difference
+ # a reader most often wants: was this me, or was this the rules?
+ sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=True),
+ sa.Column("detail", _JSON, nullable=False, server_default="{}"),
+ sa.ForeignKeyConstraint(["workspace_id"], ["workspaces.id"], ondelete="CASCADE"),
+ sa.ForeignKeyConstraint(
+ ["transaction_id"], ["transactions.id"], ondelete="SET NULL"
+ ),
+ sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
+ sa.PrimaryKeyConstraint("id"),
+ sa.CheckConstraint(
+ "action IN ('linked', 'suggested', 'accepted', 'declined',"
+ " 'expired', 'unlinked')",
+ name="ck_reconciliation_event_action",
+ ),
+ )
+ # The only two ways this is ever read: the workspace's stream, newest
+ # first, and everything that happened to one promise.
+ op.create_index(
+ "ix_reconciliation_events_stream",
+ "reconciliation_events",
+ ["workspace_id", "at"],
+ )
+ op.create_index(
+ "ix_reconciliation_events_expectation",
+ "reconciliation_events",
+ ["expectation_id"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("reconciliation_events")
diff --git a/backend/alembic/versions/089_reconciliation_rule_deleted.py b/backend/alembic/versions/089_reconciliation_rule_deleted.py
new file mode 100644
index 00000000..9f3fa024
--- /dev/null
+++ b/backend/alembic/versions/089_reconciliation_rule_deleted.py
@@ -0,0 +1,39 @@
+"""letting a workspace delete a rule that ships with the product
+
+Shipped rules are a document in the image, not rows in the database, so
+there is nothing to delete. That is what makes them keep improving with
+the product, and it also meant a workspace could turn one off but never
+be rid of it, which reads as us knowing better than the person whose
+money it is.
+
+So the row that already records "I changed this rule" learns to record
+"I do not want this rule". A tombstone: the strategy still ships, this
+workspace no longer runs it, and the page can offer it back because we
+still know its name.
+
+The column is not null with a false default, so every existing override
+means exactly what it meant yesterday.
+"""
+import sqlalchemy as sa
+from alembic import op
+
+revision = "089"
+down_revision = "088"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "reconciliation_rules",
+ sa.Column(
+ "deleted",
+ sa.Boolean(),
+ nullable=False,
+ server_default=sa.false(),
+ ),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("reconciliation_rules", "deleted")
diff --git a/backend/app/api/invoices.py b/backend/app/api/invoices.py
index e73d86ab..5931ef49 100644
--- a/backend/app/api/invoices.py
+++ b/backend/app/api/invoices.py
@@ -15,6 +15,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, UploadFi
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_async_session
+from app.models.invoice import Invoice
from app.models.workspace import Workspace
from app.core.module_gate import require_module, require_module_write
from app.core.workspace_context import WorkspaceContext
@@ -33,11 +34,14 @@ from app.schemas.invoice import (
ShareLinkRead,
)
from app.services import (
+ invoice_archive,
invoice_attachment_service,
invoice_logo_service,
invoice_document,
invoice_pdf,
invoice_service,
+ reconciliation_history_service,
+ reconciliation_service,
)
from app.services.invoice_service import InvoiceError
from app.services.module_service import ModuleId
@@ -211,6 +215,32 @@ async def list_invoices(
return [_serialize(inv) for inv in invoices]
+async def _settle_from_money_already_there(
+ session: AsyncSession, invoice: Invoice
+) -> None:
+ """Look back at payments that arrived before this document existed.
+
+ The client pays, and the nota follows days later: common enough here
+ that a matcher which only looked forward would miss a good share of
+ the traffic. Nothing about the money changes when the invoice is
+ written, so this is the only moment anything would re-examine it.
+
+ Called from the router rather than from `invoice_service`, which
+ matching already depends on. Failing to find a match is the ordinary
+ outcome and never affects the response.
+
+ **Committed either way.** Looking back can end in a link, in a
+ question for the queue, or in nothing, and only the first of those
+ returns anything. Committing on the return value alone threw away
+ every suggestion this moment raised, which is the outcome that needed
+ saving most: a rule set to suggest would have done nothing here while
+ doing its job on the other trigger, the exact silent switch the queue
+ exists to prevent.
+ """
+ await reconciliation_service.match_for_invoice(session, invoice)
+ await session.commit()
+
+
@router.post("", response_model=InvoiceRead, status_code=status.HTTP_201_CREATED)
async def create_invoice(
payload: InvoiceCreate,
@@ -228,7 +258,15 @@ async def create_invoice(
raise _http(exc)
await session.commit()
invoice = await _load(session, invoice.id, ctx.workspace.id)
- return _serialize(invoice)
+ # A workspace that opens invoices on creation issues them here, so the
+ # document has to be filed here too. Both doors, or the one that is
+ # missed silently goes back to a PDF that drifts.
+ await invoice_archive.file_issued_document(
+ session, invoice, ctx.workspace, ctx.user_id
+ )
+ await session.commit()
+ await _settle_from_money_already_there(session, invoice)
+ return _serialize(await _load(session, invoice.id, ctx.workspace.id))
@router.get("/{invoice_id}", response_model=InvoiceRead)
@@ -289,6 +327,16 @@ async def issue_invoice(
except InvoiceError as exc:
raise _http(exc)
await session.commit()
+ # Filed while the figures still say what was sent. From here the
+ # answer to "what did we send" is a stored file rather than a
+ # re-rendering that depends on what has happened since.
+ await invoice_archive.file_issued_document(
+ session, invoice, ctx.workspace, ctx.user_id
+ )
+ await session.commit()
+ await _settle_from_money_already_there(
+ session, await _load(session, invoice_id, ctx.workspace.id)
+ )
return _serialize(await _load(session, invoice_id, ctx.workspace.id))
@@ -349,9 +397,26 @@ async def create_allocation(
):
invoice = await _load(session, invoice_id, ctx.workspace.id)
try:
- await invoice_service.allocate(session, invoice, payload.transaction_id, payload.amount)
+ allocation = await invoice_service.allocate(
+ session, invoice, payload.transaction_id, payload.amount
+ )
except InvoiceError as exc:
raise _http(exc)
+ # `linked` with a user is a person doing it by hand; `linked` with none
+ # is the rules acting on their own. One verb, and the column that
+ # already answers the question the history is organised around.
+ # Without this the stream could show an unlink with no link before it.
+ await reconciliation_history_service.record(
+ session,
+ ctx.workspace.id,
+ "linked",
+ expectation_kind="invoice",
+ expectation_id=invoice.id,
+ amount=allocation.amount,
+ transaction_id=payload.transaction_id,
+ strategy_id=allocation.method,
+ user_id=ctx.user_id,
+ )
await session.commit()
return _serialize(await _load(session, invoice_id, ctx.workspace.id))
@@ -364,10 +429,26 @@ async def remove_allocation(
session: AsyncSession = Depends(get_async_session),
):
invoice = await _load(session, invoice_id, ctx.workspace.id)
+ # Read before it goes: unallocating deletes the row, so without this
+ # the fact that a match was made and then undone is indistinguishable
+ # from one that was never made at all.
+ undone = next((a for a in invoice.allocations if a.id == allocation_id), None)
try:
await invoice_service.unallocate(session, invoice, allocation_id)
except InvoiceError as exc:
raise _http(exc)
+ if undone is not None:
+ await reconciliation_history_service.record(
+ session,
+ ctx.workspace.id,
+ "unlinked",
+ expectation_kind="invoice",
+ expectation_id=invoice.id,
+ amount=undone.amount,
+ transaction_id=undone.transaction_id,
+ strategy_id=undone.method,
+ user_id=ctx.user_id,
+ )
await session.commit()
return _serialize(await _load(session, invoice_id, ctx.workspace.id))
diff --git a/backend/app/api/reconciliation.py b/backend/app/api/reconciliation.py
new file mode 100644
index 00000000..6fe252b5
--- /dev/null
+++ b/backend/app/api/reconciliation.py
@@ -0,0 +1,601 @@
+"""The matching rules, and the questions matching could not answer.
+
+Two surfaces that belong together: the rules decide, and the queue is
+where a decision was not confident enough to be made alone. Seeing them
+side by side is the point: somebody staring at a long queue should be
+one click from the rule that keeps sending things there.
+
+Gated on the invoices module, and every route in it answers 404 rather
+than 403: a workspace without the module should not be able to tell the
+feature is there.
+
+It was not always. While the recurring rules were editable here too, the
+router served a personal workspace something real, so it stayed open and
+the invoice set carried an "inactive" flag as the honest signal. Those
+rules left the page (they decide whether an arriving charge is a row we
+generated ourselves, which is bookkeeping about our own duplicates), and
+what is left decides whose money settles which invoice. A personal
+workspace could still write, reorder and import matching rules that could
+never fire, which is configuration accumulating for a module nobody has.
+"""
+import uuid
+from decimal import Decimal
+from typing import Optional
+
+from fastapi import APIRouter, Depends, HTTPException, status
+from fastapi.responses import JSONResponse
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.database import get_async_session
+from app.core.module_gate import require_any_module, require_any_module_write
+from app.core.workspace_context import WorkspaceContext
+from app.models.invoice import Invoice
+from app.models.reconciliation import ReconciliationRule
+from app.models.recurring_transaction import RecurringTransaction
+from app.models.transaction import Transaction
+from app.schemas.reconciliation import (
+ DiscardedRuleRead,
+ ReconciliationImportRequest,
+ ReconciliationImportResponse,
+ ReconciliationNodeRead,
+ ReconciliationRuleCreate,
+ ReconciliationRuleRead,
+ ReconciliationOrder,
+ ReconciliationRuleUpdate,
+ HistoryEventRead,
+ SuggestionCovers,
+ SuggestionRead,
+)
+from app.services import (
+ invoice_service,
+ reconciliation_history_service as history,
+ reconciliation_portability as portability,
+ reconciliation_rule_service as rules,
+ reconciliation_suggestion_service as suggestions,
+)
+from app.services.module_service import ModuleId, resolve_modules
+
+router = APIRouter(prefix="/api/reconciliation", tags=["reconciliation"])
+
+#: Reaching the router at all takes one of the two, because the sets it
+#: serves belong to different modules: a workspace with recurring bills
+#: and no invoicing has real rules here. Which *set* you may touch is a
+#: second question, asked per node by `_assert_node`.
+_MATCHING_MODULES = (ModuleId.INVOICES, ModuleId.RECURRING)
+_read = require_any_module(*_MATCHING_MODULES)
+_write = require_any_module_write(*_MATCHING_MODULES)
+
+
+def _assert_node(ctx: WorkspaceContext, node: str) -> None:
+ """Refuse a set this workspace does not have, the same way as a route.
+
+ 404 rather than 403, matching the module gate above: a workspace
+ without invoicing should not learn that invoice matching exists by
+ being told it may not touch it.
+ """
+ if node not in rules.nodes_for(resolve_modules(ctx.workspace)):
+ raise HTTPException(status_code=404, detail="Not found")
+
+
+def _http(error: rules.RuleError) -> HTTPException:
+ return HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={"code": error.code, "message": error.message},
+ )
+
+
+def _as_read(node: str, strategy: dict, position: int) -> ReconciliationRuleRead:
+ return ReconciliationRuleRead(
+ id=strategy["id"],
+ node=node,
+ name=strategy.get("name"),
+ origin=strategy.get("origin", "default"),
+ customised=bool(strategy.get("customised")),
+ enabled=bool(strategy.get("enabled", True)),
+ outcome=strategy.get("outcome", "suggest"),
+ trigger=strategy.get("trigger", "money_arrives"),
+ when=strategy.get("when", {}),
+ position=position,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Rules
+# ---------------------------------------------------------------------------
[email protected]("/rules", response_model=list[ReconciliationNodeRead])
+async def list_rules(
+ ctx: WorkspaceContext = Depends(_read),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Every rule this workspace runs, in the order they are tried.
+
+ Shipped ∪ changed, composed on read. Nothing here is stored as a list
+ of rules: that is what keeps an untouched rule improving when we
+ improve it.
+ """
+ out: list[ReconciliationNodeRead] = []
+ for node in rules.nodes_for(resolve_modules(ctx.workspace)):
+ policy = await rules.resolve(session, ctx.workspace.id, node)
+ out.append(
+ ReconciliationNodeRead(
+ node=node,
+ # Structural now: reaching this route at all means the
+ # module is on, so a set that is listed is a set that
+ # runs. The flag stays on the wire for the day a node
+ # depends on something else.
+ active=True,
+ rules=[
+ _as_read(node, strategy, index)
+ for index, strategy in enumerate(policy["strategies"])
+ ],
+ discarded=[
+ DiscardedRuleRead(**item) for item in policy.get("discarded", [])
+ ],
+ )
+ )
+ return out
+
+
[email protected]("/rules/{node}/{strategy_id}", response_model=ReconciliationRuleRead)
+async def update_rule(
+ node: str,
+ strategy_id: str,
+ payload: ReconciliationRuleUpdate,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Change a rule: one we ship, or one the workspace wrote."""
+ _assert_node(ctx, node)
+ data = payload.model_dump(exclude_unset=True)
+ position = data.pop("position", None)
+ existing = await _find_custom(session, ctx.workspace.id, node, strategy_id)
+
+ try:
+ if existing is not None:
+ merged = {**existing.config, **data}
+ await rules.update_custom(session, existing, config=merged, position=position)
+ else:
+ await rules.upsert_override(
+ session,
+ ctx.workspace.id,
+ ctx.user_id,
+ node,
+ strategy_id,
+ data,
+ position=position,
+ )
+ except rules.RuleError as exc:
+ raise _http(exc)
+
+ await session.commit()
+ return await _one(session, ctx.workspace.id, node, strategy_id)
+
+
+ "/rules/{node}/order", response_model=list[ReconciliationRuleRead]
+)
+async def reorder_rules(
+ node: str,
+ payload: ReconciliationOrder,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Set the order rules are tried in.
+
+ The first rule that matches wins, so this is not cosmetic: it is how a
+ band is expressed: *link under two per cent, ask between two and
+ five* is one rule placed above another, with no lower bound written
+ anywhere.
+ """
+ _assert_node(ctx, node)
+ try:
+ await rules.reorder(
+ session, ctx.workspace.id, ctx.user_id, node, payload.order
+ )
+ except rules.RuleError as exc:
+ raise _http(exc)
+ await session.commit()
+
+ policy = await rules.resolve(session, ctx.workspace.id, node)
+ return [
+ _as_read(node, strategy, index)
+ for index, strategy in enumerate(policy["strategies"])
+ ]
+
+
+ "/rules", response_model=ReconciliationRuleRead, status_code=status.HTTP_201_CREATED
+)
+async def create_rule(
+ payload: ReconciliationRuleCreate,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ _assert_node(ctx, payload.node)
+ try:
+ row = await rules.create_custom(
+ session,
+ ctx.workspace.id,
+ ctx.user_id,
+ payload.node,
+ payload.name,
+ {
+ "enabled": payload.enabled,
+ "outcome": payload.outcome,
+ "trigger": payload.trigger,
+ "when": payload.when,
+ },
+ position=payload.position,
+ )
+ except rules.RuleError as exc:
+ raise _http(exc)
+
+ await session.commit()
+ return await _one(session, ctx.workspace.id, payload.node, row.strategy_id)
+
+
[email protected]("/rules/{node}/{strategy_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_rule(
+ node: str,
+ strategy_id: str,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Get rid of a rule, including one of ours.
+
+ There is no rule we refuse to remove. What happens underneath differs:
+ a workspace's own rule is a row and goes; one of ours is a document
+ in the image, so a tombstone records that this workspace does not run
+ it, but that is our problem, not something to make a person learn.
+ """
+ _assert_node(ctx, node)
+ try:
+ await rules.delete_rule(session, ctx.workspace.id, node, strategy_id)
+ except rules.RuleError as exc:
+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=exc.message)
+ await session.commit()
+
+
[email protected]("/rules/{node}/{strategy_id}/reset", status_code=status.HTTP_204_NO_CONTENT)
+async def reset_rule(
+ node: str,
+ strategy_id: str,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Forget everything this workspace did to one of our rules.
+
+ One verb for every kind of disagreement, because they are all the same
+ row: a threshold somebody moved, a place in the order, and a rule
+ somebody deleted all go back together. What comes back is whatever we
+ ship *today*, not what shipped the day it was changed.
+ """
+ _assert_node(ctx, node)
+ await rules.reset(session, ctx.workspace.id, node, strategy_id)
+ await session.commit()
+
+
+# ---------------------------------------------------------------------------
+# Carrying a policy elsewhere
+# ---------------------------------------------------------------------------
[email protected]("/rules/export")
+async def export_rules(
+ ctx: WorkspaceContext = Depends(_read),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """The matching policy as a file, with ids resolved to names."""
+ payload = await portability.export_policy(
+ session, ctx.workspace.id, rules.nodes_for(resolve_modules(ctx.workspace))
+ )
+ return JSONResponse(
+ content=payload,
+ headers={
+ "Content-Disposition": 'attachment; filename="securo-reconciliation-rules.json"',
+ },
+ )
+
+
[email protected]("/rules/import", response_model=ReconciliationImportResponse)
+async def import_rules(
+ data: ReconciliationImportRequest,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ try:
+ result = await portability.import_policy(
+ session,
+ ctx.workspace.id,
+ ctx.user_id,
+ data.payload,
+ overwrite=data.overwrite,
+ nodes=rules.nodes_for(resolve_modules(ctx.workspace)),
+ )
+ except rules.ExistingPolicyError as exc:
+ # 409 rather than 400: nothing is wrong with the file, and the
+ # answer is a question for the person rather than a correction.
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
+ except rules.RuleError as exc:
+ # The same shape as every other error here, code included: "12
+ # imported, 40 skipped" does not say what was wrong with the file,
+ # and a refusal that cannot name its reason is a refusal nobody
+ # can act on.
+ raise _http(exc)
+ await session.commit()
+ return ReconciliationImportResponse(**result)
+
+
+async def _find_custom(
+ session: AsyncSession, workspace_id: uuid.UUID, node: str, strategy_id: str
+):
+ result = await session.execute(
+ select(ReconciliationRule).where(
+ ReconciliationRule.workspace_id == workspace_id,
+ ReconciliationRule.node == node,
+ ReconciliationRule.strategy_id == strategy_id,
+ ReconciliationRule.origin == "custom",
+ )
+ )
+ return result.scalar_one_or_none()
+
+
+async def _one(
+ session: AsyncSession, workspace_id: uuid.UUID, node: str, strategy_id: str
+) -> ReconciliationRuleRead:
+ policy = await rules.resolve(session, workspace_id, node)
+ for index, strategy in enumerate(policy["strategies"]):
+ if strategy["id"] == strategy_id:
+ return _as_read(node, strategy, index)
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Rule not found")
+
+
+# ---------------------------------------------------------------------------
+# The doubtful space
+# ---------------------------------------------------------------------------
[email protected]("/suggestions", response_model=list[SuggestionRead])
+async def list_suggestions(
+ ctx: WorkspaceContext = Depends(_read),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Matches nobody has answered yet, oldest first.
+
+ Stale ones are retired on the way in rather than by a scheduled job:
+ the queue is small, this is the only place it is read, and a nightly
+ task that exists solely to change a string is a moving part with no
+ reason to exist.
+ """
+ await suggestions.expire_stale(session, ctx.workspace.id)
+ await session.commit()
+
+ rows = await suggestions.open_for(session, ctx.workspace.id)
+
+ # One row per *question*. A payment offered against three invoices is
+ # one thing to decide, and listing it three times would invite exactly
+ # the inconsistent answer the grouping exists to prevent.
+ seen: set[uuid.UUID] = set()
+ out = []
+ for row in rows:
+ if row.group_id is not None:
+ if row.group_id in seen:
+ continue
+ seen.add(row.group_id)
+ out.append(await _with_label(session, row))
+ return out
+
+
[email protected]("/suggestions/{suggestion_id}/accept", response_model=SuggestionRead)
+async def accept_suggestion(
+ suggestion_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Take the match, and write it the way its kind is written.
+
+ An invoice gets an allocation; a recurring bill gets the charge bound
+ to it. The two are genuinely different writes, which is why the
+ suggestion service marks and this route links.
+
+ **A payment offered against several invoices is accepted whole.** The
+ question was "does this cover these three", so answering it two thirds
+ of the way would leave the payment short on the rest with nothing
+ having warned anybody. All the writes happen inside one savepoint: if
+ the last invoice refuses, the first two are not left standing.
+ """
+ row = await suggestions.get(session, ctx.workspace.id, suggestion_id)
+ if row is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail="Suggestion not found"
+ )
+ if row.status != "pending":
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={"code": "already_answered", "message": "This one is already settled"},
+ )
+
+ members = await suggestions.members_of(session, row)
+ try:
+ async with session.begin_nested():
+ for member in members:
+ await _settle(session, ctx, member)
+ except invoice_service.InvoiceError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={"code": exc.code, "message": str(exc)},
+ )
+
+ for member in members:
+ await suggestions.mark_accepted(session, member, ctx.user_id)
+ # One event for the whole question, written where the whole act is known.
+ await suggestions.answered(session, members, "accepted", ctx.user_id)
+ await session.commit()
+ return await _with_label(session, row)
+
+
+async def _settle(
+ session: AsyncSession, ctx: WorkspaceContext, row
+) -> None:
+ """Write one member of an accepted question."""
+ if row.expectation_kind == "invoice":
+ invoice = await session.get(Invoice, row.expectation_id)
+ if invoice is None or invoice.workspace_id != ctx.workspace.id:
+ raise invoice_service.InvoiceError(
+ "invoice_missing", "The invoice is no longer there"
+ )
+ await invoice_service.allocate(
+ session,
+ invoice,
+ row.transaction_id,
+ amount=row.amount,
+ # The rule that suggested it, not "manual": the person agreed
+ # with a specific rule, and that is worth keeping.
+ method=row.strategy_id,
+ )
+ return
+
+ bill = await session.get(RecurringTransaction, row.expectation_id)
+ if bill is None or bill.workspace_id != ctx.workspace.id:
+ raise invoice_service.InvoiceError(
+ "bill_missing", "The recurring bill is no longer there"
+ )
+ from app.services import recurring_match_service
+
+ transaction = row.transaction
+ transaction.recurring_transaction_id = bill.id
+ recurring_match_service.advance_past(bill, transaction.date)
+
+
[email protected]("/suggestions/{suggestion_id}/decline", response_model=SuggestionRead)
+async def decline_suggestion(
+ suggestion_id: uuid.UUID,
+ ctx: WorkspaceContext = Depends(_write),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """Say no. The rows stay, so this pair is never offered again.
+
+ A grouped question is refused whole, for the same reason it is
+ accepted whole: it was one question."""
+ row = await suggestions.get(session, ctx.workspace.id, suggestion_id)
+ if row is None:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND, detail="Suggestion not found"
+ )
+ if row.status != "pending":
+ # The same guard accepting already has. Without it a decline
+ # arriving after an accept would mark the row declined and write
+ # a second history event while `_settle`'s allocation stayed
+ # exactly where it was: a suggestion reading "dismissed" on top of
+ # an invoice it had settled.
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={
+ "code": "already_answered",
+ "message": "This one is already settled",
+ },
+ )
+ members = await suggestions.members_of(session, row)
+ for member in members:
+ await suggestions.decline(session, member, ctx.user_id)
+ await suggestions.answered(session, members, "declined", ctx.user_id)
+ await session.commit()
+ return await _with_label(session, row)
+
+
+async def _invoice_name(session: AsyncSession, invoice: Invoice) -> Optional[str]:
+ """The number as the client would recognise it.
+
+ Mirrors what every invoice screen shows, and for the same reason: the
+ snapshot taken at issue is authoritative: including when it recorded
+ *no* prefix, which is an answer rather than a gap. An invoice issued
+ as "2" must keep reading as "2" after somebody sets a prefix, or the
+ queue would name a document differently from the copy the client is
+ holding. An imported document keeps the name it arrived with; ours
+ would rename a supplier's reference.
+ """
+ if invoice.origin == "imported":
+ return invoice.external_number
+ if invoice.number is None:
+ return None
+ if invoice.snapshot is not None:
+ prefix = invoice.snapshot.get("number_prefix") or ""
+ else:
+ settings = await invoice_service.get_settings(session, invoice.workspace_id)
+ prefix = settings.number_prefix or ""
+ return f"{prefix}{invoice.number}"
+
+
+async def _with_label(session: AsyncSession, row) -> SuggestionRead:
+ """Name the promises a suggestion points at.
+
+ Resolved here rather than stored on the row: an invoice that gets
+ renumbered or a bill that gets renamed should read correctly in the
+ queue, not as it was called on the day we became unsure about it.
+ """
+ read = SuggestionRead.model_validate(row)
+ read.covers = [
+ SuggestionCovers(
+ expectation_kind=member.expectation_kind,
+ expectation_id=member.expectation_id,
+ label=await _name_of(session, member),
+ amount=member.amount,
+ )
+ for member in await suggestions.members_of(session, row)
+ ]
+ read.expectation_label = read.covers[0].label if read.covers else None
+ # What the whole question is worth, so a grouped row shows the payment
+ # rather than one slice of it.
+ read.amount = sum((c.amount for c in read.covers), Decimal("0"))
+ return read
+
+
+async def _name_of(session: AsyncSession, row) -> Optional[str]:
+ if row.expectation_kind == "invoice":
+ invoice = await session.get(Invoice, row.expectation_id)
+ return await _invoice_name(session, invoice) if invoice else None
+ bill = await session.get(RecurringTransaction, row.expectation_id)
+ return bill.description if bill else None
+
+
+async def _currency_of(session: AsyncSession, row) -> Optional[str]:
+ """What the recorded amount is denominated in.
+
+ Taken from the promise rather than from the movement, because the
+ settlement was written in the promise's currency and matching refuses
+ a pair whose currencies disagree, so there is only ever one answer.
+ """
+ if row.expectation_kind == "invoice":
+ invoice = await session.get(Invoice, row.expectation_id)
+ return invoice.currency if invoice else None
+ bill = await session.get(RecurringTransaction, row.expectation_id)
+ return bill.currency if bill else None
+
+
+# ---------------------------------------------------------------------------
+# What matching did
+# ---------------------------------------------------------------------------
[email protected]("/history", response_model=list[HistoryEventRead])
+async def list_history(
+ limit: int = 50,
+ expectation_id: Optional[uuid.UUID] = None,
+ ctx: WorkspaceContext = Depends(_read),
+ session: AsyncSession = Depends(get_async_session),
+):
+ """The stream, newest first, or everything that happened to one promise.
+
+ Newest first here and oldest first in the queue, deliberately: a queue
+ is work to get through, so its oldest question is the most urgent,
+ while a history is read to find out what just happened.
+ """
+ events = await history.recent(
+ session, ctx.workspace.id, expectation_id=expectation_id, limit=limit
+ )
+
+ out: list[HistoryEventRead] = []
+ for event in events:
+ read = HistoryEventRead.model_validate(event)
+ read.expectation_label = await _name_of(session, event)
+ read.currency = await _currency_of(session, event)
+ if event.transaction_id is not None:
+ transaction = await session.get(Transaction, event.transaction_id)
+ read.transaction_description = transaction.description if transaction else None
+ out.append(read)
+ return out
diff --git a/backend/app/core/module_gate.py b/backend/app/core/module_gate.py
index 157d5740..737417d4 100644
--- a/backend/app/core/module_gate.py
+++ b/backend/app/core/module_gate.py
@@ -53,3 +53,43 @@ def require_module_write(module: ModuleId) -> Callable[..., Awaitable[WorkspaceC
return ctx
return dependency
+
+
+def require_any_module(*modules: ModuleId) -> Callable[..., Awaitable[WorkspaceContext]]:
+ """Read access to routes that serve more than one module.
+
+ Matching is the case this exists for: its rules cover invoices and
+ recurring bills, which are separate modules a workspace may have one
+ of, both, or neither. Gating the router on either one alone would
+ have hidden a real feature from the workspaces it was written for.
+ A route reached this way still has to check the module of whatever it
+ is addressed at.
+ """
+
+ async def dependency(
+ ctx: WorkspaceContext = Depends(current_workspace),
+ ) -> WorkspaceContext:
+ _assert_any_enabled(ctx, modules)
+ return ctx
+
+ return dependency
+
+
+def require_any_module_write(
+ *modules: ModuleId,
+) -> Callable[..., Awaitable[WorkspaceContext]]:
+ """The same, for writes: any of the modules, and a role that may write."""
+
+ async def dependency(
+ ctx: WorkspaceContext = Depends(current_writable_workspace),
+ ) -> WorkspaceContext:
+ _assert_any_enabled(ctx, modules)
+ return ctx
+
+ return dependency
+
+
+def _assert_any_enabled(ctx: WorkspaceContext, modules: tuple[ModuleId, ...]) -> None:
+ enabled = resolve_modules(ctx.workspace)
+ if not any(module.value in enabled for module in modules):
+ raise HTTPException(status_code=404, detail="Not found")
diff --git a/backend/app/main.py b/backend/app/main.py
index cf7bbcd8..215161c4 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -21,6 +21,7 @@ from app.api.passkeys import router as passkeys_router
from app.api.import_transactions import router as import_router
from app.api.info import router as info_router
from app.api.recurring_transactions import router as recurring_router
+from app.api.reconciliation import router as reconciliation_router
from app.api.rules import router as rules_router
from app.api.assets import router as assets_router
from app.api.asset_groups import router as asset_groups_router
@@ -166,6 +167,7 @@ app.include_router(
app.include_router(categories_router)
app.include_router(category_groups_router)
app.include_router(rules_router)
+app.include_router(reconciliation_router)
app.include_router(transactions_router)
app.include_router(import_router)
app.include_router(import_logs_router)
diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py
index 1aad089f..ee798442 100644
--- a/backend/app/models/__init__.py
+++ b/backend/app/models/__init__.py
@@ -27,6 +27,11 @@ from app.models.group_settlement import GroupSettlement
from app.models.collection import Collection, collection_accounts, collection_asset_groups
from app.models.invoice import Invoice, InvoiceAllocation, InvoiceLine, InvoiceSettings
from app.models.invoice_attachment import InvoiceAttachment
+from app.models.reconciliation import (
+ ReconciliationEvent,
+ ReconciliationRule,
+ ReconciliationSuggestion,
+)
# Side-effect import: register the before_insert listener that auto-stamps
# workspace_id from user_id on financial entities. Imported last so all
@@ -71,6 +76,9 @@ __all__ = [
"InvoiceLine",
"InvoiceSettings",
"InvoiceAttachment",
+ "ReconciliationEvent",
+ "ReconciliationRule",
+ "ReconciliationSuggestion",
"collection_accounts",
"collection_asset_groups",
]
diff --git a/backend/app/models/reconciliation.py b/backend/app/models/reconciliation.py
new file mode 100644
index 00000000..8e049c58
--- /dev/null
+++ b/backend/app/models/reconciliation.py
@@ -0,0 +1,269 @@
+"""What a workspace changed about matching, and what matching is unsure of.
+
+Two tables, and they answer two different questions.
+
+`reconciliation_rules` holds **only what a workspace changed.** The rules
+themselves ship with the image, in `reconciliation_policy`. Copying them
+into every workspace at creation would freeze them: a better default six
+months from now would never reach anyone who had already opened the
+page. So an untouched rule keeps improving with the product, and a row
+here exists exactly when somebody decided otherwise.
+
+`reconciliation_suggestions` holds the doubtful space: money that looks
+like it answers a promise without the evidence to say so. Its most
+important column is `status`, and specifically that `declined` is stored:
+without it a suggestion somebody rejected comes back on the next sync,
+and asking a person the same question every morning is worse than never
+asking.
+"""
+import uuid
+from datetime import datetime
+from decimal import Decimal
+from typing import TYPE_CHECKING, Any, Optional
+
+from sqlalchemy import (
+ Boolean,
+ CheckConstraint,
+ DateTime,
+ ForeignKey,
+ Index,
+ Integer,
+ Numeric,
+ String,
+ UniqueConstraint,
+ false,
+ func,
+)
+from sqlalchemy.dialects.postgresql import JSONB, UUID
+from sqlalchemy.orm import Mapped, mapped_column, relationship
+from sqlalchemy.types import JSON
+
+from app.core.database import Base
+
+if TYPE_CHECKING:
+ from app.models.transaction import Transaction
+
+#: jsonb on Postgres, plain JSON elsewhere. The overrides are read on
+#: every match, so on the deployment everyone actually runs they should
+#: be the indexable, queryable type rather than a string of text.
+_Json = JSON().with_variant(JSONB(), "postgresql")
+
+
+class ReconciliationRule(Base):
+ """One workspace's departure from a shipped rule, or a rule of its own.
+
+ `config` is a **sparse patch** for an overridden default: it carries
+ only the keys somebody touched, so turning a rule off does not also
+ freeze its date window at today's value. For a rule the workspace
+ wrote itself it is the whole strategy.
+ """
+
+ __tablename__ = "reconciliation_rules"
+ __table_args__ = (
+ # One row per rule per workspace. A second override of the same
+ # strategy is not a second opinion, it is a bug.
+ UniqueConstraint(
+ "workspace_id", "node", "strategy_id", name="uq_reconciliation_rule_strategy"
+ ),
+ CheckConstraint(
+ "origin IN ('default', 'custom')", name="ck_reconciliation_rule_origin"
+ ),
+ Index("ix_reconciliation_rules_workspace_node", "workspace_id", "node"),
+ )
+
+ 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 wrote it. Kept for the same reason the categorization rules keep
+ #: it: in a workspace with several members, "who changed this" is the
+ #: first question asked when matching starts behaving differently.
+ user_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("users.id"), nullable=True
+ )
+ #: Which policy document this belongs to: invoices or recurring bills.
+ node: Mapped[str] = mapped_column(String(64))
+ #: The shipped strategy being overridden, or this rule's own id.
+ strategy_id: Mapped[str] = mapped_column(String(64))
+ #: `default` patches something we ship; `custom` is the workspace's own.
+ origin: Mapped[str] = mapped_column(String(16), default="default")
+ #: What the workspace calls it. Null for an overridden default, which
+ #: keeps its translated shipped name: a name that would otherwise
+ #: freeze in one language the day somebody edited a threshold.
+ name: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
+ #: Where it sits in the order strategies are tried. Null means "leave
+ #: it where the shipped document put it", so inserting a rule above a
+ #: default does not require rewriting every other row.
+ position: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
+ config: Mapped[dict[str, Any]] = mapped_column(_Json, default=dict)
+ #: The workspace threw this rule away.
+ #:
+ #: Only meaningful on an `origin='default'` row: a rule of the
+ #: workspace's own is deleted by deleting the row, because it exists
+ #: nowhere else. A shipped rule is a document in the image, so the
+ #: only way to be rid of it is to say so here. `config` is kept, not
+ #: cleared: a deleted rule does not run, and nobody is served by
+ #: silently discarding thresholds somebody tuned in case they bring
+ #: it back.
+ deleted: Mapped[bool] = mapped_column(
+ Boolean, nullable=False, default=False, server_default=false()
+ )
+ #: The shape this override was written against, so a future change to
+ #: the document can tell which rows it has to migrate.
+ policy_version: Mapped[int] = mapped_column(Integer, default=1)
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now()
+ )
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
+ )
+
+
+class ReconciliationSuggestion(Base):
+ """A match the engine is not confident enough to make on its own.
+
+ The row is keyed on the pair, not on the transaction, because one
+ payment can plausibly answer several promises and a person should see
+ all of them rather than whichever we happened to score highest.
+
+ `scores` keeps the per-signal breakdown rather than one number. "We
+ are 78% sure" tells a person nothing they can act on; "the amount is
+ exact, the date is four days out, the name does not match" tells them
+ what to look at, and is the difference between a queue somebody
+ trusts and one they clear without reading.
+ """
+
+ __tablename__ = "reconciliation_suggestions"
+ __table_args__ = (
+ UniqueConstraint(
+ "workspace_id",
+ "transaction_id",
+ "expectation_kind",
+ "expectation_id",
+ name="uq_reconciliation_suggestion_pair",
+ ),
+ CheckConstraint(
+ "status IN ('pending', 'accepted', 'declined', 'expired')",
+ name="ck_reconciliation_suggestion_status",
+ ),
+ CheckConstraint(
+ "expectation_kind IN ('invoice', 'recurring')",
+ name="ck_reconciliation_suggestion_kind",
+ ),
+ # The queue is always read as "what is still open here", so that is
+ # what the index serves.
+ Index(
+ "ix_reconciliation_suggestions_open",
+ "workspace_id",
+ "status",
+ "created_at",
+ ),
+ )
+
+ 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
+ )
+ transaction_id: Mapped[uuid.UUID] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="CASCADE"), index=True
+ )
+ #: Which kind of promise this points at. There is no foreign key,
+ #: deliberately: an invoice and a recurring bill live in different
+ #: tables and a column cannot point at both. Deletion is handled by
+ #: the reaper rather than by the database.
+ expectation_kind: Mapped[str] = mapped_column(String(16))
+ expectation_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), index=True)
+ #: Ties together the several invoices one payment may cover, so the
+ #: queue asks *"does this cover these three?"* rather than three
+ #: separate questions somebody could answer inconsistently and end up
+ #: with a payment spread across two debts and short on a third. Null
+ #: for the ordinary single-invoice case.
+ group_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), nullable=True, index=True
+ )
+ #: The rule that produced it, so the queue can say *why*; the same id
+ #: the rules page shows.
+ strategy_id: Mapped[str] = mapped_column(String(64))
+ node: Mapped[str] = mapped_column(String(64))
+ #: What would be settled if this were accepted.
+ amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))
+ #: Per-signal breakdown, e.g. {"amount": 1.0, "date": 0.6, "name": 0.0}.
+ scores: Mapped[dict[str, Any]] = mapped_column(_Json, default=dict)
+ status: Mapped[str] = mapped_column(String(16), default="pending", index=True)
+ #: When a person acted on it, and who.
+ resolved_at: Mapped[Optional[datetime]] = mapped_column(
+ DateTime(timezone=True), nullable=True
+ )
+ resolved_by: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("users.id"), nullable=True
+ )
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now()
+ )
+
+ transaction: Mapped["Transaction"] = relationship(lazy="joined")
+
+
+class ReconciliationEvent(Base):
+ """What matching did, in one order.
+
+ Small on purpose. Most of what a person calls "the history" is
+ already stored: a link is an allocation with a rule id and a
+ timestamp, an answered suggestion is a suggestion row with a status
+ and who resolved it. What did not exist was a single stream: reading
+ those two tables together means joining shapes that have nothing in
+ common and no shared ordering.
+
+ And one event genuinely had nowhere to live. `unallocate` **deletes**
+ the allocation, so a match that was made and then undone looked
+ exactly like one that never happened. That is the row this table
+ exists for first.
+
+ It is **not** a log of everything the engine considered. A sync of
+ three hundred transactions where two hundred and ninety match nothing
+ would write two hundred and ninety rows saying nothing happened, and
+ a history nobody can scan is the same as no history.
+ """
+
+ __tablename__ = "reconciliation_events"
+ __table_args__ = (
+ CheckConstraint(
+ "action IN ('linked', 'suggested', 'accepted', 'declined',"
+ " 'expired', 'unlinked')",
+ name="ck_reconciliation_event_action",
+ ),
+ Index("ix_reconciliation_events_stream", "workspace_id", "at"),
+ Index("ix_reconciliation_events_expectation", "expectation_id"),
+ )
+
+ 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")
+ )
+ at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), server_default=func.now()
+ )
+ action: Mapped[str] = mapped_column(String(16))
+ #: SET NULL rather than CASCADE: deleting a transaction should not
+ #: erase the record that something was once matched to it. The
+ #: history is the one place that has to survive the tidying up.
+ transaction_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("transactions.id", ondelete="SET NULL"),
+ nullable=True,
+ )
+ expectation_kind: Mapped[str] = mapped_column(String(16))
+ expectation_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
+ amount: Mapped[Decimal] = mapped_column(Numeric(precision=15, scale=2))
+ strategy_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
+ #: Null means the system did it on its own: the difference a reader
+ #: most often wants: was this me, or was this the rules?
+ user_id: Mapped[Optional[uuid.UUID]] = mapped_column(
+ UUID(as_uuid=True), ForeignKey("users.id"), nullable=True
+ )
+ detail: Mapped[dict[str, Any]] = mapped_column(_Json, default=dict)
diff --git a/backend/app/schemas/reconciliation.py b/backend/app/schemas/reconciliation.py
new file mode 100644
index 00000000..455d3088
--- /dev/null
+++ b/backend/app/schemas/reconciliation.py
@@ -0,0 +1,201 @@
+"""What the matching rules and the doubtful queue look like over HTTP."""
+import uuid
+from datetime import date, datetime
+from decimal import Decimal
+from typing import Any, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+
+class RuleWindow(BaseModel):
+ """How far from the expected day a movement may land.
+
+ Asymmetric because money arrives after a due date far more often than
+ before it, and the two sides are measured from different anchors: late
+ from the due date, early from the day the promise was written.
+ """
+
+ before_days: int = Field(ge=0, le=365)
+ after_days: int = Field(ge=0, le=365)
+
+
+class ReconciliationRuleRead(BaseModel):
+ """One rule as the page shows it: shipped, changed, or the workspace's own.
+
+ `customised` is what lets the screen say "you changed this" and offer
+ to put it back, without the client having to know what we ship.
+ """
+
+ id: str
+ node: str
+ name: Optional[str] = None
+ origin: str
+ customised: bool
+ enabled: bool
+ #: `link` or `suggest`: what happens when it matches.
+ outcome: str
+ #: **Which moment it runs at.** `money_arrives` when a payment lands
+ #: and we look for the promise it answers; `invoice_issued` when a
+ #: document is written and we look back at money already there; `both`.
+ #: The evidence differs between the two, so a rule is allowed to trust
+ #: only one, and saying so here is what keeps that choice out of the
+ #: matching code, where nobody could see it.
+ trigger: str
+ when: dict[str, Any]
+ position: int
+
+
+class DiscardedRuleRead(BaseModel):
+ """A rule we ship that this workspace threw away.
+
+ Sent so the page can offer it back. A shipped rule is a document in
+ the image, so deleting one leaves a tombstone rather than a hole:
+ which means we still know its name, and the only alternative to
+ showing it here would be a deletion nobody could undo.
+ """
+
+ id: str
+ node: str
+
+
+class ReconciliationNodeRead(BaseModel):
+ """A whole set of rules, in the order they are tried."""
+
+ node: str
+ #: Whether this set is reachable at all for this workspace. The invoice
+ #: rules mean nothing where the module is off, and showing them as if
+ #: they were live would be a lie the page tells every time it loads.
+ active: bool
+ rules: list[ReconciliationRuleRead]
+ discarded: list[DiscardedRuleRead] = []
+
+
+class ReconciliationRuleUpdate(BaseModel):
+ """A change to a rule we ship. Every field optional: what is not sent
+ stays as shipped, and keeps improving when we improve it."""
+
+ enabled: Optional[bool] = None
+ outcome: Optional[str] = None
+ trigger: Optional[str] = None
+ when: Optional[dict[str, Any]] = None
+ position: Optional[int] = None
+
+
+class ReconciliationRuleCreate(BaseModel):
+ """A rule the workspace writes itself."""
+
+ node: str
+ name: str = Field(min_length=1, max_length=120)
+ outcome: str
+ trigger: str = "money_arrives"
+ when: dict[str, Any]
+ enabled: bool = True
+ position: Optional[int] = None
+
+
+class ReconciliationOrder(BaseModel):
+ """The order rules are tried in, named in full.
+
+ Every rule in the set, not only the one that moved: order is the
+ mechanism the feature rests on, and a half-implicit order rearranges
+ itself the day a new default is shipped.
+ """
+
+ order: list[str] = Field(min_length=1)
+
+
+class SuggestionTransactionRead(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ id: uuid.UUID
+ description: Optional[str] = None
+ amount: Decimal
+ currency: Optional[str] = None
+ date: date
+ type: str
+
+
+class SuggestionCovers(BaseModel):
+ """One promise inside a question that names several."""
+
+ expectation_kind: str
+ expectation_id: uuid.UUID
+ label: Optional[str] = None
+ amount: Decimal
+
+
+class SuggestionRead(BaseModel):
+ """One open question, with the evidence behind it.
+
+ `scores` is the per-signal breakdown rather than one number, because
+ "we are 78% sure" is not something anyone can check, while "the amount
+ is exact and the date is four days out" is.
+ """
+
+ model_config = ConfigDict(from_attributes=True)
+
+ id: uuid.UUID
+ node: str
+ strategy_id: str
+ expectation_kind: str
+ expectation_id: uuid.UUID
+ #: What the promise is called, resolved for display: an invoice number
+ #: and client, or the recurring bill's description.
+ expectation_label: Optional[str] = None
+ amount: Decimal
+ scores: dict[str, Any]
+ status: str
+ created_at: datetime
+ transaction: Optional[SuggestionTransactionRead] = None
+ #: Everything this one question covers. A single entry for the ordinary
+ #: case; several when one payment is offered against several invoices,
+ #: which is answered whole or not at all.
+ covers: list[SuggestionCovers] = []
+
+
+class HistoryEventRead(BaseModel):
+ """One thing that happened, as the stream shows it."""
+
+ model_config = ConfigDict(from_attributes=True)
+
+ id: uuid.UUID
+ at: datetime
+ #: `linked` · `suggested` · `accepted` · `declined` · `expired` ·
+ #: `unlinked`. Six verbs, each of which changed something visible.
+ action: str
+ expectation_kind: str
+ expectation_id: uuid.UUID
+ #: Resolved for display, so a renamed invoice reads correctly.
+ expectation_label: Optional[str] = None
+ amount: Decimal
+ #: What the amount is denominated in. Resolved for display rather than
+ #: stored: an amount without its currency is not an amount, and a
+ #: reader that assumed one would tell a workspace it received dollars.
+ currency: Optional[str] = None
+ strategy_id: Optional[str] = None
+ #: Null means the rules did it on their own: the distinction a reader
+ #: reaches for first.
+ user_id: Optional[uuid.UUID] = None
+ transaction_id: Optional[uuid.UUID] = None
+ transaction_description: Optional[str] = None
+
+
+class ReconciliationImportRequest(BaseModel):
+ """A matching-rules file, and permission to replace what is here.
+
+ `overwrite` is asked for rather than assumed: importing replaces the
+ workspace's matching rules, and a policy somebody tuned is not
+ something to overwrite on a mis-click.
+ """
+
+ payload: dict[str, Any]
+ overwrite: bool = False
+
+
+class ReconciliationImportResponse(BaseModel):
+ imported: int
+ #: Rules the file carried that could not be brought in: one naming an
+ #: account this workspace does not have, or a rule this version no
+ #: longer ships. Counted rather than hidden: "12 imported" and "12
+ #: imported, 3 skipped" are different outcomes.
+ skipped: int
diff --git a/backend/app/services/connection_service.py b/backend/app/services/connection_service.py
index c23dac7f..d17485cc 100644
--- a/backend/app/services/connection_service.py
+++ b/backend/app/services/connection_service.py
@@ -36,7 +36,8 @@ from app.providers.base import (
)
from app.services import oauth_state
from app.services import admin_service
-from app.services import recurring_match_service
+from app.services import reconciliation_service, recurring_match_service
+from app.services.text_similarity import token_overlap
from app.services.account_service import (
_simplefin_to_internal_balance,
sync_opening_balance_for_connected_account,
@@ -1191,6 +1192,19 @@ async def handle_oauth_callback(
# Detect transfer pairs among newly synced transactions
await detect_transfer_pairs(session, workspace_id, candidate_ids=new_tx_ids)
+ # And settle what this money was promised against, once the rows exist.
+ if new_tx_ids:
+ landed = list(
+ (
+ await session.execute(
+ select(Transaction).where(Transaction.id.in_(new_tx_ids))
+ )
+ )
+ .scalars()
+ .all()
+ )
+ await reconciliation_service.match_incoming(session, workspace_id, landed)
+
# Investment holdings live on /investments — separate endpoint from
# /accounts. Pulled after account setup when enabled so holdings are
# available on the Assets page immediately after the widget closes.
@@ -1203,18 +1217,6 @@ async def handle_oauth_callback(
return connection
-def _description_similarity(a: str | None, b: str | None) -> float:
- """Token overlap ratio between two descriptions."""
- if not a or not b:
- return 0.0
- tokens_a = set(a.lower().split())
- tokens_b = set(b.lower().split())
- if not tokens_a or not tokens_b:
- return 0.0
- intersection = tokens_a & tokens_b
- return len(intersection) / max(len(tokens_a), len(tokens_b))
-
-
async def _fuzzy_match_manual(
session: AsyncSession,
account_id: uuid.UUID,
@@ -1242,7 +1244,7 @@ async def _fuzzy_match_manual(
best_match = None
best_score = 0.0
for candidate in candidates:
- score = _description_similarity(
+ score = token_overlap(
candidate.original_description or candidate.description,
txn_data.description,
)
@@ -1324,7 +1326,7 @@ async def _find_synced_duplicate(
for candidate in result.scalars():
if candidate.external_id and candidate.external_id.startswith("bill_charge:"):
continue
- if _description_similarity(
+ if token_overlap(
candidate.original_description or candidate.description,
txn_data.description,
) >= 0.7:
@@ -1383,7 +1385,7 @@ async def _cleanup_phantom_duplicates(
)
)
for sibling in sibling_result.scalars():
- if _description_similarity(
+ if token_overlap(
sibling.original_description or sibling.description,
tx.original_description or tx.description,
) >= 0.9:
@@ -2082,6 +2084,25 @@ async def sync_connection(
if new_tx_ids:
await detect_transfer_pairs(session, workspace_id, candidate_ids=new_tx_ids)
+ # Then settle whatever this money was promised against. It runs
+ # after the rows are written, not inside the loop: the recurring
+ # match upgrades a placeholder in place, while an invoice link is
+ # a row pointing at a transaction that has to exist first. It is
+ # also a single batch, so the candidate invoices are loaded once
+ # per sync rather than once per transaction.
+ landed = list(
+ (
+ await session.execute(
+ select(Transaction).where(Transaction.id.in_(new_tx_ids))
+ )
+ )
+ .scalars()
+ .all()
+ )
+ await reconciliation_service.match_incoming(
+ session, workspace_id, landed
+ )
+
# Clean up phantom duplicates: providers occasionally double-report the
# same payment with different ids. Once transfer detection has paired
# the real one, the orphan twin gets removed here.
diff --git a/backend/app/services/dashboard_service.py b/backend/app/services/dashboard_service.py
index 0fec491c..a2167ecf 100644
--- a/backend/app/services/dashboard_service.py
+++ b/backend/app/services/dashboard_service.py
@@ -22,6 +22,7 @@ from app.services._query_filters import (
viewer_shared_pnl,
viewer_shared_spending_by_category,
)
+from app.services import invoice_forecast_service
from app.services.admin_service import get_credit_card_accounting_mode
from app.services.recurring_transaction_service import get_occurrences_in_range
from app.services.asset_service import get_asset_values_at
@@ -310,6 +311,28 @@ async def get_summary(
projected_balance.get(account_currency, 0.0) + float(signed)
)
+ # Money promised but not yet moved. An invoice is a claim rather
+ # than a movement, so it never entered here for free, and adding
+ # it before matching existed would have counted the same money
+ # twice: the open invoice and the pending bank credit that pays
+ # it. Only the *unallocated* balance is carried, so the moment a
+ # payment is linked the claim shrinks and the transaction above
+ # carries the forecast alone.
+ #
+ # Filtered by account? No. A claim has no account until it is
+ # paid, so narrowing the dashboard to one account cannot include
+ # it without inventing where the money will land.
+ # `is None`, not falsy: a collection holding only wallets narrows
+ # the report to an empty set of bank accounts, and an empty list
+ # means filtered to nothing rather than not filtered at all.
+ if account_ids is None:
+ for claim in await invoice_forecast_service.claims_in_range(
+ session, workspace_id, projection_start, month_end
+ ):
+ projected_balance[claim.currency] = (
+ projected_balance.get(claim.currency, 0.0) + float(claim.signed)
+ )
+
# Monthly income and expenses — exclude opening_balance so initial deposits
# don't inflate the month's income figure. counts_as_user_pnl() skips
# paired transfers, transfer-like categories AND settlement movements
diff --git a/backend/app/services/import_service.py b/backend/app/services/import_service.py
index 94eff8f2..d5419ad4 100644
--- a/backend/app/services/import_service.py
+++ b/backend/app/services/import_service.py
@@ -19,7 +19,7 @@ from app.models.category import Category
from app.models.rule import Rule
from app.models.transaction import Transaction
from app.schemas.transaction import TransactionImport, FailedRow
-from app.services import recurring_match_service
+from app.services import reconciliation_service, recurring_match_service
from app.services.credit_card_service import apply_effective_date
from app.services.category_service import get_hidden_category_ids
from app.services.rule_engine import apply_rule_actions, evaluate_conditions, merge_notes
@@ -765,6 +765,7 @@ async def import_transactions(
}
imported = 0
+ landed: list[Transaction] = []
skipped = 0
effective_format = (detected_format or source or "").lower()
should_detect_duplicates = detect_duplicates if effective_format == "csv" else True
@@ -924,10 +925,17 @@ async def import_transactions(
await stamp_primary_amount(session, user_id, incoming)
imported += 1
+ landed.append(incoming)
# Update import log with actual imported count
import_log.transaction_count = imported
+ # Invoices last, and as one batch. Unlike the recurring match above:
+ # which upgrades a placeholder in place and so must happen before the
+ # row is written: settling an invoice creates an allocation pointing
+ # at a transaction, which has to exist first.
+ await reconciliation_service.match_incoming(session, workspace_id, landed)
+
await session.commit()
return imported, skipped, excluded_count, import_log.id
diff --git a/backend/app/services/invoice_archive.py b/backend/app/services/invoice_archive.py
new file mode 100644
index 00000000..a8c4125b
--- /dev/null
+++ b/backend/app/services/invoice_archive.py
@@ -0,0 +1,135 @@
+"""Filing the document that was issued, at the moment it is issued.
+
+## The problem this fixes
+
+`/pdf` renders the invoice live, and the renderer prints *Paid* and
+*Balance* as soon as money moves against it. So an invoice sent showing
+"Total 10.000" came back, after a 5.000 payment, showing a balance of
+5.000: a different document at the same address, including the public
+link the client was given.
+
+That is the same failure the numbering rules exist to prevent: **renaming
+a document somebody already has in their hands.**
+
+The fix is not to make the renderer forget about payments. Two different
+documents were coming out of one door:
+
+ - **The invoice as issued** is a record of what was communicated. It
+ must be reproducible forever.
+ - **A statement of account** says what is paid and what is left. It is
+ supposed to change, and it is a different thing to ask for.
+
+## Why filing, rather than a flag on the renderer
+
+The architecture already answers this and was not being used. An invoice
+gathers paper (`invoice_attachments`), and one file can be marked as
+*the* document, which `/pdf` already prefers over anything it could
+render. A file cannot drift. So issuing files the PDF, and from that
+moment the answer to "what did we send" is a stored artifact rather than
+a re-rendering that depends on what has happened since.
+
+Nothing new has to be remembered, and no second code path can forget to
+freeze anything: it is frozen because it is a file.
+
+## What it deliberately does not do
+
+**An imported document is never filed this way.** We did not write it,
+and rendering our own page over someone else's bill produces something
+that looks official and is not; the same reason `/pdf` refuses to render
+for them at all.
+
+**Failing to file never fails the issue.** Issuing an invoice is the act
+that matters; the archive is a courtesy to your future self. A storage
+error must not leave a workspace unable to bill.
+"""
+from __future__ import annotations
+
+import logging
+import uuid
+from typing import Optional
+
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.invoice import Invoice
+from app.models.workspace import Workspace
+from app.services import (
+ invoice_attachment_service,
+ invoice_document,
+ invoice_logo_service,
+ invoice_pdf,
+ invoice_service,
+)
+
+logger = logging.getLogger(__name__)
+
+#: Marks the file as one we produced rather than one that was handed to
+#: us, so a later importer can tell them apart without guessing from the
+#: filename.
+SOURCE = "issued"
+
+
+async def file_issued_document(
+ session: AsyncSession,
+ invoice: Invoice,
+ workspace: Workspace,
+ user_id: Optional[uuid.UUID] = None,
+) -> None:
+ """Render the invoice as issued and keep it.
+
+ Called right after issuing, while the figures still say what was sent.
+ Silent about everything that would make it a nuisance: an imported
+ document, an invoice that already has a filed document, or a storage
+ failure.
+ """
+ if invoice.origin == "imported":
+ return
+ if invoice.number is None:
+ # Not actually issued. Nothing to preserve, and a draft's numbers
+ # are still moving.
+ return
+
+ # Somebody already filed the real thing: a signed copy, the version
+ # that went by email. Ours would be a second opinion about a document
+ # that has an original.
+ if await invoice_attachment_service.primary_for(session, invoice.id) is not None:
+ return
+
+ try:
+ settings = await invoice_service.get_settings(session, workspace.id)
+ document = await invoice_document.build_document(
+ session, invoice, settings, workspace
+ )
+ logo = (
+ await invoice_logo_service.read(workspace.id, uuid.UUID(document.logo_id))
+ if document.logo_id
+ else None
+ )
+ pdf = invoice_pdf.render_pdf(document, logo)
+ name = f"{document.number or invoice.number}.pdf".replace("/", "-")
+
+ await invoice_attachment_service.upload(
+ session,
+ workspace.id,
+ user_id,
+ invoice.id,
+ filename=name,
+ content_type="application/pdf",
+ data=pdf,
+ kind="bill",
+ source=SOURCE,
+ # Unique per workspace, so re-issuing or a retry converges on
+ # one row instead of filing the same page twice.
+ external_id=f"{SOURCE}:{invoice.id}",
+ document_number=document.number,
+ issued_at=invoice.issue_date,
+ is_primary=True,
+ )
+ except Exception: # noqa: BLE001 - see the module docstring
+ # Issuing is the act that matters. A storage error must not leave
+ # a workspace unable to bill, so this is logged and swallowed:
+ # the invoice is issued either way, and `/pdf` falls back to
+ # rendering exactly as it did before.
+ logger.warning(
+ "Could not file the issued document for invoice %s", invoice.id,
+ exc_info=True,
+ )
diff --git a/backend/app/services/invoice_forecast_service.py b/backend/app/services/invoice_forecast_service.py
new file mode 100644
index 00000000..a3389fdd
--- /dev/null
+++ b/backend/app/services/invoice_forecast_service.py
@@ -0,0 +1,133 @@
+"""What is still owed, as money the forecast can carry.
+
+## Why invoices were kept out until now
+
+Everything that projects in Securo does so **by being a transaction**: a
+row counts as forecast when it is `pending`, or `posted` with a future
+date, and a recurring schedule enters by being materialised into rows.
+An invoice is a claim, not a movement, so it never qualified for free.
+
+Projecting it before matching existed would have **double counted**. The
+same R$5.000 is routinely an open invoice *and* a pending bank credit,
+and until the two could be said to be the same money, adding both would
+have inflated every forecast in the product. Saying they are the same
+money is exactly what payment matching does, which is why this lands
+with it and not before.
+
+## What resolves the double count
+
+Only the **unallocated** balance is projected. The moment a payment is
+linked, the invoice's outstanding drops and the transaction carries the
+forecast alone, so the total never moves twice for one payment. Nothing
+has to be kept in sync: the subtraction is the mechanism.
+
+## Three deliberate narrowings
+
+**Only `status == 'open'`.** That is the stored decision, not the derived
+reading. A draft is not owed by anybody yet, and `void` and
+`uncollectible` are the two ways of saying the money is not coming.
+
+**Only inside the window, by due date.** An invoice sixty days overdue is
+still owed, and it is deliberately *not* projected: the only date we have
+for it has passed, and moving it to today would be inventing a date
+nobody promised. Overdue money is the aging table's subject, and a
+forecast that quietly relocates it would make the aging table and the
+forecast disagree about the same debt.
+
+**Per currency, unconverted.** The caller decides. The dashboard keeps a
+figure per currency, so a euro invoice belongs in the euro bucket; the
+cash-flow report sums into one currency and converts on the way in.
+Converting here would force the first caller to undo it.
+
+## The module gate
+
+There is no flag lookup. A workspace without invoicing has no rows in
+`invoices`, so this costs one index probe and returns nothing, which is
+cheaper than the query that would have asked whether to run it.
+"""
+from __future__ import annotations
+
+import uuid
+from dataclasses import dataclass
+from datetime import date
+from decimal import Decimal
+from typing import Optional
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.invoice import Invoice, InvoiceAllocation
+
+ZERO = Decimal("0")
+
+
+@dataclass(frozen=True)
+class Claim:
+ """One promise of money, and when it was promised for."""
+
+ due_date: date
+ currency: str
+ #: Always positive. `direction` says which way it points, because the
+ #: two callers sign it differently: a balance walk adds or subtracts,
+ #: a cash-flow report files it under income or expenses.
+ amount: Decimal
+ #: `receivable` (money owed to the workspace) or `payable`.
+ direction: str
+
+ @property
+ def signed(self) -> Decimal:
+ return self.amount if self.direction == "receivable" else -self.amount
+
+
+async def claims_in_range(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ range_start: date,
+ range_end: date,
+ *,
+ directions: Optional[tuple[str, ...]] = None,
+) -> list[Claim]:
+ """Every open invoice falling due in `[range_start, range_end)`.
+
+ Half-open on purpose, matching `_get_forecast_transactions`, so a
+ caller walking month by month never counts the boundary day twice.
+ """
+ allocated = (
+ select(
+ InvoiceAllocation.invoice_id.label("invoice_id"),
+ func.coalesce(func.sum(InvoiceAllocation.amount), 0).label("total"),
+ )
+ .group_by(InvoiceAllocation.invoice_id)
+ .subquery()
+ )
+
+ query = (
+ select(
+ Invoice.due_date,
+ Invoice.currency,
+ Invoice.direction,
+ (Invoice.total - func.coalesce(allocated.c.total, 0)).label("outstanding"),
+ )
+ .outerjoin(allocated, allocated.c.invoice_id == Invoice.id)
+ .where(
+ Invoice.workspace_id == workspace_id,
+ Invoice.status == "open",
+ Invoice.due_date >= range_start,
+ Invoice.due_date < range_end,
+ (Invoice.total - func.coalesce(allocated.c.total, 0)) > 0,
+ )
+ )
+
+ if directions is not None:
+ query = query.where(Invoice.direction.in_(directions))
+
+ rows = (await session.execute(query)).all()
+ return [
+ Claim(
+ due_date=row.due_date,
+ currency=row.currency or "USD",
+ amount=Decimal(str(row.outstanding)),
+ direction=row.direction,
+ )
+ for row in rows
+ ]
diff --git a/backend/app/services/reconciliation_engine.py b/backend/app/services/reconciliation_engine.py
new file mode 100644
index 00000000..bdf39bb8
--- /dev/null
+++ b/backend/app/services/reconciliation_engine.py
@@ -0,0 +1,816 @@
+"""Deciding which expectation a movement of money settles.
+
+**This module decides and never writes.** It touches no session, loads
+nothing, and returns a decision plus the reasoning that produced it.
+Applying that decision (creating an allocation, or upgrading a
+placeholder in place) belongs to the caller, and is deliberately a
+separate step: a function that mutates cannot be dry-run, and "show me
+what would happen before it happens" is the whole point of putting this
+in front of a person.
+
+## What an expectation is
+
+An invoice and a scheduled recurring occurrence are the same thing seen
+from here: **a promise that money will move, waiting for the movement
+that confirms it.** A workspace that never issues an invoice still has
+promises (the rent leaving on the 5th, the retainer arriving on the
+20th), and they want matching for exactly the same reason.
+
+So both arrive here as an `Expectation` and are scored by the same
+signals. What they do *not* share is what happens afterwards, and that
+difference is real rather than cosmetic:
+
+ - An invoice link is **N:N with an amount**, and both rows survive: one
+ payout settles a dozen invoices net of fees.
+ - A recurring occurrence is **1:1**, and the placeholder *is* the
+ transaction: the real charge replaces it in place, so there is only
+ ever one row.
+
+Forcing those into one "apply" would produce a function with a mode
+switch and two half-truths. They stay apart; only the decision is shared.
+
+## Ports, not a boolean
+
+`linked` · `suggested` · `unmatched`. The direction for automations is a
+node graph rather than a bigger predicate builder, so this is shaped as a
+node from the first line: named outputs, and a trace saying which
+strategy fired and why the others did not.
+"""
+from __future__ import annotations
+
+import uuid
+import itertools
+from dataclasses import dataclass, field
+from datetime import date
+from decimal import ROUND_DOWN, Decimal
+from enum import Enum
+from typing import Any, Literal, Optional
+
+from app.services.text_similarity import token_overlap
+
+#: What the decision came out of. Named rather than boolean so a node
+#: graph can wire each one somewhere different later.
+Port = Literal["linked", "suggested", "unmatched"]
+
+#: Which kind of promise a candidate is. The engine treats them alike;
+#: the caller uses this to pick how to apply the decision.
+ExpectationKind = Literal["invoice", "recurring"]
+
+#: **Which way round the match is being made.** Matching happens at two
+#: different moments and they are not the same question.
+#:
+#: - `money_arrives`: a payment lands and we look for the promise it
+#: answers. The promise came first and was waiting.
+#: - `invoice_issued`: a document is written and we look back at money
+#: that arrived before it existed: the client who pays and lets the
+#: nota follow.
+#:
+#: The evidence is weaker in the second: money that was already sitting
+#: there had a life of its own, and might have been a refund or another
+#: job. So a rule says which moments it is willing to run in, and that
+#: choice is on the page rather than buried in whichever function happens
+#: to be doing the looking.
+Trigger = Literal["money_arrives", "invoice_issued", "both"]
+
+
+class Reason(str, Enum):
+ """Why a strategy did not fire, in words a UI can show.
+
+ A rejected candidate is more useful than a silent one: "no strategy
+ matched" tells a person nothing, while "the amount was right and the
+ date was eleven days outside the window" tells them what to change.
+ """
+
+ DIRECTION = "direction_differs"
+ CURRENCY = "currency_differs"
+ COUNTERPARTY = "different_counterparty"
+ AMOUNT = "amount_outside_tolerance"
+ DATE = "date_outside_window"
+ DESCRIPTION = "description_too_different"
+ ALREADY_SETTLED = "nothing_left_to_settle"
+ AMBIGUOUS = "several_candidates_matched"
+ SOURCE_IGNORED = "transaction_source_ignored"
+ #: The rule does not apply to this money at all: wrong account, wrong
+ #: currency, outside the amount band, text that does not match. Kept
+ #: apart from the comparison reasons above because it answers a
+ #: different question: not "why did this pair fail" but "why was this
+ #: rule not even consulted".
+ OUT_OF_SCOPE = "rule_does_not_apply_here"
+ #: The rule runs at the other moment: when money arrives rather than
+ #: when a document is written, or the reverse.
+ WRONG_MOMENT = "rule_runs_at_another_moment"
+ #: More than one combination of promises adds up to this payment, and
+ #: they are equally good. A person picks.
+ AMBIGUOUS_SET = "several_combinations_add_up"
+ #: Too many promises are open to work out which combination this
+ #: payment covers without guessing.
+ TOO_MANY_TO_COMBINE = "too_many_candidates_to_combine"
+
+
+@dataclass(frozen=True)
+class Movement:
+ """The money that actually moved, reduced to what matching needs.
+
+ Built from a `Transaction` by the caller. A value object rather than
+ the ORM row so this module stays pure and trivially testable, and so
+ a future intake that is not a `Transaction` (a gateway payout line,
+ say) can be scored without pretending to be one.
+ """
+
+ amount: Decimal
+ currency: str
+ #: `credit` (money in) or `debit` (money out).
+ direction: str
+ when: date
+ description: Optional[str] = None
+ #: The counterparty exactly as the bank printed it, before anything of
+ #: ours resolved it to a person. Kept apart from `payee_id` because a
+ #: rule may need it long before the name has been mapped to anybody:
+ #: a Pix description is generic and the payer's name arrives in its
+ #: own field, so a rule that could only read `description` could not
+ #: express "the transfers that come from this company", which is the
+ #: identifying fact on the most common inflow there is.
+ counterparty: Optional[str] = None
+ payee_id: Optional[uuid.UUID] = None
+ account_id: Optional[uuid.UUID] = None
+ #: `sync`, `ofx`, `csv`, `manual`, `recurring`. A policy may ignore
+ #: some: the receivable node ignores `recurring`, because a
+ #: generated placeholder is a promise and not the money itself.
+ source: Optional[str] = None
+
+
+@dataclass(frozen=True)
+class Expectation:
+ """A promise of money moving, waiting to be confirmed.
+
+ `amount` is what is **still outstanding**, never the original total:
+ an invoice half paid expects the other half, and matching it against
+ its full value would miss every second instalment.
+ """
+
+ kind: ExpectationKind
+ id: uuid.UUID
+ amount: Decimal
+ currency: str
+ direction: str
+ when: date
+ description: Optional[str] = None
+ payee_id: Optional[uuid.UUID] = None
+ #: Set for a recurring bill, which is charged to a known account.
+ #: Null for an invoice, where the money may land anywhere.
+ account_id: Optional[uuid.UUID] = None
+ #: When the promise came into existence, if that is a different day
+ #: from when it comes due. An invoice has both and they are weeks
+ #: apart; a recurring occurrence has one, and leaves this null.
+ issued: Optional[date] = None
+
+
+@dataclass(frozen=True)
+class Settlement:
+ """One promise, and how much of this movement goes against it.
+
+ Exists because a payment does not always answer exactly one thing. A
+ client clearing three of their own invoices in a single transfer is
+ ordinary, and so is a commercial arrangement that settles a month's
+ worth at once. The ledger has always been able to record that
+ (allocations are many-to-many with an amount on each), but a decision
+ that could only ever name one promise could never propose it.
+ """
+
+ expectation: Expectation
+ amount: Decimal
+
+
+@dataclass
+class Consideration:
+ """One candidate, and what the engine made of it."""
+
+ expectation_id: uuid.UUID
+ strategy: Optional[str] = None
+ rejected_by: Optional[Reason] = None
+ score: float = 0.0
+
+
+@dataclass
+class Decision:
+ """What to do, and the reasoning that got there.
+
+ `trace` carries every candidate that was looked at, including the
+ ones that lost. It is what lets the invoice screen answer "why is
+ this linked" with the name of the rule that fired, and "why is this
+ not" with the specific signal that failed.
+ """
+
+ port: Port
+ #: Everything this movement settles. Usually one entry; several when a
+ #: single payment answers several promises at once.
+ settlements: list[Settlement] = field(default_factory=list)
+ #: The first settlement, spelled out, because one promise is the
+ #: overwhelming majority and every caller written before sets existed
+ #: still reads these. Never a *different* answer from `settlements`:
+ #: its head.
+ expectation: Optional[Expectation] = None
+ strategy: Optional[str] = None
+ amount: Optional[Decimal] = None
+ #: Set when a strategy matched a known fraction rather than the whole
+ #: Brazilian withholding is the reason this exists. The caller
+ #: books the difference; the engine only names it.
+ difference: Optional[Decimal] = None
+ difference_kind: Optional[str] = None
+ #: How well the winner scored, 1.0 when the strategy carries no
+ #: graded signal. A caller holding several movements for one
+ #: expectation ranks them by this: the recurring matcher does, and
+ #: has always taken the better-matching charge rather than refusing
+ #: both. Exposed rather than dug out of the trace because it is also
+ #: what a suggestion has to show a person to be worth showing. Zero
+ #: when nothing was decided, so an unmatched result never sorts above
+ #: a real one.
+ score: float = 0.0
+ trace: list[Consideration] = field(default_factory=list)
+
+
+def _amount_verdict(
+ movement: Decimal, expected: Decimal, rule: dict[str, Any], ratios: list[Decimal]
+) -> tuple[bool, Optional[Decimal], Optional[str]]:
+ """Does the money that moved answer the amount expected?
+
+ Returns whether it matched, the unexplained difference, and what that
+ difference is. `ratio` is the one that carries meaning: money arriving
+ at a known fraction of the invoice is withholding, not an error, and
+ the caller books it rather than asking a person about it.
+ """
+ match = rule.get("match", "exact")
+ moved = abs(movement)
+ want = abs(expected)
+
+ if match == "exact":
+ return moved == want, None, None
+
+ if match == "tolerance":
+ percent = Decimal(str(rule.get("percent", "0")))
+ allowed = (want * percent / Decimal("100")).copy_abs()
+ return abs(moved - want) <= allowed, None, None
+
+ if match == "partial":
+ # Money that covers *part* of what is owed. Two transactions
+ # settling one invoice is ordinary (an instalment, a client
+ # paying what they had), and the ledger has always supported it,
+ # but without this mode nothing could ever propose the first half:
+ # every other mode compares against the whole outstanding balance
+ # and a half is simply not it.
+ #
+ # Strictly less than, so this and `exact` never both fire and a
+ # trace never has to explain which one won.
+ if moved >= want or moved <= Decimal("0"):
+ return False, None, None
+
+ floor = Decimal(str(rule.get("min_ratio", "0")))
+ if floor > 0 and moved < (want * floor):
+ # A token amount against a large invoice is noise, not an
+ # instalment. Offering it would teach people to ignore the
+ # queue.
+ return False, None, None
+
+ ceiling = Decimal(str(rule.get("max_ratio", "1")))
+ if ceiling < 1 and moved > (want * ceiling):
+ # Money that is *almost* the whole thing is not an instalment
+ # either: it is a fee, a withholding, a rounding. Calling it
+ # a part payment would put a confident wrong word on the
+ # queue, and the tolerance rules are the ones written for it.
+ return False, None, None
+
+ return True, (want - moved), "part_payment"
+
+ if match == "ratio":
+ epsilon = Decimal(str(rule.get("epsilon", "0")))
+ for ratio in ratios:
+ target = (want * ratio).quantize(Decimal("0.01"))
+ if abs(moved - target) <= epsilon:
+ return True, (want - moved), rule.get("difference_kind")
+ return False, None, None
+
+ return False, None, None
+
+
+def _within_window(
+ movement_date: date,
+ expected: date,
+ rule: dict[str, Any],
+ issued: Optional[date] = None,
+) -> bool:
+ """Is this money close enough in time to be this promise's?
+
+ Asymmetric on purpose: money arrives *after* a due date far more
+ often than before it, and a symmetric window either misses the late
+ ones or reaches into the neighbouring occurrence.
+
+ The two sides are also measured from different days when the
+ expectation has both. **Late is late by reference to the due date;
+ early is early by reference to the day the promise was made.** An
+ invoice due on the 30th and issued on the 1st is not "29 days paid
+ early" when the client pays on the 2nd: it is paid the day after it
+ was issued, which is the best case there is. Collapsing both onto the
+ due date is what would push every deposit and every pay-then-invoice
+ into the rejected pile. A recurring occurrence has no separate issue
+ date, leaves `issued` null, and keeps the single-anchor behaviour it
+ has always had.
+ """
+ before = int(rule.get("before_days", 0))
+ after = int(rule.get("after_days", 0))
+ return (
+ ((issued or expected) - movement_date).days <= before
+ and (movement_date - expected).days <= after
+ )
+
+
+#: How many open promises a set rule will consider at once, and how many
+#: it will put in one answer. Both are hard limits rather than
+#: preferences: finding which invoices add up to a payment is subset-sum,
+#: which grows explosively, and a sync that hangs is worse than a match
+#: that is not made. Beyond these the engine says so and stops.
+MAX_SET_CANDIDATES = 12
+MAX_SET_SIZE = 6
+
+
+def _combinations_that_add_up(
+ moved: Decimal,
+ candidates: list[Expectation],
+ percent: Decimal,
+ max_size: int,
+) -> list[list[Expectation]]:
+ """Which groups of promises this payment could be covering.
+
+ Every group that fits, not the first one found, because the number of
+ answers *is* the finding. One combination is a match; two are a
+ question, and picking the first would be inventing certainty exactly
+ where the single-promise path refuses to.
+
+ Search order is smallest group first, so a payment that settles one
+ invoice exactly is never reported as also settling three that happen
+ to sum to the same figure.
+ """
+ found: list[list[Expectation]] = []
+ usable = [c for c in candidates if c.amount > Decimal("0")]
+ if len(usable) > MAX_SET_CANDIDATES:
+ return []
+
+ for size in range(2, min(max_size, len(usable)) + 1):
+ for group in itertools.combinations(usable, size):
+ total = sum((c.amount for c in group), Decimal("0"))
+ # The allowance is a share of what the invoices are worth, not
+ # of what arrived. A gateway's cut is a percentage of the
+ # gross, and "two per cent" should mean the thing a person
+ # means by it rather than two per cent of the figure left
+ # after the cut.
+ tolerance = (total * percent / Decimal("100")).copy_abs()
+ if abs(total - moved) <= tolerance:
+ found.append(list(group))
+ # Two is already an answer of "ask a person", so there is
+ # nothing to learn from finding a third.
+ if len(found) > 1:
+ return found
+ return found
+
+
+def _in_scope(
+ movement: Movement, rule: dict[str, Any], base_currency: Optional[str]
+) -> bool:
+ """Does this rule apply to this money at all?
+
+ Separate from the comparisons below, and worth naming as its own idea.
+ Every other signal asks *how well the pair fits*; these ask *whether
+ the rule was written for money like this*: a specific account, a
+ currency that is not the one you normally deal in, an amount above the
+ threshold where you stop trusting an automatic match, a statement line
+ whose text you recognise.
+
+ That distinction is what the rule tools converged on independently:
+ they let a rule name its bank account, its direction
+ and a text fragment before any comparison happens. Without it a rule
+ can only say "money like this matches invoices like that", and every
+ real request (*only for dollars*, *only above ten thousand*, *only
+ this client*) is inexpressible.
+
+ All conditions must hold. Deliberately no ANY/OR mode, unlike the
+ categorization rules: those pick a label and a wrong guess is a
+ mislabelled row, while these bind money to a debt. "The amount matches
+ OR the date is close" is a sentence with no safe reading.
+ """
+ accounts = rule.get("accounts", {}).get("in")
+ if accounts and str(movement.account_id) not in {str(a) for a in accounts}:
+ return False
+
+ payees = rule.get("payees", {}).get("in")
+ if payees and str(movement.payee_id) not in {str(p) for p in payees}:
+ return False
+
+ direction = rule.get("direction")
+ if direction and direction != "any" and movement.direction != direction:
+ return False
+
+ currency = rule.get("currency", {})
+ allowed = currency.get("in")
+ if allowed and movement.currency not in set(allowed):
+ return False
+ if currency.get("foreign"):
+ # "Foreign" is relative to the workspace, so without knowing the
+ # base currency the honest answer is that the rule does not apply,
+ # never that everything is foreign.
+ if not base_currency or movement.currency == base_currency:
+ return False
+
+ amount_rule = rule.get("amount", {})
+ moved = abs(movement.amount)
+ minimum = amount_rule.get("min")
+ if minimum not in (None, "") and moved < Decimal(str(minimum)):
+ return False
+ maximum = amount_rule.get("max")
+ if maximum not in (None, "") and moved > Decimal(str(maximum)):
+ return False
+
+ text = rule.get("text", {})
+ if text:
+ # Both fields, as one haystack. The identifying words land in
+ # whichever of the two the bank felt like using, and asking a
+ # person which field their bank prefers is asking them to know
+ # something about our data model.
+ printed = " ".join(
+ part.lower()
+ for part in (movement.description, movement.counterparty)
+ if part
+ )
+ wanted = _as_list(text.get("contains"))
+ # Any of them, not all: somebody receiving through three acquirers
+ # wants one rule saying "a payout from any of these", not three
+ # rules that differ by a word.
+ if wanted and not any(word.lower() in printed for word in wanted):
+ return False
+ for word in _as_list(text.get("not_contains")):
+ if word.lower() in printed:
+ return False
+
+ return True
+
+
+def _as_list(value: Any) -> list[str]:
+ """One word or several, read the same way.
+
+ Stored as a list once a rule names alternatives; a plain string is
+ still accepted because every rule written before this said one word.
+ """
+ if value in (None, ""):
+ return []
+ if isinstance(value, str):
+ return [value]
+ return [str(item) for item in value if str(item).strip()]
+
+
+def _eligible_for_set(
+ movement: Movement, candidate: Expectation, rule: dict[str, Any]
+) -> bool:
+ """Whether a promise may take part in a combination at all.
+
+ Every condition except the amount, because the amount is the one being
+ asked about the group rather than the member. Narrowing first is also
+ what keeps the search tractable: a rule that demands the same client
+ usually leaves three or four candidates, not four hundred.
+ """
+ if candidate.direction != movement.direction:
+ return False
+ if candidate.amount <= Decimal("0"):
+ return False
+ if candidate.currency != movement.currency:
+ return False
+ if rule.get("counterparty") == "same_payee":
+ if not movement.payee_id or movement.payee_id != candidate.payee_id:
+ return False
+ if rule.get("same_account") and movement.account_id != candidate.account_id:
+ return False
+ if not _within_window(movement.when, candidate.when, rule.get("date", {}), candidate.issued):
+ return False
+ return True
+
+
+ZERO = Decimal("0")
+#: Money is stored to two places, so a share of it has to land there too.
+CENTS = Decimal("0.01")
+
+def _share_out(moved: Decimal, chosen: list[Expectation]) -> list[Settlement]:
+ """Split what arrived across the promises it answers.
+
+ The single-candidate path settles `min(what moved, what is owed)`, and
+ this is the same rule for a group: a payment can never write more than
+ it carried. Without it a tolerance-based group was allowed to settle
+ every invoice at its full value, so 980 arriving against two invoices
+ of 500 wrote 1.000 of allocations. `allocate` would not catch it: it
+ guards each invoice's own balance and knows nothing about how much of
+ the transaction earlier members of the group already spent.
+
+ Short payments are shared **in proportion**, because that is what the
+ shortfall usually is: a gateway's cut is a percentage of the gross, so
+ the larger invoice gives up the larger part of it. The rounding
+ residue lands on the last settlement, which keeps the parts summing to
+ exactly what moved rather than to a figure a cent away from it.
+
+ A payment larger than the group (interest, a late fee) is not shared
+ out at all. Each invoice closes at its value and the surplus stays on
+ the transaction, where `difference` names it.
+ """
+ total = sum((c.amount for c in chosen), Decimal("0"))
+ if total <= moved or total <= ZERO:
+ return [Settlement(expectation=c, amount=c.amount) for c in chosen]
+
+ settlements: list[Settlement] = []
+ spent = Decimal("0")
+ for candidate in chosen[:-1]:
+ share = (moved * candidate.amount / total).quantize(CENTS, rounding=ROUND_DOWN)
+ settlements.append(Settlement(expectation=candidate, amount=share))
+ spent += share
+ settlements.append(Settlement(expectation=chosen[-1], amount=moved - spent))
+ return settlements
+
+
+def _evaluate_set(
+ movement: Movement,
+ candidates: list[Expectation],
+ strategy: dict[str, Any],
+ rule: dict[str, Any],
+ policy: dict[str, Any],
+ base_currency: Optional[str],
+ trace: list[Consideration],
+) -> Optional[Decision]:
+ """One payment against several promises.
+
+ Returns a decision when this rule has something to say, and nothing
+ when it does not, so the strategies after it still get their turn.
+
+ The whole design of the rest of this module carries over unchanged:
+ **one answer is a match, more than one is a question.** Three invoices
+ of a thousand and a credit of two thousand admit three equally good
+ readings, and choosing among them is a person's job.
+ """
+ amount_rule = rule.get("amount", {})
+ eligible = [c for c in candidates if _eligible_for_set(movement, c, rule)]
+ moved = abs(movement.amount)
+
+ if len(eligible) < 2:
+ return None
+
+ if len(eligible) > MAX_SET_CANDIDATES:
+ # Refusing loudly. Silently searching a space this size would make
+ # a sync unpredictable, and silently skipping it would leave
+ # somebody wondering why their payout never matched.
+ trace.append(
+ Consideration(
+ expectation_id=eligible[0].id,
+ strategy=strategy["id"],
+ rejected_by=Reason.TOO_MANY_TO_COMBINE,
+ )
+ )
+ return None
+
+ percent = Decimal(str(amount_rule.get("percent", "0")))
+ max_size = min(int(amount_rule.get("max_invoices", MAX_SET_SIZE)), MAX_SET_SIZE)
+
+ groups = _combinations_that_add_up(moved, eligible, percent, max_size)
+ if not groups:
+ for candidate in eligible:
+ trace.append(
+ Consideration(
+ expectation_id=candidate.id,
+ strategy=strategy["id"],
+ rejected_by=Reason.AMOUNT,
+ )
+ )
+ return None
+
+ outcome = strategy.get("outcome", "suggest")
+ if len(groups) > 1:
+ # Several combinations fit. Which one is a question about intent,
+ # not about arithmetic, so it goes to a person.
+ outcome = policy.get("on_ambiguity", "suggest")
+ for candidate in eligible:
+ trace.append(
+ Consideration(
+ expectation_id=candidate.id,
+ strategy=strategy["id"],
+ rejected_by=Reason.AMBIGUOUS_SET,
+ )
+ )
+
+ chosen = groups[0]
+ settlements = _share_out(moved, chosen)
+ # The gap is measured against what the invoices are **worth**, not
+ # against what was written. Sharing out caps the allocations at what
+ # arrived, so comparing with those would report a gap of zero and the
+ # gateway's cut would go unnamed: the one number a later deduction
+ # has to book.
+ promised = sum((c.amount for c in chosen), Decimal("0"))
+
+ for candidate in chosen:
+ trace.append(
+ Consideration(
+ expectation_id=candidate.id, strategy=strategy["id"], score=1.0
+ )
+ )
+
+ return Decision(
+ port="linked" if outcome == "link" else "suggested",
+ settlements=settlements,
+ expectation=settlements[0].expectation,
+ strategy=strategy["id"],
+ amount=settlements[0].amount,
+ # What the payment carried beyond the invoices it covers: a
+ # gateway fee, a bank charge, a rounding. Named rather than
+ # swallowed, so the caller can book it instead of leaving money
+ # unexplained.
+ difference=(moved - promised) if moved != promised else None,
+ difference_kind="set_difference" if moved != promised else None,
+ score=1.0,
+ trace=trace,
+ )
+
+
+def evaluate(
+ movement: Movement,
+ candidates: list[Expectation],
+ policy: dict[str, Any],
+ *,
+ withholding_ratios: Optional[list[Decimal]] = None,
+ base_currency: Optional[str] = None,
+ trigger: str = "money_arrives",
+) -> Decision:
+ """Which expectation this movement settles, if any.
+
+ Strategies are ordered and the first one to match wins; the same
+ precedence `rules.priority` already has, so there is one mental model
+ for "which rule applied" across the product.
+
+ `base_currency` is what the workspace normally deals in, and is only
+ consulted by rules that say "foreign": what counts as foreign is a
+ fact about the workspace, not about the money.
+
+ `trigger` says which of the two moments this is (money arriving, or a
+ document being written), and rules that were not written for this
+ moment sit it out.
+ """
+ trace: list[Consideration] = []
+ ratios = withholding_ratios or []
+
+ ignored = set(policy.get("scope", {}).get("ignore_transaction_sources", []))
+ if movement.source and movement.source in ignored:
+ # A generated placeholder is a promise, not the money. Matching a
+ # promise against a promise would settle an invoice with nothing.
+ return Decision(port="unmatched", trace=[])
+
+ for strategy in policy.get("strategies", []):
+ if not strategy.get("enabled", True):
+ continue
+ # Written for the other moment. Looking back at money that was
+ # already there is weaker evidence than answering a promise that
+ # was waiting, so a rule is allowed to say it only trusts one of
+ # them, and saying so on the page beats the same restriction
+ # hardcoded into whichever function does the looking.
+ wanted = strategy.get("trigger", "money_arrives")
+ if wanted != "both" and wanted != trigger:
+ trace.append(
+ Consideration(
+ expectation_id=candidates[0].id if candidates else uuid.uuid4(),
+ strategy=strategy["id"],
+ rejected_by=Reason.WRONG_MOMENT,
+ )
+ )
+ continue
+
+ rule = strategy.get("when", {})
+ if not _in_scope(movement, rule, base_currency):
+ # Not written for money like this. One note rather than one per
+ # candidate: the rule was never consulted, so there is nothing
+ # to say about any particular promise.
+ trace.append(
+ Consideration(
+ expectation_id=candidates[0].id if candidates else uuid.uuid4(),
+ strategy=strategy["id"],
+ rejected_by=Reason.OUT_OF_SCOPE,
+ )
+ )
+ continue
+ # A payment that answers several promises at once. Kept as its own
+ # branch because it asks a different question of the candidates:
+ # not "which one of you is this" but "which of you, together".
+ if rule.get("amount", {}).get("match") == "set":
+ decision = _evaluate_set(
+ movement, candidates, strategy, rule, policy, base_currency, trace
+ )
+ if decision is not None:
+ return decision
+ continue
+
+ matched: list[tuple[Expectation, Optional[Decimal], Optional[str], float]] = []
+
+ for candidate in candidates:
+ note = Consideration(expectation_id=candidate.id, strategy=strategy["id"])
+
+ if candidate.direction != movement.direction:
+ note.rejected_by = Reason.DIRECTION
+ trace.append(note)
+ continue
+
+ if candidate.amount <= Decimal("0"):
+ note.rejected_by = Reason.ALREADY_SETTLED
+ trace.append(note)
+ continue
+
+ # Always, and not a setting.
+ #
+ # There was a `currency.conversion` knob here whose "allow"
+ # value read as *convert and compare*. It did no such thing:
+ # this module is pure and holds no session, so it cannot look
+ # up a rate. All "allow" did was stop comparing currencies,
+ # which made a $3.000 payment an **exact** match for a €3.000
+ # invoice and settled the euros with the dollars.
+ #
+ # Matching across currencies needs three things this does not
+ # have: a rate, a date to take it on (the invoice's or the
+ # bank's, and they differ), and somewhere to put the leftover
+ # difference. The third is the same booking problem as
+ # withholding, which is why it belongs with deductions rather
+ # than here.
+ if candidate.currency != movement.currency:
+ note.rejected_by = Reason.CURRENCY
+ trace.append(note)
+ continue
+
+ if rule.get("counterparty") == "same_payee":
+ if not movement.payee_id or movement.payee_id != candidate.payee_id:
+ note.rejected_by = Reason.COUNTERPARTY
+ trace.append(note)
+ continue
+
+ if rule.get("same_account") and movement.account_id != candidate.account_id:
+ note.rejected_by = Reason.COUNTERPARTY
+ trace.append(note)
+ continue
+
+ ok, difference, difference_kind = _amount_verdict(
+ movement.amount, candidate.amount, rule.get("amount", {}), ratios
+ )
+ if not ok:
+ note.rejected_by = Reason.AMOUNT
+ trace.append(note)
+ continue
+
+ if not _within_window(
+ movement.when, candidate.when, rule.get("date", {}), candidate.issued
+ ):
+ note.rejected_by = Reason.DATE
+ trace.append(note)
+ continue
+
+ score = 1.0
+ similarity = rule.get("description_similarity")
+ if similarity:
+ score = token_overlap(movement.description, candidate.description)
+ if score < float(similarity.get("min", 0)):
+ note.rejected_by = Reason.DESCRIPTION
+ note.score = score
+ trace.append(note)
+ continue
+
+ note.score = score
+ trace.append(note)
+ matched.append((candidate, difference, difference_kind, score))
+
+ if not matched:
+ continue
+
+ outcome = strategy.get("outcome", "suggest")
+ if len(matched) > 1:
+ if rule.get("unique_candidate", False):
+ # Several answers to a question that admits one. Downgrade
+ # rather than guess: picking the highest score here would
+ # be inventing certainty the signals do not carry.
+ outcome = policy.get("on_ambiguity", "suggest")
+ for note in trace:
+ if note.strategy == strategy["id"] and note.rejected_by is None:
+ note.rejected_by = Reason.AMBIGUOUS
+ matched.sort(key=lambda m: m[3], reverse=True)
+
+ winner, difference, difference_kind, score = matched[0]
+ settled = min(abs(movement.amount), winner.amount)
+ return Decision(
+ port="linked" if outcome == "link" else "suggested",
+ # Always a set, even when it holds one. A caller that has to
+ # ask "is this the single kind or the several kind" before it
+ # can write anything is a caller that will one day forget to.
+ settlements=[Settlement(expectation=winner, amount=settled)],
+ expectation=winner,
+ strategy=strategy["id"],
+ amount=settled,
+ difference=difference,
+ difference_kind=difference_kind,
+ score=score,
+ trace=trace,
+ )
+
+ return Decision(port="unmatched", trace=trace)
diff --git a/backend/app/services/reconciliation_history_service.py b/backend/app/services/reconciliation_history_service.py
new file mode 100644
index 00000000..f8c38587
--- /dev/null
+++ b/backend/app/services/reconciliation_history_service.py
@@ -0,0 +1,108 @@
+"""What matching did, written down and read back.
+
+Two functions, and that is the whole module. The restraint is the design:
+almost everything a person calls "the history" is already stored
+elsewhere, so the temptation is to build a second copy of the ledger and
+call it an audit trail. What was actually missing is narrower: a single
+stream, in one order, including the one event that used to vanish.
+
+## What gets written, and what deliberately does not
+
+Written: a link made, a question asked, a question answered, a link
+undone. Six verbs, each of which changed something a person can see.
+
+`linked` and `accepted` are **not** both written for one act. A link the
+rules made on their own is `linked`; a link a person made by accepting a
+question is `accepted`, and the allocation is its consequence rather than
+a second event. That is the same line the whole stream is organised
+around (*was this me, or was this the rules?*), and writing both would
+put two rows against one decision and blur it.
+
+Not written: everything the engine looked at and passed over. A sync of
+three hundred transactions where two hundred and ninety match nothing
+would produce two hundred and ninety rows saying so, and a history nobody
+can scan is the same as no history. The engine's full trace (which rule
+fired, why each candidate lost) stays in memory and reaches a person
+through the queue's evidence, where it is attached to a decision they
+have to make rather than filed away for nobody.
+"""
+from __future__ import annotations
+
+import uuid
+from decimal import Decimal
+from typing import Any, Optional
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.reconciliation import ReconciliationEvent
+
+#: The six things worth remembering.
+Action = str
+
+
+async def record(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ action: Action,
+ *,
+ expectation_kind: str,
+ expectation_id: uuid.UUID,
+ amount: Decimal,
+ transaction_id: Optional[uuid.UUID] = None,
+ strategy_id: Optional[str] = None,
+ user_id: Optional[uuid.UUID] = None,
+ detail: Optional[dict[str, Any]] = None,
+) -> ReconciliationEvent:
+ """Note that something happened.
+
+ `user_id` left null says the system did it on its own, which is the
+ distinction a reader reaches for first: was this me, or was this the
+ rules?
+
+ Never raises on its own account. A history that can fail a sync is a
+ history that will one day be removed from the sync.
+ """
+ event = ReconciliationEvent(
+ id=uuid.uuid4(),
+ workspace_id=workspace_id,
+ action=action,
+ transaction_id=transaction_id,
+ expectation_kind=expectation_kind,
+ expectation_id=expectation_id,
+ amount=amount,
+ strategy_id=strategy_id,
+ user_id=user_id,
+ detail=detail or {},
+ )
+ session.add(event)
+ return event
+
+
+async def recent(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ *,
+ expectation_id: Optional[uuid.UUID] = None,
+ limit: int = 50,
+) -> list[ReconciliationEvent]:
+ """The stream, newest first.
+
+ Newest first here and oldest first in the queue, on purpose: a queue
+ is work to get through, so the oldest question is the most urgent,
+ while a history is read to find out what just happened.
+
+ `expectation_id` narrows it to one promise (everything that ever
+ happened to this invoice), which is the second and only other way
+ anybody reads this.
+ """
+ query = select(ReconciliationEvent).where(
+ ReconciliationEvent.workspace_id == workspace_id
+ )
+ if expectation_id is not None:
+ query = query.where(ReconciliationEvent.expectation_id == expectation_id)
+
+ result = await session.execute(
+ query.order_by(ReconciliationEvent.at.desc()).limit(min(limit, 200))
+ )
+ return list(result.scalars().all())
diff --git a/backend/app/services/reconciliation_policy.py b/backend/app/services/reconciliation_policy.py
new file mode 100644
index 00000000..3f8dc6f5
--- /dev/null
+++ b/backend/app/services/reconciliation_policy.py
@@ -0,0 +1,310 @@
+"""The rules matching follows, as data rather than as code.
+
+Two nodes ship: one for money arriving against an invoice, one for money
+moving against a recurring bill. They are separate documents because
+their scopes genuinely differ (an invoice has no account and is settled
+N:N, a recurring bill is anchored to one account and settled once), and
+because a workspace should be able to loosen one without touching the
+other.
+
+**Defaults ship with the image; a workspace stores only what it changed.**
+Copying the defaults into every workspace at creation would freeze them:
+a better default six months from now would never reach anyone who had
+already opened the module. An untouched strategy keeps improving with the
+product, and the UI renders shipped ∪ override.
+
+Nothing here is surfaced yet. It is written as a document from the first
+line because the direction for automations is a node graph, and a
+threshold that starts life as a constant inside an engine has to be
+excavated later; see `recurring_match_service`, whose numbers were
+excellent and unreachable.
+"""
+from __future__ import annotations
+
+import copy
+from decimal import Decimal
+from typing import Any
+
+#: Bumped when the shape changes in a way a stored override must be
+#: migrated against. Overrides record the version they were written for.
+POLICY_VERSION = 1
+
+#: Money moving against an invoice, in either direction.
+#:
+#: Named for the object rather than the direction: a payable is settled
+#: by money going out and by the same strategies, and the engine already
+#: refuses a candidate whose direction disagrees with the movement. A
+#: node called `match_receivable` that also matched bills would be a name
+#: that lies.
+#:
+#: The withholding strategy is a `link` rather than a `suggest`, and that
+#: is the most consequential line in this file. A R$3.000 invoice paid by
+#: a Brazilian company lands as R$2.955 or R$2.860,50: withholding is
+#: 1.5–11%, not cents. Sending those to a confirmation queue would send
+#: *the best clients* to the queue, and the accountant interview is
+#: explicit that import-then-make-the-user-confirm is what killed
+#: adoption of the incumbent.
+MATCH_INVOICE: dict[str, Any] = {
+ "version": POLICY_VERSION,
+ "node": "reconciliation.match_invoice",
+ "scope": {
+ "movement": "any",
+ "candidate_states": ["open", "partial", "overdue"],
+ # A generated placeholder is a promise, not the money that keeps
+ # it. Matching one against an invoice would settle a debt with
+ # another debt.
+ "ignore_transaction_sources": ["recurring"],
+ },
+ "strategies": [
+ {
+ "id": "same_client_exact",
+ "enabled": True,
+ "outcome": "link",
+ # Runs at both moments: a known client paying the exact amount
+ # is as convincing before the nota as after it, and the
+ # pay-then-invoice case is ordinary here.
+ "trigger": "both",
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "exact"},
+ # `before_days` counts back from the **issue date**, not
+ # the due date: a client who pays a deposit, or pays on
+ # the promise of a nota that follows, is the ordinary
+ # case here and not an anomaly to be queued.
+ "date": {"before_days": 10, "after_days": 60},
+ "currency": {"conversion": "reject"},
+ "unique_candidate": True,
+ },
+ },
+ {
+ "id": "same_client_net_of_withholding",
+ "enabled": True,
+ "outcome": "link",
+ "trigger": "both",
+ "when": {
+ "counterparty": "same_payee",
+ # Ratios come from the jurisdiction pack, never from
+ # here: shapes in this file, vocabulary in the pack.
+ "amount": {
+ "match": "ratio",
+ "ratios": "@jurisdiction.withholding_ratios",
+ "epsilon": "0.02",
+ "difference_kind": "withholding_tax",
+ },
+ "date": {"before_days": 10, "after_days": 60},
+ "currency": {"conversion": "reject"},
+ "unique_candidate": True,
+ },
+ },
+ {
+ "id": "exact_amount_any_client",
+ "enabled": True,
+ "outcome": "link",
+ # Only when money arrives. Backwards, an exact amount from a
+ # payer we cannot name is not enough: that money already had a
+ # life of its own (a refund, a transfer, another job), and
+ # claiming it for a document written afterwards is a guess.
+ "trigger": "money_arrives",
+ "when": {
+ "counterparty": "any",
+ "amount": {"match": "exact"},
+ "date": {"before_days": 3, "after_days": 15},
+ "currency": {"conversion": "reject"},
+ "unique_candidate": True,
+ },
+ },
+ {
+ "id": "same_client_several_invoices",
+ "enabled": True,
+ # A link, because the arithmetic either works out or it does
+ # not: the engine only gets here when exactly one combination
+ # of this client's open invoices adds up to what arrived. Two
+ # combinations is a question, and the engine downgrades it on
+ # its own.
+ "outcome": "link",
+ "trigger": "money_arrives",
+ "when": {
+ "counterparty": "same_payee",
+ # The sum of several promises rather than any one of them.
+ # `percent` at zero means the total must be exact: a
+ # payout net of a fee needs a tolerance, and guessing
+ # which fee applies is how a wrong split gets written
+ # confidently. Somebody who knows their gateway's cut can
+ # set it here.
+ "amount": {"match": "set", "max_invoices": 6, "percent": "0"},
+ "date": {"before_days": 10, "after_days": 60},
+ "currency": {"conversion": "reject"},
+ },
+ },
+ {
+ "id": "same_client_part_payment",
+ "enabled": True,
+ # A suggestion, not a link. Money that covers part of an
+ # invoice is genuinely ambiguous (an instalment, a client
+ # paying what they had, or a different job entirely), and the
+ # difference matters enough to ask. Promoting it to a link is
+ # one click for somebody whose clients always pay in parts.
+ "outcome": "suggest",
+ "trigger": "both",
+ "when": {
+ "counterparty": "same_payee",
+ # The mode that makes two transactions on one invoice
+ # reachable at all. Every other mode compares against the
+ # whole outstanding balance, so nothing could ever propose
+ # the first half of a payment made in two.
+ # Between a twentieth and nineteen twentieths of what is
+ # owed. Below that it is noise; above it, the gap is a fee
+ # or a withholding rather than an instalment, and the
+ # tolerance rules are the ones written for that.
+ "amount": {
+ "match": "partial",
+ "min_ratio": "0.05",
+ "max_ratio": "0.95",
+ },
+ "date": {"before_days": 10, "after_days": 60},
+ "currency": {"conversion": "reject"},
+ "unique_candidate": True,
+ },
+ },
+ {
+ "id": "similar_description",
+ "enabled": True,
+ "outcome": "suggest",
+ "trigger": "money_arrives",
+ "when": {
+ "counterparty": "any",
+ "amount": {"match": "tolerance", "percent": "2"},
+ "date": {"before_days": 10, "after_days": 45},
+ "description_similarity": {"min": "0.6"},
+ },
+ },
+ ],
+ "on_ambiguity": "suggest",
+}
+
+#: Money moving against a recurring bill or income.
+#:
+#: **These numbers are not new.** They are what
+#: `recurring_match_service` has run in production since issue #116,
+#: lifted out of the code unchanged: same account, same direction, exact
+#: amount, 3 days before / 5 after (2/2 weekly), description similarity
+#: at 0.6, and only the exact tier auto-links. Reproducing today's
+#: behaviour exactly is the point: a personal workspace should notice
+#: nothing on the day this lands, and gain the ability to change it on
+#: the day the automations screen ships.
+MATCH_RECURRING: dict[str, Any] = {
+ "version": POLICY_VERSION,
+ "node": "reconciliation.match_recurring",
+ "scope": {
+ "movement": "any",
+ # The placeholder is what we are matching *to*, so unlike the
+ # receivable node this one has nothing to ignore.
+ "ignore_transaction_sources": [],
+ },
+ "strategies": [
+ {
+ "id": "same_account_exact",
+ "enabled": True,
+ "outcome": "link",
+ "trigger": "money_arrives",
+ "when": {
+ "counterparty": "any",
+ "same_account": True,
+ "amount": {"match": "exact"},
+ "date": {"before_days": 3, "after_days": 5},
+ "currency": {"conversion": "reject"},
+ "description_similarity": {"min": "0.6"},
+ # Deliberately **not** `unique_candidate`, unlike the
+ # invoice node. Two placeholders of the same value on one
+ # account are told apart by description, and production
+ # has always taken the better-matching one rather than
+ # refusing both. Refusing here would be a stricter product
+ # than the one running today, on the day this lands, for
+ # people who never asked for reconciliation at all.
+ },
+ },
+ ],
+ "on_ambiguity": "suggest",
+}
+
+#: A real charge arriving where a generated placeholder is already
+#: standing.
+#:
+#: Separate from `match_recurring` because its window genuinely differs:
+#: five days either side, the same on both, regardless of how often the
+#: bill repeats. That is not an oversight in the code this replaces: the
+#: placeholder was written *for* a specific occurrence, so there is no
+#: neighbouring occurrence to be confused with, and the window can afford
+#: to be symmetric where the bill-level one cannot.
+MATCH_PLACEHOLDER: dict[str, Any] = {
+ "version": POLICY_VERSION,
+ "node": "reconciliation.match_placeholder",
+ "scope": {
+ "movement": "any",
+ "ignore_transaction_sources": [],
+ },
+ "strategies": [
+ {
+ "id": "placeholder_same_account_exact",
+ "enabled": True,
+ "outcome": "link",
+ "trigger": "money_arrives",
+ "when": {
+ "counterparty": "any",
+ "same_account": True,
+ "amount": {"match": "exact"},
+ "date": {"before_days": 5, "after_days": 5},
+ "currency": {"conversion": "reject"},
+ "description_similarity": {"min": "0.6"},
+ },
+ },
+ ],
+ "on_ambiguity": "suggest",
+}
+
+#: A weekly bill sits closer to its neighbours, so its window narrows or
+#: a charge could match the wrong occurrence. Carried as an override on
+#: the strategy rather than as a second document.
+RECURRING_WINDOW_BY_FREQUENCY: dict[str, dict[str, int]] = {
+ "weekly": {"before_days": 2, "after_days": 2},
+}
+
+_DEFAULTS: dict[str, dict[str, Any]] = {
+ MATCH_INVOICE["node"]: MATCH_INVOICE,
+ MATCH_RECURRING["node"]: MATCH_RECURRING,
+ MATCH_PLACEHOLDER["node"]: MATCH_PLACEHOLDER,
+}
+
+
+def default_policy(node: str) -> dict[str, Any]:
+ """The shipped document for one node.
+
+ Deep-copied, because callers adjust it per movement (the recurring
+ window narrows for a weekly bill), and a caller must never be able to
+ edit the defaults for everyone else in the process.
+ """
+ try:
+ return copy.deepcopy(_DEFAULTS[node])
+ except KeyError:
+ raise ValueError(f"Unknown reconciliation node '{node}'") from None
+
+
+def for_recurring(frequency: str) -> dict[str, Any]:
+ """The recurring node, with the window this frequency needs."""
+ policy = default_policy(MATCH_RECURRING["node"])
+ window = RECURRING_WINDOW_BY_FREQUENCY.get(frequency)
+ if window:
+ for strategy in policy["strategies"]:
+ strategy["when"]["date"] = dict(window)
+ return policy
+
+
+def withholding_ratios(jurisdiction: str | None) -> list[Decimal]:
+ """What fraction of an invoice a client may actually pay.
+
+ Placeholder until the jurisdiction pack carries these: the ratio
+ strategy is disabled in practice while this returns nothing, which is
+ the honest state: a wrong ratio would auto-link a wrong amount, and
+ that is worse than asking.
+ """
+ return []
diff --git a/backend/app/services/reconciliation_portability.py b/backend/app/services/reconciliation_portability.py
new file mode 100644
index 00000000..4c641366
--- /dev/null
+++ b/backend/app/services/reconciliation_portability.py
@@ -0,0 +1,308 @@
+"""Carrying a matching policy from one Securo to another.
+
+## Why a file at all
+
+The rules that decide whether a payment settles an invoice are the most
+carefully tuned thing on the page, and they are worth more than one
+workspace. An accountant who has worked out how their clients' banks
+actually behave should be able to hand that to the next workspace, and to
+the next machine, without retyping eleven thresholds. Categorization
+rules already travel this way; there was no reason matching should not.
+
+## What travels, and what cannot
+
+**Ids do not travel.** A rule limited to two bank accounts names them by
+UUID, and that UUID means nothing in another database. So the file
+carries names, and importing looks them up again. A name that finds
+nothing is *not* silently dropped: a rule that was limited to one client
+and arrives limited to nobody is a different rule, and a wider one: the
+dangerous direction when the decision is whether money moves. Those rules
+are skipped and counted, so the number on screen is the truth.
+
+**Shipped rules travel as a reference, not a copy.** The file says "the
+rule we call `same_client_exact`, with these thresholds", not the whole
+strategy. Copying it in would freeze it, and a workspace that imported a
+policy in March would stop receiving improvements to rules it never had
+an opinion about. On import an entry becomes what it already was: the
+difference between the file and what we ship *today*.
+
+An id in the file that this version no longer ships is skipped rather
+than guessed at.
+
+**Deletions travel too.** "I do not run this rule" is part of a policy,
+and a file that quietly restored six rules the author had thrown away
+would describe a policy nobody chose.
+
+## Why import replaces rather than merges
+
+Merging two orderings has no correct answer, and order is the whole
+mechanism here: the first rule that matches wins, so a rule's meaning
+depends on what sits above it. A merge would produce a policy neither
+side wrote. So an import replaces the workspace's matching rules, and the
+screen asks first.
+"""
+from __future__ import annotations
+
+import uuid
+from typing import Any, Optional
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.payee import Payee
+from app.services import reconciliation_policy, reconciliation_rule_service as rules
+
+#: What the file says it is. Checked on import, because a categorization
+#: export dropped into the matching importer would otherwise arrive as a
+#: file with no rules in it and look like it worked.
+FORMAT = "securo-reconciliation-rules"
+
+#: The `when` keys holding ids of things that live in a database, and the
+#: kind of thing each holds. Everything else in a rule is a number, a word
+#: or a flag, and travels as it is.
+BY_NAME = {"accounts": "account", "payees": "payee"}
+
+
+async def _directory(
+ session: AsyncSession, workspace_id: uuid.UUID
+) -> tuple[dict[str, dict[str, str]], dict[str, dict[str, str]]]:
+ """Ids to names, and names back to ids, for one workspace."""
+ accounts = (
+ await session.execute(select(Account).where(Account.workspace_id == workspace_id))
+ ).scalars().all()
+ payees = (
+ await session.execute(select(Payee).where(Payee.workspace_id == workspace_id))
+ ).scalars().all()
+
+ to_name = {
+ "account": {str(a.id): a.name for a in accounts},
+ "payee": {str(p.id): p.name for p in payees},
+ }
+ # Last one wins on a duplicate name, which is the same thing the
+ # categorization import does. Two accounts called "Checking" is a
+ # problem a person has to fix; guessing between them here would only
+ # hide it.
+ to_id = {
+ "account": {a.name: str(a.id) for a in accounts},
+ "payee": {p.name: str(p.id) for p in payees},
+ }
+ return to_name, to_id
+
+
+def _swap(
+ when: dict[str, Any], table: dict[str, dict[str, str]]
+) -> Optional[dict[str, Any]]:
+ """Rewrite the id lists in a `when` block through `table`.
+
+ Returns None when any single entry cannot be translated. Not a
+ partial answer: half of a two-account restriction is a rule that
+ matches money it was told not to.
+ """
+ out = dict(when)
+ for key, kind in BY_NAME.items():
+ block = out.get(key)
+ if not isinstance(block, dict):
+ continue
+ values = block.get("in") or []
+ swapped = []
+ for value in values:
+ found = table[kind].get(str(value))
+ if found is None:
+ return None
+ swapped.append(found)
+ out[key] = {**block, "in": swapped}
+ return out
+
+
+async def export_policy(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ nodes: Optional[tuple[str, ...]] = None,
+) -> dict[str, Any]:
+ """The matching policy this workspace runs, as a portable document.
+
+ `nodes` narrows it to the sets this workspace has, so a file carries
+ what its author could actually see. Defaults to every editable set,
+ which is what a caller with no module opinion means.
+ """
+ to_name, _ = await _directory(session, workspace_id)
+ rows = await rules.overrides_for(session, workspace_id)
+
+ carried_nodes = []
+ for node in (nodes if nodes is not None else rules.EDITABLE_NODES):
+ policy = rules.compose(node, [r for r in rows if r.node == node])
+ carried = []
+ for strategy in policy["strategies"]:
+ when = _swap(strategy.get("when") or {}, to_name)
+ if when is None:
+ # An account or client the rule names is gone from this
+ # workspace. Exporting it by id would produce a file that
+ # cannot be read anywhere, including here.
+ continue
+ carried.append(
+ {
+ "id": strategy["id"],
+ "origin": strategy["origin"],
+ "name": strategy.get("name"),
+ "enabled": strategy.get("enabled", True),
+ "outcome": strategy["outcome"],
+ "trigger": strategy.get("trigger", "money_arrives"),
+ "when": when,
+ }
+ )
+ carried_nodes.append(
+ {
+ "node": node,
+ "rules": carried,
+ "discarded": [item["id"] for item in policy.get("discarded", [])],
+ }
+ )
+
+ return {
+ "format": FORMAT,
+ "version": 1,
+ # Which shape the rules were written against, so a file from an
+ # older Securo can be recognised rather than half-read.
+ "policy_version": reconciliation_policy.POLICY_VERSION,
+ "nodes": carried_nodes,
+ }
+
+
+async def import_policy(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ payload: dict[str, Any],
+ *,
+ overwrite: bool = False,
+ nodes: Optional[tuple[str, ...]] = None,
+) -> dict[str, int]:
+ """Make this workspace's matching policy match the file.
+
+ Replaces rather than merges; see the module docstring. Returns what
+ happened in numbers, because "12 imported" and "12 imported, 3
+ skipped" are different outcomes and only one of them needs looking
+ into.
+
+ **Worked out in full before anything is removed.** Replacing means
+ deleting what is here, and a malformed entry discovered after that
+ left the workspace with no rules and a count of what was skipped: the
+ policy erased, and nothing on screen saying why. So the whole file is
+ resolved first and a structurally broken one is refused with its
+ reason, while the rules this workspace has are still standing.
+
+ A skip is not a refusal. A set this workspace does not have, an
+ account or a person the file names and this workspace never had, a
+ rule this version no longer ships: those are things the file can
+ legitimately say that cannot land here, and they are counted.
+ """
+ if payload.get("format") != FORMAT:
+ raise rules.RuleError("bad_format", "That is not a matching-rules file")
+
+ incoming_nodes = payload.get("nodes")
+ if not isinstance(incoming_nodes, list):
+ raise rules.RuleError("bad_file", "That file has no rules in it")
+
+ existing = await rules.overrides_for(session, workspace_id)
+ if existing and not overwrite:
+ raise rules.ExistingPolicyError(
+ "Importing replaces the matching rules this workspace has now"
+ )
+
+ _, to_id = await _directory(session, workspace_id)
+
+ allowed = nodes if nodes is not None else rules.EDITABLE_NODES
+
+ skipped = 0
+ planned: list[tuple[str, dict[str, Any], dict[str, Any], bool, int]] = []
+ discards: list[tuple[str, str]] = []
+
+ for node_data in incoming_nodes:
+ node = node_data.get("node")
+ # A file may carry a set this workspace does not have. Skipped and
+ # counted rather than written: importing it would store rules the
+ # author cannot see and cannot undo.
+ if node not in allowed:
+ skipped += len(node_data.get("rules") or [])
+ continue
+
+ shipped = {
+ s["id"]: s
+ for s in reconciliation_policy.default_policy(node)["strategies"]
+ }
+
+ for place, entry in enumerate(node_data.get("rules") or []):
+ when = _swap(entry.get("when") or {}, to_id)
+ if when is None:
+ # Named an account or a client this workspace does not
+ # have. Importing it anyway would widen the rule.
+ skipped += 1
+ continue
+
+ config = {
+ "enabled": entry.get("enabled", True),
+ "outcome": entry.get("outcome"),
+ "trigger": entry.get("trigger", "money_arrives"),
+ "when": when,
+ }
+ custom = entry.get("origin") == "custom"
+ if not custom and entry.get("id") not in shipped:
+ # A rule this version does not ship. Guessing at what it
+ # meant is worse than saying it was skipped.
+ skipped += 1
+ continue
+
+ # Raises, and the caller answers with the code and the
+ # message. This is the line that has to run before the delete
+ # below rather than after it.
+ rules.validate_config(config, whole=custom)
+ planned.append((node, entry, config, custom, place))
+
+ for strategy_id in node_data.get("discarded") or []:
+ if strategy_id in shipped:
+ discards.append((node, strategy_id))
+
+ for row in existing:
+ if row.node in allowed:
+ await session.delete(row)
+ await session.flush()
+
+ imported = 0
+
+ for node, entry, config, custom, place in planned:
+ try:
+ if custom:
+ await rules.create_custom(
+ session,
+ workspace_id,
+ user_id,
+ node,
+ entry.get("name") or entry.get("id") or "",
+ config,
+ position=place,
+ )
+ else:
+ await rules.upsert_override(
+ session,
+ workspace_id,
+ user_id,
+ node,
+ entry["id"],
+ config,
+ position=place,
+ )
+ except rules.RuleError:
+ # The structural check above already passed, so anything
+ # left is about this workspace rather than the file: a
+ # name colliding with one already here, say. Counted, not
+ # fatal.
+ skipped += 1
+ continue
+ imported += 1
+
+ for node, strategy_id in discards:
+ await rules.delete_rule(session, workspace_id, node, strategy_id)
+
+ await session.flush()
+ return {"imported": imported, "skipped": skipped}
diff --git a/backend/app/services/reconciliation_rule_service.py b/backend/app/services/reconciliation_rule_service.py
new file mode 100644
index 00000000..83db9970
--- /dev/null
+++ b/backend/app/services/reconciliation_rule_service.py
@@ -0,0 +1,884 @@
+"""Turning shipped rules plus a workspace's changes into one policy.
+
+The rules a workspace actually runs are **not** stored anywhere. They are
+computed, on every read, from two things: the document that shipped with
+the image, and the rows recording what somebody chose to change. That is
+the whole idea, and it costs one small query per match.
+
+The alternative, writing the defaults into each workspace at creation,
+looks simpler for about six months, until the day a better default ships
+and reaches nobody who had already opened the page. Under this model an
+untouched rule keeps improving with the product, and a row exists exactly
+where a person decided otherwise.
+
+## What a person may change, and what they may not
+
+Everything the engine reads: whether a rule runs, whether it links or
+merely suggests, how close the amount and the date have to be, how
+similar the description, whether the payer must be known. They may also
+write rules of their own, and put them before ours.
+
+They may not change the *shape*. A rule whose amount rule names a match
+mode the engine has never heard of would not fail loudly, it would
+quietly stop matching, and nobody would find out until a month of
+payments had gone unreconciled. So writes are validated against the
+schema before they are stored, and a stored rule that no longer parses is
+skipped with its reason recorded rather than crashing the sync.
+"""
+from __future__ import annotations
+
+import copy
+import re
+import uuid
+from decimal import Decimal
+from typing import Any, Collection, Optional
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.reconciliation import ReconciliationRule
+from app.services import reconciliation_policy
+from app.services.module_service import ModuleId
+
+#: The nodes a person is shown and may edit, and the module each needs.
+#:
+#: `match_placeholder` is absent, and only it. That one decides whether an
+#: arriving charge is the row *we* generated from a schedule: bookkeeping
+#: about our own duplicates, whose only visible effect is a line appearing
+#: twice. Nobody should be offered that lever.
+#:
+#: `match_recurring` was removed alongside it for a while, under the same
+#: description, and the description was wrong. It decides whether the
+#: charge that arrived is the bill you told us to expect, which is a
+#: judgement about your money and the personal-workspace counterpart of
+#: matching an invoice. Its thresholds are exactly what somebody wants to
+#: change: rent that posts anywhere between the 1st and the 8th, a gym
+#: that bills a different amount every month.
+#:
+#: The confusion that removed it was real but came from the labels. "An
+#: invoice can itself be recurring" made "invoices" and "recurring" read
+#: as two kinds of invoice, and then no answer existed for where a monthly
+#: retainer belonged. The sets are not two kinds of thing: they are what
+#: the money is matched **against**. A document you issued and are owed
+#: for, or a bill you asked us to expect. A monthly retainer's invoice
+#: goes against the invoice; a subscription charge against the bill.
+#:
+#: Each carries the module it needs, because they are not the same
+#: feature: a workspace with recurring bills and no invoicing sees one
+#: set, one with both sees both, and one with neither never reaches the
+#: page.
+EDITABLE_NODES_BY_MODULE: dict[str, ModuleId] = {
+ reconciliation_policy.MATCH_INVOICE["node"]: ModuleId.INVOICES,
+ reconciliation_policy.MATCH_RECURRING["node"]: ModuleId.RECURRING,
+}
+
+#: Every node a rule may be written against, in the order they are shown.
+EDITABLE_NODES = tuple(EDITABLE_NODES_BY_MODULE)
+
+
+def nodes_for(enabled_modules: Collection[str]) -> tuple[str, ...]:
+ """The sets this workspace may see, in shipped order."""
+ return tuple(
+ node
+ for node, module in EDITABLE_NODES_BY_MODULE.items()
+ if module.value in enabled_modules
+ )
+
+
+#: A custom rule's id: what the workspace typed, reduced to something
+#: safe to store, compare and show. Ids are compared against shipped ones,
+#: so they live in the same namespace and follow the same shape.
+_ID_SHAPE = re.compile(r"[^a-z0-9_]+")
+
+#: Reserved prefix so a workspace can never write a rule that shadows one
+#: of ours by claiming its id.
+CUSTOM_PREFIX = "custom_"
+
+
+class ExistingPolicyError(Exception):
+ """Importing would replace matching rules this workspace already has.
+
+ Its own type rather than a `RuleError`, because it is not a bad
+ request: the file is fine, and the answer is a question for the
+ person rather than a correction to the file.
+ """
+
+
+class RuleError(Exception):
+ """A rule that cannot be stored, with a code the UI can translate."""
+
+ def __init__(self, code: str, message: str):
+ self.code = code
+ self.message = message
+ super().__init__(message)
+
+
+def slug(name: str) -> str:
+ base = _ID_SHAPE.sub("_", name.strip().lower()).strip("_")[:48]
+ return f"{CUSTOM_PREFIX}{base or uuid.uuid4().hex[:8]}"
+
+
+def _merge(shipped: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]:
+ """Apply a sparse patch over a shipped rule.
+
+ Recursive, so a workspace that only widened the date window keeps
+ every other signal live: including improvements shipped later. A
+ patch that replaced the whole `when` block would silently freeze the
+ signals it did not mention, which is the failure this exists to
+ avoid.
+ """
+ result = copy.deepcopy(shipped)
+ for key, value in patch.items():
+ if isinstance(value, dict) and isinstance(result.get(key), dict):
+ result[key] = _merge(result[key], value)
+ else:
+ result[key] = copy.deepcopy(value)
+ return result
+
+
+def _prune(patch: dict[str, Any], shipped: dict[str, Any]) -> dict[str, Any]:
+ """Drop everything the patch says that we already say ourselves.
+
+ The screen sends a whole rule, because a form holds a whole rule:
+ every field, whether or not somebody touched it. Storing that as the
+ override would quietly freeze the parts nobody meant to change, and
+ the workspace would stop receiving improvements to signals it never
+ had an opinion about. That is the exact failure this design exists to
+ avoid, so the difference is taken **here**, where it cannot be
+ forgotten by a future caller.
+
+ Recursive, and it drops sub-objects that end up empty: a `when` block
+ identical to ours leaves nothing behind rather than an empty husk that
+ would still read as "customised" on the page.
+ """
+ out: dict[str, Any] = {}
+ for key, value in patch.items():
+ theirs = shipped.get(key)
+ if isinstance(value, dict) and isinstance(theirs, dict):
+ nested = _prune(value, theirs)
+ if nested:
+ out[key] = nested
+ elif key not in shipped or theirs != value:
+ out[key] = value
+ return out
+
+
+async def overrides_for(
+ session: AsyncSession, workspace_id: uuid.UUID, node: Optional[str] = None
+) -> list[ReconciliationRule]:
+ query = select(ReconciliationRule).where(
+ ReconciliationRule.workspace_id == workspace_id
+ )
+ if node is not None:
+ query = query.where(ReconciliationRule.node == node)
+ result = await session.execute(query)
+ return list(result.scalars().all())
+
+
+def compose(node: str, rows: list[ReconciliationRule]) -> dict[str, Any]:
+ """The policy this workspace actually runs, for one node.
+
+ Shipped rules in shipped order, each with its patch applied; the
+ workspace's own rules interleaved by position. A rule with no position
+ stays where the shipped document put it, so adding one rule does not
+ require renumbering the rest.
+ """
+ policy = reconciliation_policy.default_policy(node)
+ patches = {row.strategy_id: row for row in rows if row.origin == "default"}
+ # Thrown away by this workspace. Still shipped, so we still know its
+ # name, which is the only reason the page can offer it back.
+ discarded: list[dict[str, Any]] = []
+ # Sort key: where it sits, then whether somebody *asked* for that spot,
+ # then the shipped order. The middle term is what makes "put this
+ # first" mean first: an explicit position beats a rule that merely
+ # happens to occupy that index, while a rule nobody positioned never
+ # displaces one that was.
+ ordered: list[tuple[float, int, int, dict[str, Any]]] = []
+
+ for index, strategy in enumerate(policy["strategies"]):
+ row = patches.get(strategy["id"])
+ if row is not None and row.deleted:
+ discarded.append({"id": strategy["id"], "node": node})
+ continue
+ merged = _merge(strategy, row.config) if row else strategy
+ merged["origin"] = "default"
+ # "Changed" means the *rule* differs, not that a row exists. A row
+ # carrying only a position: written when somebody reordered the
+ # list: is not a departure from what we ship, and marking it as
+ # one would offer to "restore" a rule that was never altered.
+ merged["customised"] = bool(row and row.config)
+ asked = row is not None and row.position is not None
+ place = float(row.position) if asked and row else float(index)
+ ordered.append((place, 0 if asked else 1, index, merged))
+
+ for offset, row in enumerate(r for r in rows if r.origin == "custom"):
+ strategy = copy.deepcopy(row.config)
+ strategy["id"] = row.strategy_id
+ strategy["origin"] = "custom"
+ strategy["customised"] = True
+ strategy["name"] = row.name
+ asked = row.position is not None
+ place = (
+ float(row.position)
+ if asked
+ else float(len(policy["strategies"]) + offset)
+ )
+ ordered.append(
+ (place, 0 if asked else 1, len(policy["strategies"]) + offset, strategy)
+ )
+
+ ordered.sort(key=lambda item: (item[0], item[1], item[2]))
+ policy["strategies"] = [strategy for _, _, _, strategy in ordered]
+ policy["discarded"] = discarded
+ return policy
+
+
+async def resolve(
+ session: AsyncSession, workspace_id: uuid.UUID, node: str
+) -> dict[str, Any]:
+ """The live policy for one node in one workspace."""
+ return compose(node, await overrides_for(session, workspace_id, node))
+
+
+def narrow_for_frequency(policy: dict[str, Any], frequency: str) -> dict[str, Any]:
+ """Clamp a recurring policy to what this frequency can safely allow.
+
+ Applied *after* the workspace's changes, and it only ever narrows.
+ Somebody who widened the monthly window to ten days has said something
+ reasonable about how late their bills post; letting that same ten days
+ apply to a weekly bill would let a charge match the neighbouring
+ occurrence, which is not a preference they expressed: it is a fact
+ about weekly bills sitting seven days apart. So the workspace's number
+ wins wherever it is tighter, and loses only where physics disagrees.
+
+ A copy, because the caller holds one composed policy and narrows it
+ differently for each bill in the batch.
+ """
+ window = reconciliation_policy.RECURRING_WINDOW_BY_FREQUENCY.get(frequency)
+ if not window:
+ return policy
+ narrowed = copy.deepcopy(policy)
+ for strategy in narrowed["strategies"]:
+ date_rule = strategy.get("when", {}).get("date")
+ if not isinstance(date_rule, dict):
+ continue
+ date_rule["before_days"] = min(
+ int(date_rule.get("before_days", 0)), window["before_days"]
+ )
+ date_rule["after_days"] = min(
+ int(date_rule.get("after_days", 0)), window["after_days"]
+ )
+ return narrowed
+
+
+async def resolve_recurring(
+ session: AsyncSession, workspace_id: uuid.UUID, frequency: str
+) -> dict[str, Any]:
+ """The recurring policy for one bill, workspace changes and all."""
+ policy = await resolve(
+ session, workspace_id, reconciliation_policy.MATCH_RECURRING["node"]
+ )
+ return narrow_for_frequency(policy, frequency)
+
+
+# ---------------------------------------------------------------------------
+# Writing
+# ---------------------------------------------------------------------------
+_OUTCOMES = ("link", "suggest")
+_AMOUNT_MATCHES = ("exact", "tolerance", "ratio", "partial", "set")
+_COUNTERPARTIES = ("any", "same_payee")
+
+
+def validate_config(config: dict[str, Any], *, whole: bool) -> dict[str, Any]:
+ """Check a rule before it is stored.
+
+ `whole` distinguishes a workspace's own rule, which must stand on its
+ own, from a patch over one of ours, where every key is optional and
+ absence means "leave it as shipped".
+
+ Validating on the way in rather than on the way out is deliberate: a
+ malformed rule discovered during a sync would stop matching silently,
+ and the person who broke it would be nowhere near a screen.
+ """
+ clean: dict[str, Any] = {}
+
+ if "enabled" in config:
+ clean["enabled"] = bool(config["enabled"])
+
+ if "trigger" in config:
+ if config["trigger"] not in ("money_arrives", "invoice_issued", "both"):
+ raise RuleError("bad_trigger", "Unknown moment for a rule to run")
+ clean["trigger"] = config["trigger"]
+
+ if "outcome" in config:
+ if config["outcome"] not in _OUTCOMES:
+ raise RuleError("bad_outcome", "A rule either links or suggests")
+ clean["outcome"] = config["outcome"]
+ elif whole:
+ raise RuleError("outcome_required", "Say whether this rule links or suggests")
+
+ when = config.get("when")
+ if when is None:
+ if whole:
+ raise RuleError("conditions_required", "A rule needs at least one condition")
+ return clean
+ if not isinstance(when, dict):
+ raise RuleError("bad_conditions", "Conditions must be a set of named signals")
+
+ checked: dict[str, Any] = {}
+
+ if "counterparty" in when:
+ if when["counterparty"] not in _COUNTERPARTIES:
+ raise RuleError("bad_counterparty", "Unknown counterparty condition")
+ checked["counterparty"] = when["counterparty"]
+
+ if "amount" in when:
+ checked["amount"] = _validate_amount(when["amount"])
+
+ if "date" in when:
+ checked["date"] = _validate_window(when["date"])
+
+ if "description_similarity" in when:
+ checked["description_similarity"] = _validate_similarity(
+ when["description_similarity"]
+ )
+
+ if "currency" in when:
+ checked["currency"] = _validate_currency(when["currency"])
+
+ if "accounts" in when:
+ checked["accounts"] = {"in": _validate_ids(when["accounts"], "bad_accounts")}
+
+ if "payees" in when:
+ checked["payees"] = {"in": _validate_ids(when["payees"], "bad_payees")}
+
+ if "direction" in when:
+ if when["direction"] not in ("any", "credit", "debit"):
+ raise RuleError("bad_direction", "Money either comes in or goes out")
+ checked["direction"] = when["direction"]
+
+ if "text" in when:
+ checked["text"] = _validate_text(when["text"])
+
+ for flag in ("same_account", "unique_candidate"):
+ if flag in when:
+ checked[flag] = bool(when[flag])
+
+ if whole and not checked:
+ raise RuleError("conditions_required", "A rule needs at least one condition")
+
+ clean["when"] = checked
+ return clean
+
+
+def _positive_number(value: Any, code: str, message: str) -> str:
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ raise RuleError(code, message) from None
+ if number < 0:
+ raise RuleError(code, message)
+ return str(value)
+
+
+def _validate_amount(rule: Any) -> dict[str, Any]:
+ """Two different questions live in this block, and they are not the same.
+
+ `match` asks how close the money has to be **to the promise**: exact,
+ within a margin, net of withholding. `min` and `max` ask whether the
+ rule applies to money of this size at all, which is what somebody
+ means by "don't link anything over ten thousand on its own". Keeping
+ both here rather than in separate blocks is how every tool that
+ offers them presents them, and it reads as one sentence about amount.
+ """
+ if not isinstance(rule, dict):
+ raise RuleError("bad_amount", "Unknown amount condition")
+ match = rule.get("match", "exact")
+ if match not in _AMOUNT_MATCHES:
+ raise RuleError("bad_amount", "Unknown amount condition")
+ checked: dict[str, Any] = {"match": match}
+
+ for bound in ("min", "max"):
+ value = rule.get(bound)
+ if value in (None, ""):
+ continue
+ checked[bound] = _positive_number(
+ value, "bad_amount_bound", "An amount limit must not be negative"
+ )
+ if "min" in checked and "max" in checked:
+ if Decimal(checked["min"]) > Decimal(checked["max"]):
+ raise RuleError(
+ "impossible_amount_band",
+ "The lower limit is above the upper one, so nothing can match",
+ )
+ if match == "tolerance":
+ percent = _positive_number(
+ rule.get("percent", "0"), "bad_tolerance", "The tolerance must not be negative"
+ )
+ if float(percent) > 100:
+ raise RuleError(
+ "tolerance_too_wide",
+ "A tolerance above 100% would match every amount there is",
+ )
+ checked["percent"] = percent
+ if match == "partial":
+ # A floor, so a token payment against a large invoice is not
+ # offered as an instalment. Expressed as a fraction of what is
+ # outstanding rather than an absolute, because "at least five per
+ # cent" means the same thing on a small invoice and a large one.
+ for bound, default in (("min_ratio", "0.05"), ("max_ratio", "0.95")):
+ raw = rule.get(bound, default)
+ try:
+ value = Decimal(str(raw))
+ except (ArithmeticError, TypeError, ValueError):
+ raise RuleError("bad_part_ratio", "That is not a fraction") from None
+ if not 0 <= value <= 1:
+ raise RuleError(
+ "bad_part_ratio", "A part payment is between none and all of it"
+ )
+ checked[bound] = str(raw)
+ if Decimal(checked["min_ratio"]) > Decimal(checked["max_ratio"]):
+ raise RuleError(
+ "impossible_part_band",
+ "The lower share is above the upper one, so nothing can match",
+ )
+
+ if match == "set":
+ # How many promises one payment may cover, and how far the total
+ # may be from what arrived. The cap is bounded again in the engine
+ #: searching which invoices add up to a payment grows explosively,
+ # and a sync that hangs is worse than a match that is not made.
+ try:
+ most = int(rule.get("max_invoices", 6))
+ except (TypeError, ValueError):
+ raise RuleError("bad_set_size", "That is not a number of invoices") from None
+ if not 2 <= most <= 6:
+ raise RuleError(
+ "bad_set_size", "A combination holds between two and six invoices"
+ )
+ checked["max_invoices"] = most
+ checked["percent"] = _positive_number(
+ rule.get("percent", "0"), "bad_tolerance", "The tolerance must not be negative"
+ )
+ if Decimal(checked["percent"]) > 20:
+ raise RuleError(
+ "set_tolerance_too_wide",
+ "Above twenty per cent almost any group of invoices adds up",
+ )
+
+ if match == "ratio":
+ # The ratios themselves come from the jurisdiction pack, never from
+ # a workspace: a wrong withholding rate would auto-link a wrong
+ # amount, which is worse than asking.
+ checked["ratios"] = "@jurisdiction.withholding_ratios"
+ checked["epsilon"] = _positive_number(
+ rule.get("epsilon", "0.02"), "bad_epsilon", "The margin must not be negative"
+ )
+ checked["difference_kind"] = "withholding_tax"
+ return checked
+
+
+def _validate_currency(rule: Any) -> dict[str, Any]:
+ """Two independent questions again, and conflating them would hide one.
+
+ `conversion` says whether a movement may settle a promise held in a
+ different currency: a comparison rule. `in` and `foreign` say which
+ money the rule is written for at all. Somebody who wants "dollars are
+ reviewed by hand" needs the second, and has no use for the first.
+ """
+ if not isinstance(rule, dict):
+ raise RuleError("bad_currency", "Unknown currency condition")
+ # `allow` used to be accepted here and meant "stop comparing
+ # currencies", which is not conversion: it settled a euro invoice
+ # with dollars at face value. Refused on the way in rather than
+ # quietly ignored, so a policy file carrying it is reported instead
+ # of silently doing something other than what it says.
+ conversion = rule.get("conversion", "reject")
+ if conversion == "allow":
+ raise RuleError(
+ "conversion_unsupported",
+ "Money in another currency is never matched. Converting it needs a rate and a place to book the difference.",
+ )
+ if conversion != "reject":
+ raise RuleError("bad_currency", "Unknown currency condition")
+ checked: dict[str, Any] = {"conversion": conversion}
+
+ codes = rule.get("in")
+ if codes:
+ if not isinstance(codes, list) or not all(
+ isinstance(code, str) and len(code) == 3 for code in codes
+ ):
+ raise RuleError("bad_currency_list", "Currencies are three-letter codes")
+ checked["in"] = [code.upper() for code in codes]
+ if rule.get("foreign"):
+ checked["foreign"] = True
+ return checked
+
+
+def _validate_ids(rule: Any, code: str) -> list[str]:
+ """A list of accounts or clients the rule is limited to.
+
+ Stored as strings rather than UUID objects because this lives in JSON
+ and has to survive a round trip through the database unchanged. They
+ are compared as strings too, so a malformed id narrows the rule to
+ nothing rather than widening it to everything: the safe direction to
+ fail in when the thing being decided is whether money moves.
+ """
+ if isinstance(rule, dict):
+ rule = rule.get("in")
+ if not isinstance(rule, list) or not rule:
+ raise RuleError(code, "Choose at least one, or leave the condition out")
+ out = []
+ for value in rule:
+ try:
+ out.append(str(uuid.UUID(str(value))))
+ except (ValueError, AttributeError, TypeError):
+ raise RuleError(code, "That is not something we can identify") from None
+ return out
+
+
+def _validate_text(rule: Any) -> dict[str, str]:
+ """What the statement line has to say, or must not.
+
+ The plainest of the new conditions and probably the most used: bank
+ text is where the real identity of a payment hides, and matching on a
+ fragment of it is how somebody encodes "this is the client whose
+ transfers always carry their tax number" long before we can read that
+ number structurally.
+ """
+ if not isinstance(rule, dict):
+ raise RuleError("bad_text", "Unknown text condition")
+ checked: dict[str, Any] = {}
+ for key in ("contains", "not_contains"):
+ value = rule.get(key)
+ if value in (None, "", []):
+ continue
+ # One word or several. Several means *any of them*, which is how
+ # somebody receiving through three acquirers writes one rule
+ # instead of three that differ by a word.
+ words = [value] if isinstance(value, str) else value
+ if not isinstance(words, list):
+ raise RuleError("bad_text", "Say what the text must contain")
+ cleaned = []
+ for word in words:
+ if not isinstance(word, str) or len(word) > 120:
+ raise RuleError("bad_text", "Keep the text short and plain")
+ word = word.strip()
+ if word:
+ cleaned.append(word)
+ if not cleaned:
+ continue
+ if len(cleaned) > 12:
+ raise RuleError(
+ "too_many_words",
+ "A rule this long is easier to read as two rules",
+ )
+ # Stored as it was written: one word stays a string, so a rule
+ # nobody touched does not show up as changed.
+ checked[key] = cleaned[0] if len(cleaned) == 1 else cleaned
+ if not checked:
+ raise RuleError("bad_text", "Say what the text must contain")
+ return checked
+
+
+def _validate_window(rule: Any) -> dict[str, int]:
+ if not isinstance(rule, dict):
+ raise RuleError("bad_window", "Unknown date condition")
+ checked = {}
+ for side in ("before_days", "after_days"):
+ try:
+ days = int(rule.get(side, 0))
+ except (TypeError, ValueError):
+ raise RuleError("bad_window", "The date window must be in whole days") from None
+ if days < 0 or days > 365:
+ raise RuleError(
+ "window_out_of_range", "The date window must be between 0 and 365 days"
+ )
+ checked[side] = days
+ return checked
+
+
+def _validate_similarity(rule: Any) -> dict[str, str]:
+ if not isinstance(rule, dict):
+ raise RuleError("bad_similarity", "Unknown description condition")
+ try:
+ minimum = float(rule.get("min", 0))
+ except (TypeError, ValueError):
+ raise RuleError("bad_similarity", "Unknown description condition") from None
+ if not 0 <= minimum <= 1:
+ raise RuleError("similarity_out_of_range", "Similarity runs from 0 to 1")
+ # The value the check above validated, not a second lookup: a
+ # `description_similarity` carrying no `min` passed on the default
+ # and was then stored as the string "None", which no consumer can
+ # parse.
+ return {"min": str(rule.get("min", 0))}
+
+
+async def upsert_override(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ node: str,
+ strategy_id: str,
+ config: dict[str, Any],
+ position: Optional[int] = None,
+) -> ReconciliationRule:
+ """Record a change to one of the rules we ship."""
+ if node not in EDITABLE_NODES:
+ raise RuleError("unknown_node", "That set of rules cannot be edited")
+ shipped = {s["id"] for s in reconciliation_policy.default_policy(node)["strategies"]}
+ if strategy_id not in shipped:
+ raise RuleError("unknown_rule", "No such rule in this set")
+
+ clean = validate_config(config, whole=False)
+ row = await _find(session, workspace_id, node, strategy_id)
+
+ # Merged rather than replaced: a screen that sends one changed field
+ # must not erase a change made from another screen, or last week.
+ # Then pruned, so what remains is only the disagreement.
+ merged = _merge(row.config if row else {}, clean)
+ shipped_strategy = next(
+ s
+ for s in reconciliation_policy.default_policy(node)["strategies"]
+ if s["id"] == strategy_id
+ )
+ pruned = _prune(merged, shipped_strategy)
+
+ keeps_position = row is not None and row.position is not None
+ if (
+ not pruned
+ and position is None
+ and not keeps_position
+ and not (row is not None and row.deleted)
+ ):
+ # Nothing left to disagree about. Setting a value back to what we
+ # ship is the same act as restoring it, so the row goes and the
+ # rule returns to the live default rather than lingering as a
+ # copy that happens to agree today.
+ #
+ # Except when the row is a tombstone: "I do not want this rule"
+ # is a disagreement even when every threshold matches ours, and
+ # dropping the row here would quietly bring back a rule somebody
+ # deleted. Or when it carries a position: reordering writes one
+ # for every rule in the node, so deleting the row would drop this
+ # rule back to its shipped index while its siblings kept theirs,
+ # and the order somebody set would rearrange itself.
+ if row is not None:
+ await session.delete(row)
+ await session.flush()
+ return row or ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=workspace_id,
+ user_id=user_id,
+ node=node,
+ strategy_id=strategy_id,
+ origin="default",
+ config={},
+ policy_version=reconciliation_policy.POLICY_VERSION,
+ )
+
+ if row is None:
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=workspace_id,
+ user_id=user_id,
+ node=node,
+ strategy_id=strategy_id,
+ origin="default",
+ policy_version=reconciliation_policy.POLICY_VERSION,
+ )
+ session.add(row)
+ row.config = pruned
+ if position is not None:
+ row.position = position
+ await session.flush()
+ return row
+
+
+async def reorder(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ node: str,
+ strategy_ids: list[str],
+) -> None:
+ """Fix the order rules are tried in.
+
+ Writes an explicit position for **every** rule in the node rather than
+ only the one that moved. Order is the mechanism the whole feature
+ rests on: the first rule that matches wins, so a band is expressed by
+ what sits above and below it, and half-implicit ordering, where some
+ rules carry a position and others fall back to where we happened to
+ ship them, is the kind of thing that reads correctly today and
+ silently rearranges the day a default is inserted.
+
+ A row holding only a position is not a customised rule: its `config`
+ stays empty, so it keeps inheriting every improvement.
+ """
+ if node not in EDITABLE_NODES:
+ raise RuleError("unknown_node", "That set of rules cannot be reordered")
+
+ known = {s["id"] for s in reconciliation_policy.default_policy(node)["strategies"]}
+ rows = {row.strategy_id: row for row in await overrides_for(session, workspace_id, node)}
+ known |= {row_id for row_id, row in rows.items() if row.origin == "custom"}
+ # A rule this workspace deleted is not in the list any more, so
+ # naming every rule cannot mean naming that one.
+ known -= {row_id for row_id, row in rows.items() if row.deleted}
+
+ unknown = [rid for rid in strategy_ids if rid not in known]
+ if unknown:
+ raise RuleError("unknown_rule", "No such rule in this set")
+ if len(set(strategy_ids)) != len(strategy_ids):
+ raise RuleError("duplicate_rule", "A rule cannot be in two places at once")
+ if set(strategy_ids) != known:
+ raise RuleError(
+ "incomplete_order",
+ "Reordering names every rule in the set, so none is left implicit",
+ )
+
+ for place, strategy_id in enumerate(strategy_ids):
+ row = rows.get(strategy_id)
+ if row is None:
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=workspace_id,
+ user_id=user_id,
+ node=node,
+ strategy_id=strategy_id,
+ origin="default",
+ config={},
+ policy_version=reconciliation_policy.POLICY_VERSION,
+ )
+ session.add(row)
+ row.position = place
+ await session.flush()
+
+
+async def create_custom(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ user_id: uuid.UUID,
+ node: str,
+ name: str,
+ config: dict[str, Any],
+ position: Optional[int] = None,
+) -> ReconciliationRule:
+ """Store a rule the workspace wrote itself."""
+ if node not in EDITABLE_NODES:
+ raise RuleError("unknown_node", "That set of rules cannot be edited")
+ if not name.strip():
+ raise RuleError("name_required", "Give the rule a name")
+
+ strategy_id = slug(name)
+ if await _find(session, workspace_id, node, strategy_id) is not None:
+ strategy_id = f"{strategy_id}_{uuid.uuid4().hex[:6]}"
+
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=workspace_id,
+ user_id=user_id,
+ node=node,
+ strategy_id=strategy_id,
+ origin="custom",
+ name=name.strip(),
+ position=position,
+ config=validate_config(config, whole=True),
+ policy_version=reconciliation_policy.POLICY_VERSION,
+ )
+ session.add(row)
+ await session.flush()
+ return row
+
+
+async def update_custom(
+ session: AsyncSession,
+ row: ReconciliationRule,
+ name: Optional[str] = None,
+ config: Optional[dict[str, Any]] = None,
+ position: Optional[int] = None,
+) -> ReconciliationRule:
+ if name is not None:
+ if not name.strip():
+ raise RuleError("name_required", "Give the rule a name")
+ row.name = name.strip()
+ if config is not None:
+ row.config = validate_config(config, whole=True)
+ if position is not None:
+ row.position = position
+ await session.flush()
+ return row
+
+
+async def delete_rule(
+ session: AsyncSession, workspace_id: uuid.UUID, node: str, strategy_id: str
+) -> None:
+ """Get rid of a rule, whoever wrote it.
+
+ A rule the workspace wrote is deleted by deleting its row: it exists
+ nowhere else. One of ours cannot be, because it is a document in the
+ image and would be back on the next start, so the row records that
+ this workspace does not want it, and `compose` leaves it out.
+
+ There is no rule we refuse to remove. A matching policy decides what
+ happens to somebody's money, and a default we happen to believe in is
+ not a reason to make them keep it. What we do keep is the name, so
+ the page can offer it back.
+ """
+ if node not in EDITABLE_NODES:
+ raise RuleError("unknown_node", "That set of rules cannot be edited")
+
+ row = await _find(session, workspace_id, node, strategy_id)
+ if row is not None and row.origin == "custom":
+ await session.delete(row)
+ await session.flush()
+ return
+
+ shipped = {s["id"] for s in reconciliation_policy.default_policy(node)["strategies"]}
+ if strategy_id not in shipped:
+ raise RuleError("unknown_rule", "No such rule in this set")
+
+ if row is None:
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=workspace_id,
+ node=node,
+ strategy_id=strategy_id,
+ origin="default",
+ config={},
+ policy_version=reconciliation_policy.POLICY_VERSION,
+ )
+ session.add(row)
+ row.deleted = True
+ await session.flush()
+
+
+async def reset(
+ session: AsyncSession, workspace_id: uuid.UUID, node: str, strategy_id: str
+) -> None:
+ """Forget a change, and go back to whatever we ship *today*.
+
+ Not "go back to what shipped when you changed it": deleting the row
+ puts the rule back under the live default, which is the point of not
+ copying defaults in the first place.
+
+ One row holds every kind of disagreement, so one verb undoes all of
+ them: a threshold somebody moved, a place in the order, and a rule
+ somebody deleted all go back to shipped together.
+ """
+ row = await _find(session, workspace_id, node, strategy_id)
+ if row is not None:
+ await session.delete(row)
+ await session.flush()
+
+
+async def _find(
+ session: AsyncSession, workspace_id: uuid.UUID, node: str, strategy_id: str
+) -> Optional[ReconciliationRule]:
+ result = await session.execute(
+ select(ReconciliationRule).where(
+ ReconciliationRule.workspace_id == workspace_id,
+ ReconciliationRule.node == node,
+ ReconciliationRule.strategy_id == strategy_id,
+ )
+ )
+ return result.scalar_one_or_none()
diff --git a/backend/app/services/reconciliation_service.py b/backend/app/services/reconciliation_service.py
new file mode 100644
index 00000000..7fced06f
--- /dev/null
+++ b/backend/app/services/reconciliation_service.py
@@ -0,0 +1,522 @@
+"""Bringing money and promises together, and writing the result.
+
+The half that touches the database. `reconciliation_engine` decides;
+this loads the candidates, hands them over, and applies what comes back.
+Keeping the two apart is what lets the decision be dry-run later, and it
+is the reason this module contains no thresholds.
+
+## It runs in both directions, and that is not symmetry for its own sake
+
+Money arrives and settles an invoice that already existed: the obvious
+case. But the common Brazilian one runs the other way: the client pays,
+*then* the nota is issued. An invoice created on Tuesday is often settled
+by money that landed on Friday of the week before, and a matcher that
+only looked forward would never see it. So issuing an invoice looks back
+at money nobody has explained yet.
+
+## Both ports are acted on, and they are not equals
+
+`linked` writes an allocation. `suggested` goes to the queue in
+`reconciliation_suggestion_service`, to be answered by a person.
+
+**The automatic tier carries the traffic and the queue is the residue.**
+That ordering is the product, not an implementation detail: the
+accountant interview is unambiguous that import-then-make-the-user-confirm
+is what killed adoption of the incumbent (*"eles acharam muito
+trabalhoso"*), and a product that turns every payment into a confirmation
+is that product with a different logo. If the queue is where the volume
+goes, the rules are wrong, and the fix belongs in the rules.
+
+## The rules are the workspace's, not ours
+
+Which is why nothing here calls `default_policy` any more. The policy
+comes from `reconciliation_rule_service.resolve`, which is what we ship
+with whatever this workspace changed applied over it. A person can turn a
+rule off, loosen it, demote it from linking to suggesting, or write one
+of their own, and this module simply runs what comes back.
+"""
+from __future__ import annotations
+
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+from typing import Optional
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+
+from app.models.invoice import Invoice, InvoiceAllocation
+from app.models.recurring_transaction import RecurringTransaction
+from app.models.transaction import Transaction
+from app.models.workspace import Workspace
+from app.services import (
+ invoice_service,
+ reconciliation_history_service,
+ reconciliation_policy,
+ reconciliation_rule_service,
+ reconciliation_suggestion_service,
+)
+from app.services.module_service import ModuleId, resolve_modules
+from app.services.reconciliation_engine import (
+ Decision,
+ Expectation,
+ Movement,
+ evaluate,
+)
+
+#: The policy document this module runs under.
+NODE = reconciliation_policy.MATCH_INVOICE["node"]
+
+#: The other kind of promise. A personal workspace has only these, and
+#: the doubtful space has to serve it too.
+RECURRING_NODE = reconciliation_policy.MATCH_RECURRING["node"]
+
+#: How far back issuing an invoice looks for money that already arrived.
+#: Wide enough for the pay-then-invoice case, bounded so issuing an
+#: invoice never scans a year of a busy account.
+LOOKBACK_DAYS = 90
+
+
+def _as_expectation(invoice: Invoice) -> Expectation:
+ """One open invoice, as the engine sees it.
+
+ The amount is the **balance**, never the total: an invoice half paid
+ expects the other half, and a market that pays by Pix pays in parts.
+ """
+ return Expectation(
+ kind="invoice",
+ id=invoice.id,
+ amount=invoice_service.balance(invoice),
+ currency=invoice.currency,
+ # A receivable is settled by money coming in, a payable by money
+ # going out. The engine refuses a candidate facing the wrong way.
+ direction="credit" if invoice.direction == "receivable" else "debit",
+ when=invoice.due_date,
+ # Both dates: late is measured from the due date, early from the
+ # day the document was written.
+ issued=invoice.issue_date,
+ description=invoice.notes or (invoice.payee.name if invoice.payee else None),
+ payee_id=invoice.payee_id,
+ )
+
+
+def _as_movement(transaction: Transaction) -> Movement:
+ return Movement(
+ amount=Decimal(transaction.amount or 0),
+ currency=transaction.currency or "",
+ direction=transaction.type,
+ when=transaction.date,
+ description=transaction.description,
+ # The raw string the bank sent, not the person we resolved it to.
+ # A rule may need it before any mapping exists, which is the usual
+ # state of a Pix from a client who has not been seen before.
+ counterparty=transaction.payee,
+ payee_id=transaction.payee_id,
+ account_id=transaction.account_id,
+ source=transaction.source,
+ )
+
+
+async def _base_currency(
+ session: AsyncSession, workspace_id: uuid.UUID
+) -> Optional[str]:
+ """What this workspace normally deals in.
+
+ Only rules that say "foreign" consult it, and they need it because
+ foreign is relative: dollars are unremarkable to a workspace that
+ keeps its books in dollars and worth a second look to one that does
+ not.
+ """
+ workspace = await session.get(Workspace, workspace_id)
+ return workspace.default_currency if workspace else None
+
+
+async def _module_is_on(session: AsyncSession, workspace_id: uuid.UUID) -> bool:
+ """Whether this workspace has invoicing at all.
+
+ The candidate query would return nothing for a personal workspace
+ anyway, so this is not correctness: it is the modularity promise
+ kept literally: a workspace that never enabled the module pays one
+ cheap lookup on an already-loaded row, not a join against a table it
+ has no rows in, on every transaction of every sync.
+ """
+ workspace = await session.get(Workspace, workspace_id)
+ if workspace is None:
+ return False
+ return ModuleId.INVOICES.value in resolve_modules(workspace)
+
+
+async def _open_invoices(
+ session: AsyncSession, workspace_id: uuid.UUID, policy: dict
+) -> list[Invoice]:
+ """Every invoice the policy considers still waiting for money.
+
+ Two filters, and the split is not incidental. `status` is a stored
+ decision (draft, void, written off), so SQL can exclude it. Whether
+ something is `partial` or `overdue` is **derived per read** from the
+ allocations and the clock, so it is decided here, against the same
+ function the screen uses. Reading `candidate_states` rather than
+ hard-coding it is what keeps the policy a document instead of a
+ comment: a workspace that stops auto-matching overdue invoices
+ changes that list, not this file.
+
+ Allocations are eager-loaded because the balance is computed from
+ them: fetching them per invoice would turn one match into an N+1 on
+ an ingest path that already handles hundreds of rows.
+ """
+ wanted = set(policy.get("scope", {}).get("candidate_states", []))
+ result = await session.execute(
+ select(Invoice)
+ .where(Invoice.workspace_id == workspace_id, Invoice.status == "open")
+ .options(
+ selectinload(Invoice.allocations),
+ selectinload(Invoice.payee),
+ )
+ )
+ today = date.today()
+ return [
+ invoice
+ for invoice in result.unique().scalars().all()
+ if invoice_service.derive_state(invoice, today) in wanted
+ ]
+
+
+async def _already_settles_something(
+ session: AsyncSession, transaction_id: uuid.UUID
+) -> bool:
+ """Whether this money is already accounted for against an invoice.
+
+ Re-matching a transaction that already carries an allocation would
+ let one payment settle two debts, which is how a ledger starts
+ disagreeing with a bank."""
+ result = await session.execute(
+ select(InvoiceAllocation.id)
+ .where(InvoiceAllocation.transaction_id == transaction_id)
+ .limit(1)
+ )
+ return result.scalar_one_or_none() is not None
+
+
+async def _apply(
+ session: AsyncSession, decision: Decision, transaction: Transaction
+) -> Optional[InvoiceAllocation]:
+ """Write what the engine decided.
+
+ Applying is deliberately a separate step from deciding, and it goes
+ through `allocate` rather than around it: every guard that protects a
+ hand-made link (the invoice is open, the currency agrees, the amount
+ fits) protects an automatic one too. **An automatic decision is not
+ a trusted one.**
+
+ **All of it or none of it.** One payment can settle several invoices,
+ and a payout that lands against four of them and fails on the fifth
+ would leave a ledger nobody can explain: money spread across some
+ debts, the rest of it unaccounted for, and no record of what was
+ attempted. The savepoint makes the whole set a single act.
+ """
+ if decision.port != "linked" or not decision.settlements:
+ return None
+
+ first: Optional[InvoiceAllocation] = None
+ try:
+ async with session.begin_nested():
+ for settlement in decision.settlements:
+ invoice = await session.get(Invoice, settlement.expectation.id)
+ if invoice is None:
+ raise invoice_service.InvoiceError(
+ "invoice_missing", "The invoice is no longer there"
+ )
+ allocation = await invoice_service.allocate(
+ session,
+ invoice,
+ transaction.id,
+ amount=settlement.amount,
+ # The strategy id, not a generic "auto": this is what
+ # lets the screen answer "why is this linked" with the
+ # name of the rule that fired.
+ method=decision.strategy or "auto",
+ )
+ if first is None:
+ first = allocation
+ await reconciliation_history_service.record(
+ session,
+ invoice.workspace_id,
+ "linked",
+ expectation_kind=settlement.expectation.kind,
+ expectation_id=settlement.expectation.id,
+ amount=settlement.amount,
+ transaction_id=transaction.id,
+ strategy_id=decision.strategy,
+ # No user: the rules did this on their own, and that
+ # is the distinction a reader reaches for first.
+ detail={"of_set": len(decision.settlements)},
+ )
+ except invoice_service.InvoiceError:
+ # A guard refused one of them, so none of them happened. The money
+ # stays unexplained, which is the honest outcome: the alternative
+ # is a half-settled payout.
+ return None
+
+ return first
+
+
+async def match_incoming(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ transactions: list[Transaction],
+) -> list[InvoiceAllocation]:
+ """Bind newly arrived money to the promises it answers.
+
+ Called once per batch rather than once per row: the candidate list is
+ fetched a single time and reused, so a sync importing three hundred
+ transactions runs one query for invoices instead of three hundred.
+
+ Two passes, and the second is not an afterthought. A workspace that
+ never issues an invoice still has promises (the rent leaving on the
+ 5th, the retainer arriving on the 20th), and the doubtful space has to
+ exist for them too, or reconciliation would be a feature only
+ businesses got.
+ """
+ if not transactions:
+ return []
+
+ applied: list[InvoiceAllocation] = []
+ if await _module_is_on(session, workspace_id):
+ applied = await _match_invoices(session, workspace_id, transactions)
+
+ await _suggest_recurring(session, workspace_id, transactions)
+ return applied
+
+
+async def _match_invoices(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ transactions: list[Transaction],
+) -> list[InvoiceAllocation]:
+ # What the workspace normally deals in, so a rule can say "foreign".
+ # Foreign is a fact about the workspace, not about the money.
+ base_currency = await _base_currency(session, workspace_id)
+ policy = await reconciliation_rule_service.resolve(session, workspace_id, NODE)
+ candidates = await _open_invoices(session, workspace_id, policy)
+ if not candidates:
+ return []
+
+ applied: list[InvoiceAllocation] = []
+
+ for transaction in transactions:
+ if await _already_settles_something(session, transaction.id):
+ continue
+
+ expectations = [_as_expectation(inv) for inv in candidates]
+ movement = _as_movement(transaction)
+ decision = evaluate(
+ movement,
+ expectations,
+ policy,
+ withholding_ratios=reconciliation_policy.withholding_ratios(None),
+ base_currency=base_currency,
+ )
+ allocation = await _apply(session, decision, transaction)
+ if allocation is not None:
+ applied.append(allocation)
+ # Re-read on the next pass: this invoice's balance just
+ # dropped, and the following transaction must see that rather
+ # than settling the same debt twice.
+ candidates = await _open_invoices(session, workspace_id, policy)
+ else:
+ # Not confident enough to act. The pair goes to the queue,
+ # where the service refuses to re-ask anything already
+ # answered, including anything already refused.
+ await reconciliation_suggestion_service.record(
+ session, workspace_id, transaction.id, decision, movement, NODE
+ )
+
+ return applied
+
+
+async def _suggest_recurring(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ transactions: list[Transaction],
+) -> None:
+ """Offer the recurring bills that money might answer.
+
+ Nothing is linked here. A charge that the recurring rules were
+ confident about was already bound during normalisation, in place, and
+ carries a `recurring_transaction_id` by the time it reaches this
+ function, so anything still unattached is by definition something
+ that pass was *not* sure about.
+
+ Which is exactly why this exists: it is what happens when somebody
+ demotes the recurring rule from linking to suggesting. Without it that
+ setting would be a switch that quietly does nothing, and a
+ configuration screen whose switches do nothing is worse than no screen.
+ """
+ unexplained = [
+ transaction
+ for transaction in transactions
+ if transaction.recurring_transaction_id is None
+ and transaction.source != "recurring"
+ and not transaction.is_ignored
+ ]
+ if not unexplained:
+ return
+
+ result = await session.execute(
+ select(RecurringTransaction).where(
+ RecurringTransaction.workspace_id == workspace_id,
+ RecurringTransaction.is_active.is_(True),
+ )
+ )
+ bills = list(result.scalars().all())
+ if not bills:
+ return
+
+ from app.services.recurring_transaction_service import adjust_weekend_date
+
+ composed = await reconciliation_rule_service.resolve(
+ session, workspace_id, RECURRING_NODE
+ )
+ base_currency = await _base_currency(session, workspace_id)
+
+ for transaction in unexplained:
+ if await _already_settles_something(session, transaction.id):
+ continue
+ movement = _as_movement(transaction)
+ for bill in bills:
+ if bill.account_id != transaction.account_id:
+ continue
+ occurrence = adjust_weekend_date(
+ bill.next_occurrence, bill.weekend_adjustment
+ )
+ decision = evaluate(
+ movement,
+ [
+ Expectation(
+ kind="recurring",
+ id=bill.id,
+ amount=Decimal(bill.amount or 0),
+ currency=bill.currency,
+ direction=bill.type,
+ when=occurrence,
+ description=bill.description,
+ account_id=bill.account_id,
+ )
+ ],
+ reconciliation_rule_service.narrow_for_frequency(
+ composed, bill.frequency
+ ),
+ base_currency=base_currency,
+ )
+ if decision.port == "suggested":
+ await reconciliation_suggestion_service.record(
+ session,
+ workspace_id,
+ transaction.id,
+ decision,
+ movement,
+ RECURRING_NODE,
+ )
+
+
+async def match_for_invoice(
+ session: AsyncSession, invoice: Invoice
+) -> Optional[InvoiceAllocation]:
+ """Look back at money that arrived before this invoice existed.
+
+ The pay-then-invoice case: a client pays, and the nota follows days
+ later. Nothing about the money changed, so nothing would ever
+ re-examine it: this is the pass that does.
+
+ **Which rules run here is the rules' own business, not this
+ function's.** It used to be hardcoded: only known-client strategies,
+ decided in this file, and that was a restriction nobody could see or
+ change, on a page whose whole purpose is that matching is not a black
+ box. Now a rule declares the moments it trusts, and this pass simply
+ asks for the ones that trust this one.
+
+ The asymmetry that motivated the old restriction is still real, and it
+ lives in the shipped defaults instead: money of an exact value from a
+ payer we cannot name links when an invoice was already open and
+ waiting, and does not when the document came afterwards. The
+ difference is that a workspace can now disagree.
+
+ One allocation at most, and none at all if several movements fit.
+ Picking the most recent of three identical payments would be
+ inventing certainty exactly where the forward direction refuses to.
+ """
+ policy = await reconciliation_rule_service.resolve(
+ session, invoice.workspace_id, NODE
+ )
+ wanted = set(policy.get("scope", {}).get("candidate_states", []))
+ if invoice_service.derive_state(invoice, date.today()) not in wanted:
+ return None
+
+ policy["strategies"] = [
+ strategy
+ for strategy in policy["strategies"]
+ if strategy.get("trigger", "money_arrives") in ("invoice_issued", "both")
+ ]
+ if not policy["strategies"]:
+ return None
+
+ window_start = invoice.due_date - timedelta(days=LOOKBACK_DAYS)
+ wanted_direction = "credit" if invoice.direction == "receivable" else "debit"
+
+ # Not narrowed by payee any more. The old query could afford it
+ # because the only rules that ran here demanded a known client; now
+ # that the rules decide, the query has to be able to see everything
+ # they might legitimately match, or a workspace's own rule would fail
+ # for a reason nothing on screen could explain.
+ result = await session.execute(
+ select(Transaction)
+ .where(
+ Transaction.workspace_id == invoice.workspace_id,
+ Transaction.type == wanted_direction,
+ Transaction.currency == invoice.currency,
+ Transaction.date >= window_start,
+ Transaction.is_ignored.is_(False),
+ # A generated placeholder is a promise, not money that
+ # arrived. The policy says so too; saying it here as well
+ # keeps the query from loading rows only to discard them.
+ Transaction.source != "recurring",
+ )
+ .order_by(Transaction.date.desc())
+ .limit(200)
+ )
+
+ expectation = [_as_expectation(invoice)]
+ settles: list[tuple[Transaction, Decision]] = []
+
+ for transaction in result.scalars().all():
+ if await _already_settles_something(session, transaction.id):
+ continue
+ movement = _as_movement(transaction)
+ decision = evaluate(
+ movement,
+ expectation,
+ policy,
+ withholding_ratios=reconciliation_policy.withholding_ratios(None),
+ base_currency=await _base_currency(session, invoice.workspace_id),
+ trigger="invoice_issued",
+ )
+ if decision.port == "linked":
+ settles.append((transaction, decision))
+ if len(settles) > 1:
+ # Two payments answer this invoice equally well. Neither
+ # is taken; a person decides which.
+ return None
+ elif decision.port == "suggested":
+ # Dropping these would make a rule set to suggest do nothing
+ # at this moment while doing something at the other; the same
+ # silent switch the queue exists to prevent.
+ await reconciliation_suggestion_service.record(
+ session, invoice.workspace_id, transaction.id, decision, movement, NODE
+ )
+
+ if not settles:
+ return None
+
+ transaction, decision = settles[0]
+ return await _apply(session, decision, transaction)
diff --git a/backend/app/services/reconciliation_suggestion_service.py b/backend/app/services/reconciliation_suggestion_service.py
new file mode 100644
index 00000000..2c2aad23
--- /dev/null
+++ b/backend/app/services/reconciliation_suggestion_service.py
@@ -0,0 +1,391 @@
+"""The doubtful space: matches that are plausible without being certain.
+
+A suggestion is what the engine produces when the signals point somewhere
+but not hard enough to act. Storing them rather than recomputing them is
+not an optimisation: it is the only way to remember that somebody
+already said no.
+
+## Why `declined` is the important column
+
+Without it the loop is: sync finds a plausible pair, the person rejects
+it, the next sync finds the same pair and asks again. A queue that
+re-asks yesterday's questions is worse than no queue, because people stop
+reading it, and then they stop reading the good ones too. The accountant
+interview is unambiguous about where that ends: an incumbent whose
+import-then-confirm flow was abandoned because *"eles acharam muito
+trabalhoso"*.
+
+So the rule this module exists to keep: **the queue only ever grows by
+questions nobody has answered.** A declined pair is never offered again.
+An accepted one is settled and gone. And a pending one that has gone
+stale expires on its own, because a question nobody answered in two
+months is not a question any more.
+
+## It is the residue, never the main road
+
+Every suggestion here is a payment the automatic tier could not claim.
+If this queue is where the volume goes, the rules are wrong and the fix
+is in the rules, not in asking people to work harder.
+"""
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timedelta, timezone
+from decimal import Decimal
+from typing import Any, Optional
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.reconciliation import ReconciliationSuggestion
+from app.services import reconciliation_history_service
+from app.services.reconciliation_engine import Decision, Movement, Settlement
+
+#: How long an unanswered suggestion stays in the queue. Long enough that
+#: somebody who reconciles monthly still sees it; short enough that the
+#: queue does not become an archive of everything we were ever unsure
+#: about.
+STALE_AFTER_DAYS = 60
+
+
+def _signal_scores(
+ decision: Decision, movement: Movement, settlement: "Settlement"
+) -> dict[str, object]:
+ """The per-signal breakdown a person actually needs.
+
+ One overall number would be worse than none. "We are 78% sure" is not
+ something anyone can check; "the amount is exact, the date is four
+ days out, the name does not match" tells them exactly where to look,
+ and lets them disagree with a specific thing rather than with a
+ verdict.
+ """
+ expectation = settlement.expectation
+ return {
+ "strategy": decision.strategy,
+ # How many promises this one payment is being offered against, so
+ # the queue can say "one of three" rather than showing a number
+ # that looks wrong on its own.
+ "of_set": len(decision.settlements),
+ "description": round(decision.score, 3),
+ "amount_expected": str(expectation.amount),
+ "amount_moved": str(abs(movement.amount)),
+ "amount_exact": settlement.amount == expectation.amount,
+ "days_apart": (movement.when - expectation.when).days,
+ "same_counterparty": bool(
+ movement.payee_id and movement.payee_id == expectation.payee_id
+ ),
+ "currency": expectation.currency,
+ }
+
+
+async def record(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ transaction_id: uuid.UUID,
+ decision: Decision,
+ movement: Movement,
+ node: str,
+) -> list[ReconciliationSuggestion]:
+ """Keep a doubtful match, unless this pair has been settled already.
+
+ Returns the rows written: several when one payment may be covering
+ several promises, and none at all when every pair is already in the
+ queue or was already answered. That last case is the common one on a
+ re-sync, and the whole reason the table exists.
+
+ A payment covering several invoices is stored as a **group**, because
+ the question is the whole question. Asking about each invoice
+ separately would let somebody accept two thirds of a payout and leave
+ the payment short on the rest, with nothing on screen having warned
+ them.
+ """
+ if decision.port != "suggested" or not decision.settlements:
+ return []
+
+ group_id = uuid.uuid4() if len(decision.settlements) > 1 else None
+ written: list[ReconciliationSuggestion] = []
+
+ for settlement in decision.settlements:
+ expectation = settlement.expectation
+ existing = await session.execute(
+ select(ReconciliationSuggestion).where(
+ ReconciliationSuggestion.workspace_id == workspace_id,
+ ReconciliationSuggestion.transaction_id == transaction_id,
+ ReconciliationSuggestion.expectation_kind == expectation.kind,
+ ReconciliationSuggestion.expectation_id == expectation.id,
+ )
+ )
+ if existing.scalar_one_or_none() is not None:
+ # Pending, accepted or declined: all three mean "do not ask
+ # again". Declined is the one that matters: re-offering it is
+ # the failure this table was built to prevent.
+ #
+ # One member of a group already answered is enough to drop the
+ # whole group: the question was about the combination, and a
+ # combination missing a piece is a different question.
+ return []
+
+ written.append(
+ ReconciliationSuggestion(
+ id=uuid.uuid4(),
+ workspace_id=workspace_id,
+ transaction_id=transaction_id,
+ group_id=group_id,
+ expectation_kind=expectation.kind,
+ expectation_id=expectation.id,
+ strategy_id=decision.strategy or "unknown",
+ node=node,
+ amount=settlement.amount,
+ scores=_signal_scores(decision, movement, settlement),
+ status="pending",
+ )
+ )
+
+ for suggestion in written:
+ session.add(suggestion)
+
+ if written:
+ # **One event per question, not per invoice inside it.** A payment
+ # offered against three invoices is one thing that happened and one
+ # thing a person will answer; three rows in the stream would be the
+ # same noise the queue collapses, in the place meant for scanning.
+ head = written[0]
+ await reconciliation_history_service.record(
+ session,
+ workspace_id,
+ "suggested",
+ expectation_kind=head.expectation_kind,
+ expectation_id=head.expectation_id,
+ amount=sum((s.amount for s in written), Decimal("0")),
+ transaction_id=transaction_id,
+ strategy_id=head.strategy_id,
+ detail={"of_set": len(written)},
+ )
+ await session.flush()
+ return written
+
+
+async def members_of(
+ session: AsyncSession, suggestion: ReconciliationSuggestion
+) -> list[ReconciliationSuggestion]:
+ """Every row this question is made of.
+
+ A suggestion covering one invoice is its own group of one. A payment
+ offered against three is answered whole or not at all: accepting two
+ thirds of it would leave the payment short on the rest, with nothing
+ on screen having said so.
+ """
+ if suggestion.group_id is None:
+ return [suggestion]
+ result = await session.execute(
+ select(ReconciliationSuggestion).where(
+ ReconciliationSuggestion.workspace_id == suggestion.workspace_id,
+ ReconciliationSuggestion.group_id == suggestion.group_id,
+ )
+ )
+ return list(result.unique().scalars().all())
+
+
+async def open_for(
+ session: AsyncSession,
+ workspace_id: uuid.UUID,
+ *,
+ limit: int = 100,
+) -> list[ReconciliationSuggestion]:
+ """The questions still waiting for an answer, oldest first.
+
+ Oldest first because a queue read newest-first grows a tail nobody
+ ever reaches, and the oldest question is the one closest to expiring
+ unanswered.
+ """
+ result = await session.execute(
+ select(ReconciliationSuggestion)
+ .where(
+ ReconciliationSuggestion.workspace_id == workspace_id,
+ ReconciliationSuggestion.status == "pending",
+ )
+ .order_by(ReconciliationSuggestion.created_at.asc())
+ .limit(limit)
+ )
+ return list(result.unique().scalars().all())
+
+
+async def count_open(session: AsyncSession, workspace_id: uuid.UUID) -> int:
+ from sqlalchemy import func
+
+ result = await session.execute(
+ select(func.count(ReconciliationSuggestion.id)).where(
+ ReconciliationSuggestion.workspace_id == workspace_id,
+ ReconciliationSuggestion.status == "pending",
+ )
+ )
+ return int(result.scalar_one() or 0)
+
+
+async def get(
+ session: AsyncSession, workspace_id: uuid.UUID, suggestion_id: uuid.UUID
+) -> Optional[ReconciliationSuggestion]:
+ """The row, locked for the length of the transaction.
+
+ Both callers read `status` and then write, and a plain read lets two
+ requests pass that check before either commits: a double click, or a
+ phone and a laptop a second apart. The pair that costs something is an
+ accept and a decline, which would settle the invoice and then record
+ the suggestion as dismissed, leaving the queue disagreeing with the
+ ledger. The status guard closes the window; the lock closes what is
+ left of it.
+
+ `with_for_update` renders nothing on SQLite, which the test suite
+ uses, the same trade the invoice numbering lock already makes: the
+ guarantee is real in production, and the status check remains the
+ backstop in both.
+
+ **`of=` is not decoration.** This row eager-loads its transaction, so
+ the statement is a LEFT OUTER JOIN, and Postgres refuses to lock the
+ nullable side of one. A bare `FOR UPDATE` here raises
+ `FeatureNotSupportedError` against Postgres and renders nothing at all
+ against the SQLite the tests run on, which is the worst pair of
+ behaviours available: green suite, broken endpoint. Naming the table
+ locks the row we came for and leaves the join alone.
+ """
+ result = await session.execute(
+ select(ReconciliationSuggestion)
+ .where(
+ ReconciliationSuggestion.id == suggestion_id,
+ ReconciliationSuggestion.workspace_id == workspace_id,
+ )
+ .with_for_update(of=ReconciliationSuggestion)
+ )
+ return result.unique().scalar_one_or_none()
+
+
+def _resolve(
+ suggestion: ReconciliationSuggestion, status: str, user_id: Optional[uuid.UUID]
+) -> None:
+ """Mark one row. **Does not write history**: a grouped question is
+ resolved row by row but *happened* once, so the event belongs to
+ whoever knows the whole act. `answered` is that place."""
+ suggestion.status = status
+ suggestion.resolved_at = datetime.now(timezone.utc)
+ suggestion.resolved_by = user_id
+
+
+async def answered(
+ session: AsyncSession,
+ members: list[ReconciliationSuggestion],
+ status: str,
+ user_id: Optional[uuid.UUID],
+) -> None:
+ """Record that a question (all of it) was answered.
+
+ One event, whether the question named one invoice or four. Splitting
+ it would put several rows in the stream against a single decision, in
+ the one place built for scanning.
+ """
+ if not members:
+ return
+ head = members[0]
+ await reconciliation_history_service.record(
+ session,
+ head.workspace_id,
+ status,
+ expectation_kind=head.expectation_kind,
+ expectation_id=head.expectation_id,
+ amount=sum((m.amount for m in members), Decimal("0")),
+ transaction_id=head.transaction_id,
+ strategy_id=head.strategy_id,
+ user_id=user_id,
+ detail={"of_set": len(members)},
+ )
+
+
+async def decline(
+ session: AsyncSession,
+ suggestion: ReconciliationSuggestion,
+ user_id: Optional[uuid.UUID],
+) -> ReconciliationSuggestion:
+ """Say no, once and for all.
+
+ The row stays rather than being deleted, because the *record* of the
+ refusal is the useful part: it is what stops the same pair being
+ offered on every sync from here on.
+ """
+ _resolve(suggestion, "declined", user_id)
+ await session.flush()
+ return suggestion
+
+
+async def mark_accepted(
+ session: AsyncSession,
+ suggestion: ReconciliationSuggestion,
+ user_id: Optional[uuid.UUID],
+) -> ReconciliationSuggestion:
+ """Note that this one was taken. The link itself is the caller's job.
+
+ Marking and linking are separate for the same reason deciding and
+ writing are: an invoice allocation and a recurring upgrade are
+ genuinely different writes, and this module should not know which.
+ """
+ _resolve(suggestion, "accepted", user_id)
+ await session.flush()
+ return suggestion
+
+
+def _by_question(
+ rows: list[ReconciliationSuggestion],
+) -> list[list[ReconciliationSuggestion]]:
+ """Gather rows back into the questions they came from."""
+ groups: dict[Any, list[ReconciliationSuggestion]] = {}
+ for row in rows:
+ groups.setdefault(row.group_id or row.id, []).append(row)
+ return list(groups.values())
+
+
+async def expire_stale(
+ session: AsyncSession, workspace_id: uuid.UUID, *, now: Optional[datetime] = None
+) -> int:
+ """Retire questions nobody answered.
+
+ Expired rather than deleted: the pair stays remembered, so a stale
+ question is not re-asked the moment it is forgotten. That would be the
+ original bug wearing a hat.
+ """
+ cutoff = (now or datetime.now(timezone.utc)) - timedelta(days=STALE_AFTER_DAYS)
+ result = await session.execute(
+ select(ReconciliationSuggestion).where(
+ ReconciliationSuggestion.workspace_id == workspace_id,
+ ReconciliationSuggestion.status == "pending",
+ ReconciliationSuggestion.created_at < cutoff,
+ )
+ )
+ stale = list(result.unique().scalars().all())
+ for suggestion in stale:
+ # Nobody answered, so nobody is recorded as having.
+ _resolve(suggestion, "expired", None)
+ # Grouped questions expire as one event, like every other answer.
+ for group in _by_question(stale):
+ await answered(session, group, "expired", None)
+ if stale:
+ await session.flush()
+ return len(stale)
+
+
+async def drop_for_expectation(
+ session: AsyncSession, workspace_id: uuid.UUID, expectation_id: uuid.UUID
+) -> None:
+ """Clear the queue of a promise that no longer exists.
+
+ There is no foreign key to follow (an invoice and a recurring bill
+ live in different tables), so a deleted promise is cleaned up here.
+ Only pending rows go: an answered question stays answered, which is
+ what keeps `declined` meaningful.
+ """
+ result = await session.execute(
+ select(ReconciliationSuggestion).where(
+ ReconciliationSuggestion.workspace_id == workspace_id,
+ ReconciliationSuggestion.expectation_id == expectation_id,
+ ReconciliationSuggestion.status == "pending",
+ )
+ )
+ for suggestion in result.unique().scalars().all():
+ await session.delete(suggestion)
diff --git a/backend/app/services/recurring_match_service.py b/backend/app/services/recurring_match_service.py
index df98bf56..0722e702 100644
--- a/backend/app/services/recurring_match_service.py
+++ b/backend/app/services/recurring_match_service.py
@@ -5,12 +5,30 @@ card, and bank sync then imports that charge as its own transaction. Without
linking, the user ends up with two rows: the bill's generated placeholder and
the synced charge. This service reconciles the two.
-Matching signals (the intersection of what Actual and Sure use): same account,
-same direction (``type``), exact amount, transaction date within a small window
-of the expected occurrence, and description token-similarity above the same bar
-the bank-sync fuzzy merge already uses. Matches are one-to-one and only the
-high-confidence (exact-amount) tier auto-links; softer/variable-amount matching
-is intentionally left for a later suggestion-based pass.
+## What changed, and what did not
+
+The judgement used to live here as constants and a hand-rolled comparison.
+It now lives in `reconciliation_engine`, under policy documents in
+`reconciliation_policy`; the same decider an invoice goes through, because
+**an invoice and a scheduled occurrence are the same kind of promise**: money
+that is expected, waiting for the movement that confirms it.
+
+**The decisions are unchanged, deliberately.** Same account, same direction,
+exact amount, three days before and five after (two and two for a weekly bill,
+five either side against a placeholder), description token-overlap at 0.6, and
+the better-matching candidate wins rather than both being refused. This lands
+under bills that have been reconciling this way since #116, and a matcher that
+started finding pairs it used to miss would be a behaviour change nobody asked
+for. What is gained today is only that those numbers are now reachable: a
+threshold buried in a module is a threshold no one can ever be shown or offered.
+
+The queries stay here, because they are what differs: three lookups, in two
+directions, over two tables. Only the verdict is shared.
+
+One dormant edge is worth naming: a bill of zero is now never matched, because
+a promise with nothing outstanding is not a candidate. Nothing reaches it:
+banks do not post charges of zero, but it is a difference rather than an
+identity.
"""
import uuid
from datetime import date, timedelta
@@ -22,53 +40,82 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.recurring_transaction import RecurringTransaction
from app.models.transaction import Transaction
-
-# Description-similarity bar for accepting a link. Matches the established
-# bank-sync fuzzy-merge threshold (connection_service._fuzzy_match_manual).
-_SIMILARITY_THRESHOLD = 0.6
+from app.services import reconciliation_policy, reconciliation_rule_service
+from app.services.reconciliation_engine import Expectation, Movement, evaluate
# Real-transaction sources a recurring charge can arrive under. Excludes
-# "recurring" itself — that is the generated placeholder, handled separately.
+# "recurring" itself: that is the generated placeholder, handled separately.
_REAL_SOURCES = ("sync", "ofx", "csv", "manual")
+#: The widest window any recurring policy uses, in days. Only the SQL date
+#: range is cut with it; the policy still decides, per candidate, whether a
+#: charge is close enough. Kept generous on purpose: narrowing the query to
+#: the exact window would silently re-implement the rule in a second place,
+#: and the two would drift.
+_QUERY_WINDOW_DAYS = 5
-def _description_similarity(a: Optional[str], b: Optional[str]) -> float:
- """Token-overlap ratio between two descriptions (0..1)."""
- if not a or not b:
- return 0.0
- tokens_a = set(a.lower().split())
- tokens_b = set(b.lower().split())
- if not tokens_a or not tokens_b:
- return 0.0
- return len(tokens_a & tokens_b) / max(len(tokens_a), len(tokens_b))
+def _as_movement(transaction: Transaction) -> Movement:
+ return Movement(
+ amount=Decimal(transaction.amount or 0),
+ currency=transaction.currency or "",
+ direction=transaction.type,
+ when=transaction.date,
+ description=transaction.description,
+ counterparty=transaction.payee,
+ account_id=transaction.account_id,
+ source=transaction.source,
+ )
-def _match_window(frequency: str) -> tuple[int, int]:
- """Days (before, after) an expected occurrence a real charge may land.
- Charges commonly post a few days after the nominal due date and sometimes
- a day or two early. Windows stay well under one period so a charge can
- never match the neighbouring occurrence.
+def _as_occurrence(
+ recurring: RecurringTransaction, when: date
+) -> Expectation:
+ """One expected occurrence of a bill, as the engine sees it.
+
+ `when` is passed rather than read off the row because the caller knows
+ which occurrence is in question: the one being generated, or the next one
+ due, adjusted for a weekend.
"""
- if frequency == "weekly":
- return 2, 2
- # monthly / yearly
- return 3, 5
+ return Expectation(
+ kind="recurring",
+ id=recurring.id,
+ amount=Decimal(recurring.amount or 0),
+ currency=recurring.currency,
+ direction=recurring.type,
+ when=when,
+ description=recurring.description,
+ account_id=recurring.account_id,
+ )
-def _best_by_similarity(
- candidates, description: Optional[str]
+def _best_movement(
+ candidates,
+ expectation: Expectation,
+ policy: dict,
) -> Optional[Transaction]:
+ """The charge that best answers one expected occurrence.
+
+ The engine takes one movement and many promises; here it is the other way
+ round, so it is asked once per candidate and the answers are ranked. Best
+ score wins, exactly as before: two subscriptions of the same value on one
+ account are told apart by their description, not refused.
+ """
best: Optional[Transaction] = None
- best_score = 0.0
- for cand in candidates:
- if cand.is_ignored:
+ # Below the range a score can take, not at its floor: a rule whose
+ # similarity threshold is 0 can link a candidate scoring exactly
+ # 0.0, and a strict comparison against 0.0 would drop it.
+ best_score = -1.0
+ for candidate in candidates:
+ if candidate.is_ignored:
+ continue
+ decision = evaluate(_as_movement(candidate), [expectation], policy)
+ if decision.port != "linked":
continue
- score = _description_similarity(cand.description, description)
- if score > best_score:
- best_score = score
- best = cand
- return best if best and best_score >= _SIMILARITY_THRESHOLD else None
+ if decision.score > best_score:
+ best_score = decision.score
+ best = candidate
+ return best
async def find_real_tx_for_occurrence(
@@ -81,7 +128,9 @@ async def find_real_tx_for_occurrence(
Used by generate_pending: instead of writing a duplicate placeholder for an
occurrence a real charge already covers, link that charge to the bill.
"""
- before, after = _match_window(recurring.frequency)
+ policy = await reconciliation_rule_service.resolve_recurring(
+ session, recurring.workspace_id, recurring.frequency
+ )
result = await session.execute(
select(Transaction).where(
Transaction.account_id == recurring.account_id,
@@ -90,11 +139,13 @@ async def find_real_tx_for_occurrence(
Transaction.amount == recurring.amount,
Transaction.currency == recurring.currency,
Transaction.type == recurring.type,
- Transaction.date >= occurrence_date - timedelta(days=before),
- Transaction.date <= occurrence_date + timedelta(days=after),
+ Transaction.date >= occurrence_date - timedelta(days=_QUERY_WINDOW_DAYS),
+ Transaction.date <= occurrence_date + timedelta(days=_QUERY_WINDOW_DAYS),
)
)
- return _best_by_similarity(result.scalars(), recurring.description)
+ return _best_movement(
+ result.scalars(), _as_occurrence(recurring, occurrence_date), policy
+ )
async def find_placeholder_for_incoming(
@@ -111,7 +162,14 @@ async def find_placeholder_for_incoming(
Placeholders carry ``source="recurring"`` and a ``recurring_transaction_id``
but no ``external_id`` yet. The caller upgrades the matched row in place to
the synced/imported charge, preserving the recurring link (no duplicate).
+
+ Inverted from the rest of the module: the placeholder is the thing being
+ searched for, so the incoming charge plays the part of the promise and each
+ placeholder is scored against it. The window is symmetric here: a
+ placeholder was written for one specific occurrence, so unlike a bill it has
+ no neighbour to be confused with.
"""
+ policy = reconciliation_policy.default_policy("reconciliation.match_placeholder")
result = await session.execute(
select(Transaction).where(
Transaction.account_id == account_id,
@@ -121,11 +179,21 @@ async def find_placeholder_for_incoming(
Transaction.amount == amount,
Transaction.currency == currency,
Transaction.type == tx_type,
- Transaction.date >= tx_date - timedelta(days=5),
- Transaction.date <= tx_date + timedelta(days=5),
+ Transaction.date >= tx_date - timedelta(days=_QUERY_WINDOW_DAYS),
+ Transaction.date <= tx_date + timedelta(days=_QUERY_WINDOW_DAYS),
)
)
- return _best_by_similarity(result.scalars(), description)
+ incoming = Expectation(
+ kind="recurring",
+ id=uuid.uuid4(),
+ amount=amount,
+ currency=currency,
+ direction=tx_type,
+ when=tx_date,
+ description=description,
+ account_id=account_id,
+ )
+ return _best_movement(result.scalars(), incoming, policy)
async def find_bill_for_incoming(
@@ -143,7 +211,13 @@ async def find_bill_for_incoming(
Used when a real charge arrives before any placeholder was generated. The
caller stamps the charge with the bill and advances the bill past the
fulfilled occurrence so generate_pending won't later duplicate it.
+
+ The one lookup shaped the way the engine natively is (one movement, many
+ promises), except that each bill carries its own window, so each is asked
+ under its own policy rather than all of them under one.
"""
+ from app.services.recurring_transaction_service import adjust_weekend_date
+
result = await session.execute(
select(RecurringTransaction).where(
RecurringTransaction.user_id == user_id,
@@ -154,31 +228,53 @@ async def find_bill_for_incoming(
RecurringTransaction.type == tx_type,
)
)
- from app.services.recurring_transaction_service import adjust_weekend_date
+ charge = Movement(
+ amount=amount,
+ currency=currency,
+ direction=tx_type,
+ when=tx_date,
+ description=description,
+ account_id=account_id,
+ )
best: Optional[RecurringTransaction] = None
- best_score = 0.0
- for rec in result.scalars():
- before, after = _match_window(rec.frequency)
- effective_occurrence = adjust_weekend_date(
- rec.next_occurrence, rec.weekend_adjustment
+ # Below the range a score can take, not at its floor: a rule whose
+ # similarity threshold is 0 can link a candidate scoring exactly
+ # 0.0, and a strict comparison against 0.0 would drop it.
+ best_score = -1.0
+ # The workspace's rules are fetched once for the batch and then
+ # narrowed per bill, rather than queried per candidate: every bill here
+ # belongs to one account, so they share a workspace, and the only thing
+ # that varies between them is how often they repeat.
+ composed: Optional[dict] = None
+ for recurring in result.scalars():
+ if composed is None:
+ composed = await reconciliation_rule_service.resolve(
+ session,
+ recurring.workspace_id,
+ reconciliation_policy.MATCH_RECURRING["node"],
+ )
+ occurrence = adjust_weekend_date(
+ recurring.next_occurrence, recurring.weekend_adjustment
)
- lo = effective_occurrence - timedelta(days=before)
- hi = effective_occurrence + timedelta(days=after)
- if not (lo <= tx_date <= hi):
- continue
- score = _description_similarity(rec.description, description)
- if score > best_score:
- best_score = score
- best = rec
- return best if best and best_score >= _SIMILARITY_THRESHOLD else None
+ decision = evaluate(
+ charge,
+ [_as_occurrence(recurring, occurrence)],
+ reconciliation_rule_service.narrow_for_frequency(
+ composed, recurring.frequency
+ ),
+ )
+ if decision.port == "linked" and decision.score > best_score:
+ best_score = decision.score
+ best = recurring
+ return best
def advance_past(recurring: RecurringTransaction, fulfilled_date: date) -> None:
"""Advance a bill's next_occurrence past the occurrence a charge fulfilled.
- The target is floored at the bill's current next_occurrence — the matched
- occurrence — so an *early-posted* charge (one that lands inside the
+ The target is floored at the bill's current next_occurrence: the matched
+ occurrence, so an *early-posted* charge (one that lands inside the
before-window, i.e. before next_occurrence) still moves the pointer forward.
Advancing only past the posting date would leave next_occurrence unchanged
for early charges (e.g. a Jan 8 charge for a Jan 10 occurrence), and
diff --git a/backend/app/services/report_service.py b/backend/app/services/report_service.py
index 6d5cc49a..6a7c0909 100644
--- a/backend/app/services/report_service.py
+++ b/backend/app/services/report_service.py
@@ -32,6 +32,7 @@ from app.schemas.report import (
ReportResponse,
ReportSummary,
)
+from app.services import invoice_forecast_service
from app.services.dashboard_service import (
_account_balance_at,
_counts_as_user_pnl_row,
@@ -632,6 +633,30 @@ async def get_income_expenses_report(
forecast_map[label] = (existing_income + amount, existing_expenses)
else:
forecast_map[label] = (existing_income, existing_expenses + amount)
+
+ # Invoices still owed, at the date they were promised for. Only
+ # the unallocated balance, so a claim and the payment that
+ # settles it never both land in the same month. Skipped when the
+ # report is narrowed to particular accounts: a claim has no
+ # account until somebody pays it.
+ # `is None`, not falsy: a collection holding only wallets narrows
+ # the report to an empty set of bank accounts, and an empty list
+ # means filtered to nothing rather than not filtered at all.
+ if account_ids is None:
+ for claim in await invoice_forecast_service.claims_in_range(
+ session, workspace_id, max(m_start, start), m_end
+ ):
+ converted, _ = await fx_convert(
+ session, claim.amount, claim.currency, primary_currency,
+ )
+ claim_amount = abs(float(converted))
+ label = _format_date_label(claim.due_date, interval)
+ existing_income, existing_expenses = forecast_map.get(label, (0.0, 0.0))
+ if claim.direction == "receivable":
+ forecast_map[label] = (existing_income + claim_amount, existing_expenses)
+ else:
+ forecast_map[label] = (existing_income, existing_expenses + claim_amount)
+
# Advance to next month
if cursor.month == 12:
cursor = date(cursor.year + 1, 1, 1)
@@ -1490,6 +1515,28 @@ async def get_cash_flow_report(
cat_totals[key] = {"label": info["label"], "color": info["color"], "value": 0.0}
cat_totals[key]["value"] += amount_primary
+ # 3b. Invoices still owed, on the day they were promised for. An
+ # invoice is a claim rather than a movement, which is why it never
+ # reached this chart before: until matching could say that an open
+ # invoice and a pending bank credit were the same money, adding
+ # both would have inflated every projection in the product.
+ #
+ # Only the unallocated balance is carried, so a claim and the
+ # payment that settles it never both appear. Skipped when the
+ # chart is narrowed to particular accounts: a claim has no account
+ # until somebody pays it.
+ # `is None`, not falsy: a collection holding only wallets narrows
+ # the report to an empty set of bank accounts, and an empty list
+ # means filtered to nothing rather than not filtered at all.
+ if account_ids is None:
+ for claim in await invoice_forecast_service.claims_in_range(
+ session, workspace_id, today + timedelta(days=1), end + timedelta(days=1)
+ ):
+ claim_primary = await _to_primary(claim.amount, claim.currency)
+ if claim_primary == 0:
+ continue
+ _add_flow(claim.due_date, abs(claim_primary), claim.direction == "receivable")
+
# 4. Walk day-by-day. The actual section is anchored at today's
# authoritative balance. The forward projected section starts from that
# balance plus pending payables already dated today or earlier.
diff --git a/backend/app/services/text_similarity.py b/backend/app/services/text_similarity.py
new file mode 100644
index 00000000..16578ff1
--- /dev/null
+++ b/backend/app/services/text_similarity.py
@@ -0,0 +1,30 @@
+"""How alike two descriptions are, in one place.
+
+Token overlap over the longer side. It lived in `connection_service`,
+where the bank-sync fuzzy merge tuned it, and was reproduced inside the
+matching engine because that module is pure: it holds no session and
+imports no service, so it could not reach across to a module that pulls in
+models and SQLAlchemy.
+
+Two copies of one formula drift, and this one is a threshold people tune
+against. So it moves here instead: a function with no dependencies, which
+the pure engine may import without giving up what makes it pure.
+
+It is deliberately unforgiving. A bank string and a hand-typed one rarely
+share tokens exactly, which is why the exact-amount signal carries the
+weight and this only guards against two promises of the same value.
+"""
+from __future__ import annotations
+
+from typing import Optional
+
+
+def token_overlap(a: Optional[str], b: Optional[str]) -> float:
+ """0 when nothing is shared, 1 when the words are the same set."""
+ if not a or not b:
+ return 0.0
+ tokens_a = {token for token in a.lower().split() if token}
+ tokens_b = {token for token in b.lower().split() if token}
+ if not tokens_a or not tokens_b:
+ return 0.0
+ return len(tokens_a & tokens_b) / max(len(tokens_a), len(tokens_b))
diff --git a/backend/app/services/transaction_service.py b/backend/app/services/transaction_service.py
index baaca4fc..f67635c3 100644
--- a/backend/app/services/transaction_service.py
+++ b/backend/app/services/transaction_service.py
@@ -22,7 +22,7 @@ from app.schemas.transaction import (
TransferCreate,
)
from app.schemas.transaction_split import TransactionSplitInput, TransactionSplitsInput
-from app.services import split_service
+from app.services import reconciliation_service, split_service
from app.services.credit_card_service import apply_effective_date
from app.services.rule_service import apply_rules_to_transaction
from app.services.fx_rate_service import stamp_primary_amount, convert as fx_convert
@@ -751,6 +751,13 @@ async def create_transaction(
if data.splits is not None:
await split_service.replace_splits(session, transaction, data.splits, user_id)
+ # A payment recorded by hand settles an invoice exactly as a synced one
+ # does. Someone who reconciles by typing the Pix in should not have to
+ # then go and link it: that is the manual work the whole feature exists
+ # to remove, and leaving this path out would remove it only for people
+ # whose bank happens to be connected.
+ await reconciliation_service.match_incoming(session, workspace_id, [transaction])
+
await session.commit()
await session.refresh(transaction, ["category", "splits"])
return transaction
diff --git a/backend/tests/test_connection_service.py b/backend/tests/test_connection_service.py
index 2263d66e..b6610148 100644
--- a/backend/tests/test_connection_service.py
+++ b/backend/tests/test_connection_service.py
@@ -22,8 +22,8 @@ from app.providers.base import (
ProviderUserActionRequired,
TransactionData,
)
+from app.services.text_similarity import token_overlap
from app.services.connection_service import (
- _description_similarity,
_match_pluggy_category,
create_connect_token,
delete_connection,
@@ -78,31 +78,31 @@ async def _make_category(
def test_description_similarity_identical():
- assert _description_similarity("hello world", "hello world") == 1.0
+ assert token_overlap("hello world", "hello world") == 1.0
def test_description_similarity_partial():
- score = _description_similarity("hello world foo", "hello world bar")
+ score = token_overlap("hello world foo", "hello world bar")
assert 0.0 < score < 1.0
def test_description_similarity_no_overlap():
- assert _description_similarity("abc", "xyz") == 0.0
+ assert token_overlap("abc", "xyz") == 0.0
def test_description_similarity_none():
- assert _description_similarity(None, "hello") == 0.0
- assert _description_similarity("hello", None) == 0.0
- assert _description_similarity(None, None) == 0.0
+ assert token_overlap(None, "hello") == 0.0
+ assert token_overlap("hello", None) == 0.0
+ assert token_overlap(None, None) == 0.0
def test_description_similarity_empty():
- assert _description_similarity("", "hello") == 0.0
- assert _description_similarity("hello", "") == 0.0
+ assert token_overlap("", "hello") == 0.0
+ assert token_overlap("hello", "") == 0.0
def test_description_similarity_case_insensitive():
- score = _description_similarity("Hello World", "hello world")
+ score = token_overlap("Hello World", "hello world")
assert score == 1.0
diff --git a/backend/tests/test_fuzzy_matching.py b/backend/tests/test_fuzzy_matching.py
index 90b19da9..a9d0828a 100644
--- a/backend/tests/test_fuzzy_matching.py
+++ b/backend/tests/test_fuzzy_matching.py
@@ -1,54 +1,54 @@
"""Tests for fuzzy transaction matching logic (Phase 2)."""
import pytest
-from app.services.connection_service import _description_similarity
+from app.services.text_similarity import token_overlap
class TestDescriptionSimilarity:
- """Unit tests for the _description_similarity helper."""
+ """Unit tests for the shared token-overlap helper."""
def test_identical_descriptions(self):
- assert _description_similarity("UBER TRIP", "UBER TRIP") == 1.0
+ assert token_overlap("UBER TRIP", "UBER TRIP") == 1.0
def test_partial_overlap(self):
# "UBER" overlaps, "TRIP" vs "RIDE" don't → 1/2 = 0.5
- score = _description_similarity("UBER TRIP", "UBER RIDE")
+ score = token_overlap("UBER TRIP", "UBER RIDE")
assert score == pytest.approx(0.5)
def test_no_overlap(self):
- score = _description_similarity("NETFLIX", "SPOTIFY")
+ score = token_overlap("NETFLIX", "SPOTIFY")
assert score == 0.0
def test_case_insensitive(self):
- score = _description_similarity("Uber Trip", "UBER TRIP")
+ score = token_overlap("Uber Trip", "UBER TRIP")
assert score == 1.0
def test_null_first_arg(self):
- assert _description_similarity(None, "UBER") == 0.0
+ assert token_overlap(None, "UBER") == 0.0
def test_null_second_arg(self):
- assert _description_similarity("UBER", None) == 0.0
+ assert token_overlap("UBER", None) == 0.0
def test_both_null(self):
- assert _description_similarity(None, None) == 0.0
+ assert token_overlap(None, None) == 0.0
def test_empty_first_arg(self):
- assert _description_similarity("", "UBER") == 0.0
+ assert token_overlap("", "UBER") == 0.0
def test_empty_second_arg(self):
- assert _description_similarity("UBER", "") == 0.0
+ assert token_overlap("UBER", "") == 0.0
def test_single_token_match(self):
# "IFOOD" matches in both → 1/2 = 0.5
- score = _description_similarity("IFOOD RESTAURANTE", "IFOOD")
+ score = token_overlap("IFOOD RESTAURANTE", "IFOOD")
assert score == pytest.approx(0.5)
def test_high_overlap_above_threshold(self):
# 3 out of 4 tokens match → 0.75
- score = _description_similarity("PIX RECEBIDO JOAO", "PIX RECEBIDO JOAO SILVA")
+ score = token_overlap("PIX RECEBIDO JOAO", "PIX RECEBIDO JOAO SILVA")
assert score >= 0.6
def test_low_overlap_below_threshold(self):
# Only 1 out of 3 tokens match → 0.33
- score = _description_similarity("PAGAMENTO PIX", "UBER TRIP PIX")
+ score = token_overlap("PAGAMENTO PIX", "UBER TRIP PIX")
assert score < 0.6
diff --git a/backend/tests/test_invoice_attachments.py b/backend/tests/test_invoice_attachments.py
index 0af9107d..6202b9b8 100644
--- a/backend/tests/test_invoice_attachments.py
+++ b/backend/tests/test_invoice_attachments.py
@@ -61,6 +61,10 @@ async def make_invoice(client, headers, **overrides) -> dict:
"total": "1200.00",
"due_date": str(TODAY + timedelta(days=20)),
"lines": [{"description": "Servico", "quantity": "1", "unit_price": "1200.00"}],
+ # A draft, because issuing files our own rendered page and every
+ # test below counts what a *person* put in the folder. The filed
+ # document has its own tests, in `test_invoices_api.py`.
+ "as_draft": True,
}
payload.update(overrides)
resp = await client.post("/api/invoices", headers=headers, json=payload)
diff --git a/backend/tests/test_invoice_forecast.py b/backend/tests/test_invoice_forecast.py
new file mode 100644
index 00000000..0a247208
--- /dev/null
+++ b/backend/tests/test_invoice_forecast.py
@@ -0,0 +1,372 @@
+"""Money promised, in the forecast, without being counted twice.
+
+The whole reason invoices stayed out of the projected balance until now:
+the same R$5.000 is routinely an open invoice *and* a pending bank credit,
+and nothing could say they were the same money. Payment matching is what
+says it, so these tests care less about "does an invoice show up" than
+about "does it stop showing up the moment the payment does".
+"""
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+import pytest_asyncio
+from httpx import AsyncClient
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.account import Account
+from app.models.payee import Payee
+from app.services import invoice_forecast_service as forecast
+
+TODAY = date.today()
+SOON = TODAY + timedelta(days=10)
+FAR = TODAY + timedelta(days=400)
+
+
+@pytest_asyncio.fixture
+async def business_ws(client: AsyncClient, auth_headers) -> dict:
+ resp = await client.post(
+ "/api/workspaces",
+ headers=auth_headers,
+ json={"name": "Previsao", "kind": "business", "self_membership": True},
+ )
+ assert resp.status_code == 201, resp.text
+ return resp.json()
+
+
+@pytest_asyncio.fixture
+async def biz_headers(auth_headers, business_ws) -> dict:
+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}
+
+
+@pytest_asyncio.fixture
+async def account(session: AsyncSession, business_ws, test_user) -> Account:
+ acc = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Conta PJ",
+ type="checking",
+ currency="USD",
+ balance=Decimal("0"),
+ )
+ session.add(acc)
+ await session.commit()
+ return acc
+
+
+@pytest_asyncio.fixture
+async def client_payee(session: AsyncSession, business_ws, test_user) -> Payee:
+ payee = Payee(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Cliente Alpha",
+ source="manual",
+ )
+ session.add(payee)
+ await session.commit()
+ return payee
+
+
+async def an_invoice(client, headers, **overrides) -> dict:
+ payload = {"total": "5000.00", "due_date": str(SOON)}
+ payload.update(overrides)
+ resp = await client.post("/api/invoices", headers=headers, json=payload)
+ assert resp.status_code == 201, resp.text
+ return resp.json()
+
+
+async def claims(session, business_ws, *, start=None, end=None):
+ return await forecast.claims_in_range(
+ session,
+ uuid.UUID(business_ws["id"]),
+ start or TODAY,
+ end or FAR,
+ )
+
+
+# ---------------------------------------------------------------------------
+# What is carried
+# ---------------------------------------------------------------------------
+async def test_an_open_invoice_is_money_the_forecast_can_carry(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ await an_invoice(client, biz_headers)
+ found = await claims(session, business_ws)
+
+ assert len(found) == 1
+ assert found[0].amount == Decimal("5000.00")
+ assert found[0].due_date == SOON
+ assert found[0].signed == Decimal("5000.00")
+
+
+async def test_a_bill_to_pay_points_the_other_way(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """A payable is the same claim with the sign reversed. Filing it as
+ income would turn every supplier bill into revenue."""
+ await an_invoice(
+ client, biz_headers, direction="payable", origin="imported",
+ external_source="supplier", external_number="NF-1",
+ )
+ found = await claims(session, business_ws)
+
+ assert len(found) == 1
+ assert found[0].direction == "payable"
+ assert found[0].signed == Decimal("-5000.00")
+
+
+async def test_a_draft_is_not_owed_by_anybody_yet(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ await an_invoice(client, biz_headers, as_draft=True)
+ assert await claims(session, business_ws) == []
+
+
+async def test_a_cancelled_invoice_is_money_that_is_not_coming(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ invoice = await an_invoice(client, biz_headers)
+ resp = await client.post(f"/api/invoices/{invoice['id']}/void", headers=biz_headers)
+ assert resp.status_code == 200, resp.text
+
+ assert await claims(session, business_ws) == []
+
+
+async def test_written_off_money_is_not_forecast_either(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ invoice = await an_invoice(client, biz_headers)
+ resp = await client.post(
+ f"/api/invoices/{invoice['id']}/uncollectible", headers=biz_headers
+ )
+ assert resp.status_code == 200, resp.text
+
+ assert await claims(session, business_ws) == []
+
+
+# ---------------------------------------------------------------------------
+# The double count this waited for
+# ---------------------------------------------------------------------------
+async def test_a_paid_invoice_leaves_the_forecast_to_the_transaction(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws, account,
+ client_payee,
+):
+ """The reason invoices stayed out until matching existed. Once the
+ payment is linked the claim is gone, and the money is counted once."""
+ await an_invoice(client, biz_headers, payee_id=str(client_payee.id))
+ tx = await client.post(
+ "/api/transactions",
+ headers=biz_headers,
+ json={
+ "description": "PIX ALPHA",
+ "amount": "5000.00",
+ "currency": "USD",
+ "date": str(TODAY),
+ "type": "credit",
+ "account_id": str(account.id),
+ "payee_id": str(client_payee.id),
+ },
+ )
+ assert tx.status_code in (200, 201), tx.text
+
+ # Nobody linked anything by hand: the engine did it on the way in,
+ # which is the whole point. The claim is gone and the transaction
+ # carries the money alone.
+ assert await claims(session, business_ws) == []
+
+
+async def test_only_what_is_left_is_carried(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws, account
+):
+ """Half paid means half forecast. Carrying the whole total would
+ count the settled half twice."""
+ invoice = await an_invoice(client, biz_headers)
+ tx = await client.post(
+ "/api/transactions",
+ headers=biz_headers,
+ json={
+ "description": "Sinal",
+ "amount": "2000.00",
+ "currency": "USD",
+ "date": str(TODAY),
+ "type": "credit",
+ "account_id": str(account.id),
+ },
+ )
+ await client.post(
+ f"/api/invoices/{invoice['id']}/allocations",
+ headers=biz_headers,
+ json={"transaction_id": tx.json()["id"], "amount": "2000.00"},
+ )
+
+ found = await claims(session, business_ws)
+ assert len(found) == 1
+ assert found[0].amount == Decimal("3000.00")
+
+
+# ---------------------------------------------------------------------------
+# Where it sits in time
+# ---------------------------------------------------------------------------
+async def test_it_lands_on_the_day_it_was_promised_for(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ await an_invoice(client, biz_headers)
+
+ assert await claims(session, business_ws, end=SOON) == [], "before the due date"
+ assert len(await claims(session, business_ws, end=SOON + timedelta(days=1))) == 1
+
+
+async def test_an_overdue_invoice_is_not_relocated_to_today(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """Still owed, deliberately not projected. The only date we have has
+ passed, and moving it to today would invent one nobody promised, and
+ make the aging table and the forecast disagree about one debt."""
+ await an_invoice(
+ client,
+ biz_headers,
+ issue_date=str(TODAY - timedelta(days=90)),
+ due_date=str(TODAY - timedelta(days=60)),
+ )
+
+ assert await claims(session, business_ws) == []
+
+
+async def test_a_foreign_invoice_stays_in_its_own_currency(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """Unconverted on the way out: a balance walk keeps a figure per
+ currency, and converting here would force it to undo the conversion."""
+ await an_invoice(client, biz_headers, currency="EUR")
+ found = await claims(session, business_ws)
+
+ assert len(found) == 1
+ assert found[0].currency == "EUR"
+
+
+async def test_another_workspace_never_leaks_into_this_forecast(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws, auth_headers
+):
+ other = await client.post(
+ "/api/workspaces",
+ headers=auth_headers,
+ json={"name": "Outra", "kind": "business", "self_membership": True},
+ )
+ await an_invoice(
+ client, {**auth_headers, "X-Workspace-Id": other.json()["id"]}
+ )
+
+ assert await claims(session, business_ws) == []
+
+
+# ---------------------------------------------------------------------------
+# Through the dashboard, which is where a person sees it
+# ---------------------------------------------------------------------------
+async def test_the_projected_balance_carries_what_is_owed(
+ client: AsyncClient, biz_headers, session: AsyncSession, account
+):
+ """Reaching the endpoint, not just the service. The claim was that
+ nothing in invoicing reaches the projected balance; this is the line
+ that stops being true."""
+ month = TODAY.replace(day=1).isoformat()
+ before = await client.get(
+ f"/api/dashboard/summary?month={month}", headers=biz_headers
+ )
+ assert before.status_code == 200, before.text
+ base = before.json()["projected_balance"]
+
+ await an_invoice(client, biz_headers, due_date=str(TODAY + timedelta(days=1)))
+
+ after = await client.get(
+ f"/api/dashboard/summary?month={month}", headers=biz_headers
+ )
+ grew = after.json()["projected_balance"]
+ assert float(grew.get("USD", 0)) == pytest.approx(float(base.get("USD", 0)) + 5000.0)
+
+
+async def test_the_cash_flow_report_carries_it_too(
+ client: AsyncClient, biz_headers, session: AsyncSession
+):
+ """The dashboard and the report walk the forecast separately, so
+ landing in one proves nothing about the other."""
+ url = "/api/reports/cash-flow?months=6&interval=monthly"
+ before = await client.get(url, headers=biz_headers)
+ assert before.status_code == 200, before.text
+
+ def projected(payload: dict) -> float:
+ return sum(
+ float(point["breakdowns"].get("inflow") or 0) for point in payload["trend"]
+ )
+
+ base = projected(before.json())
+ await an_invoice(client, biz_headers, due_date=str(TODAY + timedelta(days=1)))
+
+ after = await client.get(url, headers=biz_headers)
+ assert projected(after.json()) == pytest.approx(base + 5000.0)
+
+
+async def test_a_bill_to_pay_lands_on_the_other_side_of_the_report(
+ client: AsyncClient, biz_headers, session: AsyncSession
+):
+ """Filing a supplier bill under income would turn every debt into
+ revenue, which is the one mistake a cash-flow report cannot make."""
+ url = "/api/reports/cash-flow?months=6&interval=monthly"
+ before = (await client.get(url, headers=biz_headers)).json()
+
+ def outgoing(payload: dict) -> float:
+ return sum(
+ float(point["breakdowns"].get("outflow") or 0) for point in payload["trend"]
+ )
+
+ base = outgoing(before)
+ await an_invoice(
+ client, biz_headers, direction="payable", origin="imported",
+ external_source="supplier", external_number="NF-2",
+ due_date=str(TODAY + timedelta(days=1)),
+ )
+
+ after = (await client.get(url, headers=biz_headers)).json()
+ assert outgoing(after) == pytest.approx(base + 5000.0)
+
+
+async def test_a_filter_that_matches_no_account_does_not_carry_claims(
+ client: AsyncClient, biz_headers, session: AsyncSession, account
+):
+ """A collection of wallets and no bank accounts still filters.
+
+ It coerces the account list to empty, and empty means *narrowed to
+ nothing*, not *not narrowed*. Reading it as falsy put every claim in
+ the workspace back into a total whose transactions had all been
+ filtered away: a projected balance built from money the filter had
+ just excluded."""
+ month = TODAY.replace(day=1).isoformat()
+ wallets_only = f"?month={month}&asset_group_ids={uuid.uuid4()}"
+
+ before = (await client.get(f"/api/dashboard/summary{wallets_only}", headers=biz_headers)).json()
+ await an_invoice(client, biz_headers, due_date=str(TODAY + timedelta(days=1)))
+ after = (await client.get(f"/api/dashboard/summary{wallets_only}", headers=biz_headers)).json()
+
+ assert after["projected_balance"] == before["projected_balance"]
+
+ # And unfiltered it does carry, so the guard narrowed the case rather
+ # than switching the feature off.
+ whole = (await client.get(f"/api/dashboard/summary?month={month}", headers=biz_headers)).json()
+ assert float(whole["projected_balance"].get("USD", 0)) > 0
diff --git a/backend/tests/test_invoices_api.py b/backend/tests/test_invoices_api.py
index 7d828174..15da2d6e 100644
--- a/backend/tests/test_invoices_api.py
+++ b/backend/tests/test_invoices_api.py
@@ -1439,3 +1439,134 @@ async def test_one_payment_advertises_every_invoice_it_settled(
first["id"], second["id"],
}
assert sum(Decimal(link["amount"]) for link in row["invoice_links"]) == Decimal("1000.00")
+
+
+# ---------------------------------------------------------------------------
+# The document that was issued stays the document that was issued
+# ---------------------------------------------------------------------------
+async def test_issuing_files_the_pdf_so_it_stops_drifting(
+ client: AsyncClient, biz_headers, session: AsyncSession, inflow, client_payee
+):
+ """The renderer prints Paid and Balance as soon as money moves, so an
+ invoice sent showing a total of 3000 came back, after a payment,
+ showing a balance instead. A different document at the same address,
+ including the public link the client was given.
+
+ Filing it at issue makes the answer a stored file. A file cannot
+ drift.
+ """
+ invoice = await _create(client, biz_headers, payee_id=str(client_payee.id))
+
+ before = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)
+ assert before.status_code == 200, before.text
+ original = before.content
+ assert original.startswith(b"%PDF")
+
+ resp = await client.post(
+ f"/api/invoices/{invoice['id']}/allocations",
+ headers=biz_headers,
+ json={"transaction_id": str(inflow.id), "amount": "1000.00"},
+ )
+ assert resp.status_code == 201, resp.text
+
+ after = await client.get(f"/api/invoices/{invoice['id']}/pdf", headers=biz_headers)
+ assert after.status_code == 200
+ assert after.content == original, "the document a client holds must not change"
+
+
+async def test_the_filed_document_is_the_one_the_shared_link_serves(
+ client: AsyncClient, biz_headers, session: AsyncSession, inflow, client_payee
+):
+ """The failure that motivated this: the link handed to a client is
+ public and permanent, so it is the worst place for content to move."""
+ invoice = await _create(client, biz_headers, payee_id=str(client_payee.id))
+ listing = await client.get(
+ f"/api/invoices/{invoice['id']}/attachments", headers=biz_headers
+ )
+ assert listing.status_code == 200, listing.text
+ filed = listing.json()
+ assert len(filed) == 1
+ assert filed[0]["is_primary"] is True
+ assert filed[0]["source"] == "issued"
+ assert filed[0]["filename"].endswith(".pdf")
+
+
+async def test_a_draft_files_nothing_until_it_is_issued(
+ client: AsyncClient, biz_headers, session: AsyncSession, client_payee
+):
+ """A draft's numbers are still moving, and it was never sent."""
+ draft = await _create(
+ client, biz_headers, payee_id=str(client_payee.id), as_draft=True
+ )
+ listing = await client.get(
+ f"/api/invoices/{draft['id']}/attachments", headers=biz_headers
+ )
+ assert listing.json() == []
+
+ issued = await client.post(
+ f"/api/invoices/{draft['id']}/issue", headers=biz_headers
+ )
+ assert issued.status_code == 200, issued.text
+
+ listing = await client.get(
+ f"/api/invoices/{draft['id']}/attachments", headers=biz_headers
+ )
+ assert len(listing.json()) == 1
+
+
+async def test_a_document_somebody_already_filed_is_never_overwritten(
+ client: AsyncClient, biz_headers, session: AsyncSession, client_payee
+):
+ """A signed copy, or the version that actually went by email, is the
+ original. Ours would be a second opinion about a document that has
+ one.
+
+ Marking it primary is the act that says so: an ordinary upload
+ against an invoice we wrote is supplementary paper, and the guard is
+ deliberately keyed to that flag rather than to "any file is here".
+ """
+ draft = await _create(
+ client, biz_headers, payee_id=str(client_payee.id), as_draft=True
+ )
+ upload = await client.post(
+ f"/api/invoices/{draft['id']}/attachments",
+ headers=biz_headers,
+ files={"file": ("assinada.pdf", b"%PDF-1.4 the real one", "application/pdf")},
+ data={"kind": "bill", "is_primary": "true"},
+ )
+ assert upload.status_code == 201, upload.text
+ assert upload.json()["is_primary"] is True
+
+ await client.post(f"/api/invoices/{draft['id']}/issue", headers=biz_headers)
+
+ served = await client.get(f"/api/invoices/{draft['id']}/pdf", headers=biz_headers)
+ assert served.content == b"%PDF-1.4 the real one"
+
+
+async def test_an_imported_document_is_never_given_a_page_we_wrote(
+ client: AsyncClient, biz_headers, session: AsyncSession, client_payee
+):
+ """We did not write it. Rendering our own page over a supplier's bill
+ produces something that looks official and is not."""
+ imported = await _create(
+ client,
+ biz_headers,
+ payee_id=str(client_payee.id),
+ origin="imported",
+ external_source="supplier",
+ external_number="FAT-9931",
+ )
+ listing = await client.get(
+ f"/api/invoices/{imported['id']}/attachments", headers=biz_headers
+ )
+ assert listing.json() == [], "nothing of ours was filed against it"
+
+ served = await client.get(
+ f"/api/invoices/{imported['id']}/pdf", headers=biz_headers
+ )
+ assert served.status_code == 409
diff --git a/backend/tests/test_reconciliation_conditions.py b/backend/tests/test_reconciliation_conditions.py
new file mode 100644
index 00000000..1cef3470
--- /dev/null
+++ b/backend/tests/test_reconciliation_conditions.py
@@ -0,0 +1,1463 @@
+"""Every condition a rule can carry, and what it does to a real match.
+
+Pure tests, no database: the engine decides and never writes, which is
+what lets this file ask several hundred questions in a fraction of a
+second. Reconciliation binds money to debts, so the bar here is not "the
+happy path works": it is that each condition is exercised on **both**
+sides of its boundary, and that combinations behave the way the sentence
+on screen says they do.
+
+Organised by the question each condition answers:
+
+ - *Does this rule apply to money like this?*: account, payee list,
+ direction, currency, amount band, statement text. These decide
+ whether the rule is consulted at all.
+ - *Does this money answer this promise?*: amount comparison, dates,
+ description similarity, counterparty. These decide the pair.
+
+The distinction matters because the two fail differently, and a person
+reading a trace needs to know which happened: "no rule was written for
+money like this" and "the rule looked and said no" are different problems
+with different fixes.
+"""
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+
+from app.services import reconciliation_policy as policy_module
+from app.services import reconciliation_rule_service as rule_service
+from app.services.reconciliation_engine import (
+ Expectation,
+ Movement,
+ Reason,
+ evaluate,
+)
+
+TODAY = date(2026, 9, 1)
+CLIENT = uuid.uuid4()
+OTHER_CLIENT = uuid.uuid4()
+ACCOUNT = uuid.uuid4()
+OTHER_ACCOUNT = uuid.uuid4()
+
+
+def an_invoice(
+ *,
+ amount: Decimal = Decimal("3000.00"),
+ currency: str = "BRL",
+ direction: str = "credit",
+ when: date = TODAY,
+ issued: date | None = None,
+ description: str = "Consultoria",
+ payee_id: uuid.UUID | None = CLIENT,
+) -> Expectation:
+ return Expectation(
+ kind="invoice",
+ id=uuid.uuid4(),
+ amount=amount,
+ currency=currency,
+ direction=direction,
+ when=when,
+ issued=issued,
+ description=description,
+ payee_id=payee_id,
+ )
+
+
+def money(
+ *,
+ amount: Decimal = Decimal("3000.00"),
+ currency: str = "BRL",
+ direction: str = "credit",
+ when: date = TODAY,
+ description: str | None = "PIX RECEBIDO",
+ payee_id: uuid.UUID | None = CLIENT,
+ account_id: uuid.UUID | None = ACCOUNT,
+ source: str = "sync",
+) -> Movement:
+ return Movement(
+ amount=amount,
+ currency=currency,
+ direction=direction,
+ when=when,
+ description=description,
+ payee_id=payee_id,
+ account_id=account_id,
+ source=source,
+ )
+
+
+def one_rule(when: dict, outcome: str = "link") -> dict:
+ """A policy holding a single rule, so a test isolates one condition.
+
+ Built rather than taken from the shipped document on purpose: a test
+ that leans on the defaults starts failing when the defaults improve,
+ which is the opposite of what these are for.
+ """
+ return {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {"id": "under_test", "enabled": True, "outcome": outcome, "when": when}
+ ],
+ "on_ambiguity": "suggest",
+ }
+
+
+BASE = {
+ "counterparty": "any",
+ "amount": {"match": "exact"},
+ "date": {"before_days": 30, "after_days": 30},
+}
+
+
+def with_scope(**extra) -> dict:
+ return {**BASE, **extra}
+
+
+# ===========================================================================
+# Does this rule apply to money like this?
+# ===========================================================================
+class TestAccountScope:
+ """"Only for this bank account."
+
+ The rule tools make this the first choice on every rule, and the reason
+ is mundane: a business with a payments account and an operating
+ account does not want one account's automation reaching into the
+ other's statement.
+ """
+
+ def test_money_in_a_named_account_is_matched(self):
+ rule = with_scope(accounts={"in": [str(ACCOUNT)]})
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "linked"
+
+ def test_money_in_any_other_account_is_left_alone(self):
+ rule = with_scope(accounts={"in": [str(ACCOUNT)]})
+ decision = evaluate(
+ money(account_id=OTHER_ACCOUNT), [an_invoice()], one_rule(rule)
+ )
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.OUT_OF_SCOPE
+
+ def test_several_accounts_can_share_one_rule(self):
+ rule = with_scope(accounts={"in": [str(ACCOUNT), str(OTHER_ACCOUNT)]})
+ for account in (ACCOUNT, OTHER_ACCOUNT):
+ assert (
+ evaluate(
+ money(account_id=account), [an_invoice()], one_rule(rule)
+ ).port
+ == "linked"
+ )
+
+ def test_money_with_no_account_does_not_slip_through_an_account_rule(self):
+ """A rule naming accounts must not treat "no account" as "every
+ account". Failing narrow is the safe direction when the thing
+ being decided is whether money moves."""
+ rule = with_scope(accounts={"in": [str(ACCOUNT)]})
+ assert (
+ evaluate(money(account_id=None), [an_invoice()], one_rule(rule)).port
+ == "unmatched"
+ )
+
+ def test_no_account_condition_means_every_account(self):
+ assert (
+ evaluate(
+ money(account_id=OTHER_ACCOUNT), [an_invoice()], one_rule(BASE)
+ ).port
+ == "linked"
+ )
+
+
+class TestPayeeScope:
+ """"Only for these clients."
+
+ Distinct from `counterparty: same_payee`, which asks whether the payer
+ is *the one on the invoice*. This names specific clients: the ask
+ behind "this customer always pays short, never auto-link them".
+ """
+
+ def test_a_named_client_is_matched(self):
+ rule = with_scope(payees={"in": [str(CLIENT)]})
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "linked"
+
+ def test_another_client_is_left_alone(self):
+ rule = with_scope(payees={"in": [str(OTHER_CLIENT)]})
+ decision = evaluate(money(), [an_invoice()], one_rule(rule))
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.OUT_OF_SCOPE
+
+ def test_an_unidentified_payer_is_not_one_of_the_named_clients(self):
+ rule = with_scope(payees={"in": [str(CLIENT)]})
+ assert (
+ evaluate(money(payee_id=None), [an_invoice()], one_rule(rule)).port
+ == "unmatched"
+ )
+
+
+class TestDirectionScope:
+ """"Only money going out", or only money coming in.
+
+ The rule tools ask this before anything else. Here the expectation
+ already implies a direction, so this is the narrower statement: a rule
+ that exists only for payables, even though invoices come in both
+ kinds.
+ """
+
+ def test_an_outflow_rule_ignores_incoming_money(self):
+ rule = with_scope(direction="debit")
+ decision = evaluate(money(), [an_invoice()], one_rule(rule))
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.OUT_OF_SCOPE
+
+ def test_an_outflow_rule_matches_a_payable(self):
+ rule = with_scope(direction="debit")
+ decision = evaluate(
+ money(direction="debit"),
+ [an_invoice(direction="debit")],
+ one_rule(rule),
+ )
+ assert decision.port == "linked"
+
+ def test_any_is_the_same_as_saying_nothing(self):
+ assert (
+ evaluate(money(), [an_invoice()], one_rule(with_scope(direction="any"))).port
+ == "linked"
+ )
+
+
+class TestCurrencyScope:
+ """"Only in dollars", or "only in a currency that is not ours".
+
+ The second is the one somebody actually asks for: a workspace keeping
+ books in reais wants euro receipts looked at by a person, without
+ having to name every currency the world might send.
+ """
+
+ def test_a_named_currency_matches(self):
+ rule = with_scope(currency={"conversion": "reject", "in": ["USD"]})
+ decision = evaluate(
+ money(currency="USD"), [an_invoice(currency="USD")], one_rule(rule)
+ )
+ assert decision.port == "linked"
+
+ def test_a_currency_not_on_the_list_is_out_of_scope(self):
+ rule = with_scope(currency={"conversion": "reject", "in": ["USD"]})
+ decision = evaluate(money(), [an_invoice()], one_rule(rule))
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.OUT_OF_SCOPE
+
+ def test_currency_codes_are_compared_as_written(self):
+ """Stored uppercase by the validator, so the engine can compare
+ plainly rather than guessing at case on every transaction."""
+ rule = with_scope(currency={"conversion": "reject", "in": ["USD", "EUR"]})
+ assert (
+ evaluate(
+ money(currency="EUR"), [an_invoice(currency="EUR")], one_rule(rule)
+ ).port
+ == "linked"
+ )
+
+ def test_foreign_means_not_what_this_workspace_deals_in(self):
+ rule = with_scope(currency={"conversion": "reject", "foreign": True})
+ decision = evaluate(
+ money(currency="USD"),
+ [an_invoice(currency="USD")],
+ one_rule(rule),
+ base_currency="BRL",
+ )
+ assert decision.port == "linked"
+
+ def test_the_home_currency_is_not_foreign(self):
+ rule = with_scope(currency={"conversion": "reject", "foreign": True})
+ decision = evaluate(
+ money(), [an_invoice()], one_rule(rule), base_currency="BRL"
+ )
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.OUT_OF_SCOPE
+
+ def test_without_a_home_currency_a_foreign_rule_does_nothing(self):
+ """Rather than treating everything as foreign. A rule that fires on
+ everything because we failed to look something up is worse than a
+ rule that fires on nothing."""
+ rule = with_scope(currency={"conversion": "reject", "foreign": True})
+ assert (
+ evaluate(money(currency="USD"), [an_invoice(currency="USD")], one_rule(rule)).port
+ == "unmatched"
+ )
+
+ def test_naming_a_currency_never_lets_the_pair_disagree(self):
+ """`in` says which money the rule looks at at all. It is not
+ permission for the two sides to be different money.
+
+ This test used to assert the opposite, because a
+ `conversion: allow` knob read as *convert and compare* and did
+ nothing of the sort: it settled a Brazilian invoice with dollars
+ at face value, and this test pinned that as a feature.
+ """
+ rule = with_scope(currency={"in": ["USD"]})
+ assert (
+ evaluate(
+ money(currency="USD"), [an_invoice(currency="BRL")], one_rule(rule)
+ ).port
+ == "unmatched"
+ )
+ assert (
+ evaluate(
+ money(currency="USD"), [an_invoice(currency="USD")], one_rule(rule)
+ ).port
+ == "linked"
+ )
+
+
+class TestAmountBand:
+ """"Only under ten thousand", or "only above five hundred".
+
+ The amount operators every rule tool offers, and the single most
+ requested guardrail:
+ small payments settle themselves, large ones get a human. It is a
+ filter on the money, not a comparison with the promise: a rule can
+ demand an exact match *and* refuse to act above a ceiling.
+ """
+
+ def test_money_inside_the_band_matches(self):
+ rule = with_scope(amount={"match": "exact", "min": "100", "max": "5000"})
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "linked"
+
+ def test_money_above_the_ceiling_is_left_for_a_person(self):
+ rule = with_scope(amount={"match": "exact", "max": "1000"})
+ decision = evaluate(money(), [an_invoice()], one_rule(rule))
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.OUT_OF_SCOPE
+
+ def test_money_below_the_floor_is_left_alone(self):
+ rule = with_scope(amount={"match": "exact", "min": "5000"})
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "unmatched"
+
+ def test_the_boundaries_are_inclusive(self):
+ """Somebody who writes "up to 3000" means 3000 is allowed. Off by
+ one here is a payment that silently stops being matched."""
+ exact = with_scope(amount={"match": "exact", "min": "3000", "max": "3000"})
+ assert evaluate(money(), [an_invoice()], one_rule(exact)).port == "linked"
+
+ def test_a_band_is_read_on_the_size_of_the_movement_not_its_sign(self):
+ """An outflow of 3000 is three thousand of money, not minus three
+ thousand: otherwise every band would need writing twice."""
+ rule = with_scope(
+ direction="debit", amount={"match": "exact", "min": "1000", "max": "5000"}
+ )
+ decision = evaluate(
+ money(amount=Decimal("-3000.00"), direction="debit"),
+ [an_invoice(direction="debit")],
+ one_rule(rule),
+ )
+ assert decision.port == "linked"
+
+ def test_a_band_and_a_tolerance_are_different_questions(self):
+ """The band says the rule applies; the tolerance says how close the
+ pair must be. Both hold at once."""
+ rule = with_scope(
+ amount={"match": "tolerance", "percent": "5", "min": "1000"}
+ )
+ near = evaluate(
+ money(amount=Decimal("2950.00")), [an_invoice()], one_rule(rule)
+ )
+ assert near.port == "linked"
+
+ below_band = evaluate(
+ money(amount=Decimal("500.00")),
+ [an_invoice(amount=Decimal("500.00"))],
+ one_rule(rule),
+ )
+ assert below_band.port == "unmatched"
+
+
+class TestStatementText:
+ """"Only when the statement says PIX", or "never when it says ESTORNO".
+
+ Bank text is where a payment's real identity hides, which is why every
+ rule tool puts it front and centre. It is also the bridge to
+ something we cannot yet read structurally: a client whose transfers
+ always carry their tax number can be recognised by that number today,
+ typed in as a fragment.
+ """
+
+ def test_a_required_fragment_matches(self):
+ rule = with_scope(text={"contains": "PIX"})
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "linked"
+
+ def test_a_missing_fragment_puts_the_rule_out_of_scope(self):
+ rule = with_scope(text={"contains": "TED"})
+ decision = evaluate(money(), [an_invoice()], one_rule(rule))
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.OUT_OF_SCOPE
+
+ def test_matching_ignores_case(self):
+ """Banks shout. Nobody should have to guess whether their
+ statement writes PIX or Pix."""
+ rule = with_scope(text={"contains": "pix recebido"})
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "linked"
+
+ def test_an_excluded_fragment_holds_the_rule_back(self):
+ rule = with_scope(text={"not_contains": "ESTORNO"})
+ decision = evaluate(
+ money(description="PIX ESTORNO CLIENTE"), [an_invoice()], one_rule(rule)
+ )
+ assert decision.port == "unmatched"
+
+ def test_include_and_exclude_work_together(self):
+ rule = with_scope(text={"contains": "PIX", "not_contains": "ESTORNO"})
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "linked"
+ assert (
+ evaluate(
+ money(description="PIX ESTORNO"), [an_invoice()], one_rule(rule)
+ ).port
+ == "unmatched"
+ )
+
+ def test_a_movement_with_no_description_fails_a_required_fragment(self):
+ rule = with_scope(text={"contains": "PIX"})
+ assert (
+ evaluate(money(description=None), [an_invoice()], one_rule(rule)).port
+ == "unmatched"
+ )
+
+ def test_a_movement_with_no_description_passes_an_exclusion(self):
+ """Nothing was said, so nothing forbidden was said."""
+ rule = with_scope(text={"not_contains": "ESTORNO"})
+ assert (
+ evaluate(money(description=None), [an_invoice()], one_rule(rule)).port
+ == "linked"
+ )
+
+
+# ===========================================================================
+# Conditions working together
+# ===========================================================================
+class TestCombinations:
+ """Every condition must hold: there is no ANY mode, on purpose.
+
+ The categorization rules above this feature offer AND/OR because a
+ wrong guess there is a mislabelled row. Here a wrong guess binds money
+ to a debt, and "the amount matches OR the date is close" has no safe
+ reading.
+ """
+
+ def test_all_conditions_must_hold(self):
+ rule = with_scope(
+ accounts={"in": [str(ACCOUNT)]},
+ text={"contains": "PIX"},
+ amount={"match": "exact", "max": "5000"},
+ currency={"conversion": "reject", "in": ["BRL"]},
+ )
+ assert evaluate(money(), [an_invoice()], one_rule(rule)).port == "linked"
+
+ @pytest.mark.parametrize(
+ "broken",
+ [
+ {"accounts": {"in": [str(OTHER_ACCOUNT)]}},
+ {"text": {"contains": "BOLETO"}},
+ {"amount": {"match": "exact", "max": "100"}},
+ {"currency": {"conversion": "reject", "in": ["USD"]}},
+ {"direction": "debit"},
+ {"payees": {"in": [str(OTHER_CLIENT)]}},
+ ],
+ )
+ def test_one_failing_condition_is_enough_to_stop_the_rule(self, broken):
+ """Parametrised because the failure has to be symmetric: a rule
+ with five conditions that fires when four hold is not a rule."""
+ rule = with_scope(
+ **{
+ "accounts": {"in": [str(ACCOUNT)]},
+ "text": {"contains": "PIX"},
+ "amount": {"match": "exact", "max": "5000"},
+ "currency": {"conversion": "reject", "in": ["BRL"]},
+ "direction": "credit",
+ "payees": {"in": [str(CLIENT)]},
+ **broken,
+ }
+ )
+ decision = evaluate(money(), [an_invoice()], one_rule(rule))
+ assert decision.port == "unmatched"
+
+ def test_a_narrow_rule_can_run_before_a_broad_one(self):
+ """The whole reason order is editable: a specific client's
+ exception has to be consulted before the general rule that would
+ otherwise swallow it."""
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "this_client_needs_a_human",
+ "enabled": True,
+ "outcome": "suggest",
+ "when": with_scope(payees={"in": [str(CLIENT)]}),
+ },
+ {
+ "id": "everyone_else_links",
+ "enabled": True,
+ "outcome": "link",
+ "when": BASE,
+ },
+ ],
+ "on_ambiguity": "suggest",
+ }
+ theirs = evaluate(money(), [an_invoice()], policy)
+ assert theirs.port == "suggested"
+ assert theirs.strategy == "this_client_needs_a_human"
+
+ anyone = evaluate(
+ money(payee_id=OTHER_CLIENT), [an_invoice(payee_id=OTHER_CLIENT)], policy
+ )
+ assert anyone.port == "linked"
+ assert anyone.strategy == "everyone_else_links"
+
+ def test_a_rule_out_of_scope_lets_the_next_one_try(self):
+ """Out of scope is not a verdict on the money: it means this rule
+ had nothing to say, and the rest still get their turn."""
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "dollars_only",
+ "enabled": True,
+ "outcome": "suggest",
+ "when": with_scope(currency={"conversion": "reject", "in": ["USD"]}),
+ },
+ {"id": "anything", "enabled": True, "outcome": "link", "when": BASE},
+ ],
+ "on_ambiguity": "suggest",
+ }
+ decision = evaluate(money(), [an_invoice()], policy)
+ assert decision.port == "linked"
+ assert decision.strategy == "anything"
+
+ def test_the_trace_says_which_rules_never_applied(self):
+ """"No rule matched" is useless. "That rule is for dollars and
+ this was reais" is something a person can act on."""
+ rule = with_scope(currency={"conversion": "reject", "in": ["USD"]})
+ decision = evaluate(money(), [an_invoice()], one_rule(rule))
+ assert [n.rejected_by for n in decision.trace] == [Reason.OUT_OF_SCOPE]
+
+ def test_scope_is_judged_once_however_many_promises_are_open(self):
+ """The rule was never consulted, so there is nothing to say about
+ any particular invoice: one note, not one per candidate."""
+ rule = with_scope(accounts={"in": [str(OTHER_ACCOUNT)]})
+ decision = evaluate(
+ money(), [an_invoice(), an_invoice(), an_invoice()], one_rule(rule)
+ )
+ assert len(decision.trace) == 1
+
+
+# ===========================================================================
+# The use cases behind the conditions
+# ===========================================================================
+class TestRealWorldCases:
+ """Whole rules as somebody would actually write them.
+
+ Each of these is a sentence a person said, turned into a document.
+ They exist because a condition that works in isolation and cannot
+ express the request it was built for has not been delivered.
+ """
+
+ def test_large_receipts_get_a_human_and_small_ones_settle_themselves(self):
+ """*"Anything over ten thousand I want to look at myself."*"""
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "large_needs_review",
+ "enabled": True,
+ "outcome": "suggest",
+ "when": with_scope(amount={"match": "exact", "min": "10000"}),
+ },
+ {
+ "id": "the_rest_link",
+ "enabled": True,
+ "outcome": "link",
+ "when": BASE,
+ },
+ ],
+ "on_ambiguity": "suggest",
+ }
+ big = evaluate(
+ money(amount=Decimal("25000.00")),
+ [an_invoice(amount=Decimal("25000.00"))],
+ policy,
+ )
+ assert big.port == "suggested"
+
+ small = evaluate(money(), [an_invoice()], policy)
+ assert small.port == "linked"
+
+ def test_foreign_currency_receipts_are_never_linked_automatically(self):
+ """*"Dollars I always want to check, because of the rate."*"""
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "foreign_needs_review",
+ "enabled": True,
+ "outcome": "suggest",
+ "when": with_scope(
+ currency={"conversion": "allow", "foreign": True}
+ ),
+ },
+ {"id": "home_links", "enabled": True, "outcome": "link", "when": BASE},
+ ],
+ "on_ambiguity": "suggest",
+ }
+ dollars = evaluate(
+ money(currency="USD"),
+ [an_invoice(currency="USD")],
+ policy,
+ base_currency="BRL",
+ )
+ assert dollars.port == "suggested"
+
+ reais = evaluate(money(), [an_invoice()], policy, base_currency="BRL")
+ assert reais.port == "linked"
+
+ def test_one_difficult_client_is_always_reviewed(self):
+ """*"This customer pays in parts and never the same way twice."*"""
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "that_client",
+ "enabled": True,
+ "outcome": "suggest",
+ "when": with_scope(
+ payees={"in": [str(OTHER_CLIENT)]},
+ amount={"match": "tolerance", "percent": "50"},
+ ),
+ },
+ {"id": "everyone_else", "enabled": True, "outcome": "link", "when": BASE},
+ ],
+ "on_ambiguity": "suggest",
+ }
+ decision = evaluate(
+ money(amount=Decimal("2000.00"), payee_id=OTHER_CLIENT),
+ [an_invoice(payee_id=OTHER_CLIENT)],
+ policy,
+ )
+ assert decision.port == "suggested"
+ assert decision.strategy == "that_client"
+
+ def test_a_payments_account_is_automated_and_the_operating_one_is_not(self):
+ """*"The account the gateway pays into can settle itself. The one
+ I move money around in should not."*"""
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "gateway_account",
+ "enabled": True,
+ "outcome": "link",
+ "when": with_scope(accounts={"in": [str(ACCOUNT)]}),
+ }
+ ],
+ "on_ambiguity": "suggest",
+ }
+ assert evaluate(money(), [an_invoice()], policy).port == "linked"
+ assert (
+ evaluate(money(account_id=OTHER_ACCOUNT), [an_invoice()], policy).port
+ == "unmatched"
+ )
+
+ def test_a_reversal_is_never_taken_as_a_payment(self):
+ """*"An estorno is money coming back, not a client paying."* The
+ amount and the client are both right, which is exactly why the
+ text condition has to be able to override them."""
+ rule = with_scope(text={"not_contains": "ESTORNO"})
+ decision = evaluate(
+ money(description="TED ESTORNO PARCIAL"), [an_invoice()], one_rule(rule)
+ )
+ assert decision.port == "unmatched"
+
+ def test_a_named_transfer_from_one_account_within_a_ceiling(self):
+ """Four conditions at once, which is what a real rule looks like
+ once somebody has been burned twice."""
+ rule = with_scope(
+ accounts={"in": [str(ACCOUNT)]},
+ text={"contains": "TED"},
+ amount={"match": "exact", "max": "50000"},
+ currency={"conversion": "reject", "in": ["BRL"]},
+ )
+ decision = evaluate(
+ money(description="TED RECEBIDA CLIENTE ALPHA"),
+ [an_invoice()],
+ one_rule(rule),
+ )
+ assert decision.port == "linked"
+
+
+# ===========================================================================
+# The shipped rules still behave, with the new vocabulary present
+# ===========================================================================
+class TestShippedRulesUnchanged:
+ """The conditions above are additions. Nothing that shipped may have
+ changed meaning because the engine learned new words."""
+
+ def test_the_invoice_rules_carry_no_scope_filters(self):
+ """A shipped rule that quietly limited itself to one account would
+ be a default nobody could explain."""
+ policy = policy_module.default_policy("reconciliation.match_invoice")
+ for strategy in policy["strategies"]:
+ when = strategy["when"]
+ assert "accounts" not in when
+ assert "payees" not in when
+ assert "text" not in when
+ assert "direction" not in when
+ assert "min" not in when.get("amount", {})
+ assert "max" not in when.get("amount", {})
+
+ def test_a_known_client_paying_exactly_still_links(self):
+ policy = policy_module.default_policy("reconciliation.match_invoice")
+ assert evaluate(money(), [an_invoice()], policy).port == "linked"
+
+ def test_the_recurring_rule_still_links_on_the_same_signals(self):
+ policy = policy_module.for_recurring("monthly")
+ charge = Movement(
+ amount=Decimal("89.90"),
+ currency="BRL",
+ direction="debit",
+ when=TODAY + timedelta(days=2),
+ description="NETFLIX ASSINATURA",
+ account_id=ACCOUNT,
+ source="sync",
+ )
+ occurrence = Expectation(
+ kind="recurring",
+ id=uuid.uuid4(),
+ amount=Decimal("89.90"),
+ currency="BRL",
+ direction="debit",
+ when=TODAY,
+ description="NETFLIX ASSINATURA",
+ account_id=ACCOUNT,
+ )
+ assert evaluate(charge, [occurrence], policy).port == "linked"
+
+
+# ===========================================================================
+# Two transactions, one invoice
+# ===========================================================================
+class TestPartPayments:
+ """One invoice settled by several payments.
+
+ The ledger has always allowed it: allocations are many-to-one with an
+ amount, but until this mode existed nothing could ever *propose* the
+ first half. Every other comparison measures against the whole
+ outstanding balance, and half of it is simply not that. So a client
+ paying R$3.000 in two transfers produced two unmatched rows and an
+ invoice that looked untouched.
+ """
+
+ def part_rule(self, outcome: str = "suggest", **extra) -> dict:
+ return one_rule(
+ {
+ "counterparty": "same_payee",
+ "amount": {"match": "partial", "min_ratio": "0.05", **extra},
+ "date": {"before_days": 30, "after_days": 30},
+ },
+ outcome=outcome,
+ )
+
+ def test_half_of_what_is_owed_is_offered(self):
+ decision = evaluate(
+ money(amount=Decimal("1500.00")), [an_invoice()], self.part_rule()
+ )
+ assert decision.port == "suggested"
+ assert decision.amount == Decimal("1500.00")
+
+ def test_what_is_left_over_is_named(self):
+ """So the screen can say "R$1.500 of R$3.000" rather than leaving a
+ reader to do the subtraction."""
+ decision = evaluate(
+ money(amount=Decimal("1200.00")), [an_invoice()], self.part_rule()
+ )
+ assert decision.difference == Decimal("1800.00")
+ assert decision.difference_kind == "part_payment"
+
+ def test_the_whole_amount_is_not_a_part_payment(self):
+ """Strictly less than, so this and an exact match never both fire
+ and a trace never has to explain which one won."""
+ decision = evaluate(money(), [an_invoice()], self.part_rule())
+ assert decision.port == "unmatched"
+
+ def test_more_than_is_owed_is_not_a_part_payment_either(self):
+ decision = evaluate(
+ money(amount=Decimal("5000.00")), [an_invoice()], self.part_rule()
+ )
+ assert decision.port == "unmatched"
+
+ def test_a_token_amount_is_not_offered_as_an_instalment(self):
+ """R$10 against a R$3.000 invoice is noise. Offering it would teach
+ people to stop reading the queue, which costs more than the one
+ match it might have caught."""
+ decision = evaluate(
+ money(amount=Decimal("10.00")), [an_invoice()], self.part_rule()
+ )
+ assert decision.port == "unmatched"
+
+ def test_the_floor_is_a_fraction_so_it_scales(self):
+ """Five per cent means the same thing on a small invoice and a
+ large one, which an absolute floor could not."""
+ small = evaluate(
+ money(amount=Decimal("10.00")),
+ [an_invoice(amount=Decimal("100.00"))],
+ self.part_rule(),
+ )
+ assert small.port == "suggested", "ten per cent of a small invoice is real"
+
+ def test_the_floor_can_be_removed(self):
+ decision = evaluate(
+ money(amount=Decimal("1.00")),
+ [an_invoice()],
+ self.part_rule(min_ratio="0"),
+ )
+ assert decision.port == "suggested"
+
+ def test_a_workspace_may_promote_part_payments_to_linking(self):
+ """For somebody whose clients always pay in parts, confirming each
+ one is the manual work the feature exists to remove."""
+ decision = evaluate(
+ money(amount=Decimal("1500.00")), [an_invoice()], self.part_rule("link")
+ )
+ assert decision.port == "linked"
+
+ def test_the_second_payment_matches_exactly_once_the_first_is_booked(self):
+ """Which is why the shipped default only suggests: after the first
+ half is recorded, the balance is 1500 and the second half is an
+ ordinary exact match. The ambiguity only ever exists at the start."""
+ remaining = an_invoice(amount=Decimal("1500.00"))
+ decision = evaluate(
+ money(amount=Decimal("1500.00")), [remaining], one_rule(BASE)
+ )
+ assert decision.port == "linked"
+ assert decision.amount == Decimal("1500.00")
+
+ def test_a_part_payment_never_claims_more_than_is_owed(self):
+ decision = evaluate(
+ money(amount=Decimal("2999.99")), [an_invoice()], self.part_rule()
+ )
+ assert decision.amount is not None
+ assert decision.amount == Decimal("2999.99")
+ assert decision.amount < Decimal("3000.00")
+
+
+# ===========================================================================
+# Which moment a rule runs at
+# ===========================================================================
+class TestTrigger:
+ """Money arriving, or a document being written.
+
+ Two different questions with different evidence behind them, and until
+ now the answer was hardcoded in whichever function happened to be
+ doing the looking: a restriction nobody could see or change, on a
+ feature whose entire premise is that matching is not a black box.
+ """
+
+ def only_when(self, trigger: str) -> dict:
+ policy = one_rule(BASE)
+ policy["strategies"][0]["trigger"] = trigger
+ return policy
+
+ def test_a_rule_for_arriving_money_sits_out_the_look_back(self):
+ decision = evaluate(
+ money(), [an_invoice()], self.only_when("money_arrives"),
+ trigger="invoice_issued",
+ )
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.WRONG_MOMENT
+
+ def test_a_rule_for_the_look_back_sits_out_arriving_money(self):
+ decision = evaluate(
+ money(), [an_invoice()], self.only_when("invoice_issued"),
+ trigger="money_arrives",
+ )
+ assert decision.port == "unmatched"
+ assert decision.trace[0].rejected_by is Reason.WRONG_MOMENT
+
+ def test_both_runs_at_either_moment(self):
+ policy = self.only_when("both")
+ for moment in ("money_arrives", "invoice_issued"):
+ assert evaluate(money(), [an_invoice()], policy, trigger=moment).port == "linked"
+
+ def test_a_rule_that_says_nothing_runs_when_money_arrives(self):
+ """The common case, and the one a rule written without thinking
+ about this should mean."""
+ policy = one_rule(BASE)
+ assert "trigger" not in policy["strategies"][0]
+ assert evaluate(money(), [an_invoice()], policy).port == "linked"
+ assert (
+ evaluate(money(), [an_invoice()], policy, trigger="invoice_issued").port
+ == "unmatched"
+ )
+
+ def test_the_wrong_moment_is_told_apart_from_a_failed_comparison(self):
+ """"This rule runs at the other moment" and "this rule looked and
+ said no" are different problems with different fixes, so they are
+ different reasons."""
+ decision = evaluate(
+ money(), [an_invoice()], self.only_when("invoice_issued")
+ )
+ assert decision.trace[0].rejected_by is Reason.WRONG_MOMENT
+ assert decision.trace[0].rejected_by is not Reason.OUT_OF_SCOPE
+
+ def test_a_rule_at_the_wrong_moment_lets_the_next_one_try(self):
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "look_back_only",
+ "enabled": True,
+ "outcome": "suggest",
+ "trigger": "invoice_issued",
+ "when": BASE,
+ },
+ {
+ "id": "arrivals",
+ "enabled": True,
+ "outcome": "link",
+ "trigger": "money_arrives",
+ "when": BASE,
+ },
+ ],
+ "on_ambiguity": "suggest",
+ }
+ decision = evaluate(money(), [an_invoice()], policy)
+ assert decision.port == "linked"
+ assert decision.strategy == "arrivals"
+
+
+class TestShippedTriggers:
+ """What the defaults say about the two moments, and why.
+
+ These are product decisions rather than arithmetic, so they are pinned
+ here: a change to any of them changes whose money gets claimed by a
+ document written afterwards.
+ """
+
+ def shipped(self, rule_id: str) -> dict:
+ policy = policy_module.default_policy("reconciliation.match_invoice")
+ return next(s for s in policy["strategies"] if s["id"] == rule_id)
+
+ def test_a_known_client_paying_exactly_is_trusted_at_both_moments(self):
+ """The pay-then-invoice case is ordinary here, and a named client
+ paying their exact amount is as convincing before the nota as
+ after it."""
+ assert self.shipped("same_client_exact")["trigger"] == "both"
+
+ def test_an_unnamed_payer_is_only_trusted_when_a_promise_was_waiting(self):
+ """Backwards, that money already had a life of its own: a refund,
+ a transfer, another job, and claiming it for a document written
+ afterwards is a guess."""
+ assert self.shipped("exact_amount_any_client")["trigger"] == "money_arrives"
+
+ def test_part_payments_are_offered_at_both_moments_and_never_linked(self):
+ rule = self.shipped("same_client_part_payment")
+ assert rule["trigger"] == "both"
+ assert rule["outcome"] == "suggest"
+ assert rule["when"]["amount"]["match"] == "partial"
+
+
+# ===========================================================================
+# One transaction, several invoices
+# ===========================================================================
+class TestSets:
+ """A payment that answers several promises at once.
+
+ The gateway payout, the client clearing three of their own invoices in
+ one transfer, the commercial arrangement that settles a month at a
+ time. The ledger has always been able to record it: allocations are
+ many-to-many with an amount, but a decision that could only name one
+ promise could never propose it.
+
+ The hard part is not the arithmetic, it is **refusing when there is
+ more than one answer**. Three invoices of a thousand and a credit of
+ two thousand admit three equally good readings, and picking one would
+ be inventing certainty exactly where the single-promise path refuses.
+ """
+
+ def set_rule(self, outcome: str = "link", **amount) -> dict:
+ return one_rule(
+ {
+ "counterparty": "same_payee",
+ "amount": {"match": "set", "max_invoices": 6, "percent": "0", **amount},
+ "date": {"before_days": 30, "after_days": 30},
+ },
+ outcome=outcome,
+ )
+
+ def test_a_payment_covering_two_invoices_settles_both(self):
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [an_invoice(amount=Decimal("1000.00")), an_invoice(amount=Decimal("2000.00"))],
+ self.set_rule(),
+ )
+ assert decision.port == "linked"
+ assert len(decision.settlements) == 2
+ assert sum(s.amount for s in decision.settlements) == Decimal("3000.00")
+
+ def test_a_payment_covering_three_invoices_settles_all_three(self):
+ decision = evaluate(
+ money(amount=Decimal("6000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("2000.00")),
+ an_invoice(amount=Decimal("3000.00")),
+ ],
+ self.set_rule(),
+ )
+ assert decision.port == "linked"
+ assert len(decision.settlements) == 3
+
+ def test_each_invoice_is_settled_for_its_own_amount(self):
+ """Not the payment split evenly. The whole point of allocations
+ carrying an amount is that each debt gets what it is owed."""
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [an_invoice(amount=Decimal("1000.00")), an_invoice(amount=Decimal("2000.00"))],
+ self.set_rule(),
+ )
+ assert sorted(s.amount for s in decision.settlements) == [
+ Decimal("1000.00"),
+ Decimal("2000.00"),
+ ]
+
+ def test_two_combinations_that_both_add_up_settle_nothing_automatically(self):
+ """Three invoices of a thousand and a payment of two thousand: any
+ two of them fit. Which two is a question about intent, not
+ arithmetic."""
+ decision = evaluate(
+ money(amount=Decimal("2000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("1000.00")),
+ ],
+ self.set_rule(),
+ )
+ assert decision.port == "suggested"
+ assert any(n.rejected_by is Reason.AMBIGUOUS_SET for n in decision.trace)
+
+ def test_an_ambiguous_set_still_offers_one_reading_to_start_from(self):
+ """A person answering the question needs something concrete in
+ front of them, not an empty prompt."""
+ decision = evaluate(
+ money(amount=Decimal("2000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("1000.00")),
+ ],
+ self.set_rule(),
+ )
+ assert len(decision.settlements) == 2
+
+ def test_a_single_invoice_is_left_to_the_ordinary_rules(self):
+ """A set rule is about combinations. One invoice matching exactly
+ is what the exact rule is for, and having both claim it would make
+ the trace ambiguous about which fired."""
+ decision = evaluate(
+ money(), [an_invoice()], self.set_rule()
+ )
+ assert decision.port == "unmatched"
+
+ def test_smaller_combinations_are_preferred_over_larger_ones(self):
+ """A payment that is exactly one pair should not be reported as
+ also being a trio that happens to sum the same."""
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("2000.00")),
+ an_invoice(amount=Decimal("500.00")),
+ an_invoice(amount=Decimal("2500.00")),
+ ],
+ self.set_rule(),
+ )
+ # Two pairs add up, so it is ambiguous, and the reading offered is
+ # a pair rather than something longer.
+ assert decision.port == "suggested"
+ assert len(decision.settlements) == 2
+
+ def test_a_payment_that_matches_nothing_together_is_left_alone(self):
+ decision = evaluate(
+ money(amount=Decimal("7777.00")),
+ [an_invoice(amount=Decimal("1000.00")), an_invoice(amount=Decimal("2000.00"))],
+ self.set_rule(),
+ )
+ assert decision.port == "unmatched"
+
+ def test_only_this_clients_invoices_are_combined(self):
+ """The counterparty is what keeps the search small and the answer
+ meaningful: adding up strangers' invoices to reach a total is
+ numerology, not reconciliation."""
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("2000.00"), payee_id=OTHER_CLIENT),
+ ],
+ self.set_rule(),
+ )
+ assert decision.port == "unmatched"
+
+ def test_invoices_outside_the_date_window_are_not_combined(self):
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("2000.00"), when=TODAY - timedelta(days=200)),
+ ],
+ self.set_rule(),
+ )
+ assert decision.port == "unmatched"
+
+ def test_invoices_in_another_currency_are_not_combined(self):
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("2000.00"), currency="USD"),
+ ],
+ self.set_rule(),
+ )
+ assert decision.port == "unmatched"
+
+ def test_a_fee_can_be_allowed_for_and_is_named(self):
+ """The gateway case: the payout is the invoices minus the cut. The
+ gap is reported rather than swallowed, so the caller can book it
+ instead of leaving money unexplained."""
+ decision = evaluate(
+ money(amount=Decimal("2940.00")),
+ [an_invoice(amount=Decimal("1000.00")), an_invoice(amount=Decimal("2000.00"))],
+ self.set_rule(percent="2"),
+ )
+ assert decision.port == "linked"
+ assert decision.difference == Decimal("-60.00")
+ assert decision.difference_kind == "set_difference"
+
+ def test_without_a_tolerance_a_fee_stops_the_match(self):
+ """Shipped at zero on purpose. Guessing which fee applies is how a
+ wrong split gets written confidently."""
+ decision = evaluate(
+ money(amount=Decimal("2940.00")),
+ [an_invoice(amount=Decimal("1000.00")), an_invoice(amount=Decimal("2000.00"))],
+ self.set_rule(),
+ )
+ assert decision.port == "unmatched"
+
+ def test_the_number_of_invoices_in_one_answer_is_capped(self):
+ """A cap the rule sets, bounded again by the engine. Somebody who
+ allows two cannot be handed a combination of four."""
+ decision = evaluate(
+ money(amount=Decimal("4000.00")),
+ [an_invoice(amount=Decimal("1000.00")) for _ in range(4)],
+ self.set_rule(max_invoices=2),
+ )
+ assert decision.port == "unmatched"
+
+ def test_too_many_open_invoices_is_refused_out_loud(self):
+ """Searching which of forty invoices add up to a payment is
+ subset-sum, and a sync that hangs is worse than a match that is
+ not made. Refusing silently would leave somebody wondering why
+ their payout never matched."""
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [an_invoice(amount=Decimal("100.00")) for _ in range(40)],
+ self.set_rule(),
+ )
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.TOO_MANY_TO_COMBINE for n in decision.trace)
+
+ def test_a_settled_invoice_is_never_part_of_a_combination(self):
+ decision = evaluate(
+ money(amount=Decimal("3000.00")),
+ [
+ an_invoice(amount=Decimal("1000.00")),
+ an_invoice(amount=Decimal("2000.00")),
+ an_invoice(amount=Decimal("0")),
+ ],
+ self.set_rule(),
+ )
+ assert decision.port == "linked"
+ assert all(s.expectation.amount > Decimal("0") for s in decision.settlements)
+
+ def test_a_set_rule_that_finds_nothing_lets_the_next_rule_try(self):
+ """It is one strategy among several, not a terminal branch."""
+ policy = {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {
+ "id": "sets",
+ "enabled": True,
+ "outcome": "link",
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "set"},
+ "date": {"before_days": 30, "after_days": 30},
+ },
+ },
+ {"id": "singles", "enabled": True, "outcome": "link", "when": BASE},
+ ],
+ "on_ambiguity": "suggest",
+ }
+ decision = evaluate(money(), [an_invoice()], policy)
+ assert decision.port == "linked"
+ assert decision.strategy == "singles"
+
+
+class TestSettlementsAreAlwaysPresent:
+ """Every decision names its settlements, even the ordinary one.
+
+ A caller that has to ask "is this the single kind or the several kind"
+ before it can write anything is a caller that will one day forget to.
+ """
+
+ def test_an_ordinary_match_carries_one_settlement(self):
+ decision = evaluate(money(), [an_invoice()], one_rule(BASE))
+ assert len(decision.settlements) == 1
+ assert decision.settlements[0].expectation is decision.expectation
+ assert decision.settlements[0].amount == decision.amount
+
+ def test_an_unmatched_decision_carries_none(self):
+ decision = evaluate(
+ money(currency="USD"), [an_invoice()], one_rule(BASE)
+ )
+ assert decision.settlements == []
+
+
+# ===========================================================================
+# Bands: link under 2%, ask between 2% and 5%, refuse above
+# ===========================================================================
+class TestTolerangeBands:
+ """*"Under two per cent I want it linked. Between two and five, ask me.
+ Above five, leave it alone."*
+
+ The shape the ordered list was built for: first match wins, so a band
+ is just a looser rule placed after a tighter one. Nothing new is
+ needed, but the rules shipped *below* a person's own still get their
+ turn, and that is where this gets interesting.
+ """
+
+ def banded(self, *, with_shipped_partial: bool = False) -> dict:
+ strategies = [
+ {
+ "id": "under_two",
+ "enabled": True,
+ "outcome": "link",
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "2"},
+ "date": {"before_days": 30, "after_days": 30},
+ },
+ },
+ {
+ "id": "two_to_five",
+ "enabled": True,
+ "outcome": "suggest",
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "5"},
+ "date": {"before_days": 30, "after_days": 30},
+ },
+ },
+ ]
+ if with_shipped_partial:
+ # What actually sits below a workspace's own rules.
+ strategies.append(
+ {
+ "id": "same_client_part_payment",
+ "enabled": True,
+ "outcome": "suggest",
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {
+ "match": "partial",
+ "min_ratio": "0.05",
+ "max_ratio": "0.95",
+ },
+ "date": {"before_days": 30, "after_days": 30},
+ },
+ }
+ )
+ return {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": strategies,
+ "on_ambiguity": "suggest",
+ }
+
+ def test_a_one_percent_difference_links(self):
+ decision = evaluate(
+ money(amount=Decimal("2970.00")), [an_invoice()], self.banded()
+ )
+ assert decision.port == "linked"
+ assert decision.strategy == "under_two"
+
+ def test_a_three_percent_difference_is_asked_about(self):
+ """The band is expressed by *order*, not by a lower bound: the 5%
+ rule only ever sees what the 2% rule did not take."""
+ decision = evaluate(
+ money(amount=Decimal("2910.00")), [an_invoice()], self.banded()
+ )
+ assert decision.port == "suggested"
+ assert decision.strategy == "two_to_five"
+
+ def test_the_bands_hold_on_both_sides_of_the_amount(self):
+ """Tolerance is symmetric, so an overpayment falls in the same
+ band as an underpayment of the same size."""
+ over = evaluate(
+ money(amount=Decimal("3090.00")), [an_invoice()], self.banded()
+ )
+ assert over.port == "suggested" and over.strategy == "two_to_five"
+
+ def test_the_boundary_belongs_to_the_tighter_rule(self):
+ """Exactly two per cent links rather than asks: inclusive, and on
+ the side a person means when they write "under 2%"."""
+ decision = evaluate(
+ money(amount=Decimal("2940.00")), [an_invoice()], self.banded()
+ )
+ assert decision.port == "linked"
+
+ def test_above_the_last_band_nothing_matches(self):
+ """"Reject" is not a verb the engine has. It is what happens when
+ no rule claims the money: same outcome, reached by absence."""
+ decision = evaluate(
+ money(amount=Decimal("2700.00")), [an_invoice()], self.banded()
+ )
+ assert decision.port == "unmatched"
+
+ def test_but_a_shipped_rule_below_still_gets_its_turn(self):
+ """**The non-obvious part.** A 10% difference is not rejected while
+ the shipped part-payment rule sits underneath: to that rule, 90% of
+ a balance is an instalment, and it offers it.
+
+ Which is correct in isolation and wrong for somebody who said
+ "above five per cent, leave it alone", so expressing a real
+ ceiling means narrowing or turning off what lies below it, not
+ only adding rules above.
+ """
+ decision = evaluate(
+ money(amount=Decimal("2700.00")),
+ [an_invoice()],
+ self.banded(with_shipped_partial=True),
+ )
+ assert decision.port == "suggested"
+ assert decision.strategy == "same_client_part_payment"
+
+ def test_a_real_ceiling_means_turning_off_what_lies_underneath(self):
+ """The two rules tile the space exactly, which is why narrowing is
+ not enough.
+
+ A 5% tolerance reaches down to 95% of the balance. The shipped
+ part-payment rule offers from 5% *to* 95% of it. They meet at the
+ same point with no gap, so the region a person means by "above
+ five per cent" is precisely the region part-payment claims.
+
+ There is no threshold to tune: the resolution is the switch that
+ is already on the page. Worth knowing before somebody spends an
+ afternoon adjusting numbers that cannot express what they want.
+ """
+ with_partial = self.banded(with_shipped_partial=True)
+ under_five = evaluate(
+ money(amount=Decimal("2700.00")), [an_invoice()], with_partial
+ )
+ assert under_five.port == "suggested"
+ assert under_five.strategy == "same_client_part_payment"
+
+ with_partial["strategies"][2]["enabled"] = False
+ assert (
+ evaluate(money(amount=Decimal("2700.00")), [an_invoice()], with_partial).port
+ == "unmatched"
+ )
+
+ def test_the_two_rules_meet_exactly_and_leave_no_gap(self):
+ """Pinned because it is arithmetic somebody will otherwise
+ rediscover by being confused: at exactly 95% of the balance both
+ rules would fire, and the tighter one placed first takes it."""
+ at_the_seam = money(amount=Decimal("2850.00"))
+ decision = evaluate(
+ at_the_seam, [an_invoice()], self.banded(with_shipped_partial=True)
+ )
+ assert decision.port == "suggested"
+ assert decision.strategy == "two_to_five", "the band above wins the seam"
+
+
+class TestMoneyInAnotherCurrency:
+ """Never matched, and not a setting somebody can turn off.
+
+ There used to be a `currency.conversion` knob whose `allow` value read
+ as *convert and compare*. It did no such thing: the engine is pure and
+ cannot look up a rate, so all `allow` did was stop comparing
+ currencies. A $3.000 payment became an **exact** match for a €3.000
+ invoice, and settled the euros with the dollars.
+ """
+
+ def test_a_payment_in_another_currency_never_settles_an_invoice(self):
+ decision = evaluate(
+ money(currency="USD"),
+ [an_invoice(currency="EUR")],
+ one_rule(with_scope()),
+ base_currency="USD",
+ )
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.CURRENCY for n in decision.trace)
+
+ def test_the_same_numbers_are_not_the_same_money(self):
+ """The exact-amount rule is the dangerous one: both sides read
+ 3000, and only the currency says they are different money."""
+ decision = evaluate(
+ money(amount=Decimal("3000.00"), currency="USD"),
+ [an_invoice(amount=Decimal("3000.00"), currency="EUR")],
+ one_rule(with_scope()),
+ base_currency="USD",
+ )
+
+ assert decision.settlements == []
+
+ def test_asking_for_conversion_no_longer_turns_the_check_off(self):
+ """The knob is gone from the engine, so a stored rule that still
+ carries it is matched as if it never said anything."""
+ decision = evaluate(
+ money(currency="USD"),
+ [an_invoice(currency="EUR")],
+ one_rule(with_scope(currency={"conversion": "allow"})),
+ base_currency="USD",
+ )
+
+ assert decision.port == "unmatched"
+
+ def test_a_rule_cannot_ask_for_conversion_that_does_not_exist(self):
+ """Refused on the way in rather than quietly ignored, so a policy
+ file carrying it is reported instead of doing something other than
+ what it says."""
+ with pytest.raises(rule_service.RuleError) as caught:
+ rule_service.validate_config(
+ {"when": {"currency": {"conversion": "allow"}}}, whole=False
+ )
+
+ assert caught.value.code == "conversion_unsupported"
diff --git a/backend/tests/test_reconciliation_engine.py b/backend/tests/test_reconciliation_engine.py
new file mode 100644
index 00000000..4a8f453e
--- /dev/null
+++ b/backend/tests/test_reconciliation_engine.py
@@ -0,0 +1,420 @@
+"""What the matcher decides, and why.
+
+Pure tests: no session, no fixtures, no database. That is the point of
+splitting deciding from writing: the half that holds the judgement can
+be asked a hundred questions in a second.
+
+The organising claim under all of it: **an invoice and a recurring
+occurrence are the same kind of promise**, and the engine scores them
+identically. Where they differ is in what the caller does afterwards,
+which is not this module's business and not tested here.
+"""
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+import pytest
+
+from app.services import reconciliation_policy as policy_module
+from app.services.reconciliation_engine import (
+ Expectation,
+ Movement,
+ Reason,
+ evaluate,
+)
+
+TODAY = date(2026, 9, 1)
+CLIENT = uuid.uuid4()
+ACCOUNT = uuid.uuid4()
+
+
+def receivable() -> dict:
+ return policy_module.default_policy("reconciliation.match_invoice")
+
+
+def an_invoice(
+ *,
+ amount: Decimal = Decimal("3000.00"),
+ currency: str = "BRL",
+ direction: str = "credit",
+ when: date = TODAY,
+ description: str = "Consultoria",
+ payee_id: uuid.UUID | None = CLIENT,
+ issued: date | None = None,
+) -> Expectation:
+ """Built field by field rather than from a splatted dict: keyword
+ -splatting a heterogeneous mapping loses every type on the way in,
+ and these fixtures are what the whole file leans on."""
+ return Expectation(
+ kind="invoice",
+ id=uuid.uuid4(),
+ amount=amount,
+ currency=currency,
+ direction=direction,
+ when=when,
+ issued=issued,
+ description=description,
+ payee_id=payee_id,
+ )
+
+
+def an_inflow(
+ *,
+ amount: Decimal = Decimal("3000.00"),
+ currency: str = "BRL",
+ direction: str = "credit",
+ when: date = TODAY,
+ description: str = "PIX RECEBIDO",
+ payee_id: uuid.UUID | None = CLIENT,
+ source: str = "sync",
+) -> Movement:
+ return Movement(
+ amount=amount,
+ currency=currency,
+ direction=direction,
+ when=when,
+ description=description,
+ payee_id=payee_id,
+ source=source,
+ )
+
+
+# ---------------------------------------------------------------------------
+# The tier that should carry the traffic
+# ---------------------------------------------------------------------------
+def test_a_known_client_paying_the_exact_amount_is_linked_not_suggested():
+ """This is a lookup, not a heuristic. The payee is already on the
+ transaction (set by a mapping or a rule), so asking a person to
+ confirm it would be asking them to confirm what they configured."""
+ invoice = an_invoice()
+ decision = evaluate(an_inflow(), [invoice], receivable())
+
+ assert decision.port == "linked"
+ assert decision.strategy == "same_client_exact"
+ assert decision.expectation is invoice
+ assert decision.amount == Decimal("3000.00")
+
+
+def test_money_from_an_unknown_payer_still_links_on_an_exact_amount():
+ """A Pix arrives with no payee attached far more often than not."""
+ decision = evaluate(an_inflow(payee_id=None), [an_invoice()], receivable())
+
+ assert decision.port == "linked"
+ assert decision.strategy == "exact_amount_any_client"
+
+
+def test_a_near_amount_is_offered_rather_than_taken():
+ """Two per cent off is not a rounding difference the product should
+ decide about on its own."""
+ decision = evaluate(
+ an_inflow(amount=Decimal("2950.00"), description="Consultoria"),
+ [an_invoice()],
+ receivable(),
+ )
+
+ assert decision.port == "suggested"
+ assert decision.strategy == "similar_description"
+
+
+# ---------------------------------------------------------------------------
+# Refusing to guess
+# ---------------------------------------------------------------------------
+def test_two_invoices_for_the_same_amount_are_offered_never_chosen():
+ """The signals cannot tell them apart, and picking the higher score
+ would be inventing certainty. The user is asked instead."""
+ twins = [an_invoice(), an_invoice()]
+ decision = evaluate(an_inflow(), twins, receivable())
+
+ assert decision.port == "suggested"
+ assert any(n.rejected_by is Reason.AMBIGUOUS for n in decision.trace)
+
+
+def test_a_different_currency_fails_loudly_instead_of_binding():
+ """Binding across currencies means inventing a rate nobody chose."""
+ decision = evaluate(
+ an_inflow(currency="USD"), [an_invoice(currency="BRL")], receivable()
+ )
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.CURRENCY for n in decision.trace)
+
+
+def test_money_going_the_wrong_way_never_settles_a_receivable():
+ decision = evaluate(an_inflow(direction="debit"), [an_invoice()], receivable())
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.DIRECTION for n in decision.trace)
+
+
+def test_a_generated_placeholder_never_settles_an_invoice():
+ """It is a promise, not the money that keeps it. Settling a debt with
+ another debt is the failure this scope rule exists for."""
+ decision = evaluate(an_inflow(source="recurring"), [an_invoice()], receivable())
+
+ assert decision.port == "unmatched"
+
+
+def test_an_invoice_with_nothing_left_is_not_a_candidate():
+ decision = evaluate(an_inflow(), [an_invoice(amount=Decimal("0"))], receivable())
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.ALREADY_SETTLED for n in decision.trace)
+
+
+def test_paying_the_day_after_issue_is_not_twenty_nine_days_early():
+ """An invoice issued on the 1st and due on the 30th, paid on the 2nd.
+ Measured from the due date that is 28 days early and rejected, which
+ would reject the best-paying client in the workspace. Early is
+ measured from the day the promise was made."""
+ invoice = an_invoice(when=TODAY + timedelta(days=29), issued=TODAY)
+ decision = evaluate(an_inflow(when=TODAY + timedelta(days=1)), [invoice], receivable())
+
+ assert decision.port == "linked"
+
+
+def test_money_from_before_the_invoice_existed_still_has_a_limit():
+ """The look-back is not unbounded: money from two months before the
+ document was written is not this document's."""
+ invoice = an_invoice(when=TODAY + timedelta(days=29), issued=TODAY)
+ decision = evaluate(an_inflow(when=TODAY - timedelta(days=60)), [invoice], receivable())
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.DATE for n in decision.trace)
+
+
+def test_the_date_window_is_asymmetric_on_purpose():
+ """Money arrives after a due date far more often than before it, so
+ the window reaches much further forward than back."""
+ late = evaluate(
+ an_inflow(when=TODAY + timedelta(days=40)), [an_invoice()], receivable()
+ )
+ early = evaluate(
+ an_inflow(when=TODAY - timedelta(days=40)), [an_invoice()], receivable()
+ )
+
+ assert late.port == "linked"
+ assert early.port == "unmatched"
+ assert any(n.rejected_by is Reason.DATE for n in early.trace)
+
+
+# ---------------------------------------------------------------------------
+# Partial settlement
+# ---------------------------------------------------------------------------
+def test_a_second_instalment_matches_what_is_left_not_the_original_total():
+ """An invoice half paid expects the other half. Matching against the
+ full value would miss every second Pix in a market that pays in
+ parts."""
+ half_settled = an_invoice(amount=Decimal("1500.00"))
+ decision = evaluate(an_inflow(amount=Decimal("1500.00")), [half_settled], receivable())
+
+ assert decision.port == "linked"
+ assert decision.amount == Decimal("1500.00")
+
+
+def test_more_money_than_the_invoice_owes_settles_only_what_is_owed():
+ """The remainder is not this module's problem (it is an ordinary
+ transaction), but the allocation must never exceed the debt."""
+ decision = evaluate(
+ an_inflow(amount=Decimal("5000.00")),
+ [an_invoice(amount=Decimal("3000.00"))],
+ {
+ **receivable(),
+ "strategies": [
+ {
+ "id": "loose",
+ "outcome": "link",
+ "when": {
+ "counterparty": "any",
+ "amount": {"match": "tolerance", "percent": "100"},
+ "date": {"before_days": 5, "after_days": 60},
+ },
+ }
+ ],
+ },
+ )
+
+ assert decision.amount == Decimal("3000.00")
+
+
+# ---------------------------------------------------------------------------
+# Withholding: the reason the ratio strategy is a link
+# ---------------------------------------------------------------------------
+def test_an_invoice_paid_net_of_withholding_is_linked_and_the_gap_named():
+ """R$3.000 from a Brazilian company lands as R$2.955 after 1.5% IRRF.
+ Sending that to a confirmation queue sends the best clients to the
+ queue, and the difference is named so the caller can book it rather
+ than leaving R$45 unexplained."""
+ decision = evaluate(
+ an_inflow(amount=Decimal("2955.00")),
+ [an_invoice()],
+ receivable(),
+ withholding_ratios=[Decimal("0.985")],
+ )
+
+ assert decision.port == "linked"
+ assert decision.strategy == "same_client_net_of_withholding"
+ assert decision.difference == Decimal("45.00")
+ assert decision.difference_kind == "withholding_tax"
+
+
+def test_without_ratios_the_withholding_strategy_simply_does_not_fire():
+ """A wrong ratio would auto-link a wrong amount, which is worse than
+ asking. An empty pack means the strategy is inert, not permissive."""
+ decision = evaluate(
+ an_inflow(amount=Decimal("2955.00")), [an_invoice()], receivable()
+ )
+
+ assert decision.port != "linked"
+
+
+# ---------------------------------------------------------------------------
+# The same engine, the other kind of promise
+# ---------------------------------------------------------------------------
+def a_recurring_occurrence(
+ *,
+ amount: Decimal = Decimal("89.90"),
+ when: date = TODAY,
+ description: str = "NETFLIX ASSINATURA",
+ account_id: uuid.UUID = ACCOUNT,
+) -> Expectation:
+ return Expectation(
+ kind="recurring",
+ id=uuid.uuid4(),
+ amount=amount,
+ currency="BRL",
+ direction="debit",
+ when=when,
+ description=description,
+ account_id=account_id,
+ )
+
+
+def test_a_recurring_bill_is_matched_by_the_same_engine():
+ """A workspace that never issues an invoice still has promises: the
+ rent leaving on the 5th is a receivable seen from the other side."""
+ charge = Movement(
+ amount=Decimal("89.90"), currency="BRL", direction="debit",
+ when=TODAY + timedelta(days=2), description="NETFLIX ASSINATURA",
+ account_id=ACCOUNT, source="sync",
+ )
+ decision = evaluate(
+ charge, [a_recurring_occurrence()], policy_module.for_recurring("monthly")
+ )
+
+ assert decision.port == "linked"
+ assert decision.strategy == "same_account_exact"
+ assert decision.expectation is not None
+ assert decision.expectation.kind == "recurring"
+
+
+def test_a_recurring_bill_paid_from_another_account_is_not_a_match():
+ """Unlike an invoice, a recurring bill is anchored: the account is
+ part of what identifies it."""
+ charge = Movement(
+ amount=Decimal("89.90"), currency="BRL", direction="debit", when=TODAY,
+ description="NETFLIX.COM", account_id=uuid.uuid4(), source="sync",
+ )
+ decision = evaluate(
+ charge, [a_recurring_occurrence()], policy_module.for_recurring("monthly")
+ )
+
+ assert decision.port == "unmatched"
+
+
+def test_a_weekly_bill_gets_a_narrower_window_so_it_cannot_take_its_neighbour():
+ """Four days out is fine for a monthly bill and wrong for a weekly
+ one, where it reaches into the next occurrence."""
+ charge = Movement(
+ amount=Decimal("89.90"), currency="BRL", direction="debit",
+ when=TODAY + timedelta(days=4), description="NETFLIX ASSINATURA",
+ account_id=ACCOUNT, source="sync",
+ )
+
+ monthly = evaluate(
+ charge, [a_recurring_occurrence()], policy_module.for_recurring("monthly")
+ )
+ weekly = evaluate(
+ charge, [a_recurring_occurrence()], policy_module.for_recurring("weekly")
+ )
+
+ assert monthly.port == "linked"
+ assert weekly.port == "unmatched"
+
+
+def test_an_unrelated_charge_of_the_same_amount_is_refused_on_description():
+ """The amount alone is not enough for a recurring bill: two
+ subscriptions at R$89,90 on one account are ordinary."""
+ charge = Movement(
+ amount=Decimal("89.90"), currency="BRL", direction="debit", when=TODAY,
+ description="POSTO IPIRANGA", account_id=ACCOUNT, source="sync",
+ )
+ decision = evaluate(
+ charge, [a_recurring_occurrence()], policy_module.for_recurring("monthly")
+ )
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.DESCRIPTION for n in decision.trace)
+
+
+# ---------------------------------------------------------------------------
+# The trace
+# ---------------------------------------------------------------------------
+def test_every_candidate_leaves_a_reason_behind():
+ """"No strategy matched" tells a person nothing. "The amount was
+ right and the date was outside the window" tells them what to
+ change."""
+ decision = evaluate(
+ an_inflow(when=TODAY - timedelta(days=90)), [an_invoice()], receivable()
+ )
+
+ assert decision.port == "unmatched"
+ assert decision.trace, "a rejected candidate must still be accounted for"
+ assert all(n.rejected_by is not None for n in decision.trace)
+ # Every strategy that got as far as the date failed on it, which is
+ # the signal a person would need to see.
+ assert Reason.DATE in {n.rejected_by for n in decision.trace}
+
+
+def test_the_winner_carries_its_score():
+ """A caller holding several movements for one promise ranks them by
+ this: the recurring matcher does, and has always taken the better
+ -matching charge rather than refusing both. It is also what a
+ suggestion has to show a person to be worth showing."""
+ charge = Movement(
+ amount=Decimal("89.90"), currency="BRL", direction="debit", when=TODAY,
+ description="NETFLIX ASSINATURA", account_id=ACCOUNT, source="sync",
+ )
+ exact = evaluate(
+ charge, [a_recurring_occurrence()], policy_module.for_recurring("monthly")
+ )
+ partial_words = evaluate(
+ charge,
+ [a_recurring_occurrence(description="NETFLIX ASSINATURA MENSAL")],
+ policy_module.for_recurring("monthly"),
+ )
+
+ assert exact.score == 1.0
+ assert 0.6 <= partial_words.score < 1.0
+
+ # A strategy with no graded signal still reports a usable score rather
+ # than a zero that would sort below every graded match.
+ assert evaluate(an_inflow(), [an_invoice()], receivable()).score == 1.0
+ # And nothing decided scores nothing, so it never sorts above a match.
+ assert evaluate(an_inflow(currency="USD"), [an_invoice()], receivable()).score == 0.0
+
+
+def test_the_winning_strategy_is_named():
+ """What lets the screen answer "why is this linked" with the name of
+ the rule rather than a shrug."""
+ decision = evaluate(an_inflow(), [an_invoice()], receivable())
+
+ assert decision.strategy == "same_client_exact"
+ assert any(
+ n.strategy == "same_client_exact" and n.rejected_by is None
+ for n in decision.trace
+ )
+
+
+def test_an_unknown_node_is_refused_rather_than_silently_empty():
+ with pytest.raises(ValueError, match="Unknown reconciliation node"):
+ policy_module.default_policy("reconciliation.does_not_exist")
diff --git a/backend/tests/test_reconciliation_field_cases.py b/backend/tests/test_reconciliation_field_cases.py
new file mode 100644
index 00000000..74b5e398
--- /dev/null
+++ b/backend/tests/test_reconciliation_field_cases.py
@@ -0,0 +1,459 @@
+"""The situations people actually reconcile, taken from the field.
+
+Not a second grammar test: `test_reconciliation_conditions.py` covers what
+a rule may say. This file takes reconciliation cases that accountants and
+owners describe as their real work, and shows the shipped vocabulary
+either handles each one or does not. Every case names where it came from,
+so a reader can check that it is a real problem rather than one we
+invented to have an answer for.
+
+The cases are deliberately mundane. A matching engine that only shines on
+exotic inputs is of no use to somebody closing a month.
+"""
+import uuid
+from datetime import date, timedelta
+from decimal import Decimal
+
+from app.services.reconciliation_engine import (
+ Expectation,
+ Movement,
+ Reason,
+ evaluate,
+)
+
+TODAY = date(2026, 9, 1)
+CLIENT = uuid.uuid4()
+OTHER_CLIENT = uuid.uuid4()
+ACCOUNT = uuid.uuid4()
+PERSONAL = uuid.uuid4()
+
+
+def invoice(
+ *,
+ amount: str = "1000.00",
+ when: date = TODAY,
+ payee: uuid.UUID | None = CLIENT,
+ currency: str = "BRL",
+ direction: str = "credit",
+) -> Expectation:
+ return Expectation(
+ kind="invoice",
+ id=uuid.uuid4(),
+ amount=Decimal(amount),
+ currency=currency,
+ direction=direction,
+ when=when,
+ description="Consultoria",
+ payee_id=payee,
+ issued=when - timedelta(days=30),
+ )
+
+
+def money(
+ *,
+ amount: str = "1000.00",
+ when: date = TODAY,
+ payee: uuid.UUID | None = CLIENT,
+ description: str = "PIX RECEBIDO",
+ counterparty: str | None = None,
+ account: uuid.UUID | None = ACCOUNT,
+ currency: str = "BRL",
+ direction: str = "credit",
+) -> Movement:
+ return Movement(
+ amount=Decimal(amount),
+ currency=currency,
+ direction=direction,
+ when=when,
+ description=description,
+ counterparty=counterparty,
+ payee_id=payee,
+ account_id=account,
+ source="sync",
+ )
+
+
+def rule(when: dict, outcome: str = "link") -> dict:
+ """A policy holding the one rule under test."""
+ return {
+ "version": 1,
+ "node": "test",
+ "scope": {"movement": "any", "ignore_transaction_sources": []},
+ "strategies": [
+ {"id": "under_test", "enabled": True, "outcome": outcome, "when": when}
+ ],
+ "on_ambiguity": "suggest",
+ }
+
+
+WINDOW = {"before_days": 10, "after_days": 60}
+
+
+# ---------------------------------------------------------------------------
+# One payment, several promises
+# ---------------------------------------------------------------------------
+def test_one_deposit_settles_five_invoices():
+ """The case every reconciliation vendor leads with: a retailer sends
+ one transfer covering five invoices, the books hold five receivables,
+ the bank holds one line.
+ """
+ invoices = [invoice(amount=a) for a in ("2000", "3200", "1800", "4000", "1400")]
+ total = sum(Decimal(str(i.amount)) for i in invoices)
+ assert total == Decimal("12400")
+
+ decision = evaluate(
+ money(amount="12400.00"),
+ invoices,
+ rule({
+ "counterparty": "same_payee",
+ "amount": {"match": "set", "max_invoices": 6, "percent": "0"},
+ "date": WINDOW,
+ }),
+ )
+
+ assert decision.port == "linked"
+ assert len(decision.settlements) == 5
+ assert sum(s.amount for s in decision.settlements) == Decimal("12400")
+
+
+def test_a_gateway_payout_arrives_net_of_its_cut():
+ """The retail case Brazilian accountants describe as the hard one: the
+ acquirer deposits the day's sales minus its fee, so the deposit never
+ equals the sum of the invoices it pays.
+ """
+ invoices = [invoice(amount="1000.00"), invoice(amount="1000.00")]
+ # 3.5% of 2.000 kept by the acquirer.
+ decision = evaluate(
+ money(amount="1930.00", description="REPASSE ADQUIRENTE"),
+ invoices,
+ rule({
+ "counterparty": "same_payee",
+ "amount": {"match": "set", "max_invoices": 6, "percent": "4"},
+ "date": WINDOW,
+ }),
+ )
+
+ assert decision.port == "linked"
+ assert len(decision.settlements) == 2
+
+
+# ---------------------------------------------------------------------------
+# Several payments, one promise
+# ---------------------------------------------------------------------------
+def test_a_client_paying_in_two_transfers():
+ """Decoding messy partial payments is named as the recurring forum
+ complaint. The first half has to be proposable, and every mode that
+ compares against the whole balance cannot propose it.
+ """
+ decision = evaluate(
+ money(amount="400.00"),
+ [invoice(amount="1000.00")],
+ rule(
+ {
+ "counterparty": "same_payee",
+ "amount": {"match": "partial", "min_ratio": "0.05", "max_ratio": "0.95"},
+ "date": WINDOW,
+ },
+ outcome="suggest",
+ ),
+ )
+
+ assert decision.port == "suggested"
+ assert decision.settlements[0].amount == Decimal("400.00")
+
+
+def test_the_remainder_matches_what_is_left_not_the_original_total():
+ """After the first 400, the invoice expects 600, not 1.000. An engine
+ comparing against the original total would miss every second
+ instalment."""
+ decision = evaluate(
+ money(amount="600.00"),
+ [invoice(amount="600.00")], # what is still outstanding
+ rule({
+ "counterparty": "same_payee",
+ "amount": {"match": "exact"},
+ "date": WINDOW,
+ }),
+ )
+
+ assert decision.port == "linked"
+ assert decision.settlements[0].amount == Decimal("600.00")
+
+
+def test_a_token_amount_is_not_offered_as_an_instalment():
+ """Ten reais against a thousand-real invoice is noise. Offering it
+ would teach people to ignore the queue, which costs more than the
+ match is worth."""
+ decision = evaluate(
+ money(amount="10.00"),
+ [invoice(amount="1000.00")],
+ rule(
+ {
+ "counterparty": "same_payee",
+ "amount": {"match": "partial", "min_ratio": "0.05"},
+ "date": WINDOW,
+ },
+ outcome="suggest",
+ ),
+ )
+
+ assert decision.port == "unmatched"
+
+
+# ---------------------------------------------------------------------------
+# The money is not the number on the document
+# ---------------------------------------------------------------------------
+def test_a_late_boleto_paid_with_interest_and_penalty():
+ """The ordinary Brazilian case, and the one a symmetric tolerance has
+ to get right: the client pays *more* than the invoice because the
+ boleto carried juros and multa.
+
+ The invoice closes at its own value and the surplus stays on the
+ transaction, which is where interest income belongs. Settling 1.023
+ against a 1.000 invoice would invent revenue on the receivable.
+ """
+ decision = evaluate(
+ money(amount="1023.40", when=TODAY + timedelta(days=12)),
+ [invoice(amount="1000.00")],
+ rule({
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "5"},
+ "date": WINDOW,
+ }),
+ )
+
+ assert decision.port == "linked"
+ assert decision.settlements[0].amount == Decimal("1000.00"), (
+ "the invoice closes at its value; the extra 23,40 is interest income"
+ )
+
+
+def test_an_early_payment_discount():
+ """The mirror case: paid before the due date, so the client took the
+ agreed discount and sent less."""
+ decision = evaluate(
+ money(amount="980.00", when=TODAY - timedelta(days=5)),
+ [invoice(amount="1000.00")],
+ rule({
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "3"},
+ "date": WINDOW,
+ }),
+ )
+
+ assert decision.port == "linked"
+
+
+def test_a_receivables_advance_arrives_smaller_and_sooner():
+ """Antecipação de recebíveis: the acquirer pays early and keeps a
+ financing fee, so the money is both lighter and earlier than the
+ document says.
+ """
+ decision = evaluate(
+ money(amount="1955.00", when=TODAY - timedelta(days=25), description="ANTECIP"),
+ [invoice(amount="2000.00", when=TODAY)],
+ rule(
+ {
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "3"},
+ "date": {"before_days": 30, "after_days": 5},
+ },
+ outcome="suggest",
+ ),
+ )
+
+ assert decision.port == "suggested"
+
+
+# ---------------------------------------------------------------------------
+# Timing, text and scope
+# ---------------------------------------------------------------------------
+def test_a_deposit_in_transit_still_matches():
+ """Settlement delay is the classic reconciling item: the money left
+ the client days before it reached the account.
+ """
+ decision = evaluate(
+ money(amount="1000.00", when=TODAY + timedelta(days=45)),
+ [invoice(amount="1000.00")],
+ rule({"counterparty": "same_payee", "amount": {"match": "exact"}, "date": WINDOW}),
+ )
+
+ assert decision.port == "linked"
+
+
+def test_a_rule_written_against_the_statement_text():
+ """The commonest rule people write anywhere: the payout is recognised
+ by the words the bank prints, not by its amount.
+ """
+ conditions = {
+ "amount": {"match": "exact"},
+ "date": WINDOW,
+ "text": {"contains": "REPASSE ADQUIRENTE"},
+ }
+
+ assert evaluate(
+ money(amount="1000.00", description="REPASSE ADQUIRENTE 8812"),
+ [invoice(amount="1000.00")],
+ rule(conditions),
+ ).port == "linked"
+
+ assert evaluate(
+ money(amount="1000.00", description="TED RECEBIDA"),
+ [invoice(amount="1000.00")],
+ rule(conditions),
+ ).port == "unmatched"
+
+
+def test_text_that_must_not_appear_keeps_a_reversal_out():
+ """The other half of the same condition, and the one that prevents a
+ refund from closing the invoice it refunded."""
+ decision = evaluate(
+ money(amount="1000.00", description="ESTORNO PIX CONSULTORIA"),
+ [invoice(amount="1000.00")],
+ rule({
+ "amount": {"match": "exact"},
+ "date": WINDOW,
+ "text": {"not_contains": "ESTORNO"},
+ }),
+ )
+
+ assert decision.port == "unmatched"
+
+
+def test_a_ceiling_sends_the_big_ones_to_a_person():
+ """The single most requested guardrail in the rule tools: small
+ payments settle themselves, large ones get looked at.
+ """
+ conditions = {
+ "counterparty": "same_payee",
+ "amount": {"match": "exact", "max": "10000"},
+ "date": WINDOW,
+ }
+
+ assert evaluate(
+ money(amount="9000.00"), [invoice(amount="9000.00")], rule(conditions)
+ ).port == "linked"
+
+ big = evaluate(
+ money(amount="50000.00"), [invoice(amount="50000.00")], rule(conditions)
+ )
+ assert big.port == "unmatched"
+ assert any(n.rejected_by is Reason.OUT_OF_SCOPE for n in big.trace)
+
+
+def test_the_personal_account_is_left_out_of_it():
+ """Mixing the personal and the company account is named as the thing
+ that makes reconciliation impossible. A rule can be told which
+ accounts are the company's.
+ """
+ conditions = {
+ "counterparty": "same_payee",
+ "amount": {"match": "exact"},
+ "date": WINDOW,
+ "accounts": {"in": [str(ACCOUNT)]},
+ }
+
+ assert evaluate(
+ money(amount="1000.00", account=ACCOUNT),
+ [invoice(amount="1000.00")],
+ rule(conditions),
+ ).port == "linked"
+
+ assert evaluate(
+ money(amount="1000.00", account=PERSONAL),
+ [invoice(amount="1000.00")],
+ rule(conditions),
+ ).port == "unmatched"
+
+
+# ---------------------------------------------------------------------------
+# Money that must never settle anything
+# ---------------------------------------------------------------------------
+def test_a_second_payment_of_the_same_boleto_finds_nothing_left():
+ """Paying the same boleto twice is common enough that every Brazilian
+ processor documents the refund path. What matters here is that the
+ duplicate does not settle a second invoice by accident: the first one
+ is closed, and nothing else is owed.
+ """
+ settled = invoice(amount="0.00") # nothing outstanding after the first payment
+ decision = evaluate(
+ money(amount="1000.00"),
+ [settled],
+ rule({"counterparty": "same_payee", "amount": {"match": "exact"}, "date": WINDOW}),
+ )
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.ALREADY_SETTLED for n in decision.trace)
+
+
+def test_a_refund_leaving_the_account_never_settles_a_receivable():
+ """A chargeback or estorno is money going the other way. It reverses a
+ settlement rather than making one.
+ """
+ decision = evaluate(
+ money(amount="1000.00", direction="debit", description="ESTORNO"),
+ [invoice(amount="1000.00")],
+ rule({"amount": {"match": "exact"}, "date": WINDOW}),
+ )
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.DIRECTION for n in decision.trace)
+
+
+def test_another_clients_money_never_closes_this_clients_invoice():
+ decision = evaluate(
+ money(amount="1000.00", payee=OTHER_CLIENT),
+ [invoice(amount="1000.00", payee=CLIENT)],
+ rule({"counterparty": "same_payee", "amount": {"match": "exact"}, "date": WINDOW}),
+ )
+
+ assert decision.port == "unmatched"
+ assert any(n.rejected_by is Reason.COUNTERPARTY for n in decision.trace)
+
+
+# ---------------------------------------------------------------------------
+# What the vocabulary could not say, until it could
+# ---------------------------------------------------------------------------
+def test_a_rule_can_read_the_name_the_bank_printed():
+ """A Pix description is generic ("PIX RECEBIDO"); the payer's name is
+ a separate field on the statement. A rule that can only read the
+ description cannot say "the transfers that come from this company",
+ which is the identifying fact on the most common inflow in Brazil.
+ """
+ decision = evaluate(
+ money(amount="1000.00", description="PIX RECEBIDO", counterparty="ALPHA LTDA"),
+ [invoice(amount="1000.00", payee=None)],
+ rule({
+ "amount": {"match": "exact"},
+ "date": WINDOW,
+ "text": {"contains": "ALPHA"},
+ }),
+ )
+
+ assert decision.port == "linked"
+
+
+def test_one_rule_can_name_several_gateways():
+ """Somebody receiving through three acquirers wants one rule that says
+ "a payout from any of them", not three rules that differ by a word.
+ Letting a rule match on any of its conditions is standard in the rule
+ tools; this is the same need at the level of one field.
+ """
+ conditions = {
+ "amount": {"match": "exact"},
+ "date": WINDOW,
+ "text": {"contains": ["REPASSE", "LIQUIDACAO", "SETTLEMENT"]},
+ }
+
+ for printed in ("REPASSE 8812", "LIQUIDACAO DIARIA", "SETTLEMENT 0042"):
+ assert evaluate(
+ money(amount="1000.00", description=printed),
+ [invoice(amount="1000.00", payee=None)],
+ rule(conditions),
+ ).port == "linked", printed
+
+ assert evaluate(
+ money(amount="1000.00", description="TED RECEBIDA"),
+ [invoice(amount="1000.00", payee=None)],
+ rule(conditions),
+ ).port == "unmatched"
diff --git a/backend/tests/test_reconciliation_rules.py b/backend/tests/test_reconciliation_rules.py
new file mode 100644
index 00000000..8feeb13a
--- /dev/null
+++ b/backend/tests/test_reconciliation_rules.py
@@ -0,0 +1,2957 @@
+"""Rules a workspace can see and change, and what changing them does.
+
+The claim under all of it: **matching is not a black box.** Every number
+the engine consults is visible, editable, and reversible, and an untouched
+rule keeps improving with the product rather than freezing on the day the
+workspace was created.
+"""
+import uuid
+from datetime import date, timedelta
+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.account import Account
+from app.models.payee import Payee
+from app.models.reconciliation import ReconciliationRule, ReconciliationSuggestion
+from app.models.transaction import Transaction
+from app.services import (
+ reconciliation_policy,
+ reconciliation_rule_service as rules,
+ reconciliation_service,
+)
+
+TODAY = date.today()
+INVOICE_NODE = reconciliation_policy.MATCH_INVOICE["node"]
+RECURRING_NODE = reconciliation_policy.MATCH_RECURRING["node"]
+
+
+@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 personal_ws(session: AsyncSession, test_user):
+ """The user's personal workspace, resolved by kind.
+
+ Not the shared `test_workspace` fixture: that one takes the first row
+ with no ORDER BY, so once these tests create a business workspace it
+ can return either. Which workspace is which is the whole subject of
+ the gate test.
+ """
+ from sqlalchemy import select
+
+ from app.models.workspace import Workspace, WorkspaceMember
+
+ result = await session.execute(
+ select(Workspace)
+ .join(WorkspaceMember, WorkspaceMember.workspace_id == Workspace.id)
+ .where(WorkspaceMember.user_id == test_user.id, Workspace.kind == "personal")
+ .order_by(Workspace.created_at.asc())
+ .limit(1)
+ )
+ return result.scalar_one()
+
+
+@pytest_asyncio.fixture
+async def biz_headers(auth_headers, business_ws) -> dict:
+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}
+
+
+@pytest_asyncio.fixture
+async def account(session: AsyncSession, business_ws, test_user) -> Account:
+ acc = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Conta PJ",
+ type="checking",
+ currency="USD",
+ balance=Decimal("0"),
+ )
+ session.add(acc)
+ await session.commit()
+ return acc
+
+
+@pytest_asyncio.fixture
+async def client_payee(session: AsyncSession, business_ws, test_user) -> Payee:
+ payee = Payee(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Alpha Tecnologia",
+ source="manual",
+ )
+ session.add(payee)
+ await session.commit()
+ return payee
+
+
+async def a_payment(
+ client: AsyncClient, headers: dict, account: Account, payee: Payee,
+ *, amount: str = "3000.00", when: date | None = None,
+) -> dict:
+ resp = await client.post(
+ "/api/transactions",
+ headers=headers,
+ json={
+ "description": "PIX RECEBIDO ALPHA",
+ "amount": amount,
+ "currency": "USD",
+ "date": str(when or TODAY),
+ "type": "credit",
+ "account_id": str(account.id),
+ "payee_id": str(payee.id),
+ },
+ )
+ assert resp.status_code in (200, 201), resp.text
+ return resp.json()
+
+
+async def an_invoice(
+ client: AsyncClient, headers: dict, payee: Payee, *, total: str = "3000.00"
+) -> dict:
+ resp = await client.post(
+ "/api/invoices",
+ headers=headers,
+ json={"total": total, "due_date": str(TODAY), "payee_id": str(payee.id)},
+ )
+ assert resp.status_code == 201, resp.text
+ return resp.json()
+
+
+def find(nodes: list[dict], node: str, rule_id: str) -> dict:
+ for entry in nodes:
+ if entry["node"] == node:
+ for rule in entry["rules"]:
+ if rule["id"] == rule_id:
+ return rule
+ raise AssertionError(f"{rule_id} not found in {node}")
+
+
+# ---------------------------------------------------------------------------
+# What the page shows
+# ---------------------------------------------------------------------------
+async def test_the_shipped_rules_are_visible_without_anyone_creating_them(
+ client: AsyncClient, biz_headers
+):
+ """Nothing was written to the database, and yet the rules are there.
+
+ That is the design: the defaults ship with the image, so a workspace
+ created a year ago sees the rules we ship today rather than the ones
+ that existed the day it was made."""
+ resp = await client.get("/api/reconciliation/rules", headers=biz_headers)
+ assert resp.status_code == 200, resp.text
+ nodes = resp.json()
+
+ assert {n["node"] for n in nodes} == {INVOICE_NODE, RECURRING_NODE}
+ exact = find(nodes, INVOICE_NODE, "same_client_exact")
+ assert exact["enabled"] is True
+ assert exact["outcome"] == "link"
+ assert exact["customised"] is False
+ assert exact["when"]["amount"]["match"] == "exact"
+
+
+async def test_a_personal_workspace_gets_its_own_set_and_not_the_other(
+ client: AsyncClient, auth_headers, personal_ws
+):
+ """The gate is per set, because the two sets are different modules.
+
+ A workspace with recurring bills and no invoicing has real rules here:
+ whether the charge that arrived is the bill it expected. Gating the
+ whole router on invoicing hid that from exactly the people the
+ recurring matcher was written for.
+ """
+ personal = {**auth_headers, "X-Workspace-Id": str(personal_ws.id)}
+
+ listing = await client.get("/api/reconciliation/rules", headers=personal)
+ assert listing.status_code == 200, listing.text
+ assert {n["node"] for n in listing.json()} == {RECURRING_NODE}
+
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{RECURRING_NODE}/same_account_exact",
+ headers=personal,
+ json={"enabled": False},
+ )
+ assert resp.status_code == 200, resp.text
+
+
+async def test_a_personal_workspace_cannot_touch_the_invoice_set(
+ client: AsyncClient, auth_headers, personal_ws
+):
+ """Every route addressed at it, not a sample: one ungated route is the
+ whole hole. 404 rather than 403, matching the invoice routes, because
+ a workspace without the module should not learn the feature is there
+ by being told it may not use it.
+ """
+ personal = {**auth_headers, "X-Workspace-Id": str(personal_ws.id)}
+ routes = [
+ ("post", "/api/reconciliation/rules", {"node": INVOICE_NODE, "name": "x",
+ "outcome": "link",
+ "when": {"amount": {"match": "exact"}}}),
+ ("patch", f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ {"enabled": False}),
+ ("delete", f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact", None),
+ ("post", f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact/reset", None),
+ ("put", f"/api/reconciliation/rules/{INVOICE_NODE}/order", {"order": ["x"]}),
+ ]
+ for method, url, body in routes:
+ call = getattr(client, method)
+ resp = await call(url, headers=personal, **({"json": body} if body else {}))
+ assert resp.status_code == 404, f"{method.upper()} {url} -> {resp.status_code}"
+
+
+async def test_a_file_carrying_a_set_this_workspace_lacks_is_skipped(
+ client: AsyncClient, auth_headers, personal_ws, biz_headers
+):
+ """Importing it would store rules the author can neither see nor
+ undo."""
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+ assert INVOICE_NODE in {n["node"] for n in file["nodes"]}
+
+ personal = {**auth_headers, "X-Workspace-Id": str(personal_ws.id)}
+ resp = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=personal,
+ json={"payload": file, "overwrite": True},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["skipped"] > 0
+
+ listing = (
+ await client.get("/api/reconciliation/rules", headers=personal)
+ ).json()
+ assert {n["node"] for n in listing} == {RECURRING_NODE}
+
+
+async def test_a_business_workspace_still_reaches_all_of_it(
+ client: AsyncClient, biz_headers
+):
+ """The other half of the gate, so a mistake in it fails loudly rather
+ than by everybody quietly losing the feature."""
+ assert (
+ await client.get("/api/reconciliation/rules", headers=biz_headers)
+ ).status_code == 200
+ assert (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).status_code == 200
+
+
+async def test_the_recurring_rules_are_offered_and_editable(
+ client: AsyncClient, biz_headers
+):
+ """They were taken off the page for a while, described as bookkeeping
+ about rows we generate ourselves. That description belongs to the
+ placeholder set, not this one: this decides whether the charge that
+ arrived is the bill you told us to expect, which is a judgement about
+ your money and the personal-workspace counterpart of matching an
+ invoice."""
+ listing = (
+ await client.get("/api/reconciliation/rules", headers=biz_headers)
+ ).json()
+ assert RECURRING_NODE in {n["node"] for n in listing}
+
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{RECURRING_NODE}/same_account_exact",
+ headers=biz_headers,
+ json={"when": {"date": {"before_days": 8, "after_days": 8}}},
+ )
+ assert resp.status_code == 200, resp.text
+
+ rule = find(
+ (await client.get("/api/reconciliation/rules", headers=biz_headers)).json(),
+ RECURRING_NODE,
+ "same_account_exact",
+ )
+ assert rule["when"]["date"] == {"before_days": 8, "after_days": 8}
+
+
+async def test_the_placeholder_set_is_still_nobody_business(
+ client: AsyncClient, biz_headers
+):
+ """That one decides whether an arriving charge is the row we wrote
+ from a schedule. Its only visible effect is a line appearing twice, so
+ it is not a lever to offer."""
+ listing = (
+ await client.get("/api/reconciliation/rules", headers=biz_headers)
+ ).json()
+ assert "reconciliation.match_placeholder" not in {n["node"] for n in listing}
+
+ resp = await client.patch(
+ "/api/reconciliation/rules/reconciliation.match_placeholder/"
+ "placeholder_same_account_exact",
+ headers=biz_headers,
+ json={"enabled": False},
+ )
+ assert resp.status_code == 404
+
+
+async def test_the_recurring_rules_keep_running_even_though_nobody_sees_them(
+ session: AsyncSession, business_ws
+):
+ """Taking a set off the page is not the same as switching it off. The
+ charge that pays a bill we generated still has to be recognised, or
+ the row appears twice."""
+ policy = await rules.resolve(
+ session, uuid.UUID(business_ws["id"]), RECURRING_NODE
+ )
+ assert [s["id"] for s in policy["strategies"]] == ["same_account_exact"]
+ assert policy["strategies"][0]["enabled"] is True
+
+
+async def test_the_placeholder_rules_are_not_offered(client: AsyncClient, biz_headers):
+ """It decides whether an arriving charge is a row we generated
+ ourselves: bookkeeping about our own duplicates, not a judgement
+ about whose money this is. A lever whose only effect is duplicate rows
+ does not belong on a page."""
+ resp = await client.get("/api/reconciliation/rules", headers=biz_headers)
+ assert "reconciliation.match_placeholder" not in {n["node"] for n in resp.json()}
+
+
+# ---------------------------------------------------------------------------
+# Changing them
+# ---------------------------------------------------------------------------
+async def test_turning_a_rule_off_stops_it_matching(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The whole point of the page: a number in the engine is now a
+ decision somebody can reverse."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"enabled": False},
+ )
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ json={"enabled": False},
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert detail.json()["allocations"] == []
+
+
+async def test_a_change_stores_only_what_changed(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """A workspace that widened the window must keep every other signal
+ live, including improvements shipped later. Storing the whole rule
+ would freeze the parts nobody touched."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"date": {"before_days": 30, "after_days": 90}}},
+ )
+
+ result = await session.execute(
+ select(ReconciliationRule).where(
+ ReconciliationRule.workspace_id == uuid.UUID(business_ws["id"])
+ )
+ )
+ row = result.scalar_one()
+ assert row.config == {"when": {"date": {"before_days": 30, "after_days": 90}}}
+ assert "amount" not in row.config["when"], "an untouched signal is not stored"
+
+ # And the composed rule still carries the shipped parts.
+ resp = await client.get("/api/reconciliation/rules", headers=biz_headers)
+ rule = find(resp.json(), INVOICE_NODE, "same_client_exact")
+ assert rule["when"]["date"] == {"before_days": 30, "after_days": 90}
+ assert rule["when"]["amount"]["match"] == "exact"
+ assert rule["customised"] is True
+
+
+async def test_resetting_returns_to_what_ships_today(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """Not to what shipped when it was changed. Deleting the row puts the
+ rule back under the live default, which is the entire reason the
+ defaults are not copied in."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"enabled": False},
+ )
+ resp = await client.post(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact/reset",
+ headers=biz_headers,
+ )
+ assert resp.status_code == 204
+
+ rule = find(
+ (await client.get("/api/reconciliation/rules", headers=biz_headers)).json(),
+ INVOICE_NODE,
+ "same_client_exact",
+ )
+ assert rule["enabled"] is True
+ assert rule["customised"] is False
+
+
+async def test_a_rule_that_would_match_everything_is_refused(
+ client: AsyncClient, biz_headers
+):
+ """Configurable is not the same as unguarded. A tolerance above 100%
+ matches every amount there is, and a rule that links everything to
+ everything is not a preference: it is a broken ledger."""
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "tolerance", "percent": "400"}}},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "tolerance_too_wide"
+
+
+async def test_a_shape_the_engine_cannot_read_is_refused_on_the_way_in(
+ client: AsyncClient, biz_headers
+):
+ """A rule naming a match mode the engine never heard of would not fail
+ loudly: it would quietly stop matching, and nobody would find out
+ until a month of payments had gone unreconciled."""
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "vibes"}}},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "bad_amount"
+
+
+# ---------------------------------------------------------------------------
+# Rules a workspace writes itself
+# ---------------------------------------------------------------------------
+async def test_a_workspace_can_write_its_own_rule_and_run_it_first(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """Order matters (the first rule that matches wins), so a rule
+ somebody wrote is worth little if it can only ever run last."""
+ resp = await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={
+ "node": INVOICE_NODE,
+ "name": "Cliente conhecido, valor aproximado",
+ "outcome": "suggest",
+ "position": 0,
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "5"},
+ "date": {"before_days": 10, "after_days": 60},
+ },
+ },
+ )
+ assert resp.status_code == 201, resp.text
+ created = resp.json()
+ assert created["origin"] == "custom"
+ assert created["id"].startswith("custom_")
+
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ invoice_rules = next(n for n in nodes if n["node"] == INVOICE_NODE)["rules"]
+ assert invoice_rules[0]["id"] == created["id"], "it runs before the shipped ones"
+
+
+async def test_a_custom_rule_cannot_claim_the_name_of_one_of_ours(
+ client: AsyncClient, biz_headers
+):
+ """Ids share a namespace, so a workspace rule is prefixed. Otherwise a
+ rule could shadow a shipped one and the override table would stop
+ meaning what it says."""
+ resp = await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={
+ "node": INVOICE_NODE,
+ "name": "same_client_exact",
+ "outcome": "link",
+ "when": {"amount": {"match": "exact"}},
+ },
+ )
+ assert resp.status_code == 201
+ assert resp.json()["id"] == "custom_same_client_exact"
+
+
+async def test_a_custom_rule_without_conditions_is_refused(
+ client: AsyncClient, biz_headers
+):
+ resp = await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={"node": INVOICE_NODE, "name": "Tudo", "outcome": "link", "when": {}},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "conditions_required"
+
+
+# ---------------------------------------------------------------------------
+# The doubtful space
+# ---------------------------------------------------------------------------
+async def test_demoting_a_rule_sends_the_match_to_the_queue_instead(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The switch that would be a lie if the queue did not exist: a rule
+ set to suggest has to produce something a person can see."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": "suggest"},
+ )
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert detail.json()["allocations"] == [], "nothing was linked"
+
+ queue = await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ assert queue.status_code == 200, queue.text
+ assert len(queue.json()) == 1
+ offered = queue.json()[0]
+ assert offered["expectation_kind"] == "invoice"
+ assert offered["expectation_id"] == invoice["id"]
+ assert offered["strategy_id"] == "same_client_exact"
+
+
+async def test_the_queue_shows_the_evidence_and_not_a_single_number(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """"We are 78% sure" is not something anyone can check. "The amount is
+ exact and the payer is known" is."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": "suggest"},
+ )
+ await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ offered = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()[0]
+
+ assert offered["scores"]["amount_exact"] is True
+ assert offered["scores"]["same_counterparty"] is True
+ assert offered["scores"]["days_apart"] == 0
+ assert offered["transaction"]["description"] == "PIX RECEBIDO ALPHA"
+ # And the promise is named the way every invoice screen names it, so
+ # the queue and the document the client is holding agree.
+ assert offered["expectation_label"] == "1"
+
+
+async def test_accepting_settles_the_invoice_and_records_which_rule_agreed(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": "suggest"},
+ )
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+ offered = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()[0]
+
+ resp = await client.post(
+ f"/api/reconciliation/suggestions/{offered['id']}/accept", headers=biz_headers
+ )
+ assert resp.status_code == 200, resp.text
+
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert len(detail["allocations"]) == 1
+ # The person agreed with a specific rule, and that is worth keeping.
+ assert detail["allocations"][0]["method"] == "same_client_exact"
+ # `state`, not `status`: the stored column records what a person
+ # decided, and paid is a fact about money that is derived per read.
+ assert detail["state"] == "paid"
+
+
+async def test_a_declined_suggestion_never_comes_back(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee,
+ business_ws,
+):
+ """The single most important behaviour in the queue. Re-asking
+ yesterday's question is how people stop reading it, and then they
+ stop reading the good ones too."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": "suggest"},
+ )
+ await an_invoice(client, biz_headers, client_payee)
+ payment = await a_payment(client, biz_headers, account, client_payee)
+ offered = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()[0]
+
+ await client.post(
+ f"/api/reconciliation/suggestions/{offered['id']}/decline", headers=biz_headers
+ )
+
+ # Run matching over the same money again, exactly as the next sync
+ # would. Nothing new may appear.
+ from app.services import reconciliation_service
+
+ result = await session.execute(
+ select(Transaction).where(Transaction.id == uuid.UUID(payment["id"]))
+ )
+ transaction = result.scalar_one()
+ await reconciliation_service.match_incoming(
+ session, uuid.UUID(business_ws["id"]), [transaction]
+ )
+ await session.commit()
+
+ assert (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json() == []
+
+ result = await session.execute(select(ReconciliationSuggestion))
+ rows = result.unique().scalars().all()
+ assert len(rows) == 1 and rows[0].status == "declined", "the refusal is remembered"
+
+
+async def test_a_question_nobody_answered_expires_on_its_own(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """A queue that only grows is an archive. Expired rather than deleted,
+ so the forgotten question is not immediately re-asked."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": "suggest"},
+ )
+ await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ result = await session.execute(select(ReconciliationSuggestion))
+ row = result.unique().scalar_one()
+ row.created_at = row.created_at - timedelta(days=90)
+ await session.commit()
+
+ assert (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json() == []
+
+ await session.refresh(row)
+ assert row.status == "expired"
+
+
+async def test_a_viewer_can_read_the_rules_but_not_change_them(
+ client: AsyncClient, viewer_auth_headers, biz_headers, business_ws
+):
+ """Matching decides what a ledger says, so who may change it is not a
+ cosmetic question."""
+ headers = {**viewer_auth_headers, "X-Workspace-Id": business_ws["id"]}
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=headers,
+ json={"enabled": False},
+ )
+ assert resp.status_code in (403, 404)
+
+
+# ---------------------------------------------------------------------------
+# Composition, below HTTP
+# ---------------------------------------------------------------------------
+def test_a_sparse_patch_leaves_everything_it_did_not_mention():
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=uuid.uuid4(),
+ node=INVOICE_NODE,
+ strategy_id="same_client_exact",
+ origin="default",
+ config={"enabled": False},
+ )
+ composed = rules.compose(INVOICE_NODE, [row])
+ changed = next(s for s in composed["strategies"] if s["id"] == "same_client_exact")
+
+ assert changed["enabled"] is False
+ assert changed["outcome"] == "link", "untouched, so still what we ship"
+ assert changed["when"]["amount"]["match"] == "exact"
+
+
+def test_the_shipped_document_is_never_mutated_by_composing():
+ """`compose` runs on every match. One caller editing the module-level
+ default would change matching for every workspace in the process."""
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=uuid.uuid4(),
+ node=INVOICE_NODE,
+ strategy_id="same_client_exact",
+ origin="default",
+ config={"enabled": False},
+ )
+ rules.compose(INVOICE_NODE, [row])
+
+ shipped = reconciliation_policy.MATCH_INVOICE["strategies"][0]
+ assert shipped["id"] == "same_client_exact"
+ assert shipped["enabled"] is True
+
+
+def test_narrowing_for_a_weekly_bill_only_ever_tightens():
+ """Somebody who widened the monthly window said something reasonable
+ about how late their bills post. Letting that reach into next week's
+ occurrence is not a preference they expressed."""
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=uuid.uuid4(),
+ node=RECURRING_NODE,
+ strategy_id="same_account_exact",
+ origin="default",
+ config={"when": {"date": {"before_days": 10, "after_days": 10}}},
+ )
+ composed = rules.compose(RECURRING_NODE, [row])
+ monthly = rules.narrow_for_frequency(composed, "monthly")
+ weekly = rules.narrow_for_frequency(composed, "weekly")
+
+ assert monthly["strategies"][0]["when"]["date"] == {
+ "before_days": 10,
+ "after_days": 10,
+ }
+ assert weekly["strategies"][0]["when"]["date"] == {
+ "before_days": 2,
+ "after_days": 2,
+ }
+
+
+def test_a_tighter_choice_survives_the_narrowing():
+ """It clamps, it does not overwrite: somebody who asked for one day
+ keeps one day, not the two a weekly bill would allow."""
+ row = ReconciliationRule(
+ id=uuid.uuid4(),
+ workspace_id=uuid.uuid4(),
+ node=RECURRING_NODE,
+ strategy_id="same_account_exact",
+ origin="default",
+ config={"when": {"date": {"before_days": 1, "after_days": 1}}},
+ )
+ weekly = rules.narrow_for_frequency(
+ rules.compose(RECURRING_NODE, [row]), "weekly"
+ )
+ assert weekly["strategies"][0]["when"]["date"] == {
+ "before_days": 1,
+ "after_days": 1,
+ }
+
+
+# ---------------------------------------------------------------------------
+# What a rule may say, and what it may not
+# ---------------------------------------------------------------------------
+class TestConditionValidation:
+ """Writes are checked on the way in, never on the way out.
+
+ A malformed rule discovered during a sync would stop matching
+ silently, and the person who broke it would be nowhere near a screen
+ by then. So every shape the engine can read is accepted here, every
+ shape it cannot is refused with a code the UI can translate, and the
+ stored document is the cleaned version rather than whatever arrived.
+ """
+
+ def check(self, when: dict, *, whole: bool = False) -> dict:
+ return rules.validate_config(
+ {"outcome": "link", "when": when}, whole=whole
+ )["when"]
+
+ def refused(self, when: dict) -> str:
+ with pytest.raises(rules.RuleError) as caught:
+ rules.validate_config({"outcome": "link", "when": when}, whole=False)
+ return caught.value.code
+
+ # -- accounts ----------------------------------------------------------
+ def test_accounts_are_stored_as_canonical_ids(self):
+ account = uuid.uuid4()
+ assert self.check({"accounts": {"in": [str(account).upper()]}}) == {
+ "accounts": {"in": [str(account)]}
+ }
+
+ def test_a_bare_list_of_accounts_is_accepted(self):
+ """The screen sends `{in: [...]}`; a script may reasonably send the
+ list itself. Both mean the same thing."""
+ account = uuid.uuid4()
+ assert self.check({"accounts": [str(account)]}) == {
+ "accounts": {"in": [str(account)]}
+ }
+
+ def test_something_that_is_not_an_account_is_refused(self):
+ assert self.refused({"accounts": {"in": ["the checking one"]}}) == "bad_accounts"
+
+ def test_an_empty_account_list_is_refused_rather_than_ignored(self):
+ """An empty list reads as "no accounts", which would silently
+ disable the rule. Leaving the condition out is how you say "any"."""
+ assert self.refused({"accounts": {"in": []}}) == "bad_accounts"
+
+ # -- payees ------------------------------------------------------------
+ def test_payees_are_validated_like_accounts(self):
+ payee = uuid.uuid4()
+ assert self.check({"payees": {"in": [str(payee)]}}) == {
+ "payees": {"in": [str(payee)]}
+ }
+ assert self.refused({"payees": {"in": ["Alpha"]}}) == "bad_payees"
+
+ # -- direction ---------------------------------------------------------
+ @pytest.mark.parametrize("value", ["any", "credit", "debit"])
+ def test_the_three_directions_are_accepted(self, value):
+ assert self.check({"direction": value}) == {"direction": value}
+
+ def test_a_direction_that_is_neither_in_nor_out_is_refused(self):
+ assert self.refused({"direction": "sideways"}) == "bad_direction"
+
+ # -- currency ----------------------------------------------------------
+ def test_currency_codes_are_normalised_to_upper_case(self):
+ assert self.check({"currency": {"in": ["usd", "eur"]}}) == {
+ "currency": {"conversion": "reject", "in": ["USD", "EUR"]}
+ }
+
+ def test_something_that_is_not_a_currency_code_is_refused(self):
+ assert self.refused({"currency": {"in": ["dollars"]}}) == "bad_currency_list"
+
+ def test_foreign_is_kept_only_when_asked_for(self):
+ assert "foreign" not in self.check({"currency": {"foreign": False}})["currency"]
+ assert self.check({"currency": {"foreign": True}})["currency"]["foreign"] is True
+
+ def test_conversion_still_defaults_to_refusing(self):
+ """Binding across currencies means inventing a rate nobody chose,
+ so silence has to mean no."""
+ assert self.check({"currency": {"in": ["USD"]}})["currency"]["conversion"] == "reject"
+
+ def test_an_unknown_conversion_mode_is_refused(self):
+ assert self.refused({"currency": {"conversion": "guess"}}) == "bad_currency"
+
+ # -- amount ------------------------------------------------------------
+ def test_a_band_is_stored_alongside_the_comparison(self):
+ assert self.check(
+ {"amount": {"match": "exact", "min": "100", "max": "10000"}}
+ ) == {"amount": {"match": "exact", "min": "100", "max": "10000"}}
+
+ def test_an_empty_bound_is_dropped_rather_than_stored_as_zero(self):
+ """A cleared field means "no limit". Storing it as zero would turn
+ an erased ceiling into a floor that blocks nothing but reads as a
+ rule somebody wrote."""
+ assert self.check({"amount": {"match": "exact", "min": "", "max": None}}) == {
+ "amount": {"match": "exact"}
+ }
+
+ def test_a_negative_limit_is_refused(self):
+ assert (
+ self.refused({"amount": {"match": "exact", "min": "-5"}})
+ == "bad_amount_bound"
+ )
+
+ def test_a_band_that_can_never_match_is_refused(self):
+ """Above 10000 and below 100 is not a narrow rule, it is a rule
+ that will never fire, and it would look fine on the screen."""
+ assert (
+ self.refused({"amount": {"match": "exact", "min": "10000", "max": "100"}})
+ == "impossible_amount_band"
+ )
+
+ def test_a_tolerance_over_a_hundred_percent_is_still_refused(self):
+ assert (
+ self.refused({"amount": {"match": "tolerance", "percent": "150"}})
+ == "tolerance_too_wide"
+ )
+
+ def test_the_withholding_ratios_stay_out_of_a_workspaces_hands(self):
+ """A wrong rate would auto-link a wrong amount. The rates come from
+ the jurisdiction pack, and anything sent here is discarded."""
+ checked = self.check(
+ {"amount": {"match": "ratio", "ratios": ["0.5"], "epsilon": "0.02"}}
+ )
+ assert checked["amount"]["ratios"] == "@jurisdiction.withholding_ratios"
+
+ # -- text --------------------------------------------------------------
+ def test_text_conditions_are_trimmed(self):
+ assert self.check({"text": {"contains": " PIX "}}) == {
+ "text": {"contains": "PIX"}
+ }
+
+ def test_both_sides_of_a_text_condition_can_be_set(self):
+ assert self.check({"text": {"contains": "PIX", "not_contains": "ESTORNO"}}) == {
+ "text": {"contains": "PIX", "not_contains": "ESTORNO"}
+ }
+
+ def test_an_empty_text_condition_is_refused(self):
+ assert self.refused({"text": {"contains": ""}}) == "bad_text"
+
+ def test_an_essay_is_refused(self):
+ assert self.refused({"text": {"contains": "x" * 200}}) == "bad_text"
+
+ # -- shape -------------------------------------------------------------
+ def test_an_unknown_signal_is_dropped_rather_than_stored(self):
+ """Storing a key the engine cannot read would produce a rule that
+ looks stricter on screen than it is in fact."""
+ assert "vibes" not in self.check({"vibes": "good", "direction": "credit"})
+
+ def test_a_window_beyond_a_year_is_refused(self):
+ assert (
+ self.refused({"date": {"before_days": 5, "after_days": 900}})
+ == "window_out_of_range"
+ )
+
+ def test_a_similarity_outside_zero_to_one_is_refused(self):
+ assert (
+ self.refused({"description_similarity": {"min": "5"}})
+ == "similarity_out_of_range"
+ )
+
+ def test_a_workspaces_own_rule_needs_at_least_one_condition(self):
+ with pytest.raises(rules.RuleError) as caught:
+ rules.validate_config({"outcome": "link", "when": {}}, whole=True)
+ assert caught.value.code == "conditions_required"
+
+ def test_a_patch_over_a_shipped_rule_may_touch_a_single_signal(self):
+ """The whole point of a sparse patch: widening one window must not
+ require restating every other condition."""
+ patch = rules.validate_config(
+ {"when": {"date": {"before_days": 20, "after_days": 90}}}, whole=False
+ )
+ assert patch == {"when": {"date": {"before_days": 20, "after_days": 90}}}
+
+
+# ---------------------------------------------------------------------------
+# The conditions, through the API, against a real workspace
+# ---------------------------------------------------------------------------
+async def test_a_rule_limited_to_one_account_leaves_another_alone(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee,
+ test_user, business_ws,
+):
+ """The end-to-end shape of "only automate the account the gateway pays
+ into"."""
+ from app.models.account import Account as AccountModel
+
+ other = AccountModel(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Conta operacional",
+ type="checking",
+ currency="USD",
+ balance=Decimal("0"),
+ )
+ session.add(other)
+ await session.commit()
+
+ for rule_id in ("same_client_exact", "exact_amount_any_client"):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/{rule_id}",
+ headers=biz_headers,
+ json={"when": {"accounts": {"in": [str(account.id)]}}},
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ resp = await client.post(
+ "/api/transactions",
+ headers=biz_headers,
+ json={
+ "description": "PIX RECEBIDO ALPHA",
+ "amount": "3000.00",
+ "currency": "USD",
+ "date": str(TODAY),
+ "type": "credit",
+ "account_id": str(other.id),
+ "payee_id": str(client_payee.id),
+ },
+ )
+ assert resp.status_code in (200, 201), resp.text
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert detail.json()["allocations"] == [], "the rule was not written for that account"
+
+
+async def test_a_ceiling_keeps_a_large_payment_out_of_the_automatic_tier(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """*"Anything over a thousand I want to look at myself."*"""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "exact", "max": "1000"}}},
+ )
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "exact", "max": "1000"}}},
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert detail.json()["allocations"] == []
+
+
+async def test_a_text_condition_keeps_a_reversal_from_settling_an_invoice(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The amount and the client are both right, which is exactly why the
+ statement text has to be able to overrule them."""
+ for rule_id in ("same_client_exact", "exact_amount_any_client"):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/{rule_id}",
+ headers=biz_headers,
+ json={"when": {"text": {"not_contains": "ESTORNO"}}},
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ resp = await client.post(
+ "/api/transactions",
+ headers=biz_headers,
+ json={
+ "description": "TED ESTORNO PARCIAL ALPHA",
+ "amount": "3000.00",
+ "currency": "USD",
+ "date": str(TODAY),
+ "type": "credit",
+ "account_id": str(account.id),
+ "payee_id": str(client_payee.id),
+ },
+ )
+ assert resp.status_code in (200, 201), resp.text
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert detail.json()["allocations"] == []
+
+
+async def test_a_rule_naming_one_client_does_not_touch_another(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee,
+ test_user, business_ws,
+):
+ from app.models.payee import Payee as PayeeModel
+
+ stranger = PayeeModel(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Beta Servicos",
+ source="manual",
+ )
+ session.add(stranger)
+ await session.commit()
+
+ for rule_id in ("same_client_exact", "exact_amount_any_client"):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/{rule_id}",
+ headers=biz_headers,
+ json={"when": {"payees": {"in": [str(stranger.id)]}}},
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert detail.json()["allocations"] == []
+
+
+async def test_a_conditions_effect_is_undone_by_restoring_the_rule(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """Every condition has to be reversible, or the page is a trap rather
+ than a control."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "exact", "max": "10"}}},
+ )
+ await client.post(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact/reset",
+ headers=biz_headers,
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert len(detail.json()["allocations"]) == 1
+
+
+# ---------------------------------------------------------------------------
+# An override stores the disagreement, and nothing else
+# ---------------------------------------------------------------------------
+async def test_a_form_that_sends_the_whole_rule_still_stores_only_the_change(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """A form holds every field whether or not somebody touched it, so the
+ screen sends the whole rule. Storing that verbatim would freeze the
+ signals nobody had an opinion about, and this workspace would stop
+ receiving improvements to them: the exact failure the design exists
+ to avoid. The difference is taken on the server, where no future
+ caller can forget it."""
+ shipped = find(
+ (await client.get("/api/reconciliation/rules", headers=biz_headers)).json(),
+ INVOICE_NODE,
+ "same_client_exact",
+ )
+ whole = {**shipped["when"], "amount": {**shipped["when"]["amount"], "max": "10000"}}
+
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": shipped["outcome"], "when": whole},
+ )
+ assert resp.status_code == 200, resp.text
+
+ result = await session.execute(
+ select(ReconciliationRule).where(
+ ReconciliationRule.workspace_id == uuid.UUID(business_ws["id"])
+ )
+ )
+ row = result.scalar_one()
+ assert row.config == {"when": {"amount": {"max": "10000"}}}, "only the ceiling is ours"
+
+ # And the composed rule still carries everything, so the page reads the
+ # same as it did before.
+ rule = find(
+ (await client.get("/api/reconciliation/rules", headers=biz_headers)).json(),
+ INVOICE_NODE,
+ "same_client_exact",
+ )
+ assert rule["when"]["counterparty"] == "same_payee"
+ assert rule["when"]["date"] == shipped["when"]["date"]
+ assert rule["when"]["amount"]["max"] == "10000"
+ assert rule["customised"] is True
+
+
+async def test_setting_a_value_back_to_ours_stops_being_an_override(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """Typing the shipped number back in is the same act as restoring the
+ rule. Leaving a row that happens to agree today would silently freeze
+ that signal tomorrow."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"date": {"before_days": 30, "after_days": 90}}},
+ )
+ shipped_window = reconciliation_policy.MATCH_INVOICE["strategies"][0]["when"]["date"]
+
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"date": dict(shipped_window)}},
+ )
+
+ result = await session.execute(select(ReconciliationRule))
+ assert result.scalars().all() == [], "nothing left to disagree about"
+
+ rule = find(
+ (await client.get("/api/reconciliation/rules", headers=biz_headers)).json(),
+ INVOICE_NODE,
+ "same_client_exact",
+ )
+ assert rule["customised"] is False
+
+
+async def test_two_separate_edits_accumulate_rather_than_replace(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """Somebody who set a ceiling last week and a text exclusion today has
+ said two things, not one."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "exact", "max": "10000"}}},
+ )
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"text": {"not_contains": "ESTORNO"}}},
+ )
+
+ result = await session.execute(select(ReconciliationRule))
+ row = result.scalar_one()
+ assert row.config == {
+ "when": {
+ "amount": {"max": "10000"},
+ "text": {"not_contains": "ESTORNO"},
+ }
+ }
+
+
+def test_pruning_keeps_only_what_differs():
+ shipped = {
+ "id": "x",
+ "outcome": "link",
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "exact"},
+ "date": {"before_days": 10, "after_days": 60},
+ },
+ }
+ patch = {
+ "outcome": "link",
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "exact", "max": "500"},
+ "date": {"before_days": 10, "after_days": 90},
+ },
+ }
+ assert rules._prune(patch, shipped) == {
+ "when": {"amount": {"max": "500"}, "date": {"after_days": 90}}
+ }
+
+
+def test_pruning_an_identical_rule_leaves_nothing():
+ shipped = {"outcome": "link", "when": {"amount": {"match": "exact"}}}
+ assert rules._prune(dict(shipped), shipped) == {}
+
+
+# ---------------------------------------------------------------------------
+# One invoice, several payments: end to end
+# ---------------------------------------------------------------------------
+async def test_a_client_paying_in_two_transfers_is_reconciled_without_manual_work(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The whole journey, because the parts working in isolation is not
+ the claim: a R$3.000 invoice paid as two R$1.500 transfers ends up
+ settled, with both transactions on it.
+
+ The first half is a suggestion (it genuinely could be an instalment,
+ a different job, or a client paying what they had), and the second is
+ an ordinary exact match, because by then the balance *is* 1500. The
+ ambiguity only ever exists at the start.
+ """
+ invoice = await an_invoice(client, biz_headers, client_payee)
+
+ first = await a_payment(client, biz_headers, account, client_payee, amount="1500.00")
+ assert first["id"]
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ assert len(queue) == 1
+ assert queue[0]["strategy_id"] == "same_client_part_payment"
+ assert Decimal(queue[0]["amount"]) == Decimal("1500.00")
+
+ accepted = await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/accept", headers=biz_headers
+ )
+ assert accepted.status_code == 200, accepted.text
+
+ partly = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert partly["state"] == "partial"
+ assert Decimal(partly["balance"]) == Decimal("1500.00")
+
+ # The second transfer needs nobody: what is outstanding is now exactly
+ # what arrived.
+ await a_payment(client, biz_headers, account, client_payee, amount="1500.00")
+
+ settled = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert settled["state"] == "paid"
+ assert len(settled["allocations"]) == 2
+ assert sum(Decimal(a["amount"]) for a in settled["allocations"]) == Decimal("3000.00")
+ assert {a["method"] for a in settled["allocations"]} == {
+ "same_client_part_payment",
+ "same_client_exact",
+ }
+
+
+async def test_three_payments_can_settle_one_invoice(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """Nothing about the design caps it at two. Each accepted part narrows
+ the balance for the next."""
+ invoice = await an_invoice(client, biz_headers, client_payee)
+
+ for amount in ("1000.00", "1000.00"):
+ await a_payment(client, biz_headers, account, client_payee, amount=amount)
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ assert queue, f"no suggestion for the {amount} transfer"
+ await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/accept",
+ headers=biz_headers,
+ )
+
+ await a_payment(client, biz_headers, account, client_payee, amount="1000.00")
+
+ settled = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert settled["state"] == "paid"
+ assert len(settled["allocations"]) == 3
+
+
+async def test_a_workspace_that_wants_part_payments_linked_can_say_so(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """For somebody whose clients always pay in parts, confirming every
+ instalment is precisely the manual work this feature exists to
+ remove."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_part_payment",
+ headers=biz_headers,
+ json={"outcome": "link"},
+ )
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee, amount="1500.00")
+
+ partly = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert partly["state"] == "partial"
+ assert len(partly["allocations"]) == 1
+ assert (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json() == [], "nothing was left to ask about"
+
+
+async def test_a_token_payment_is_not_offered_as_an_instalment(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee, amount="20.00")
+
+ assert (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json() == []
+
+
+# ---------------------------------------------------------------------------
+# The moment a rule runs at, visible and editable
+# ---------------------------------------------------------------------------
+async def test_every_rule_says_which_moment_it_runs_at(
+ client: AsyncClient, biz_headers
+):
+ """It used to be decided in the matching code, where nobody could see
+ it. A page that claims matching is not a black box cannot keep a rule
+ about *when we even look* out of view."""
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ invoice_rules = next(n for n in nodes if n["node"] == INVOICE_NODE)["rules"]
+
+ assert all("trigger" in rule for rule in invoice_rules)
+ by_id = {rule["id"]: rule["trigger"] for rule in invoice_rules}
+ assert by_id["same_client_exact"] == "both"
+ assert by_id["exact_amount_any_client"] == "money_arrives"
+
+
+async def test_narrowing_a_rule_to_arriving_money_stops_it_looking_back(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The restriction that used to be hardcoded is now a choice, and it
+ works in both directions: a workspace can take it away as well as
+ apply it."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"trigger": "money_arrives"},
+ )
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_part_payment",
+ headers=biz_headers,
+ json={"trigger": "money_arrives"},
+ )
+
+ await a_payment(
+ client, biz_headers, account, client_payee, when=TODAY - timedelta(days=6)
+ )
+ invoice = await an_invoice(client, biz_headers, client_payee)
+
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert detail["allocations"] == [], "no rule was willing to look back"
+
+
+async def test_widening_a_rule_lets_an_unnamed_payer_settle_a_later_invoice(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, test_user
+):
+ """We ship this off, because money that predates a document had a life
+ of its own. Somebody who knows their account only ever receives client
+ payments is entitled to disagree, and now can.
+
+ The payment sits two days before the invoice was written, inside this
+ rule's own three-day early window, so the only thing standing between
+ it and a match is the moment the rule is willing to run at, which is
+ exactly what this test is about."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ json={"trigger": "both"},
+ )
+
+ resp = await client.post(
+ "/api/transactions",
+ headers=biz_headers,
+ json={
+ "description": "TED RECEBIDA",
+ "amount": "3000.00",
+ "currency": "USD",
+ "date": str(TODAY - timedelta(days=2)),
+ "type": "credit",
+ "account_id": str(account.id),
+ },
+ )
+ assert resp.status_code in (200, 201), resp.text
+
+ resp = await client.post(
+ "/api/invoices",
+ headers=biz_headers,
+ json={"total": "3000.00", "due_date": str(TODAY)},
+ )
+ invoice = resp.json()
+
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert len(detail["allocations"]) == 1
+
+
+async def test_a_bad_moment_is_refused(client: AsyncClient, biz_headers):
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"trigger": "whenever"},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "bad_trigger"
+
+
+# ---------------------------------------------------------------------------
+# One transaction, several invoices: end to end
+# ---------------------------------------------------------------------------
+async def test_one_transfer_settles_three_invoices_from_the_same_client(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The commercial arrangement that pays a month at a time: one
+ transfer, three invoices, and nothing for anybody to do."""
+ invoices = [
+ await an_invoice(client, biz_headers, client_payee, total=total)
+ for total in ("1000.00", "2000.00", "3000.00")
+ ]
+ await a_payment(client, biz_headers, account, client_payee, amount="6000.00")
+
+ for invoice, total in zip(invoices, ("1000.00", "2000.00", "3000.00")):
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert detail["state"] == "paid", f"{total} left open"
+ assert len(detail["allocations"]) == 1
+ # Each debt got what it was owed, not the payment split evenly.
+ assert Decimal(detail["allocations"][0]["amount"]) == Decimal(total)
+ assert detail["allocations"][0]["method"] == "same_client_several_invoices"
+
+
+async def test_the_same_transaction_appears_on_every_invoice_it_settled(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """Many-to-many in both directions, which is the claim: one payment
+ row, three allocation rows, all pointing at it."""
+ invoices = [
+ await an_invoice(client, biz_headers, client_payee, total=total)
+ for total in ("1000.00", "2000.00")
+ ]
+ payment = await a_payment(
+ client, biz_headers, account, client_payee, amount="3000.00"
+ )
+
+ for invoice in invoices:
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert detail["allocations"][0]["transaction_id"] == payment["id"]
+
+
+async def test_an_ambiguous_combination_is_asked_about_as_one_question(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """Three invoices of a thousand and a payment of two thousand: any two
+ fit. The queue asks *"does this cover these two?"* once, not twice:
+ two separate questions could be answered inconsistently and leave the
+ payment spread across one debt and short on another."""
+ for _ in range(3):
+ await an_invoice(client, biz_headers, client_payee, total="1000.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="2000.00")
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ assert len(queue) == 1, "one question, not one per invoice"
+ offered = queue[0]
+ assert offered["strategy_id"] == "same_client_several_invoices"
+ assert len(offered["covers"]) == 2
+ assert Decimal(offered["amount"]) == Decimal("2000.00")
+
+
+async def test_accepting_a_combination_settles_all_of_it(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ for _ in range(3):
+ await an_invoice(client, biz_headers, client_payee, total="1000.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="2000.00")
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ resp = await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/accept", headers=biz_headers
+ )
+ assert resp.status_code == 200, resp.text
+
+ paid = [
+ inv
+ for inv in (
+ await client.get("/api/invoices", headers=biz_headers)
+ ).json()
+ if inv["state"] == "paid"
+ ]
+ assert len(paid) == 2, "both halves of the answer were written"
+ assert (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json() == [], "the question is answered and gone"
+
+
+async def test_declining_a_combination_refuses_all_of_it(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee,
+ business_ws,
+):
+ """And every member is remembered as refused, so no part of it comes
+ back on the next sync wearing a different combination."""
+ for _ in range(3):
+ await an_invoice(client, biz_headers, client_payee, total="1000.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="2000.00")
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/decline", headers=biz_headers
+ )
+
+ result = await session.execute(select(ReconciliationSuggestion))
+ rows = result.unique().scalars().all()
+ assert len(rows) == 2
+ assert {row.status for row in rows} == {"declined"}
+ assert len({row.group_id for row in rows}) == 1, "one question, one group"
+
+
+async def test_a_gateway_fee_can_be_allowed_for(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """*"The payout is my invoices minus their cut."* Shipped at zero
+ because guessing which fee applies is how a wrong split gets written
+ confidently, but somebody who knows their gateway's percentage can
+ say so.
+
+ **The payout is matched; it does not close the invoices in full.**
+ Only 2.940 arrived, so only 2.940 is written, and each invoice keeps
+ its share of the 60 that the gateway kept. That is the same answer
+ the single-invoice path already gives an invoice paid net of
+ withholding, and for the same reason: settling all 3.000 would record
+ money nobody received. Booking the 60 as a fee is what closes them,
+ and that is a deduction, not a match."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_several_invoices",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "set", "max_invoices": 6, "percent": "2"}}},
+ )
+ for total in ("1000.00", "2000.00"):
+ await an_invoice(client, biz_headers, client_payee, total=total)
+
+ await a_payment(client, biz_headers, account, client_payee, amount="2940.00")
+
+ invoices = (await client.get("/api/invoices", headers=biz_headers)).json()
+ settled = {
+ inv["total"]: sum(Decimal(a["amount"]) for a in inv["allocations"])
+ for inv in invoices
+ }
+ # Both matched, both short by their own share of the cut: 2% of each.
+ assert settled == {"1000.00": Decimal("980.00"), "2000.00": Decimal("1960.00")}
+ # And the whole payout is spoken for, to the cent. Never more than it.
+ assert sum(settled.values()) == Decimal("2940.00")
+ assert all(inv["state"] == "partial" for inv in invoices)
+
+
+async def test_a_group_never_writes_more_than_the_payment_carried(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The guard `allocate` cannot provide.
+
+ `allocate` checks the invoice's own remaining balance and knows
+ nothing about how much of the transaction the earlier members of the
+ group already spent, so nothing below the engine would catch a set
+ that hands out more money than arrived. Before this, a tolerance wide
+ enough to match wrote every invoice at its full value: 980 arriving
+ against two invoices of 500 wrote 1.000."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_several_invoices",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "set", "max_invoices": 6, "percent": "5"}}},
+ )
+ for total in ("500.00", "500.00"):
+ await an_invoice(client, biz_headers, client_payee, total=total)
+
+ await a_payment(client, biz_headers, account, client_payee, amount="980.00")
+
+ invoices = (await client.get("/api/invoices", headers=biz_headers)).json()
+ written = sum(
+ Decimal(a["amount"]) for inv in invoices for a in inv["allocations"]
+ )
+ assert written == Decimal("980.00")
+
+
+async def test_without_the_tolerance_a_short_payout_settles_nothing(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The shipped behaviour, and the safe one."""
+ for total in ("1000.00", "2000.00"):
+ await an_invoice(client, biz_headers, client_payee, total=total)
+ await a_payment(client, biz_headers, account, client_payee, amount="2940.00")
+
+ paid = [
+ inv
+ for inv in (await client.get("/api/invoices", headers=biz_headers)).json()
+ if inv["state"] == "paid"
+ ]
+ assert paid == []
+
+
+async def test_a_combination_is_written_whole_or_not_at_all(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """If one invoice of a payout refuses, none of them are written. A
+ payment landing against two of three debts and unaccounted for on the
+ rest is a ledger nobody can explain."""
+ first = await an_invoice(client, biz_headers, client_payee, total="1000.00")
+ await an_invoice(client, biz_headers, client_payee, total="2000.00")
+
+ # Voiding one of them makes it refuse allocation while leaving it out
+ # of the candidate list is not possible, so instead the whole set
+ # simply stops matching, which is the same guarantee seen from the
+ # outside: no partial write.
+ await client.post(f"/api/invoices/{first['id']}/void", headers=biz_headers)
+ await a_payment(client, biz_headers, account, client_payee, amount="3000.00")
+
+ detail = (
+ await client.get(f"/api/invoices/{first['id']}", headers=biz_headers)
+ ).json()
+ assert detail["allocations"] == []
+ remaining = (
+ await client.get("/api/invoices", headers=biz_headers)
+ ).json()
+ assert not any(inv["state"] == "paid" for inv in remaining)
+
+
+async def test_a_set_rule_is_visible_and_editable_like_every_other(
+ client: AsyncClient, biz_headers
+):
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ rule = find(nodes, INVOICE_NODE, "same_client_several_invoices")
+ assert rule["outcome"] == "link"
+ assert rule["when"]["amount"]["match"] == "set"
+ assert rule["when"]["amount"]["max_invoices"] == 6
+
+
+async def test_an_impossible_set_size_is_refused(client: AsyncClient, biz_headers):
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_several_invoices",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "set", "max_invoices": 50}}},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "bad_set_size"
+
+
+async def test_a_tolerance_wide_enough_to_match_anything_is_refused(
+ client: AsyncClient, biz_headers
+):
+ """Above twenty per cent almost any group of invoices adds up to
+ almost any payment, and a rule that always matches is not a rule."""
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_several_invoices",
+ headers=biz_headers,
+ json={"when": {"amount": {"match": "set", "percent": "60"}}},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "set_tolerance_too_wide"
+
+
+# ---------------------------------------------------------------------------
+# What matching did
+# ---------------------------------------------------------------------------
+async def test_an_automatic_link_is_recorded_with_the_rule_that_made_it(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """And with no user, which is the distinction a reader reaches for
+ first: was this me, or was this the rules?"""
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert len(events) == 1
+ event = events[0]
+ assert event["action"] == "linked"
+ assert event["expectation_id"] == invoice["id"]
+ assert event["strategy_id"] == "same_client_exact"
+ assert event["user_id"] is None, "the rules did this on their own"
+ assert event["transaction_description"] == "PIX RECEBIDO ALPHA"
+
+
+async def test_undoing_a_link_leaves_a_trace(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The event this table exists for. Unallocating **deletes** the
+ allocation, so without a record a match that was made and then undone
+ is indistinguishable from one that was never made."""
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ allocation_id = detail["allocations"][0]["id"]
+ resp = await client.delete(
+ f"/api/invoices/{invoice['id']}/allocations/{allocation_id}",
+ headers=biz_headers,
+ )
+ assert resp.status_code in (200, 204), resp.text
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert events[0]["action"] == "unlinked"
+ assert events[0]["user_id"] is not None, "a person did this one"
+ assert events[0]["strategy_id"] == "same_client_exact", "what it had been"
+
+ # And the invoice really is open again: the history did not replace
+ # the undoing, it recorded it.
+ after = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert after["allocations"] == []
+
+
+async def test_a_question_and_its_answer_both_land_in_the_stream(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": "suggest"},
+ )
+ await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/accept", headers=biz_headers
+ )
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ actions = [e["action"] for e in events]
+
+ # Two rows, not three. Accepting *is* the link (the allocation is its
+ # consequence, not a second event), and the whole stream is organised
+ # around one line: was this me, or was this the rules? `linked` means
+ # the rules; `accepted` means a person. Writing both would blur it.
+ assert actions == ["accepted", "suggested"], "newest first, one row per act"
+ assert events[0]["user_id"] is not None, "a person accepted"
+
+ # And the invoice really was settled by it.
+ detail = (
+ await client.get("/api/invoices", headers=biz_headers)
+ ).json()
+ assert any(inv["state"] == "paid" for inv in detail)
+
+
+async def test_a_refusal_is_remembered_as_an_event_too(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"outcome": "suggest"},
+ )
+ await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/decline", headers=biz_headers
+ )
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert events[0]["action"] == "declined"
+ assert events[0]["user_id"] is not None
+
+
+async def test_the_history_of_one_invoice_can_be_read_on_its_own(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The second and only other way anybody reads this: everything that
+ ever happened to this promise."""
+ mine = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ other_payee_invoice = await an_invoice(
+ client, biz_headers, client_payee, total="4444.00"
+ )
+ await a_payment(client, biz_headers, account, client_payee, amount="4444.00")
+
+ events = (
+ await client.get(
+ f"/api/reconciliation/history?expectation_id={mine['id']}",
+ headers=biz_headers,
+ )
+ ).json()
+ assert len(events) == 1
+ assert events[0]["expectation_id"] == mine["id"]
+ assert other_payee_invoice["id"] != mine["id"]
+
+
+async def test_nothing_is_written_for_money_that_matched_nothing(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The restraint that keeps the history readable. A sync of three
+ hundred transactions where most match nothing must not produce three
+ hundred rows saying so."""
+ await a_payment(client, biz_headers, account, client_payee, amount="77.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="88.00")
+
+ assert (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json() == []
+
+
+async def test_the_history_stays_inside_its_workspace(
+ client: AsyncClient, auth_headers, biz_headers, session: AsyncSession,
+ account, client_payee,
+):
+ await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ other = await client.post(
+ "/api/workspaces",
+ headers=auth_headers,
+ json={"name": "Outro", "kind": "business", "self_membership": True},
+ )
+ headers = {**auth_headers, "X-Workspace-Id": other.json()["id"]}
+ assert (
+ await client.get("/api/reconciliation/history", headers=headers)
+ ).json() == []
+
+
+async def test_a_grouped_question_is_one_line_in_the_history(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """A payment offered against several invoices is one thing that
+ happened and one thing a person answers. Three rows in the stream
+ would be the same noise the queue collapses, in the one place built
+ for scanning."""
+ for _ in range(3):
+ await an_invoice(client, biz_headers, client_payee, total="1000.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="2000.00")
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert [e["action"] for e in events] == ["suggested"]
+ # And it is worth the whole payment, not one slice of it.
+ assert Decimal(events[0]["amount"]) == Decimal("2000.00")
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/accept", headers=biz_headers
+ )
+
+ after = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert [e["action"] for e in after] == ["accepted", "suggested"]
+ assert Decimal(after[0]["amount"]) == Decimal("2000.00")
+
+
+async def test_declining_a_grouped_question_is_also_one_line(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ for _ in range(3):
+ await an_invoice(client, biz_headers, client_payee, total="1000.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="2000.00")
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/decline", headers=biz_headers
+ )
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert [e["action"] for e in events] == ["declined", "suggested"]
+
+
+async def test_a_payment_settling_several_invoices_records_each_link(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """Links are the exception, and deliberately: each one is a separate
+ write against a separate debt, and the invoice-level history (*what
+ ever happened to this invoice*) has to find its own row."""
+ for total in ("1000.00", "2000.00"):
+ await an_invoice(client, biz_headers, client_payee, total=total)
+ await a_payment(client, biz_headers, account, client_payee, amount="3000.00")
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert [e["action"] for e in events] == ["linked", "linked"]
+ assert sorted(Decimal(e["amount"]) for e in events) == [
+ Decimal("1000.00"),
+ Decimal("2000.00"),
+ ]
+
+
+# ---------------------------------------------------------------------------
+# The withholding gap, and what a rule can and cannot do about it
+# ---------------------------------------------------------------------------
+async def test_a_rule_can_send_a_withheld_payment_to_the_queue_today(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """R$3.000 invoiced, R$2.955 received: 1,5% IRRF withheld by a PJ
+ client. Nothing shipped catches it: the exact rules miss by R$45, the
+ part-payment rule refuses because 98,5% of the balance is a fee and
+ not an instalment, and the tolerance rule that would catch it also
+ demands a matching description, which bank text almost never has.
+
+ But a workspace can write the rule itself, and it works.
+ """
+ resp = await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={
+ "node": INVOICE_NODE,
+ "name": "Cliente conhecido, diferença pequena",
+ "outcome": "suggest",
+ "position": 0,
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "2"},
+ "date": {"before_days": 10, "after_days": 60},
+ },
+ },
+ )
+ assert resp.status_code == 201, resp.text
+
+ await an_invoice(client, biz_headers, client_payee, total="3000.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="2955.00")
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ assert len(queue) == 1, "the withheld payment reached a person"
+ assert queue[0]["scores"]["amount_exact"] is False
+ assert queue[0]["scores"]["amount_expected"] == "3000.00"
+ assert queue[0]["scores"]["amount_moved"] == "2955.00"
+
+
+async def test_but_accepting_it_leaves_the_invoice_short_by_the_withheld_tax(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The half a rule cannot reach, and the reason `invoice_deductions`
+ is still owed.
+
+ Reviewing the payment is solvable with a rule. **Closing the invoice
+ is not.** Accepting allocates what actually arrived, so R$45 stays
+ outstanding: the invoice reads `partial` forever, and the aging
+ report carries R$45 that is never coming, because it was never a
+ debt: the client paid it to the Receita on the seller's behalf.
+
+ Nothing in the ledger can currently say that. `uncollectible` is a
+ whole-invoice decision and the wrong word besides. Until a deduction
+ can be recorded, the honest outcome of this flow is a permanently
+ part-paid invoice.
+ """
+ await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={
+ "node": INVOICE_NODE,
+ "name": "Cliente conhecido, diferença pequena",
+ "outcome": "suggest",
+ "position": 0,
+ "when": {
+ "counterparty": "same_payee",
+ "amount": {"match": "tolerance", "percent": "2"},
+ "date": {"before_days": 10, "after_days": 60},
+ },
+ },
+ )
+ invoice = await an_invoice(client, biz_headers, client_payee, total="3000.00")
+ await a_payment(client, biz_headers, account, client_payee, amount="2955.00")
+
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ accepted = await client.post(
+ f"/api/reconciliation/suggestions/{queue[0]['id']}/accept", headers=biz_headers
+ )
+ assert accepted.status_code == 200, accepted.text
+
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert Decimal(detail["allocations"][0]["amount"]) == Decimal("2955.00")
+ assert Decimal(detail["balance"]) == Decimal("45.00")
+ assert detail["state"] == "partial", "not paid, and it never will be"
+
+
+# ---------------------------------------------------------------------------
+# The order rules are tried in
+# ---------------------------------------------------------------------------
+async def test_the_order_can_be_changed_and_holds(
+ client: AsyncClient, biz_headers
+):
+ """Order is the mechanism, not a preference: the first rule that
+ matches wins, so a band is expressed by what sits above and below."""
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ ids = [r["id"] for r in next(n for n in nodes if n["node"] == INVOICE_NODE)["rules"]]
+
+ reversed_ids = list(reversed(ids))
+ resp = await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": reversed_ids},
+ )
+ assert resp.status_code == 200, resp.text
+ assert [r["id"] for r in resp.json()] == reversed_ids
+
+ again = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ assert [
+ r["id"] for r in next(n for n in again if n["node"] == INVOICE_NODE)["rules"]
+ ] == reversed_ids
+
+
+async def test_reordering_alone_does_not_mark_a_rule_as_changed(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """A row carrying only a position is not a departure from what we
+ ship. Marking it as one would offer to "restore" a rule nobody
+ altered, and would suggest it had stopped inheriting improvements,
+ which it has not."""
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ ids = [r["id"] for r in next(n for n in nodes if n["node"] == INVOICE_NODE)["rules"]]
+ await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": list(reversed(ids))},
+ )
+
+ after = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ rules_now = next(n for n in after if n["node"] == INVOICE_NODE)["rules"]
+ assert all(r["customised"] is False for r in rules_now)
+
+ # Rows exist (they carry the order), but their config is empty, so
+ # every one of them still inherits what we ship.
+ result = await session.execute(
+ select(ReconciliationRule).where(
+ ReconciliationRule.workspace_id == uuid.UUID(business_ws["id"])
+ )
+ )
+ stored = result.scalars().all()
+ assert stored and all(row.config == {} for row in stored)
+
+
+async def test_reordering_changes_which_rule_wins(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The point of it. Moving the part-payment rule above the exact one
+ changes what happens to money, not just what the list looks like."""
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ ids = [r["id"] for r in next(n for n in nodes if n["node"] == INVOICE_NODE)["rules"]]
+
+ # A rule that suggests, moved above every rule that links.
+ moved = ["similar_description"] + [i for i in ids if i != "similar_description"]
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ json={"when": {"description_similarity": {"min": "0"}}},
+ )
+ await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": moved},
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = (
+ await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ ).json()
+ assert detail["allocations"] == [], "the suggesting rule got there first"
+ queue = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ assert queue[0]["strategy_id"] == "similar_description"
+
+
+async def test_an_order_that_leaves_a_rule_out_is_refused(
+ client: AsyncClient, biz_headers
+):
+ """Naming only some rules would leave the rest wherever we happened to
+ ship them: an order that reads correctly today and rearranges itself
+ the day a default is inserted."""
+ resp = await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": ["same_client_exact"]},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "incomplete_order"
+
+
+async def test_a_rule_named_twice_is_refused(client: AsyncClient, biz_headers):
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ ids = [r["id"] for r in next(n for n in nodes if n["node"] == INVOICE_NODE)["rules"]]
+ resp = await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": [ids[0]] + ids},
+ )
+ assert resp.status_code == 400
+ assert resp.json()["detail"]["code"] == "duplicate_rule"
+
+
+async def test_a_workspaces_own_rule_takes_part_in_the_order(
+ client: AsyncClient, biz_headers
+):
+ created = await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={
+ "node": INVOICE_NODE,
+ "name": "Minha regra",
+ "outcome": "suggest",
+ "when": {"amount": {"match": "exact"}},
+ },
+ )
+ mine = created.json()["id"]
+
+ nodes = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ ids = [r["id"] for r in next(n for n in nodes if n["node"] == INVOICE_NODE)["rules"]]
+ assert mine in ids
+
+ resp = await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": [mine] + [i for i in ids if i != mine]},
+ )
+ assert resp.status_code == 200
+ assert resp.json()[0]["id"] == mine
+
+
+# ---------------------------------------------------------------------------
+# Throwing a rule away, including one of ours
+# ---------------------------------------------------------------------------
+def node_of(nodes: list[dict], node: str) -> dict:
+ for entry in nodes:
+ if entry["node"] == node:
+ return entry
+ raise AssertionError(f"{node} not in {[n['node'] for n in nodes]}")
+
+
+def ids_in(nodes: list[dict], node: str) -> list[str]:
+ return [rule["id"] for rule in node_of(nodes, node)["rules"]]
+
+
+async def policy(client: AsyncClient, headers: dict) -> list[dict]:
+ resp = await client.get("/api/reconciliation/rules", headers=headers)
+ assert resp.status_code == 200, resp.text
+ return resp.json()
+
+
+async def test_a_rule_we_ship_can_be_deleted(client: AsyncClient, biz_headers):
+ """Turning one off was the only thing on offer, which reads as us
+ deciding what somebody may be rid of. A matching policy decides what
+ happens to their money."""
+ before = await policy(client, biz_headers)
+ assert "exact_amount_any_client" in ids_in(before, INVOICE_NODE)
+
+ resp = await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ )
+ assert resp.status_code == 204, resp.text
+
+ after = await policy(client, biz_headers)
+ assert "exact_amount_any_client" not in ids_in(after, INVOICE_NODE)
+
+
+async def test_a_deleted_rule_stops_deciding(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The list is not the point; the engine is. A rule that is off the
+ page and still matching would be the worst of both."""
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ )
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ )
+
+ invoice = await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ detail = await client.get(f"/api/invoices/{invoice['id']}", headers=biz_headers)
+ assert detail.json()["allocations"] == []
+
+
+async def test_a_deleted_rule_is_named_so_it_can_come_back(
+ client: AsyncClient, biz_headers
+):
+ """A shipped rule leaves a tombstone rather than a hole, so we still
+ know what was thrown away. Without this the delete is a trap: the row
+ is gone from the page and there is nothing left to click."""
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ )
+
+ listing = await policy(client, biz_headers)
+ assert [item["id"] for item in node_of(listing, INVOICE_NODE)["discarded"]] == [
+ "similar_description"
+ ]
+
+ resp = await client.post(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description/reset",
+ headers=biz_headers,
+ )
+ assert resp.status_code == 204
+
+ back = await policy(client, biz_headers)
+ assert "similar_description" in ids_in(back, INVOICE_NODE)
+ assert node_of(back, INVOICE_NODE)["discarded"] == []
+
+
+async def test_deleting_survives_a_later_edit_of_another_rule(
+ client: AsyncClient, biz_headers
+):
+ """`upsert_override` drops a row that no longer disagrees with us.
+ "I do not want this rule" is a disagreement even when every threshold
+ matches, and the row must not be swept up by that rule."""
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ )
+ # Sets a value, then sets it straight back: the path that deletes a
+ # row it decides is redundant.
+ shipped = next(
+ s
+ for s in reconciliation_policy.default_policy(INVOICE_NODE)["strategies"]
+ if s["id"] == "exact_amount_any_client"
+ )
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ json={"outcome": shipped["outcome"]},
+ )
+
+ after = await policy(client, biz_headers)
+ assert "exact_amount_any_client" not in ids_in(after, INVOICE_NODE)
+
+
+async def test_reordering_does_not_demand_a_rule_that_was_deleted(
+ client: AsyncClient, biz_headers
+):
+ """Reordering names every rule so none is left implicit. A deleted one
+ is not a rule any more, and asking for it would make the list
+ unorderable after any delete."""
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ )
+ remaining = ids_in(await policy(client, biz_headers), INVOICE_NODE)
+
+ resp = await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": list(reversed(remaining))},
+ )
+ assert resp.status_code == 200, resp.text
+ assert ids_in(await policy(client, biz_headers), INVOICE_NODE) == list(
+ reversed(remaining)
+ )
+
+
+async def test_a_workspaces_own_rule_is_deleted_outright(
+ client: AsyncClient, biz_headers, session: AsyncSession, business_ws
+):
+ """It exists nowhere else, so there is nothing to record."""
+ created = await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={
+ "node": INVOICE_NODE,
+ "name": "So do Bradesco",
+ "outcome": "suggest",
+ "when": {"amount": {"match": "exact"}},
+ },
+ )
+ assert created.status_code == 201, created.text
+ rule_id = created.json()["id"]
+
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/{rule_id}", headers=biz_headers
+ )
+
+ assert rule_id not in ids_in(await policy(client, biz_headers), INVOICE_NODE)
+ rows = (
+ await session.execute(
+ select(ReconciliationRule).where(
+ ReconciliationRule.workspace_id == uuid.UUID(business_ws["id"]),
+ ReconciliationRule.strategy_id == rule_id,
+ )
+ )
+ ).scalars().all()
+ assert rows == [], "no tombstone for a rule that was only ever a row"
+
+
+async def test_every_shipped_rule_can_go(client: AsyncClient, biz_headers):
+ """No protected rule, and no rule whose removal breaks the page."""
+ for rule_id in ids_in(await policy(client, biz_headers), INVOICE_NODE):
+ resp = await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/{rule_id}", headers=biz_headers
+ )
+ assert resp.status_code == 204, resp.text
+
+ empty = await policy(client, biz_headers)
+ assert ids_in(empty, INVOICE_NODE) == []
+ assert len(node_of(empty, INVOICE_NODE)["discarded"]) > 0
+
+
+async def test_a_rule_that_does_not_exist_cannot_be_deleted(
+ client: AsyncClient, biz_headers
+):
+ resp = await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/nao_existe", headers=biz_headers
+ )
+ assert resp.status_code == 400
+
+
+# ---------------------------------------------------------------------------
+# Carrying a policy elsewhere
+# ---------------------------------------------------------------------------
+async def test_the_export_carries_the_policy_that_is_actually_running(
+ client: AsyncClient, biz_headers
+):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"date": {"before_days": 3, "after_days": 90}}},
+ )
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ )
+
+ resp = await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["format"] == "securo-reconciliation-rules"
+
+ node = next(n for n in body["nodes"] if n["node"] == INVOICE_NODE)
+ exported = next(r for r in node["rules"] if r["id"] == "same_client_exact")
+ assert exported["when"]["date"] == {"before_days": 3, "after_days": 90}
+ assert "similar_description" in node["discarded"]
+
+
+async def test_an_import_reproduces_the_file_including_what_was_thrown_away(
+ client: AsyncClient, biz_headers
+):
+ """A file that quietly restored six rules the author had deleted would
+ describe a policy nobody chose."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"date": {"before_days": 3, "after_days": 90}}},
+ )
+ await client.delete(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ )
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+
+ # Back to shipped, so the import has something to do.
+ for rule_id in ("same_client_exact", "similar_description"):
+ await client.post(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/{rule_id}/reset",
+ headers=biz_headers,
+ )
+
+ resp = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["skipped"] == 0
+ assert resp.json()["imported"] > 0
+
+ listing = await policy(client, biz_headers)
+ restored = find(listing, INVOICE_NODE, "same_client_exact")
+ assert restored["when"]["date"] == {"before_days": 3, "after_days": 90}
+ assert "similar_description" not in ids_in(listing, INVOICE_NODE)
+
+
+async def test_an_import_keeps_the_order_the_file_describes(
+ client: AsyncClient, biz_headers
+):
+ """Order is the mechanism (the first rule that matches wins), so a
+ file that arrived in a different order would be a different policy."""
+ original = ids_in(await policy(client, biz_headers), INVOICE_NODE)
+ await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": list(reversed(original))},
+ )
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+
+ await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ assert ids_in(await policy(client, biz_headers), INVOICE_NODE) == list(
+ reversed(original)
+ )
+
+
+async def test_a_rule_of_your_own_travels_with_its_name(
+ client: AsyncClient, biz_headers
+):
+ await client.post(
+ "/api/reconciliation/rules",
+ headers=biz_headers,
+ json={
+ "node": INVOICE_NODE,
+ "name": "Repasse da maquininha",
+ "outcome": "suggest",
+ "when": {"amount": {"match": "tolerance", "tolerance": "2"}},
+ },
+ )
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+ node = next(n for n in file["nodes"] if n["node"] == INVOICE_NODE)
+ assert any(r["name"] == "Repasse da maquininha" for r in node["rules"])
+
+ resp = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ assert resp.status_code == 200, resp.text
+ names = [
+ rule["name"]
+ for rule in node_of(await policy(client, biz_headers), INVOICE_NODE)["rules"]
+ ]
+ assert "Repasse da maquininha" in names
+
+
+async def test_an_account_a_rule_names_travels_by_name_not_by_id(
+ client: AsyncClient, biz_headers, account
+):
+ """A UUID means nothing in another database. The names are what
+ survive the trip."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"accounts": {"in": [str(account.id)]}}},
+ )
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+ node = next(n for n in file["nodes"] if n["node"] == INVOICE_NODE)
+ exported = next(r for r in node["rules"] if r["id"] == "same_client_exact")
+ assert exported["when"]["accounts"]["in"] == ["Conta PJ"]
+
+ await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ back = find(await policy(client, biz_headers), INVOICE_NODE, "same_client_exact")
+ assert back["when"]["accounts"]["in"] == [str(account.id)]
+
+
+async def test_a_rule_naming_an_account_we_do_not_have_is_skipped_not_widened(
+ client: AsyncClient, biz_headers, account
+):
+ """A rule that was limited to one account and arrives limited to
+ nobody is a different rule, and a wider one: the dangerous direction
+ when the decision is whether money moves."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"accounts": {"in": [str(account.id)]}}},
+ )
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+ node = next(n for n in file["nodes"] if n["node"] == INVOICE_NODE)
+ rule = next(r for r in node["rules"] if r["id"] == "same_client_exact")
+ rule["when"]["accounts"]["in"] = ["Conta que nao existe aqui"]
+
+ resp = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["skipped"] == 1
+
+ back = find(await policy(client, biz_headers), INVOICE_NODE, "same_client_exact")
+ assert "accounts" not in back["when"], "shipped, not a widened copy of theirs"
+
+
+async def test_an_import_asks_before_replacing_what_is_already_there(
+ client: AsyncClient, biz_headers
+):
+ """Merging two orderings has no correct answer, so an import replaces
+ , which is exactly why it has to ask first."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"enabled": False},
+ )
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+
+ refused = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file},
+ )
+ assert refused.status_code == 409
+
+ accepted = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ assert accepted.status_code == 200
+
+
+async def test_a_file_of_the_wrong_kind_is_refused(client: AsyncClient, biz_headers):
+ """A categorization export dropped in here would otherwise arrive as a
+ file with no rules and look like it worked."""
+ resp = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={
+ "payload": {"format": "securo-categorization-rules", "rules": []},
+ "overwrite": True,
+ },
+ )
+ assert resp.status_code == 400
+
+
+async def test_a_rule_this_version_no_longer_ships_is_skipped(
+ client: AsyncClient, biz_headers
+):
+ """Guessing at what it meant is worse than saying it was skipped."""
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+ node = next(n for n in file["nodes"] if n["node"] == INVOICE_NODE)
+ node["rules"].append(
+ {
+ "id": "regra_de_uma_versao_futura",
+ "origin": "default",
+ "name": None,
+ "enabled": True,
+ "outcome": "link",
+ "trigger": "money_arrives",
+ "when": {"amount": {"match": "exact"}},
+ }
+ )
+
+ resp = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["skipped"] == 1
+ assert "regra_de_uma_versao_futura" not in ids_in(
+ await policy(client, biz_headers), INVOICE_NODE
+ )
+
+
+# ---------------------------------------------------------------------------
+# The words on the statement, end to end
+# ---------------------------------------------------------------------------
+async def test_a_rule_reads_the_name_the_bank_printed_not_only_the_description(
+ client: AsyncClient, biz_headers, session: AsyncSession, account
+):
+ """A Pix description is generic and the payer's name arrives in its own
+ field. Until the engine read that field, a rule could not express "the
+ transfers that come from this company", which is the identifying fact
+ on the most common inflow in Brazil.
+
+ No payee is mapped here on purpose: that is the state a first payment
+ from a new client arrives in, and the whole point is that the rule
+ works before anybody has been mapped to anything.
+ """
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/exact_amount_any_client",
+ headers=biz_headers,
+ json={"when": {"text": {"contains": "ALPHA IND"}}},
+ )
+
+ invoice = await client.post(
+ "/api/invoices",
+ headers=biz_headers,
+ json={"total": "3000.00", "due_date": str(TODAY)},
+ )
+ assert invoice.status_code == 201, invoice.text
+
+ # Built as the bank delivers it rather than through the JSON route:
+ # `Transaction.payee` is written by sync and by import, which is
+ # exactly where a counterparty name comes from. Somebody typing a
+ # transaction by hand writes their own description.
+ tx = Transaction(
+ id=uuid.uuid4(),
+ user_id=account.user_id,
+ workspace_id=account.workspace_id,
+ account_id=account.id,
+ description="PIX RECEBIDO",
+ payee="ALPHA INDUSTRIA LTDA",
+ amount=Decimal("3000.00"),
+ currency="USD",
+ date=TODAY,
+ effective_date=TODAY,
+ type="credit",
+ source="sync",
+ )
+ session.add(tx)
+ await session.commit()
+
+ await reconciliation_service.match_incoming(session, account.workspace_id, [tx])
+ await session.commit()
+
+ detail = await client.get(
+ f"/api/invoices/{invoice.json()['id']}", headers=biz_headers
+ )
+ assert len(detail.json()["allocations"]) == 1, (
+ "the words are in the payee field, not the description"
+ )
+
+
+async def test_one_rule_can_name_several_acquirers(client: AsyncClient, biz_headers):
+ """Somebody receiving through three gateways writes one rule rather
+ than three that differ by a word. Stored as a list, and read back as
+ one."""
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ json={"when": {"text": {"contains": ["REPASSE", "LIQUIDACAO", "SETTLEMENT"]}}},
+ )
+ assert resp.status_code == 200, resp.text
+
+ rule = find(
+ (await client.get("/api/reconciliation/rules", headers=biz_headers)).json(),
+ INVOICE_NODE,
+ "similar_description",
+ )
+ assert rule["when"]["text"]["contains"] == ["REPASSE", "LIQUIDACAO", "SETTLEMENT"]
+
+
+async def test_one_word_is_still_stored_as_one_word(client: AsyncClient, biz_headers):
+ """A rule naming a single word must not start reading as a list, or
+ every rule written before this looks changed."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ json={"when": {"text": {"contains": ["REPASSE"]}}},
+ )
+
+ rule = find(
+ (await client.get("/api/reconciliation/rules", headers=biz_headers)).json(),
+ INVOICE_NODE,
+ "similar_description",
+ )
+ assert rule["when"]["text"]["contains"] == "REPASSE"
+
+
+async def test_a_rule_naming_a_dozen_words_is_refused(client: AsyncClient, biz_headers):
+ """At some length a list stops being a rule somebody can read."""
+ resp = await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/similar_description",
+ headers=biz_headers,
+ json={"when": {"text": {"contains": [f"BANCO {n}" for n in range(15)]}}},
+ )
+ assert resp.status_code == 400
+
+
+async def test_a_question_raised_when_the_invoice_is_written_is_kept(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """The client paid first, the nota followed, and the money only
+ covers part of it: a question, not a link.
+
+ The looking-back pass raises it, and the request has to keep it.
+ Committing only when a link was made discarded every suggestion this
+ moment produced, so a rule set to suggest did its job on one trigger
+ and silently nothing on the other, which is the switch the queue
+ exists to prevent."""
+ await a_payment(client, biz_headers, account, client_payee, amount="1500.00")
+ await an_invoice(client, biz_headers, client_payee, total="3000.00")
+
+ waiting = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+ assert len(waiting) == 1
+ assert waiting[0]["strategy_id"] == "same_client_part_payment"
+
+
+async def test_a_question_already_answered_cannot_be_answered_again(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """Accepting settles the invoice. A decline arriving afterwards used
+ to mark the row dismissed and write a second line of history while
+ the allocation stayed exactly where it was: the queue saying one
+ thing and the ledger another."""
+ await a_payment(client, biz_headers, account, client_payee, amount="1500.00")
+ await an_invoice(client, biz_headers, client_payee, total="3000.00")
+ waiting = (
+ await client.get("/api/reconciliation/suggestions", headers=biz_headers)
+ ).json()
+
+ accepted = await client.post(
+ f"/api/reconciliation/suggestions/{waiting[0]['id']}/accept",
+ headers=biz_headers,
+ )
+ assert accepted.status_code == 200, accepted.text
+
+ refused = await client.post(
+ f"/api/reconciliation/suggestions/{waiting[0]['id']}/decline",
+ headers=biz_headers,
+ )
+ assert refused.status_code == 409
+ assert refused.json()["detail"]["code"] == "already_answered"
+
+ # And the settlement it made is still there.
+ invoices = (await client.get("/api/invoices", headers=biz_headers)).json()
+ assert sum(Decimal(a["amount"]) for a in invoices[0]["allocations"]) == Decimal(
+ "1500.00"
+ )
+
+
+async def test_putting_a_threshold_back_does_not_move_the_rule(
+ client: AsyncClient, biz_headers
+):
+ """Ordering is explicit or it is nothing.
+
+ Reordering writes a position for every rule in the set. Editing one
+ of them back to the shipped value leaves nothing to disagree about,
+ and the row used to be dropped for that reason alone: the rule fell
+ back to its shipped index while its siblings kept the positions the
+ person gave them, and the order rearranged itself."""
+ listing = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ ids = [r["id"] for r in [r for e in listing if e["node"] == INVOICE_NODE for r in e["rules"]]]
+ reversed_ids = list(reversed(ids))
+
+ await client.put(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/order",
+ headers=biz_headers,
+ json={"order": reversed_ids},
+ )
+ # Change a threshold, then put it back to what we ship.
+ for days in (99, 60):
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"when": {"date": {"before_days": 10, "after_days": days}}},
+ )
+
+ after = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ assert [r["id"] for r in [r for e in after if e["node"] == INVOICE_NODE for r in e["rules"]]] == reversed_ids
+
+
+async def test_history_says_what_currency_the_amount_is_in(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee
+):
+ """An amount without its currency is not an amount.
+
+ The row carries a figure and the screen has to render it. Reading a
+ fixed code there told every workspace it had received dollars, so a
+ R$ 1.200,00 settlement came back as $1,200.00: the right number under
+ the wrong sign, which is worse than no number at all."""
+ await an_invoice(client, biz_headers, client_payee)
+ await a_payment(client, biz_headers, account, client_payee)
+
+ events = (
+ await client.get("/api/reconciliation/history", headers=biz_headers)
+ ).json()
+ assert events[0]["currency"] == "USD", "the invoice's own currency"
+
+
+async def test_a_broken_file_leaves_the_rules_it_could_not_replace(
+ client: AsyncClient, biz_headers
+):
+ """Replacing means deleting, so the file has to be readable first.
+
+ An entry the importer cannot make sense of used to be discovered
+ after the delete had already run: the workspace was left with no
+ rules at all and a count of what had been skipped, which says nothing
+ about why. Now the whole file is resolved before anything is removed,
+ and a broken one is refused with its reason while what is here stands."""
+ await client.patch(
+ f"/api/reconciliation/rules/{INVOICE_NODE}/same_client_exact",
+ headers=biz_headers,
+ json={"enabled": False},
+ )
+ file = (
+ await client.get("/api/reconciliation/rules/export", headers=biz_headers)
+ ).json()
+ # A rule that says it links or suggests, and says neither.
+ for node in file["nodes"]:
+ for rule in node["rules"]:
+ rule["outcome"] = "perhaps"
+
+ refused = await client.post(
+ "/api/reconciliation/rules/import",
+ headers=biz_headers,
+ json={"payload": file, "overwrite": True},
+ )
+ assert refused.status_code == 400
+ assert refused.json()["detail"]["code"] == "bad_outcome"
+
+ # And the workspace still has what it had: the rule it turned off is
+ # still off, rather than back on because everything was wiped.
+ after = (await client.get("/api/reconciliation/rules", headers=biz_headers)).json()
+ assert find(after, INVOICE_NODE, "same_client_exact")["enabled"] is False
diff --git a/backend/tests/test_reconciliation_service.py b/backend/tests/test_reconciliation_service.py
new file mode 100644
index 00000000..258d453d
--- /dev/null
+++ b/backend/tests/test_reconciliation_service.py
@@ -0,0 +1,436 @@
+"""Money and promises, brought together against a real database.
+
+The engine's own tests prove what it decides. These prove the half that
+loads candidates and writes the result: including the direction that is
+easy to forget: an invoice issued *after* the money arrived.
+"""
+import uuid
+from datetime import date, timedelta
+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.account import Account
+from app.models.invoice import Invoice, InvoiceAllocation
+from app.models.payee import Payee
+from app.models.transaction import Transaction
+from app.services import invoice_service, reconciliation_service
+
+TODAY = date.today()
+
+
+@pytest_asyncio.fixture
+async def business_ws(client: AsyncClient, auth_headers) -> dict:
+ resp = await client.post(
+ "/api/workspaces",
+ headers=auth_headers,
+ json={"name": "Estudio", "kind": "business", "self_membership": True},
+ )
+ assert resp.status_code == 201, resp.text
+ return resp.json()
+
+
+@pytest_asyncio.fixture
+async def biz_headers(auth_headers, business_ws) -> dict:
+ return {**auth_headers, "X-Workspace-Id": business_ws["id"]}
+
+
+@pytest_asyncio.fixture
+async def account(session: AsyncSession, business_ws, test_user) -> Account:
+ acc = Account(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Conta PJ",
+ type="checking",
+ currency="USD",
+ balance=Decimal("0"),
+ )
+ session.add(acc)
+ await session.commit()
+ return acc
+
+
+@pytest_asyncio.fixture
+async def client_payee(session: AsyncSession, business_ws, test_user) -> Payee:
+ payee = Payee(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=uuid.UUID(business_ws["id"]),
+ name="Alpha Tecnologia",
+ )
+ session.add(payee)
+ await session.commit()
+ return payee
+
+
+async def a_transaction(
+ session: AsyncSession,
+ account: Account,
+ test_user,
+ *,
+ amount: Decimal = Decimal("3000.00"),
+ kind: str = "credit",
+ when: date = TODAY,
+ description: str = "PIX RECEBIDO ALPHA",
+ payee_id: uuid.UUID | None = None,
+ source: str = "sync",
+) -> Transaction:
+ tx = Transaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ workspace_id=account.workspace_id,
+ account_id=account.id,
+ description=description,
+ amount=amount,
+ currency="USD",
+ date=when,
+ type=kind,
+ source=source,
+ payee_id=payee_id,
+ )
+ session.add(tx)
+ await session.commit()
+ return tx
+
+
+async def an_invoice(
+ client: AsyncClient,
+ headers: dict,
+ *,
+ total: str = "3000.00",
+ due: date | None = None,
+ payee_id: uuid.UUID | None = None,
+ direction: str = "receivable",
+ as_draft: bool = False,
+) -> dict:
+ payload: dict = {
+ "total": total,
+ "due_date": str(due or TODAY),
+ "direction": direction,
+ "as_draft": as_draft,
+ }
+ if payee_id:
+ payload["payee_id"] = str(payee_id)
+ resp = await client.post("/api/invoices", headers=headers, json=payload)
+ assert resp.status_code == 201, resp.text
+ return resp.json()
+
+
+async def _load(session: AsyncSession, invoice_id: str) -> Invoice:
+ from sqlalchemy.orm import selectinload
+
+ result = await session.execute(
+ select(Invoice)
+ .where(Invoice.id == uuid.UUID(invoice_id))
+ .options(selectinload(Invoice.allocations), selectinload(Invoice.payee))
+ )
+ return result.unique().scalar_one()
+
+
+# ---------------------------------------------------------------------------
+# Money arriving against an invoice that already exists
+# ---------------------------------------------------------------------------
+async def test_a_clients_payment_settles_their_invoice_without_being_asked(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """The tier that should carry the traffic: the payee is already on the
+ transaction, so this is a lookup rather than a guess."""
+ invoice = await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ tx = await a_transaction(session, account, test_user, payee_id=client_payee.id)
+
+ applied = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [tx]
+ )
+ await session.commit()
+
+ assert len(applied) == 1
+ settled = await _load(session, invoice["id"])
+ assert settled.allocations[0].transaction_id == tx.id
+ assert settled.allocations[0].amount == Decimal("3000.00")
+ # The rule that fired is recorded, not a generic "auto".
+ assert settled.allocations[0].method == "same_client_exact"
+
+
+async def test_one_payment_never_settles_two_invoices(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, test_user
+):
+ """Re-matching money that already carries an allocation is how a
+ ledger starts disagreeing with a bank.
+
+ **One invoice, not two.** Two identical invoices are ambiguous, so a
+ first pass over them links nothing and a second pass has nothing to
+ re-link: the test would pass with the guard removed. One invoice makes
+ the first pass succeed, which is the only state in which the guard
+ has anything to do."""
+ invoice = await an_invoice(client, biz_headers)
+ tx = await a_transaction(session, account, test_user)
+
+ first = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [tx]
+ )
+ await session.commit()
+ again = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [tx]
+ )
+ await session.commit()
+
+ # The first pass takes it; the second finds the money already spoken
+ # for and leaves it alone.
+ assert len(first) == 1 and again == []
+ total = await session.execute(select(InvoiceAllocation))
+ allocations = total.scalars().all()
+ assert len(allocations) == 1
+ assert str(allocations[0].invoice_id) == invoice["id"]
+
+
+async def test_half_the_money_is_not_taken_for_the_whole_invoice(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """R$1.500 against a R$3.000 invoice is not evidence of anything. It
+ could be an instalment, a different job, or a client paying the wrong
+ amount, and the engine has no exact signal to tell those apart, so it
+ takes none of them."""
+ invoice = await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ half = await a_transaction(
+ session, account, test_user, amount=Decimal("1500.00"), payee_id=client_payee.id
+ )
+
+ applied = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [half]
+ )
+ await session.commit()
+
+ assert applied == []
+ assert (await _load(session, invoice["id"])).allocations == []
+
+
+async def test_the_rest_of_an_instalment_matches_what_is_left(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """Once a person books the first half, the second is exact again:
+ because a candidate's amount is its **balance**, not its total. This
+ is what makes a market that pays in parts reconcilable at all: each
+ settlement narrows the target for the next one."""
+ invoice = await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ first = await a_transaction(
+ session, account, test_user, amount=Decimal("1500.00"), payee_id=client_payee.id
+ )
+ booked = await _load(session, invoice["id"])
+ await invoice_service.allocate(
+ session, booked, first.id, amount=Decimal("1500.00"), method="manual"
+ )
+ await session.commit()
+
+ rest = await a_transaction(
+ session, account, test_user, amount=Decimal("1500.00"), payee_id=client_payee.id
+ )
+ applied = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [rest]
+ )
+ await session.commit()
+
+ assert len(applied) == 1
+ settled = await _load(session, invoice["id"])
+ assert sum(a.amount for a in settled.allocations) == Decimal("3000.00")
+ assert {a.method for a in settled.allocations} == {"manual", "same_client_exact"}
+
+
+async def test_a_supplier_payment_settles_a_bill(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """A payable is settled by money going out, and by the same
+ strategies. The node is named for the object, not the direction."""
+ bill = await an_invoice(
+ client, biz_headers, direction="payable", payee_id=client_payee.id
+ )
+ payment = await a_transaction(
+ session, account, test_user, kind="debit",
+ description="PAGAMENTO ALPHA", payee_id=client_payee.id,
+ )
+
+ applied = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [payment]
+ )
+ await session.commit()
+
+ assert len(applied) == 1
+ settled = await _load(session, bill["id"])
+ assert settled.allocations[0].transaction_id == payment.id
+
+
+async def test_money_leaving_never_settles_a_receivable(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ outflow = await a_transaction(
+ session, account, test_user, kind="debit", payee_id=client_payee.id
+ )
+
+ applied = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [outflow]
+ )
+ assert applied == []
+
+
+async def test_a_generated_placeholder_is_not_money(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """It is a promise. Settling a debt with another debt is what the
+ scope rule exists to prevent."""
+ await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ placeholder = await a_transaction(
+ session, account, test_user, payee_id=client_payee.id, source="recurring"
+ )
+
+ applied = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [placeholder]
+ )
+ assert applied == []
+
+
+async def test_an_invoice_in_another_workspace_is_never_a_candidate(
+ client: AsyncClient, auth_headers, biz_headers, session: AsyncSession,
+ account, test_user,
+):
+ """The workspace boundary is not a filter anyone may forget."""
+ other = await client.post(
+ "/api/workspaces",
+ headers=auth_headers,
+ json={"name": "Outro", "kind": "business", "self_membership": True},
+ )
+ other_headers = {**auth_headers, "X-Workspace-Id": other.json()["id"]}
+ await an_invoice(client, other_headers)
+
+ tx = await a_transaction(session, account, test_user)
+ applied = await reconciliation_service.match_incoming(
+ session, account.workspace_id, [tx]
+ )
+ assert applied == []
+
+
+async def test_a_payment_typed_in_by_hand_settles_its_invoice(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """Through the endpoint, not the service. Someone who reconciles by
+ typing the Pix in should not then have to go and link it: that is the
+ manual work the feature exists to remove, and leaving this path out
+ would remove it only for people whose bank happens to be connected."""
+ invoice = await an_invoice(client, biz_headers, payee_id=client_payee.id)
+
+ resp = await client.post(
+ "/api/transactions",
+ headers=biz_headers,
+ json={
+ "description": "PIX RECEBIDO ALPHA",
+ "amount": "3000.00",
+ "currency": "USD",
+ "date": str(TODAY),
+ "type": "credit",
+ "account_id": str(account.id),
+ "payee_id": str(client_payee.id),
+ },
+ )
+ assert resp.status_code in (200, 201), resp.text
+
+ settled = await _load(session, invoice["id"])
+ assert len(settled.allocations) == 1
+ assert settled.allocations[0].method == "same_client_exact"
+
+
+# ---------------------------------------------------------------------------
+# The direction that is easy to forget
+# ---------------------------------------------------------------------------
+async def test_an_invoice_issued_after_the_payment_finds_it(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """The common Brazilian case: the client pays, and the nota follows
+ days later. Nothing about the money changed, so nothing would ever
+ re-examine it: this is the pass that does."""
+ paid = await a_transaction(
+ session, account, test_user,
+ when=TODAY - timedelta(days=6), payee_id=client_payee.id,
+ )
+
+ invoice = await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ settled = await _load(session, invoice["id"])
+
+ assert len(settled.allocations) == 1
+ assert settled.allocations[0].transaction_id == paid.id
+
+
+async def test_money_from_a_payer_we_cannot_name_is_left_alone(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, test_user
+):
+ """Backwards, an exact amount is not enough. The money already had a
+ life of its own (a refund, a transfer, another job), and claiming it
+ for a document written afterwards is a guess. Forward, the same
+ payment links, because there the promise came first."""
+ await a_transaction(session, account, test_user, when=TODAY - timedelta(days=6))
+
+ invoice = await an_invoice(client, biz_headers)
+ assert (await _load(session, invoice["id"])).allocations == []
+
+
+async def test_two_payments_that_fit_equally_well_settle_nothing(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """Taking the most recent of two identical payments would invent
+ certainty exactly where the forward direction refuses to."""
+ for days in (3, 6):
+ await a_transaction(
+ session, account, test_user,
+ when=TODAY - timedelta(days=days), payee_id=client_payee.id,
+ )
+
+ invoice = await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ assert (await _load(session, invoice["id"])).allocations == []
+
+
+async def test_the_look_back_stops_at_the_window(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """Bounded so issuing an invoice never scans a year of a busy
+ account, and because money from six months ago is not this
+ invoice's."""
+ await a_transaction(
+ session, account, test_user,
+ when=TODAY - timedelta(days=200), payee_id=client_payee.id,
+ )
+ invoice = await an_invoice(client, biz_headers, payee_id=client_payee.id)
+ loaded = await _load(session, invoice["id"])
+
+ assert await reconciliation_service.match_for_invoice(session, loaded) is None
+
+
+async def test_a_draft_looks_back_at_nothing(
+ client: AsyncClient, biz_headers, session: AsyncSession, account, client_payee, test_user
+):
+ """A draft is not owed yet. Settling one would claim a document that
+ was never issued had been paid."""
+ await a_transaction(session, account, test_user, payee_id=client_payee.id)
+ draft = await an_invoice(
+ client, biz_headers, payee_id=client_payee.id, as_draft=True
+ )
+ loaded = await _load(session, draft["id"])
+ assert loaded.status == "draft"
+
+ assert await reconciliation_service.match_for_invoice(session, loaded) is None
diff --git a/backend/tests/test_recurring_match.py b/backend/tests/test_recurring_match.py
index faeb0d9b..de105bbd 100644
--- a/backend/tests/test_recurring_match.py
+++ b/backend/tests/test_recurring_match.py
@@ -12,6 +12,7 @@ from app.models.account import Account
from app.models.transaction import Transaction
from app.schemas.recurring_transaction import RecurringTransactionCreate
from app.services import recurring_match_service as rms
+from app.services.text_similarity import token_overlap
from app.services.recurring_transaction_service import (
create_recurring_transaction,
generate_pending,
@@ -76,17 +77,37 @@ async def _add_tx(session, test_user, test_workspace, account, **kw):
def test_description_similarity():
- assert rms._description_similarity("Netflix Sub", "netflix sub") == 1.0
- assert rms._description_similarity("Netflix", "Spotify") == 0.0
- assert rms._description_similarity(None, "x") == 0.0
+ """One implementation now, shared by the matching engine and the
+ bank-sync fuzzy merge. The bar it sets did not move."""
+ assert token_overlap("Netflix Sub", "netflix sub") == 1.0
+ assert token_overlap("Netflix", "Spotify") == 0.0
+ assert token_overlap(None, "x") == 0.0
def test_match_window():
- assert rms._match_window("weekly") == (2, 2)
- assert rms._match_window("monthly") == (3, 5)
- assert rms._match_window("yearly") == (3, 5)
- assert rms._match_window("biweekly") == (3, 5)
- assert rms._match_window("semiannual") == (3, 5)
+ """The windows are policy now rather than a function, and they are the
+ same windows.
+
+ Only weekly narrows, and the reason is arithmetic rather than taste: a
+ weekly bill sits seven days from its neighbours, and the shipped
+ window spans eight (three before, five after), so a charge could match
+ the wrong occurrence. Every other frequency is far enough apart that
+ the shipped window cannot reach the next one, which is why they all
+ read the same and why a new frequency needs no entry here unless its
+ occurrences fall closer together than eight days.
+ """
+ from app.services import reconciliation_policy
+
+ def window(frequency: str) -> tuple[int, int]:
+ rule = reconciliation_policy.for_recurring(frequency)["strategies"][0]["when"]
+ return rule["date"]["before_days"], rule["date"]["after_days"]
+
+ assert window("weekly") == (2, 2)
+ assert window("monthly") == (3, 5)
+ assert window("yearly") == (3, 5)
+ # Fourteen and one hundred and eighty days apart: nothing to narrow.
+ assert window("biweekly") == (3, 5)
+ assert window("semiannual") == (3, 5)
# ---------------------------------------------------------------------------
diff --git a/backend/tests/test_recurring_match_sync.py b/backend/tests/test_recurring_match_sync.py
index b0a31cda..667a8fe2 100644
--- a/backend/tests/test_recurring_match_sync.py
+++ b/backend/tests/test_recurring_match_sync.py
@@ -28,7 +28,8 @@ from app.models.recurring_transaction import RecurringTransaction
from app.models.transaction import Transaction
from app.schemas.recurring_transaction import RecurringTransactionCreate
from app.schemas.rule import RuleAction, RuleCondition, RuleCreate
-from app.services.connection_service import _description_similarity, sync_connection
+from app.services.connection_service import sync_connection
+from app.services.text_similarity import token_overlap
from app.services.recurring_transaction_service import (
create_recurring_transaction,
generate_pending,
@@ -205,7 +206,7 @@ async def test_sync_normalizes_before_active_recurring_match(
),
)
raw_description = "D01-1234567 AMZNPrime DE changing-token"
- assert _description_similarity(raw_description, "Amazon Prime") < 0.6
+ assert token_overlap(raw_description, "Amazon Prime") < 0.6
provider = _provider(
[
_tx(
diff --git a/frontend/src/components/components.contract.test.ts b/frontend/src/components/components.contract.test.ts
index e8a229b5..83c229aa 100644
--- a/frontend/src/components/components.contract.test.ts
+++ b/frontend/src/components/components.contract.test.ts
@@ -23,6 +23,16 @@ const paths = Object.keys(modules)
.filter((path) => !path.includes('.test.'))
.sort()
+// First evaluation of a module compiles its whole transitive graph through
+// Vite, which is slow and varies with how much else is running in parallel.
+// The default 5s is a budget for a *test*, not for a compile, and the page
+// with the heaviest graph sits right on it, so adding one component
+// anywhere in the tree can fail a page test that has nothing to do with it.
+//
+// A generous ceiling hides nothing: a module that fails to evaluate rejects
+// immediately, and only a genuine hang reaches this number.
+const EVALUATION_BUDGET_MS = 20_000
+
describe('component modules', () => {
it('finds the component tree', () => {
// If a refactor moves components elsewhere, this suite would silently
@@ -45,6 +55,6 @@ describe('component modules', () => {
(typeof value === 'object' && value !== null && '$$typeof' in value),
)
expect(components.length).toBeGreaterThan(0)
- })
+ }, EVALUATION_BUDGET_MS)
}
})
diff --git a/frontend/src/components/invoice-documents.tsx b/frontend/src/components/invoice-documents.tsx
index 4bc42d72..2a12bdf8 100644
--- a/frontend/src/components/invoice-documents.tsx
+++ b/frontend/src/components/invoice-documents.tsx
@@ -13,7 +13,12 @@ import {
SelectValue,
} from '@/components/ui/select'
import { invoices as invoicesApi } from '@/lib/api'
-import { documentProvenance, formatFileSize, previewKind } from '@/lib/invoice-utils'
+import {
+ documentProvenance,
+ formatFileSize,
+ ISSUED_BY_US,
+ previewKind,
+} from '@/lib/invoice-utils'
import { useDateLocale } from '@/hooks/use-display-locale'
import { cn } from '@/lib/utils'
import type { InvoiceAttachment, InvoiceAttachmentKind } from '@/types'
@@ -74,9 +79,15 @@ export function InvoiceDocumentBrowser({
queryFn: () => invoicesApi.attachments.list(invoiceId),
})
+ // Issuing files the page as it read at that moment, and that file is
+ // the document from then on. Listing the live render beside it shows
+ // one invoice twice under one name, and the live one is precisely the
+ // copy that drifts as payments land, which is what filing was for.
+ const filedAtIssue = attachments.some((a) => a.source === ISSUED_BY_US)
+
// An import with nothing filed has no page at all: drawing ours would
// invent a document a supplier issued and we were never handed.
- const showOurPage = origin !== 'imported' && ourPage !== null
+ const showOurPage = origin !== 'imported' && ourPage !== null && !filedAtIssue
const active = useMemo(() => {
if (selected === OUR_PAGE && showOurPage) return OUR_PAGE
@@ -239,6 +250,12 @@ export function InvoiceDocumentBrowser({
provenance={(() => {
const from = documentProvenance(attachment.source)
const arrived = showArrival(attachment.created_at)
+ if (from.kind === 'ours') {
+ // The same words the live render carried before it
+ // was filed, so nothing about the row changes when
+ // the drawing becomes a file.
+ return t('invoices.documents.rendered', { date: arrived })
+ }
return from.kind === 'system'
? t('invoices.documents.fromSystem', { source: from.name, date: arrived })
: t('invoices.documents.fromUpload', { date: arrived })
diff --git a/frontend/src/components/invoice-suggestions.tsx b/frontend/src/components/invoice-suggestions.tsx
new file mode 100644
index 00000000..649f2850
--- /dev/null
+++ b/frontend/src/components/invoice-suggestions.tsx
@@ -0,0 +1,142 @@
+/** The questions matching could not answer, where the invoice is.
+ *
+ * Matching produced these, and until now the only place they existed was
+ * a tab on the rules page. That is the wrong place for them to be the
+ * *only* place: somebody looking at an unpaid invoice is exactly the
+ * person who can say whether that payment is it, and they had no way of
+ * knowing a question was waiting unless they went looking for a queue
+ * they had no reason to visit.
+ *
+ * So the same question appears here, answerable in place. The queue is
+ * still where you go to clear a backlog; this is where you find one
+ * without having gone looking.
+ */
+import { useTranslation } from 'react-i18next'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'sonner'
+import { Check, HelpCircle, X } from 'lucide-react'
+
+import { Button } from '@/components/ui/button'
+import { reconciliation as reconciliationApi } from '@/lib/api'
+import { extractApiError } from '@/lib/api-errors'
+import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
+import { formatCurrency } from '@/lib/format'
+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
+import { usePrivacyMode } from '@/hooks/use-privacy-mode'
+import { suggestionsFor } from '@/lib/invoice-suggestions'
+import type { ReconciliationSuggestion } from '@/types'
+
+export function InvoiceSuggestions({
+ invoiceId,
+ canWrite,
+}: {
+ invoiceId: string
+ canWrite: boolean
+}) {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+ const locale = useDisplayLocale()
+ const dateLocale = useDateLocale()
+ const { mask } = usePrivacyMode()
+
+ // The same key the queue uses, so answering in either place updates
+ // both without either knowing the other exists.
+ const { data: pending = [] } = useQuery<ReconciliationSuggestion[]>({
+ queryKey: ['reconciliation-suggestions'],
+ queryFn: reconciliationApi.suggestions,
+ })
+
+ const answer = useMutation({
+ mutationFn: ({ id, accept }: { id: string; accept: boolean }) =>
+ accept ? reconciliationApi.accept(id) : reconciliationApi.decline(id),
+ onSuccess: (_result, { accept }) => {
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-suggestions'] })
+ void queryClient.invalidateQueries({ queryKey: ['invoice', invoiceId] })
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-history'] })
+ // Accepting moves money against a debt, so the figures everywhere
+ // else are now stale. Declining changes nothing but the question.
+ if (accept) invalidateFinancialQueries(queryClient)
+ // The same words the queue says for the same act. Two vocabularies
+ // for one decision would read as two features.
+ toast.success(
+ t(accept ? 'reconciliation.queue.linked' : 'reconciliation.queue.declined'),
+ )
+ },
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ const mine = suggestionsFor(pending, invoiceId)
+ if (mine.length === 0) return null
+
+ const showDate = (iso: string) => new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)
+ const money = (value: string | number, code?: string | null) =>
+ mask(formatCurrency(Number(value), code || 'USD', locale))
+
+ return (
+ <div className="bg-amber-50/60 dark:bg-amber-950/20 rounded-xl border border-amber-200 dark:border-amber-900/60 overflow-hidden">
+ <div className="px-4 sm:px-5 py-3 flex items-center gap-2 border-b border-amber-200 dark:border-amber-900/60">
+ <HelpCircle className="h-4 w-4 text-amber-600 dark:text-amber-400 shrink-0" />
+ <p className="text-sm font-semibold text-foreground">
+ {t('invoices.suggestions.title', { count: mine.length })}
+ </p>
+ </div>
+
+ <ul className="divide-y divide-amber-200 dark:divide-amber-900/60">
+ {mine.map((suggestion) => (
+ <li
+ key={suggestion.id}
+ className="px-4 sm:px-5 py-3 flex flex-wrap items-center justify-between gap-3"
+ data-testid="invoice-suggestion"
+ >
+ <div className="min-w-0">
+ <p className="text-sm font-medium text-foreground truncate">
+ {suggestion.transaction?.description ?? t('invoices.linkedPayment')}
+ </p>
+ <p className="text-xs text-muted-foreground tabular-nums mt-0.5">
+ {suggestion.transaction?.date ? showDate(suggestion.transaction.date) : ''}
+ {' · '}
+ {t('invoices.suggestions.wouldApply', {
+ amount: money(suggestion.amount, suggestion.transaction?.currency),
+ })}
+ {/* A question naming several invoices is answered whole or
+ not at all, so saying so before the buttons is the
+ difference between a decision and a surprise. */}
+ {(suggestion.covers?.length ?? 0) > 1 && (
+ <> · {t('invoices.suggestions.alsoCovers', {
+ count: (suggestion.covers?.length ?? 1) - 1,
+ })}</>
+ )}
+ </p>
+ </div>
+
+ {/* Same order, same icons, same words as the queue: this is
+ the same decision reached from a different door. */}
+ {canWrite && (
+ <div className="flex items-center gap-1 shrink-0">
+ <Button
+ size="sm"
+ className="h-8 gap-1.5"
+ disabled={answer.isPending}
+ onClick={() => answer.mutate({ id: suggestion.id, accept: true })}
+ >
+ <Check size={13} />
+ {t('reconciliation.queue.accept')}
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-8 gap-1 text-muted-foreground"
+ disabled={answer.isPending}
+ title={t('reconciliation.queue.declineHint')}
+ onClick={() => answer.mutate({ id: suggestion.id, accept: false })}
+ >
+ <X size={13} />
+ </Button>
+ </div>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )
+}
diff --git a/frontend/src/components/reconciliation-history.tsx b/frontend/src/components/reconciliation-history.tsx
new file mode 100644
index 00000000..7f2733a3
--- /dev/null
+++ b/frontend/src/components/reconciliation-history.tsx
@@ -0,0 +1,187 @@
+/** What matching did, in one order.
+ *
+ * Sits under the queue because the two answer neighbouring questions:
+ * the queue is *what still needs me*, this is *what already happened*.
+ * Newest first here and oldest first there, deliberately: a queue is
+ * work to get through, so its oldest item is the most urgent, while a
+ * history is read to find out what just happened.
+ *
+ * One line per event and nothing else. The thing a reader wants from a
+ * history like this is almost always the same: *was that me, or was that
+ * the rules?*, so that distinction is what the row leads with, and the
+ * rest is detail behind it.
+ */
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery } from '@tanstack/react-query'
+import { reconciliation as reconciliationApi } from '@/lib/api'
+import type { ReconciliationHistoryEvent } from '@/types'
+import { Link2, Link2Off, HelpCircle, Check, X, Clock } from 'lucide-react'
+import { formatCurrency } from '@/lib/format'
+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
+import { usePrivacyMode } from '@/hooks/use-privacy-mode'
+import { useAuth } from '@/contexts/auth-context'
+import { cn } from '@/lib/utils'
+import { ReconciliationPair, type PairSide } from '@/components/reconciliation-pair'
+
+function SectionCard({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
+ {children}
+ </div>
+ )
+}
+
+/** The six verbs, each with the shape a reader can scan for. */
+const LOOK: Record<
+ ReconciliationHistoryEvent['action'],
+ { icon: typeof Link2; tone: string }
+> = {
+ // A link, not a lightning bolt. The bolt meant "the rules did this",
+ // which is a claim about *who*, and a person linking a payment by hand
+ // writes a `linked` event too: the row then showed the automatic mark
+ // beside the words "by you". Who did it is said once, in the line
+ // underneath, where it can be read rather than decoded.
+ linked: { icon: Link2, tone: 'text-emerald-600' },
+ accepted: { icon: Check, tone: 'text-emerald-600' },
+ suggested: { icon: HelpCircle, tone: 'text-amber-600' },
+ declined: { icon: X, tone: 'text-muted-foreground' },
+ expired: { icon: Clock, tone: 'text-muted-foreground' },
+ unlinked: { icon: Link2Off, tone: 'text-rose-500' },
+}
+
+const SHOWN_AT_FIRST = 8
+
+export function ReconciliationHistory() {
+ const { t } = useTranslation()
+ const locale = useDisplayLocale()
+ const dateLocale = useDateLocale()
+ const { mask } = usePrivacyMode()
+ const [expanded, setExpanded] = useState(false)
+ // Same panel the queue uses. "Linked to AUR5" tells you what happened;
+ // it does not let you check whether it should have.
+ const [openId, setOpenId] = useState<string | null>(null)
+
+ // Only the fallback: an event that lost its promise (deleted, or from
+ // before the field existed) still has to render something, and the
+ // viewer's own currency is the least wrong guess available.
+ const { user } = useAuth()
+ const displayCurrency = user?.preferences?.currency_display ?? 'USD'
+
+ const { data: events } = useQuery<ReconciliationHistoryEvent[]>({
+ queryKey: ['reconciliation-history'],
+ queryFn: () => reconciliationApi.history(),
+ })
+
+ if (!events) return null
+
+ const shown = expanded ? events : events.slice(0, SHOWN_AT_FIRST)
+ // The event's own currency, never a guess: a workspace keeping invoices
+ // in more than one is ordinary, and a hardcoded code would have read a
+ // R$ 1.200,00 settlement back as $1,200.00.
+ const money = (value: string, currency?: string | null) =>
+ mask(formatCurrency(Number(value ?? 0), currency || displayCurrency, locale))
+ const when = (iso: string) =>
+ new Date(iso).toLocaleString(dateLocale, {
+ day: 'numeric',
+ month: 'short',
+ hour: '2-digit',
+ minute: '2-digit',
+ })
+
+ return (
+ <SectionCard>
+ <div className="px-4 sm:px-5 py-4 border-b border-border">
+ <p className="text-sm font-semibold text-foreground">
+ {t('reconciliation.history.title')}
+ </p>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {t('reconciliation.history.hint')}
+ </p>
+ </div>
+
+ {events.length === 0 ? (
+ // An empty state rather than nothing: as a card in a stack,
+ // rendering nothing was right. As a tab somebody clicked, a blank
+ // page reads as broken.
+ <p className="text-sm text-muted-foreground text-center py-10">
+ {t('reconciliation.history.empty')}
+ </p>
+ ) : (
+ <div className="divide-y divide-border">
+ {shown.map((event) => {
+ const look = LOOK[event.action]
+ const Icon = look.icon
+ return (
+ <div
+ key={event.id}
+ className="px-4 sm:px-5 py-2.5 text-sm hover:bg-muted/60 transition-colors cursor-pointer"
+ onClick={() =>
+ setOpenId((current) => (current === event.id ? null : event.id))
+ }
+ >
+ <div className="flex items-start gap-3">
+ <Icon size={14} className={cn('mt-0.5 shrink-0', look.tone)} />
+ <div className="flex-1 min-w-0">
+ <p className="text-foreground">
+ {t(`reconciliation.history.action.${event.action}`, {
+ name: event.expectation_label ?? '—',
+ })}
+ <span className="text-muted-foreground">
+ {' · '}
+ {money(event.amount, event.currency)}
+ </span>
+ </p>
+ <p className="text-xs text-muted-foreground truncate">
+ {/* Whether a person or the rules did it is the first
+ thing anybody wants from a history like this, so it
+ leads the detail line. */}
+ {event.user_id
+ ? t('reconciliation.history.byPerson')
+ : t('reconciliation.history.byRules')}
+ {event.transaction_description
+ ? ` · ${event.transaction_description}`
+ : ''}
+ </p>
+ </div>
+ <span className="text-xs text-muted-foreground shrink-0 tabular-nums">
+ {when(event.at)}
+ </span>
+ </div>
+
+ <ReconciliationPair
+ open={openId === event.id}
+ transactionId={event.transaction_id}
+ // Already written: the invoice reflects it, so the panel
+ // reports rather than projects.
+ pending={false}
+ sides={[
+ {
+ kind: event.expectation_kind,
+ id: event.expectation_id,
+ label: event.expectation_label,
+ amount: event.amount,
+ } satisfies PairSide,
+ ]}
+ />
+ </div>
+ )
+ })}
+ </div>
+ )}
+
+ {events.length > SHOWN_AT_FIRST && (
+ <button
+ className="w-full px-4 py-2.5 text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted transition-colors border-t border-border"
+ onClick={() => setExpanded((open) => !open)}
+ >
+ {expanded
+ ? t('reconciliation.history.less')
+ : t('reconciliation.history.more', {
+ count: events.length - SHOWN_AT_FIRST,
+ })}
+ </button>
+ )}
+ </SectionCard>
+ )
+}
diff --git a/frontend/src/components/reconciliation-pair.tsx b/frontend/src/components/reconciliation-pair.tsx
new file mode 100644
index 00000000..5624ae73
--- /dev/null
+++ b/frontend/src/components/reconciliation-pair.tsx
@@ -0,0 +1,295 @@
+/** The promise and the money, resolved into the arithmetic that decides.
+ *
+ * This began as a dialog holding two bordered boxes and an arrow. Three
+ * things were wrong with it, and the structural one came first: a modal
+ * is the answer you reach for before thinking. You inspected, closed,
+ * and the Accept button was behind the thing you had just dismissed. So
+ * this expands the row in place. The list stays put, several can be read
+ * in sequence, and the decision stays under your cursor.
+ *
+ * The second was that a reader had to diff two lists in their head. The
+ * question is never "what are the properties of this invoice", it is
+ * "does this money belong to this debt", and that is one subtraction. So
+ * the subtraction is the headline, and everything else is provenance
+ * underneath it, quieter and smaller.
+ *
+ * The third was boxes inside a box. There are no cards here: a hairline
+ * between two columns says the same thing and costs nothing.
+ */
+import { useTranslation } from 'react-i18next'
+import { useQuery } from '@tanstack/react-query'
+import {
+ invoices as invoicesApi,
+ transactions as transactionsApi,
+ accounts as accountsApi,
+} from '@/lib/api'
+import type { Account, Invoice, Transaction } from '@/types'
+import { formatCurrency } from '@/lib/format'
+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
+import { usePrivacyMode } from '@/hooks/use-privacy-mode'
+import { cn } from '@/lib/utils'
+
+export interface PairSide {
+ kind: 'invoice' | 'recurring'
+ id: string
+ label?: string | null
+ /** What this movement puts, or would put, against this promise. */
+ amount: string
+}
+
+/** A figure with its meaning beneath it, sized so the figures read as one
+ * row of numbers and the words stay out of the way. */
+function Figure({
+ value,
+ caption,
+ tone = 'neutral',
+}: {
+ value: string
+ caption: string
+ tone?: 'neutral' | 'applied' | 'quiet'
+}) {
+ return (
+ <div className="min-w-0">
+ <p
+ className={cn(
+ 'text-lg font-semibold tabular-nums leading-none truncate',
+ tone === 'applied' && 'text-emerald-600 dark:text-emerald-400',
+ tone === 'quiet' && 'text-muted-foreground',
+ tone === 'neutral' && 'text-foreground',
+ )}
+ >
+ {value}
+ </p>
+ <p className="text-[11px] text-muted-foreground mt-1 truncate">{caption}</p>
+ </div>
+ )
+}
+
+/** One line of provenance. Deliberately not a label/value table: six rows
+ * of those compete with the figures above, and the figures are what the
+ * decision rests on. */
+function Facts({ items }: { items: (string | null | undefined)[] }) {
+ const shown = items.filter(Boolean) as string[]
+ return (
+ <p className="text-xs text-muted-foreground leading-relaxed">
+ {shown.join(' · ')}
+ </p>
+ )
+}
+
+function useInvoice(id: string, enabled: boolean) {
+ return useQuery<Invoice>({
+ queryKey: ['invoice', id],
+ queryFn: () => invoicesApi.get(id),
+ enabled,
+ })
+}
+
+function PromiseLine({
+ side,
+ open,
+ money,
+ showDate,
+}: {
+ side: PairSide
+ open: boolean
+ money: (value: string | number | null | undefined, code?: string | null) => string
+ showDate: (iso: string) => string
+}) {
+ const { t } = useTranslation()
+ const { data: invoice } = useInvoice(side.id, open && side.kind === 'invoice')
+
+ if (side.kind !== 'invoice') {
+ return (
+ <div>
+ <p className="text-sm font-medium text-foreground">
+ {side.label ?? t('reconciliation.pair.recurringBill')}
+ </p>
+ <Facts items={[t('reconciliation.pair.recurringBill')]} />
+ </div>
+ )
+ }
+
+ if (!invoice) {
+ return <p className="text-xs text-muted-foreground">{t('common.loading')}</p>
+ }
+
+ // The label the API resolved. Composing it from `series` and `number`
+ // gets it wrong: `series` is the fiscal year, and the prefix a reader
+ // recognises lives in the snapshot taken at issue.
+ const name = side.label ?? invoice.external_number ?? null
+
+ return (
+ <div className="space-y-0.5">
+ <p className="text-sm font-medium text-foreground flex items-center gap-2">
+ {name ?? t('reconciliation.pair.draftInvoice')}
+ {invoice.state === 'overdue' && (
+ <span className="text-[10px] font-semibold uppercase tracking-wide text-rose-600 dark:text-rose-400">
+ {t('invoices.state.overdue', 'overdue')}
+ </span>
+ )}
+ </p>
+ <Facts
+ items={[
+ invoice.payee?.name,
+ t('reconciliation.pair.dueOn', { date: showDate(invoice.due_date) }),
+ t('reconciliation.pair.totalOf', {
+ amount: money(invoice.total, invoice.currency),
+ }),
+ ]}
+ />
+ </div>
+ )
+}
+
+export function ReconciliationPair({
+ open,
+ transactionId,
+ sides,
+ /** Pending means the money has not been applied yet, so the arithmetic
+ * can say what *would* be left. Once applied, the invoice already
+ * reflects it, and subtracting again would be a lie told confidently. */
+ pending,
+}: {
+ open: boolean
+ transactionId?: string | null
+ sides: PairSide[]
+ pending: boolean
+}) {
+ const { t } = useTranslation()
+ const locale = useDisplayLocale()
+ const dateLocale = useDateLocale()
+ const { mask } = usePrivacyMode()
+
+ const { data: accounts = [] } = useQuery<Account[]>({
+ queryKey: ['accounts'],
+ queryFn: () => accountsApi.list(),
+ enabled: open,
+ })
+ const { data: transaction } = useQuery<Transaction>({
+ queryKey: ['transaction', transactionId],
+ queryFn: () => transactionsApi.get(transactionId as string),
+ enabled: open && !!transactionId,
+ })
+ const first = sides.length > 0 ? sides[0] : undefined
+ const { data: firstInvoice } = useInvoice(
+ first?.id ?? '',
+ open && first?.kind === 'invoice',
+ )
+
+ if (!open) return null
+
+ const currency = firstInvoice?.currency ?? transaction?.currency
+ const money = (value: string | number | null | undefined, code?: string | null) =>
+ mask(formatCurrency(Number(value ?? 0), code || currency || 'USD', locale))
+ const showDate = (iso: string) =>
+ new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)
+ const accountName = accounts.find((a) => a.id === transaction?.account_id)?.name
+
+ const applied = sides.reduce((sum, side) => sum + Number(side.amount), 0)
+ const outstanding = Number(firstInvoice?.balance ?? 0)
+ const remaining = outstanding - applied
+ const singleInvoice = sides.length === 1 && first?.kind === 'invoice'
+
+ return (
+ <div className="mt-3 pt-3 border-t border-border">
+ {/* The subtraction that decides, before anything else. One invoice
+ gets the whole sentence; a payment spread over several gets the
+ two totals, because "what is left" is not one number then. */}
+ <div className="flex items-end gap-6 sm:gap-10 flex-wrap">
+ {singleInvoice ? (
+ <>
+ <Figure
+ value={money(outstanding)}
+ caption={t('reconciliation.pair.stillOpen')}
+ tone="quiet"
+ />
+ <Figure
+ value={money(applied)}
+ caption={
+ pending
+ ? t('reconciliation.pair.thisPayment')
+ : t('reconciliation.pair.wasApplied')
+ }
+ tone="applied"
+ />
+ {pending && (
+ <Figure
+ value={money(remaining > 0 ? remaining : 0)}
+ caption={
+ remaining <= 0
+ ? t('reconciliation.pair.wouldClose')
+ : t('reconciliation.pair.wouldRemain')
+ }
+ tone={remaining <= 0 ? 'applied' : 'neutral'}
+ />
+ )}
+ </>
+ ) : (
+ <>
+ <Figure
+ value={money(applied)}
+ caption={t('reconciliation.pair.acrossInvoices', {
+ count: sides.length,
+ })}
+ tone="applied"
+ />
+ {transaction && (
+ <Figure
+ value={money(transaction.amount, transaction.currency)}
+ caption={t('reconciliation.pair.thePayment')}
+ tone="quiet"
+ />
+ )}
+ </>
+ )}
+ </div>
+
+ {/* Provenance, quieter, split only by a hairline. Boxes here would be
+ boxes inside a row inside a card. */}
+ <div className="mt-4 grid gap-4 sm:grid-cols-2 sm:divide-x divide-border">
+ <div className="space-y-2 sm:pr-5">
+ <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
+ {t('reconciliation.pair.owed')}
+ </p>
+ {sides.map((side) => (
+ <PromiseLine
+ key={side.id}
+ side={side}
+ open={open}
+ money={money}
+ showDate={showDate}
+ />
+ ))}
+ </div>
+
+ <div className="space-y-2 sm:pl-5">
+ <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">
+ {t('reconciliation.pair.arrived')}
+ </p>
+ {transaction ? (
+ <div className="space-y-0.5">
+ <p className="text-sm font-medium text-foreground truncate">
+ {transaction.description}
+ </p>
+ <Facts
+ items={[
+ showDate(transaction.date),
+ accountName,
+ // `payee_name` is the resolved one; `payee` is the raw
+ // string the bank sent, worth falling back to when
+ // nothing has been mapped yet.
+ transaction.payee_name || transaction.payee,
+ ]}
+ />
+ </div>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ {transactionId ? t('common.loading') : t('reconciliation.pair.noMoney')}
+ </p>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/components/reconciliation-queue.tsx b/frontend/src/components/reconciliation-queue.tsx
new file mode 100644
index 00000000..543f94f3
--- /dev/null
+++ b/frontend/src/components/reconciliation-queue.tsx
@@ -0,0 +1,279 @@
+/** The doubtful space: matches that are plausible without being certain.
+ *
+ * This queue is the **residue**, never the main road. Every row here is a
+ * payment the automatic rules could not claim, and if it is where the
+ * volume goes then the rules are wrong and the fix belongs one card up,
+ * not in asking somebody to work through a list every morning.
+ *
+ * Which is why the empty state is written as good news rather than as an
+ * apology for having nothing to show.
+ *
+ * Each row states its evidence (the amount is exact, the payer is known,
+ * the date is four days out) instead of a confidence score. A percentage
+ * is not something a person can check, and a queue nobody can check is a
+ * queue they clear without reading.
+ */
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { reconciliation as reconciliationApi } from '@/lib/api'
+import { extractApiError } from '@/lib/api-errors'
+import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
+import { toast } from 'sonner'
+import { Button } from '@/components/ui/button'
+import type { ReconciliationSuggestion } from '@/types'
+import { Check, X, CircleCheck } from 'lucide-react'
+import { ReconciliationPair, type PairSide } from '@/components/reconciliation-pair'
+import { formatCurrency } from '@/lib/format'
+import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
+import { usePrivacyMode } from '@/hooks/use-privacy-mode'
+
+function SectionCard({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
+ {children}
+ </div>
+ )
+}
+
+/** The evidence, as short claims a reader can agree or disagree with. */
+function Evidence({ suggestion }: { suggestion: ReconciliationSuggestion }) {
+ const { t } = useTranslation()
+ const { scores } = suggestion
+ const claims: { label: string; good: boolean }[] = []
+
+ if (scores.amount_exact !== undefined) {
+ claims.push({
+ label: scores.amount_exact
+ ? t('reconciliation.evidence.amountExact')
+ : t('reconciliation.evidence.amountOff', {
+ expected: scores.amount_expected,
+ moved: scores.amount_moved,
+ }),
+ good: !!scores.amount_exact,
+ })
+ }
+ if (scores.same_counterparty !== undefined) {
+ claims.push({
+ label: scores.same_counterparty
+ ? t('reconciliation.evidence.knownPayer')
+ : t('reconciliation.evidence.unknownPayer'),
+ good: !!scores.same_counterparty,
+ })
+ }
+ if (scores.days_apart !== undefined) {
+ claims.push({
+ label:
+ scores.days_apart === 0
+ ? t('reconciliation.evidence.sameDay')
+ : t('reconciliation.evidence.daysApart', { days: Math.abs(scores.days_apart) }),
+ good: Math.abs(scores.days_apart) <= 3,
+ })
+ }
+
+ return (
+ <div className="flex flex-wrap gap-1.5 mt-1.5">
+ {claims.map((claim) => (
+ <span
+ key={claim.label}
+ className={
+ claim.good
+ ? 'text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300'
+ : 'text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-muted text-muted-foreground'
+ }
+ >
+ {claim.label}
+ </span>
+ ))}
+ </div>
+ )
+}
+
+export function ReconciliationQueue({ canWrite }: { canWrite: boolean }) {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+ const locale = useDisplayLocale()
+ const dateLocale = useDateLocale()
+ const { mask } = usePrivacyMode()
+
+ const { data: suggestions } = useQuery<ReconciliationSuggestion[]>({
+ queryKey: ['reconciliation-suggestions'],
+ queryFn: reconciliationApi.suggestions,
+ })
+
+ // Deciding is a comparison, and the evidence chips describe an invoice
+ // without ever showing it. Expanding the row puts both halves on screen
+ // without taking the Accept button away with a modal.
+ const [openId, setOpenId] = useState<string | null>(null)
+
+ const accept = useSettleMutation('accept', queryClient, t)
+ const decline = useSettleMutation('decline', queryClient, t)
+
+ const money = (value: string | number | null | undefined, currency?: string | null) =>
+ mask(formatCurrency(Number(value ?? 0), currency || 'USD', locale))
+ const showDate = (iso: string) =>
+ new Date(`${iso}T00:00:00`).toLocaleDateString(dateLocale)
+
+ if (!suggestions) return null
+
+ return (
+ <SectionCard>
+ <div className="px-4 sm:px-5 py-4 border-b border-border">
+ <p className="text-sm font-semibold text-foreground">
+ {t('reconciliation.queue.title')}
+ {suggestions.length > 0 && (
+ <span className="ml-2 text-[10px] font-semibold bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300 px-1.5 py-0.5 rounded-full">
+ {suggestions.length}
+ </span>
+ )}
+ </p>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {t('reconciliation.queue.hint')}
+ </p>
+ </div>
+
+ {suggestions.length === 0 ? (
+ <div className="py-10 text-center">
+ <CircleCheck size={20} className="mx-auto text-emerald-500 mb-2" />
+ <p className="text-sm text-muted-foreground">{t('reconciliation.queue.empty')}</p>
+ </div>
+ ) : (
+ <div className="divide-y divide-border">
+ {suggestions.map((suggestion) => (
+ <div
+ key={suggestion.id}
+ className="px-4 sm:px-5 py-3 hover:bg-muted/60 transition-colors cursor-pointer"
+ onClick={() =>
+ setOpenId((current) => (current === suggestion.id ? null : suggestion.id))
+ }
+ >
+ <div className="flex items-start justify-between gap-4">
+ <div className="flex-1 min-w-0">
+ <p className="text-sm font-medium text-foreground truncate">
+ {suggestion.transaction?.description ??
+ t('reconciliation.queue.aPayment')}
+ </p>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {suggestion.transaction?.date
+ ? showDate(suggestion.transaction.date)
+ : ''}
+ {' · '}
+ {t(
+ suggestion.expectation_kind === 'invoice'
+ ? 'reconciliation.queue.maySettle'
+ : 'reconciliation.queue.mayBe',
+ {
+ // One payment can answer several promises, and the
+ // question is the whole question, so the row names
+ // all of them rather than the first and a count.
+ name:
+ suggestion.covers.length > 1
+ ? suggestion.covers
+ .map((c) => c.label ?? '—')
+ .join(', ')
+ : suggestion.expectation_label ?? '—',
+ },
+ )}
+ </p>
+
+ {suggestion.covers.length > 1 && (
+ <ul className="mt-1 space-y-0.5">
+ {suggestion.covers.map((cover) => (
+ <li
+ key={cover.expectation_id}
+ className="text-xs text-muted-foreground flex justify-between gap-3 max-w-xs"
+ >
+ <span className="truncate">{cover.label ?? '—'}</span>
+ <span className="tabular-nums">
+ {money(cover.amount, suggestion.scores.currency)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ <Evidence suggestion={suggestion} />
+ </div>
+
+ <div className="flex items-center gap-2 shrink-0">
+ <span className="text-sm font-bold tabular-nums text-foreground">
+ {money(suggestion.amount, suggestion.scores.currency)}
+ </span>
+ {canWrite && (
+ <div
+ className="flex items-center gap-1"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-8 gap-1"
+ onClick={() => accept.mutate(suggestion.id)}
+ disabled={accept.isPending || decline.isPending}
+ >
+ <Check size={13} />
+ <span className="hidden sm:inline">
+ {t('reconciliation.queue.accept')}
+ </span>
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-8 gap-1 text-muted-foreground"
+ onClick={() => decline.mutate(suggestion.id)}
+ disabled={accept.isPending || decline.isPending}
+ title={t('reconciliation.queue.declineHint')}
+ >
+ <X size={13} />
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+
+ <div onClick={(e) => e.stopPropagation()}>
+ <ReconciliationPair
+ open={openId === suggestion.id}
+ transactionId={suggestion.transaction?.id}
+ pending
+ sides={suggestion.covers.map<PairSide>((cover) => ({
+ kind: cover.expectation_kind,
+ id: cover.expectation_id,
+ label: cover.label,
+ amount: cover.amount,
+ }))}
+ />
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </SectionCard>
+ )
+}
+
+/** Accept and decline differ only in which endpoint they call and what
+ * they say afterwards, so they share one definition rather than two
+ * near-identical blocks that drift. */
+function useSettleMutation(
+ action: 'accept' | 'decline',
+ queryClient: ReturnType<typeof useQueryClient>,
+ t: (key: string) => string,
+) {
+ return useMutation({
+ mutationFn: (id: string) =>
+ action === 'accept'
+ ? reconciliationApi.accept(id)
+ : reconciliationApi.decline(id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-suggestions'] })
+ // Answering a question is itself an event, so the stream below has
+ // to be re-read or it shows a history that stops one act ago.
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-history'] })
+ if (action === 'accept') invalidateFinancialQueries(queryClient)
+ toast.success(
+ t(action === 'accept' ? 'reconciliation.queue.linked' : 'reconciliation.queue.declined'),
+ )
+ },
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+}
diff --git a/frontend/src/components/reconciliation-rules.tsx b/frontend/src/components/reconciliation-rules.tsx
new file mode 100644
index 00000000..5ce64c0c
--- /dev/null
+++ b/frontend/src/components/reconciliation-rules.tsx
@@ -0,0 +1,1433 @@
+/** The rules matching follows, shown and editable.
+ *
+ * Sits under the categorization rules because it is the same promise made
+ * twice: the software decides things about your money, and you get to see
+ * the decision and disagree with it. Matching used to be numbers buried in
+ * a module; this is those numbers, with a name and a switch.
+ *
+ * Two things this screen deliberately is not. It is not an open-ended
+ * condition builder like the rules above it: matching runs on a fixed set
+ * of signals, and offering fields the engine cannot read would be a lie
+ * told in a nice font. And it is not a list stored in the database: what
+ * you see is what we ship with whatever you changed applied over it, so a
+ * rule you never touched keeps improving when we improve it.
+ */
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import {
+ reconciliation as reconciliationApi,
+ accounts as accountsApi,
+ payees as payeesApi,
+} from '@/lib/api'
+import { extractApiError } from '@/lib/api-errors'
+import { toast } from 'sonner'
+import { Button } from '@/components/ui/button'
+import { Label } from '@/components/ui/label'
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog'
+import type {
+ Account,
+ Payee,
+ Trigger,
+ ReconciliationConditions,
+ ReconciliationNode,
+ ReconciliationPolicyFile,
+ ReconciliationRule,
+} from '@/types'
+import { Plus, RotateCcw, Trash2, Zap, HelpCircle, ChevronUp, ChevronDown, Power, Download, Upload } from 'lucide-react'
+import { cn } from '@/lib/utils'
+import { DeleteConfirmationDialog } from '@/components/delete-confirmation-dialog'
+
+/** Names for the rules we ship. Kept here rather than sent by the API so
+ * they follow the reader's language, and so a rule someone edited does not
+ * freeze its label in whatever language it was edited in. */
+const SHIPPED_NAME: Record<string, string> = {
+ same_client_exact: 'reconciliation.rule.sameClientExact',
+ same_client_net_of_withholding: 'reconciliation.rule.netOfWithholding',
+ exact_amount_any_client: 'reconciliation.rule.exactAmountAnyClient',
+ same_client_part_payment: 'reconciliation.rule.partPayment',
+ same_client_several_invoices: 'reconciliation.rule.severalInvoices',
+ similar_description: 'reconciliation.rule.similarDescription',
+ same_account_exact: 'reconciliation.rule.sameAccountExact',
+}
+
+/** What the file says it is. A categorization export dropped into the
+ * matching importer would otherwise arrive as a file with no rules in
+ * it and look like it worked. */
+const POLICY_FORMAT = 'securo-reconciliation-rules'
+
+const NODE_TITLE: Record<string, string> = {
+ 'reconciliation.match_invoice': 'reconciliation.node.invoices',
+ 'reconciliation.match_recurring': 'reconciliation.node.recurring',
+}
+
+const NODE_HINT: Record<string, string> = {
+ 'reconciliation.match_invoice': 'reconciliation.node.invoicesHint',
+ 'reconciliation.match_recurring': 'reconciliation.node.recurringHint',
+}
+
+/** The whole order with two entries exchanged.
+ *
+ * Returns every id, not the pair that moved, because that is what the
+ * API takes, and for a good reason: an order where some rules are
+ * placed and the rest fall back to wherever we shipped them reads fine
+ * today and quietly rearranges the day a new default is inserted. */
+function swap(rules: ReconciliationRule[], from: number, to: number): string[] {
+ const ids = rules.map((rule) => rule.id)
+ const moved = ids.splice(from, 1)[0]
+ ids.splice(to, 0, moved)
+ return ids
+}
+
+
+function SectionCard({ children }: { children: React.ReactNode }) {
+ return (
+ <div className="bg-card rounded-xl border border-border shadow-sm overflow-hidden">
+ {children}
+ </div>
+ )
+}
+
+/** One rule in a sentence, built from the signals it actually consults.
+ *
+ * Written out rather than shown as a form on the row because the question
+ * a reader arrives with is "why did this match", and a sentence answers it
+ * where a grid of numbers does not. */
+/** Several words mean *any of them*, so they read as a list and are typed
+ * as one. Commas rather than a repeater: somebody adding a fourth
+ * acquirer types four more characters instead of finding a button. */
+function joinWords(value: string | string[] | undefined): string {
+ if (!value) return ''
+ return Array.isArray(value) ? value.join(', ') : value
+}
+
+/** A text field whose value is a list.
+ *
+ * It holds what is being typed, not the split result read back. Splitting
+ * on every keystroke and re-joining ate the separator: a word followed by
+ * a comma became one word, which rendered back without the comma, so the
+ * next letter landed against it and three names arrived as one.
+ */
+/** The currency list, held as text while it is being typed.
+
+ * Same problem `WordsInput` solves, and the same shape of answer. A code
+ * is only a code at three letters, so deriving the field's value from
+ * the rule meant the first two keystrokes filtered away to nothing and
+ * the input emptied itself: `BRL` could not be typed at all. What is
+ * shown is what was typed; what is stored is what parses.
+ */
+function CodesInput({
+ className,
+ placeholder,
+ value,
+ onChange,
+}: {
+ className: string
+ placeholder: string
+ value: string[] | undefined
+ onChange: (next: string[] | undefined) => void
+}) {
+ const settled = (value ?? []).join(', ')
+ const [text, setText] = useState(settled)
+ const [seed, setSeed] = useState(settled)
+
+ const parse = (raw: string) => {
+ const codes = raw
+ .split(',')
+ .map((code) => code.trim().toUpperCase())
+ .filter((code) => code.length === 3)
+ return codes.length ? codes : undefined
+ }
+
+ // Reseeded only when the rule changed underneath, never from our own
+ // keystrokes.
+ if (seed !== settled) {
+ setSeed(settled)
+ if ((parse(text) ?? []).join(', ') !== settled) setText(settled)
+ }
+
+ return (
+ <input
+ className={className}
+ placeholder={placeholder}
+ value={text}
+ onChange={(event) => {
+ setText(event.target.value)
+ onChange(parse(event.target.value))
+ }}
+ />
+ )
+}
+
+function WordsInput({
+ className,
+ placeholder,
+ value,
+ onChange,
+}: {
+ className: string
+ placeholder: string
+ value: string | string[] | undefined
+ onChange: (next: string | string[] | undefined) => void
+}) {
+ const settled = joinWords(value)
+ const [text, setText] = useState(settled)
+ const [seed, setSeed] = useState(settled)
+
+ // Reseeded only when the rule changed underneath, never from our own
+ // keystrokes: what distinguishes the two is whether the text still
+ // splits to what the rule holds.
+ if (seed !== settled) {
+ setSeed(settled)
+ if (joinWords(splitWords(text)) !== settled) setText(settled)
+ }
+
+ return (
+ <input
+ className={className}
+ placeholder={placeholder}
+ value={text}
+ onChange={(event) => {
+ setText(event.target.value)
+ onChange(splitWords(event.target.value))
+ }}
+ />
+ )
+}
+
+function splitWords(raw: string): string | string[] | undefined {
+ const words = raw
+ .split(',')
+ .map((word) => word.trim())
+ .filter(Boolean)
+ if (words.length === 0) return undefined
+ // One word stays a string, so a rule nobody meant to change does not
+ // arrive at the server looking different from what we ship.
+ return words.length === 1 ? words[0] : words
+}
+
+function conditionSummary(
+ when: ReconciliationConditions & { trigger?: Trigger },
+ t: (key: string, opts?: Record<string, unknown>) => string,
+ names: { accounts: Account[]; payees: Payee[] },
+): string {
+ const parts: string[] = []
+
+ // The moment first, because it is the question the old summary could
+ // not answer: does this fire when money lands, or when the document is
+ // written? "Both" says nothing worth a word, so it says nothing.
+ if (when.trigger === 'invoice_issued') parts.push(t('reconciliation.cond.onIssue'))
+ else if (when.trigger === 'money_arrives') parts.push(t('reconciliation.cond.onArrival'))
+
+ // Then the scope filters, which answer "does this even apply?" before
+ // the question of how closely the pair has to fit.
+ if (when.accounts?.in?.length) {
+ parts.push(
+ t('reconciliation.cond.accounts', {
+ names: when.accounts.in
+ .map((id) => names.accounts.find((a) => a.id === id)?.name ?? '?')
+ .join(', '),
+ }),
+ )
+ }
+ if (when.payees?.in?.length) {
+ parts.push(
+ t('reconciliation.cond.payees', {
+ names: when.payees.in
+ .map((id) => names.payees.find((p) => p.id === id)?.name ?? '?')
+ .join(', '),
+ }),
+ )
+ }
+ if (when.direction && when.direction !== 'any') {
+ parts.push(
+ t(when.direction === 'credit'
+ ? 'reconciliation.cond.moneyIn'
+ : 'reconciliation.cond.moneyOut'),
+ )
+ }
+ if (when.currency?.foreign) parts.push(t('reconciliation.cond.foreign'))
+ if (when.currency?.in?.length)
+ parts.push(t('reconciliation.cond.currencyIn', { codes: when.currency.in.join(', ') }))
+ if (when.amount?.min) parts.push(t('reconciliation.cond.atLeast', { value: when.amount.min }))
+ if (when.amount?.max) parts.push(t('reconciliation.cond.atMost', { value: when.amount.max }))
+ if (when.text?.contains)
+ parts.push(t('reconciliation.cond.textContains', { text: joinWords(when.text.contains) }))
+ if (when.text?.not_contains)
+ parts.push(t('reconciliation.cond.textExcludes', { text: joinWords(when.text.not_contains) }))
+
+ if (when.counterparty === 'same_payee') parts.push(t('reconciliation.cond.samePayee'))
+ if (when.same_account) parts.push(t('reconciliation.cond.sameAccount'))
+
+ if (when.amount?.match === 'exact') parts.push(t('reconciliation.cond.amountExact'))
+ else if (when.amount?.match === 'tolerance')
+ parts.push(t('reconciliation.cond.amountTolerance', { percent: when.amount.percent }))
+ else if (when.amount?.match === 'ratio')
+ parts.push(t('reconciliation.cond.amountRatio'))
+ else if (when.amount?.match === 'partial')
+ parts.push(t('reconciliation.cond.amountPartial'))
+ else if (when.amount?.match === 'set')
+ parts.push(
+ t('reconciliation.cond.amountSet', { count: when.amount.max_invoices ?? 6 }),
+ )
+
+ if (when.date)
+ parts.push(
+ t('reconciliation.cond.window', {
+ before: when.date.before_days,
+ after: when.date.after_days,
+ }),
+ )
+
+ if (when.description_similarity)
+ parts.push(
+ t('reconciliation.cond.similarity', { min: when.description_similarity.min }),
+ )
+
+ return parts.join(' · ') || t('reconciliation.cond.none')
+}
+
+function OutcomeBadge({ outcome }: { outcome: 'link' | 'suggest' }) {
+ const { t } = useTranslation()
+ return (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full',
+ outcome === 'link'
+ ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950 dark:text-emerald-300'
+ : 'bg-amber-50 text-amber-700 dark:bg-amber-950 dark:text-amber-300',
+ )}
+ >
+ {outcome === 'link' ? <Zap size={10} /> : <HelpCircle size={10} />}
+ {t(outcome === 'link' ? 'reconciliation.outcome.link' : 'reconciliation.outcome.suggest')}
+ </span>
+ )
+}
+
+/** One of the three questions a rule answers, with its heading.
+ *
+ * The form used to be a flat list, and two of its fields were both called
+ * "Amount": one asking how close the payment must be to the invoice, the
+ * other asking which payments the rule looks at. Same word, different
+ * question, twenty pixels apart. Splitting them under headings is not
+ * decoration: it is the difference between a form you can read and one
+ * you have to already understand. */
+function Step({
+ index,
+ title,
+ hint,
+ children,
+}: {
+ index: number
+ title: string
+ hint?: string
+ children: React.ReactNode
+}) {
+ return (
+ <section className="rounded-lg border border-border">
+ <header className="px-3 py-2 bg-muted/40 border-b border-border rounded-t-lg">
+ <p className="text-sm font-semibold text-foreground">
+ <span className="text-muted-foreground mr-1.5">{index}.</span>
+ {title}
+ </p>
+ {hint && <p className="text-xs text-muted-foreground mt-0.5">{hint}</p>}
+ </header>
+ <div className="p-3 space-y-3">{children}</div>
+ </section>
+ )
+}
+
+
+/** Pick none, one, or several: accounts or clients.
+ *
+ * Checkboxes rather than a multi-select control because the list is short
+ * and the state that matters is "nothing chosen", which a native
+ * multi-select renders as an empty box that reads like a mistake. Here it
+ * reads as a sentence: *any account*. */
+function MultiPicker({
+ options,
+ selected,
+ onChange,
+ empty,
+}: {
+ options: { id: string; label: string }[]
+ selected: string[]
+ onChange: (ids: string[]) => void
+ empty: string
+}) {
+ if (options.length === 0) return null
+ return (
+ <div className="mt-0.5 max-h-32 overflow-y-auto rounded-md border border-input divide-y divide-border">
+ {selected.length === 0 && (
+ <p className="px-3 py-1.5 text-xs text-muted-foreground italic">{empty}</p>
+ )}
+ {options.map((option) => (
+ <label
+ key={option.id}
+ className="flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer hover:bg-muted"
+ >
+ <input
+ type="checkbox"
+ checked={selected.includes(option.id)}
+ onChange={(e) =>
+ onChange(
+ e.target.checked
+ ? [...selected, option.id]
+ : selected.filter((id) => id !== option.id),
+ )
+ }
+ />
+ <span className="truncate">{option.label}</span>
+ </label>
+ ))}
+ </div>
+ )
+}
+
+
+interface EditorProps {
+ open: boolean
+ node: string
+ rule: ReconciliationRule | null
+ onClose: () => void
+}
+
+const EMPTY: ReconciliationConditions = {
+ counterparty: 'any',
+ amount: { match: 'exact' },
+ date: { before_days: 5, after_days: 30 },
+}
+
+function RuleEditor({ open, node, rule, onClose }: EditorProps) {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+ const creating = rule === null
+
+ const { data: accountList = [] } = useQuery<Account[]>({
+ queryKey: ['accounts'],
+ queryFn: () => accountsApi.list(),
+ })
+ const { data: payeeList = [] } = useQuery<Payee[]>({
+ queryKey: ['payees'],
+ queryFn: () => payeesApi.list(),
+ })
+
+ const [name, setName] = useState(rule?.name ?? '')
+ const [outcome, setOutcome] = useState<'link' | 'suggest'>(rule?.outcome ?? 'suggest')
+ const [trigger, setTrigger] = useState<Trigger>(rule?.trigger ?? 'money_arrives')
+ const [when, setWhen] = useState<ReconciliationConditions>(rule?.when ?? EMPTY)
+
+ // The dialog is mounted once and reused, so it has to be re-seeded
+ // whenever it opens, and the seed has to be *forgotten* when it closes.
+ // Without the second half, reopening the same rule after cancelling
+ // shows the abandoned edits as though they had been saved, which is a
+ // worse lie than losing them: the screen would claim a threshold the
+ // engine is not running.
+ const [seeded, setSeeded] = useState<string | null>(null)
+ const key = `${node}:${rule?.id ?? 'new'}`
+ if (!open && seeded !== null) setSeeded(null)
+ if (open && seeded !== key) {
+ setSeeded(key)
+ setName(rule?.name ?? '')
+ setOutcome(rule?.outcome ?? 'suggest')
+ setTrigger(rule?.trigger ?? 'money_arrives')
+ setWhen(rule?.when ?? EMPTY)
+ }
+
+ const save = useMutation({
+ mutationFn: async () => {
+ if (creating) {
+ return reconciliationApi.createRule({ node, name, outcome, trigger, when })
+ }
+ return reconciliationApi.updateRule(node, rule.id, { outcome, trigger, when })
+ },
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-rules'] })
+ toast.success(t('reconciliation.saved'))
+ onClose()
+ },
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ const amountMatch = when.amount?.match ?? 'exact'
+
+ /** One labelled control inside a step. Keeps the two amount questions
+ * visually distinct even though both are about money. */
+ const field = (label: string, hint: string | null, control: React.ReactNode) => (
+ <div>
+ <Label>{label}</Label>
+ {hint && <p className="text-xs text-muted-foreground mt-0.5 mb-1.5">{hint}</p>}
+ <div className={hint ? '' : 'mt-1'}>{control}</div>
+ </div>
+ )
+
+ const inputClass =
+ 'w-full px-3 py-2 text-sm border border-input rounded-md bg-background'
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => { if (!next) onClose() }}>
+ {/* Capped and scrolled, with the actions outside the scrolling part.
+ A rule with every section open is taller than a laptop viewport,
+ and a dialog whose Save button is below the fold with nothing to
+ scroll is a dialog you cannot save from. */}
+ <DialogContent className="max-w-lg max-h-[85vh] flex flex-col">
+ <DialogHeader>
+ <DialogTitle>
+ {creating
+ ? t('reconciliation.newRule')
+ : rule?.name || t(SHIPPED_NAME[rule?.id ?? ''] ?? 'reconciliation.rule.unknown')}
+ </DialogTitle>
+ </DialogHeader>
+
+ {/* Three questions, in the order a person asks them: when does this
+ run, which money does it look at, and what counts as a match.
+ The old flat list had two fields called "Amount" twenty pixels
+ apart: one about how close the payment must be to the invoice,
+ one about which payments the rule looks at. Same word, different
+ question. */}
+ <div className="space-y-4 flex-1 overflow-y-auto -mx-1 px-1">
+ <Step index={1} title={t('reconciliation.step.what')}>
+ {creating &&
+ field(
+ t('reconciliation.field.name'),
+ null,
+ <input
+ className={inputClass}
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder={t('reconciliation.field.namePlaceholder')}
+ />,
+ )}
+
+ {field(
+ t('reconciliation.field.trigger'),
+ t('reconciliation.field.triggerHint'),
+ <div className="space-y-1.5">
+ {(['money_arrives', 'invoice_issued', 'both'] as const).map((value) => (
+ <label
+ key={value}
+ className={cn(
+ 'flex items-start gap-2 px-3 py-2 rounded-md border cursor-pointer transition-colors',
+ trigger === value
+ ? 'border-primary bg-primary/5'
+ : 'border-input hover:bg-muted',
+ )}
+ >
+ <input
+ type="radio"
+ className="mt-1"
+ checked={trigger === value}
+ onChange={() => setTrigger(value)}
+ />
+ <span>
+ <span className="text-sm font-medium block">
+ {t(`reconciliation.trigger.${value}`)}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {t(`reconciliation.trigger.${value}Hint`)}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>,
+ )}
+
+ {field(
+ t('reconciliation.field.outcome'),
+ t('reconciliation.field.outcomeHint'),
+ <div className="flex gap-2">
+ {(['link', 'suggest'] as const).map((value) => (
+ <button
+ key={value}
+ type="button"
+ onClick={() => setOutcome(value)}
+ className={cn(
+ 'flex-1 px-3 py-2 rounded-md text-sm font-medium border transition-colors',
+ outcome === value
+ ? 'bg-primary text-primary-foreground border-primary'
+ : 'bg-background border-input text-muted-foreground hover:text-foreground',
+ )}
+ >
+ {t(
+ value === 'link'
+ ? 'reconciliation.outcome.link'
+ : 'reconciliation.outcome.suggest',
+ )}
+ </button>
+ ))}
+ </div>,
+ )}
+ </Step>
+
+ <Step
+ index={2}
+ title={t('reconciliation.step.which')}
+ hint={t('reconciliation.step.whichHint')}
+ >
+ {field(
+ t('reconciliation.field.accounts'),
+ null,
+ <MultiPicker
+ options={accountList.map((a) => ({ id: a.id, label: a.name }))}
+ selected={when.accounts?.in ?? []}
+ onChange={(ids) =>
+ setWhen({ ...when, accounts: ids.length ? { in: ids } : undefined })
+ }
+ empty={t('reconciliation.field.anyAccount')}
+ />,
+ )}
+
+ {field(
+ t('reconciliation.field.payees'),
+ null,
+ <MultiPicker
+ options={payeeList.map((p) => ({ id: p.id, label: p.name }))}
+ selected={when.payees?.in ?? []}
+ onChange={(ids) =>
+ setWhen({ ...when, payees: ids.length ? { in: ids } : undefined })
+ }
+ empty={t('reconciliation.field.anyPayee')}
+ />,
+ )}
+
+ {field(
+ t('reconciliation.field.direction'),
+ null,
+ <select
+ className={inputClass}
+ value={when.direction ?? 'any'}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ direction: e.target.value as 'any' | 'credit' | 'debit',
+ })
+ }
+ >
+ <option value="any">{t('reconciliation.direction.any')}</option>
+ <option value="credit">{t('reconciliation.direction.in')}</option>
+ <option value="debit">{t('reconciliation.direction.out')}</option>
+ </select>,
+ )}
+
+ {field(
+ t('reconciliation.field.currencyScope'),
+ null,
+ <>
+ <CodesInput
+ // Only what was typed is shouted. Uppercasing the
+ // placeholder too turns a hint into an instruction.
+ className={`${inputClass} [&:not(:placeholder-shown)]:uppercase`}
+ placeholder={t('reconciliation.field.currencyPlaceholder')}
+ value={when.currency?.in}
+ onChange={(codes) =>
+ setWhen({
+ ...when,
+ currency: {
+ ...(when.currency ?? { conversion: 'reject' }),
+ in: codes,
+ },
+ })
+ }
+ />
+ <label className="flex items-center gap-2 mt-1.5 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={!!when.currency?.foreign}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ currency: {
+ ...(when.currency ?? { conversion: 'reject' }),
+ foreign: e.target.checked || undefined,
+ },
+ })
+ }
+ />
+ {t('reconciliation.field.foreignOnly')}
+ </label>
+ </>,
+ )}
+
+ {field(
+ t('reconciliation.field.amountBand'),
+ t('reconciliation.field.amountBandHint'),
+ <div className="flex gap-2">
+ <input
+ type="number"
+ min={0}
+ className={inputClass}
+ placeholder={t('reconciliation.field.noMinimum')}
+ value={when.amount?.min ?? ''}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ amount: {
+ ...(when.amount ?? { match: 'exact' }),
+ min: e.target.value || undefined,
+ },
+ })
+ }
+ />
+ <input
+ type="number"
+ min={0}
+ className={inputClass}
+ placeholder={t('reconciliation.field.noMaximum')}
+ value={when.amount?.max ?? ''}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ amount: {
+ ...(when.amount ?? { match: 'exact' }),
+ max: e.target.value || undefined,
+ },
+ })
+ }
+ />
+ </div>,
+ )}
+
+ {field(
+ t('reconciliation.field.text'),
+ null,
+ <>
+ <WordsInput
+ className={inputClass}
+ placeholder={t('reconciliation.field.textContains')}
+ value={when.text?.contains}
+ onChange={(next) =>
+ setWhen({ ...when, text: { ...when.text, contains: next } })
+ }
+ />
+ <WordsInput
+ className={`${inputClass} mt-1.5`}
+ placeholder={t('reconciliation.field.textExcludes')}
+ value={when.text?.not_contains}
+ onChange={(next) =>
+ setWhen({ ...when, text: { ...when.text, not_contains: next } })
+ }
+ />
+ <p className="text-[11px] text-muted-foreground mt-1">
+ {t('reconciliation.field.textHint')}
+ </p>
+ </>,
+ )}
+ </Step>
+
+ <Step
+ index={3}
+ title={t('reconciliation.step.match')}
+ hint={t('reconciliation.step.matchHint')}
+ >
+ {field(
+ t('reconciliation.field.counterparty'),
+ null,
+ <select
+ className={inputClass}
+ value={when.counterparty ?? 'any'}
+ onChange={(e) =>
+ setWhen({ ...when, counterparty: e.target.value as 'any' | 'same_payee' })
+ }
+ >
+ <option value="any">{t('reconciliation.counterparty.any')}</option>
+ <option value="same_payee">{t('reconciliation.counterparty.samePayee')}</option>
+ </select>,
+ )}
+
+ {field(
+ t('reconciliation.field.amountMatch'),
+ t('reconciliation.field.amountMatchHint'),
+ <>
+ <div className="flex gap-2">
+ <select
+ className={inputClass}
+ value={amountMatch}
+ onChange={(e) => {
+ const match = e.target.value as
+ | 'exact'
+ | 'tolerance'
+ | 'ratio'
+ | 'partial'
+ | 'set'
+ const kept = { min: when.amount?.min, max: when.amount?.max }
+ setWhen({
+ ...when,
+ amount:
+ match === 'tolerance'
+ ? { match, percent: when.amount?.percent ?? '2', ...kept }
+ : match === 'partial'
+ ? {
+ match,
+ min_ratio: when.amount?.min_ratio ?? '0.05',
+ max_ratio: when.amount?.max_ratio ?? '0.95',
+ ...kept,
+ }
+ : match === 'set'
+ ? {
+ match,
+ max_invoices: when.amount?.max_invoices ?? 6,
+ percent: when.amount?.percent ?? '0',
+ ...kept,
+ }
+ : { match, ...kept },
+ })
+ }}
+ >
+ <option value="exact">{t('reconciliation.amount.exact')}</option>
+ <option value="partial">{t('reconciliation.amount.partial')}</option>
+ <option value="set">{t('reconciliation.amount.set')}</option>
+ <option value="tolerance">{t('reconciliation.amount.tolerance')}</option>
+ <option value="ratio">{t('reconciliation.amount.ratio')}</option>
+ </select>
+ {amountMatch === 'tolerance' && (
+ <div className="flex items-center gap-1 shrink-0">
+ <input
+ type="number"
+ min={0}
+ max={100}
+ step="0.5"
+ className="w-20 px-3 py-2 text-sm border border-input rounded-md bg-background"
+ value={when.amount?.percent ?? '2'}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ amount: {
+ ...(when.amount ?? { match: 'tolerance' }),
+ match: 'tolerance',
+ percent: e.target.value,
+ },
+ })
+ }
+ />
+ <span className="text-sm text-muted-foreground">%</span>
+ </div>
+ )}
+ </div>
+ {amountMatch === 'partial' && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {t('reconciliation.amount.partialHint')}
+ </p>
+ )}
+ {amountMatch === 'set' && (
+ <div className="mt-1.5 space-y-1.5">
+ <p className="text-xs text-muted-foreground">
+ {t('reconciliation.amount.setHint')}
+ </p>
+ <div className="flex gap-2 items-end">
+ <label className="flex-1">
+ <span className="text-xs text-muted-foreground">
+ {t('reconciliation.amount.setMax')}
+ </span>
+ <input
+ type="number"
+ min={2}
+ max={6}
+ className={`${inputClass} mt-0.5`}
+ value={when.amount?.max_invoices ?? 6}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ amount: {
+ ...(when.amount ?? { match: 'set' }),
+ match: 'set',
+ max_invoices: Number(e.target.value),
+ },
+ })
+ }
+ />
+ </label>
+ <label className="flex-1">
+ <span className="text-xs text-muted-foreground">
+ {t('reconciliation.amount.setFee')}
+ </span>
+ <div className="flex items-center gap-1 mt-0.5">
+ <input
+ type="number"
+ min={0}
+ max={20}
+ step="0.5"
+ className={inputClass}
+ value={when.amount?.percent ?? '0'}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ amount: {
+ ...(when.amount ?? { match: 'set' }),
+ match: 'set',
+ percent: e.target.value,
+ },
+ })
+ }
+ />
+ <span className="text-sm text-muted-foreground">%</span>
+ </div>
+ </label>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t('reconciliation.amount.setFeeHint')}
+ </p>
+ </div>
+ )}
+ {amountMatch === 'ratio' && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {t('reconciliation.amount.ratioHint')}
+ </p>
+ )}
+ </>,
+ )}
+
+ {field(
+ t('reconciliation.field.window'),
+ t('reconciliation.field.windowHint'),
+ <div className="flex gap-2">
+ <div className="flex-1">
+ <span className="text-xs text-muted-foreground">
+ {t('reconciliation.field.beforeDays')}
+ </span>
+ <input
+ type="number"
+ min={0}
+ max={365}
+ className={`${inputClass} mt-0.5`}
+ value={when.date?.before_days ?? 0}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ date: {
+ before_days: Number(e.target.value),
+ after_days: when.date?.after_days ?? 0,
+ },
+ })
+ }
+ />
+ </div>
+ <div className="flex-1">
+ <span className="text-xs text-muted-foreground">
+ {t('reconciliation.field.afterDays')}
+ </span>
+ <input
+ type="number"
+ min={0}
+ max={365}
+ className={`${inputClass} mt-0.5`}
+ value={when.date?.after_days ?? 0}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ date: {
+ before_days: when.date?.before_days ?? 0,
+ after_days: Number(e.target.value),
+ },
+ })
+ }
+ />
+ </div>
+ </div>,
+ )}
+
+ {field(
+ t('reconciliation.field.similarity'),
+ t('reconciliation.field.similarityHint'),
+ <input
+ type="number"
+ min={0}
+ max={1}
+ step="0.05"
+ className="w-28 px-3 py-2 text-sm border border-input rounded-md bg-background"
+ value={when.description_similarity?.min ?? ''}
+ placeholder={t('reconciliation.field.similarityOff')}
+ onChange={(e) =>
+ setWhen({
+ ...when,
+ description_similarity: e.target.value
+ ? { min: e.target.value }
+ : undefined,
+ })
+ }
+ />,
+ )}
+ </Step>
+ </div>
+
+ <div className="flex justify-end gap-2 pt-2 shrink-0 border-t border-border mt-2">
+ <Button variant="outline" onClick={onClose}>
+ {t('common.cancel')}
+ </Button>
+ <Button onClick={() => save.mutate()} disabled={save.isPending}>
+ {t('common.save')}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+export function ReconciliationRules({ canWrite }: { canWrite: boolean }) {
+ const { t } = useTranslation()
+ const queryClient = useQueryClient()
+ const [editing, setEditing] = useState<{ node: string; rule: ReconciliationRule | null } | null>(
+ null,
+ )
+ const [deleting, setDeleting] = useState<{
+ node: string
+ rule: ReconciliationRule
+ } | null>(null)
+ const [pending, setPending] = useState<{
+ file: ReconciliationPolicyFile
+ name: string
+ } | null>(null)
+ const fileInput = useRef<HTMLInputElement>(null)
+
+ const { data: nodes } = useQuery<ReconciliationNode[]>({
+ queryKey: ['reconciliation-rules'],
+ queryFn: reconciliationApi.rules,
+ })
+ // Loaded once for the whole list rather than per row: a rule naming
+ // three accounts should read as their names, not their ids.
+ const { data: accountList = [] } = useQuery<Account[]>({
+ queryKey: ['accounts'],
+ queryFn: () => accountsApi.list(),
+ })
+ const { data: payeeList = [] } = useQuery<Payee[]>({
+ queryKey: ['payees'],
+ queryFn: () => payeesApi.list(),
+ })
+ const names = { accounts: accountList, payees: payeeList }
+
+ const toggle = useMutation({
+ mutationFn: ({ node, rule }: { node: string; rule: ReconciliationRule }) =>
+ reconciliationApi.updateRule(node, rule.id, { enabled: !rule.enabled }),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['reconciliation-rules'] }),
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ // Moving one rule sends the whole order, because that is what the API
+ // takes: an order where some rules are placed and others fall back to
+ // where we shipped them reads correctly today and rearranges itself the
+ // day a default is inserted.
+ const move = useMutation({
+ mutationFn: ({ node, ids }: { node: string; ids: string[] }) =>
+ reconciliationApi.reorderRules(node, ids),
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ['reconciliation-rules'] }),
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ const reset = useMutation({
+ mutationFn: ({ node, id }: { node: string; id: string }) =>
+ reconciliationApi.resetRule(node, id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-rules'] })
+ toast.success(t('reconciliation.reset'))
+ },
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ const remove = useMutation({
+ mutationFn: ({ node, id }: { node: string; id: string }) =>
+ reconciliationApi.deleteRule(node, id),
+ onSuccess: () => {
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-rules'] })
+ setDeleting(null)
+ toast.success(t('rules.deleted'))
+ },
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ const exporting = useMutation({
+ mutationFn: () => reconciliationApi.exportRules(),
+ onSuccess: () => toast.success(t('reconciliation.exported')),
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ const importing = useMutation({
+ mutationFn: (file: ReconciliationPolicyFile) =>
+ reconciliationApi.importRules(file, true),
+ onSuccess: (result) => {
+ void queryClient.invalidateQueries({ queryKey: ['reconciliation-rules'] })
+ setPending(null)
+ toast.success(t('reconciliation.imported', result))
+ },
+ onError: (error) => toast.error(extractApiError(error, t('common.error'))),
+ })
+
+ async function readFile(file: File) {
+ try {
+ const parsed = JSON.parse(await file.text()) as ReconciliationPolicyFile
+ if (parsed.format !== POLICY_FORMAT || !Array.isArray(parsed.nodes)) {
+ // A categorization export dropped in here would otherwise arrive
+ // as a file with no rules and look like it worked.
+ toast.error(t('reconciliation.invalidImportFile'))
+ return
+ }
+ setPending({ file: parsed, name: file.name })
+ } catch {
+ toast.error(t('reconciliation.invalidImportFile'))
+ }
+ }
+
+ if (!nodes) return null
+
+ // One set is the shape today, and the card is laid out for it: no strip
+ // naming a list the card already names, and adding lives in the header.
+ const single = nodes.length === 1 ? nodes[0] : null
+
+ // Nothing here is live for this workspace. A card of rules that cannot
+ // act on anything, under a heading saying so, is furniture, and while
+ // there were two sets one of them was always live, which is why the
+ // page could carry the honest label instead.
+ if (!nodes.some((group) => group.active)) return null
+
+ return (
+ <>
+ {/* One card for matching, not one per set. The two sets are real:
+ separate ordered lists, matched against different kinds of
+ promise, but a whole card each, with its own frame, heading and
+ button, is a lot of furniture for a list that is often one rule
+ long. They are sections of the same thing. */}
+ <SectionCard>
+ <div className="px-4 sm:px-5 py-4 border-b border-border flex flex-wrap items-start justify-between gap-2">
+ <div>
+ <p className="text-sm font-semibold text-foreground">
+ {t('reconciliation.matchingTitle')}
+ </p>
+ <p className="text-xs text-muted-foreground mt-0.5">
+ {t('reconciliation.matchingHint')}
+ </p>
+ </div>
+ {/* A policy is worth more than one workspace. Somebody who has
+ worked out how their clients' banks actually behave should
+ be able to hand that to the next machine without retyping
+ eleven thresholds. */}
+ <div className="flex items-center gap-1.5 shrink-0">
+ <Button
+ size="sm"
+ variant="outline"
+ className="gap-1.5 h-8"
+ onClick={() => exporting.mutate()}
+ disabled={exporting.isPending}
+ >
+ <Download size={12} />
+ <span className="hidden sm:inline">{t('rules.export')}</span>
+ </Button>
+ {canWrite && single && (
+ // With one set, the card is the list, and adding belongs
+ // where the list is named; the same place, shape and word
+ // as on the categorization card above.
+ <Button
+ size="sm"
+ className="gap-1.5 h-8 order-last"
+ onClick={() => setEditing({ node: single.node, rule: null })}
+ >
+ <Plus size={13} />
+ <span className="hidden sm:inline">{t('rules.add')}</span>
+ </Button>
+ )}
+ {canWrite && (
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ className="gap-1.5 h-8"
+ onClick={() => fileInput.current?.click()}
+ disabled={importing.isPending}
+ >
+ <Upload size={12} />
+ <span className="hidden sm:inline">{t('rules.import')}</span>
+ </Button>
+ <input
+ ref={fileInput}
+ type="file"
+ accept="application/json,.json"
+ className="hidden"
+ data-testid="reconciliation-import-input"
+ onChange={(event) => {
+ const file = event.target.files?.[0]
+ if (file) void readFile(file)
+ event.target.value = ''
+ }}
+ />
+ </>
+ )}
+ </div>
+ </div>
+
+ {nodes.map((group) => (
+ <div key={group.node}>
+ {/* Only when there is more than one set to tell apart. A strip
+ naming the single list that follows it, inside a card that
+ already names it, is a heading for a heading. */}
+ {!single && (
+ <div className="px-4 sm:px-5 py-2 bg-muted/40 border-b border-border flex flex-wrap items-center justify-between gap-x-2 gap-y-1">
+ <p className="text-xs text-muted-foreground">
+ <span className="font-semibold text-foreground">
+ {t(NODE_TITLE[group.node] ?? group.node)}
+ </span>
+ <span className="mx-1.5">·</span>
+ {t(NODE_HINT[group.node] ?? '')}
+ {!group.active && (
+ <span className="ml-2 text-[10px] font-semibold bg-muted text-muted-foreground px-1.5 py-0.5 rounded-full">
+ {t('reconciliation.node.inactive')}
+ </span>
+ )}
+ </p>
+ {canWrite && (
+ // The same word as the list above, from the same key. Two
+ // names for one act made two lists of rules read as two
+ // features that happen to sit near each other.
+ <Button
+ size="sm"
+ variant="outline"
+ className="gap-1.5 h-8"
+ onClick={() => setEditing({ node: group.node, rule: null })}
+ >
+ <Plus size={13} />
+ <span className="hidden sm:inline">{t('rules.add')}</span>
+ </Button>
+ )}
+ </div>
+ )}
+
+ <div className="divide-y divide-border">
+ {group.rules.map((rule, index) => (
+ <div
+ key={rule.id}
+ className={cn(
+ 'px-4 sm:px-5 py-3 hover:bg-muted transition-colors',
+ canWrite && 'cursor-pointer',
+ !rule.enabled && 'opacity-55',
+ )}
+ onClick={() => { if (canWrite) setEditing({ node: group.node, rule }) }}
+ >
+ <div className="flex items-start justify-between gap-4">
+ {/* The position, shown because it *is* the mechanism: the
+ first rule that matches wins, so a band like "link
+ under 2%, ask between 2 and 5" is one rule placed
+ above another with no lower bound written anywhere.
+ An order you cannot see is a rule you cannot reason
+ about. */}
+ <div className="flex flex-col items-center shrink-0 pt-0.5">
+ <span className="text-xs font-semibold text-muted-foreground tabular-nums w-5 text-center">
+ {index + 1}
+ </span>
+ {canWrite && group.rules.length > 1 && (
+ <div
+ className="flex flex-col -space-y-1 mt-0.5"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <button
+ className="text-muted-foreground hover:text-foreground disabled:opacity-25 disabled:hover:text-muted-foreground"
+ disabled={index === 0 || move.isPending}
+ title={t('reconciliation.moveUp')}
+ onClick={() =>
+ move.mutate({ node: group.node, ids: swap(group.rules, index, index - 1) })
+ }
+ >
+ <ChevronUp size={13} />
+ </button>
+ <button
+ className="text-muted-foreground hover:text-foreground disabled:opacity-25 disabled:hover:text-muted-foreground"
+ disabled={index === group.rules.length - 1 || move.isPending}
+ title={t('reconciliation.moveDown')}
+ onClick={() =>
+ move.mutate({ node: group.node, ids: swap(group.rules, index, index + 1) })
+ }
+ >
+ <ChevronDown size={13} />
+ </button>
+ </div>
+ )}
+ </div>
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 mb-1 flex-wrap">
+ <p className="text-sm font-semibold text-foreground">
+ {rule.name || t(SHIPPED_NAME[rule.id] ?? 'reconciliation.rule.unknown')}
+ </p>
+ <OutcomeBadge outcome={rule.outcome} />
+ {rule.customised && (
+ <span className="text-[10px] font-semibold bg-sky-50 text-sky-700 dark:bg-sky-950 dark:text-sky-300 px-1.5 py-0.5 rounded-full">
+ {t(
+ rule.origin === 'custom'
+ ? 'reconciliation.yours'
+ : 'reconciliation.changed',
+ )}
+ </span>
+ )}
+ {!rule.enabled && (
+ <span className="text-[10px] font-semibold bg-muted text-muted-foreground px-1.5 py-0.5 rounded-full">
+ {t('rules.inactive')}
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground font-mono truncate">
+ {conditionSummary({ ...rule.when, trigger: rule.trigger }, t, names)}
+ </p>
+ </div>
+
+ {canWrite && (
+ <div
+ className="flex items-center gap-1 shrink-0"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {/* Two slots, in this order, on every rule in both
+ lists: stop it, then get rid of it. The same
+ icons in the same places, because a
+ categorization rule and a matching rule are the
+ same promise made twice and reading as two
+ unrelated features was the whole complaint. */}
+ <button
+ className={cn(
+ 'p-1.5 rounded-md transition-colors hover:bg-background',
+ rule.enabled
+ ? 'text-emerald-600 hover:text-emerald-700'
+ : 'text-muted-foreground hover:text-foreground',
+ )}
+ title={t(rule.enabled ? 'rules.turnOff' : 'rules.turnOn')}
+ onClick={() => toggle.mutate({ node: group.node, rule })}
+ disabled={toggle.isPending}
+ >
+ <Power size={13} />
+ </button>
+ {/* Only where there is something to undo. Putting
+ a rule back the way we ship it and getting rid
+ of it are different wishes, and one icon for
+ both meant a workspace could restore our
+ version of a rule or keep it, and nothing
+ else. */}
+ {rule.customised && rule.origin === 'default' && (
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-background transition-colors"
+ title={t('reconciliation.restore')}
+ onClick={() => reset.mutate({ node: group.node, id: rule.id })}
+ disabled={reset.isPending}
+ >
+ <RotateCcw size={13} />
+ </button>
+ )}
+ {/* No rule we refuse to remove, ours included. A
+ matching policy decides what happens to
+ somebody's money, and a default we happen to
+ believe in is not a reason to make them keep
+ it. What we keep is the name, so the list below
+ can offer it back. */}
+ <button
+ className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-950 transition-colors"
+ title={t('common.delete')}
+ onClick={() => setDeleting({ node: group.node, rule })}
+ disabled={remove.isPending}
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ ))}
+
+ {group.rules.length === 0 && (
+ <p className="px-4 sm:px-5 py-6 text-xs text-muted-foreground text-center">
+ {t('reconciliation.noneLeft')}
+ </p>
+ )}
+ </div>
+
+ {/* What was thrown away, and the way back. Deleting a shipped
+ rule leaves a tombstone rather than a hole, so we still know
+ its name, and without somewhere to show it, deleting one
+ would be a trap: the row is gone from the page and there is
+ nothing left to click. */}
+ {group.discarded.length > 0 && (
+ <div className="px-4 sm:px-5 py-2.5 bg-muted/30 border-t border-border flex flex-wrap items-center gap-x-2 gap-y-1">
+ <span className="text-[11px] text-muted-foreground">
+ {t('reconciliation.discarded')}
+ </span>
+ {group.discarded.map((gone) => (
+ <button
+ key={gone.id}
+ className="text-[11px] font-medium text-muted-foreground hover:text-foreground underline decoration-dotted underline-offset-2 disabled:opacity-50"
+ disabled={!canWrite || reset.isPending}
+ title={t('reconciliation.restore')}
+ onClick={() => reset.mutate({ node: group.node, id: gone.id })}
+ >
+ {t(SHIPPED_NAME[gone.id] ?? 'reconciliation.rule.unknown')}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ ))}
+ </SectionCard>
+
+ <DeleteConfirmationDialog
+ open={deleting !== null}
+ title={t('reconciliation.confirmDeleteTitle')}
+ description={t('reconciliation.confirmDeleteDescription', {
+ name:
+ deleting?.rule.name ||
+ t(SHIPPED_NAME[deleting?.rule.id ?? ''] ?? 'reconciliation.rule.unknown'),
+ })}
+ isPending={remove.isPending}
+ onClose={() => setDeleting(null)}
+ onConfirm={() =>
+ deleting && remove.mutate({ node: deleting.node, id: deleting.rule.id })
+ }
+ />
+
+ {/* Asked rather than assumed. Importing replaces the matching rules
+ this workspace has now (order is the mechanism here, and there
+ is no correct way to interleave two orderings), so a policy
+ somebody tuned is not something to overwrite on a mis-click. */}
+ <Dialog open={pending !== null} onOpenChange={(open) => { if (!open) setPending(null) }}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('reconciliation.importConfirmTitle')}</DialogTitle>
+ </DialogHeader>
+ <div className="space-y-3 text-sm text-muted-foreground">
+ <p>
+ {t('reconciliation.importConfirmDescription', {
+ count: (pending?.file.nodes ?? []).reduce(
+ (sum, node) => sum + node.rules.length,
+ 0,
+ ),
+ file: pending?.name ?? '',
+ })}
+ </p>
+ <p className="font-medium text-amber-600 dark:text-amber-400">
+ {t('reconciliation.importOverwriteWarning')}
+ </p>
+ </div>
+ <div className="flex justify-end gap-2 pt-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setPending(null)}
+ disabled={importing.isPending}
+ >
+ {t('common.cancel')}
+ </Button>
+ <Button
+ type="button"
+ variant="destructive"
+ onClick={() => { if (pending) importing.mutate(pending.file) }}
+ disabled={!pending || importing.isPending}
+ >
+ {t('rules.confirmOverwriteImport')}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <RuleEditor
+ open={editing !== null}
+ node={editing?.node ?? ''}
+ rule={editing?.rule ?? null}
+ onClose={() => setEditing(null)}
+ />
+ </>
+ )
+}
diff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsx
index 313e8880..d8d7955c 100644
--- a/frontend/src/components/rule-dialog.tsx
+++ b/frontend/src/components/rule-dialog.tsx
@@ -440,7 +440,10 @@ export function RuleDialog({
defaultActions.length ? defaultActions : [{ op: 'set_category', value: '' }]
)
const [priority, setPriority] = useState(String(rule?.priority ?? 0))
- const [isActive, setIsActive] = useState(rule?.is_active ?? true)
+ // Read, never written here: the row owns the switch. Kept so an edit
+ // preserves the rule's own state instead of resetting it to on, and so
+ // the preview can still say "this will match, but the rule is off".
+ const [isActive] = useState(rule?.is_active ?? true)
const [applyToExisting, setApplyToExisting] = useState(!rule)
const [overwriteExistingCategories, setOverwriteExistingCategories] = useState(false)
const [previewOpen, setPreviewOpen] = useState(false)
@@ -740,16 +743,14 @@ export function RuleDialog({
</div>
</div>
- {/* Active toggle */}
- <label className="flex items-center gap-2 cursor-pointer">
- <input
- type="checkbox"
- checked={isActive}
- onChange={(e) => setIsActive(e.target.checked)}
- className="h-4 w-4 rounded border-border"
- />
- <span className="text-sm text-foreground">{t('rules.ruleActive')}</span>
- </label>
+ {/* No "rule is active" box here any more. Whether a rule runs
+ is a property of the rule as it sits in the list, not of
+ the form you edit it in, and having it here meant turning
+ one off was: open it, scroll, find a checkbox, save a form
+ you did not otherwise want to touch. It is a switch on the
+ row now. `isActive` is still carried and sent back
+ untouched, so editing a stopped rule does not quietly
+ restart it. */}
<label className="flex items-center gap-2 cursor-pointer">
<input
diff --git a/frontend/src/lib/api-errors.ts b/frontend/src/lib/api-errors.ts
index db6fa857..d55cf70d 100644
--- a/frontend/src/lib/api-errors.ts
+++ b/frontend/src/lib/api-errors.ts
@@ -14,6 +14,14 @@ export function extractApiError(
if (data && typeof data === 'object' && 'detail' in data) {
const detail = (data as { detail: unknown }).detail
if (typeof detail === 'string') return detail
+ // `{ code, message }`, the shape every hand-raised error in the API
+ // uses. Without this branch a precise message ("Similarity runs from
+ // 0 to 1") was thrown away and the caller showed its generic
+ // fallback instead.
+ if (detail && typeof detail === 'object' && !Array.isArray(detail)) {
+ const message = (detail as { message?: unknown }).message
+ if (typeof message === 'string' && message.trim()) return message
+ }
if (Array.isArray(detail)) {
const message = detail.map((d: { msg?: string; loc?: string[] }) => {
const field = d.loc?.slice(-1)[0] ?? ''
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 7e4cc673..077def0e 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -77,6 +77,13 @@ import type {
InstallmentSeriesInput,
TransactionApplyScope,
InvoiceAttachment,
+ ReconciliationNode,
+ ReconciliationPolicyFile,
+ ReconciliationRule,
+ ReconciliationRuleDraft,
+ ReconciliationRulePatch,
+ ReconciliationSuggestion,
+ ReconciliationHistoryEvent,
} from '@/types'
const api = axios.create({
@@ -994,6 +1001,109 @@ export const rules = {
}
// Recurring Transactions
+// Reconciliation: the rules matching follows, and the matches it was
+// not confident enough to make on its own.
+export const reconciliation = {
+ rules: async (): Promise<ReconciliationNode[]> => {
+ const { data } = await api.get('/reconciliation/rules')
+ return data
+ },
+ updateRule: async (
+ node: string,
+ id: string,
+ patch: ReconciliationRulePatch,
+ ): Promise<ReconciliationRule> => {
+ const { data } = await api.patch(
+ `/reconciliation/rules/${encodeURIComponent(node)}/${encodeURIComponent(id)}`,
+ patch,
+ )
+ return data
+ },
+ /** Set the order rules are tried in. Names every rule in the set: the
+ * first match wins, so a half-implicit order rearranges itself the day
+ * a new default ships. */
+ reorderRules: async (
+ node: string,
+ order: string[],
+ ): Promise<ReconciliationRule[]> => {
+ const { data } = await api.put(
+ `/reconciliation/rules/${encodeURIComponent(node)}/order`,
+ { order },
+ )
+ return data
+ },
+ createRule: async (rule: ReconciliationRuleDraft): Promise<ReconciliationRule> => {
+ const { data } = await api.post('/reconciliation/rules', rule)
+ return data
+ },
+ /** Get rid of a rule, whoever wrote it: ours included. What happens
+ * underneath differs (a rule of your own is a row and goes; one of
+ * ours ships in the image, so a tombstone records that this workspace
+ * does not run it) but that is our problem, not something to make a
+ * person learn. */
+ deleteRule: async (node: string, id: string): Promise<void> => {
+ await api.delete(
+ `/reconciliation/rules/${encodeURIComponent(node)}/${encodeURIComponent(id)}`,
+ )
+ },
+ /** Forget everything this workspace did to one of our rules (a moved
+ * threshold, a place in the order, a deletion), and go back to
+ * whatever we ship today. */
+ resetRule: async (node: string, id: string): Promise<void> => {
+ await api.post(
+ `/reconciliation/rules/${encodeURIComponent(node)}/${encodeURIComponent(id)}/reset`,
+ )
+ },
+ exportRules: async (): Promise<void> => {
+ const { data } = await api.get('/reconciliation/rules/export', {
+ responseType: 'blob',
+ })
+ const blob = new Blob([data], { type: 'application/json;charset=utf-8;' })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `securo-reconciliation-rules-${new Date().toISOString().slice(0, 10)}.json`
+ document.body.appendChild(a)
+ a.click()
+ document.body.removeChild(a)
+ URL.revokeObjectURL(url)
+ },
+ /** Replaces rather than merges: order is the mechanism here, and there
+ * is no correct way to interleave two orderings. Hence `overwrite`. */
+ importRules: async (
+ payload: ReconciliationPolicyFile,
+ overwrite = false,
+ ): Promise<{ imported: number; skipped: number }> => {
+ const { data } = await api.post('/reconciliation/rules/import', {
+ payload,
+ overwrite,
+ })
+ return data
+ },
+ /** What matching did, newest first. `expectationId` narrows it to
+ * everything that ever happened to one invoice. */
+ history: async (
+ expectationId?: string,
+ ): Promise<ReconciliationHistoryEvent[]> => {
+ const { data } = await api.get('/reconciliation/history', {
+ params: expectationId ? { expectation_id: expectationId } : undefined,
+ })
+ return data
+ },
+ suggestions: async (): Promise<ReconciliationSuggestion[]> => {
+ const { data } = await api.get('/reconciliation/suggestions')
+ return data
+ },
+ accept: async (id: string): Promise<ReconciliationSuggestion> => {
+ const { data } = await api.post(`/reconciliation/suggestions/${id}/accept`)
+ return data
+ },
+ decline: async (id: string): Promise<ReconciliationSuggestion> => {
+ const { data } = await api.post(`/reconciliation/suggestions/${id}/decline`)
+ return data
+ },
+}
+
export const recurring = {
list: async (): Promise<RecurringTransaction[]> => {
const { data } = await api.get('/recurring-transactions')
diff --git a/frontend/src/lib/invoice-suggestions.ts b/frontend/src/lib/invoice-suggestions.ts
new file mode 100644
index 00000000..9b27a5ec
--- /dev/null
+++ b/frontend/src/lib/invoice-suggestions.ts
@@ -0,0 +1,23 @@
+import type { ReconciliationSuggestion } from '@/types'
+
+/** Every question that names this invoice, whether it names it alone or
+ * alongside others. A payout settling three invoices is one question,
+ * and it has to be findable from any of the three.
+ *
+ * Here rather than beside the component that renders it: a file that
+ * exports both a component and a plain function loses fast refresh for
+ * the whole module, and this half is pure enough to be tested without a
+ * render.
+ */
+export function suggestionsFor(
+ suggestions: ReconciliationSuggestion[],
+ invoiceId: string,
+): ReconciliationSuggestion[] {
+ return suggestions.filter(
+ (s) =>
+ (s.expectation_kind === 'invoice' && s.expectation_id === invoiceId) ||
+ (s.covers ?? []).some(
+ (c) => c.expectation_kind === 'invoice' && c.expectation_id === invoiceId,
+ ),
+ )
+}
diff --git a/frontend/src/lib/invoice-utils.test.ts b/frontend/src/lib/invoice-utils.test.ts
index bf26cfd4..8905353a 100644
--- a/frontend/src/lib/invoice-utils.test.ts
+++ b/frontend/src/lib/invoice-utils.test.ts
@@ -351,3 +351,18 @@ describe('documentProvenance', () => {
expect(documentProvenance(' ')).toEqual({ kind: 'uploaded' })
})
})
+
+describe('documentProvenance, on the page we drew ourselves', () => {
+ it('names it rather than printing the source id', () => {
+ // It read as the literal "De issued · Sep 02" on screen: a machine
+ // name is right for somebody else's integration and wrong for us.
+ expect(documentProvenance('issued')).toEqual({ kind: 'ours' })
+ })
+
+ it('still treats every other source as the system that sent it', () => {
+ expect(documentProvenance('issued-by-hand')).toEqual({
+ kind: 'system',
+ name: 'issued-by-hand',
+ })
+ })
+})
diff --git a/frontend/src/lib/invoice-utils.ts b/frontend/src/lib/invoice-utils.ts
index b3f58061..f25dd452 100644
--- a/frontend/src/lib/invoice-utils.ts
+++ b/frontend/src/lib/invoice-utils.ts
@@ -192,17 +192,24 @@ export function documentSource(
return origin === 'imported' ? 'missing' : 'rendered'
}
+/** The source stamped on the page we render and file at the moment an
+ * invoice is issued. */
+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
* shown as it is rather than translated — renaming somebody's system in
* our own words helps nobody trying to work out which integration
- * delivered which file. Only the absence of one is our word: a file
- * with no source was uploaded here by hand.
+ * delivered which file. Two sources are our word rather than theirs: a
+ * file with no source was uploaded here by hand, and one stamped
+ * `issued` is the page we drew ourselves, which read as the literal
+ * "De issued" until it was given a name.
*/
export function documentProvenance(
source: string | null | undefined,
-): { kind: 'uploaded' } | { kind: 'system'; name: string } {
+): { kind: 'uploaded' } | { kind: 'ours' } | { kind: 'system'; name: string } {
const name = (source ?? '').trim()
+ if (name === ISSUED_BY_US) return { kind: 'ours' }
return name ? { kind: 'system', name } : { kind: 'uploaded' }
}
diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.json
index 37148cc1..2bf819ba 100644
--- a/frontend/src/locales/de.json
+++ b/frontend/src/locales/de.json
@@ -372,7 +372,14 @@
"fromSystem": "Von {{source}} · {{date}}",
"fromUpload": "Hochgeladen · {{date}}"
},
- "draftSaved": "Entwurf gespeichert"
+ "draftSaved": "Entwurf gespeichert",
+ "suggestions": {
+ "title_one": "Eine Zahlung könnte diese Rechnung begleichen",
+ "title_other": "{{count}} Zahlungen könnten diese Rechnung begleichen",
+ "wouldApply": "würde {{amount}} anrechnen",
+ "alsoCovers_one": "deckt auch {{count}} weitere Rechnung",
+ "alsoCovers_other": "deckt auch {{count}} weitere Rechnungen"
+ }
},
"collections": {
"title": "Sammlungen",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "Umbuchungen zählen nicht als Einnahmen oder Ausgaben",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Diese Transaktion begleicht eine Rechnung. Öffnen.",
+ "suggestionBadge": "Frage",
+ "suggestionBadgeTooltip": "Eine Zahlung könnte diese Rechnung begleichen. Öffnen Sie die Warteschlange."
},
"accounts": {
"title": "Konten",
@@ -1137,6 +1146,7 @@
"createMissingCategories": "Auch die benötigten Standardkategorien erstellen",
"duplicateName": "Eine Regel mit diesem Namen existiert bereits",
"sectionTitle": "Kategorisierungsregeln",
+ "sectionHint": "Wie Transaktionen kategorisiert werden.",
"resetAndReapplyAll": "Zurücksetzen und erneut anwenden",
"confirmResetAndReapplyAll": "Kategorien, Notizen und durch Regeln geänderte Beschreibungen übereinstimmender Transaktionen zurücksetzen und anschließend alle aktiven Regeln erneut anwenden?",
"add": "Hinzufügen",
@@ -1179,7 +1189,10 @@
"ignoreActionHint": "(kein Wert erforderlich)",
"selectCategory": "Kategorie auswählen...",
"selectAccount": "Konto auswählen...",
- "ruleActive": "Regel aktiv",
+ "turnOn": "Einschalten",
+ "turnOff": "Ausschalten",
+ "turnedOn": "Regel aktiviert",
+ "turnedOff": "Regel deaktiviert",
"noConditions": "(keine Bedingungen)",
"noActions": "(keine Aktionen)",
"fieldDescription": "Beschreibung",
@@ -1214,7 +1227,12 @@
"importConfirmTitle": "Kategorisierungsregeln importieren?",
"importConfirmDescription": "Die Datei {{file}} enthält {{count}} Regeln.",
"importOverwriteWarning": "Der Import überschreibt deine aktuellen Kategorisierungsregeln. Dies kann nicht rückgängig gemacht werden.",
- "confirmOverwriteImport": "Überschreiben und importieren"
+ "confirmOverwriteImport": "Überschreiben und importieren",
+ "tab": {
+ "rules": "Regeln",
+ "queue": "Wartet auf Sie",
+ "history": "Verlauf"
+ }
},
"categories": {
"title": "Kategorien",
@@ -2239,5 +2257,200 @@
"subtitle": "Füge eine Verbindung hinzu, um Securo auf dein lokales Ollama, OpenAI, Anthropic oder einen OpenAI-kompatiblen Endpunkt zu verweisen."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Rechnungen",
+ "invoicesHint": "gegen das, was Sie einnehmen und zahlen müssen",
+ "recurring": "Wiederkehrend",
+ "recurringHint": "gegen das, was Sie ohnehin erwartet haben",
+ "inactive": "Hier nicht in Gebrauch"
+ },
+ "rule": {
+ "sameClientExact": "Bekannte Person, exakter Betrag",
+ "netOfWithholding": "Bekannte Person, mit Quellensteuer gezahlt",
+ "exactAmountAnyClient": "Exakter Betrag, beliebige Person",
+ "similarDescription": "Ähnlicher Betrag und ähnlicher Text",
+ "sameAccountExact": "Gleiches Konto, exakter Betrag",
+ "unknown": "Regel",
+ "partPayment": "Bekannte Person, Teil des Betrags",
+ "severalInvoices": "Bekannte Person, mehrere Rechnungen auf einmal"
+ },
+ "outcome": {
+ "link": "Verknüpft selbst",
+ "suggest": "Schlägt vor"
+ },
+ "cond": {
+ "samePayee": "die Person ist die auf der Rechnung",
+ "sameAccount": "dasselbe Konto",
+ "amountExact": "der Betrag stimmt genau",
+ "amountTolerance": "der Betrag liegt innerhalb von {{percent}}%",
+ "amountRatio": "der Betrag stimmt abzüglich Quellensteuer",
+ "window": "bis zu {{before}} Tage früher, {{after}} Tage später",
+ "similarity": "der Text ist mindestens {{min}} ähnlich",
+ "none": "keine Bedingungen",
+ "accounts": "auf {{names}}",
+ "payees": "für {{names}}",
+ "moneyIn": "eingehendes Geld",
+ "moneyOut": "ausgehendes Geld",
+ "foreign": "in Fremdwährung",
+ "currencyIn": "in {{codes}}",
+ "atLeast": "ab {{value}}",
+ "atMost": "bis {{value}}",
+ "textContains": "im Auszug steht „{{text}}“",
+ "textExcludes": "im Auszug steht nicht „{{text}}“",
+ "onArrival": "wenn Geld eingeht oder abgeht",
+ "onIssue": "wenn eine Rechnung gestellt wird",
+ "amountPartial": "der Betrag deckt einen Teil des Offenen",
+ "amountSet": "bis zu {{count}} Rechnungen ergeben die Summe"
+ },
+ "newRule": "Neue Abgleichregel",
+ "saved": "Regel gespeichert",
+ "reset": "Regel zurückgesetzt",
+ "restore": "Auf Standard zurücksetzen",
+ "changed": "Geändert",
+ "yours": "Ihre",
+ "field": {
+ "name": "Name",
+ "namePlaceholder": "z. B. Bekannte Person, ähnlicher Betrag",
+ "outcome": "Was passiert, wenn sie zutrifft",
+ "outcomeHint": "Verknüpfen bucht von selbst. Vorschlagen schickt es in die Liste unten, damit Sie es bestätigen.",
+ "counterparty": "Wer gezahlt oder erhalten hat",
+ "amount": "Betrag",
+ "window": "Zulässiger Abstand zwischen den Daten",
+ "windowHint": "Verspätung zählt ab dem Fälligkeitstag, Vorauszahlung ab dem Tag der Rechnungsstellung, wer also einen Tag nach Ausstellung zahlt, ist nicht Wochen zu früh.",
+ "beforeDays": "Tage früher",
+ "afterDays": "Tage später",
+ "similarity": "Textähnlichkeit",
+ "similarityHint": "Von 0 bis 1. Leer lassen, um den Text zu ignorieren.",
+ "similarityOff": "aus",
+ "scope": "Wann diese Regel gilt",
+ "scopeHint": "Leer lassen, damit sie für alles gilt",
+ "accounts": "Bankkonten",
+ "anyAccount": "Beliebiges Konto",
+ "payees": "Personen",
+ "anyPayee": "Beliebige Person",
+ "direction": "Ein- oder Ausgang",
+ "currencyScope": "Nur in diesen Währungen",
+ "currencyPlaceholder": "z. B. USD, EUR",
+ "foreignOnly": "Nur Währungen außer der dieses Arbeitsbereichs",
+ "amountBand": "Nur Beträge in diesem Bereich",
+ "noMinimum": "kein Minimum",
+ "noMaximum": "kein Maximum",
+ "text": "Text im Kontoauszug",
+ "textContains": "muss enthalten …",
+ "textExcludes": "darf nicht enthalten …",
+ "textHint": "Mehrere, durch Kommas getrennt, bedeutet eines davon.",
+ "trigger": "Wann wir suchen",
+ "triggerHint": "Der Abgleich passiert zu zwei Zeitpunkten, und die Indizien sind nicht dieselben.",
+ "amountMatch": "Wie genau der Betrag stimmen muss",
+ "amountMatchHint": "Verglichen mit dem noch offenen Betrag, nicht mit der ursprünglichen Summe.",
+ "amountBandHint": "Über die Zahlung selbst: eine Größe, die diese Regel behandeln soll oder eben nicht."
+ },
+ "counterparty": {
+ "any": "Beliebig",
+ "samePayee": "Die Person auf der Rechnung"
+ },
+ "amount": {
+ "exact": "Genau der offene Betrag",
+ "tolerance": "Innerhalb einer Toleranz",
+ "ratio": "Abzüglich Quellensteuer",
+ "ratioHint": "Nutzt die Quellensteuersätze Ihres Landes. Solange es keine gibt, trifft die Regel auf nichts zu.",
+ "partial": "Ein Teil des offenen Betrags",
+ "partialHint": "Für alle, die in Raten zahlen. Was übrig bleibt, bleibt offen, und die nächste Zahlung passt genau.",
+ "set": "Mehrere Rechnungen zusammen",
+ "setHint": "Für eine Zahlung, die mehr als eine Rechnung deckt. Passt mehr als eine Kombination, fragen wir, statt zu wählen.",
+ "setMax": "Höchstens so viele Rechnungen",
+ "setFee": "Gebühr zulassen von",
+ "setFeeHint": "Ein Anteil am Rechnungswert, für eine Zahlung, die netto nach Abzug fließt. Null bedeutet, die Summe muss exakt sein."
+ },
+ "queue": {
+ "title": "Wartet auf Sie",
+ "hint": "Zuordnungen, die Ihre Bestätigung brauchen.",
+ "empty": "Nichts zu prüfen. Alles hat von selbst gepasst.",
+ "aPayment": "Eine Zahlung",
+ "maySettle": "begleicht vielleicht {{name}}",
+ "mayBe": "ist vielleicht {{name}}",
+ "accept": "Verknüpfen",
+ "declineHint": "Passt nicht. Dieses Paar wird nicht erneut vorgeschlagen.",
+ "linked": "Verknüpft",
+ "declined": "Verworfen. Wir fragen nicht noch einmal",
+ "covers": "deckt"
+ },
+ "evidence": {
+ "amountExact": "Betrag stimmt genau",
+ "amountOff": "erwartet {{expected}}, bewegt {{moved}}",
+ "knownPayer": "bekannte Person",
+ "unknownPayer": "Person nicht erkannt",
+ "sameDay": "gleicher Tag",
+ "daysApart": "{{days}} Tage Abstand"
+ },
+ "direction": {
+ "any": "Egal",
+ "in": "Eingehendes Geld",
+ "out": "Ausgehendes Geld"
+ },
+ "step": {
+ "what": "Was diese Regel ist",
+ "which": "Welches Geld sie ansieht",
+ "whichHint": "Alles leer lassen, dann sieht sie alles an",
+ "match": "Wann es als Treffer gilt",
+ "matchHint": "Wie genau Zahlung und Versprechen zusammenpassen müssen"
+ },
+ "trigger": {
+ "money_arrives": "Wenn Geld eingeht oder abgeht",
+ "money_arrivesHint": "Die Zahlung taucht im Kontoauszug auf und wir suchen die Rechnung, die sie begleicht.",
+ "invoice_issued": "Wenn eine Rechnung gestellt wird",
+ "invoice_issuedHint": "Die Zahlung kam zuerst und die Rechnung danach, also schauen wir zurück auf Geld, das schon da war.",
+ "both": "Zu beiden Zeitpunkten",
+ "bothHint": "Die Regel gilt in beide Richtungen."
+ },
+ "history": {
+ "title": "Was der Abgleich getan hat",
+ "hint": "Neueste zuerst.",
+ "byPerson": "von Ihnen",
+ "byRules": "von den Regeln",
+ "more": "{{count}} weitere anzeigen",
+ "less": "Weniger anzeigen",
+ "action": {
+ "linked": "Mit {{name}} verknüpft",
+ "accepted": "Vorschlag für {{name}} angenommen",
+ "suggested": "Für {{name}} vorgeschlagen",
+ "declined": "Vorschlag für {{name}} verworfen",
+ "expired": "Vorschlag abgelaufen: {{name}}",
+ "unlinked": "Von {{name}} getrennt"
+ },
+ "empty": "Noch nichts. Das füllt sich, während der Abgleich verknüpft, fragt und beantwortet wird."
+ },
+ "moveUp": "Diese früher prüfen",
+ "moveDown": "Diese später prüfen",
+ "matchingTitle": "Abgleichregeln",
+ "matchingHint": "Wie jede Zahlung mit dem verknüpft wird, was sie begleicht.",
+ "pair": {
+ "owed": "Was offen ist",
+ "arrived": "Was sich bewegt hat",
+ "draftInvoice": "Rechnungsentwurf",
+ "recurringBill": "Wiederkehrende Rechnung",
+ "noMoney": "Keine Buchung dazu.",
+ "stillOpen": "noch offen",
+ "thisPayment": "diese Zahlung",
+ "wasApplied": "angerechnet",
+ "wouldRemain": "bliebe offen",
+ "wouldClose": "gleicht sie aus",
+ "thePayment": "die Zahlung",
+ "acrossInvoices": "auf {{count}} Rechnungen",
+ "dueOn": "fällig {{date}}",
+ "totalOf": "Gesamt {{amount}}"
+ },
+ "discarded": "Aus diesem Arbeitsbereich gelöscht:",
+ "noneLeft": "Keine Abgleichsregeln mehr in dieser Gruppe. Hier wird nichts automatisch zugeordnet.",
+ "confirmDeleteTitle": "Diese Regel löschen?",
+ "confirmDeleteDescription": "„{{name}}“ entscheidet nichts mehr. Wenn es eine unserer Regeln ist, können Sie sie später zurückholen.",
+ "exported": "Abgleichsregeln heruntergeladen",
+ "imported": "{{imported}} Regeln importiert ({{skipped}} übersprungen)",
+ "invalidImportFile": "Das ist keine Datei mit Abgleichsregeln",
+ "importConfirmTitle": "Abgleichsregeln importieren?",
+ "importConfirmDescription": "Die Datei {{file}} enthält {{count}} Regeln.",
+ "importOverwriteWarning": "Der Import ersetzt die Abgleichsregeln dieses Arbeitsbereichs samt ihrer Reihenfolge. Das lässt sich nicht rückgängig machen."
}
}
diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.json
index 8d7e0ca3..461d560e 100644
--- a/frontend/src/locales/el.json
+++ b/frontend/src/locales/el.json
@@ -372,7 +372,14 @@
"fromSystem": "Από {{source}} · {{date}}",
"fromUpload": "Μεταφορτώθηκε · {{date}}"
},
- "draftSaved": "Το πρόχειρο αποθηκεύτηκε"
+ "draftSaved": "Το πρόχειρο αποθηκεύτηκε",
+ "suggestions": {
+ "title_one": "Μια πληρωμή μπορεί να εξοφλεί αυτό το τιμολόγιο",
+ "title_other": "{{count}} πληρωμές μπορεί να εξοφλούν αυτό το τιμολόγιο",
+ "wouldApply": "θα εφάρμοζε {{amount}}",
+ "alsoCovers_one": "καλύπτει επίσης {{count}} ακόμη τιμολόγιο",
+ "alsoCovers_other": "καλύπτει επίσης {{count}} ακόμη τιμολόγια"
+ }
},
"collections": {
"title": "Συλλογές",
@@ -984,7 +991,9 @@
"calendarTransfersExcluded": "Οι μεταφορές δεν υπολογίζονται ως έσοδα ή έξοδα",
"invoiceBadge": "Τιμολόγιο {{number}}",
"invoiceBadgeNoNumber": "Τιμολόγιο",
- "invoiceBadgeTooltip": "Αυτή η συναλλαγή εξοφλεί ένα τιμολόγιο. Ανοίξτε το."
+ "invoiceBadgeTooltip": "Αυτή η συναλλαγή εξοφλεί ένα τιμολόγιο. Ανοίξτε το.",
+ "suggestionBadge": "Ερώτηση",
+ "suggestionBadgeTooltip": "Μια πληρωμή μπορεί να εξοφλεί ένα τιμολόγιο. Ανοίξτε την ουρά για να απαντήσετε."
},
"budgets": {
"title": "Προϋπολογισμοί",
@@ -1178,7 +1187,6 @@
"ignoreActionHint": "(δεν απαιτείται τιμή)",
"selectCategory": "Επιλογή κατηγορίας...",
"selectAccount": "Επιλογή λογαριασμού...",
- "ruleActive": "Ενεργός κανόνας",
"noConditions": "(χωρίς συνθήκες)",
"noActions": "(χωρίς ενέργειες)",
"fieldDescription": "Περιγραφή",
@@ -1213,7 +1221,17 @@
"importConfirmTitle": "Εισαγωγή κανόνων κατηγοριοποίησης;",
"importConfirmDescription": "Το αρχείο {{file}} περιέχει {{count}} κανόνες.",
"importOverwriteWarning": "Η εισαγωγή θα αντικαταστήσει τους τρέχοντες κανόνες κατηγοριοποίησης. Αυτό δεν μπορεί να αναιρεθεί.",
- "confirmOverwriteImport": "Αντικατάσταση και εισαγωγή"
+ "confirmOverwriteImport": "Αντικατάσταση και εισαγωγή",
+ "sectionHint": "Πώς κατηγοριοποιούνται οι συναλλαγές.",
+ "turnOn": "Ενεργοποίηση",
+ "turnOff": "Απενεργοποίηση",
+ "turnedOn": "Ο κανόνας ενεργοποιήθηκε",
+ "turnedOff": "Ο κανόνας απενεργοποιήθηκε",
+ "tab": {
+ "rules": "Κανόνες",
+ "queue": "Σε αναμονή",
+ "history": "Ιστορικό"
+ }
},
"categories": {
"title": "Κατηγορίες",
@@ -2238,5 +2256,200 @@
"subtitle": "Προσθέστε μια σύνδεση για να κατευθύνετε το Securo στο τοπικό σας Ollama, OpenAI, Anthropic ή οποιοδήποτε συμβατό τελικό σημείο OpenAI."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Τιμολόγια",
+ "invoicesHint": "σε σχέση με όσα έχετε να εισπράξετε και να πληρώσετε",
+ "recurring": "Επαναλαμβανόμενα",
+ "recurringHint": "σε σχέση με όσα ήδη περιμένατε",
+ "inactive": "Δεν χρησιμοποιείται εδώ"
+ },
+ "rule": {
+ "sameClientExact": "Γνωστό πρόσωπο, ακριβές ποσό",
+ "netOfWithholding": "Γνωστό πρόσωπο, πληρωμή με παρακράτηση",
+ "exactAmountAnyClient": "Ακριβές ποσό, οποιοσδήποτε",
+ "similarDescription": "Κοντινό ποσό και παρόμοια περιγραφή",
+ "sameAccountExact": "Ίδιος λογαριασμός, ακριβές ποσό",
+ "unknown": "Άγνωστος κανόνας",
+ "partPayment": "Γνωστό πρόσωπο, μέρος του ποσού",
+ "severalInvoices": "Γνωστό πρόσωπο, πολλά τιμολόγια μαζί"
+ },
+ "outcome": {
+ "link": "Συνδέει μόνο του",
+ "suggest": "Προτείνει"
+ },
+ "cond": {
+ "samePayee": "το πρόσωπο είναι αυτό του τιμολογίου",
+ "sameAccount": "ο ίδιος λογαριασμός",
+ "amountExact": "το ποσό ταιριάζει ακριβώς",
+ "amountTolerance": "το ποσό είναι εντός {{percent}}%",
+ "amountRatio": "το ποσό ταιριάζει μετά την παρακράτηση",
+ "window": "έως {{before}} ημέρες νωρίτερα, {{after}} ημέρες αργότερα",
+ "similarity": "η περιγραφή μοιάζει τουλάχιστον {{min}}",
+ "none": "καμία συνθήκη",
+ "accounts": "μόνο {{names}}",
+ "payees": "μόνο {{names}}",
+ "moneyIn": "μόνο εισερχόμενα χρήματα",
+ "moneyOut": "μόνο εξερχόμενα χρήματα",
+ "foreign": "σε ξένο νόμισμα",
+ "currencyIn": "μόνο σε {{codes}}",
+ "atLeast": "τουλάχιστον {{value}}",
+ "atMost": "το πολύ {{value}}",
+ "textContains": "το κείμενο περιέχει «{{text}}»",
+ "textExcludes": "το κείμενο δεν περιέχει «{{text}}»",
+ "onArrival": "όταν τα χρήματα μπαίνουν ή βγαίνουν",
+ "onIssue": "όταν εκδίδεται τιμολόγιο",
+ "amountPartial": "το ποσό καλύπτει μέρος του οφειλόμενου",
+ "amountSet": "έως {{count}} τιμολόγια αθροίζουν σε αυτό το ποσό"
+ },
+ "newRule": "Νέος κανόνας αντιστοίχισης",
+ "saved": "Ο κανόνας αποθηκεύτηκε",
+ "reset": "Ο κανόνας επαναφέρθηκε",
+ "restore": "Επαναφορά στην προεπιλογή",
+ "changed": "Τροποποιημένος",
+ "yours": "Δικός σας",
+ "field": {
+ "name": "Όνομα",
+ "namePlaceholder": "π.χ. Γνωστό πρόσωπο, κοντινό ποσό",
+ "outcome": "Τι γίνεται όταν ταιριάζει",
+ "outcomeHint": "Το «Συνδέει μόνο του» εξοφλεί χωρίς ερώτηση. Το «Προτείνει» στέλνει στη λίστα παρακάτω για επιβεβαίωση.",
+ "counterparty": "Ποιος πλήρωσε ή πληρώθηκε",
+ "amount": "Ποσό",
+ "window": "Παράθυρο ημερομηνιών",
+ "windowHint": "Η καθυστέρηση μετράει από τη λήξη, η πρόωρη πληρωμή από την ημέρα έκδοσης του τιμολογίου, οπότε μια πληρωμή την επομένη της έκδοσης δεν είναι εβδομάδες νωρίτερα.",
+ "beforeDays": "Ημέρες νωρίτερα",
+ "afterDays": "Ημέρες αργότερα",
+ "similarity": "Ομοιότητα περιγραφής",
+ "similarityHint": "Το 0 δεν ελέγχει τίποτα, το 1 απαιτεί ταύτιση.",
+ "similarityOff": "ανενεργό",
+ "scope": "Σε ποια χρήματα ισχύει",
+ "scopeHint": "Αφήστε τα όλα κενά και κοιτάζει όλα τα χρήματα",
+ "accounts": "Τραπεζικοί λογαριασμοί",
+ "anyAccount": "Οποιοσδήποτε λογαριασμός",
+ "payees": "Πρόσωπα",
+ "anyPayee": "Οποιοσδήποτε",
+ "direction": "Κατεύθυνση",
+ "currencyScope": "Μόνο σε αυτά τα νομίσματα",
+ "currencyPlaceholder": "EUR, USD",
+ "foreignOnly": "Μόνο νομίσματα διαφορετικά από αυτό του χώρου",
+ "amountBand": "Εύρος ποσού",
+ "noMinimum": "χωρίς ελάχιστο",
+ "noMaximum": "χωρίς μέγιστο",
+ "text": "Κείμενο στην περιγραφή",
+ "textContains": "Περιέχει",
+ "textExcludes": "Δεν περιέχει",
+ "textHint": "Πολλές, χωρισμένες με κόμμα, σημαίνει οποιαδήποτε από αυτές.",
+ "trigger": "Πότε ψάχνουμε",
+ "triggerHint": "Η αντιστοίχιση γίνεται σε δύο στιγμές, και τα στοιχεία δεν είναι τα ίδια.",
+ "amountMatch": "Πώς συγκρίνεται το ποσό",
+ "amountMatchHint": "Σε σχέση με το υπόλοιπο του τιμολογίου.",
+ "amountBandHint": "Για την ίδια την πληρωμή: ένα μέγεθος που θέλετε, ή δεν θέλετε, να χειρίζεται αυτός ο κανόνας."
+ },
+ "counterparty": {
+ "any": "Οποιοσδήποτε",
+ "samePayee": "Το πρόσωπο του τιμολογίου"
+ },
+ "amount": {
+ "exact": "Ακριβές",
+ "tolerance": "Εντός ποσοστού",
+ "ratio": "Μετά την παρακράτηση",
+ "ratioHint": "Χρησιμοποιεί τους συντελεστές που δηλώνει η φορολογική δικαιοδοσία του χώρου.",
+ "partial": "Μέρος του οφειλόμενου",
+ "partialHint": "Για όσους πληρώνουν σε δόσεις. Ό,τι απομένει παραμένει ανοιχτό, και η επόμενη πληρωμή ταιριάζει ακριβώς.",
+ "set": "Πολλά τιμολόγια μαζί",
+ "setHint": "Μία πληρωμή που εξοφλεί περισσότερα από ένα τιμολόγια.",
+ "setMax": "Μέγιστος αριθμός τιμολογίων",
+ "setFee": "Προμήθεια",
+ "setFeeHint": "Ένα μέρος της αξίας των τιμολογίων, για πληρωμή που κινείται καθαρή από προμήθεια. Το μηδέν σημαίνει ότι το σύνολο πρέπει να είναι ακριβές."
+ },
+ "queue": {
+ "title": "Σε αναμονή",
+ "hint": "Αντιστοιχίσεις που χρειάζονται την επιβεβαίωσή σας.",
+ "empty": "Τίποτα προς έλεγχο. Όλα ταίριαξαν μόνα τους.",
+ "aPayment": "Μια πληρωμή",
+ "maySettle": "μπορεί να εξοφλεί το {{name}}",
+ "mayBe": "μπορεί να είναι το {{name}}",
+ "accept": "Σύνδεση",
+ "declineHint": "Δεν ταιριάζει. Δεν θα προταθεί ξανά.",
+ "linked": "Συνδέθηκε",
+ "declined": "Απορρίφθηκε. Δεν θα ρωτήσουμε ξανά",
+ "covers": "καλύπτει"
+ },
+ "evidence": {
+ "amountExact": "ακριβές ποσό",
+ "amountOff": "αναμενόμενο {{expected}}, κινήθηκε {{moved}}",
+ "knownPayer": "γνωστό πρόσωπο",
+ "unknownPayer": "το πρόσωπο δεν αναγνωρίστηκε",
+ "sameDay": "ίδια ημέρα",
+ "daysApart": "{{days}} ημέρες διαφορά"
+ },
+ "direction": {
+ "any": "Οποιαδήποτε",
+ "in": "Εισερχόμενα",
+ "out": "Εξερχόμενα"
+ },
+ "step": {
+ "what": "Τι κάνει αυτός ο κανόνας",
+ "which": "Σε ποια χρήματα κοιτάζει",
+ "whichHint": "Αφήστε τα όλα κενά και κοιτάζει σε όλα",
+ "match": "Τι μετράει ως αντιστοίχιση",
+ "matchHint": "Σε σχέση με το τιμολόγιο"
+ },
+ "trigger": {
+ "money_arrives": "Όταν τα χρήματα μπαίνουν ή βγαίνουν",
+ "money_arrivesHint": "Η πληρωμή εμφανίζεται στην κίνηση του λογαριασμού και ψάχνουμε το τιμολόγιο που εξοφλεί.",
+ "invoice_issued": "Όταν εκδίδεται τιμολόγιο",
+ "invoice_issuedHint": "Η πληρωμή ήρθε πρώτη και το τιμολόγιο μετά, οπότε κοιτάμε πίσω, στα χρήματα που ήταν ήδη εκεί.",
+ "both": "Και στις δύο στιγμές",
+ "bothHint": "Ο κανόνας ισχύει και προς τις δύο κατευθύνσεις."
+ },
+ "history": {
+ "title": "Τι έκανε η αντιστοίχιση",
+ "hint": "Πρώτα τα πιο πρόσφατα.",
+ "byPerson": "από εσάς",
+ "byRules": "από τους κανόνες",
+ "more": "Δείτε {{count}} ακόμη",
+ "less": "Δείτε λιγότερα",
+ "action": {
+ "linked": "Συνδέθηκε με {{name}}",
+ "accepted": "Η πρόταση για {{name}} έγινε δεκτή",
+ "suggested": "Προτάθηκε για {{name}}",
+ "declined": "Η πρόταση για {{name}} απορρίφθηκε",
+ "expired": "Η πρόταση έληξε: {{name}}",
+ "unlinked": "Η σύνδεση με {{name}} καταργήθηκε"
+ },
+ "empty": "Τίποτα ακόμη. Γεμίζει καθώς η αντιστοίχιση συνδέει, ρωτά και απαντάται."
+ },
+ "moveUp": "Μετακίνηση πάνω",
+ "moveDown": "Μετακίνηση κάτω",
+ "matchingTitle": "Κανόνες αντιστοίχισης",
+ "matchingHint": "Πώς κάθε πληρωμή συνδέεται με αυτό που εξοφλεί.",
+ "pair": {
+ "owed": "Οφείλεται",
+ "arrived": "Τι κινήθηκε",
+ "draftInvoice": "Πρόχειρο τιμολόγιο",
+ "recurringBill": "Επαναλαμβανόμενο έξοδο",
+ "noMoney": "Καμία συναλλαγή",
+ "stillOpen": "Ανοιχτό υπόλοιπο",
+ "thisPayment": "Αυτή η πληρωμή",
+ "wasApplied": "Εφαρμόστηκε",
+ "wouldRemain": "Θα έμενε",
+ "wouldClose": "Θα το έκλεινε",
+ "thePayment": "Η πληρωμή",
+ "acrossInvoices": "σε {{count}} τιμολόγια",
+ "dueOn": "λήγει στις {{date}}",
+ "totalOf": "σύνολο {{amount}}"
+ },
+ "discarded": "Διαγράφηκαν από αυτόν τον χώρο:",
+ "noneLeft": "Δεν έμεινε κανένας κανόνας αντιστοίχισης σε αυτό το σύνολο. Τίποτα εδώ δεν αντιστοιχίζεται αυτόματα.",
+ "confirmDeleteTitle": "Διαγραφή αυτού του κανόνα;",
+ "confirmDeleteDescription": "Το «{{name}}» σταματά να αποφασίζει οτιδήποτε. Αν είναι δικός μας, μπορείτε να τον επαναφέρετε αργότερα.",
+ "exported": "Οι κανόνες αντιστοίχισης κατέβηκαν",
+ "imported": "Εισήχθησαν {{imported}} κανόνες ({{skipped}} παραλείφθηκαν)",
+ "invalidImportFile": "Αυτό δεν είναι αρχείο κανόνων αντιστοίχισης",
+ "importConfirmTitle": "Εισαγωγή κανόνων αντιστοίχισης;",
+ "importConfirmDescription": "Το αρχείο {{file}} περιέχει {{count}} κανόνες.",
+ "importOverwriteWarning": "Η εισαγωγή αντικαθιστά τους κανόνες αντιστοίχισης αυτού του χώρου, μαζί με τη σειρά τους. Δεν αναιρείται."
}
}
diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json
index 91703002..d68857d7 100644
--- a/frontend/src/locales/en.json
+++ b/frontend/src/locales/en.json
@@ -372,7 +372,14 @@
"fromSystem": "From {{source}} · {{date}}",
"fromUpload": "Uploaded · {{date}}"
},
- "draftSaved": "Draft saved"
+ "draftSaved": "Draft saved",
+ "suggestions": {
+ "title_one": "A payment may settle this invoice",
+ "title_other": "{{count}} payments may settle this invoice",
+ "wouldApply": "would apply {{amount}}",
+ "alsoCovers_one": "also covers {{count}} other invoice",
+ "alsoCovers_other": "also covers {{count}} other invoices"
+ }
},
"collections": {
"title": "Collections",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "Transfers are not counted as income or expenses",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "This transaction settles an invoice. Open it.",
+ "suggestionBadge": "Question",
+ "suggestionBadgeTooltip": "A payment may settle this. Open the queue to answer."
},
"accounts": {
"title": "Accounts",
@@ -1136,6 +1145,7 @@
"createMissingCategories": "Also create default categories the pack needs",
"duplicateName": "A rule with this name already exists",
"sectionTitle": "Categorization Rules",
+ "sectionHint": "How to categorize transactions.",
"resetAndReapplyAll": "Reset and reapply",
"confirmResetAndReapplyAll": "Reset matching transaction categories, notes, and rule-managed descriptions, then reapply all active rules?",
"add": "Add",
@@ -1178,7 +1188,10 @@
"ignoreActionHint": "(no value needed)",
"selectCategory": "Select category...",
"selectAccount": "Select account...",
- "ruleActive": "Active rule",
+ "turnOn": "Turn on",
+ "turnOff": "Turn off",
+ "turnedOn": "Rule turned on",
+ "turnedOff": "Rule turned off",
"noConditions": "(no conditions)",
"noActions": "(no actions)",
"fieldDescription": "Description",
@@ -1213,7 +1226,12 @@
"importConfirmTitle": "Import categorization rules?",
"importConfirmDescription": "File {{file}} contains {{count}} rules.",
"importOverwriteWarning": "Importing will overwrite your current categorization rules. This cannot be undone.",
- "confirmOverwriteImport": "Overwrite and import"
+ "confirmOverwriteImport": "Overwrite and import",
+ "tab": {
+ "rules": "Rules",
+ "queue": "Waiting for you",
+ "history": "History"
+ }
},
"categories": {
"title": "Categories",
@@ -2238,5 +2256,200 @@
"subtitle": "Add a connection to point Securo at your local Ollama, OpenAI, Anthropic, or any OpenAI-compatible endpoint."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Invoices",
+ "invoicesHint": "against what you have to receive and to pay",
+ "recurring": "Recurring",
+ "recurringHint": "against what you were already expecting",
+ "inactive": "Not in use here"
+ },
+ "rule": {
+ "sameClientExact": "Known person, exact amount",
+ "netOfWithholding": "Known person, paid net of withholding",
+ "exactAmountAnyClient": "Exact amount, anyone",
+ "similarDescription": "Close amount and similar description",
+ "sameAccountExact": "Same account, exact amount",
+ "unknown": "Rule",
+ "partPayment": "Known person, part of the amount",
+ "severalInvoices": "Known person, several invoices at once"
+ },
+ "outcome": {
+ "link": "Links",
+ "suggest": "Suggests"
+ },
+ "cond": {
+ "samePayee": "the person is the one on the invoice",
+ "sameAccount": "the same account",
+ "amountExact": "the amount matches exactly",
+ "amountTolerance": "the amount is within {{percent}}%",
+ "amountRatio": "the amount matches net of withholding",
+ "window": "up to {{before}} days early, {{after}} days late",
+ "similarity": "the description is at least {{min}} similar",
+ "none": "no conditions",
+ "accounts": "in {{names}}",
+ "payees": "for {{names}}",
+ "moneyIn": "money coming in",
+ "moneyOut": "money going out",
+ "foreign": "in a foreign currency",
+ "currencyIn": "in {{codes}}",
+ "atLeast": "at least {{value}}",
+ "atMost": "at most {{value}}",
+ "textContains": "the statement says “{{text}}”",
+ "textExcludes": "the statement does not say “{{text}}”",
+ "onArrival": "when money comes in or goes out",
+ "onIssue": "when an invoice is issued",
+ "amountPartial": "the amount covers part of what is owed",
+ "amountSet": "up to {{count}} invoices add up to it"
+ },
+ "newRule": "New matching rule",
+ "saved": "Rule saved",
+ "reset": "Rule restored",
+ "restore": "Restore what we ship",
+ "changed": "Changed",
+ "yours": "Yours",
+ "field": {
+ "name": "Name",
+ "namePlaceholder": "e.g. Known person, close amount",
+ "outcome": "What it does when it matches",
+ "outcomeHint": "Link binds the payment on its own. Suggest sends it to the queue below for you to confirm.",
+ "counterparty": "Who paid or was paid",
+ "amount": "Amount",
+ "window": "How far apart the dates may be",
+ "windowHint": "Late is counted from the due date, early from the day the invoice was written, so paying the day after issue is not weeks early.",
+ "beforeDays": "Days early",
+ "afterDays": "Days late",
+ "similarity": "Description similarity",
+ "similarityHint": "From 0 to 1. Leave empty to ignore the description entirely.",
+ "similarityOff": "off",
+ "scope": "When this rule applies",
+ "scopeHint": "Leave empty to apply to everything",
+ "accounts": "Bank accounts",
+ "anyAccount": "Any account",
+ "payees": "People",
+ "anyPayee": "Anyone",
+ "direction": "Money in or out",
+ "currencyScope": "Only these currencies",
+ "currencyPlaceholder": "e.g. USD, EUR",
+ "foreignOnly": "Only currencies other than the one this workspace uses",
+ "amountBand": "Only amounts in this range",
+ "noMinimum": "no minimum",
+ "noMaximum": "no maximum",
+ "text": "Statement text",
+ "textContains": "must contain…",
+ "textExcludes": "must not contain…",
+ "textHint": "Several, separated by commas, means any of them.",
+ "trigger": "When we look",
+ "triggerHint": "Matching happens at two moments, and the evidence is not the same in both.",
+ "amountMatch": "How close the amount must be",
+ "amountMatchHint": "Compared against what is still owed, not the original total.",
+ "amountBandHint": "About the payment itself: a size you do or do not want this rule handling."
+ },
+ "counterparty": {
+ "any": "Anyone",
+ "samePayee": "The person on the invoice"
+ },
+ "amount": {
+ "exact": "Exactly the amount owed",
+ "tolerance": "Within a margin",
+ "ratio": "Net of withholding tax",
+ "ratioHint": "Uses the withholding rates for your country. Nothing matches until those are set.",
+ "partial": "Part of what is owed",
+ "partialHint": "For payments made in instalments. What is left stays open, and the next payment matches it exactly.",
+ "set": "Several invoices added up",
+ "setHint": "For a payment that covers more than one invoice. If more than one combination adds up, we ask instead of choosing.",
+ "setMax": "At most this many invoices",
+ "setFee": "Allow for a fee of",
+ "setFeeHint": "A share of what the invoices are worth, for a payment that moves net of a cut. Zero means the total must be exact."
+ },
+ "queue": {
+ "title": "Waiting for you",
+ "hint": "Matches that need your confirmation.",
+ "empty": "Nothing to review. Everything matched on its own.",
+ "aPayment": "A payment",
+ "maySettle": "may settle {{name}}",
+ "mayBe": "may be {{name}}",
+ "accept": "Link",
+ "declineHint": "Not a match. This pair will not be suggested again.",
+ "linked": "Linked",
+ "declined": "Dismissed. We will not ask again",
+ "covers": "covers"
+ },
+ "evidence": {
+ "amountExact": "amount matches exactly",
+ "amountOff": "expected {{expected}}, moved {{moved}}",
+ "knownPayer": "known person",
+ "unknownPayer": "person not identified",
+ "sameDay": "same day",
+ "daysApart": "{{days}} days apart"
+ },
+ "direction": {
+ "any": "Either",
+ "in": "Money coming in",
+ "out": "Money going out"
+ },
+ "step": {
+ "what": "What this rule is",
+ "which": "Which money it looks at",
+ "whichHint": "Leave everything empty and it looks at all of it",
+ "match": "When it counts as a match",
+ "matchHint": "How closely the payment and the promise have to fit"
+ },
+ "trigger": {
+ "money_arrives": "When money comes in or goes out",
+ "money_arrivesHint": "The payment shows up on the statement and we look for the invoice it settles.",
+ "invoice_issued": "When an invoice is issued",
+ "invoice_issuedHint": "The payment came first and the invoice follows, so we look back at money already there.",
+ "both": "Both moments",
+ "bothHint": "The rule is trusted either way round."
+ },
+ "history": {
+ "title": "What matching did",
+ "hint": "Newest first.",
+ "byPerson": "by you",
+ "byRules": "by the rules",
+ "more": "Show {{count}} more",
+ "less": "Show fewer",
+ "action": {
+ "linked": "Linked to {{name}}",
+ "accepted": "Suggestion accepted for {{name}}",
+ "suggested": "Offered against {{name}}",
+ "declined": "Suggestion dismissed for {{name}}",
+ "expired": "Suggestion expired: {{name}}",
+ "unlinked": "Unlinked from {{name}}"
+ },
+ "empty": "Nothing yet. This fills in as matching links, asks and is answered."
+ },
+ "moveUp": "Try this one earlier",
+ "moveDown": "Try this one later",
+ "matchingTitle": "Matching rules",
+ "matchingHint": "How each payment is bound to what it settles.",
+ "pair": {
+ "owed": "What is owed",
+ "arrived": "What moved",
+ "draftInvoice": "Draft invoice",
+ "recurringBill": "Recurring bill",
+ "noMoney": "No transaction on this one.",
+ "stillOpen": "still open",
+ "thisPayment": "this payment",
+ "wasApplied": "applied",
+ "wouldRemain": "would remain",
+ "wouldClose": "closes it",
+ "thePayment": "the payment",
+ "acrossInvoices": "across {{count}} invoices",
+ "dueOn": "due {{date}}",
+ "totalOf": "{{amount}} total"
+ },
+ "discarded": "Deleted from this workspace:",
+ "noneLeft": "No matching rules left in this set. Nothing here is matched automatically.",
+ "confirmDeleteTitle": "Delete this rule?",
+ "confirmDeleteDescription": "\"{{name}}\" stops deciding anything. You can bring it back later if it is one of ours.",
+ "exported": "Matching rules downloaded",
+ "imported": "Imported {{imported}} rules ({{skipped}} skipped)",
+ "invalidImportFile": "That is not a matching-rules file",
+ "importConfirmTitle": "Import matching rules?",
+ "importConfirmDescription": "File {{file}} contains {{count}} rules.",
+ "importOverwriteWarning": "Importing replaces the matching rules this workspace has now, including their order. This cannot be undone."
}
}
diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json
index 9841cf28..0a0633fe 100644
--- a/frontend/src/locales/es.json
+++ b/frontend/src/locales/es.json
@@ -372,7 +372,14 @@
"fromSystem": "De {{source}} · {{date}}",
"fromUpload": "Subido · {{date}}"
},
- "draftSaved": "Borrador guardado"
+ "draftSaved": "Borrador guardado",
+ "suggestions": {
+ "title_one": "Un pago puede saldar esta factura",
+ "title_other": "{{count}} pagos pueden saldar esta factura",
+ "wouldApply": "aplicaría {{amount}}",
+ "alsoCovers_one": "también cubre otra {{count}} factura",
+ "alsoCovers_other": "también cubre otras {{count}} facturas"
+ }
},
"collections": {
"title": "Colecciones",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "Las transferencias no cuentan como ingresos ni gastos",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Esta transacción salda una factura. Ábrela.",
+ "suggestionBadge": "Pregunta",
+ "suggestionBadgeTooltip": "Un pago puede saldar esta factura. Abre la cola para responder."
},
"accounts": {
"title": "Cuentas",
@@ -1137,6 +1146,7 @@
"createMissingCategories": "Crear también las categorías predeterminadas que necesita el paquete",
"duplicateName": "Ya existe una regla con este nombre",
"sectionTitle": "Reglas de categorización",
+ "sectionHint": "Cómo categorizar las transacciones.",
"resetAndReapplyAll": "Restablecer y reaplicar",
"confirmResetAndReapplyAll": "¿Restablecer las categorías, las notas y las descripciones gestionadas por reglas de las transacciones coincidentes y volver a aplicar todas las reglas activas?",
"add": "Agregar",
@@ -1179,7 +1189,10 @@
"ignoreActionHint": "(no se necesita valor)",
"selectCategory": "Seleccionar categoría...",
"selectAccount": "Seleccionar cuenta...",
- "ruleActive": "Regla activa",
+ "turnOn": "Activar",
+ "turnOff": "Desactivar",
+ "turnedOn": "Regla activada",
+ "turnedOff": "Regla desactivada",
"noConditions": "(sin condiciones)",
"noActions": "(sin acciones)",
"fieldDescription": "Descripción",
@@ -1206,15 +1219,20 @@
"sortBy_priority": "Prioridad",
"sortBy_name": "Nombre",
"sortBy_category": "Categoría",
- "export": "Export",
- "import": "Import",
- "exported": "Rules export downloaded",
- "imported": "Imported {{imported}} rules ({{skipped}} skipped)",
- "invalidImportFile": "Invalid rules import file",
- "importConfirmTitle": "Import categorization rules?",
- "importConfirmDescription": "File {{file}} contains {{count}} rules.",
- "importOverwriteWarning": "Importing will overwrite your current categorization rules. This cannot be undone.",
- "confirmOverwriteImport": "Overwrite and import"
+ "export": "Exportar",
+ "import": "Importar",
+ "exported": "Exportación de reglas descargada",
+ "imported": "{{imported}} reglas importadas ({{skipped}} omitidas)",
+ "invalidImportFile": "Archivo de importación de reglas no válido",
+ "importConfirmTitle": "¿Importar reglas de categorización?",
+ "importConfirmDescription": "El archivo {{file}} contiene {{count}} reglas.",
+ "importOverwriteWarning": "Importar sustituirá tus reglas de categorización actuales. Esto no se puede deshacer.",
+ "confirmOverwriteImport": "Sobrescribir e importar",
+ "tab": {
+ "rules": "Reglas",
+ "queue": "Esperándote",
+ "history": "Historial"
+ }
},
"categories": {
"title": "Categorías",
@@ -2239,5 +2257,200 @@
"openai": "OpenAI Responses API"
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Facturas",
+ "invoicesHint": "contra lo que tienes que cobrar y pagar",
+ "recurring": "Recurrentes",
+ "recurringHint": "contra lo que ya esperabas",
+ "inactive": "No se usa aquí"
+ },
+ "rule": {
+ "sameClientExact": "Persona conocida, importe exacto",
+ "netOfWithholding": "Persona conocida, pagado con retención",
+ "exactAmountAnyClient": "Importe exacto, cualquier persona",
+ "similarDescription": "Importe cercano y descripción parecida",
+ "sameAccountExact": "Misma cuenta, importe exacto",
+ "unknown": "Regla",
+ "partPayment": "Persona conocida, parte del importe",
+ "severalInvoices": "Persona conocida, varias facturas a la vez"
+ },
+ "outcome": {
+ "link": "Vincula solo",
+ "suggest": "Sugiere"
+ },
+ "cond": {
+ "samePayee": "la persona es la misma de la factura",
+ "sameAccount": "la misma cuenta",
+ "amountExact": "el importe coincide exactamente",
+ "amountTolerance": "el importe está dentro del {{percent}}%",
+ "amountRatio": "el importe coincide descontada la retención",
+ "window": "hasta {{before}} días antes, {{after}} días después",
+ "similarity": "la descripción se parece al menos {{min}}",
+ "none": "sin condiciones",
+ "accounts": "en {{names}}",
+ "payees": "para {{names}}",
+ "moneyIn": "dinero que entra",
+ "moneyOut": "dinero que sale",
+ "foreign": "en moneda extranjera",
+ "currencyIn": "en {{codes}}",
+ "atLeast": "desde {{value}}",
+ "atMost": "hasta {{value}}",
+ "textContains": "el extracto dice “{{text}}”",
+ "textExcludes": "el extracto no dice “{{text}}”",
+ "onArrival": "cuando el dinero entra o sale",
+ "onIssue": "cuando se emite una factura",
+ "amountPartial": "el importe cubre parte de lo que se debe",
+ "amountSet": "hasta {{count}} facturas suman ese importe"
+ },
+ "newRule": "Nueva regla de conciliación",
+ "saved": "Regla guardada",
+ "reset": "Regla restaurada",
+ "restore": "Volver al valor por defecto",
+ "changed": "Modificada",
+ "yours": "Tuya",
+ "field": {
+ "name": "Nombre",
+ "namePlaceholder": "ej.: Persona conocida, importe cercano",
+ "outcome": "Qué hacer cuando coincide",
+ "outcomeHint": "Vincular salda por su cuenta. Sugerir lo envía a la lista de abajo para que lo confirmes.",
+ "counterparty": "Quién pagó o cobró",
+ "amount": "Importe",
+ "window": "Distancia permitida entre las fechas",
+ "windowHint": "El retraso se cuenta desde el vencimiento; la anticipación, desde el día en que se emitió la factura, así pagar al día siguiente no parece semanas antes.",
+ "beforeDays": "Días antes",
+ "afterDays": "Días después",
+ "similarity": "Similitud de la descripción",
+ "similarityHint": "De 0 a 1. Déjalo vacío para ignorar la descripción.",
+ "similarityOff": "desactivado",
+ "scope": "Cuándo se aplica esta regla",
+ "scopeHint": "Déjalo vacío para que valga para todo",
+ "accounts": "Cuentas bancarias",
+ "anyAccount": "Cualquier cuenta",
+ "payees": "Personas",
+ "anyPayee": "Cualquier persona",
+ "direction": "Entrada o salida",
+ "currencyScope": "Solo en estas monedas",
+ "currencyPlaceholder": "p. ej.: USD, EUR",
+ "foreignOnly": "Solo monedas distintas de la que usa este espacio",
+ "amountBand": "Solo importes en este rango",
+ "noMinimum": "sin mínimo",
+ "noMaximum": "sin máximo",
+ "text": "Texto del extracto",
+ "textContains": "debe contener…",
+ "textExcludes": "no debe contener…",
+ "textHint": "Varios, separados por comas, significa cualquiera de ellos.",
+ "trigger": "Cuándo buscamos",
+ "triggerHint": "La conciliación ocurre en dos momentos, y la evidencia no es la misma en ambos.",
+ "amountMatch": "Cuán cerca debe estar el importe",
+ "amountMatchHint": "Comparado con lo que aún se debe, no con el total original.",
+ "amountBandHint": "Sobre el pago en sí: un tamaño que quieres, o no, que esta regla trate."
+ },
+ "counterparty": {
+ "any": "Cualquiera",
+ "samePayee": "La persona de la factura"
+ },
+ "amount": {
+ "exact": "Exactamente el importe adeudado",
+ "tolerance": "Dentro de un margen",
+ "ratio": "Descontada la retención fiscal",
+ "ratioHint": "Usa los tipos de retención de tu país. Mientras no existan, la regla no coincide con nada.",
+ "partial": "Parte de lo que se debe",
+ "partialHint": "Para quien paga a plazos. Lo que queda sigue abierto, y el siguiente pago cuadra exacto.",
+ "set": "Varias facturas sumadas",
+ "setHint": "Para un pago que cubre más de una factura. Si más de una combinación cuadra, preguntamos en vez de elegir.",
+ "setMax": "Como mucho estas facturas",
+ "setFee": "Admitir una comisión de",
+ "setFeeHint": "Una parte del valor de las facturas, para un pago que se mueve neto de comisión. Cero significa que el total debe ser exacto."
+ },
+ "queue": {
+ "title": "Esperándote",
+ "hint": "Conciliaciones que necesitan tu confirmación.",
+ "empty": "Nada que revisar. Todo coincidió solo.",
+ "aPayment": "Un pago",
+ "maySettle": "puede saldar {{name}}",
+ "mayBe": "puede ser {{name}}",
+ "accept": "Vincular",
+ "declineHint": "No es esto. Este par no se volverá a sugerir.",
+ "linked": "Vinculado",
+ "declined": "Descartado: no volveremos a preguntar",
+ "covers": "cubre"
+ },
+ "evidence": {
+ "amountExact": "el importe coincide exactamente",
+ "amountOff": "esperado {{expected}}, movido {{moved}}",
+ "knownPayer": "persona conocida",
+ "unknownPayer": "persona no identificada",
+ "sameDay": "mismo día",
+ "daysApart": "{{days}} días de diferencia"
+ },
+ "direction": {
+ "any": "Cualquiera",
+ "in": "Dinero que entra",
+ "out": "Dinero que sale"
+ },
+ "step": {
+ "what": "Qué es esta regla",
+ "which": "Qué dinero mira",
+ "whichHint": "Déjalo todo vacío y mira todo el dinero",
+ "match": "Cuándo cuenta como coincidencia",
+ "matchHint": "Cuán cerca deben estar el pago y la promesa"
+ },
+ "trigger": {
+ "money_arrives": "Cuando el dinero entra o sale",
+ "money_arrivesHint": "El pago aparece en el extracto y buscamos la factura que salda.",
+ "invoice_issued": "Cuando se emite una factura",
+ "invoice_issuedHint": "El pago llegó antes y la factura después, así que miramos atrás, al dinero que ya estaba ahí.",
+ "both": "En ambos momentos",
+ "bothHint": "La regla vale en los dos sentidos."
+ },
+ "history": {
+ "title": "Qué hizo la conciliación",
+ "hint": "Lo más reciente primero.",
+ "byPerson": "por ti",
+ "byRules": "por las reglas",
+ "more": "Ver {{count}} más",
+ "less": "Ver menos",
+ "action": {
+ "linked": "Vinculado a {{name}}",
+ "accepted": "Sugerencia aceptada para {{name}}",
+ "suggested": "Propuesto para {{name}}",
+ "declined": "Sugerencia descartada para {{name}}",
+ "expired": "Sugerencia caducada: {{name}}",
+ "unlinked": "Desvinculado de {{name}}"
+ },
+ "empty": "Nada aún. Esto se llena a medida que la conciliación vincula, pregunta y se responde."
+ },
+ "moveUp": "Probar esta antes",
+ "moveDown": "Probar esta después",
+ "matchingTitle": "Reglas de conciliación",
+ "matchingHint": "Cómo cada pago se vincula a lo que salda.",
+ "pair": {
+ "owed": "Lo que se debe",
+ "arrived": "Lo que se movió",
+ "draftInvoice": "Factura en borrador",
+ "recurringBill": "Cuenta recurrente",
+ "noMoney": "Sin transacción en esta.",
+ "stillOpen": "pendiente",
+ "thisPayment": "este pago",
+ "wasApplied": "aplicado",
+ "wouldRemain": "quedaría",
+ "wouldClose": "la salda",
+ "thePayment": "el pago",
+ "acrossInvoices": "en {{count}} facturas",
+ "dueOn": "vence {{date}}",
+ "totalOf": "total de {{amount}}"
+ },
+ "discarded": "Eliminadas de este espacio:",
+ "noneLeft": "No queda ninguna regla de conciliación en este conjunto. Aquí no se concilia nada automáticamente.",
+ "confirmDeleteTitle": "¿Eliminar esta regla?",
+ "confirmDeleteDescription": "\"{{name}}\" deja de decidir nada. Si es una de las nuestras, puedes recuperarla más tarde.",
+ "exported": "Reglas de conciliación descargadas",
+ "imported": "{{imported}} reglas importadas ({{skipped}} omitidas)",
+ "invalidImportFile": "Ese no es un archivo de reglas de conciliación",
+ "importConfirmTitle": "¿Importar reglas de conciliación?",
+ "importConfirmDescription": "El archivo {{file}} contiene {{count}} reglas.",
+ "importOverwriteWarning": "La importación reemplaza las reglas de conciliación de este espacio, incluido su orden. No se puede deshacer."
}
}
diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.json
index 2efffccc..22d2dd31 100644
--- a/frontend/src/locales/fr.json
+++ b/frontend/src/locales/fr.json
@@ -372,7 +372,14 @@
"fromSystem": "De {{source}} · {{date}}",
"fromUpload": "Importé · {{date}}"
},
- "draftSaved": "Brouillon enregistré"
+ "draftSaved": "Brouillon enregistré",
+ "suggestions": {
+ "title_one": "Un paiement peut solder cette facture",
+ "title_other": "{{count}} paiements peuvent solder cette facture",
+ "wouldApply": "appliquerait {{amount}}",
+ "alsoCovers_one": "couvre aussi {{count}} autre facture",
+ "alsoCovers_other": "couvre aussi {{count}} autres factures"
+ }
},
"collections": {
"title": "Collections",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "Les virements ne comptent pas comme revenus ou dépenses",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Cette transaction solde une facture. Ouvrir.",
+ "suggestionBadge": "Question",
+ "suggestionBadgeTooltip": "Un paiement peut solder cette facture. Ouvrez la file pour répondre."
},
"accounts": {
"title": "Comptes",
@@ -1137,6 +1146,7 @@
"createMissingCategories": "Créer aussi les catégories par défaut dont le pack a besoin",
"duplicateName": "Une règle portant ce nom existe déjà",
"sectionTitle": "Règles de catégorisation",
+ "sectionHint": "Comment catégoriser les transactions.",
"resetAndReapplyAll": "Réinitialiser et réappliquer",
"confirmResetAndReapplyAll": "Réinitialiser les catégories, les notes et les descriptions gérées par des règles des transactions correspondantes, puis réappliquer toutes les règles actives ?",
"add": "Ajouter",
@@ -1179,7 +1189,10 @@
"ignoreActionHint": "(aucune valeur requise)",
"selectCategory": "Sélectionner une catégorie...",
"selectAccount": "Sélectionner un compte...",
- "ruleActive": "Règle active",
+ "turnOn": "Activer",
+ "turnOff": "Désactiver",
+ "turnedOn": "Règle activée",
+ "turnedOff": "Règle désactivée",
"noConditions": "(aucune condition)",
"noActions": "(aucune action)",
"fieldDescription": "Description",
@@ -1214,7 +1227,12 @@
"importConfirmTitle": "Importer les règles de catégorisation ?",
"importConfirmDescription": "Le fichier {{file}} contient {{count}} règles.",
"importOverwriteWarning": "L'importation écrasera vos règles de catégorisation actuelles. Cette action est irréversible.",
- "confirmOverwriteImport": "Écraser et importer"
+ "confirmOverwriteImport": "Écraser et importer",
+ "tab": {
+ "rules": "Règles",
+ "queue": "En attente de vous",
+ "history": "Historique"
+ }
},
"categories": {
"title": "Catégories",
@@ -2239,5 +2257,200 @@
"subtitle": "Ajoutez une connexion pour pointer Securo vers votre Ollama local, OpenAI, Anthropic, ou tout point de terminaison compatible OpenAI."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Factures",
+ "invoicesHint": "face à ce que vous avez à encaisser et à payer",
+ "recurring": "Récurrents",
+ "recurringHint": "face à ce que vous attendiez déjà",
+ "inactive": "Non utilisée ici"
+ },
+ "rule": {
+ "sameClientExact": "Personne connue, montant exact",
+ "netOfWithholding": "Personne connue, payé net de retenue",
+ "exactAmountAnyClient": "Montant exact, n'importe qui",
+ "similarDescription": "Montant proche et libellé semblable",
+ "sameAccountExact": "Même compte, montant exact",
+ "unknown": "Règle",
+ "partPayment": "Personne connue, une partie du montant",
+ "severalInvoices": "Personne connue, plusieurs factures à la fois"
+ },
+ "outcome": {
+ "link": "Rattache seule",
+ "suggest": "Propose"
+ },
+ "cond": {
+ "samePayee": "la personne est celle de la facture",
+ "sameAccount": "le même compte",
+ "amountExact": "le montant correspond exactement",
+ "amountTolerance": "le montant est à {{percent}}% près",
+ "amountRatio": "le montant correspond net de retenue",
+ "window": "jusqu'à {{before}} jours en avance, {{after}} en retard",
+ "similarity": "le libellé se ressemble au moins de {{min}}",
+ "none": "aucune condition",
+ "accounts": "sur {{names}}",
+ "payees": "pour {{names}}",
+ "moneyIn": "argent entrant",
+ "moneyOut": "argent sortant",
+ "foreign": "en devise étrangère",
+ "currencyIn": "en {{codes}}",
+ "atLeast": "à partir de {{value}}",
+ "atMost": "jusqu'à {{value}}",
+ "textContains": "le relevé indique « {{text}} »",
+ "textExcludes": "le relevé n'indique pas « {{text}} »",
+ "onArrival": "quand l'argent entre ou sort",
+ "onIssue": "quand une facture est émise",
+ "amountPartial": "le montant couvre une partie de ce qui est dû",
+ "amountSet": "jusqu'à {{count}} factures en font le total"
+ },
+ "newRule": "Nouvelle règle de rapprochement",
+ "saved": "Règle enregistrée",
+ "reset": "Règle rétablie",
+ "restore": "Revenir au réglage par défaut",
+ "changed": "Modifiée",
+ "yours": "La vôtre",
+ "field": {
+ "name": "Nom",
+ "namePlaceholder": "ex. : Personne connue, montant proche",
+ "outcome": "Ce qu'elle fait quand elle correspond",
+ "outcomeHint": "Rattacher règle tout seul. Proposer l'envoie dans la liste ci-dessous, pour que vous confirmiez.",
+ "counterparty": "Qui a payé ou été payé",
+ "amount": "Montant",
+ "window": "Écart autorisé entre les dates",
+ "windowHint": "Le retard se compte depuis l'échéance, l'avance depuis le jour d'émission de la facture : payer le lendemain de l'émission n'est pas des semaines en avance.",
+ "beforeDays": "Jours en avance",
+ "afterDays": "Jours en retard",
+ "similarity": "Ressemblance du libellé",
+ "similarityHint": "De 0 à 1. Laissez vide pour ignorer le libellé.",
+ "similarityOff": "désactivé",
+ "scope": "Quand cette règle s'applique",
+ "scopeHint": "Laissez vide pour tout couvrir",
+ "accounts": "Comptes bancaires",
+ "anyAccount": "N'importe quel compte",
+ "payees": "Personnes",
+ "anyPayee": "N'importe qui",
+ "direction": "Entrée ou sortie",
+ "currencyScope": "Uniquement ces devises",
+ "currencyPlaceholder": "ex. : USD, EUR",
+ "foreignOnly": "Uniquement les devises autres que celle de cet espace",
+ "amountBand": "Uniquement les montants dans cette plage",
+ "noMinimum": "pas de minimum",
+ "noMaximum": "pas de maximum",
+ "text": "Libellé du relevé",
+ "textContains": "doit contenir…",
+ "textExcludes": "ne doit pas contenir…",
+ "textHint": "Plusieurs, séparés par des virgules, signifie n'importe lequel.",
+ "trigger": "Quand nous cherchons",
+ "triggerHint": "Le rapprochement a lieu à deux moments, et les indices ne sont pas les mêmes.",
+ "amountMatch": "À quel point le montant doit correspondre",
+ "amountMatchHint": "Comparé à ce qui reste dû, pas au total d'origine.",
+ "amountBandHint": "À propos du paiement lui-même : une taille que vous voulez, ou non, voir traitée par cette règle."
+ },
+ "counterparty": {
+ "any": "N'importe qui",
+ "samePayee": "La personne de la facture"
+ },
+ "amount": {
+ "exact": "Exactement le montant dû",
+ "tolerance": "Dans une marge",
+ "ratio": "Net de retenue à la source",
+ "ratioHint": "Utilise les taux de retenue de votre pays. Tant qu'il n'y en a pas, la règle ne correspond à rien.",
+ "partial": "Une partie de ce qui est dû",
+ "partialHint": "Pour qui paie en plusieurs fois. Ce qui reste demeure ouvert, et le paiement suivant tombe juste.",
+ "set": "Plusieurs factures additionnées",
+ "setHint": "Pour un paiement qui couvre plus d'une facture. Si plusieurs combinaisons tombent juste, nous demandons plutôt que de choisir.",
+ "setMax": "Au plus ce nombre de factures",
+ "setFee": "Admettre des frais de",
+ "setFeeHint": "Une part de la valeur des factures, pour un paiement qui circule net de commission. Zéro signifie que le total doit être exact."
+ },
+ "queue": {
+ "title": "En attente de vous",
+ "hint": "Rapprochements qui attendent votre confirmation.",
+ "empty": "Rien à vérifier. Tout a été rapproché tout seul.",
+ "aPayment": "Un paiement",
+ "maySettle": "règle peut-être {{name}}",
+ "mayBe": "est peut-être {{name}}",
+ "accept": "Rattacher",
+ "declineHint": "Ce n'est pas ça. Cette paire ne sera plus proposée.",
+ "linked": "Rattaché",
+ "declined": "Écarté. Nous ne redemanderons pas",
+ "covers": "couvre"
+ },
+ "evidence": {
+ "amountExact": "le montant correspond exactement",
+ "amountOff": "attendu {{expected}}, mouvementé {{moved}}",
+ "knownPayer": "personne connue",
+ "unknownPayer": "personne non identifiée",
+ "sameDay": "même jour",
+ "daysApart": "{{days}} jours d'écart"
+ },
+ "direction": {
+ "any": "Peu importe",
+ "in": "Argent entrant",
+ "out": "Argent sortant"
+ },
+ "step": {
+ "what": "Ce qu'est cette règle",
+ "which": "Quel argent elle regarde",
+ "whichHint": "Laissez tout vide et elle regarde tout l'argent",
+ "match": "Quand cela compte comme un rapprochement",
+ "matchHint": "À quel point le paiement et la promesse doivent correspondre"
+ },
+ "trigger": {
+ "money_arrives": "Quand l'argent entre ou sort",
+ "money_arrivesHint": "Le paiement apparaît sur le relevé et nous cherchons la facture qu'il solde.",
+ "invoice_issued": "Quand une facture est émise",
+ "invoice_issuedHint": "Le paiement est arrivé avant et la facture après, alors nous regardons en arrière, vers l'argent déjà là.",
+ "both": "Aux deux moments",
+ "bothHint": "La règle vaut dans les deux sens."
+ },
+ "history": {
+ "title": "Ce que le rapprochement a fait",
+ "hint": "Du plus récent.",
+ "byPerson": "par vous",
+ "byRules": "par les règles",
+ "more": "Afficher {{count}} de plus",
+ "less": "Afficher moins",
+ "action": {
+ "linked": "Rattaché à {{name}}",
+ "accepted": "Suggestion acceptée pour {{name}}",
+ "suggested": "Proposé pour {{name}}",
+ "declined": "Suggestion écartée pour {{name}}",
+ "expired": "Suggestion expirée : {{name}}",
+ "unlinked": "Détaché de {{name}}"
+ },
+ "empty": "Rien pour l'instant. Cela se remplit à mesure que le rapprochement rattache, demande et reçoit une réponse."
+ },
+ "moveUp": "Essayer celle-ci plus tôt",
+ "moveDown": "Essayer celle-ci plus tard",
+ "matchingTitle": "Règles de rapprochement",
+ "matchingHint": "Comment chaque paiement est rattaché à ce qu'il solde.",
+ "pair": {
+ "owed": "Ce qui est dû",
+ "arrived": "Ce qui a bougé",
+ "draftInvoice": "Facture en brouillon",
+ "recurringBill": "Dépense récurrente",
+ "noMoney": "Aucune opération ici.",
+ "stillOpen": "reste dû",
+ "thisPayment": "ce paiement",
+ "wasApplied": "appliqué",
+ "wouldRemain": "resterait",
+ "wouldClose": "la solde",
+ "thePayment": "le paiement",
+ "acrossInvoices": "sur {{count}} factures",
+ "dueOn": "échéance {{date}}",
+ "totalOf": "total de {{amount}}"
+ },
+ "discarded": "Supprimées de cet espace :",
+ "noneLeft": "Plus aucune règle de rapprochement dans cet ensemble. Rien n'est rapproché automatiquement ici.",
+ "confirmDeleteTitle": "Supprimer cette règle ?",
+ "confirmDeleteDescription": "« {{name}} » ne décide plus rien. S'il s'agit d'une des nôtres, vous pourrez la rétablir plus tard.",
+ "exported": "Règles de rapprochement téléchargées",
+ "imported": "{{imported}} règles importées ({{skipped}} ignorées)",
+ "invalidImportFile": "Ce n'est pas un fichier de règles de rapprochement",
+ "importConfirmTitle": "Importer les règles de rapprochement ?",
+ "importConfirmDescription": "Le fichier {{file}} contient {{count}} règles.",
+ "importOverwriteWarning": "L'import remplace les règles de rapprochement de cet espace, y compris leur ordre. C'est irréversible."
}
}
diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.json
index 58564570..481e7b4d 100644
--- a/frontend/src/locales/hi.json
+++ b/frontend/src/locales/hi.json
@@ -372,7 +372,14 @@
"fromSystem": "{{source}} से · {{date}}",
"fromUpload": "अपलोड किया गया · {{date}}"
},
- "draftSaved": "ड्राफ़्ट सहेजा गया"
+ "draftSaved": "ड्राफ़्ट सहेजा गया",
+ "suggestions": {
+ "title_one": "एक भुगतान इस इनवॉइस को चुका सकता है",
+ "title_other": "{{count}} भुगतान इस इनवॉइस को चुका सकते हैं",
+ "wouldApply": "{{amount}} लगाया जाएगा",
+ "alsoCovers_one": "{{count}} और इनवॉइस भी शामिल है",
+ "alsoCovers_other": "{{count}} और इनवॉइस भी शामिल हैं"
+ }
},
"collections": {
"title": "संग्रह",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "ट्रांसफ़र आय या खर्च के रूप में नहीं गिने जाते",
"invoiceBadge": "इनवॉइस {{number}}",
"invoiceBadgeNoNumber": "इनवॉइस",
- "invoiceBadgeTooltip": "यह लेन-देन एक इनवॉइस चुकाता है। इसे खोलें।"
+ "invoiceBadgeTooltip": "यह लेन-देन एक इनवॉइस चुकाता है। इसे खोलें।",
+ "suggestionBadge": "सवाल",
+ "suggestionBadgeTooltip": "एक भुगतान इसे चुका सकता है। जवाब देने के लिए कतार खोलें।"
},
"accounts": {
"title": "खाते",
@@ -1178,7 +1187,6 @@
"ignoreActionHint": "(किसी मान की ज़रूरत नहीं)",
"selectCategory": "श्रेणी चुनें...",
"selectAccount": "खाता चुनें...",
- "ruleActive": "सक्रिय नियम",
"noConditions": "(कोई शर्त नहीं)",
"noActions": "(कोई कार्रवाई नहीं)",
"fieldDescription": "विवरण",
@@ -1213,7 +1221,17 @@
"importConfirmTitle": "वर्गीकरण नियम इंपोर्ट करें?",
"importConfirmDescription": "फ़ाइल {{file}} में {{count}} नियम हैं।",
"importOverwriteWarning": "इंपोर्ट करने से आपके मौजूदा वर्गीकरण नियम बदल जाएँगे। इसे पूर्ववत नहीं किया जा सकता।",
- "confirmOverwriteImport": "बदलें और इंपोर्ट करें"
+ "confirmOverwriteImport": "बदलें और इंपोर्ट करें",
+ "sectionHint": "लेन-देन को कैसे वर्गीकृत करें।",
+ "turnOn": "चालू करें",
+ "turnOff": "बंद करें",
+ "turnedOn": "नियम चालू किया गया",
+ "turnedOff": "नियम बंद किया गया",
+ "tab": {
+ "rules": "नियम",
+ "queue": "आपकी प्रतीक्षा में",
+ "history": "इतिहास"
+ }
},
"categories": {
"title": "श्रेणियाँ",
@@ -2238,5 +2256,200 @@
"subtitle": "Securo को अपने लोकल Ollama, OpenAI, Anthropic, या किसी भी OpenAI-संगत एंडपॉइंट की ओर इंगित करने के लिए एक कनेक्शन जोड़ें।"
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "इनवॉइस",
+ "invoicesHint": "जो आपको मिलना है और जो चुकाना है, उसके सामने",
+ "recurring": "आवर्ती",
+ "recurringHint": "जिसकी आप पहले से उम्मीद कर रहे थे, उसके सामने",
+ "inactive": "यहाँ उपयोग में नहीं"
+ },
+ "rule": {
+ "sameClientExact": "ज्ञात व्यक्ति, ठीक वही राशि",
+ "netOfWithholding": "ज्ञात व्यक्ति, स्रोत पर कर कटौती के बाद",
+ "exactAmountAnyClient": "ठीक वही राशि, कोई भी व्यक्ति",
+ "similarDescription": "राशि करीब और विवरण मिलता-जुलता",
+ "sameAccountExact": "वही खाता, ठीक वही राशि",
+ "unknown": "नियम",
+ "partPayment": "ज्ञात व्यक्ति, राशि का एक हिस्सा",
+ "severalInvoices": "ज्ञात व्यक्ति, एक साथ कई इनवॉइस"
+ },
+ "outcome": {
+ "link": "जोड़ता है",
+ "suggest": "सुझाता है"
+ },
+ "cond": {
+ "samePayee": "व्यक्ति वही है जो इनवॉइस पर है",
+ "sameAccount": "वही खाता",
+ "amountExact": "राशि बिल्कुल मेल खाती है",
+ "amountTolerance": "राशि {{percent}}% के भीतर है",
+ "amountRatio": "कर कटौती के बाद राशि मेल खाती है",
+ "window": "{{before}} दिन पहले से {{after}} दिन बाद तक",
+ "similarity": "विवरण कम से कम {{min}} मिलता-जुलता है",
+ "none": "कोई शर्त नहीं",
+ "accounts": "{{names}} में",
+ "payees": "{{names}} के लिए",
+ "moneyIn": "आने वाला पैसा",
+ "moneyOut": "जाने वाला पैसा",
+ "foreign": "विदेशी मुद्रा में",
+ "currencyIn": "{{codes}} में",
+ "atLeast": "कम से कम {{value}}",
+ "atMost": "ज्यादा से ज्यादा {{value}}",
+ "textContains": "विवरण में “{{text}}” है",
+ "textExcludes": "विवरण में “{{text}}” नहीं है",
+ "onArrival": "जब पैसा आता या जाता है",
+ "onIssue": "जब इनवॉइस जारी होता है",
+ "amountPartial": "राशि बकाया का एक हिस्सा चुकाती है",
+ "amountSet": "{{count}} तक इनवॉइस मिलकर यह राशि बनाते हैं"
+ },
+ "newRule": "नया मिलान नियम",
+ "saved": "नियम सहेजा गया",
+ "reset": "नियम बहाल किया गया",
+ "restore": "जो हम देते हैं वही बहाल करें",
+ "changed": "बदला हुआ",
+ "yours": "आपका",
+ "field": {
+ "name": "नाम",
+ "namePlaceholder": "जैसे: ज्ञात व्यक्ति, राशि करीब",
+ "outcome": "मेल होने पर क्या करे",
+ "outcomeHint": "जोड़ना अपने आप निपटा देता है। सुझाना नीचे की कतार में भेजता है, ताकि आप पुष्टि करें।",
+ "counterparty": "किसने चुकाया या किसे मिला",
+ "amount": "राशि",
+ "window": "तारीखों में कितना अंतर चल सकता है",
+ "windowHint": "देरी देय तिथि से गिनी जाती है, जल्दी होना इनवॉइस बनने के दिन से, इसलिए जारी होने के अगले दिन चुकाना हफ्तों पहले नहीं है।",
+ "beforeDays": "कितने दिन पहले",
+ "afterDays": "कितने दिन बाद",
+ "similarity": "विवरण की समानता",
+ "similarityHint": "0 से 1 तक। विवरण को अनदेखा करने के लिए खाली छोड़ें।",
+ "similarityOff": "बंद",
+ "scope": "यह नियम कब लागू होता है",
+ "scopeHint": "सब पर लागू करने के लिए खाली छोड़ें",
+ "accounts": "बैंक खाते",
+ "anyAccount": "कोई भी खाता",
+ "payees": "व्यक्ति",
+ "anyPayee": "कोई भी व्यक्ति",
+ "direction": "पैसा आना या जाना",
+ "currencyScope": "सिर्फ ये मुद्राएँ",
+ "currencyPlaceholder": "जैसे: USD, EUR",
+ "foreignOnly": "सिर्फ वे मुद्राएँ जो इस वर्कस्पेस की मुद्रा नहीं हैं",
+ "amountBand": "सिर्फ इस दायरे की राशि",
+ "noMinimum": "कोई न्यूनतम नहीं",
+ "noMaximum": "कोई अधिकतम नहीं",
+ "text": "विवरण का पाठ",
+ "textContains": "होना चाहिए…",
+ "textExcludes": "नहीं होना चाहिए…",
+ "textHint": "कॉमा से अलग करके कई लिखें, तो उनमें से कोई भी।",
+ "trigger": "हम कब देखते हैं",
+ "triggerHint": "मिलान दो मौकों पर होता है, और दोनों में सबूत एक जैसा नहीं होता।",
+ "amountMatch": "राशि कितनी करीब होनी चाहिए",
+ "amountMatchHint": "मूल कुल से नहीं, जो अब भी बकाया है उससे तुलना होती है।",
+ "amountBandHint": "खुद भुगतान के बारे में: वह आकार जो आप इस नियम से संभलवाना चाहते हैं, या नहीं चाहते।"
+ },
+ "counterparty": {
+ "any": "कोई भी",
+ "samePayee": "इनवॉइस का व्यक्ति"
+ },
+ "amount": {
+ "exact": "ठीक उतनी राशि जो बकाया है",
+ "tolerance": "एक दायरे के भीतर",
+ "ratio": "स्रोत पर कर कटौती के बाद",
+ "ratioHint": "आपके देश की कर कटौती दरें इस्तेमाल होती हैं। जब तक वे तय नहीं होतीं, कुछ भी मेल नहीं खाएगा।",
+ "partial": "बकाया का एक हिस्सा",
+ "partialHint": "किस्तों में किए गए भुगतान के लिए। जो बचता है वह बकाया रहता है, और अगला भुगतान उससे ठीक मेल खाता है।",
+ "set": "कई इनवॉइस मिलाकर",
+ "setHint": "उस भुगतान के लिए जो एक से ज्यादा इनवॉइस चुकाता है। अगर एक से ज्यादा संयोजन बनते हैं, तो हम चुनने के बजाय पूछते हैं।",
+ "setMax": "ज्यादा से ज्यादा इतने इनवॉइस",
+ "setFee": "इतने शुल्क की छूट",
+ "setFeeHint": "इनवॉइस की राशि का एक हिस्सा, उस भुगतान के लिए जो शुल्क कटकर आता या जाता है। शून्य का मतलब कुल बिल्कुल सही होना चाहिए।"
+ },
+ "queue": {
+ "title": "आपकी प्रतीक्षा में",
+ "hint": "वे मेल जिन्हें आपकी पुष्टि चाहिए।",
+ "empty": "देखने को कुछ नहीं। सब अपने आप मिल गया।",
+ "aPayment": "एक भुगतान",
+ "maySettle": "{{name}} को चुका सकता है",
+ "mayBe": "{{name}} हो सकता है",
+ "accept": "जोड़ें",
+ "declineHint": "यह मेल नहीं है। यह जोड़ी दोबारा नहीं सुझाई जाएगी।",
+ "linked": "जोड़ा गया",
+ "declined": "खारिज किया गया। हम दोबारा नहीं पूछेंगे",
+ "covers": "शामिल करता है"
+ },
+ "evidence": {
+ "amountExact": "राशि बिल्कुल मेल खाती है",
+ "amountOff": "अपेक्षित {{expected}}, हुआ {{moved}}",
+ "knownPayer": "ज्ञात व्यक्ति",
+ "unknownPayer": "व्यक्ति की पहचान नहीं",
+ "sameDay": "उसी दिन",
+ "daysApart": "{{days}} दिन का अंतर"
+ },
+ "direction": {
+ "any": "कोई भी",
+ "in": "आने वाला पैसा",
+ "out": "जाने वाला पैसा"
+ },
+ "step": {
+ "what": "यह नियम क्या है",
+ "which": "यह किस पैसे को देखता है",
+ "whichHint": "सब खाली छोड़ें तो यह सब कुछ देखता है",
+ "match": "मेल कब माना जाए",
+ "matchHint": "भुगतान और वादा कितने करीब होने चाहिए"
+ },
+ "trigger": {
+ "money_arrives": "जब पैसा आता या जाता है",
+ "money_arrivesHint": "भुगतान विवरण में दिखता है और हम वह इनवॉइस ढूँढते हैं जिसे वह चुकाता है।",
+ "invoice_issued": "जब इनवॉइस जारी होता है",
+ "invoice_issuedHint": "भुगतान पहले आया और इनवॉइस बाद में, इसलिए हम पीछे देखते हैं, उस पैसे में जो पहले से था।",
+ "both": "दोनों मौकों पर",
+ "bothHint": "यह नियम दोनों तरफ से भरोसे लायक है।"
+ },
+ "history": {
+ "title": "मिलान ने क्या किया",
+ "hint": "नया पहले।",
+ "byPerson": "आपके द्वारा",
+ "byRules": "नियमों द्वारा",
+ "more": "{{count}} और दिखाएँ",
+ "less": "कम दिखाएँ",
+ "action": {
+ "linked": "{{name}} से जोड़ा गया",
+ "accepted": "{{name}} के लिए सुझाव स्वीकार किया गया",
+ "suggested": "{{name}} के सामने सुझाया गया",
+ "declined": "{{name}} के लिए सुझाव खारिज किया गया",
+ "expired": "सुझाव की अवधि खत्म: {{name}}",
+ "unlinked": "{{name}} से अलग किया गया"
+ },
+ "empty": "अभी कुछ नहीं। जैसे-जैसे मिलान जोड़ता है, पूछता है और जवाब पाता है, यह भरता जाएगा।"
+ },
+ "moveUp": "इसे पहले आज़माएँ",
+ "moveDown": "इसे बाद में आज़माएँ",
+ "matchingTitle": "मिलान नियम",
+ "matchingHint": "हर भुगतान उसी से कैसे जुड़ता है जिसे वह चुकाता है।",
+ "pair": {
+ "owed": "क्या बकाया है",
+ "arrived": "जो पैसा चला",
+ "draftInvoice": "इनवॉइस का ड्राफ्ट",
+ "recurringBill": "आवर्ती बिल",
+ "noMoney": "इस पर कोई लेन-देन नहीं।",
+ "stillOpen": "अब भी बकाया",
+ "thisPayment": "यह भुगतान",
+ "wasApplied": "लगाया गया",
+ "wouldRemain": "बचेगा",
+ "wouldClose": "इसे चुका देता है",
+ "thePayment": "वह भुगतान",
+ "acrossInvoices": "{{count}} इनवॉइस में",
+ "dueOn": "देय {{date}}",
+ "totalOf": "कुल {{amount}}"
+ },
+ "discarded": "इस वर्कस्पेस से हटाए गए:",
+ "noneLeft": "इस समूह में कोई मिलान नियम नहीं बचा। यहाँ कुछ भी अपने आप मेल नहीं खाएगा।",
+ "confirmDeleteTitle": "यह नियम हटाएँ?",
+ "confirmDeleteDescription": "\"{{name}}\" कुछ भी तय करना बंद कर देगा। अगर यह हमारा दिया हुआ है तो आप इसे बाद में वापस ला सकते हैं।",
+ "exported": "मिलान नियम डाउनलोड हुए",
+ "imported": "{{imported}} नियम इंपोर्ट हुए ({{skipped}} छोड़े गए)",
+ "invalidImportFile": "यह मिलान नियमों की फ़ाइल नहीं है",
+ "importConfirmTitle": "मिलान नियम इंपोर्ट करें?",
+ "importConfirmDescription": "फ़ाइल {{file}} में {{count}} नियम हैं।",
+ "importOverwriteWarning": "इंपोर्ट करने पर इस वर्कस्पेस के मौजूदा मिलान नियम, उनके क्रम सहित, बदल जाएँगे। यह वापस नहीं किया जा सकता।"
}
}
diff --git a/frontend/src/locales/i18n.test.ts b/frontend/src/locales/i18n.test.ts
index 1f714d8a..b1db8dc6 100644
--- a/frontend/src/locales/i18n.test.ts
+++ b/frontend/src/locales/i18n.test.ts
@@ -44,7 +44,13 @@ const PLURAL_SUFFIXES = ['_zero', '_one', '_two', '_few', '_many', '_other']
function pluralBase(key: string): string | null {
for (const s of PLURAL_SUFFIXES) {
- if (key.endsWith(s)) return key.slice(0, -s.length)
+ if (key.endsWith(s)) {
+ const base = key.slice(0, -s.length)
+ // One suffix, not a chain. Without this, "title_one_other" reduces
+ // to "title_one", which en does have, and a malformed key rides in
+ // as though it were a plural form of a real one.
+ return PLURAL_SUFFIXES.some((inner) => base.endsWith(inner)) ? null : base
+ }
}
return null
}
@@ -149,12 +155,16 @@ describe('i18n locale files', () => {
for (const locale of LOCALES.filter((l: string) => l !== 'en')) {
it(locale, () => {
const keys = new Set(flattenKeys(JSON.parse(readRaw(locale))))
- // A key is valid if it exists in en directly, OR if it is a plural form
- // of a key that exists in en (e.g. "foo_few" is valid when en has "foo").
+ // A key is valid if it exists in en directly, OR if it is a plural
+ // form of a key en carries. English has two plural categories and
+ // Slavic languages have four, so "title_few" is a translation of
+ // "title_one"/"title_other" rather than an invented key: matching
+ // against the bare base alone would have forced those languages to
+ // choose between reading correctly and passing here.
const extra = [...keys].filter((k) => {
if (enKeys.has(k)) return false
const base = pluralBase(k)
- return !(base && enKeys.has(base))
+ return !(base && hasKeyOrPluralForms(enKeys, base))
})
expect(extra, `Extra keys in ${locale} not in en:`).toEqual([])
})
diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.json
index 145bb27a..0e529716 100644
--- a/frontend/src/locales/it.json
+++ b/frontend/src/locales/it.json
@@ -372,7 +372,14 @@
"fromSystem": "Da {{source}} · {{date}}",
"fromUpload": "Caricato · {{date}}"
},
- "draftSaved": "Bozza salvata"
+ "draftSaved": "Bozza salvata",
+ "suggestions": {
+ "title_one": "Un pagamento potrebbe saldare questa fattura",
+ "title_other": "{{count}} pagamenti potrebbero saldare questa fattura",
+ "wouldApply": "applicherebbe {{amount}}",
+ "alsoCovers_one": "copre anche altra {{count}} fattura",
+ "alsoCovers_other": "copre anche altre {{count}} fatture"
+ }
},
"collections": {
"title": "Collezioni",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "I trasferimenti non contano come entrate o spese",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Questa transazione salda una fattura. Aprila.",
+ "suggestionBadge": "Domanda",
+ "suggestionBadgeTooltip": "Un pagamento potrebbe saldare questa fattura. Apri la coda per rispondere."
},
"accounts": {
"title": "Conti",
@@ -1137,6 +1146,7 @@
"createMissingCategories": "Crea anche le categorie predefinite necessarie al pacchetto",
"duplicateName": "Esiste già una regola con questo nome",
"sectionTitle": "Regole di categorizzazione",
+ "sectionHint": "Come categorizzare le transazioni.",
"resetAndReapplyAll": "Reimposta e riapplica",
"confirmResetAndReapplyAll": "Reimpostare categorie, note e descrizioni gestite dalle regole delle transazioni corrispondenti e riapplicare tutte le regole attive?",
"add": "Aggiungi",
@@ -1179,7 +1189,10 @@
"ignoreActionHint": "(nessun valore richiesto)",
"selectCategory": "Seleziona categoria...",
"selectAccount": "Seleziona conto...",
- "ruleActive": "Regola attiva",
+ "turnOn": "Attiva",
+ "turnOff": "Disattiva",
+ "turnedOn": "Regola attivata",
+ "turnedOff": "Regola disattivata",
"noConditions": "(nessuna condizione)",
"noActions": "(nessuna azione)",
"fieldDescription": "Descrizione",
@@ -1206,15 +1219,20 @@
"sortBy_priority": "Priorità",
"sortBy_name": "Nome",
"sortBy_category": "Categoria",
- "export": "Export",
- "import": "Import",
- "exported": "Rules export downloaded",
- "imported": "Imported {{imported}} rules ({{skipped}} skipped)",
- "invalidImportFile": "Invalid rules import file",
- "importConfirmTitle": "Import categorization rules?",
- "importConfirmDescription": "File {{file}} contains {{count}} rules.",
- "importOverwriteWarning": "Importing will overwrite your current categorization rules. This cannot be undone.",
- "confirmOverwriteImport": "Overwrite and import"
+ "export": "Esporta",
+ "import": "Importa",
+ "exported": "Esportazione delle regole scaricata",
+ "imported": "{{imported}} regole importate ({{skipped}} saltate)",
+ "invalidImportFile": "File di importazione delle regole non valido",
+ "importConfirmTitle": "Importare le regole di categorizzazione?",
+ "importConfirmDescription": "Il file {{file}} contiene {{count}} regole.",
+ "importOverwriteWarning": "L'importazione sostituirà le tue regole di categorizzazione attuali. Non si può annullare.",
+ "confirmOverwriteImport": "Sovrascrivi e importa",
+ "tab": {
+ "rules": "Regole",
+ "queue": "In attesa di te",
+ "history": "Cronologia"
+ }
},
"categories": {
"title": "Categorie",
@@ -2239,5 +2257,200 @@
"openai": "OpenAI Responses API"
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Fatture",
+ "invoicesHint": "rispetto a ciò che devi incassare e pagare",
+ "recurring": "Ricorrenti",
+ "recurringHint": "rispetto a ciò che già ti aspettavi",
+ "inactive": "Non usata qui"
+ },
+ "rule": {
+ "sameClientExact": "Persona conosciuta, importo esatto",
+ "netOfWithholding": "Persona conosciuta, pagato con ritenuta",
+ "exactAmountAnyClient": "Importo esatto, chiunque",
+ "similarDescription": "Importo vicino e descrizione simile",
+ "sameAccountExact": "Stesso conto, importo esatto",
+ "unknown": "Regola",
+ "partPayment": "Persona conosciuta, parte dell'importo",
+ "severalInvoices": "Persona conosciuta, più fatture insieme"
+ },
+ "outcome": {
+ "link": "Collega da sola",
+ "suggest": "Suggerisce"
+ },
+ "cond": {
+ "samePayee": "la persona è quella della fattura",
+ "sameAccount": "lo stesso conto",
+ "amountExact": "l'importo corrisponde esattamente",
+ "amountTolerance": "l'importo rientra nel {{percent}}%",
+ "amountRatio": "l'importo corrisponde al netto della ritenuta",
+ "window": "fino a {{before}} giorni in anticipo, {{after}} in ritardo",
+ "similarity": "la descrizione è simile almeno {{min}}",
+ "none": "nessuna condizione",
+ "accounts": "su {{names}}",
+ "payees": "per {{names}}",
+ "moneyIn": "denaro in entrata",
+ "moneyOut": "denaro in uscita",
+ "foreign": "in valuta estera",
+ "currencyIn": "in {{codes}}",
+ "atLeast": "da {{value}}",
+ "atMost": "fino a {{value}}",
+ "textContains": "l'estratto dice “{{text}}”",
+ "textExcludes": "l'estratto non dice “{{text}}”",
+ "onArrival": "quando il denaro entra o esce",
+ "onIssue": "quando si emette una fattura",
+ "amountPartial": "l'importo copre parte di quanto è dovuto",
+ "amountSet": "fino a {{count}} fatture danno quella somma"
+ },
+ "newRule": "Nuova regola di riconciliazione",
+ "saved": "Regola salvata",
+ "reset": "Regola ripristinata",
+ "restore": "Torna all'impostazione predefinita",
+ "changed": "Modificata",
+ "yours": "Tua",
+ "field": {
+ "name": "Nome",
+ "namePlaceholder": "es.: Persona conosciuta, importo vicino",
+ "outcome": "Cosa fare quando corrisponde",
+ "outcomeHint": "Collega salda da sola. Suggerisci la manda nell'elenco qui sotto perché tu la confermi.",
+ "counterparty": "Chi ha pagato o incassato",
+ "amount": "Importo",
+ "window": "Distanza consentita tra le date",
+ "windowHint": "Il ritardo si conta dalla scadenza, l'anticipo dal giorno in cui la fattura è stata emessa: pagare il giorno dopo l'emissione non è settimane in anticipo.",
+ "beforeDays": "Giorni in anticipo",
+ "afterDays": "Giorni in ritardo",
+ "similarity": "Somiglianza della descrizione",
+ "similarityHint": "Da 0 a 1. Lascia vuoto per ignorare la descrizione.",
+ "similarityOff": "disattivata",
+ "scope": "Quando si applica questa regola",
+ "scopeHint": "Lascia vuoto per applicarla a tutto",
+ "accounts": "Conti bancari",
+ "anyAccount": "Qualsiasi conto",
+ "payees": "Persone",
+ "anyPayee": "Chiunque",
+ "direction": "Entrata o uscita",
+ "currencyScope": "Solo in queste valute",
+ "currencyPlaceholder": "es.: USD, EUR",
+ "foreignOnly": "Solo valute diverse da quella di questo spazio",
+ "amountBand": "Solo importi in questo intervallo",
+ "noMinimum": "nessun minimo",
+ "noMaximum": "nessun massimo",
+ "text": "Testo dell'estratto conto",
+ "textContains": "deve contenere…",
+ "textExcludes": "non deve contenere…",
+ "textHint": "Più parole separate da virgole significano una qualsiasi di esse.",
+ "trigger": "Quando cerchiamo",
+ "triggerHint": "La riconciliazione avviene in due momenti, e le prove non sono le stesse.",
+ "amountMatch": "Quanto deve avvicinarsi l'importo",
+ "amountMatchHint": "Confrontato con quanto è ancora dovuto, non con il totale originale.",
+ "amountBandHint": "Sul pagamento in sé: una dimensione che vuoi, o non vuoi, che questa regola tratti."
+ },
+ "counterparty": {
+ "any": "Chiunque",
+ "samePayee": "La persona della fattura"
+ },
+ "amount": {
+ "exact": "Esattamente l'importo dovuto",
+ "tolerance": "Entro un margine",
+ "ratio": "Al netto della ritenuta d'acconto",
+ "ratioHint": "Usa le aliquote di ritenuta del tuo paese. Finché non ci sono, la regola non corrisponde a nulla.",
+ "partial": "Parte di quanto è dovuto",
+ "partialHint": "Per chi paga a rate. Ciò che resta rimane aperto, e il pagamento successivo combacia esatto.",
+ "set": "Più fatture sommate",
+ "setHint": "Per un pagamento che copre più di una fattura. Se più di una combinazione torna, chiediamo invece di scegliere.",
+ "setMax": "Al massimo queste fatture",
+ "setFee": "Ammetti una commissione del",
+ "setFeeHint": "Una quota del valore delle fatture, per un pagamento che si muove al netto di una commissione. Zero significa che il totale deve essere esatto."
+ },
+ "queue": {
+ "title": "In attesa di te",
+ "hint": "Riconciliazioni che aspettano una tua conferma.",
+ "empty": "Niente da rivedere. Ha combaciato tutto da solo.",
+ "aPayment": "Un pagamento",
+ "maySettle": "potrebbe saldare {{name}}",
+ "mayBe": "potrebbe essere {{name}}",
+ "accept": "Collega",
+ "declineHint": "Non è questo. Questa coppia non verrà più suggerita.",
+ "linked": "Collegato",
+ "declined": "Scartato: non lo chiederemo più",
+ "covers": "copre"
+ },
+ "evidence": {
+ "amountExact": "l'importo corrisponde esattamente",
+ "amountOff": "atteso {{expected}}, movimentato {{moved}}",
+ "knownPayer": "persona conosciuta",
+ "unknownPayer": "persona non identificata",
+ "sameDay": "stesso giorno",
+ "daysApart": "{{days}} giorni di differenza"
+ },
+ "direction": {
+ "any": "Indifferente",
+ "in": "Denaro in entrata",
+ "out": "Denaro in uscita"
+ },
+ "step": {
+ "what": "Che regola è questa",
+ "which": "Quale denaro guarda",
+ "whichHint": "Lascia tutto vuoto e guarda tutto il denaro",
+ "match": "Quando conta come corrispondenza",
+ "matchHint": "Quanto devono combaciare il pagamento e la promessa"
+ },
+ "trigger": {
+ "money_arrives": "Quando il denaro entra o esce",
+ "money_arrivesHint": "Il pagamento compare nell'estratto conto e cerchiamo la fattura che salda.",
+ "invoice_issued": "Quando si emette una fattura",
+ "invoice_issuedHint": "Il pagamento è arrivato prima e la fattura dopo, quindi guardiamo indietro, al denaro che era già lì.",
+ "both": "In entrambi i momenti",
+ "bothHint": "La regola vale in tutti e due i versi."
+ },
+ "history": {
+ "title": "Cosa ha fatto la riconciliazione",
+ "hint": "Dalle più recenti.",
+ "byPerson": "da te",
+ "byRules": "dalle regole",
+ "more": "Mostra altri {{count}}",
+ "less": "Mostra meno",
+ "action": {
+ "linked": "Collegato a {{name}}",
+ "accepted": "Suggerimento accettato per {{name}}",
+ "suggested": "Proposto per {{name}}",
+ "declined": "Suggerimento scartato per {{name}}",
+ "expired": "Suggerimento scaduto: {{name}}",
+ "unlinked": "Scollegato da {{name}}"
+ },
+ "empty": "Ancora niente. Si riempie man mano che la riconciliazione collega, chiede e riceve risposta."
+ },
+ "moveUp": "Provare questa prima",
+ "moveDown": "Provare questa dopo",
+ "matchingTitle": "Regole di riconciliazione",
+ "matchingHint": "Come ogni pagamento viene legato a ciò che salda.",
+ "pair": {
+ "owed": "Quanto è dovuto",
+ "arrived": "Ciò che si è mosso",
+ "draftInvoice": "Fattura in bozza",
+ "recurringBill": "Spesa ricorrente",
+ "noMoney": "Nessuna transazione qui.",
+ "stillOpen": "ancora aperto",
+ "thisPayment": "questo pagamento",
+ "wasApplied": "applicato",
+ "wouldRemain": "resterebbe",
+ "wouldClose": "la salda",
+ "thePayment": "il pagamento",
+ "acrossInvoices": "su {{count}} fatture",
+ "dueOn": "scade {{date}}",
+ "totalOf": "totale di {{amount}}"
+ },
+ "discarded": "Eliminate da questo spazio:",
+ "noneLeft": "Nessuna regola di riconciliazione in questo insieme. Qui non viene riconciliato nulla in automatico.",
+ "confirmDeleteTitle": "Eliminare questa regola?",
+ "confirmDeleteDescription": "\"{{name}}\" smette di decidere qualsiasi cosa. Se è una delle nostre, puoi riportarla indietro più tardi.",
+ "exported": "Regole di riconciliazione scaricate",
+ "imported": "{{imported}} regole importate ({{skipped}} ignorate)",
+ "invalidImportFile": "Questo non è un file di regole di riconciliazione",
+ "importConfirmTitle": "Importare le regole di riconciliazione?",
+ "importConfirmDescription": "Il file {{file}} contiene {{count}} regole.",
+ "importOverwriteWarning": "L'importazione sostituisce le regole di riconciliazione di questo spazio, incluso il loro ordine. Non è reversibile."
}
}
diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.json
index 9d7d6f75..72ef7691 100644
--- a/frontend/src/locales/ja.json
+++ b/frontend/src/locales/ja.json
@@ -372,7 +372,14 @@
"fromSystem": "{{source}}から · {{date}}",
"fromUpload": "アップロード · {{date}}"
},
- "draftSaved": "下書きを保存しました"
+ "draftSaved": "下書きを保存しました",
+ "suggestions": {
+ "title_one": "この請求書を消し込める支払いがあります",
+ "title_other": "この請求書を消し込める支払いが{{count}}件あります",
+ "wouldApply": "{{amount}}を充当します",
+ "alsoCovers_one": "他に{{count}}件の請求書もカバーします",
+ "alsoCovers_other": "他に{{count}}件の請求書もカバーします"
+ }
},
"collections": {
"title": "コレクション",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "振替は収入・支出にカウントされません",
"invoiceBadge": "請求書 {{number}}",
"invoiceBadgeNoNumber": "請求書",
- "invoiceBadgeTooltip": "この取引は請求書を決済しています。開く。"
+ "invoiceBadgeTooltip": "この取引は請求書を決済しています。開く。",
+ "suggestionBadge": "要確認",
+ "suggestionBadgeTooltip": "これが何かを消し込む可能性があります。キューを開いて回答してください。"
},
"accounts": {
"title": "口座",
@@ -1178,7 +1187,6 @@
"ignoreActionHint": "(値は不要)",
"selectCategory": "カテゴリを選択...",
"selectAccount": "口座を選択...",
- "ruleActive": "有効なルール",
"noConditions": "(条件なし)",
"noActions": "(操作なし)",
"fieldDescription": "摘要",
@@ -1213,7 +1221,17 @@
"importConfirmTitle": "分類ルールをインポートしますか?",
"importConfirmDescription": "ファイル{{file}}には{{count}}件のルールが含まれています。",
"importOverwriteWarning": "インポートすると現在の分類ルールを上書きします。この操作は取り消せません。",
- "confirmOverwriteImport": "上書きしてインポート"
+ "confirmOverwriteImport": "上書きしてインポート",
+ "sectionHint": "取引を分類する方法です。",
+ "turnOn": "有効にする",
+ "turnOff": "無効にする",
+ "turnedOn": "ルールを有効にしました",
+ "turnedOff": "ルールを無効にしました",
+ "tab": {
+ "rules": "ルール",
+ "queue": "要対応",
+ "history": "履歴"
+ }
},
"categories": {
"title": "カテゴリ",
@@ -2238,5 +2256,200 @@
"subtitle": "接続を追加して、ローカルのOllama、OpenAI、Anthropic、任意のOpenAI互換エンドポイントをSecuroに指し示してください。"
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "請求書",
+ "invoicesHint": "受け取る分と支払う分に対して",
+ "recurring": "定期取引",
+ "recurringHint": "すでに予定していたものに対して",
+ "inactive": "ここでは使いません"
+ },
+ "rule": {
+ "sameClientExact": "既知の相手、金額が一致",
+ "netOfWithholding": "既知の相手、源泉徴収後の入金",
+ "exactAmountAnyClient": "金額が一致、相手は問わない",
+ "similarDescription": "金額が近く摘要も類似",
+ "sameAccountExact": "同じ口座、金額が一致",
+ "unknown": "ルール",
+ "partPayment": "既知の相手、金額の一部",
+ "severalInvoices": "既知の相手、複数の請求書をまとめて"
+ },
+ "outcome": {
+ "link": "自動連結",
+ "suggest": "提案"
+ },
+ "cond": {
+ "samePayee": "取引相手が請求書と同じ",
+ "sameAccount": "同じ口座",
+ "amountExact": "金額が完全に一致",
+ "amountTolerance": "金額が{{percent}}%以内",
+ "amountRatio": "源泉徴収を差し引いた金額が一致",
+ "window": "{{before}}日前から{{after}}日後まで",
+ "similarity": "摘要が{{min}}以上類似",
+ "none": "条件なし",
+ "accounts": "{{names}}で",
+ "payees": "{{names}}向け",
+ "moneyIn": "入金",
+ "moneyOut": "出金",
+ "foreign": "外貨で",
+ "currencyIn": "{{codes}}で",
+ "atLeast": "{{value}}以上",
+ "atMost": "{{value}}以下",
+ "textContains": "明細に「{{text}}」を含む",
+ "textExcludes": "明細に「{{text}}」を含まない",
+ "onArrival": "入金または出金があったとき",
+ "onIssue": "請求書を発行したとき",
+ "amountPartial": "金額が未回収分の一部を満たす",
+ "amountSet": "最大{{count}}件の請求書の合計が一致"
+ },
+ "newRule": "新しい照合ルール",
+ "saved": "ルールを保存しました",
+ "reset": "ルールを元に戻しました",
+ "restore": "標準の内容に戻す",
+ "changed": "変更済み",
+ "yours": "独自",
+ "field": {
+ "name": "名前",
+ "namePlaceholder": "例: 既知の相手、金額が近い",
+ "outcome": "一致したときの動作",
+ "outcomeHint": "自動連結はその場で消し込みます。提案は下のキューに送り、確認を求めます。",
+ "counterparty": "支払った側、または受け取った側",
+ "amount": "金額",
+ "window": "日付のずれをどこまで許すか",
+ "windowHint": "遅れは支払期日から、早さは請求書を作成した日から数えます。発行の翌日に支払われても数週間早いことにはなりません。",
+ "beforeDays": "何日前まで",
+ "afterDays": "何日後まで",
+ "similarity": "摘要の類似度",
+ "similarityHint": "0から1まで。空欄にすると摘要を見ません。",
+ "similarityOff": "無効",
+ "scope": "このルールを適用する範囲",
+ "scopeHint": "空欄ならすべてに適用します",
+ "accounts": "銀行口座",
+ "anyAccount": "すべての口座",
+ "payees": "取引相手",
+ "anyPayee": "すべての相手",
+ "direction": "入金か出金か",
+ "currencyScope": "これらの通貨のみ",
+ "currencyPlaceholder": "例: USD, EUR",
+ "foreignOnly": "このワークスペースの通貨以外のみ",
+ "amountBand": "この範囲の金額のみ",
+ "noMinimum": "下限なし",
+ "noMaximum": "上限なし",
+ "text": "明細の摘要",
+ "textContains": "含む必要がある…",
+ "textExcludes": "含んではいけない…",
+ "textHint": "カンマで区切ると、そのいずれかという意味になります。",
+ "trigger": "照合するタイミング",
+ "triggerHint": "照合は2つの場面で行われ、手がかりはそれぞれ異なります。",
+ "amountMatch": "金額がどれだけ近い必要があるか",
+ "amountMatchHint": "元の合計ではなく、未回収の残額と比べます。",
+ "amountBandHint": "支払いそのものについて。このルールに扱わせたい、あるいは扱わせたくない金額の大きさです。"
+ },
+ "counterparty": {
+ "any": "誰でも",
+ "samePayee": "請求書の取引相手"
+ },
+ "amount": {
+ "exact": "未回収額とちょうど同じ",
+ "tolerance": "一定の範囲内",
+ "ratio": "源泉徴収を差し引いた額",
+ "ratioHint": "お使いの国の源泉徴収率を使います。設定されるまで何も一致しません。",
+ "partial": "未回収額の一部",
+ "partialHint": "分割で支払われる場合に使います。残りは未回収のまま残り、次の支払いがちょうど一致します。",
+ "set": "複数の請求書の合計",
+ "setHint": "複数の請求書をまとめて支払う場合に使います。合計の合う組み合わせが2通り以上あるときは、選ばずに確認します。",
+ "setMax": "請求書は最大でこの件数",
+ "setFee": "手数料の許容",
+ "setFeeHint": "請求書の金額に対する割合です。手数料を差し引いて入出金される支払い向け。0なら合計がぴったり一致する必要があります。"
+ },
+ "queue": {
+ "title": "要対応",
+ "hint": "確認が必要な照合です。",
+ "empty": "確認するものはありません。すべて自動で照合されました。",
+ "aPayment": "ある支払い",
+ "maySettle": "が{{name}}を消し込む可能性があります",
+ "mayBe": "が{{name}}である可能性があります",
+ "accept": "結びつける",
+ "declineHint": "一致しません。この組み合わせは二度と提案されません。",
+ "linked": "結びつけました",
+ "declined": "却下しました。二度と確認しません",
+ "covers": "がカバーする範囲"
+ },
+ "evidence": {
+ "amountExact": "金額が完全に一致",
+ "amountOff": "想定{{expected}}、実際{{moved}}",
+ "knownPayer": "既知の相手",
+ "unknownPayer": "相手を特定できず",
+ "sameDay": "同じ日",
+ "daysApart": "{{days}}日差"
+ },
+ "direction": {
+ "any": "どちらでも",
+ "in": "入金",
+ "out": "出金"
+ },
+ "step": {
+ "what": "このルールの内容",
+ "which": "どの入出金を見るか",
+ "whichHint": "すべて空欄にすると、すべてを見ます",
+ "match": "一致とみなす条件",
+ "matchHint": "支払いと請求がどれだけ近い必要があるか"
+ },
+ "trigger": {
+ "money_arrives": "入金または出金があったとき",
+ "money_arrivesHint": "支払いが明細に現れた時点で、それが消し込む請求書を探します。",
+ "invoice_issued": "請求書を発行したとき",
+ "invoice_issuedHint": "支払いが先で請求書が後の場合です。すでにあった入出金をさかのぼって探します。",
+ "both": "どちらの場面でも",
+ "bothHint": "このルールはどちらの向きでも使います。"
+ },
+ "history": {
+ "title": "照合が行ったこと",
+ "hint": "新しい順。",
+ "byPerson": "あなたの操作",
+ "byRules": "ルールによる",
+ "more": "さらに{{count}}件表示",
+ "less": "表示を減らす",
+ "action": {
+ "linked": "{{name}}と結びつけました",
+ "accepted": "{{name}}への提案を承認しました",
+ "suggested": "{{name}}に対して提案しました",
+ "declined": "{{name}}への提案を却下しました",
+ "expired": "提案が期限切れになりました: {{name}}",
+ "unlinked": "{{name}}との結びつきを解除しました"
+ },
+ "empty": "まだ何もありません。照合が結びつけ、確認を求め、回答されるにつれて埋まります。"
+ },
+ "moveUp": "これをもっと先に試す",
+ "moveDown": "これをもっと後に試す",
+ "matchingTitle": "照合ルール",
+ "matchingHint": "各支払いが何を消し込むかを結びつける方法です。",
+ "pair": {
+ "owed": "未回収の内容",
+ "arrived": "動いたお金",
+ "draftInvoice": "下書きの請求書",
+ "recurringBill": "定期の支払い",
+ "noMoney": "これに対応する取引はありません。",
+ "stillOpen": "未回収",
+ "thisPayment": "この支払い",
+ "wasApplied": "充当済み",
+ "wouldRemain": "残る金額",
+ "wouldClose": "消し込みます",
+ "thePayment": "その支払い",
+ "acrossInvoices": "請求書{{count}}件にわたって",
+ "dueOn": "期日 {{date}}",
+ "totalOf": "合計 {{amount}}"
+ },
+ "discarded": "このワークスペースで削除済み:",
+ "noneLeft": "このセットに照合ルールは残っていません。ここでは自動で照合されません。",
+ "confirmDeleteTitle": "このルールを削除しますか?",
+ "confirmDeleteDescription": "「{{name}}」は何も判断しなくなります。標準のルールであれば後で戻せます。",
+ "exported": "照合ルールをダウンロードしました",
+ "imported": "{{imported}}件のルールをインポートしました({{skipped}}件スキップ)",
+ "invalidImportFile": "照合ルールのファイルではありません",
+ "importConfirmTitle": "照合ルールをインポートしますか?",
+ "importConfirmDescription": "ファイル{{file}}には{{count}}件のルールが含まれています。",
+ "importOverwriteWarning": "インポートすると、このワークスペースの現在の照合ルールが順序ごと置き換わります。この操作は取り消せません。"
}
}
diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json
index 18b737ac..48fa0fba 100644
--- a/frontend/src/locales/nl.json
+++ b/frontend/src/locales/nl.json
@@ -372,7 +372,14 @@
"fromSystem": "Van {{source}} · {{date}}",
"fromUpload": "Geüpload · {{date}}"
},
- "draftSaved": "Concept opgeslagen"
+ "draftSaved": "Concept opgeslagen",
+ "suggestions": {
+ "title_one": "Een betaling kan deze factuur voldoen",
+ "title_other": "{{count}} betalingen kunnen deze factuur voldoen",
+ "wouldApply": "zou {{amount}} toepassen",
+ "alsoCovers_one": "dekt ook {{count}} andere factuur",
+ "alsoCovers_other": "dekt ook {{count}} andere facturen"
+ }
},
"collections": {
"title": "Collecties",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "Overdrachten worden niet meegeteld als inkomsten of uitgaven",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Deze transactie rekent een factuur af. Openen.",
+ "suggestionBadge": "Vraag",
+ "suggestionBadgeTooltip": "Een betaling kan deze factuur voldoen. Open de wachtrij om te antwoorden."
},
"accounts": {
"title": "Rekeningen",
@@ -1138,6 +1147,7 @@
"createMissingCategories": "Maak ook standaardcategorieën aan die het pakket nodig heeft",
"duplicateName": "Er bestaat al een regel met deze naam",
"sectionTitle": "Categorisatieregels",
+ "sectionHint": "Hoe transacties worden gecategoriseerd.",
"resetAndReapplyAll": "Resetten en opnieuw aanvragen",
"confirmResetAndReapplyAll": "Overeenkomende transactiecategorieën, notities en door regels beheerde beschrijvingen resetten en vervolgens alle actieve regels opnieuw toepassen?",
"add": "Toevoegen",
@@ -1178,7 +1188,10 @@
"ignoreActionHint": "(geen waarde nodig)",
"selectCategory": "Categorie selecteren...",
"selectAccount": "Account selecteren...",
- "ruleActive": "Actieve regel",
+ "turnOn": "Aanzetten",
+ "turnOff": "Uitzetten",
+ "turnedOn": "Regel ingeschakeld",
+ "turnedOff": "Regel uitgeschakeld",
"noConditions": "(geen voorwaarden)",
"noActions": "(geen acties)",
"fieldDescription": "Beschrijving",
@@ -1215,7 +1228,12 @@
"importOverwriteWarning": "Als u importeert, worden uw huidige categorisatieregels overschreven. Dit kan niet ongedaan worden gemaakt.",
"confirmOverwriteImport": "Overschrijven en importeren",
"confirmDeleteTitle": "Regel verwijderen?",
- "confirmDeleteDescription": "De regel \"{{name}}\" wordt permanent verwijderd en wordt niet meer uitgevoerd. Wijzigingen die al op bestaande transacties zijn toegepast, blijven behouden. Deze actie kan niet ongedaan worden gemaakt."
+ "confirmDeleteDescription": "De regel \"{{name}}\" wordt permanent verwijderd en wordt niet meer uitgevoerd. Wijzigingen die al op bestaande transacties zijn toegepast, blijven behouden. Deze actie kan niet ongedaan worden gemaakt.",
+ "tab": {
+ "rules": "Regels",
+ "queue": "Wacht op jou",
+ "history": "Geschiedenis"
+ }
},
"categories": {
"title": "Categorieën",
@@ -2240,5 +2258,200 @@
"subtitle": "Voeg een verbinding toe om Securo te richten op uw lokale Ollama, OpenAI, Anthropic of een ander OpenAI-compatibel endpoint."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Facturen",
+ "invoicesHint": "tegenover wat je moet ontvangen en betalen",
+ "recurring": "Terugkerend",
+ "recurringHint": "tegenover wat je al verwachtte",
+ "inactive": "Hier niet in gebruik"
+ },
+ "rule": {
+ "sameClientExact": "Bekende persoon, exact bedrag",
+ "netOfWithholding": "Bekende persoon, betaald na inhouding",
+ "exactAmountAnyClient": "Exact bedrag, iedereen",
+ "similarDescription": "Vergelijkbaar bedrag en gelijkende omschrijving",
+ "sameAccountExact": "Zelfde rekening, exact bedrag",
+ "unknown": "Regel",
+ "partPayment": "Bekende persoon, deel van het bedrag",
+ "severalInvoices": "Bekende persoon, meerdere facturen tegelijk"
+ },
+ "outcome": {
+ "link": "Koppelt zelf",
+ "suggest": "Stelt voor"
+ },
+ "cond": {
+ "samePayee": "de persoon is die van de factuur",
+ "sameAccount": "dezelfde rekening",
+ "amountExact": "het bedrag klopt precies",
+ "amountTolerance": "het bedrag valt binnen {{percent}}%",
+ "amountRatio": "het bedrag klopt na inhouding",
+ "window": "tot {{before}} dagen te vroeg, {{after}} dagen te laat",
+ "similarity": "de omschrijving lijkt minstens {{min}}",
+ "none": "geen voorwaarden",
+ "accounts": "op {{names}}",
+ "payees": "voor {{names}}",
+ "moneyIn": "inkomend geld",
+ "moneyOut": "uitgaand geld",
+ "foreign": "in vreemde valuta",
+ "currencyIn": "in {{codes}}",
+ "atLeast": "vanaf {{value}}",
+ "atMost": "tot {{value}}",
+ "textContains": "het afschrift zegt “{{text}}”",
+ "textExcludes": "het afschrift zegt niet “{{text}}”",
+ "onArrival": "wanneer geld binnenkomt of weggaat",
+ "onIssue": "wanneer een factuur wordt opgesteld",
+ "amountPartial": "het bedrag dekt een deel van wat openstaat",
+ "amountSet": "tot {{count}} facturen tellen op tot dat bedrag"
+ },
+ "newRule": "Nieuwe afletterregel",
+ "saved": "Regel opgeslagen",
+ "reset": "Regel hersteld",
+ "restore": "Terug naar de standaard",
+ "changed": "Gewijzigd",
+ "yours": "Van jou",
+ "field": {
+ "name": "Naam",
+ "namePlaceholder": "bijv. Bekende persoon, bedrag dichtbij",
+ "outcome": "Wat er gebeurt als hij past",
+ "outcomeHint": "Koppelen boekt vanzelf. Voorstellen zet het in de lijst hieronder, zodat jij het bevestigt.",
+ "counterparty": "Wie betaalde of ontving",
+ "amount": "Bedrag",
+ "window": "Toegestaan verschil tussen de datums",
+ "windowHint": "Te laat telt vanaf de vervaldatum, te vroeg vanaf de dag dat de factuur is opgesteld, dus de dag na uitgifte betalen is niet weken te vroeg.",
+ "beforeDays": "Dagen te vroeg",
+ "afterDays": "Dagen te laat",
+ "similarity": "Gelijkenis van de omschrijving",
+ "similarityHint": "Van 0 tot 1. Laat leeg om de omschrijving te negeren.",
+ "similarityOff": "uit",
+ "scope": "Wanneer deze regel geldt",
+ "scopeHint": "Laat leeg om voor alles te gelden",
+ "accounts": "Bankrekeningen",
+ "anyAccount": "Elke rekening",
+ "payees": "Personen",
+ "anyPayee": "Iedereen",
+ "direction": "Inkomend of uitgaand",
+ "currencyScope": "Alleen in deze valuta",
+ "currencyPlaceholder": "bijv. USD, EUR",
+ "foreignOnly": "Alleen valuta anders dan die van deze werkruimte",
+ "amountBand": "Alleen bedragen in dit bereik",
+ "noMinimum": "geen minimum",
+ "noMaximum": "geen maximum",
+ "text": "Tekst op het afschrift",
+ "textContains": "moet bevatten…",
+ "textExcludes": "mag niet bevatten…",
+ "textHint": "Meerdere, gescheiden door komma's, betekent een van deze.",
+ "trigger": "Wanneer we zoeken",
+ "triggerHint": "Afletteren gebeurt op twee momenten, en het bewijs is niet hetzelfde.",
+ "amountMatch": "Hoe nauw het bedrag moet kloppen",
+ "amountMatchHint": "Vergeleken met wat nog openstaat, niet met het oorspronkelijke totaal.",
+ "amountBandHint": "Over de betaling zelf: een omvang die je deze regel wel of niet wilt laten behandelen."
+ },
+ "counterparty": {
+ "any": "Iedereen",
+ "samePayee": "De persoon op de factuur"
+ },
+ "amount": {
+ "exact": "Precies het openstaande bedrag",
+ "tolerance": "Binnen een marge",
+ "ratio": "Na inhouding van bronbelasting",
+ "ratioHint": "Gebruikt de inhoudingspercentages van jouw land. Zolang die er niet zijn, matcht de regel niets.",
+ "partial": "Een deel van wat openstaat",
+ "partialHint": "Voor wie in termijnen betaalt. Wat overblijft staat nog open, en de volgende betaling klopt precies.",
+ "set": "Meerdere facturen bij elkaar",
+ "setHint": "Voor een betaling die meer dan één factuur dekt. Passen er meerdere combinaties, dan vragen we het in plaats van te kiezen.",
+ "setMax": "Hoogstens zoveel facturen",
+ "setFee": "Sta een kosten toe van",
+ "setFeeHint": "Een deel van de factuurwaarde, voor een betaling die netto na aftrek loopt. Nul betekent dat het totaal exact moet zijn."
+ },
+ "queue": {
+ "title": "Wacht op jou",
+ "hint": "Koppelingen die je bevestiging nodig hebben.",
+ "empty": "Niets te beoordelen. Alles is vanzelf gekoppeld.",
+ "aPayment": "Een betaling",
+ "maySettle": "voldoet mogelijk {{name}}",
+ "mayBe": "is mogelijk {{name}}",
+ "accept": "Koppelen",
+ "declineHint": "Dit is het niet. Dit paar wordt niet opnieuw voorgesteld.",
+ "linked": "Gekoppeld",
+ "declined": "Afgewezen. We vragen het niet nog eens",
+ "covers": "dekt"
+ },
+ "evidence": {
+ "amountExact": "bedrag klopt precies",
+ "amountOff": "verwacht {{expected}}, bewogen {{moved}}",
+ "knownPayer": "bekende persoon",
+ "unknownPayer": "persoon niet herkend",
+ "sameDay": "zelfde dag",
+ "daysApart": "{{days}} dagen verschil"
+ },
+ "direction": {
+ "any": "Maakt niet uit",
+ "in": "Inkomend geld",
+ "out": "Uitgaand geld"
+ },
+ "step": {
+ "what": "Wat deze regel is",
+ "which": "Naar welk geld hij kijkt",
+ "whichHint": "Laat alles leeg en hij kijkt naar al het geld",
+ "match": "Wanneer het als match telt",
+ "matchHint": "Hoe nauw de betaling en de belofte moeten passen"
+ },
+ "trigger": {
+ "money_arrives": "Wanneer geld binnenkomt of weggaat",
+ "money_arrivesHint": "De betaling verschijnt op het afschrift en wij zoeken de factuur die ze afrekent.",
+ "invoice_issued": "Wanneer een factuur wordt opgesteld",
+ "invoice_issuedHint": "De betaling kwam eerst en de factuur daarna, dus kijken we terug naar geld dat er al was.",
+ "both": "Op beide momenten",
+ "bothHint": "De regel geldt beide kanten op."
+ },
+ "history": {
+ "title": "Wat het afletteren deed",
+ "hint": "Nieuwste eerst.",
+ "byPerson": "door jou",
+ "byRules": "door de regels",
+ "more": "Toon {{count}} meer",
+ "less": "Toon minder",
+ "action": {
+ "linked": "Gekoppeld aan {{name}}",
+ "accepted": "Voorstel voor {{name}} geaccepteerd",
+ "suggested": "Voorgesteld voor {{name}}",
+ "declined": "Voorstel voor {{name}} afgewezen",
+ "expired": "Voorstel verlopen: {{name}}",
+ "unlinked": "Ontkoppeld van {{name}}"
+ },
+ "empty": "Nog niets. Dit vult zich terwijl het afletteren koppelt, vraagt en antwoord krijgt."
+ },
+ "moveUp": "Deze eerder proberen",
+ "moveDown": "Deze later proberen",
+ "matchingTitle": "Afletterregels",
+ "matchingHint": "Hoe elke betaling wordt gekoppeld aan wat ze afrekent.",
+ "pair": {
+ "owed": "Wat openstaat",
+ "arrived": "Wat er bewoog",
+ "draftInvoice": "Conceptfactuur",
+ "recurringBill": "Terugkerende rekening",
+ "noMoney": "Geen transactie hierbij.",
+ "stillOpen": "nog open",
+ "thisPayment": "deze betaling",
+ "wasApplied": "toegepast",
+ "wouldRemain": "blijft open",
+ "wouldClose": "voldoet hem",
+ "thePayment": "de betaling",
+ "acrossInvoices": "over {{count}} facturen",
+ "dueOn": "vervalt {{date}}",
+ "totalOf": "totaal {{amount}}"
+ },
+ "discarded": "Verwijderd uit deze werkruimte:",
+ "noneLeft": "Geen koppelregels meer in deze set. Hier wordt niets automatisch gekoppeld.",
+ "confirmDeleteTitle": "Deze regel verwijderen?",
+ "confirmDeleteDescription": "“{{name}}” beslist niets meer. Als het een van onze regels is, kun je hem later terughalen.",
+ "exported": "Koppelregels gedownload",
+ "imported": "{{imported}} regels geïmporteerd ({{skipped}} overgeslagen)",
+ "invalidImportFile": "Dit is geen bestand met koppelregels",
+ "importConfirmTitle": "Koppelregels importeren?",
+ "importConfirmDescription": "Bestand {{file}} bevat {{count}} regels.",
+ "importOverwriteWarning": "Importeren vervangt de koppelregels van deze werkruimte, inclusief hun volgorde. Dit kan niet ongedaan worden gemaakt."
}
}
diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.json
index 1cf82a0c..a9fde0b8 100644
--- a/frontend/src/locales/pl.json
+++ b/frontend/src/locales/pl.json
@@ -372,7 +372,18 @@
"fromSystem": "Z {{source}} · {{date}}",
"fromUpload": "Przesłano · {{date}}"
},
- "draftSaved": "Szkic zapisany"
+ "draftSaved": "Szkic zapisany",
+ "suggestions": {
+ "title_one": "Płatność może opłacić tę fakturę",
+ "title_few": "{{count}} płatności mogą rozliczyć tę fakturę",
+ "title_many": "{{count}} płatności może rozliczyć tę fakturę",
+ "title_other": "{{count}} płatności może opłacić tę fakturę",
+ "alsoCovers_one": "obejmuje też {{count}} inną fakturę",
+ "alsoCovers_few": "i jeszcze {{count}} faktury",
+ "alsoCovers_many": "i jeszcze {{count}} faktur",
+ "alsoCovers_other": "obejmuje też {{count}} innych faktur",
+ "wouldApply": "zastosowałaby {{amount}}"
+ }
},
"collections": {
"title": "Kolekcje",
@@ -840,7 +851,9 @@
"calendarTransfersExcluded": "Transfery nie liczą się jako przychody ani wydatki",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Ta transakcja rozlicza fakturę. Otwórz ją.",
+ "suggestionBadge": "Pytanie",
+ "suggestionBadgeTooltip": "Płatność może opłacić tę fakturę. Otwórz kolejkę, aby odpowiedzieć."
},
"accounts": {
"title": "Konta",
@@ -1196,6 +1209,7 @@
"createMissingCategories": "Utwórz też domyślne kategorie wymagane przez pakiet",
"duplicateName": "Reguła o tej nazwie już istnieje",
"sectionTitle": "Reguły kategoryzacji",
+ "sectionHint": "Jak kategoryzować transakcje.",
"resetAndReapplyAll": "Zresetuj i zastosuj ponownie",
"confirmResetAndReapplyAll": "Zresetować kategorie, notatki i opisy zarządzane przez reguły pasujących transakcji, a następnie zastosować ponownie wszystkie aktywne reguły?",
"add": "Dodaj",
@@ -1241,7 +1255,10 @@
"ignoreActionHint": "(wartość niewymagana)",
"selectCategory": "Wybierz kategorię...",
"selectAccount": "Wybierz konto...",
- "ruleActive": "Reguła aktywna",
+ "turnOn": "Włącz",
+ "turnOff": "Wyłącz",
+ "turnedOn": "Reguła włączona",
+ "turnedOff": "Reguła wyłączona",
"noConditions": "(brak warunków)",
"noActions": "(brak akcji)",
"fieldDescription": "Opis",
@@ -1268,15 +1285,20 @@
"sortBy_priority": "Priorytet",
"sortBy_name": "Nazwa",
"sortBy_category": "Kategoria",
- "export": "Export",
- "import": "Import",
- "exported": "Rules export downloaded",
- "imported": "Imported {{imported}} rules ({{skipped}} skipped)",
- "invalidImportFile": "Invalid rules import file",
- "importConfirmTitle": "Import categorization rules?",
- "importConfirmDescription": "File {{file}} contains {{count}} rules.",
- "importOverwriteWarning": "Importing will overwrite your current categorization rules. This cannot be undone.",
- "confirmOverwriteImport": "Overwrite and import"
+ "export": "Eksportuj",
+ "import": "Importuj",
+ "exported": "Pobrano eksport reguł",
+ "imported": "Zaimportowano {{imported}} reguł ({{skipped}} pominięto)",
+ "invalidImportFile": "Nieprawidłowy plik importu reguł",
+ "importConfirmTitle": "Zaimportować reguły kategoryzacji?",
+ "importConfirmDescription": "Plik {{file}} zawiera {{count}} reguł.",
+ "importOverwriteWarning": "Import zastąpi obecne reguły kategoryzacji. Tego nie można cofnąć.",
+ "confirmOverwriteImport": "Nadpisz i importuj",
+ "tab": {
+ "rules": "Reguły",
+ "queue": "Czeka na Ciebie",
+ "history": "Historia"
+ }
},
"categories": {
"title": "Kategorie",
@@ -2340,5 +2362,200 @@
"openai": "OpenAI Responses API"
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Faktury",
+ "invoicesHint": "wobec tego, co masz otrzymać i zapłacić",
+ "recurring": "Cykliczne",
+ "recurringHint": "wobec tego, czego już się spodziewałeś",
+ "inactive": "Tu nieużywane"
+ },
+ "rule": {
+ "sameClientExact": "Znana osoba, dokładna kwota",
+ "netOfWithholding": "Znana osoba, zapłacone po potrąceniu podatku",
+ "exactAmountAnyClient": "Dokładna kwota, dowolna osoba",
+ "similarDescription": "Zbliżona kwota i podobny opis",
+ "sameAccountExact": "To samo konto, dokładna kwota",
+ "unknown": "Reguła",
+ "partPayment": "Znana osoba, część kwoty",
+ "severalInvoices": "Znana osoba, kilka faktur naraz"
+ },
+ "outcome": {
+ "link": "Wiąże sama",
+ "suggest": "Proponuje"
+ },
+ "cond": {
+ "samePayee": "osoba jest tą z faktury",
+ "sameAccount": "to samo konto",
+ "amountExact": "kwota zgadza się dokładnie",
+ "amountTolerance": "kwota mieści się w {{percent}}%",
+ "amountRatio": "kwota zgadza się po potrąceniu podatku",
+ "window": "do {{before}} dni wcześniej, {{after}} dni później",
+ "similarity": "opis jest podobny co najmniej w {{min}}",
+ "none": "brak warunków",
+ "accounts": "na {{names}}",
+ "payees": "dla {{names}}",
+ "moneyIn": "pieniądze wpływające",
+ "moneyOut": "pieniądze wypływające",
+ "foreign": "w obcej walucie",
+ "currencyIn": "w {{codes}}",
+ "atLeast": "od {{value}}",
+ "atMost": "do {{value}}",
+ "textContains": "wyciąg mówi „{{text}}”",
+ "textExcludes": "wyciąg nie mówi „{{text}}”",
+ "onArrival": "gdy pieniądze wpływają lub wypływają",
+ "onIssue": "gdy wystawiana jest faktura",
+ "amountPartial": "kwota pokrywa część należności",
+ "amountSet": "do {{count}} faktur daje tę sumę"
+ },
+ "newRule": "Nowa reguła dopasowania",
+ "saved": "Reguła zapisana",
+ "reset": "Reguła przywrócona",
+ "restore": "Przywróć ustawienie domyślne",
+ "changed": "Zmieniona",
+ "yours": "Twoja",
+ "field": {
+ "name": "Nazwa",
+ "namePlaceholder": "np. Znana osoba, zbliżona kwota",
+ "outcome": "Co robi, gdy pasuje",
+ "outcomeHint": "Wiązanie rozlicza samo. Propozycja trafia na listę poniżej, do Twojego potwierdzenia.",
+ "counterparty": "Kto zapłacił lub otrzymał",
+ "amount": "Kwota",
+ "window": "Dopuszczalna różnica dat",
+ "windowHint": "Opóźnienie liczy się od terminu płatności, a przedpłata od dnia wystawienia faktury, więc zapłata dzień po wystawieniu to nie tygodnie przed czasem.",
+ "beforeDays": "Dni wcześniej",
+ "afterDays": "Dni później",
+ "similarity": "Podobieństwo opisu",
+ "similarityHint": "Od 0 do 1. Zostaw puste, aby zignorować opis.",
+ "similarityOff": "wyłączone",
+ "scope": "Kiedy ta reguła obowiązuje",
+ "scopeHint": "Zostaw puste, aby dotyczyła wszystkiego",
+ "accounts": "Konta bankowe",
+ "anyAccount": "Dowolne konto",
+ "payees": "Osoby",
+ "anyPayee": "Dowolna osoba",
+ "direction": "Wpływ lub wypływ",
+ "currencyScope": "Tylko w tych walutach",
+ "currencyPlaceholder": "np. USD, EUR",
+ "foreignOnly": "Tylko waluty inne niż waluta tej przestrzeni",
+ "amountBand": "Tylko kwoty w tym zakresie",
+ "noMinimum": "bez minimum",
+ "noMaximum": "bez maksimum",
+ "text": "Treść wyciągu",
+ "textContains": "musi zawierać…",
+ "textExcludes": "nie może zawierać…",
+ "textHint": "Kilka, oddzielonych przecinkami, oznacza dowolne z nich.",
+ "trigger": "Kiedy szukamy",
+ "triggerHint": "Dopasowanie dzieje się w dwóch momentach, a dowody nie są takie same.",
+ "amountMatch": "Jak blisko musi być kwota",
+ "amountMatchHint": "Porównywana z tym, co wciąż pozostaje do zapłaty, nie z pierwotną sumą.",
+ "amountBandHint": "O samej płatności: wielkość, którą ta reguła ma obsługiwać albo nie."
+ },
+ "counterparty": {
+ "any": "Ktokolwiek",
+ "samePayee": "Osoba z faktury"
+ },
+ "amount": {
+ "exact": "Dokładnie należna kwota",
+ "tolerance": "W granicach marginesu",
+ "ratio": "Po potrąceniu podatku u źródła",
+ "ratioHint": "Używa stawek podatku u źródła Twojego kraju. Dopóki ich nie ma, reguła niczego nie dopasuje.",
+ "partial": "Część należności",
+ "partialHint": "Dla płacących w ratach. To, co zostaje, pozostaje otwarte, a kolejna płatność trafia dokładnie.",
+ "set": "Kilka faktur razem",
+ "setHint": "Dla płatności pokrywającej więcej niż jedną fakturę. Jeśli pasuje więcej niż jedna kombinacja, pytamy zamiast wybierać.",
+ "setMax": "Najwyżej tyle faktur",
+ "setFee": "Dopuść prowizję",
+ "setFeeHint": "Część wartości faktur, dla płatności, która przepływa po potrąceniu prowizji. Zero oznacza, że suma musi być dokładna."
+ },
+ "queue": {
+ "title": "Czeka na Ciebie",
+ "hint": "Dopasowania, które czekają na potwierdzenie.",
+ "empty": "Nic do sprawdzenia. Wszystko dopasowało się samo.",
+ "aPayment": "Płatność",
+ "maySettle": "może opłacać {{name}}",
+ "mayBe": "może być {{name}}",
+ "accept": "Powiąż",
+ "declineHint": "To nie to. Ta para nie będzie już proponowana.",
+ "linked": "Powiązano",
+ "declined": "Odrzucono. Nie zapytamy ponownie",
+ "covers": "pokrywa"
+ },
+ "evidence": {
+ "amountExact": "kwota zgadza się dokładnie",
+ "amountOff": "oczekiwano {{expected}}, przepłynęło {{moved}}",
+ "knownPayer": "znana osoba",
+ "unknownPayer": "osoba nierozpoznana",
+ "sameDay": "ten sam dzień",
+ "daysApart": "różnica {{days}} dni"
+ },
+ "direction": {
+ "any": "Obojętnie",
+ "in": "Pieniądze wpływające",
+ "out": "Pieniądze wypływające"
+ },
+ "step": {
+ "what": "Czym jest ta reguła",
+ "which": "Na jakie pieniądze patrzy",
+ "whichHint": "Zostaw wszystko puste, a patrzy na wszystkie",
+ "match": "Kiedy liczy się jako dopasowanie",
+ "matchHint": "Jak blisko muszą być płatność i zobowiązanie"
+ },
+ "trigger": {
+ "money_arrives": "Gdy pieniądze wpływają lub wypływają",
+ "money_arrivesHint": "Płatność pojawia się na wyciągu, a my szukamy faktury, którą rozlicza.",
+ "invoice_issued": "Gdy wystawiana jest faktura",
+ "invoice_issuedHint": "Płatność przyszła pierwsza, a faktura później, więc patrzymy wstecz, na pieniądze, które już tam były.",
+ "both": "W obu momentach",
+ "bothHint": "Reguła obowiązuje w obie strony."
+ },
+ "history": {
+ "title": "Co zrobiło dopasowanie",
+ "hint": "Od najnowszych.",
+ "byPerson": "przez Ciebie",
+ "byRules": "przez reguły",
+ "more": "Pokaż jeszcze {{count}}",
+ "less": "Pokaż mniej",
+ "action": {
+ "linked": "Powiązano z {{name}}",
+ "accepted": "Przyjęto propozycję dla {{name}}",
+ "suggested": "Zaproponowano dla {{name}}",
+ "declined": "Odrzucono propozycję dla {{name}}",
+ "expired": "Propozycja wygasła: {{name}}",
+ "unlinked": "Rozłączono z {{name}}"
+ },
+ "empty": "Jeszcze nic. Wypełni się, gdy dopasowanie powiąże, zapyta i otrzyma odpowiedź."
+ },
+ "moveUp": "Sprawdzaj tę wcześniej",
+ "moveDown": "Sprawdzaj tę później",
+ "matchingTitle": "Reguły dopasowania",
+ "matchingHint": "Jak każda płatność wiąże się z tym, co rozlicza.",
+ "pair": {
+ "owed": "Co jest należne",
+ "arrived": "Co się poruszyło",
+ "draftInvoice": "Faktura robocza",
+ "recurringBill": "Rachunek cykliczny",
+ "noMoney": "Brak transakcji.",
+ "stillOpen": "wciąż otwarte",
+ "thisPayment": "ta płatność",
+ "wasApplied": "zaliczone",
+ "wouldRemain": "zostanie",
+ "wouldClose": "zamyka ją",
+ "thePayment": "płatność",
+ "acrossInvoices": "na {{count}} faktur",
+ "dueOn": "termin {{date}}",
+ "totalOf": "razem {{amount}}"
+ },
+ "discarded": "Usunięte z tej przestrzeni:",
+ "noneLeft": "W tym zestawie nie ma już reguł dopasowania. Nic nie jest tu dopasowywane automatycznie.",
+ "confirmDeleteTitle": "Usunąć tę regułę?",
+ "confirmDeleteDescription": "„{{name}}” przestaje o czymkolwiek decydować. Jeśli to jedna z naszych, można ją później przywrócić.",
+ "exported": "Pobrano reguły dopasowania",
+ "imported": "Zaimportowano {{imported}} reguł ({{skipped}} pominięto)",
+ "invalidImportFile": "To nie jest plik z regułami dopasowania",
+ "importConfirmTitle": "Zaimportować reguły dopasowania?",
+ "importConfirmDescription": "Plik {{file}} zawiera {{count}} reguł.",
+ "importOverwriteWarning": "Import zastępuje reguły dopasowania tej przestrzeni wraz z ich kolejnością. Tego nie da się cofnąć."
}
}
diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.json
index 4ac0eab0..354f188e 100644
--- a/frontend/src/locales/pt-BR.json
+++ b/frontend/src/locales/pt-BR.json
@@ -372,7 +372,14 @@
"fromSystem": "De {{source}} · {{date}}",
"fromUpload": "Enviado · {{date}}"
},
- "draftSaved": "Rascunho salvo"
+ "draftSaved": "Rascunho salvo",
+ "suggestions": {
+ "title_one": "Um pagamento pode quitar esta cobrança",
+ "title_other": "{{count}} pagamentos podem quitar esta cobrança",
+ "wouldApply": "aplicaria {{amount}}",
+ "alsoCovers_one": "cobre também outra {{count}} cobrança",
+ "alsoCovers_other": "cobre também outras {{count}} cobranças"
+ }
},
"collections": {
"title": "Coleções",
@@ -807,7 +814,9 @@
"calendarTransfersExcluded": "Transferências não contam como receitas ou despesas",
"invoiceBadge": "Cobrança {{number}}",
"invoiceBadgeNoNumber": "Cobrança",
- "invoiceBadgeTooltip": "Esta transação quita uma cobrança. Abrir."
+ "invoiceBadgeTooltip": "Esta transação quita uma cobrança. Abrir.",
+ "suggestionBadge": "Pergunta",
+ "suggestionBadgeTooltip": "Um pagamento pode quitar esta cobrança. Abra a fila para responder."
},
"accounts": {
"title": "Contas",
@@ -1137,6 +1146,7 @@
"createMissingCategories": "Criar também as categorias padrão que o pacote precisa",
"duplicateName": "Já existe uma regra com este nome",
"sectionTitle": "Regras de Categorização",
+ "sectionHint": "Como categorizar as transações.",
"resetAndReapplyAll": "Redefinir e reaplicar",
"confirmResetAndReapplyAll": "Redefinir categorias, notas e descrições gerenciadas por regras das transações correspondentes e reaplicar todas as regras ativas?",
"add": "Adicionar",
@@ -1179,7 +1189,10 @@
"ignoreActionHint": "(sem valor necessário)",
"selectCategory": "Selecionar categoria...",
"selectAccount": "Selecionar conta...",
- "ruleActive": "Regra ativa",
+ "turnOn": "Ativar",
+ "turnOff": "Desativar",
+ "turnedOn": "Regra ativada",
+ "turnedOff": "Regra desativada",
"noConditions": "(sem condições)",
"noActions": "(sem ações)",
"fieldDescription": "Descrição",
@@ -1206,15 +1219,20 @@
"sortBy_priority": "Prioridade",
"sortBy_name": "Nome",
"sortBy_category": "Categoria",
- "export": "Export",
- "import": "Import",
- "exported": "Rules export downloaded",
- "imported": "Imported {{imported}} rules ({{skipped}} skipped)",
- "invalidImportFile": "Invalid rules import file",
- "importConfirmTitle": "Import categorization rules?",
- "importConfirmDescription": "File {{file}} contains {{count}} rules.",
- "importOverwriteWarning": "Importing will overwrite your current categorization rules. This cannot be undone.",
- "confirmOverwriteImport": "Overwrite and import"
+ "export": "Exportar",
+ "import": "Importar",
+ "exported": "Exportação de regras baixada",
+ "imported": "{{imported}} regras importadas ({{skipped}} ignoradas)",
+ "invalidImportFile": "Arquivo de importação de regras inválido",
+ "importConfirmTitle": "Importar regras de categorização?",
+ "importConfirmDescription": "O arquivo {{file}} contém {{count}} regras.",
+ "importOverwriteWarning": "Importar vai substituir as suas regras de categorização atuais. Isso não pode ser desfeito.",
+ "confirmOverwriteImport": "Substituir e importar",
+ "tab": {
+ "rules": "Regras",
+ "queue": "Esperando você",
+ "history": "Histórico"
+ }
},
"categories": {
"title": "Categorias",
@@ -2239,5 +2257,200 @@
"openai": "OpenAI Responses API"
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Faturas",
+ "invoicesHint": "contra o que você tem a receber e a pagar",
+ "recurring": "Recorrentes",
+ "recurringHint": "contra o que você já esperava",
+ "inactive": "Não usada aqui"
+ },
+ "rule": {
+ "sameClientExact": "Pessoa conhecida, valor exato",
+ "netOfWithholding": "Pessoa conhecida, pago com retenção",
+ "exactAmountAnyClient": "Valor exato, qualquer pessoa",
+ "similarDescription": "Valor próximo e descrição parecida",
+ "sameAccountExact": "Mesma conta, valor exato",
+ "unknown": "Regra",
+ "partPayment": "Pessoa conhecida, parte do valor",
+ "severalInvoices": "Pessoa conhecida, várias faturas de uma vez"
+ },
+ "outcome": {
+ "link": "Liga sozinho",
+ "suggest": "Sugere"
+ },
+ "cond": {
+ "samePayee": "a pessoa é a mesma da fatura",
+ "sameAccount": "a mesma conta",
+ "amountExact": "o valor bate exatamente",
+ "amountTolerance": "o valor está dentro de {{percent}}%",
+ "amountRatio": "o valor bate descontada a retenção",
+ "window": "até {{before}} dias adiantado, {{after}} dias atrasado",
+ "similarity": "a descrição é ao menos {{min}} parecida",
+ "none": "sem condições",
+ "accounts": "em {{names}}",
+ "payees": "para {{names}}",
+ "moneyIn": "dinheiro entrando",
+ "moneyOut": "dinheiro saindo",
+ "foreign": "em moeda estrangeira",
+ "currencyIn": "em {{codes}}",
+ "atLeast": "a partir de {{value}}",
+ "atMost": "até {{value}}",
+ "textContains": "o extrato diz “{{text}}”",
+ "textExcludes": "o extrato não diz “{{text}}”",
+ "onArrival": "quando o dinheiro entra ou sai",
+ "onIssue": "quando a fatura é emitida",
+ "amountPartial": "o valor cobre parte do que se deve",
+ "amountSet": "até {{count}} faturas somam esse valor"
+ },
+ "newRule": "Nova regra de conciliação",
+ "saved": "Regra salva",
+ "reset": "Regra restaurada",
+ "restore": "Voltar ao padrão",
+ "changed": "Alterada",
+ "yours": "Sua",
+ "field": {
+ "name": "Nome",
+ "namePlaceholder": "ex.: Pessoa conhecida, valor próximo",
+ "outcome": "O que fazer quando casar",
+ "outcomeHint": "Ligar liquida sozinho. Sugerir manda para a fila abaixo, para você confirmar.",
+ "counterparty": "Quem pagou ou recebeu",
+ "amount": "Valor",
+ "window": "Distância permitida entre as datas",
+ "windowHint": "O atraso conta do vencimento; a antecipação conta do dia em que a fatura foi emitida, então pagar no dia seguinte à emissão não é semanas adiantado.",
+ "beforeDays": "Dias adiantado",
+ "afterDays": "Dias atrasado",
+ "similarity": "Semelhança da descrição",
+ "similarityHint": "De 0 a 1. Deixe vazio para ignorar a descrição.",
+ "similarityOff": "desligado",
+ "scope": "Quando esta regra se aplica",
+ "scopeHint": "Deixe vazio para valer para tudo",
+ "accounts": "Contas bancárias",
+ "anyAccount": "Qualquer conta",
+ "payees": "Pessoas",
+ "anyPayee": "Qualquer pessoa",
+ "direction": "Entrada ou saída",
+ "currencyScope": "Somente nestas moedas",
+ "currencyPlaceholder": "ex.: USD, EUR",
+ "foreignOnly": "Somente moedas diferentes da que este workspace usa",
+ "amountBand": "Somente valores nesta faixa",
+ "noMinimum": "sem mínimo",
+ "noMaximum": "sem máximo",
+ "text": "Texto do extrato",
+ "textContains": "precisa conter…",
+ "textExcludes": "não pode conter…",
+ "textHint": "Vários, separados por vírgula, significa qualquer um deles.",
+ "trigger": "Quando procuramos",
+ "triggerHint": "A conciliação acontece em dois momentos, e a evidência não é a mesma nos dois.",
+ "amountMatch": "O quão perto o valor precisa estar",
+ "amountMatchHint": "Comparado com o que ainda se deve, não com o total original.",
+ "amountBandHint": "Sobre o pagamento em si: um tamanho que você quer, ou não quer, que esta regra trate."
+ },
+ "counterparty": {
+ "any": "Qualquer um",
+ "samePayee": "A pessoa da fatura"
+ },
+ "amount": {
+ "exact": "Exatamente o valor devido",
+ "tolerance": "Dentro de uma margem",
+ "ratio": "Descontado o imposto retido",
+ "ratioHint": "Usa as alíquotas de retenção do seu país. Enquanto não houver, a regra não casa nada.",
+ "partial": "Parte do que se deve",
+ "partialHint": "Para quem paga parcelado. O que sobra continua em aberto, e o próximo pagamento casa exato.",
+ "set": "Várias faturas somadas",
+ "setHint": "Para um pagamento que cobre mais de uma fatura. Se mais de uma combinação fechar, perguntamos em vez de escolher.",
+ "setMax": "No máximo estas faturas",
+ "setFee": "Admitir taxa de",
+ "setFeeHint": "Uma parcela do valor das faturas, para pagamento que se move líquido de taxa. Zero significa que o total tem de ser exato."
+ },
+ "queue": {
+ "title": "Esperando você",
+ "hint": "Conciliações que precisam da sua confirmação.",
+ "empty": "Nada para revisar. Tudo casou sozinho.",
+ "aPayment": "Um pagamento",
+ "maySettle": "pode quitar {{name}}",
+ "mayBe": "pode ser {{name}}",
+ "accept": "Ligar",
+ "declineHint": "Não é isso. Este par não será sugerido de novo.",
+ "linked": "Ligado",
+ "declined": "Descartado. Não perguntamos de novo",
+ "covers": "cobre"
+ },
+ "evidence": {
+ "amountExact": "valor bate exatamente",
+ "amountOff": "esperado {{expected}}, movimentado {{moved}}",
+ "knownPayer": "pessoa conhecida",
+ "unknownPayer": "pessoa não identificada",
+ "sameDay": "mesmo dia",
+ "daysApart": "{{days}} dias de diferença"
+ },
+ "direction": {
+ "any": "Tanto faz",
+ "in": "Dinheiro entrando",
+ "out": "Dinheiro saindo"
+ },
+ "step": {
+ "what": "O que é esta regra",
+ "which": "Que dinheiro ela olha",
+ "whichHint": "Deixe tudo vazio e ela olha todo o dinheiro",
+ "match": "Quando conta como casamento",
+ "matchHint": "O quão perto o pagamento e a promessa precisam estar"
+ },
+ "trigger": {
+ "money_arrives": "Quando o dinheiro entra ou sai",
+ "money_arrivesHint": "O pagamento aparece no extrato e procuramos a fatura que ele quita.",
+ "invoice_issued": "Quando a fatura é emitida",
+ "invoice_issuedHint": "O pagamento veio antes e a nota depois, então olhamos para trás, no dinheiro que já estava lá.",
+ "both": "Nos dois momentos",
+ "bothHint": "A regra vale nos dois sentidos."
+ },
+ "history": {
+ "title": "O que a conciliação fez",
+ "hint": "Mais recentes primeiro.",
+ "byPerson": "por você",
+ "byRules": "pelas regras",
+ "more": "Ver mais {{count}}",
+ "less": "Ver menos",
+ "action": {
+ "linked": "Vinculado a {{name}}",
+ "accepted": "Sugestão aceita para {{name}}",
+ "suggested": "Sugerido para {{name}}",
+ "declined": "Sugestão recusada para {{name}}",
+ "expired": "Sugestão expirou: {{name}}",
+ "unlinked": "Vínculo desfeito com {{name}}"
+ },
+ "empty": "Nada ainda. Isto se preenche conforme a conciliação liga, pergunta e é respondida."
+ },
+ "moveUp": "Tentar esta antes",
+ "moveDown": "Tentar esta depois",
+ "matchingTitle": "Regras de conciliação",
+ "matchingHint": "Como cada pagamento é ligado ao que ele quita.",
+ "pair": {
+ "owed": "O que se deve",
+ "arrived": "O que se moveu",
+ "draftInvoice": "Fatura em rascunho",
+ "recurringBill": "Conta recorrente",
+ "noMoney": "Sem transação nesta.",
+ "stillOpen": "em aberto",
+ "thisPayment": "este pagamento",
+ "wasApplied": "aplicado",
+ "wouldRemain": "ficaria",
+ "wouldClose": "quita",
+ "thePayment": "o pagamento",
+ "acrossInvoices": "em {{count}} faturas",
+ "dueOn": "vence {{date}}",
+ "totalOf": "total de {{amount}}"
+ },
+ "discarded": "Excluídas deste espaço:",
+ "noneLeft": "Nenhuma regra de conciliação neste conjunto. Nada aqui é conciliado automaticamente.",
+ "confirmDeleteTitle": "Excluir esta regra?",
+ "confirmDeleteDescription": "\"{{name}}\" para de decidir qualquer coisa. Se for uma das nossas, você pode trazê-la de volta depois.",
+ "exported": "Regras de conciliação baixadas",
+ "imported": "{{imported}} regras importadas ({{skipped}} ignoradas)",
+ "invalidImportFile": "Este não é um arquivo de regras de conciliação",
+ "importConfirmTitle": "Importar regras de conciliação?",
+ "importConfirmDescription": "O arquivo {{file}} contém {{count}} regras.",
+ "importOverwriteWarning": "A importação substitui as regras de conciliação deste espaço, inclusive a ordem delas. Não dá para desfazer."
}
}
diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json
index 13513310..831af551 100644
--- a/frontend/src/locales/pt-PT.json
+++ b/frontend/src/locales/pt-PT.json
@@ -372,7 +372,14 @@
"fromSystem": "De {{source}} · {{date}}",
"fromUpload": "Carregado · {{date}}"
},
- "draftSaved": "Rascunho guardado"
+ "draftSaved": "Rascunho guardado",
+ "suggestions": {
+ "title_one": "Um pagamento pode liquidar esta cobrança",
+ "title_other": "{{count}} pagamentos podem liquidar esta cobrança",
+ "wouldApply": "aplicaria {{amount}}",
+ "alsoCovers_one": "cobre também outra {{count}} cobrança",
+ "alsoCovers_other": "cobre também outras {{count}} cobranças"
+ }
},
"collections": {
"title": "Coleções",
@@ -807,7 +814,9 @@
"clearOverride": "Limpar substituição",
"invoiceBadge": "Cobrança {{number}}",
"invoiceBadgeNoNumber": "Cobrança",
- "invoiceBadgeTooltip": "Esta transação quita uma cobrança. Abrir."
+ "invoiceBadgeTooltip": "Esta transação quita uma cobrança. Abrir.",
+ "suggestionBadge": "Pergunta",
+ "suggestionBadgeTooltip": "Um pagamento pode liquidar esta cobrança. Abra a fila para responder."
},
"accounts": {
"title": "Contas",
@@ -1137,6 +1146,7 @@
"createMissingCategories": "Criar também as categorias padrão que o pacote precisa",
"duplicateName": "Já existe uma regra com este nome",
"sectionTitle": "Regras de Categorização",
+ "sectionHint": "Como categorizar as transações.",
"resetAndReapplyAll": "Redefinir e reaplicar",
"confirmResetAndReapplyAll": "Redefinir categorias, notas e descrições geridas por regras das transações correspondentes e reaplicar todas as regras ativas?",
"add": "Adicionar",
@@ -1179,7 +1189,10 @@
"ignoreActionHint": "(sem valor necessário)",
"selectCategory": "Selecionar categoria...",
"selectAccount": "Selecionar conta...",
- "ruleActive": "Regra ativa",
+ "turnOn": "Ativar",
+ "turnOff": "Desativar",
+ "turnedOn": "Regra ativada",
+ "turnedOff": "Regra desativada",
"noConditions": "(sem condições)",
"noActions": "(sem ações)",
"fieldDescription": "Descrição",
@@ -1206,15 +1219,20 @@
"sortBy_priority": "Prioridade",
"sortBy_name": "Nome",
"sortBy_category": "Categoria",
- "export": "Export",
- "import": "Import",
- "exported": "Rules export downloaded",
- "imported": "Imported {{imported}} rules ({{skipped}} skipped)",
- "invalidImportFile": "Invalid rules import file",
- "importConfirmTitle": "Import categorization rules?",
- "importConfirmDescription": "File {{file}} contains {{count}} rules.",
- "importOverwriteWarning": "Importing will overwrite your current categorization rules. This cannot be undone.",
- "confirmOverwriteImport": "Overwrite and import"
+ "export": "Exportar",
+ "import": "Importar",
+ "exported": "Exportação de regras transferida",
+ "imported": "{{imported}} regras importadas ({{skipped}} ignoradas)",
+ "invalidImportFile": "Ficheiro de importação de regras inválido",
+ "importConfirmTitle": "Importar regras de categorização?",
+ "importConfirmDescription": "O ficheiro {{file}} contém {{count}} regras.",
+ "importOverwriteWarning": "Importar vai substituir as suas regras de categorização atuais. Isto não pode ser anulado.",
+ "confirmOverwriteImport": "Substituir e importar",
+ "tab": {
+ "rules": "Regras",
+ "queue": "À sua espera",
+ "history": "Histórico"
+ }
},
"categories": {
"title": "Categorias",
@@ -2239,5 +2257,200 @@
"openai": "OpenAI Responses API"
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Faturas",
+ "invoicesHint": "contra o que tem a receber e a pagar",
+ "recurring": "Recorrentes",
+ "recurringHint": "contra o que já estava à espera",
+ "inactive": "Não usada aqui"
+ },
+ "rule": {
+ "sameClientExact": "Pessoa conhecida, valor exato",
+ "netOfWithholding": "Pessoa conhecida, pago com retenção",
+ "exactAmountAnyClient": "Valor exato, qualquer pessoa",
+ "similarDescription": "Valor próximo e descrição parecida",
+ "sameAccountExact": "Mesma conta, valor exato",
+ "unknown": "Regra",
+ "partPayment": "Pessoa conhecida, parte do valor",
+ "severalInvoices": "Pessoa conhecida, várias faturas de uma vez"
+ },
+ "outcome": {
+ "link": "Liga sozinho",
+ "suggest": "Sugere"
+ },
+ "cond": {
+ "samePayee": "a pessoa é a mesma da fatura",
+ "sameAccount": "a mesma conta",
+ "amountExact": "o valor corresponde exatamente",
+ "amountTolerance": "o valor está dentro de {{percent}}%",
+ "amountRatio": "o valor corresponde descontada a retenção",
+ "window": "até {{before}} dias adiantado, {{after}} dias atrasado",
+ "similarity": "a descrição é pelo menos {{min}} semelhante",
+ "none": "sem condições",
+ "accounts": "em {{names}}",
+ "payees": "para {{names}}",
+ "moneyIn": "dinheiro a entrar",
+ "moneyOut": "dinheiro a sair",
+ "foreign": "em moeda estrangeira",
+ "currencyIn": "em {{codes}}",
+ "atLeast": "a partir de {{value}}",
+ "atMost": "até {{value}}",
+ "textContains": "o extrato diz “{{text}}”",
+ "textExcludes": "o extrato não diz “{{text}}”",
+ "onArrival": "quando o dinheiro entra ou sai",
+ "onIssue": "quando uma fatura é emitida",
+ "amountPartial": "o valor cobre parte do que se deve",
+ "amountSet": "até {{count}} faturas somam esse valor"
+ },
+ "newRule": "Nova regra de conciliação",
+ "saved": "Regra guardada",
+ "reset": "Regra restaurada",
+ "restore": "Voltar ao valor por omissão",
+ "changed": "Alterada",
+ "yours": "Sua",
+ "field": {
+ "name": "Nome",
+ "namePlaceholder": "ex.: Pessoa conhecida, valor próximo",
+ "outcome": "O que fazer quando corresponder",
+ "outcomeHint": "Ligar liquida sozinho. Sugerir envia para a lista abaixo, para confirmar.",
+ "counterparty": "Quem pagou ou recebeu",
+ "amount": "Valor",
+ "window": "Distância permitida entre as datas",
+ "windowHint": "O atraso conta a partir do vencimento; a antecipação, a partir do dia em que a fatura foi emitida, por isso pagar no dia seguinte à emissão não é semanas adiantado.",
+ "beforeDays": "Dias adiantado",
+ "afterDays": "Dias atrasado",
+ "similarity": "Semelhança da descrição",
+ "similarityHint": "De 0 a 1. Deixe vazio para ignorar a descrição.",
+ "similarityOff": "desligado",
+ "scope": "Quando esta regra se aplica",
+ "scopeHint": "Deixe vazio para valer para tudo",
+ "accounts": "Contas bancárias",
+ "anyAccount": "Qualquer conta",
+ "payees": "Pessoas",
+ "anyPayee": "Qualquer pessoa",
+ "direction": "Entrada ou saída",
+ "currencyScope": "Apenas nestas moedas",
+ "currencyPlaceholder": "ex.: USD, EUR",
+ "foreignOnly": "Apenas moedas diferentes da que este espaço usa",
+ "amountBand": "Apenas valores neste intervalo",
+ "noMinimum": "sem mínimo",
+ "noMaximum": "sem máximo",
+ "text": "Texto do extrato",
+ "textContains": "tem de conter…",
+ "textExcludes": "não pode conter…",
+ "textHint": "Vários, separados por vírgula, significa qualquer um deles.",
+ "trigger": "Quando procuramos",
+ "triggerHint": "A conciliação acontece em dois momentos, e a evidência não é a mesma nos dois.",
+ "amountMatch": "Quão perto o valor tem de estar",
+ "amountMatchHint": "Comparado com o que ainda se deve, não com o total original.",
+ "amountBandHint": "Sobre o pagamento em si: um tamanho que quer, ou não, que esta regra trate."
+ },
+ "counterparty": {
+ "any": "Qualquer um",
+ "samePayee": "A pessoa da fatura"
+ },
+ "amount": {
+ "exact": "Exatamente o valor em dívida",
+ "tolerance": "Dentro de uma margem",
+ "ratio": "Descontado o imposto retido",
+ "ratioHint": "Usa as taxas de retenção do seu país. Enquanto não existirem, a regra não corresponde a nada.",
+ "partial": "Parte do que se deve",
+ "partialHint": "Para quem paga a prestações. O que sobra continua em aberto, e o pagamento seguinte encaixa exato.",
+ "set": "Várias faturas somadas",
+ "setHint": "Para um pagamento que cobre mais de uma fatura. Se mais de uma combinação fechar, perguntamos em vez de escolher.",
+ "setMax": "No máximo estas faturas",
+ "setFee": "Admitir taxa de",
+ "setFeeHint": "Uma parcela do valor das faturas, para pagamento que se move líquido de comissão. Zero significa que o total tem de ser exato."
+ },
+ "queue": {
+ "title": "À sua espera",
+ "hint": "Conciliações que precisam da sua confirmação.",
+ "empty": "Nada para rever. Correspondeu tudo sozinho.",
+ "aPayment": "Um pagamento",
+ "maySettle": "pode liquidar {{name}}",
+ "mayBe": "pode ser {{name}}",
+ "accept": "Ligar",
+ "declineHint": "Não é isso. Este par não voltará a ser sugerido.",
+ "linked": "Ligado",
+ "declined": "Descartado. Não voltamos a perguntar",
+ "covers": "cobre"
+ },
+ "evidence": {
+ "amountExact": "o valor corresponde exatamente",
+ "amountOff": "esperado {{expected}}, movimentado {{moved}}",
+ "knownPayer": "pessoa conhecida",
+ "unknownPayer": "pessoa não identificada",
+ "sameDay": "mesmo dia",
+ "daysApart": "{{days}} dias de diferença"
+ },
+ "direction": {
+ "any": "Tanto faz",
+ "in": "Dinheiro a entrar",
+ "out": "Dinheiro a sair"
+ },
+ "step": {
+ "what": "O que é esta regra",
+ "which": "Que dinheiro ela olha",
+ "whichHint": "Deixe tudo vazio e olha todo o dinheiro",
+ "match": "Quando conta como correspondência",
+ "matchHint": "Quão perto o pagamento e a promessa têm de estar"
+ },
+ "trigger": {
+ "money_arrives": "Quando o dinheiro entra ou sai",
+ "money_arrivesHint": "O pagamento aparece no extrato e procuramos a fatura que ele liquida.",
+ "invoice_issued": "Quando uma fatura é emitida",
+ "invoice_issuedHint": "O pagamento veio antes e a fatura depois, por isso olhamos para trás, no dinheiro que já lá estava.",
+ "both": "Nos dois momentos",
+ "bothHint": "A regra vale nos dois sentidos."
+ },
+ "history": {
+ "title": "O que a conciliação fez",
+ "hint": "Mais recentes primeiro.",
+ "byPerson": "por si",
+ "byRules": "pelas regras",
+ "more": "Ver mais {{count}}",
+ "less": "Ver menos",
+ "action": {
+ "linked": "Vinculado a {{name}}",
+ "accepted": "Sugestão aceite para {{name}}",
+ "suggested": "Sugerido para {{name}}",
+ "declined": "Sugestão recusada para {{name}}",
+ "expired": "Sugestão expirou: {{name}}",
+ "unlinked": "Vínculo desfeito com {{name}}"
+ },
+ "empty": "Nada ainda. Isto preenche-se à medida que a conciliação liga, pergunta e é respondida."
+ },
+ "moveUp": "Tentar esta antes",
+ "moveDown": "Tentar esta depois",
+ "matchingTitle": "Regras de conciliação",
+ "matchingHint": "Como cada pagamento é ligado ao que ele liquida.",
+ "pair": {
+ "owed": "O que se deve",
+ "arrived": "O que se moveu",
+ "draftInvoice": "Fatura em rascunho",
+ "recurringBill": "Conta recorrente",
+ "noMoney": "Sem transação nesta.",
+ "stillOpen": "em aberto",
+ "thisPayment": "este pagamento",
+ "wasApplied": "aplicado",
+ "wouldRemain": "ficaria",
+ "wouldClose": "liquida",
+ "thePayment": "o pagamento",
+ "acrossInvoices": "em {{count}} faturas",
+ "dueOn": "vence {{date}}",
+ "totalOf": "total de {{amount}}"
+ },
+ "discarded": "Eliminadas deste espaço:",
+ "noneLeft": "Nenhuma regra de conciliação neste conjunto. Nada aqui é conciliado automaticamente.",
+ "confirmDeleteTitle": "Eliminar esta regra?",
+ "confirmDeleteDescription": "\"{{name}}\" deixa de decidir seja o que for. Se for uma das nossas, pode trazê-la de volta mais tarde.",
+ "exported": "Regras de conciliação transferidas",
+ "imported": "{{imported}} regras importadas ({{skipped}} ignoradas)",
+ "invalidImportFile": "Este não é um ficheiro de regras de conciliação",
+ "importConfirmTitle": "Importar regras de conciliação?",
+ "importConfirmDescription": "O ficheiro {{file}} contém {{count}} regras.",
+ "importOverwriteWarning": "A importação substitui as regras de conciliação deste espaço, incluindo a ordem. Não é possível anular."
}
}
diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.json
index 7da6b4c9..efd89b28 100644
--- a/frontend/src/locales/ru.json
+++ b/frontend/src/locales/ru.json
@@ -372,7 +372,18 @@
"fromSystem": "Из {{source}} · {{date}}",
"fromUpload": "Загружено · {{date}}"
},
- "draftSaved": "Черновик сохранён"
+ "draftSaved": "Черновик сохранён",
+ "suggestions": {
+ "title_one": "Платёж может закрыть этот счёт",
+ "title_few": "{{count}} платежа могут закрыть этот счёт",
+ "title_many": "{{count}} платежей могут закрыть этот счёт",
+ "title_other": "{{count}} платежей могут закрыть этот счёт",
+ "alsoCovers_one": "также покрывает ещё {{count}} счёт",
+ "alsoCovers_few": "и ещё {{count}} счёта",
+ "alsoCovers_many": "и ещё {{count}} счетов",
+ "alsoCovers_other": "также покрывает ещё {{count}} счетов",
+ "wouldApply": "применит {{amount}}"
+ }
},
"collections": {
"title": "Коллекции",
@@ -813,7 +824,9 @@
"calendarTransfersExcluded": "Переводы не учитываются как приход или расходы",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Эта операция закрывает счёт. Открыть.",
+ "suggestionBadge": "Вопрос",
+ "suggestionBadgeTooltip": "Платёж может закрыть этот счёт. Откройте очередь, чтобы ответить."
},
"accounts": {
"title": "Счета",
@@ -1145,6 +1158,7 @@
"createMissingCategories": "Также создать категории по умолчанию, необходимые пакету",
"duplicateName": "Правило с таким именем уже существует",
"sectionTitle": "Правила категоризации",
+ "sectionHint": "Как категоризировать транзакции.",
"resetAndReapplyAll": "Сбросить и применить заново",
"confirmResetAndReapplyAll": "Сбросить категории, примечания и описания, изменённые правилами, у совпадающих транзакций, затем заново применить все активные правила?",
"add": "Добавить",
@@ -1187,7 +1201,10 @@
"ignoreActionHint": "(значение не требуется)",
"selectCategory": "Выберите категорию...",
"selectAccount": "Выберите счёт...",
- "ruleActive": "Активное правило",
+ "turnOn": "Включить",
+ "turnOff": "Выключить",
+ "turnedOn": "Правило включено",
+ "turnedOff": "Правило выключено",
"noConditions": "(нет условий)",
"noActions": "(нет действий)",
"fieldDescription": "Описание",
@@ -1222,7 +1239,12 @@
"importConfirmTitle": "Импортировать правила категоризации?",
"importConfirmDescription": "Файл {{file}} содержит правил: {{count}}.",
"importOverwriteWarning": "Импорт перезапишет текущие правила категоризации. Это действие необратимо.",
- "confirmOverwriteImport": "Перезаписать и импортировать"
+ "confirmOverwriteImport": "Перезаписать и импортировать",
+ "tab": {
+ "rules": "Правила",
+ "queue": "Ждёт вас",
+ "history": "История"
+ }
},
"categories": {
"title": "Категории",
@@ -2247,5 +2269,200 @@
"subtitle": "Добавьте подключение, чтобы направить Securo на ваш локальный Ollama, OpenAI, Anthropic или любой совместимый с OpenAI эндпоинт."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Счета",
+ "invoicesHint": "с тем, что вам должны и что должны вы",
+ "recurring": "Регулярные",
+ "recurringHint": "с тем, что вы уже ожидали",
+ "inactive": "Здесь не используется"
+ },
+ "rule": {
+ "sameClientExact": "Известный человек, точная сумма",
+ "netOfWithholding": "Известный человек, оплачено с удержанием",
+ "exactAmountAnyClient": "Точная сумма, любой человек",
+ "similarDescription": "Близкая сумма и похожее описание",
+ "sameAccountExact": "Тот же счёт, точная сумма",
+ "unknown": "Правило",
+ "partPayment": "Известный человек, часть суммы",
+ "severalInvoices": "Известный человек, несколько счетов сразу"
+ },
+ "outcome": {
+ "link": "Связывает само",
+ "suggest": "Предлагает"
+ },
+ "cond": {
+ "samePayee": "человек тот же, что в счёте",
+ "sameAccount": "тот же счёт",
+ "amountExact": "сумма совпадает точно",
+ "amountTolerance": "сумма в пределах {{percent}}%",
+ "amountRatio": "сумма совпадает за вычетом налога",
+ "window": "до {{before}} дней раньше, {{after}} дней позже",
+ "similarity": "описание похоже не менее чем на {{min}}",
+ "none": "без условий",
+ "accounts": "на {{names}}",
+ "payees": "для {{names}}",
+ "moneyIn": "приходящие деньги",
+ "moneyOut": "уходящие деньги",
+ "foreign": "в иностранной валюте",
+ "currencyIn": "в {{codes}}",
+ "atLeast": "от {{value}}",
+ "atMost": "до {{value}}",
+ "textContains": "в выписке сказано «{{text}}»",
+ "textExcludes": "в выписке не сказано «{{text}}»",
+ "onArrival": "когда деньги приходят или уходят",
+ "onIssue": "когда выставляется счёт",
+ "amountPartial": "сумма покрывает часть долга",
+ "amountSet": "до {{count}} счетов дают эту сумму"
+ },
+ "newRule": "Новое правило сопоставления",
+ "saved": "Правило сохранено",
+ "reset": "Правило восстановлено",
+ "restore": "Вернуть значение по умолчанию",
+ "changed": "Изменено",
+ "yours": "Ваше",
+ "field": {
+ "name": "Название",
+ "namePlaceholder": "напр.: Известный человек, близкая сумма",
+ "outcome": "Что делать при совпадении",
+ "outcomeHint": "«Связать» закрывает само. «Предложить» отправляет в список ниже, чтобы вы подтвердили.",
+ "counterparty": "Кто заплатил или получил",
+ "amount": "Сумма",
+ "window": "Допустимая разница между датами",
+ "windowHint": "Просрочка считается от срока оплаты, а досрочность — со дня выставления счёта: оплата на следующий день после выставления не является досрочной на недели.",
+ "beforeDays": "Дней раньше",
+ "afterDays": "Дней позже",
+ "similarity": "Схожесть описания",
+ "similarityHint": "От 0 до 1. Оставьте пустым, чтобы не учитывать описание.",
+ "similarityOff": "выключено",
+ "scope": "Когда действует это правило",
+ "scopeHint": "Оставьте пустым, чтобы оно действовало для всего",
+ "accounts": "Банковские счета",
+ "anyAccount": "Любой счёт",
+ "payees": "Люди",
+ "anyPayee": "Любой человек",
+ "direction": "Приход или расход",
+ "currencyScope": "Только в этих валютах",
+ "currencyPlaceholder": "напр. USD, EUR",
+ "foreignOnly": "Только валюты, отличные от валюты этого пространства",
+ "amountBand": "Только суммы в этом диапазоне",
+ "noMinimum": "без минимума",
+ "noMaximum": "без максимума",
+ "text": "Текст выписки",
+ "textContains": "должен содержать…",
+ "textExcludes": "не должен содержать…",
+ "textHint": "Несколько через запятую означает любое из них.",
+ "trigger": "Когда мы ищем",
+ "triggerHint": "Сопоставление происходит в два момента, и доказательства в них разные.",
+ "amountMatch": "Насколько точной должна быть сумма",
+ "amountMatchHint": "Сравнивается с остатком долга, а не с исходной суммой.",
+ "amountBandHint": "О самом платеже: размер, который это правило должно обрабатывать или нет."
+ },
+ "counterparty": {
+ "any": "Любой",
+ "samePayee": "Человек из счёта"
+ },
+ "amount": {
+ "exact": "Ровно причитающаяся сумма",
+ "tolerance": "В пределах допуска",
+ "ratio": "За вычетом удержанного налога",
+ "ratioHint": "Использует ставки удержания вашей страны. Пока их нет, правило ничего не сопоставит.",
+ "partial": "Часть того, что причитается",
+ "partialHint": "Для тех, кто платит частями. Остаток остаётся открытым, а следующий платёж совпадёт точно.",
+ "set": "Несколько счетов вместе",
+ "setHint": "Для платежа, который покрывает более одного счёта. Если подходит несколько сочетаний, мы спрашиваем, а не выбираем.",
+ "setMax": "Не больше стольких счетов",
+ "setFee": "Допустить комиссию",
+ "setFeeHint": "Доля от суммы счетов, для платежа, который проходит за вычетом комиссии. Ноль означает, что сумма должна совпадать точно."
+ },
+ "queue": {
+ "title": "Ждёт вас",
+ "hint": "Сопоставления, которые ждут вашего подтверждения.",
+ "empty": "Проверять нечего. Всё сопоставилось само.",
+ "aPayment": "Платёж",
+ "maySettle": "возможно, закрывает {{name}}",
+ "mayBe": "возможно, это {{name}}",
+ "accept": "Связать",
+ "declineHint": "Не то. Эту пару больше не предложим.",
+ "linked": "Связано",
+ "declined": "Отклонено. Больше не спросим",
+ "covers": "покрывает"
+ },
+ "evidence": {
+ "amountExact": "сумма совпадает точно",
+ "amountOff": "ожидалось {{expected}}, прошло {{moved}}",
+ "knownPayer": "известный человек",
+ "unknownPayer": "человек не определён",
+ "sameDay": "тот же день",
+ "daysApart": "разница {{days}} дней"
+ },
+ "direction": {
+ "any": "Неважно",
+ "in": "Приходящие деньги",
+ "out": "Уходящие деньги"
+ },
+ "step": {
+ "what": "Что это за правило",
+ "which": "На какие деньги оно смотрит",
+ "whichHint": "Оставьте всё пустым, и оно смотрит на все",
+ "match": "Когда это считается совпадением",
+ "matchHint": "Насколько близко должны сойтись платёж и обязательство"
+ },
+ "trigger": {
+ "money_arrives": "Когда деньги приходят или уходят",
+ "money_arrivesHint": "Платёж появляется в выписке, и мы ищем счёт, который он закрывает.",
+ "invoice_issued": "Когда выставляется счёт",
+ "invoice_issuedHint": "Платёж пришёл раньше, а счёт позже, поэтому мы смотрим назад, на деньги, которые уже были.",
+ "both": "В оба момента",
+ "bothHint": "Правило действует в обе стороны."
+ },
+ "history": {
+ "title": "Что сделало сопоставление",
+ "hint": "Сначала новые.",
+ "byPerson": "вами",
+ "byRules": "правилами",
+ "more": "Показать ещё {{count}}",
+ "less": "Показать меньше",
+ "action": {
+ "linked": "Связано с {{name}}",
+ "accepted": "Предложение по {{name}} принято",
+ "suggested": "Предложено для {{name}}",
+ "declined": "Предложение по {{name}} отклонено",
+ "expired": "Предложение истекло: {{name}}",
+ "unlinked": "Связь с {{name}} снята"
+ },
+ "empty": "Пока ничего. Здесь появится то, что сопоставление связало, спросило и получило в ответ."
+ },
+ "moveUp": "Проверять это раньше",
+ "moveDown": "Проверять это позже",
+ "matchingTitle": "Правила сопоставления",
+ "matchingHint": "Как каждый платёж связывается с тем, что он закрывает.",
+ "pair": {
+ "owed": "Что причитается",
+ "arrived": "Что прошло",
+ "draftInvoice": "Черновик счёта",
+ "recurringBill": "Регулярный платёж",
+ "noMoney": "Операции нет.",
+ "stillOpen": "ещё открыто",
+ "thisPayment": "этот платёж",
+ "wasApplied": "зачтено",
+ "wouldRemain": "останется",
+ "wouldClose": "закрывает",
+ "thePayment": "платёж",
+ "acrossInvoices": "на {{count}} счетов",
+ "dueOn": "срок {{date}}",
+ "totalOf": "итого {{amount}}"
+ },
+ "discarded": "Удалены из этого пространства:",
+ "noneLeft": "В этом наборе не осталось правил сопоставления. Здесь ничего не сопоставляется автоматически.",
+ "confirmDeleteTitle": "Удалить это правило?",
+ "confirmDeleteDescription": "«{{name}}» перестаёт что-либо решать. Если это одно из наших, его можно вернуть позже.",
+ "exported": "Правила сопоставления загружены",
+ "imported": "Импортировано правил: {{imported}} (пропущено: {{skipped}})",
+ "invalidImportFile": "Это не файл правил сопоставления",
+ "importConfirmTitle": "Импортировать правила сопоставления?",
+ "importConfirmDescription": "Файл {{file}} содержит правил: {{count}}.",
+ "importOverwriteWarning": "Импорт заменит правила сопоставления этого пространства вместе с их порядком. Отменить нельзя."
}
}
diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.json
index 4d48f91f..e1cfffc0 100644
--- a/frontend/src/locales/sk.json
+++ b/frontend/src/locales/sk.json
@@ -372,7 +372,18 @@
"fromSystem": "Z {{source}} · {{date}}",
"fromUpload": "Nahrané · {{date}}"
},
- "draftSaved": "Koncept uložený"
+ "draftSaved": "Koncept uložený",
+ "suggestions": {
+ "title_one": "Platba môže uhradiť túto faktúru",
+ "title_few": "{{count}} platby môžu vyrovnať túto faktúru",
+ "title_many": "{{count}} platieb môže vyrovnať túto faktúru",
+ "title_other": "{{count}} platieb môže uhradiť túto faktúru",
+ "alsoCovers_one": "pokrýva aj {{count}} ďalšiu faktúru",
+ "alsoCovers_few": "a ďalšie {{count}} faktúry",
+ "alsoCovers_many": "a ďalších {{count}} faktúr",
+ "alsoCovers_other": "pokrýva aj {{count}} ďalších faktúr",
+ "wouldApply": "použila by {{amount}}"
+ }
},
"collections": {
"title": "Zbierky",
@@ -851,7 +862,9 @@
"calendarTransfersExcluded": "Prevody sa nepočítajú ako príjem ani výdavok",
"invoiceBadge": "Faktúra {{number}}",
"invoiceBadgeNoNumber": "Faktúra",
- "invoiceBadgeTooltip": "Táto transakcia vyrovnáva faktúru. Otvorte ju."
+ "invoiceBadgeTooltip": "Táto transakcia vyrovnáva faktúru. Otvorte ju.",
+ "suggestionBadge": "Otázka",
+ "suggestionBadgeTooltip": "Platba môže uhradiť túto faktúru. Otvorte front a odpovedzte."
},
"accounts": {
"title": "Účty",
@@ -1216,6 +1229,7 @@
"createMissingCategories": "Vytvoriť aj predvolené kategórie, ktoré balík potrebuje",
"duplicateName": "Pravidlo s týmto názvom už existuje",
"sectionTitle": "Pravidlá kategorizácie",
+ "sectionHint": "Ako kategorizovať transakcie.",
"resetAndReapplyAll": "Resetovať a znovu aplikovať",
"confirmResetAndReapplyAll": "Resetovať kategórie, poznámky a popisy spravované pravidlami pri zodpovedajúcich transakciách a potom znovu aplikovať všetky aktívne pravidlá?",
"add": "Pridať",
@@ -1262,7 +1276,10 @@
"ignoreActionHint": "(nevyžaduje hodnotu)",
"selectCategory": "Vybrať kategóriu...",
"selectAccount": "Vybrať účet...",
- "ruleActive": "Aktívne pravidlo",
+ "turnOn": "Zapnúť",
+ "turnOff": "Vypnúť",
+ "turnedOn": "Pravidlo zapnuté",
+ "turnedOff": "Pravidlo vypnuté",
"noConditions": "(žiadne podmienky)",
"noActions": "(žiadne akcie)",
"fieldDescription": "Popis",
@@ -1289,15 +1306,20 @@
"sortBy_priority": "Priorita",
"sortBy_name": "Názov",
"sortBy_category": "Kategória",
- "export": "Export",
- "import": "Import",
+ "export": "Exportovať",
+ "import": "Importovať",
"exported": "Export pravidiel stiahnutý",
"imported": "Importovaných pravidiel: {{imported}} (preskočených: {{skipped}})",
"invalidImportFile": "Neplatný súbor importu pravidiel",
"importConfirmTitle": "Importovať pravidlá kategorizácie?",
"importConfirmDescription": "Počet pravidiel v súbore {{file}}: {{count}}.",
"importOverwriteWarning": "Import prepíše tvoje aktuálne pravidlá kategorizácie. Túto akciu nie je možné vrátiť späť.",
- "confirmOverwriteImport": "Prepísať a importovať"
+ "confirmOverwriteImport": "Prepísať a importovať",
+ "tab": {
+ "rules": "Pravidlá",
+ "queue": "Čaká na vás",
+ "history": "História"
+ }
},
"categories": {
"title": "Kategórie",
@@ -2374,5 +2396,200 @@
"subtitle": "Pridaj pripojenie a nasmeruj Securo na lokálnu Ollamu, OpenAI, Anthropic alebo ľubovoľný OpenAI-compatible endpoint."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Faktúry",
+ "invoicesHint": "voči tomu, čo máte dostať a čo zaplatiť",
+ "recurring": "Opakované",
+ "recurringHint": "voči tomu, čo ste už čakali",
+ "inactive": "Tu sa nepoužíva"
+ },
+ "rule": {
+ "sameClientExact": "Známa osoba, presná suma",
+ "netOfWithholding": "Známa osoba, zaplatené so zrážkou",
+ "exactAmountAnyClient": "Presná suma, ktokoľvek",
+ "similarDescription": "Blízka suma a podobný popis",
+ "sameAccountExact": "Rovnaký účet, presná suma",
+ "unknown": "Pravidlo",
+ "partPayment": "Známa osoba, časť sumy",
+ "severalInvoices": "Známa osoba, viac faktúr naraz"
+ },
+ "outcome": {
+ "link": "Spáruje samo",
+ "suggest": "Navrhuje"
+ },
+ "cond": {
+ "samePayee": "osoba je tá z faktúry",
+ "sameAccount": "rovnaký účet",
+ "amountExact": "suma sedí presne",
+ "amountTolerance": "suma je v rozmedzí {{percent}}%",
+ "amountRatio": "suma sedí po zrážke dane",
+ "window": "až {{before}} dní skôr, {{after}} dní neskôr",
+ "similarity": "popis je podobný aspoň na {{min}}",
+ "none": "žiadne podmienky",
+ "accounts": "na {{names}}",
+ "payees": "pre {{names}}",
+ "moneyIn": "prichádzajúce peniaze",
+ "moneyOut": "odchádzajúce peniaze",
+ "foreign": "v cudzej mene",
+ "currencyIn": "v {{codes}}",
+ "atLeast": "od {{value}}",
+ "atMost": "do {{value}}",
+ "textContains": "výpis hovorí „{{text}}“",
+ "textExcludes": "výpis nehovorí „{{text}}“",
+ "onArrival": "keď peniaze prídu alebo odídu",
+ "onIssue": "keď sa vystaví faktúra",
+ "amountPartial": "suma pokrýva časť dlžnej sumy",
+ "amountSet": "až {{count}} faktúr dá túto sumu"
+ },
+ "newRule": "Nové pravidlo párovania",
+ "saved": "Pravidlo uložené",
+ "reset": "Pravidlo obnovené",
+ "restore": "Vrátiť na predvolené",
+ "changed": "Zmenené",
+ "yours": "Vaše",
+ "field": {
+ "name": "Názov",
+ "namePlaceholder": "napr.: Známa osoba, blízka suma",
+ "outcome": "Čo urobí, keď sadne",
+ "outcomeHint": "Spárovať vyrovná samo. Navrhnúť pošle položku do zoznamu nižšie na vaše potvrdenie.",
+ "counterparty": "Kto zaplatil alebo dostal",
+ "amount": "Suma",
+ "window": "Povolený rozdiel medzi dátumami",
+ "windowHint": "Omeškanie sa počíta od splatnosti, predčasná platba odo dňa vystavenia faktúry, takže zaplatiť deň po vystavení nie sú týždne vopred.",
+ "beforeDays": "Dní skôr",
+ "afterDays": "Dní neskôr",
+ "similarity": "Podobnosť popisu",
+ "similarityHint": "Od 0 do 1. Nechajte prázdne, ak sa popis nemá brať do úvahy.",
+ "similarityOff": "vypnuté",
+ "scope": "Kedy toto pravidlo platí",
+ "scopeHint": "Nechajte prázdne, aby platilo pre všetko",
+ "accounts": "Bankové účty",
+ "anyAccount": "Ktorýkoľvek účet",
+ "payees": "Osoby",
+ "anyPayee": "Ktokoľvek",
+ "direction": "Príjem alebo výdaj",
+ "currencyScope": "Len v týchto menách",
+ "currencyPlaceholder": "napr. USD, EUR",
+ "foreignOnly": "Len meny iné než mena tohto priestoru",
+ "amountBand": "Len sumy v tomto rozsahu",
+ "noMinimum": "bez minima",
+ "noMaximum": "bez maxima",
+ "text": "Text výpisu",
+ "textContains": "musí obsahovať…",
+ "textExcludes": "nesmie obsahovať…",
+ "textHint": "Viac slov oddelených čiarkami znamená ktorékoľvek z nich.",
+ "trigger": "Kedy hľadáme",
+ "triggerHint": "Párovanie prebieha v dvoch momentoch a dôkazy nie sú rovnaké.",
+ "amountMatch": "Ako presne musí sedieť suma",
+ "amountMatchHint": "Porovnáva sa s tým, čo ešte dlhujete, nie s pôvodným súčtom.",
+ "amountBandHint": "O samotnej platbe: veľkosť, ktorú má toto pravidlo riešiť alebo nie."
+ },
+ "counterparty": {
+ "any": "Ktokoľvek",
+ "samePayee": "Osoba z faktúry"
+ },
+ "amount": {
+ "exact": "Presne dlžná suma",
+ "tolerance": "V rámci tolerancie",
+ "ratio": "Po zrážkovej dani",
+ "ratioHint": "Používa sadzby zrážkovej dane vašej krajiny. Kým nie sú, pravidlo nespáruje nič.",
+ "partial": "Časť dlžnej sumy",
+ "partialHint": "Pre tých, čo platia po častiach. Zvyšok zostáva otvorený a ďalšia platba sadne presne.",
+ "set": "Viac faktúr spolu",
+ "setHint": "Pre platbu, ktorá pokrýva viac než jednu faktúru. Ak sedí viac kombinácií, radšej sa spýtame, než by sme vyberali.",
+ "setMax": "Najviac toľko faktúr",
+ "setFee": "Povoliť poplatok",
+ "setFeeHint": "Podiel z hodnoty faktúr, pre platbu, ktorá prechádza po odpočítaní poplatku. Nula znamená, že súčet musí sedieť presne."
+ },
+ "queue": {
+ "title": "Čaká na vás",
+ "hint": "Párovania, ktoré čakajú na vaše potvrdenie.",
+ "empty": "Nič na kontrolu. Všetko sa spárovalo samo.",
+ "aPayment": "Platba",
+ "maySettle": "môže uhrádzať {{name}}",
+ "mayBe": "môže byť {{name}}",
+ "accept": "Spárovať",
+ "declineHint": "Toto to nie je. Tento pár už nebudeme navrhovať.",
+ "linked": "Spárované",
+ "declined": "Zamietnuté. Už sa nespýtame",
+ "covers": "pokrýva"
+ },
+ "evidence": {
+ "amountExact": "suma sedí presne",
+ "amountOff": "očakávané {{expected}}, pohnuté {{moved}}",
+ "knownPayer": "známa osoba",
+ "unknownPayer": "osoba neurčená",
+ "sameDay": "rovnaký deň",
+ "daysApart": "rozdiel {{days}} dní"
+ },
+ "direction": {
+ "any": "Je to jedno",
+ "in": "Prichádzajúce peniaze",
+ "out": "Odchádzajúce peniaze"
+ },
+ "step": {
+ "what": "Čo je toto pravidlo",
+ "which": "Na aké peniaze sa pozerá",
+ "whichHint": "Nechajte všetko prázdne a pozerá sa na všetky",
+ "match": "Kedy sa to počíta ako zhoda",
+ "matchHint": "Ako presne si musia platba a záväzok sadnúť"
+ },
+ "trigger": {
+ "money_arrives": "Keď peniaze prídu alebo odídu",
+ "money_arrivesHint": "Platba sa objaví vo výpise a my hľadáme faktúru, ktorú vyrovnáva.",
+ "invoice_issued": "Keď sa vystaví faktúra",
+ "invoice_issuedHint": "Platba prišla skôr a faktúra neskôr, preto sa pozeráme späť, na peniaze, ktoré tam už boli.",
+ "both": "V oboch momentoch",
+ "bothHint": "Pravidlo platí na obe strany."
+ },
+ "history": {
+ "title": "Čo párovanie urobilo",
+ "hint": "Od najnovších.",
+ "byPerson": "vami",
+ "byRules": "pravidlami",
+ "more": "Zobraziť ďalších {{count}}",
+ "less": "Zobraziť menej",
+ "action": {
+ "linked": "Prepojené s {{name}}",
+ "accepted": "Návrh pre {{name}} prijatý",
+ "suggested": "Navrhnuté pre {{name}}",
+ "declined": "Návrh pre {{name}} zamietnutý",
+ "expired": "Návrh vypršal: {{name}}",
+ "unlinked": "Odpojené od {{name}}"
+ },
+ "empty": "Zatiaľ nič. Naplní sa, ako párovanie spája, pýta sa a dostáva odpoveď."
+ },
+ "moveUp": "Skúšať túto skôr",
+ "moveDown": "Skúšať túto neskôr",
+ "matchingTitle": "Pravidlá párovania",
+ "matchingHint": "Ako sa každá platba viaže na to, čo vyrovnáva.",
+ "pair": {
+ "owed": "Čo sa dlhuje",
+ "arrived": "Čo sa pohlo",
+ "draftInvoice": "Faktúra v návrhu",
+ "recurringBill": "Opakovaná platba",
+ "noMoney": "Bez transakcie.",
+ "stillOpen": "stále otvorené",
+ "thisPayment": "táto platba",
+ "wasApplied": "započítané",
+ "wouldRemain": "zostane",
+ "wouldClose": "uhrádza ju",
+ "thePayment": "platba",
+ "acrossInvoices": "na {{count}} faktúr",
+ "dueOn": "splatnosť {{date}}",
+ "totalOf": "spolu {{amount}}"
+ },
+ "discarded": "Odstránené z tohto priestoru:",
+ "noneLeft": "V tejto skupine už nie sú žiadne pravidlá párovania. Nič sa tu nepáruje automaticky.",
+ "confirmDeleteTitle": "Odstrániť toto pravidlo?",
+ "confirmDeleteDescription": "„{{name}}“ prestáva o čomkoľvek rozhodovať. Ak je to jedno z našich, môžete ho neskôr vrátiť.",
+ "exported": "Pravidlá párovania stiahnuté",
+ "imported": "Importovaných {{imported}} pravidiel ({{skipped}} preskočených)",
+ "invalidImportFile": "Toto nie je súbor s pravidlami párovania",
+ "importConfirmTitle": "Importovať pravidlá párovania?",
+ "importConfirmDescription": "Súbor {{file}} obsahuje {{count}} pravidiel.",
+ "importOverwriteWarning": "Import nahradí pravidlá párovania tohto priestoru vrátane ich poradia. Nedá sa to vrátiť."
}
}
diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.json
index 19198ec2..a47b6a8e 100644
--- a/frontend/src/locales/uk.json
+++ b/frontend/src/locales/uk.json
@@ -372,7 +372,18 @@
"fromSystem": "Із {{source}} · {{date}}",
"fromUpload": "Завантажено · {{date}}"
},
- "draftSaved": "Чернетку збережено"
+ "draftSaved": "Чернетку збережено",
+ "suggestions": {
+ "title_one": "Платіж може закрити цей рахунок",
+ "title_few": "{{count}} платежі можуть закрити цей рахунок",
+ "title_many": "{{count}} платежів можуть закрити цей рахунок",
+ "title_other": "{{count}} платежів можуть закрити цей рахунок",
+ "alsoCovers_one": "також покриває ще {{count}} рахунок",
+ "alsoCovers_few": "і ще {{count}} рахунки",
+ "alsoCovers_many": "і ще {{count}} рахунків",
+ "alsoCovers_other": "також покриває ще {{count}} рахунків",
+ "wouldApply": "застосує {{amount}}"
+ }
},
"collections": {
"title": "Колекції",
@@ -813,7 +824,9 @@
"calendarTransfersExcluded": "Перекази не враховуються як надходження чи витрати",
"invoiceBadge": "Invoice {{number}}",
"invoiceBadgeNoNumber": "Invoice",
- "invoiceBadgeTooltip": "This transaction settles an invoice. Open it."
+ "invoiceBadgeTooltip": "Ця операція закриває рахунок. Відкрити.",
+ "suggestionBadge": "Питання",
+ "suggestionBadgeTooltip": "Платіж може закрити цей рахунок. Відкрийте чергу, щоб відповісти."
},
"accounts": {
"title": "Рахунки",
@@ -1145,6 +1158,7 @@
"createMissingCategories": "Також створити категорії за замовчуванням, необхідні пакету",
"duplicateName": "Правило з такою назвою вже існує",
"sectionTitle": "Правила категоризації",
+ "sectionHint": "Як категоризувати транзакції.",
"resetAndReapplyAll": "Скинути й застосувати заново",
"confirmResetAndReapplyAll": "Скинути категорії, примітки й описи, змінені правилами, у відповідних транзакцій, а потім заново застосувати всі активні правила?",
"add": "Додати",
@@ -1187,7 +1201,10 @@
"ignoreActionHint": "(значення не потрібне)",
"selectCategory": "Оберіть категорію...",
"selectAccount": "Оберіть рахунок...",
- "ruleActive": "Активне правило",
+ "turnOn": "Увімкнути",
+ "turnOff": "Вимкнути",
+ "turnedOn": "Правило увімкнено",
+ "turnedOff": "Правило вимкнено",
"noConditions": "(немає умов)",
"noActions": "(немає дій)",
"fieldDescription": "Опис",
@@ -1222,7 +1239,12 @@
"importConfirmTitle": "Імпортувати правила категоризації?",
"importConfirmDescription": "Файл {{file}} містить правил: {{count}}.",
"importOverwriteWarning": "Імпорт перезапише поточні правила категоризації. Ця дія незворотна.",
- "confirmOverwriteImport": "Перезаписати та імпортувати"
+ "confirmOverwriteImport": "Перезаписати та імпортувати",
+ "tab": {
+ "rules": "Правила",
+ "queue": "Чекає на вас",
+ "history": "Історія"
+ }
},
"categories": {
"title": "Категорії",
@@ -2247,5 +2269,200 @@
"subtitle": "Додайте підключення, щоб направити Securo на ваш локальний Ollama, OpenAI, Anthropic або будь-який сумісний з OpenAI ендпоінт."
}
}
+ },
+ "reconciliation": {
+ "node": {
+ "invoices": "Рахунки",
+ "invoicesHint": "з тим, що вам винні і що винні ви",
+ "recurring": "Регулярні",
+ "recurringHint": "з тим, що ви вже очікували",
+ "inactive": "Тут не використовується"
+ },
+ "rule": {
+ "sameClientExact": "Відома особа, точна сума",
+ "netOfWithholding": "Відома особа, сплачено з утриманням",
+ "exactAmountAnyClient": "Точна сума, будь-яка особа",
+ "similarDescription": "Близька сума й схожий опис",
+ "sameAccountExact": "Той самий рахунок, точна сума",
+ "unknown": "Правило",
+ "partPayment": "Відома особа, частина суми",
+ "severalInvoices": "Відома особа, кілька рахунків одразу"
+ },
+ "outcome": {
+ "link": "Зв’язує саме",
+ "suggest": "Пропонує"
+ },
+ "cond": {
+ "samePayee": "особа та сама, що в рахунку",
+ "sameAccount": "той самий рахунок",
+ "amountExact": "сума збігається точно",
+ "amountTolerance": "сума в межах {{percent}}%",
+ "amountRatio": "сума збігається за вирахуванням податку",
+ "window": "до {{before}} днів раніше, {{after}} днів пізніше",
+ "similarity": "опис схожий щонайменше на {{min}}",
+ "none": "без умов",
+ "accounts": "на {{names}}",
+ "payees": "для {{names}}",
+ "moneyIn": "гроші, що надходять",
+ "moneyOut": "гроші, що виходять",
+ "foreign": "в іноземній валюті",
+ "currencyIn": "у {{codes}}",
+ "atLeast": "від {{value}}",
+ "atMost": "до {{value}}",
+ "textContains": "у виписці сказано «{{text}}»",
+ "textExcludes": "у виписці не сказано «{{text}}»",
+ "onArrival": "коли гроші приходять або йдуть",
+ "onIssue": "коли виставляється рахунок",
+ "amountPartial": "сума покриває частину боргу",
+ "amountSet": "до {{count}} рахунків дають цю суму"
+ },
+ "newRule": "Нове правило зіставлення",
+ "saved": "Правило збережено",
+ "reset": "Правило відновлено",
+ "restore": "Повернути типове значення",
+ "changed": "Змінено",
+ "yours": "Ваше",
+ "field": {
+ "name": "Назва",
+ "namePlaceholder": "напр.: Відома особа, близька сума",
+ "outcome": "Що робити при збігу",
+ "outcomeHint": "«Зв’язати» закриває саме. «Запропонувати» надсилає до списку нижче, щоб ви підтвердили.",
+ "counterparty": "Хто заплатив або отримав",
+ "amount": "Сума",
+ "window": "Допустима різниця між датами",
+ "windowHint": "Прострочення рахується від строку оплати, а дострокова оплата — від дня виставлення рахунку: оплата наступного дня після виставлення не є достроковою на тижні.",
+ "beforeDays": "Днів раніше",
+ "afterDays": "Днів пізніше",
+ "similarity": "Схожість опису",
+ "similarityHint": "Від 0 до 1. Залиште порожнім, щоб не враховувати опис.",
+ "similarityOff": "вимкнено",
+ "scope": "Коли діє це правило",
+ "scopeHint": "Залиште порожнім, щоб діяло для всього",
+ "accounts": "Банківські рахунки",
+ "anyAccount": "Будь-який рахунок",
+ "payees": "Люди",
+ "anyPayee": "Будь-яка особа",
+ "direction": "Надходження чи витрата",
+ "currencyScope": "Лише в цих валютах",
+ "currencyPlaceholder": "напр. USD, EUR",
+ "foreignOnly": "Лише валюти, відмінні від валюти цього простору",
+ "amountBand": "Лише суми в цьому діапазоні",
+ "noMinimum": "без мінімуму",
+ "noMaximum": "без максимуму",
+ "text": "Текст виписки",
+ "textContains": "має містити…",
+ "textExcludes": "не може містити…",
+ "textHint": "Кілька через кому означає будь-яке з них.",
+ "trigger": "Коли ми шукаємо",
+ "triggerHint": "Зіставлення відбувається у два моменти, і докази в них різні.",
+ "amountMatch": "Наскільки точною має бути сума",
+ "amountMatchHint": "Порівнюється із залишком боргу, а не з початковою сумою.",
+ "amountBandHint": "Про сам платіж: розмір, який це правило має опрацьовувати чи ні."
+ },
+ "counterparty": {
+ "any": "Будь-хто",
+ "samePayee": "Особа з рахунку"
+ },
+ "amount": {
+ "exact": "Рівно належна сума",
+ "tolerance": "У межах допуску",
+ "ratio": "За вирахуванням утриманого податку",
+ "ratioHint": "Використовує ставки утримання вашої країни. Поки їх немає, правило нічого не зіставить.",
+ "partial": "Частина того, що належить",
+ "partialHint": "Для тих, хто платить частинами. Залишок лишається відкритим, а наступний платіж збігається точно.",
+ "set": "Кілька рахунків разом",
+ "setHint": "Для платежу, що покриває більше одного рахунку. Якщо підходить кілька сполучень, ми питаємо, а не обираємо.",
+ "setMax": "Не більше стількох рахунків",
+ "setFee": "Допустити комісію",
+ "setFeeHint": "Частка від суми рахунків, для платежу, що проходить за вирахуванням комісії. Нуль означає, що сума має збігатися точно."
+ },
+ "queue": {
+ "title": "Чекає на вас",
+ "hint": "Зіставлення, які чекають на ваше підтвердження.",
+ "empty": "Немає чого переглядати. Усе зіставилося саме.",
+ "aPayment": "Платіж",
+ "maySettle": "можливо, закриває {{name}}",
+ "mayBe": "можливо, це {{name}}",
+ "accept": "Зв’язати",
+ "declineHint": "Не те. Цю пару більше не пропонуватимемо.",
+ "linked": "Зв’язано",
+ "declined": "Відхилено. Більше не запитаємо",
+ "covers": "покриває"
+ },
+ "evidence": {
+ "amountExact": "сума збігається точно",
+ "amountOff": "очікувалось {{expected}}, пройшло {{moved}}",
+ "knownPayer": "відома особа",
+ "unknownPayer": "особу не визначено",
+ "sameDay": "той самий день",
+ "daysApart": "різниця {{days}} днів"
+ },
+ "direction": {
+ "any": "Байдуже",
+ "in": "Гроші, що надходять",
+ "out": "Гроші, що виходять"
+ },
+ "step": {
+ "what": "Що це за правило",
+ "which": "На які гроші воно дивиться",
+ "whichHint": "Залиште все порожнім, і воно дивиться на всі",
+ "match": "Коли це вважається збігом",
+ "matchHint": "Наскільки близько мають зійтися платіж і зобов’язання"
+ },
+ "trigger": {
+ "money_arrives": "Коли гроші приходять або йдуть",
+ "money_arrivesHint": "Платіж з'являється у виписці, і ми шукаємо рахунок, який він закриває.",
+ "invoice_issued": "Коли виставляється рахунок",
+ "invoice_issuedHint": "Платіж прийшов раніше, а рахунок пізніше, тому ми дивимось назад, на гроші, які вже були.",
+ "both": "В обидва моменти",
+ "bothHint": "Правило діє в обидва боки."
+ },
+ "history": {
+ "title": "Що зробило зіставлення",
+ "hint": "Спершу найновіші.",
+ "byPerson": "вами",
+ "byRules": "правилами",
+ "more": "Показати ще {{count}}",
+ "less": "Показати менше",
+ "action": {
+ "linked": "Пов’язано з {{name}}",
+ "accepted": "Пропозицію щодо {{name}} прийнято",
+ "suggested": "Запропоновано для {{name}}",
+ "declined": "Пропозицію щодо {{name}} відхилено",
+ "expired": "Пропозиція минула: {{name}}",
+ "unlinked": "Зв’язок з {{name}} знято"
+ },
+ "empty": "Поки нічого. Тут з’явиться те, що зіставлення пов’язало, запитало й отримало у відповідь."
+ },
+ "moveUp": "Перевіряти це раніше",
+ "moveDown": "Перевіряти це пізніше",
+ "matchingTitle": "Правила зіставлення",
+ "matchingHint": "Як кожен платіж пов'язується з тим, що він закриває.",
+ "pair": {
+ "owed": "Що належить",
+ "arrived": "Що пройшло",
+ "draftInvoice": "Чернетка рахунку",
+ "recurringBill": "Регулярний платіж",
+ "noMoney": "Операції немає.",
+ "stillOpen": "ще відкрито",
+ "thisPayment": "цей платіж",
+ "wasApplied": "зараховано",
+ "wouldRemain": "залишиться",
+ "wouldClose": "закриває",
+ "thePayment": "платіж",
+ "acrossInvoices": "на {{count}} рахунків",
+ "dueOn": "термін {{date}}",
+ "totalOf": "разом {{amount}}"
+ },
+ "discarded": "Видалені з цього простору:",
+ "noneLeft": "У цьому наборі не лишилося правил зіставлення. Тут нічого не зіставляється автоматично.",
+ "confirmDeleteTitle": "Видалити це правило?",
+ "confirmDeleteDescription": "«{{name}}» перестає щось вирішувати. Якщо це одне з наших, його можна повернути пізніше.",
+ "exported": "Правила зіставлення завантажено",
+ "imported": "Імпортовано правил: {{imported}} (пропущено: {{skipped}})",
+ "invalidImportFile": "Це не файл правил зіставлення",
+ "importConfirmTitle": "Імпортувати правила зіставлення?",
+ "importConfirmDescription": "Файл {{file}} містить правил: {{count}}.",
+ "importOverwriteWarning": "Імпорт замінює правила зіставлення цього простору разом з їхнім порядком. Скасувати не можна."
}
}
diff --git a/frontend/src/pages/invoice-detail.tsx b/frontend/src/pages/invoice-detail.tsx
index 799e77dd..0d6d1a04 100644
--- a/frontend/src/pages/invoice-detail.tsx
+++ b/frontend/src/pages/invoice-detail.tsx
@@ -34,6 +34,7 @@ import {
SelectValue,
} from '@/components/ui/select'
import { PageHeader } from '@/components/page-header'
+import { InvoiceSuggestions } from '@/components/invoice-suggestions'
import {
IconAction,
SectionCard,
@@ -545,6 +546,11 @@ export default function InvoiceDetailPage() {
</SectionCard>
)}
+ {/* Above the payments, because it is a question about them and
+ because an answer here changes the list below. Renders
+ nothing when nothing is waiting. */}
+ <InvoiceSuggestions invoiceId={invoice.id} canWrite={canWrite} />
+
<SectionCard>
<SectionHeader
title={t('invoices.payments')}
diff --git a/frontend/src/pages/pages.contract.test.ts b/frontend/src/pages/pages.contract.test.ts
index 10749081..ab6970f0 100644
--- a/frontend/src/pages/pages.contract.test.ts
+++ b/frontend/src/pages/pages.contract.test.ts
@@ -23,6 +23,16 @@ const paths = Object.keys(modules)
.filter((path) => !path.includes('.test.'))
.sort()
+// First evaluation of a module compiles its whole transitive graph through
+// Vite, which is slow and varies with how much else is running in parallel.
+// The default 5s is a budget for a *test*, not for a compile, and the page
+// with the heaviest graph sits right on it, so adding one component
+// anywhere in the tree can fail a page test that has nothing to do with it.
+//
+// A generous ceiling hides nothing: a module that fails to evaluate rejects
+// immediately, and only a genuine hang reaches this number.
+const EVALUATION_BUDGET_MS = 20_000
+
describe('page modules', () => {
it('finds the page tree', () => {
// If a refactor moves pages elsewhere, this suite would otherwise pass
@@ -46,6 +56,6 @@ describe('page modules', () => {
component !== null &&
'$$typeof' in component),
).toBe(true)
- })
+ }, EVALUATION_BUDGET_MS)
}
})
diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsx
index 82b65e45..5180dd82 100644
--- a/frontend/src/pages/rules.tsx
+++ b/frontend/src/pages/rules.tsx
@@ -1,4 +1,5 @@
import { useRef, useState, useMemo } from 'react'
+import { useSearchParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { categories as categoriesApi, categoryGroups as categoryGroupsApi, rules as rulesApi, accounts as accountsApi, payees as payeesApi } from '@/lib/api'
@@ -17,11 +18,16 @@ import {
import type { Category, Payee, Rule, RuleAction, RuleCondition, RuleConditionNode, RuleExportPayload } from '@/types'
import { isConditionGroup } from '@/lib/rule-conditions'
import { normalizeRuleMatchValue, ruleSearchText } from '@/lib/rule-match-utils'
-import { Trash2, Plus, RefreshCw, Package, Check, ArrowUpDown, ArrowUp, ArrowDown, Download, Upload, Search } from 'lucide-react'
+import { Trash2, Plus, RefreshCw, Package, Check, ArrowUpDown, ArrowUp, ArrowDown, Download, Upload, Search, Power } from 'lucide-react'
import { cn } from '@/lib/utils'
import { PageHeader } from '@/components/page-header'
import { useWorkspace } from '@/contexts/workspace-context'
import { RuleDialog } from '@/components/rule-dialog'
+import { ReconciliationRules } from '@/components/reconciliation-rules'
+import { ReconciliationQueue } from '@/components/reconciliation-queue'
+import { ReconciliationHistory } from '@/components/reconciliation-history'
+import { Segmented } from '@/components/invoice-ui'
+import { reconciliation as reconciliationApi } from '@/lib/api'
import { findCategoryReference, getRuleCategoryName } from '@/lib/category-reference-utils'
function SectionCard({ children }: { children: React.ReactNode }) {
@@ -32,10 +38,25 @@ function SectionCard({ children }: { children: React.ReactNode }) {
)
}
-function SectionHeader({ title, action }: { title: string; action?: React.ReactNode }) {
+function SectionHeader({
+ title,
+ hint,
+ action,
+}: {
+ title: string
+ /** One line saying what this list of rules decides. The matching card
+ * carried one and this one did not, so the two cards answered
+ * different questions: one told you what it was for, the other
+ * assumed you knew. */
+ hint?: string
+ action?: React.ReactNode
+}) {
return (
- <div className="px-4 sm:px-5 py-4 border-b border-border flex flex-wrap items-center justify-between gap-2">
- <p className="text-sm font-semibold text-foreground">{title}</p>
+ <div className="px-4 sm:px-5 py-4 border-b border-border flex flex-wrap items-start justify-between gap-2">
+ <div>
+ <p className="text-sm font-semibold text-foreground">{title}</p>
+ {hint && <p className="text-xs text-muted-foreground mt-0.5">{hint}</p>}
+ </div>
{action}
</div>
)
@@ -139,7 +160,7 @@ const FILTER_CONTROL_CLASS = 'h-7 rounded-md border border-border bg-background
export default function RulesPage() {
const { t } = useTranslation()
const queryClient = useQueryClient()
- const { canWrite } = useWorkspace()
+ const { canWrite, hasModule } = useWorkspace()
const [dialogOpen, setDialogOpen] = useState(false)
const [packsDialogOpen, setPacksDialogOpen] = useState(false)
const [importDialogOpen, setImportDialogOpen] = useState(false)
@@ -247,6 +268,27 @@ export default function RulesPage() {
},
})
+ // Flipping the switch, and nothing else.
+ //
+ // Turning a rule on through the editor also runs it over transactions
+ // already filed, which is the right default when you have just
+ // finished writing the rule. It is the wrong default for one click on
+ // an icon: nothing on screen warned that months of categories were
+ // about to be rewritten. So the row does the smaller act, and catching
+ // up stays explicit: the editor's own checkbox, or "Reset and
+ // reapply" in the header.
+ const toggleMutation = useMutation({
+ mutationFn: (rule: Rule) =>
+ rulesApi.update(rule.id, { is_active: !rule.is_active, apply_to_existing: false }),
+ onSuccess: (_result, rule) => {
+ queryClient.invalidateQueries({ queryKey: ['rules'] })
+ toast.success(t(rule.is_active ? 'rules.turnedOff' : 'rules.turnedOn'))
+ },
+ onError: (err: unknown) => {
+ toast.error(extractApiError(err, t('common.error')))
+ },
+ })
+
const deleteMutation = useMutation({
mutationFn: (id: string) => rulesApi.delete(id),
onSuccess: () => {
@@ -360,13 +402,85 @@ export default function RulesPage() {
return list.sort((a, b) => dir * (a.priority - b.priority))
}, [filteredRules, displayCategories, sortBy, sortDir])
+ // Three reasons to come here, not one. Rules is configuration: visited
+ // when somebody wants to change behaviour. The queue is *work*, visited
+ // when there is something pending. History is *audit*, visited to find
+ // out what happened. Burying work inside a configuration page meant only
+ // people who came to configure something ever discovered they had any.
+ // Matching serves two sets that belong to different modules: invoices,
+ // and the bills you told us to expect. Either one is enough to have a
+ // queue and a history worth showing; without both, the routes behind
+ // them answer 404, so two permanently empty tabs would be furniture and
+ // asking for their contents would be asking for a 404 on every load.
+ const matching = hasModule('invoices') || hasModule('recurring')
+
+ // Addressable, because the queue is now linked to from elsewhere: a
+ // badge on a transaction row is a promise to land on the question, and
+ // landing on the rules list instead would break it.
+ const [searchParams, setSearchParams] = useSearchParams()
+ const requested = searchParams.get('tab')
+ const asked =
+ requested === 'queue' || requested === 'history' ? requested : 'rules'
+ // A link to a tab this workspace does not have lands on the one it
+ // does, rather than on a page rendering nothing.
+ const tab: 'rules' | 'queue' | 'history' = matching ? asked : 'rules'
+ const setTab = (next: 'rules' | 'queue' | 'history') => {
+ // `replace`, so the back button leaves the page rather than walking
+ // back through tabs somebody clicked on the way.
+ setSearchParams(next === 'rules' ? {} : { tab: next }, { replace: true })
+ }
+
+ // Fetched here rather than inside the queue so the count can sit on the
+ // tab: a queue nobody can see is not a queue.
+ const { data: pending } = useQuery({
+ queryKey: ['reconciliation-suggestions'],
+ queryFn: reconciliationApi.suggestions,
+ enabled: matching,
+ })
+
return (
<div>
<PageHeader section={t('rules.section')} title={t('nav.rules')} />
+ <div className="mb-4">
+ <Segmented
+ value={tab}
+ onChange={setTab}
+ testIdPrefix="automation-tab"
+ options={[
+ { value: 'rules', label: t('rules.tab.rules') },
+ ...(matching ? [{
+ value: 'queue' as const,
+ // The count is rendered here rather than through Segmented's
+ // own `count`, which is a muted figure beside a filter: the
+ // right weight for "Overdue 2" and the wrong one for work
+ // waiting on somebody. This is a nudge, so it looks like
+ // one; when there is nothing waiting it disappears entirely
+ // rather than announcing a zero.
+ label: (
+ <span className="inline-flex items-center gap-1.5">
+ {t('rules.tab.queue')}
+ {!!pending?.length && (
+ <span className="inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-amber-500 text-white text-[10px] font-semibold tabular-nums">
+ {pending.length}
+ </span>
+ )}
+ </span>
+ ),
+ },
+ { value: 'history' as const, label: t('rules.tab.history') }] : []),
+ ]}
+ />
+ </div>
+
+ {matching && tab === 'queue' && <ReconciliationQueue canWrite={canWrite} />}
+ {matching && tab === 'history' && <ReconciliationHistory />}
+
+ <div className={tab === 'rules' ? '' : 'hidden'}>
<SectionCard>
<SectionHeader
title={t('rules.sectionTitle')}
+ hint={t('rules.sectionHint')}
action={
canWrite ? (
<div className="flex gap-2">
@@ -536,6 +650,27 @@ export default function RulesPage() {
</div>
{canWrite && (
<div className="flex items-center gap-1 shrink-0">
+ {/* Stopping a rule and deleting it are different
+ decisions, and only one of them was reachable
+ from here. The other was a checkbox inside the
+ editor, so switching a rule off meant opening
+ it, finding the box, and saving a form you did
+ not want to change. It lives on the row now, in
+ the same place and the same shape as on a
+ matching rule below. */}
+ <button
+ className={cn(
+ 'p-1.5 rounded-md transition-colors hover:bg-background',
+ rule.is_active
+ ? 'text-emerald-600 hover:text-emerald-700'
+ : 'text-muted-foreground hover:text-foreground',
+ )}
+ onClick={(e) => { e.stopPropagation(); toggleMutation.mutate(rule) }}
+ disabled={toggleMutation.isPending}
+ title={t(rule.is_active ? 'rules.turnOff' : 'rules.turnOn')}
+ >
+ <Power size={13} />
+ </button>
<button
className="p-1.5 rounded-md text-muted-foreground hover:text-rose-500 hover:bg-rose-50 transition-colors"
onClick={(e) => { e.stopPropagation(); setDeletingRule(rule) }}
@@ -557,6 +692,17 @@ export default function RulesPage() {
)}
</SectionCard>
+ {/* Matching rules below categorization rules, because they are the
+ same promise made twice: the software decides things about your
+ money, and you get to see the decision and disagree with it.
+ Not mounted at all without the module: rendering it and letting
+ it decide to show nothing still costs a request that comes back
+ 404. */}
+ <div className="mt-6 space-y-6">
+ {matching && <ReconciliationRules canWrite={canWrite} />}
+ </div>
+ </div>
+
<DeleteConfirmationDialog
open={!!deletingRule}
title={t('rules.confirmDeleteTitle')}
diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsx
index becb5678..dd08f6df 100644
--- a/frontend/src/pages/transactions.tsx
+++ b/frontend/src/pages/transactions.tsx
@@ -7,7 +7,7 @@ import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useDisplayLocale, useDateLocale } from '@/hooks/use-display-locale'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { transactions, categories as categoriesApi, categoryGroups as categoryGroupsApi, accounts as accountsApi, recurring, payees as payeesApi, admin, groups as groupsApi, rules as rulesApi } from '@/lib/api'
+import { transactions, categories as categoriesApi, categoryGroups as categoryGroupsApi, accounts as accountsApi, recurring, payees as payeesApi, admin, groups as groupsApi, rules as rulesApi, reconciliation as reconciliationApi } from '@/lib/api'
import { invalidateFinancialQueries } from '@/lib/invalidate-queries'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
@@ -36,7 +36,7 @@ import {
} from '@/components/ui/table'
import { Skeleton } from '@/components/ui/skeleton'
import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Clock, HelpCircle, Info, Paperclip, Trash2, Users, X, EyeClosed, ChartNoAxesColumn, SlidersHorizontal, Receipt } from 'lucide-react'
-import type { Transaction, Rule, InstallmentSeriesInput, TransactionApplyScope, TransactionEditPayload } from '@/types'
+import type { Transaction, Rule, InstallmentSeriesInput, TransactionApplyScope, TransactionEditPayload, ReconciliationSuggestion } from '@/types'
import { RuleDialog, type RuleDialogInitialData } from '@/components/rule-dialog'
import { PageHeader } from '@/components/page-header'
import { calculateRangeSelection } from '@/lib/selection-utils'
@@ -91,7 +91,7 @@ export default function TransactionsPage() {
const isMobile = useIsMobile()
const { user } = useAuth()
const { activeAccountIds } = useCollectionFilter()
- const { canWrite } = useWorkspace()
+ const { canWrite, hasModule } = useWorkspace()
const userCurrency = user?.preferences?.currency_display ?? 'USD'
const queryClient = useQueryClient()
const [page, setPage] = useState(1)
@@ -489,6 +489,30 @@ export default function TransactionsPage() {
[recurringList],
)
+ // Every open question, indexed by the money it is about. One request
+ // for the page rather than one per row: the queue is small by design,
+ // and if it ever is not, that is the rules wanting changing rather than
+ // this needing pagination.
+ //
+ // Skipped entirely where neither set is on, so a workspace pays nothing
+ // for a surface it cannot reach. Either one is enough: the recurring
+ // matcher records its questions against a transaction exactly as the
+ // invoice one does, and a personal workspace has only that one.
+ const { data: openQuestions } = useQuery<ReconciliationSuggestion[]>({
+ queryKey: ['reconciliation-suggestions'],
+ queryFn: reconciliationApi.suggestions,
+ enabled: hasModule('invoices') || hasModule('recurring'),
+ })
+ const suggestionsByTransaction = useMemo(
+ () =>
+ new Map(
+ (openQuestions ?? [])
+ .filter((s) => s.transaction?.id)
+ .map((s) => [s.transaction!.id, s]),
+ ),
+ [openQuestions],
+ )
+
const { data: accountingModeData } = useQuery({
queryKey: ['admin', 'accounting-mode'],
queryFn: () => admin.accountingMode(),
@@ -1117,6 +1141,22 @@ export default function TransactionsPage() {
{/* One badge per invoice this row settles: a payout net of
fees settles several, and showing only the last one read
as if the others had never been paid. */}
+ {/* A question waiting on this row. The confirmed link above
+ is green and settled; this is amber and open, because it
+ is not a fact yet. It lived only in a tab on the rules
+ page, which meant you found out a question existed by
+ going somewhere you had no reason to go. */}
+ {suggestionsByTransaction.get(tx.id) && (
+ <Link
+ to="/rules?tab=queue"
+ onClick={(e) => e.stopPropagation()}
+ title={t('transactions.suggestionBadgeTooltip')}
+ className="inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wide text-amber-700 bg-amber-50 border border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-900 px-1.5 py-0.5 rounded-full hover:bg-amber-100 dark:hover:bg-amber-950/70 transition-colors"
+ >
+ <HelpCircle className="h-3 w-3" />
+ {t('transactions.suggestionBadge')}
+ </Link>
+ )}
{(tx.invoice_links ?? []).map((link) => (
<Link
key={link.invoice_id}
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 405443d2..1685e9f1 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -1311,3 +1311,217 @@ export interface InvoiceFacets {
draft: number
}
}
+
+// ---------------------------------------------------------------------------
+// Reconciliation
+// ---------------------------------------------------------------------------
+
+/** The signals matching consults, as the API sends them.
+ *
+ * Deliberately not an open-ended condition tree like the categorization
+ * rules: matching runs on a fixed set of signals, and a form over exactly
+ * those is honest about what the engine can actually look at. */
+/** Which moment a rule runs at.
+ *
+ * `money_arrives`: a payment lands and we look for the promise it
+ * answers; the promise came first and was waiting.
+ * `invoice_issued`: a document is written and we look back at money that
+ * arrived before it existed, the client who pays and lets the nota
+ * follow. Weaker evidence: that money already had a life of its own.
+ * `both`: the rule trusts either. */
+export type Trigger = 'money_arrives' | 'invoice_issued' | 'both'
+
+export interface ReconciliationConditions {
+ // -- Which money the rule is written for. Every one of these decides
+ // whether the rule is consulted at all, before any comparison. Absent
+ // means "no limit", never "none".
+ /** Only money in these bank accounts. */
+ accounts?: { in: string[] }
+ /** Only money from these clients. Different from `counterparty`, which
+ * asks whether the payer is the one named on the invoice. */
+ payees?: { in: string[] }
+ /** Only money coming in, or only money going out. */
+ direction?: 'any' | 'credit' | 'debit'
+ /** What the statement line has to say, or must not. Case-insensitive. */
+ /** One word, or several meaning *any of them*. Stored as written, so a
+ * rule naming one gateway stays a string and does not read as changed. */
+ text?: { contains?: string | string[]; not_contains?: string | string[] }
+
+ // -- How closely the pair has to fit.
+ counterparty?: 'any' | 'same_payee'
+ amount?: {
+ /** `partial` is what makes two transactions on one invoice reachable:
+ * every other mode compares against the whole outstanding balance,
+ * and half of it is simply not that. */
+ match: 'exact' | 'tolerance' | 'ratio' | 'partial' | 'set'
+ percent?: string
+ /** For `set`: how many invoices one payment may cover. */
+ max_invoices?: number
+ epsilon?: string
+ ratios?: string
+ difference_kind?: string
+ /** For `partial`: the smallest fraction of the balance worth
+ * offering, so a token payment is not proposed as an instalment. */
+ min_ratio?: string
+ /** For `partial`: the largest, above which the gap is a fee or a
+ * withholding rather than an instalment. */
+ max_ratio?: string
+ /** Bounds on the movement itself, not on how close it is to the
+ * promise: "never link anything over ten thousand on its own". */
+ min?: string
+ max?: string
+ }
+ /** Asymmetric on purpose: late is measured from the due date, early from
+ * the day the promise was written. */
+ date?: { before_days: number; after_days: number }
+ description_similarity?: { min: string }
+ currency?: {
+ /** Whether a movement may settle a promise held in another currency. */
+ conversion: 'reject' | 'allow'
+ /** Only these currency codes. */
+ in?: string[]
+ /** Only currencies other than the workspace's own: what somebody
+ * means by "check anything that is not in our money". */
+ foreign?: boolean
+ }
+ same_account?: boolean
+ unique_candidate?: boolean
+}
+
+export interface ReconciliationRule {
+ id: string
+ node: string
+ /** Set only for a rule the workspace wrote. A shipped rule keeps its
+ * translated name, which would otherwise freeze in one language the day
+ * somebody edited a threshold. */
+ name?: string | null
+ origin: 'default' | 'custom'
+ /** Whether this workspace departed from what we ship. Drives the "you
+ * changed this" mark and the offer to put it back. */
+ customised: boolean
+ enabled: boolean
+ outcome: 'link' | 'suggest'
+ trigger: Trigger
+ when: ReconciliationConditions
+ position: number
+}
+
+export interface ReconciliationNode {
+ node: string
+ /** Whether the set is reachable for this workspace at all. The invoice
+ * rules mean nothing where the module is off. */
+ active: boolean
+ rules: ReconciliationRule[]
+ /** Rules we ship that this workspace threw away. Sent so the page can
+ * offer them back: a shipped rule leaves a tombstone rather than a
+ * hole, so we still know its name, and without this the delete is a
+ * trap, because the row is gone and there is nothing left to click. */
+ discarded: { id: string; node: string }[]
+}
+
+/** A matching policy as a file. Ids are resolved to names on the way out
+ * and looked up again on the way in: a UUID means nothing in another
+ * database. */
+export interface ReconciliationPolicyFile {
+ format: string
+ version: number
+ policy_version: number
+ nodes: {
+ node: string
+ rules: {
+ id: string
+ origin: string
+ name: string | null
+ enabled: boolean
+ outcome: string
+ trigger: string
+ when: Record<string, unknown>
+ }[]
+ discarded: string[]
+ }[]
+}
+
+export interface ReconciliationRulePatch {
+ enabled?: boolean
+ outcome?: 'link' | 'suggest'
+ trigger?: Trigger
+ when?: ReconciliationConditions
+ position?: number
+}
+
+export interface ReconciliationRuleDraft {
+ node: string
+ name: string
+ outcome: 'link' | 'suggest'
+ trigger?: Trigger
+ when: ReconciliationConditions
+ enabled?: boolean
+ position?: number | null
+}
+
+/** One match the engine was not confident enough to make on its own.
+ *
+ * `scores` is a per-signal breakdown rather than one number: "78% sure" is
+ * not something anyone can check, while "the amount is exact and the date
+ * is four days out" tells a person exactly where to look. */
+export interface ReconciliationSuggestion {
+ id: string
+ node: string
+ strategy_id: string
+ expectation_kind: 'invoice' | 'recurring'
+ expectation_id: string
+ expectation_label?: string | null
+ amount: string
+ scores: {
+ strategy?: string
+ description?: number
+ amount_expected?: string
+ amount_moved?: string
+ amount_exact?: boolean
+ days_apart?: number
+ same_counterparty?: boolean
+ currency?: string
+ }
+ status: 'pending' | 'accepted' | 'declined' | 'expired'
+ created_at: string
+ /** Everything this one question covers. A single entry for the ordinary
+ * case; several when one payment is offered against several invoices,
+ * which is answered whole or not at all. */
+ covers: {
+ expectation_kind: 'invoice' | 'recurring'
+ expectation_id: string
+ label?: string | null
+ amount: string
+ }[]
+ transaction?: {
+ id: string
+ description?: string | null
+ amount: string
+ currency?: string | null
+ date: string
+ type: string
+ } | null
+}
+
+/** One thing matching did.
+ *
+ * `linked` means the rules did it on their own; `accepted` means a person
+ * did, by answering a question. They are never both written for one act:
+ * the allocation an acceptance produces is its consequence, not a second
+ * event, because the whole stream is organised around that one line. */
+export interface ReconciliationHistoryEvent {
+ id: string
+ at: string
+ action: 'linked' | 'suggested' | 'accepted' | 'declined' | 'expired' | 'unlinked'
+ expectation_kind: 'invoice' | 'recurring'
+ expectation_id: string
+ expectation_label?: string | null
+ amount: string
+ /** What `amount` is denominated in, resolved from the promise. */
+ currency?: string | null
+ strategy_id?: string | null
+ /** Null means the rules acted on their own. */
+ user_id?: string | null
+ transaction_id?: string | null
+ transaction_description?: string | null
+}