Open-source personal finance manager. Self-hosted, privacy-first.
feat: put transfer matching on the rules page (#985)
Tássio Noronha6284972d5a37
diff --git a/backend/alembic/versions/091_suggestion_transaction_kind.py b/backend/alembic/versions/091_suggestion_transaction_kind.pynew file mode 100644index 00000000..74bc4fb6--- /dev/null+++ b/backend/alembic/versions/091_suggestion_transaction_kind.py@@ -0,0 +1,46 @@+"""letting a suggestion point at a transaction++The suggestion queue was built for promises somebody wrote down: an+invoice, or a recurring bill. Transfer pairing adds a third kind of+thing a payment can answer, and it is the odd one: the other leg is not+a promise at all, it is another statement line. Money leaving one+account *is* the expectation that the same money arrives in another, and+that is enough to be unsure about in exactly the same way.++So the check constraint learns one more word. Nothing else about the+table changes: the same pair is still asked about once, a declined pair+is still never offered again, and `expectation_id` still carries no+foreign key, for the same reason it never did. It has to point at+whichever table the kind names, and a column cannot point at three.++SQLite cannot alter a constraint in place and the test suite runs on it,+so the rebuild goes through a batch operation, which is a no-op shape on+Postgres beyond the DDL it emits anyway.+"""+from alembic import op++revision = "091"+down_revision = "090"+branch_labels = None+depends_on = None++_TABLE = "reconciliation_suggestions"+_NAME = "ck_reconciliation_suggestion_kind"+_WITH_TRANSACTION = "expectation_kind IN ('invoice', 'recurring', 'transaction')"+_WITHOUT = "expectation_kind IN ('invoice', 'recurring')"+++def upgrade() -> None:+ with op.batch_alter_table(_TABLE) as batch:+ batch.drop_constraint(_NAME, type_="check")+ batch.create_check_constraint(_NAME, _WITH_TRANSACTION)+++def downgrade() -> None:+ # The rows have to go before the constraint can come back, and they+ # are questions rather than records: a transfer suggestion nobody+ # answered is worth nothing once the feature that raised it is gone.+ op.execute(f"DELETE FROM {_TABLE} WHERE expectation_kind = 'transaction'")+ with op.batch_alter_table(_TABLE) as batch:+ batch.drop_constraint(_NAME, type_="check")+ batch.create_check_constraint(_NAME, _WITHOUT)diff --git a/backend/app/api/reconciliation.py b/backend/app/api/reconciliation.pyindex 6fe252b5..a770ad07 100644--- a/backend/app/api/reconciliation.py+++ b/backend/app/api/reconciliation.py@@ -5,18 +5,25 @@ where a decision was not confident enough to be made alone. Seeing themside by side is the point: somebody staring at a long queue should beone 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.+**Open to every workspace, gated per set.** The router itself asks only+for a workspace, because one of the sets it serves belongs to no module:+pairing the two legs of a transfer has run on every sync for every+workspace, personal ones included, since long before modules existed.+Gating the router on invoicing would have hidden the rules for the+automation that touches the most people's data.++Which *set* you may touch is still a second question, asked per node by+`_assert_node`, and it answers 404 rather than 403: a workspace without+invoicing should not learn that invoice matching exists by being told it+may not look.++This has moved twice, and both moves were the same correction. The+router was open while recurring rules were editable here, then closed to+the modules when those left the page, and a personal workspace was left+able to write and reorder rules that could never fire: configuration+accumulating for a module nobody had. The answer was never the gate. It+was that the page had nothing on it for a personal workspace. Now it+does."""import uuidfrom decimal import Decimal@@ -28,8 +35,12 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom 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.core.workspace_context import (+ WorkspaceContext,+ current_workspace,+ current_writable_workspace,+)+from app.models.account import Accountfrom app.models.invoice import Invoicefrom app.models.reconciliation import ReconciliationRulefrom app.models.recurring_transaction import RecurringTransaction@@ -54,17 +65,17 @@ from app.services import (reconciliation_rule_service as rules,reconciliation_suggestion_service as suggestions,)-from app.services.module_service import ModuleId, resolve_modules+from app.services.module_service import resolve_modulesrouter = 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)+#: A workspace, and for writes a role that may write. No module: every+#: workspace has transfer pairing, so there is no version of this page+#: that is empty, and a gate that hid it would be hiding the rules for+#: something already running on the reader's own data. The per-node check+#: below is what keeps the invoice set out of a workspace without it.+_read = current_workspace+_write = current_writable_workspacedef _assert_node(ctx: WorkspaceContext, node: str) -> None:@@ -120,10 +131,10 @@ async def list_rules(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.+ # Structural: `nodes_for` already dropped the sets this+ # workspace does not have, 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)@@ -281,13 +292,23 @@ async def reset_rule(# ---------------------------------------------------------------------------@router.get("/rules/export")async def export_rules(+ node: Optional[str] = None,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))- )+ """The matching policy as a file, with ids resolved to names.++ `node` narrows it to one set. Each set is its own card on the page+ with its own button, and a button under *Transfers* that quietly+ hands over the invoice rules too is a button that lies. Without it+ the file carries everything this workspace has, which is what the+ page-level export always meant.+ """+ available = rules.nodes_for(resolve_modules(ctx.workspace))+ if node is not None:+ _assert_node(ctx, node)+ available = (node,)+ payload = await portability.export_policy(session, ctx.workspace.id, available)return JSONResponse(content=payload,headers={@@ -299,9 +320,22 @@ async def export_rules(@router.post("/rules/import", response_model=ReconciliationImportResponse)async def import_rules(data: ReconciliationImportRequest,+ node: Optional[str] = None,ctx: WorkspaceContext = Depends(_write),session: AsyncSession = Depends(get_async_session),):+ """Take a policy file back in.++ `node` narrows it the same way the export does, and for the stronger+ reason: the button sits on one card, so a file dropped on *Transfers*+ must not be able to rewrite the invoice rules. Sets the file carries+ and this call did not ask for are skipped and counted, exactly as a+ set this workspace does not have already is.+ """+ available = rules.nodes_for(resolve_modules(ctx.workspace))+ if node is not None:+ _assert_node(ctx, node)+ available = (node,)try:result = await portability.import_policy(session,@@ -309,7 +343,7 @@ async def import_rules(ctx.user_id,data.payload,overwrite=data.overwrite,- nodes=rules.nodes_for(resolve_modules(ctx.workspace)),+ nodes=available,)except rules.ExistingPolicyError as exc:# 409 rather than 400: nothing is wrong with the file, and the@@ -431,10 +465,102 @@ async def accept_suggestion(return await _with_label(session, row)+#: What must still be true of two rows before they may be bound as one+#: transfer, whatever rule proposed them.+#:+#: The first four are the definition: money crossing between two accounts+#: moves the opposite way on each side, in one currency. They are checked+#: rather than assumed because a transaction stays editable while its+#: suggestion sits in the queue.+#:+#: The amounts are checked against what was recorded when the question+#: was raised, not against each other. A rule may well have matched an+#: approximate pair, so "are they equal" is the wrong question; "are they+#: what the person is being shown" is the right one.+def _transfer_still_holds(moved: Transaction, counterpart: Transaction, row) -> bool:+ if moved.account_id == counterpart.account_id:+ return False+ if moved.type == counterpart.type:+ return False+ if moved.currency != counterpart.currency:+ return False++ scores = row.scores or {}+ for leg, key in ((moved, "amount_moved"), (counterpart, "amount_expected")):+ recorded = scores.get(key)+ if recorded is None:+ # An older row from before the breakdown carried these. The+ # definitional checks above still ran; there is nothing more+ # to compare against, and refusing every one of them would be+ # answering uncertainty with a dead queue.+ continue+ try:+ if abs(Decimal(leg.amount)) != Decimal(str(recorded)):+ return False+ except (ArithmeticError, ValueError):+ return False+ return True++async def _settle(session: AsyncSession, ctx: WorkspaceContext, row) -> None:"""Write one member of an accepted question."""+ if row.expectation_kind == "transaction":+ # The two legs of a transfer. Nothing is allocated and nothing is+ # replaced: they are both real rows that stay, and agreeing means+ # they learn they are halves of one movement.+ #+ # **Both rows are locked, not just the suggestion.** The lock on+ # the suggestion guards this row and no other, and one transaction+ # can sit in two pending questions at once: the ambiguous case+ # that raises them puts the same credit against two debits, side+ # by side in the queue with a button each. Two accepts a moment+ # apart would both read it as unpaired, both write, and leave the+ # loser's other leg carrying a pair id with nothing on the far+ # end. Ordered by id so two requests cannot take the locks in+ # opposite orders and deadlock.+ locked = await session.execute(+ select(Transaction)+ .where(+ Transaction.id.in_([row.transaction_id, row.expectation_id]),+ Transaction.workspace_id == ctx.workspace.id,+ )+ .order_by(Transaction.id)+ .with_for_update(of=Transaction)+ )+ by_id = {leg.id: leg for leg in locked.scalars().all()}+ moved = by_id.get(row.transaction_id)+ counterpart = by_id.get(row.expectation_id)+ if moved is None or counterpart is None:+ raise invoice_service.InvoiceError(+ "transaction_missing", "One of the transactions is no longer there"+ )+ legs = (moved, counterpart)+ if any(leg.transfer_pair_id is not None for leg in legs):+ # Paired since we asked, by a sync, a rule someone edited, or+ # the person doing it by hand. Re-pairing would overwrite a+ # link somebody may have chosen deliberately.+ raise invoice_service.InvoiceError(+ "already_paired", "One of these is already part of a transfer"+ )+ if not _transfer_still_holds(moved, counterpart, row):+ # **The rows are not the ones the question was about.** A+ # transaction stays editable while its suggestion waits, so+ # the amount, the account, the direction or the currency can+ # all have moved since we asked. Accepting anyway would bind+ # two rows on the strength of an answer to a different+ # question, and a paired row leaves income and expense, so+ # the damage is a total quietly changing.+ raise invoice_service.InvoiceError(+ "suggestion_stale",+ "These transactions changed since we asked. Check them again.",+ )+ pair_id = uuid.uuid4()+ for leg in legs:+ leg.transfer_pair_id = pair_id+ return+if row.expectation_kind == "invoice":invoice = await session.get(Invoice, row.expectation_id)if invoice is None or invoice.workspace_id != ctx.workspace.id:@@ -548,6 +674,16 @@ async def _with_label(session: AsyncSession, row) -> SuggestionRead:async def _name_of(session: AsyncSession, row) -> Optional[str]:+ if row.expectation_kind == "transaction":+ # The account it came from or went to, not the statement text.+ # "Is this the other half of a transfer" is a question about two+ # accounts, and the description is usually a reference number+ # that answers nothing.+ leg = await session.get(Transaction, row.expectation_id)+ if leg is None:+ return None+ account = await session.get(Account, leg.account_id)+ return account.name if account else leg.descriptionif row.expectation_kind == "invoice":invoice = await session.get(Invoice, row.expectation_id)return await _invoice_name(session, invoice) if invoice else None@@ -562,6 +698,9 @@ async def _currency_of(session: AsyncSession, row) -> Optional[str]:settlement was written in the promise's currency and matching refusesa pair whose currencies disagree, so there is only ever one answer."""+ if row.expectation_kind == "transaction":+ leg = await session.get(Transaction, row.expectation_id)+ return leg.currency if leg else Noneif row.expectation_kind == "invoice":invoice = await session.get(Invoice, row.expectation_id)return invoice.currency if invoice else Nonediff --git a/backend/app/models/reconciliation.py b/backend/app/models/reconciliation.pyindex 8e049c58..ca8605e3 100644--- a/backend/app/models/reconciliation.py+++ b/backend/app/models/reconciliation.py@@ -149,7 +149,7 @@ class ReconciliationSuggestion(Base):name="ck_reconciliation_suggestion_status",),CheckConstraint(- "expectation_kind IN ('invoice', 'recurring')",+ "expectation_kind IN ('invoice', 'recurring', 'transaction')",name="ck_reconciliation_suggestion_kind",),# The queue is always read as "what is still open here", so that isdiff --git a/backend/app/schemas/reconciliation.py b/backend/app/schemas/reconciliation.pyindex 455d3088..5baf11ad 100644--- a/backend/app/schemas/reconciliation.py+++ b/backend/app/schemas/reconciliation.py@@ -113,6 +113,11 @@ class SuggestionTransactionRead(BaseModel):currency: Optional[str] = Nonedate: datetype: str+ #: Which account the money moved on. The queue asks whether two+ #: records are the same money, and with transfers in it that question+ #: is about accounts: a row naming only the other side leaves the+ #: reader to work out which of theirs this one is.+ account_id: Optional[uuid.UUID] = Noneclass SuggestionCovers(BaseModel):diff --git a/backend/app/services/reconciliation_engine.py b/backend/app/services/reconciliation_engine.pyindex bdf39bb8..fdb06bce 100644--- a/backend/app/services/reconciliation_engine.py+++ b/backend/app/services/reconciliation_engine.py@@ -46,7 +46,7 @@ from decimal import ROUND_DOWN, Decimalfrom enum import Enumfrom typing import Any, Literal, Optional-from app.services.text_similarity import token_overlap+from app.services.text_similarity import names_account, token_overlap#: What the decision came out of. Named rather than boolean so a node#: graph can wire each one somewhere different later.@@ -54,7 +54,16 @@ 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"]+#:+#: `transaction` is the odd one and worth naming: the other two are+#: promises somebody wrote down, while this one is the other leg of a+#: transfer, which is a promise only by implication. Money leaving one+#: account **is** the expectation that the same money arrives in another,+#: so the leg is carried here with its direction flipped: a debit of 100+#: is an expectation of a credit of 100. That flip is what lets the+#: direction check below go on meaning what it says instead of needing a+#: mode for transfers.+ExpectationKind = Literal["invoice", "recurring", "transaction"]#: **Which way round the match is being made.** Matching happens at two#: different moments and they are not the same question.@@ -84,6 +93,23 @@ class Reason(str, Enum):DIRECTION = "direction_differs"CURRENCY = "currency_differs"COUNTERPARTY = "different_counterparty"+ #: Both legs are on the same account, so nothing moved between+ #: accounts. Its own reason rather than `COUNTERPARTY`, because a+ #: person reading a transfer's trace is asking about accounts and+ #: being told "different counterparty" would send them looking at+ #: payees.+ SAME_ACCOUNT = "same_account"+ #: Neither side's text names the other side's account, and this rule+ #: only trusts a pair that says where it is going.+ ACCOUNT_NOT_NAMED = "neither_description_names_the_other_account"+ #: The rule was written for legs on a particular kind of account (a+ #: credit card, typically) and neither of these is one.+ ACCOUNT_TYPE = "account_type_not_covered"+ #: It fitted, and another candidate fitted the same way while sitting+ #: closer in time. Not a failure of this pair so much as a statement+ #: that a better one was available, and worth saying in those words:+ #: *rejected* would send somebody looking for what was wrong with it.+ FURTHER_IN_TIME = "another_candidate_is_closer_in_time"AMOUNT = "amount_outside_tolerance"DATE = "date_outside_window"DESCRIPTION = "description_too_different"@@ -133,6 +159,14 @@ class Movement:counterparty: Optional[str] = Nonepayee_id: Optional[uuid.UUID] = Noneaccount_id: Optional[uuid.UUID] = None+ #: What the account is called, and what kind it is. Only transfer+ #: matching reads them, and it needs both: the name because the one+ #: signal that reliably tells two same-amount transfers apart is a+ #: description naming where the money went, and the kind because a+ #: leg on a credit card deserves a different answer from a leg+ #: between two checking accounts.+ account_name: Optional[str] = None+ account_type: Optional[str] = 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.@@ -155,10 +189,20 @@ class Expectation:direction: strwhen: datedescription: Optional[str] = None+ #: As printed by the bank, when this expectation is itself a+ #: statement line. The identifying words land in whichever of the two+ #: fields the bank felt like using, so a signal that read only+ #: `description` would miss the half of them that use the other.+ counterparty: Optional[str] = Nonepayee_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+ #: As on `Movement`, and read by the same rules. An invoice and a+ #: recurring bill leave them null; the other leg of a transfer is an+ #: account and fills both.+ account_name: Optional[str] = None+ account_type: Optional[str] = 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.@@ -752,6 +796,62 @@ def evaluate(trace.append(note)continue+ # The inverse, and the defining condition of a transfer:+ # money that left one account and arrived in another. Its own+ # key rather than a value on `same_account`, so that a rule+ # reads as a list of things that must be true and never as a+ # flag whose meaning depends on how it is set.+ if rule.get("different_account") and (+ movement.account_id is None+ or movement.account_id == candidate.account_id+ ):+ note.rejected_by = Reason.SAME_ACCOUNT+ trace.append(note)+ continue++ wanted_types = _as_list(rule.get("account_types"))+ if wanted_types and not (+ movement.account_type in wanted_types+ or candidate.account_type in wanted_types+ ):+ # Either leg is enough. A rule that exists to be careful+ # about credit cards has to fire whichever end the card+ # is on, and asking somebody to write the rule twice+ # would be asking them to know which side we happen to+ # examine first.+ note.rejected_by = Reason.ACCOUNT_TYPE+ trace.append(note)+ continue++ # How strongly the two texts point at each other. **Graded,+ # not a yes or no**, and that is the whole of why the+ # wrong-counterpart case comes out right.+ #+ # Two transfers leave one account on the same day and the+ # incoming line reads `Transfer from BNP`. That names the+ # source, so on its own it fits *both* debits equally and+ # decides nothing. What separates them is that one of the+ # two also reads `To FORTUNEO ACCOUNT`, so that pair names+ # itself from both ends and the other only from one.+ #+ # A boolean would have called both a match and handed the+ # choice back to the tie-break, which has nothing to go on+ # when the dates are identical. Counting the directions puts+ # the better pair in front, where `tie_break` can see it.+ naming: Optional[float] = None+ if rule.get("account_name_in_description"):+ sides = (+ names_account(movement.description, candidate.account_name)+ or names_account(movement.counterparty, candidate.account_name),+ names_account(candidate.description, movement.account_name)+ or names_account(candidate.counterparty, movement.account_name),+ )+ if not any(sides):+ note.rejected_by = Reason.ACCOUNT_NOT_NAMED+ trace.append(note)+ continue+ naming = sum(1 for side in sides if side) / 2.0+ok, difference, difference_kind = _amount_verdict(movement.amount, candidate.amount, rule.get("amount", {}), ratios)@@ -776,6 +876,11 @@ def evaluate(note.score = scoretrace.append(note)continue+ elif naming is not None:+ # Only when nothing else grades the pair. A rule asking+ # for both would be asking two questions of one number,+ # and no rule does.+ score = namingnote.score = scoretrace.append(note)@@ -785,6 +890,49 @@ def evaluate(continueoutcome = strategy.get("outcome", "suggest")++ if len(matched) > 1 and rule.get("tie_break") == "closest_date":+ # **Two different meanings of "more than one candidate", and+ # collapsing them loses a signal people rely on.**+ #+ # Transfers are where this shows. Money leaves an account+ # today and two credits of the same value sit in the+ # destination, one today and one two days out: the same-day+ # one is the transfer and the other is somebody paying you+ # back. Refusing both because there were two would throw away+ # the very signal the old detector was built on, and it was+ # right about it.+ #+ # What it was wrong about is the case where nothing separates+ # them. Two debits leaving on the same day for different+ # destinations are equidistant from the credit, and there the+ # answer has to be a question.+ #+ # So this narrows to the candidates tied at the front, and+ # whatever `unique_candidate` says next applies to those. A+ # clear winner is one candidate and links; a genuine tie is+ # still several and does not.+ def _closeness(entry: tuple[Expectation, Any, Any, float]):+ return (-entry[3], abs((movement.when - entry[0].when).days))++ ranked = sorted(matched, key=_closeness)+ front = _closeness(ranked[0])+ tied = [entry for entry in ranked if _closeness(entry) == front]+ if len(tied) < len(matched):+ beaten = {id(entry) for entry in matched} - {id(e) for e in tied}+ for note in trace:+ if (+ note.strategy == strategy["id"]+ and note.rejected_by is None+ and any(+ entry[0].id == note.expectation_id+ for entry in matched+ if id(entry) in beaten+ )+ ):+ note.rejected_by = Reason.FURTHER_IN_TIME+ matched = tied+if len(matched) > 1:if rule.get("unique_candidate", False):# Several answers to a question that admits one. Downgradediff --git a/backend/app/services/reconciliation_policy.py b/backend/app/services/reconciliation_policy.pyindex 3f8dc6f5..a583ae23 100644--- a/backend/app/services/reconciliation_policy.py+++ b/backend/app/services/reconciliation_policy.py@@ -262,6 +262,187 @@ MATCH_PLACEHOLDER: dict[str, Any] = {"on_ambiguity": "suggest",}+#: The same money leaving one account and arriving in another.+#:+#: **This node is not new behaviour looking for users.** Transfer+#: detection has run on every sync since long before this file existed,+#: as a hundred and forty lines with the window, the signals and the+#: decision to link rather than ask all written as constants nobody could+#: see or change. Everything below was already happening. What changes is+#: that it is now on a page, in the workspace's own words, with a switch+#: next to it.+#:+#: Four things the old code could not do, and each is an open report:+#:+#: - **It never asked what a transfer is.** Any debit could pair with+#: any credit, so a purchase at a bar was a candidate for money+#: arriving in a current account. It is not: that money went to the+#: bar. See `exclude_legs` below, which answers it before any rule+#: runs rather than by asking.+#: - **It never read the description.** Two transfers of the same+#: amount leaving one account on the same day were told apart by+#: whichever row the database returned first, even when one line+#: plainly read `To FORTUNEO ACCOUNT`. `destination_named_in_description`+#: is that missing signal.+#: - **It only ever linked.** There was no way to say *this one is+#: plausible, ask me*, so two indistinguishable legs were settled by+#: row order. Now that case is a question.+#: - **It could not be turned off.** A workspace that wants to pair its+#: transfers by hand had to accept the guesses and undo them.+#: Disabling every rule here is now a supported answer.+#:+#: ## What may be a default, and what may not+#:+#: **The enabled rules are what already ran, plus what a transfer is.+#: Everything that is an opinion ships visible and switched off.**+#:+#: The line matters because a default is not a suggestion: it is what+#: happens to people who never open this page, which is most of them. So+#: it has to be defensible without knowing anything about the reader's+#: bank, their country or how they keep their books.+#:+#: Three things clear that bar, and only three:+#:+#: 1. **What the old detector did.** Different accounts, the same+#: amount, within two days, nearest date first. Those numbers ran+#: in production for a long time and nobody is served by us+#: changing them on the day they become visible.+#: 2. **What a transfer is.** Two accounts, opposite directions, the+#: same money. `exclude_legs` and the ignored sources are this: a+#: purchase and a generated placeholder are not money moving+#: between accounts, so no rule should get to weigh them.+#: 3. **A bug the old behaviour had.** Picking a winner when nothing+#: separates the candidates is a coin toss, not a policy, and+#: `unique_candidate` is the smallest change that stops it.+#:+#: Everything else is an opinion, however good: how much text similarity+#: is enough, what percentage counts as the same amount, how wide a+#: window a wire deserves. Those ship off. They are on the page with+#: their conditions written out, one click from running, and a workspace+#: that wants them is a workspace that has read what it is asking for.+#:+#: Cross-currency pairs stay out, and not by omission: the engine refuses+#: a candidate whose currency differs, because matching across currencies+#: needs a rate, a date to take it on, and somewhere to book the+#: remainder. A transfer between accounts of different currencies is made+#: with the transfer tool, which asks for both amounts.+MATCH_TRANSFER: dict[str, Any] = {+ "version": POLICY_VERSION,+ "node": "reconciliation.match_transfer",+ "scope": {+ "movement": "any",+ # An opening balance is where an account started, not money that+ # moved; a generated placeholder is a promise rather than the+ # money itself. Pairing either would invent a transfer.+ "ignore_transaction_sources": ["opening_balance", "recurring"],+ # **A purchase is not a transfer, and no rule below gets a say.**+ #+ # A debit on a credit card is money spent at a shop. It did not+ # move to another account, so there is no second leg anywhere and+ # the honest number of candidates is zero. Any rule that got to+ # look at one would be picking between wrong answers.+ #+ # This is the report where a bar tab and an unrelated+ # reimbursement of the same value were linked, and the purchase+ # silently left the card's bill while the money left income. The+ # first fix offered the pair for confirmation instead, which was+ # still wrong: it asks a question whose answer is always no, and+ # a queue of those is a queue people stop reading.+ #+ # The other direction stays, because it is real: paying the bill+ # is a debit on the account and a **credit** on the card, and+ # that is money moving between two things you own.+ #+ # What this gives up is the cash advance, where a card debit does+ # fund an account. It is rare, it has no signal separating it+ # from the purchase beside it, and the cost of getting it wrong+ # falls on everybody who never takes one.+ "exclude_legs": [{"account_types": ["credit_card"], "direction": "debit"}],+ },+ "strategies": [+ {+ # **Off, and that is the point of the line above.**+ #+ # This is the signal the old code was missing, and it is the+ # one that tells two same-day transfers of the same amount+ # apart: one line reads `To FORTUNEO ACCOUNT` and the other+ # does not. It works, and the person who reported the wrong+ # pairing said as much.+ #+ # But it is a guess about what a bank chose to print, not a+ # fact about what a transfer is, and a bank that prints the+ # *source* on both lines would have it link the wrong pair+ # confidently. Shipping it on would be us deciding that+ # everybody's statements read like the ones we tested+ # against.+ #+ # So it ships visible and off. With it off, the ambiguous+ # case becomes a question, which is already the fix: nothing+ # is linked wrongly. Turning it on upgrades that question to+ # an answer for anybody whose bank names the destination.+ #+ # `unique_candidate` even here: two transfers to the *same*+ # named account on one day are genuinely indistinguishable,+ # and this rule should not be the one that pretends+ # otherwise.+ "id": "destination_named_in_description",+ "enabled": False,+ "outcome": "link",+ "trigger": "both",+ "when": {+ "different_account": True,+ "account_name_in_description": True,+ "amount": {"match": "exact"},+ "date": {"before_days": 2, "after_days": 2},+ "tie_break": "closest_date",+ "unique_candidate": True,+ },+ },+ {+ # What has always run, with the window it has always used.+ # The difference is `unique_candidate`: where the old code+ # took whichever row came back first, an ambiguous pair now+ # becomes a question instead of a coin toss.+ "id": "exact_amount_nearby",+ "enabled": True,+ "outcome": "link",+ "trigger": "both",+ "when": {+ "different_account": True,+ "amount": {"match": "exact"},+ "date": {"before_days": 2, "after_days": 2},+ # Closest first, and a question only when nothing+ # separates them. This keeps the old detector's best+ # instinct and drops the coin toss it fell back on.+ "tie_break": "closest_date",+ "unique_candidate": True,+ },+ },+ {+ # Off, and on the page anyway.+ #+ # A wire that arrives a few cents short of what left is a+ # real transfer with a fee taken out of it, and no rule above+ # will ever pair it. But a percentage band over a five-day+ # window also matches a great many things that are not+ # transfers, and a queue that fills up is a queue people stop+ # reading. So it ships visible and switched off: somebody who+ # moves money between countries turns it on knowing what they+ # are buying, and everybody else is not asked to pay for it.+ "id": "close_amount_wider_window",+ "enabled": False,+ "outcome": "suggest",+ "trigger": "both",+ "when": {+ "different_account": True,+ "amount": {"match": "tolerance", "percent": "1"},+ "date": {"before_days": 5, "after_days": 5},+ },+ },+ ],+ "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.@@ -273,6 +454,7 @@ _DEFAULTS: dict[str, dict[str, Any]] = {MATCH_INVOICE["node"]: MATCH_INVOICE,MATCH_RECURRING["node"]: MATCH_RECURRING,MATCH_PLACEHOLDER["node"]: MATCH_PLACEHOLDER,+ MATCH_TRANSFER["node"]: MATCH_TRANSFER,}diff --git a/backend/app/services/reconciliation_rule_service.py b/backend/app/services/reconciliation_rule_service.pyindex 83db9970..3f57ec7d 100644--- a/backend/app/services/reconciliation_rule_service.py+++ b/backend/app/services/reconciliation_rule_service.py@@ -72,13 +72,28 @@ EDITABLE_NODES_BY_MODULE: dict[str, ModuleId] = {reconciliation_policy.MATCH_RECURRING["node"]: ModuleId.RECURRING,}+#: Sets every workspace has, because the matching they configure is not+#: part of any module.+#:+#: Transfer pairing is the first of them, and the distinction it+#: introduces is worth stating plainly: the nodes above exist *because* a+#: module does, and a workspace without invoicing has no use for a rule+#: about invoices. Pairing the two legs of a transfer is not like that.+#: It has run on every sync for every workspace since long before there+#: were modules, personal ones included, and it is the automation that+#: touches the most people's data. Putting it behind the invoicing module+#: would hide the rules for something the majority already has running.+CORE_NODES: tuple[str, ...] = (reconciliation_policy.MATCH_TRANSFER["node"],)+#: Every node a rule may be written against, in the order they are shown.-EDITABLE_NODES = tuple(EDITABLE_NODES_BY_MODULE)+#: Core first: it is the set that is there for everybody, and the page+#: should not open on a section half its readers do not have.+EDITABLE_NODES = CORE_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(+ return CORE_NODES + tuple(nodefor node, module in EDITABLE_NODES_BY_MODULE.items()if module.value in enabled_modules@@ -360,7 +375,20 @@ def validate_config(config: dict[str, Any], *, whole: bool) -> dict[str, Any]:if "text" in when:checked["text"] = _validate_text(when["text"])- for flag in ("same_account", "unique_candidate"):+ if "account_types" in when:+ checked["account_types"] = _validate_account_types(when["account_types"])++ if "tie_break" in when:+ if when["tie_break"] not in _TIE_BREAKS:+ raise RuleError("bad_tie_break", "Unknown way to separate two candidates")+ checked["tie_break"] = when["tie_break"]++ for flag in (+ "same_account",+ "different_account",+ "unique_candidate",+ "account_name_in_description",+ ):if flag in when:checked[flag] = bool(when[flag])@@ -368,9 +396,55 @@ def validate_config(config: dict[str, Any], *, whole: bool) -> dict[str, Any]:raise RuleError("conditions_required", "A rule needs at least one condition")clean["when"] = checked+ if whole:+ # A rule of the workspace's own is complete here, so this is+ # where it can be judged. A patch over one of ours cannot be:+ # it may carry only `outcome`, and whether that is safe depends+ # on conditions living in the shipped rule. `upsert_override`+ # asks again once the two are merged.+ assert_safe_to_link(clean)return clean+#: Amount comparisons that accept money which is **not** the figure+#: expected. `ratio` is deliberately absent: it matches a known fraction+#: of a known invoice, and the fraction is the meaning rather than a+#: margin of error.+_APPROXIMATE_MATCHES = ("tolerance", "partial")+++def assert_safe_to_link(strategy: dict[str, Any]) -> None:+ """Refuse a rule that would link on evidence it cannot be sure of.++ The one guardrail in this file, and it is here because of what the+ damage looks like rather than how likely it is. A rule that links on+ an *approximate* amount, with nothing requiring the winner to be the+ only candidate, quietly rewrites the books: both rows drop out of+ income and expense, the totals move, and nothing anywhere says a+ guess was made. Somebody finds it months later, if at all.++ So the combination is refused, not the ingredients. Approximate and+ linking is fine when the rule also insists there be exactly one+ candidate, because then an ambiguous case becomes a question instead+ of a coin toss. Approximate without that has to suggest.++ Everything else stays permitted on purpose. This is a page for+ people who want to change how their money is matched, and a+ guardrail that second-guesses every choice is a page they stop+ using.+ """+ if strategy.get("outcome") != "link":+ return+ when = strategy.get("when") or {}+ match = (when.get("amount") or {}).get("match", "exact")+ if match in _APPROXIMATE_MATCHES and not when.get("unique_candidate"):+ raise RuleError(+ "unsafe_link",+ "A rule matching an approximate amount can only link when it "+ "also requires a single candidate. Otherwise it has to suggest.",+ )++def _positive_number(value: Any, code: str, message: str) -> str:try:number = float(value)@@ -515,6 +589,38 @@ def _validate_currency(rule: Any) -> dict[str, Any]:return checked+#: How a rule may separate candidates that all fit. One entry, and the+#: list exists so the second one has somewhere to go: the shape of the+#: question ("what breaks the tie") outlives any particular answer.+_TIE_BREAKS = ("closest_date",)++#: The kinds of account a rule may name. Closed rather than free text:+#: a typo in a condition is a rule that silently never fires, and the one+#: place that is unforgivable is matching, where nobody is watching.+_ACCOUNT_TYPES = ("checking", "savings", "credit_card", "investment", "wallet")+++def _validate_account_types(rule: Any) -> list[str]:+ """Which kinds of account this rule is written for.++ Order is not preserved from the input: it is a set of kinds, and two+ rules naming the same kinds in a different order are the same rule.+ """+ if isinstance(rule, str):+ rule = [rule]+ if not isinstance(rule, list) or not rule:+ raise RuleError(+ "bad_account_types", "Choose at least one kind of account, or leave it out"+ )+ chosen = []+ for item in rule:+ if item not in _ACCOUNT_TYPES:+ raise RuleError("bad_account_types", "That is not a kind of account")+ if item not in chosen:+ chosen.append(item)+ return chosen++def _validate_ids(rule: Any, code: str) -> list[str]:"""A list of accounts or clients the rule is limited to.@@ -642,6 +748,17 @@ async def upsert_override(for s in reconciliation_policy.default_policy(node)["strategies"]if s["id"] == strategy_id)+ # What this rule will actually be once the patch is laid over what we+ # ship. Judged here rather than on the patch alone, because a patch+ # saying only `{"outcome": "link"}` is unreadable on its own: whether+ # it is safe depends on conditions it does not carry.+ assert_safe_to_link(+ {+ **shipped_strategy,+ **merged,+ "when": {**shipped_strategy.get("when", {}), **merged.get("when", {})},+ }+ )pruned = _prune(merged, shipped_strategy)keeps_position = row is not None and row.position is not Nonediff --git a/backend/app/services/text_similarity.py b/backend/app/services/text_similarity.pyindex 16578ff1..d9b07077 100644--- a/backend/app/services/text_similarity.py+++ b/backend/app/services/text_similarity.py@@ -16,6 +16,8 @@ weight and this only guards against two promises of the same value."""from __future__ import annotations+import re+import unicodedatafrom typing import Optional@@ -28,3 +30,110 @@ def token_overlap(a: Optional[str], b: Optional[str]) -> float:if not tokens_a or not tokens_b:return 0.0return len(tokens_a & tokens_b) / max(len(tokens_a), len(tokens_b))+++#: Words that name a kind of account rather than a particular one.+#: Without this list "Conta Corrente" would match every statement line+#: carrying the word *conta*, which in Brazil is most of them, and the+#: signal would be worse than not having it.+#:+#: Portuguese and English only, deliberately. These are matched against+#: what a **bank** printed, and the two languages cover the statements+#: this runs on; a Polish stopword that is nobody's account name costs a+#: reader of this list more than it buys.+_GENERIC_ACCOUNT_WORDS = frozenset(+ {+ "account",+ "accounts",+ "balance",+ "bank",+ "banco",+ "banking",+ "card",+ "cartao",+ "cash",+ "checking",+ "conta",+ "corrente",+ "credit",+ "credito",+ "current",+ "debit",+ "debito",+ "deposit",+ "deposito",+ "dinheiro",+ "investimento",+ "investment",+ "joint",+ "main",+ "money",+ "poupanca",+ "principal",+ "salario",+ "salary",+ "savings",+ "transfer",+ "transferencia",+ "wallet",+ "carteira",+ }+)++#: Below this a token is not identifying enough to be trusted on its own+#: as a substring, so it has to land as a whole word.+_PREFIX_MIN = 4+++def normalize_words(value: Optional[str]) -> list[str]:+ """Lowercase, unaccented, punctuation-free words.++ Accents come off because the same bank prints the same account as+ *Itaú* in one field and *ITAU* in another, and a signal that reads one+ and not the other is a signal that works for half the statements in+ the country it was written for.+ """+ if not value:+ return []+ folded = unicodedata.normalize("NFKD", value.casefold())+ stripped = "".join(ch for ch in folded if not unicodedata.combining(ch))+ return [word for word in re.split(r"[^0-9a-z]+", stripped) if word]+++def names_account(text: Optional[str], account_name: Optional[str]) -> bool:+ """Does this text name that account?++ The one signal that reliably tells two same-amount transfers apart.+ When money leaves an account on the same day for two destinations,+ the amounts are identical, the dates are identical, and the *only*+ thing that says which is which is that one line reads+ `To FORTUNEO ACCOUNT` and the other reads `To Trade Republic`.++ Generic words are dropped first, so an account called *Conta+ Corrente* names nothing and this returns False rather than matching+ every line on the statement. What is left has to land either as a+ whole word or as the start of one, which is what catches the+ `NUBANK*IFOOD` and `fortuneo-account` shapes banks actually print+ without letting three letters match anywhere they happen to occur.+ """+ wanted = [+ word+ for word in normalize_words(account_name)+ if word not in _GENERIC_ACCOUNT_WORDS and len(word) >= 3+ ]+ if not wanted:+ return False++ printed = normalize_words(text)+ if not printed:+ return False++ exact = set(printed)+ for word in wanted:+ if word in exact:+ return True+ if len(word) >= _PREFIX_MIN and any(+ token.startswith(word) for token in printed+ ):+ return True+ return Falsediff --git a/backend/app/services/transfer_detection_service.py b/backend/app/services/transfer_detection_service.pyindex 4d55db27..0d44becc 100644--- a/backend/app/services/transfer_detection_service.py+++ b/backend/app/services/transfer_detection_service.py@@ -1,123 +1,369 @@+"""Pairing the two legs of one transfer.++Money leaving one account and arriving in another is one event recorded+twice, and until the two rows know about each other the books are wrong+in a specific way: the same money counts once as an expense and once as+income, and every total that separates the two is overstated at both+ends.++## What changed, and what did not++This ran for a long time as a self-contained heuristic: same amount,+different account, within two days, link them. The signals were right.+What was wrong was that they were **constants nobody could see**, and+three reports say so in three different ways:++ - It never read the description, so two transfers of the same amount+ leaving one account on the same day were told apart by whichever row+ the database returned first, even when one line plainly named its+ destination.+ - It could only link, never ask, so a reimbursement that happened to+ match a purchase was silently removed from income and from the card's+ bill with nothing to review.+ - It could not be turned off.++So the rules moved into `reconciliation_policy` where a workspace can+read and change them, and this module became what is left: load the+candidates, ask the engine, write down what it decided. The engine holds+no session and decides without writing, which is what makes the rule+below possible at all.++## Both sides have to agree++The rule this module exists to enforce: **a pair is linked only when each+leg is the other's single best answer.**++The old code asked in one direction. It walked the debits, and for each+one took the nearest unpaired credit of the same amount. From a debit's+point of view a lone matching credit is unambiguous, so it linked, even+when a second debit was sitting right beside it with an equal claim.+That is the whole of the wrong-counterpart report, and asking the credit+the same question is the whole of the answer: it has two candidates, it+cannot choose, and the pair stops being certain.++Non-mutual pairs are not dropped. They become suggestions, which is the+honest description of them: two rows that look like a transfer, and a+reason we will not say so on our own.+"""import uuidfrom collections import defaultdict-from typing import Optional+from datetime import timedelta+from decimal import Decimal+from typing import Any, Optionalfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from app.models.account import Accountfrom app.models.transaction import Transaction+from app.services import reconciliation_policy+from app.services import reconciliation_rule_service as rule_service+from app.services import reconciliation_suggestion_service as suggestions+from app.services.reconciliation_engine import (+ Decision,+ Expectation,+ Movement,+ evaluate,+)++NODE = reconciliation_policy.MATCH_TRANSFER["node"]++#: The opposite of what a leg did, which is what the other leg must do.+_OPPOSITE = {"debit": "credit", "credit": "debit"}+++def _enabled(policy: dict[str, Any]) -> list[dict[str, Any]]:+ return [s for s in policy.get("strategies", []) if s.get("enabled", True)]+++def _widest_window(policy: dict[str, Any]) -> int:+ """The largest number of days any enabled rule reaches.++ A prefilter, never a decision. Nothing outside the widest window can+ satisfy any rule, so narrowing to it changes no outcome and keeps a+ workspace with years of unpaired rows from being compared against all+ of them.+ """+ days = 0+ for strategy in _enabled(policy):+ window = strategy.get("when", {}).get("date", {})+ days = max(+ days, int(window.get("before_days", 0)), int(window.get("after_days", 0))+ )+ return days+++def _widest_amount_ratio(policy: dict[str, Any]) -> Optional[Decimal]:+ """How far from the figure any enabled rule is willing to look.++ `None` means no useful prefilter: a rule matching a part payment or a+ set has no band around the amount, so every candidate in the window+ has to reach the engine. Zero means every enabled rule wants the+ exact figure, which is the common case and the one worth being fast+ at.+ """+ worst = Decimal("0")+ for strategy in _enabled(policy):+ amount = strategy.get("when", {}).get("amount", {})+ match = amount.get("match", "exact")+ if match == "tolerance":+ worst = max(worst, Decimal(str(amount.get("percent", "0"))) / Decimal("100"))+ elif match != "exact":+ return None+ return worst+++def _as_movement(tx: Transaction, account: Optional[Account]) -> Movement:+ return Movement(+ amount=abs(Decimal(tx.amount)),+ currency=tx.currency,+ direction=tx.type,+ when=tx.date,+ description=tx.description,+ counterparty=tx.payee or tx.original_description,+ payee_id=tx.payee_id,+ account_id=tx.account_id,+ account_name=account.name if account else None,+ account_type=account.type if account else None,+ source=tx.source,+ )+++def _as_expectation(tx: Transaction, account: Optional[Account]) -> Expectation:+ """This leg, seen as the promise it makes about the other one.++ A debit of 100 is the expectation that a credit of 100 lands+ somewhere else, so the direction is flipped on the way in. That is+ what lets the engine's ordinary direction check keep meaning what it+ says: it compares a movement against what was expected, and here what+ is expected is the mirror of what this row did.+ """+ return Expectation(+ kind="transaction",+ id=tx.id,+ amount=abs(Decimal(tx.amount)),+ currency=tx.currency,+ direction=_OPPOSITE.get(tx.type, tx.type),+ when=tx.date,+ description=tx.description,+ counterparty=tx.payee or tx.original_description,+ payee_id=tx.payee_id,+ account_id=tx.account_id,+ account_name=account.name if account else None,+ account_type=account.type if account else None,+ )+++def _excluded_leg(+ tx: Transaction, account: Optional[Account], rules_: list[dict[str, Any]]+) -> bool:+ """Is this row the kind of thing that is never half of a transfer?++ Asked once, before any rule sees it, and asked of **both sides**.+ That symmetry is the point: a card purchase has to disappear whether+ it is the row being examined or the row being offered as a+ counterpart, and a check that ran in only one direction would let it+ back in from the other.++ A veto rather than a rule, because there is nothing here to weigh. A+ debit on a credit card is money that went to a shop; it has no+ second leg to find, so the number of candidates is zero and a rule+ that got to look would only be choosing between wrong answers.+ """+ for rule in rules_:+ kinds = rule.get("account_types")+ if kinds and (account is None or account.type not in kinds):+ continue+ direction = rule.get("direction")+ if direction and tx.type != direction:+ continue+ return True+ return False+++async def _pool(+ session: AsyncSession,+ workspace_id: uuid.UUID,+ ignored_sources: set[str],+ excluded: list[dict[str, Any]],+ accounts: dict[uuid.UUID, Account],+) -> list[Transaction]:+ """Every row still looking for its other half."""+ query = select(Transaction).where(+ Transaction.workspace_id == workspace_id,+ Transaction.transfer_pair_id.is_(None),+ )+ if ignored_sources:+ query = query.where(Transaction.source.not_in(ignored_sources))+ result = await session.execute(query)+ return [+ tx+ for tx in result.scalars().all()+ if not _excluded_leg(tx, accounts.get(tx.account_id), excluded)+ ]async def detect_transfer_pairs(session: AsyncSession,workspace_id: uuid.UUID,candidate_ids: Optional[list[uuid.UUID]] = None,- date_tolerance_days: int = 2,) -> int:- """Detect inter-account transfer pairs and link them with a shared UUID.+ """Link the transfers this workspace's rules are sure about.++ `candidate_ids` narrows the work to rows that just arrived, and+ carries one rule of its own: **a pair may only form when at least one+ leg is new.** Without it a sync would keep reconsidering years of+ unpaired history and pairing two old rows on the strength of a rule+ somebody edited this morning, which is a change nobody asked for+ arriving at a moment nobody is watching.- Algorithm:- 1. When candidate_ids is given, load candidate debits AND candidate credits- so that detection works regardless of which side was just imported.- 2. For each debit, find an unpaired credit with: same user, different account,- same absolute amount, date within ±tolerance days- 3. Greedy closest-date-first matching; each tx can only pair once+ Rows outside `candidate_ids` are still *examined*, because that is+ the only way to ask whether they have a competing claim. They are+ simply never paired with each other.Returns the number of pairs created."""- # Load candidate debits — filtered to candidate_ids when provided- debit_query = select(Transaction).where(- Transaction.workspace_id == workspace_id,- Transaction.type == "debit",- Transaction.transfer_pair_id.is_(None),- Transaction.source != "opening_balance",- )- if candidate_ids:- debit_query = debit_query.where(Transaction.id.in_(candidate_ids))+ policy = await rule_service.resolve(session, workspace_id, NODE)+ strategies = _enabled(policy)+ if not strategies:+ # Every rule turned off is a supported answer, and the one the+ # old code could not give: this workspace pairs its transfers by+ # hand.+ return 0- debit_result = await session.execute(debit_query)- debits = list(debit_result.scalars().all())+ scope = policy.get("scope", {})+ # Loaded before the pool, because what counts as a leg at all depends+ # on the kind of account it sits on.+ accounts = {+ account.id: account+ for account in (+ await session.execute(+ select(Account).where(Account.workspace_id == workspace_id)+ )+ ).scalars()+ }- # When candidate_ids is given, also load ALL unpaired debits that could- # match new credits (the reverse direction).- if candidate_ids:- reverse_debit_query = select(Transaction).where(- Transaction.workspace_id == workspace_id,- Transaction.type == "debit",- Transaction.transfer_pair_id.is_(None),- Transaction.source != "opening_balance",- Transaction.id.not_in(candidate_ids),- )- reverse_result = await session.execute(reverse_debit_query)- reverse_debits = list(reverse_result.scalars().all())- else:- reverse_debits = []+ ignored = set(scope.get("ignore_transaction_sources", []))+ pool = await _pool(+ session, workspace_id, ignored, scope.get("exclude_legs", []), accounts+ )+ if len(pool) < 2:+ return 0- all_debits = debits + reverse_debits+ window = _widest_window(policy)+ ratio = _widest_amount_ratio(policy)+ by_date: dict[Any, list[Transaction]] = defaultdict(list)+ for tx in pool:+ by_date[tx.date].append(tx)- if not all_debits:- return 0+ def neighbours(tx: Transaction) -> list[Transaction]:+ """Rows close enough in time and size to be worth asking about."""+ found: list[Transaction] = []+ for offset in range(-window, window + 1):+ for other in by_date.get(tx.date + timedelta(days=offset), ()):+ if other.id == tx.id or other.account_id == tx.account_id:+ continue+ if other.type != _OPPOSITE.get(tx.type):+ continue+ if ratio is not None:+ moved = abs(Decimal(tx.amount))+ theirs = abs(Decimal(other.amount))+ if abs(moved - theirs) > (theirs * ratio):+ continue+ found.append(other)+ return found- # Load all unpaired credits for the user (potential partners)- credit_query = select(Transaction).where(- Transaction.workspace_id == workspace_id,- Transaction.type == "credit",- Transaction.transfer_pair_id.is_(None),- Transaction.source != "opening_balance",- )- credit_result = await session.execute(credit_query)- credits = list(credit_result.scalars().all())+ # **An empty list is not the same as no list.** `None` means "look at+ # everything"; `[]` means "a sync just ran and brought nothing new",+ # which is the one case where there is certainly nothing to do.+ # Collapsing the two sent a quiet sync off to reconsider the whole+ # workspace and pair two rows that had both been sitting there for+ # months, which is exactly what restricting to new rows prevents.+ new_ids = None if candidate_ids is None else set(candidate_ids)- if not credits:- return 0+ # Which rows to ask about. Everything when this is a full run;+ # otherwise the new rows plus whatever could contest them, because a+ # claim you never asked about is a claim you cannot weigh.+ if new_ids is None:+ examined = pool+ else:+ relevant: dict[uuid.UUID, Transaction] = {}+ for tx in pool:+ if tx.id in new_ids:+ relevant[tx.id] = tx+ for other in neighbours(tx):+ relevant.setdefault(other.id, other)+ examined = list(relevant.values())- # When candidate_ids is given, restrict reverse debits to only match- # credits that are in candidate_ids (avoid pairing two old transactions).- candidate_id_set = set(candidate_ids) if candidate_ids else None+ decisions: dict[uuid.UUID, tuple[Decision, Movement, Transaction]] = {}+ for tx in examined:+ candidates = [+ _as_expectation(other, accounts.get(other.account_id))+ for other in neighbours(tx)+ ]+ if not candidates:+ continue+ movement = _as_movement(tx, accounts.get(tx.account_id))+ decision = evaluate(movement, candidates, policy, trigger="money_arrives")+ if decision.port == "unmatched" or decision.expectation is None:+ continue+ decisions[tx.id] = (decision, movement, tx)- # Build a lookup: amount -> list of credits- credit_by_amount: dict[float, list[Transaction]] = defaultdict(list)- for c in credits:- credit_by_amount[abs(float(c.amount))].append(c)+ def involves_new(a: uuid.UUID, b: uuid.UUID) -> bool:+ return new_ids is None or a in new_ids or b in new_ids- paired_credit_ids: set[uuid.UUID] = set()- paired_debit_ids: set[uuid.UUID] = set()+ # Pass one: the pairs both sides agree on.+ paired: set[uuid.UUID] = set()pairs_created = 0+ for tx_id, (decision, _movement, tx) in decisions.items():+ expectation = decision.expectation+ if decision.port != "linked" or tx_id in paired or expectation is None:+ continue+ other_id = expectation.id+ if other_id in paired or not involves_new(tx_id, other_id):+ continue+ mirror = decisions.get(other_id)+ if mirror is None:+ continue+ other_decision, _m, other_tx = mirror+ if other_decision.port != "linked" or other_decision.expectation is None:+ continue+ if other_decision.expectation.id != tx_id:+ # Each side named somebody else. Neither is wrong on its own+ # terms; together they are two claims on one row, and the+ # queue is where that gets settled.+ continue- for debit in all_debits:- debit_amount = abs(float(debit.amount))- amount_candidates = credit_by_amount.get(debit_amount, [])-- is_reverse_debit = candidate_id_set is not None and debit.id not in candidate_id_set-- # Find closest-date match in a different account- best_match: Optional[Transaction] = None- best_delta: Optional[int] = None-- for credit in amount_candidates:- if credit.id in paired_credit_ids:- continue- if credit.account_id == debit.account_id:- continue- # Reverse debits may only match credits from candidate_ids- if is_reverse_debit and candidate_id_set and credit.id not in candidate_id_set:- continue-- delta = abs((credit.date - debit.date).days)- if delta > date_tolerance_days:- continue-- if best_delta is None or delta < best_delta:- best_match = credit- best_delta = delta-- if best_match:- pair_id = uuid.uuid4()- debit.transfer_pair_id = pair_id- best_match.transfer_pair_id = pair_id- paired_credit_ids.add(best_match.id)- paired_debit_ids.add(debit.id)- pairs_created += 1+ pair_id = uuid.uuid4()+ tx.transfer_pair_id = pair_id+ other_tx.transfer_pair_id = pair_id+ paired.update({tx_id, other_id})+ pairs_created += 1++ # Pass two: everything that looked like a transfer and was not certain.+ # Keyed on the unordered pair, because the same two rows reach here+ # from both ends and a person should be asked once.+ asked: set[frozenset[uuid.UUID]] = set()+ for tx_id, (decision, movement, _tx) in decisions.items():+ expectation = decision.expectation+ if tx_id in paired or expectation is None:+ continue+ other_id = expectation.id+ if other_id in paired or not involves_new(tx_id, other_id):+ continue+ key = frozenset({tx_id, other_id})+ if key in asked:+ continue+ asked.add(key)++ if decision.port == "linked":+ # Wanted to link and could not: the other leg named somebody+ # else, or never answered. Asking is what is left, and it is+ # the truthful version of what the old code did silently.+ decision.port = "suggested"+ await suggestions.record(+ session, workspace_id, tx_id, decision, movement, NODE+ )return pairs_createddiff --git a/backend/tests/test_reconciliation_rules.py b/backend/tests/test_reconciliation_rules.pyindex 8feeb13a..49fc672b 100644--- a/backend/tests/test_reconciliation_rules.py+++ b/backend/tests/test_reconciliation_rules.py@@ -28,6 +28,7 @@ from app.services import (TODAY = date.today()INVOICE_NODE = reconciliation_policy.MATCH_INVOICE["node"]RECURRING_NODE = reconciliation_policy.MATCH_RECURRING["node"]+TRANSFER_NODE = reconciliation_policy.MATCH_TRANSFER["node"]@pytest_asyncio.fixture@@ -157,7 +158,8 @@ async def test_the_shipped_rules_are_visible_without_anyone_creating_them(assert resp.status_code == 200, resp.textnodes = resp.json()- assert {n["node"] for n in nodes} == {INVOICE_NODE, RECURRING_NODE}+ # Transfer pairing belongs to no module, so it is in every listing.+ assert {n["node"] for n in nodes} == {TRANSFER_NODE, INVOICE_NODE, RECURRING_NODE}exact = find(nodes, INVOICE_NODE, "same_client_exact")assert exact["enabled"] is Trueassert exact["outcome"] == "link"@@ -180,7 +182,7 @@ async def test_a_personal_workspace_gets_its_own_set_and_not_the_other(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}+ assert {n["node"] for n in listing.json()} == {TRANSFER_NODE, RECURRING_NODE}resp = await client.patch(f"/api/reconciliation/rules/{RECURRING_NODE}/same_account_exact",@@ -239,7 +241,7 @@ async def test_a_file_carrying_a_set_this_workspace_lacks_is_skipped(listing = (await client.get("/api/reconciliation/rules", headers=personal)).json()- assert {n["node"] for n in listing} == {RECURRING_NODE}+ assert {n["node"] for n in listing} == {TRANSFER_NODE, RECURRING_NODE}@pytest.mark.asynciodiff --git a/backend/tests/test_transfer_detection.py b/backend/tests/test_transfer_detection.pyindex 72d8564e..7ae8d560 100644--- a/backend/tests/test_transfer_detection.py+++ b/backend/tests/test_transfer_detection.py@@ -125,7 +125,13 @@ async def test_detect_no_credits(session: AsyncSession, test_user, test_workspac@pytest.mark.asyncioasync def test_detect_respects_date_tolerance(session: AsyncSession, test_user, test_workspace):- """Only pairs transactions within date_tolerance_days."""+ """Only pairs transactions inside the window the rules ask for.++ The window used to be an argument to this function and is now a+ condition on a rule somebody can read and change. Two days is what+ ships, and what this asserts, because the point of moving it was to+ keep the behaviour and expose the number.+ """acc1 = await _make_account(session, test_user.id, "Tol A")acc2 = await _make_account(session, test_user.id, "Tol B")today = date.today()@@ -134,7 +140,7 @@ async def test_detect_respects_date_tolerance(session: AsyncSession, test_user,# Credit too far away (5 days)await _add_txn(session, test_user.id, acc2.id, 300, "credit", today + timedelta(days=5))- pairs = await detect_transfer_pairs(session, test_workspace.id, date_tolerance_days=2)+ pairs = await detect_transfer_pairs(session, test_workspace.id)assert pairs == 0@@ -148,7 +154,7 @@ async def test_detect_within_tolerance(session: AsyncSession, test_user, test_wodebit = await _add_txn(session, test_user.id, acc1.id, 400, "debit", today)credit = await _add_txn(session, test_user.id, acc2.id, 400, "credit", today + timedelta(days=1))- pairs = await detect_transfer_pairs(session, test_workspace.id, date_tolerance_days=2)+ pairs = await detect_transfer_pairs(session, test_workspace.id)await session.commit()assert pairs == 1diff --git a/backend/tests/test_transfer_matching_rules.py b/backend/tests/test_transfer_matching_rules.pynew file mode 100644index 00000000..456d1cf7--- /dev/null+++ b/backend/tests/test_transfer_matching_rules.py@@ -0,0 +1,591 @@+"""Transfer pairing, now that its rules are a document somebody can read.++Every test here is a report from the issue tracker or a promise the+feature makes about itself. The claim under all of them: **what the old+detector did silently, this does visibly, and the cases it got wrong it+now declines to guess at.**+"""+import uuid+from datetime import date, datetime, timedelta, timezone+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.reconciliation import ReconciliationSuggestion+from app.models.transaction import Transaction+from app.services import reconciliation_policy+from app.services import reconciliation_rule_service as rule_service+from app.services.text_similarity import names_account+from app.services.transfer_detection_service import detect_transfer_pairs++TODAY = date.today()+NODE = reconciliation_policy.MATCH_TRANSFER["node"]+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+async def _account(+ session: AsyncSession, user_id, workspace_id, name: str, kind: str = "checking"+) -> Account:+ account = Account(+ id=uuid.uuid4(),+ user_id=user_id,+ workspace_id=workspace_id,+ name=name,+ type=kind,+ currency="EUR",+ balance=Decimal("0"),+ )+ session.add(account)+ await session.commit()+ return account+++async def _txn(+ session: AsyncSession,+ user_id,+ workspace_id,+ account: Account,+ *,+ amount: str,+ kind: str,+ when: date,+ description: str = "Movement",+) -> Transaction:+ txn = Transaction(+ id=uuid.uuid4(),+ user_id=user_id,+ workspace_id=workspace_id,+ account_id=account.id,+ description=description,+ amount=Decimal(amount),+ currency="EUR",+ date=when,+ effective_date=when,+ type=kind,+ source="sync",+ created_at=datetime.now(timezone.utc),+ )+ session.add(txn)+ await session.commit()+ return txn+++async def _pending(session: AsyncSession, workspace_id) -> list[ReconciliationSuggestion]:+ result = await session.execute(+ select(ReconciliationSuggestion).where(+ ReconciliationSuggestion.workspace_id == workspace_id,+ ReconciliationSuggestion.status == "pending",+ )+ )+ return list(result.scalars().all())+++@pytest_asyncio.fixture+async def ws(test_workspace):+ return test_workspace+++# ---------------------------------------------------------------------------+# The signal the old detector never had+# ---------------------------------------------------------------------------+def test_an_account_name_is_found_however_the_bank_printed_it():+ assert names_account("To FORTUNEO ACCOUNT 1234", "Fortuneo")+ assert names_account("NUBANK*IFOOD", "Nubank")+ # Accents come off both sides: the same bank prints it both ways.+ assert names_account("TED ITAU UNIBANCO", "Itaú")+++def test_a_generic_account_name_names_nothing():+ """Otherwise "Conta Corrente" matches most of a Brazilian statement,+ and the signal is worse than not having it."""+ assert not names_account("PIX ENVIADO CONTA CORRENTE", "Conta Corrente")+ assert not names_account("To FORTUNEO ACCOUNT", "Trade Republic")+++# ---------------------------------------------------------------------------+# #973: the wrong counterpart+# ---------------------------------------------------------------------------+async def _same_day_pair(session: AsyncSession, test_user, ws):+ """The reported shape: two transfers of one amount on one day.++ One names where it went, the other names somewhere else, and the+ incoming leg lands two days later.+ """+ bnp = await _account(session, test_user.id, ws.id, "BNP checking")+ fortuneo = await _account(session, test_user.id, ws.id, "Fortuneo")+ await _account(session, test_user.id, ws.id, "Trade Republic")++ to_tr = await _txn(+ session, test_user.id, ws.id, bnp,+ amount="100.00", kind="debit", when=TODAY,+ description="To Trade Republic 0987",+ )+ to_fortuneo = await _txn(+ session, test_user.id, ws.id, bnp,+ amount="100.00", kind="debit", when=TODAY,+ description="To FORTUNEO ACCOUNT 1234",+ )+ arrival = await _txn(+ session, test_user.id, ws.id, fortuneo,+ amount="100.00", kind="credit", when=TODAY + timedelta(days=2),+ description="Transfer from BNP",+ )+ return to_tr, to_fortuneo, arrival+++async def test_by_default_the_same_day_pair_is_asked_about_not_guessed(+ session: AsyncSession, test_user, ws+):+ """What ships: nothing is linked, and the question is raised.++ The old detector paired the incoming leg with whichever debit the+ database returned first and left the other alone. Reading the+ descriptions would resolve it, but that is a guess about what a bank+ chose to print, so it is not what a default does. Refusing to guess+ is, and it is already the whole of the reported harm undone.+ """+ to_tr, to_fortuneo, arrival = await _same_day_pair(session, test_user, ws)++ assert await detect_transfer_pairs(session, ws.id) == 0+ await session.commit()+ for row in (to_tr, to_fortuneo, arrival):+ await session.refresh(row)+ assert row.transfer_pair_id is None++ assert await _pending(session, ws.id) != []+++async def test_turning_the_description_rule_on_resolves_the_same_day_pair(+ session: AsyncSession, test_user, ws+):+ """And what one click buys.++ `To FORTUNEO ACCOUNT` names the account the money landed in; the+ other line names somewhere else. That separates them, and the pair+ both sides agree on gets linked.+ """+ await rule_service.upsert_override(+ session, ws.id, test_user.id, NODE,+ "destination_named_in_description", {"enabled": True},+ )+ await session.commit()++ to_tr, to_fortuneo, arrival = await _same_day_pair(session, test_user, ws)++ assert await detect_transfer_pairs(session, ws.id) == 1+ await session.commit()+ for row in (to_tr, to_fortuneo, arrival):+ await session.refresh(row)++ assert to_fortuneo.transfer_pair_id is not None+ assert to_fortuneo.transfer_pair_id == arrival.transfer_pair_id+ assert to_tr.transfer_pair_id is None+++async def test_two_indistinguishable_legs_are_asked_about_rather_than_guessed(+ session: AsyncSession, test_user, ws+):+ """When nothing separates them, the answer is a question.++ This is the case the old code decided by row order, and the one the+ reporter asked us to leave alone: *"if the code has no way to tell+ the two debits apart, it is left unpaired for the user to resolve."*+ It is better than unpaired, because the queue says so.+ """+ source = await _account(session, test_user.id, ws.id, "Source")+ target = await _account(session, test_user.id, ws.id, "Target")++ first = await _txn(+ session, test_user.id, ws.id, source,+ amount="100.00", kind="debit", when=TODAY, description="VIREMENT 8832",+ )+ second = await _txn(+ session, test_user.id, ws.id, source,+ amount="100.00", kind="debit", when=TODAY, description="VIREMENT 8833",+ )+ await _txn(+ session, test_user.id, ws.id, target,+ amount="100.00", kind="credit", when=TODAY, description="RECU VIREMENT",+ )++ assert await detect_transfer_pairs(session, ws.id) == 0+ await session.commit()+ await session.refresh(first)+ await session.refresh(second)+ assert first.transfer_pair_id is None+ assert second.transfer_pair_id is None++ queue = await _pending(session, ws.id)+ assert len(queue) >= 1+ assert all(row.expectation_kind == "transaction" for row in queue)+ assert all(row.node == NODE for row in queue)+++# ---------------------------------------------------------------------------+# #648: the reimbursement that looked like a transfer+# ---------------------------------------------------------------------------+async def test_a_card_purchase_is_not_a_transfer_and_is_not_even_asked_about(+ session: AsyncSession, test_user, ws+):+ """A bar tab and an unrelated reimbursement of the same value.++ The old code linked them, and the purchase silently left the card's+ bill while the money left income. Offering the pair for confirmation+ instead would still be wrong: that money went to the bar, so there is+ no second leg anywhere, and a question whose answer is always no is+ how a queue stops being read.+ """+ card = await _account(session, test_user.id, ws.id, "Card", kind="credit_card")+ checking = await _account(session, test_user.id, ws.id, "Checking")++ purchase = await _txn(+ session, test_user.id, ws.id, card,+ amount="374.66", kind="debit", when=TODAY, description="BAR DO ZE",+ )+ refund = await _txn(+ session, test_user.id, ws.id, checking,+ amount="374.66", kind="credit", when=TODAY + timedelta(days=1),+ description="PIX RECEBIDO",+ )++ assert await detect_transfer_pairs(session, ws.id) == 0+ await session.commit()+ await session.refresh(purchase)+ await session.refresh(refund)+ assert purchase.transfer_pair_id is None+ assert refund.transfer_pair_id is None++ # Not linked, and not queued either. Nothing happened, which is the+ # correct amount of things to happen.+ assert await _pending(session, ws.id) == []+++async def test_paying_the_card_bill_is_a_transfer_and_still_links(+ session: AsyncSession, test_user, ws+):+ """The direction that is real, and the reason the exclusion is not+ "anything touching a card".++ Money leaves the current account and lands **on** the card, reducing+ what is owed. Both ends are things you own, so it is a transfer in+ the plainest sense and people have always wanted it paired.+ """+ card = await _account(session, test_user.id, ws.id, "Card", kind="credit_card")+ checking = await _account(session, test_user.id, ws.id, "Checking")++ paid = await _txn(+ session, test_user.id, ws.id, checking,+ amount="1240.00", kind="debit", when=TODAY, description="PAGAMENTO FATURA",+ )+ received = await _txn(+ session, test_user.id, ws.id, card,+ amount="1240.00", kind="credit", when=TODAY + timedelta(days=1),+ description="PAGAMENTO RECEBIDO",+ )++ assert await detect_transfer_pairs(session, ws.id) == 1+ await session.commit()+ await session.refresh(paid)+ await session.refresh(received)+ assert paid.transfer_pair_id is not None+ assert paid.transfer_pair_id == received.transfer_pair_id+++# ---------------------------------------------------------------------------+# Turning it off, which was never possible before+# ---------------------------------------------------------------------------+async def test_a_workspace_can_switch_transfer_pairing_off_entirely(+ session: AsyncSession, test_user, ws+):+ """No rules, no pairing and no queue: a supported answer, not a+ workaround."""+ for strategy in reconciliation_policy.MATCH_TRANSFER["strategies"]:+ await rule_service.upsert_override(+ session, ws.id, test_user.id, NODE, strategy["id"], {"enabled": False}+ )+ await session.commit()++ source = await _account(session, test_user.id, ws.id, "Off A")+ target = await _account(session, test_user.id, ws.id, "Off B")+ debit = await _txn(+ session, test_user.id, ws.id, source,+ amount="50.00", kind="debit", when=TODAY,+ )+ await _txn(+ session, test_user.id, ws.id, target,+ amount="50.00", kind="credit", when=TODAY,+ )++ assert await detect_transfer_pairs(session, ws.id) == 0+ await session.commit()+ await session.refresh(debit)+ assert debit.transfer_pair_id is None+ assert await _pending(session, ws.id) == []+++# ---------------------------------------------------------------------------+# The one guardrail+# ---------------------------------------------------------------------------+def test_an_approximate_rule_may_not_link_without_a_single_candidate():+ """The damage is silent: both rows leave income and expense, the+ totals move, and nothing says a guess was made."""+ with pytest.raises(rule_service.RuleError) as raised:+ rule_service.validate_config(+ {+ "outcome": "link",+ "when": {+ "different_account": True,+ "amount": {"match": "tolerance", "percent": "5"},+ },+ },+ whole=True,+ )+ assert raised.value.code == "unsafe_link"+++def test_the_same_rule_is_allowed_once_it_insists_on_one_candidate():+ clean = rule_service.validate_config(+ {+ "outcome": "link",+ "when": {+ "different_account": True,+ "amount": {"match": "tolerance", "percent": "5"},+ "unique_candidate": True,+ },+ },+ whole=True,+ )+ assert clean["when"]["unique_candidate"] is True+++# ---------------------------------------------------------------------------+# The page, for a workspace that has no modules at all+# ---------------------------------------------------------------------------+async def test_a_personal_workspace_sees_and_can_change_the_transfer_rules(+ client: AsyncClient, auth_headers+):+ """The reason the router stopped asking for a module. Transfer+ pairing runs for this workspace and always has, so hiding its rules+ hid an automation from the person whose data it edits."""+ listing = await client.get("/api/reconciliation/rules", headers=auth_headers)+ assert listing.status_code == 200, listing.text++ nodes = {group["node"]: group for group in listing.json()}+ assert NODE in nodes+ shipped = {rule["id"] for rule in nodes[NODE]["rules"]}+ assert "exact_amount_nearby" in shipped+ # The invoice set stays behind its module.+ assert reconciliation_policy.MATCH_INVOICE["node"] not in nodes++ resp = await client.patch(+ f"/api/reconciliation/rules/{NODE}/exact_amount_nearby",+ headers=auth_headers,+ json={"enabled": False},+ )+ assert resp.status_code == 200, resp.text+ assert resp.json()["enabled"] is False+++async def test_the_wider_window_rule_ships_visible_and_switched_off(+ client: AsyncClient, auth_headers+):+ """Somebody who moves money between countries turns it on knowing+ what they are buying; everybody else is not asked to pay for it."""+ listing = await client.get("/api/reconciliation/rules", headers=auth_headers)+ rules_by_id = {+ rule["id"]: rule+ for group in listing.json()+ if group["node"] == NODE+ for rule in group["rules"]+ }+ assert rules_by_id["close_amount_wider_window"]["enabled"] is False+ assert rules_by_id["close_amount_wider_window"]["outcome"] == "suggest"+++async def test_exporting_from_one_card_carries_only_that_card(+ client: AsyncClient, auth_headers+):+ """Each set is its own card with its own button.++ A button sitting under *Transfer rules* that quietly hands over the+ invoice rules as well is a button that lies, and the file is the+ thing people pass to each other.+ """+ whole = await client.get("/api/reconciliation/rules/export", headers=auth_headers)+ assert whole.status_code == 200, whole.text+ assert NODE in {n["node"] for n in whole.json()["nodes"]}++ scoped = await client.get(+ "/api/reconciliation/rules/export",+ headers=auth_headers,+ params={"node": NODE},+ )+ assert scoped.status_code == 200, scoped.text+ assert {n["node"] for n in scoped.json()["nodes"]} == {NODE}+++async def test_importing_on_one_card_cannot_rewrite_another_set(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user+):+ """The scope is the card, not the file.++ Otherwise a file carrying every set, dropped on the transfers card,+ silently replaces rules the reader was not looking at.+ """+ file = (+ await client.get("/api/reconciliation/rules/export", headers=auth_headers)+ ).json()+ for node in file["nodes"]:+ for rule in node["rules"]:+ rule["enabled"] = False++ resp = await client.post(+ "/api/reconciliation/rules/import",+ headers=auth_headers,+ params={"node": NODE},+ json={"payload": file, "overwrite": True},+ )+ assert resp.status_code == 200, resp.text++ listing = (+ await client.get("/api/reconciliation/rules", headers=auth_headers)+ ).json()+ by_node = {group["node"]: group for group in listing}+ assert all(not rule["enabled"] for rule in by_node[NODE]["rules"])++ other = reconciliation_policy.MATCH_RECURRING["node"]+ if other in by_node:+ # Untouched: the file asked, the scope refused.+ assert any(rule["enabled"] for rule in by_node[other]["rules"])+++def test_what_ships_enabled_is_the_old_behaviour_and_nothing_else():+ """The rule that decides what may be a default.++ A default is not a suggestion: it is what happens to people who never+ open the page. So the enabled set has to be defensible without+ knowing anything about the reader's bank or country, which leaves+ exactly what already ran plus the definition of a transfer. Every+ heuristic beyond that ships visible and off.++ Written as a test rather than a comment because the pressure is+ always toward switching a good idea on, and the cost of that lands+ on people who never asked.+ """+ node = reconciliation_policy.MATCH_TRANSFER+ on = [s for s in node["strategies"] if s.get("enabled", True)]++ assert [s["id"] for s in on] == ["exact_amount_nearby"]++ when = on[0]["when"]+ assert on[0]["outcome"] == "link"+ assert when["different_account"] is True+ assert when["amount"] == {"match": "exact"}+ # The window the old detector used, to the day.+ assert when["date"] == {"before_days": 2, "after_days": 2}+ # Nearest first, as it always did; a question when nothing separates+ # them, which it never did.+ assert when["tie_break"] == "closest_date"+ assert when["unique_candidate"] is True++ # No enabled rule reads text or accepts an approximate amount. Those+ # are opinions about statements, and they wait to be asked for.+ for strategy in on:+ assert "account_name_in_description" not in strategy["when"]+ assert "description_similarity" not in strategy["when"]+ assert strategy["when"].get("amount", {}).get("match", "exact") == "exact"+++async def test_a_sync_that_brought_nothing_new_pairs_nothing(+ session: AsyncSession, test_user, ws+):+ """`[]` is not `None`.++ One means "a sync just ran and found nothing", the other means "look+ at everything". Collapsing them sent a quiet sync off to reconsider+ the whole workspace and pair two rows that had both been sitting+ there for months.+ """+ source = await _account(session, test_user.id, ws.id, "Old A")+ target = await _account(session, test_user.id, ws.id, "Old B")+ debit = await _txn(+ session, test_user.id, ws.id, source,+ amount="75.00", kind="debit", when=TODAY,+ )+ credit = await _txn(+ session, test_user.id, ws.id, target,+ amount="75.00", kind="credit", when=TODAY,+ )++ assert await detect_transfer_pairs(session, ws.id, candidate_ids=[]) == 0+ await session.commit()+ for row in (debit, credit):+ await session.refresh(row)+ assert row.transfer_pair_id is None++ # And with no list at all it is a full run, which does pair them.+ assert await detect_transfer_pairs(session, ws.id) == 1+++async def test_accepting_a_question_about_rows_that_changed_is_refused(+ client: AsyncClient, auth_headers, session: AsyncSession, test_user, test_workspace+):+ """A transaction stays editable while its suggestion waits.++ Accepting anyway would bind two rows on the strength of an answer to+ a different question, and a paired row leaves income and expense, so+ the damage is a total quietly changing.+ """+ ws = test_workspace+ source = await _account(session, test_user.id, ws.id, "Stale A")+ target = await _account(session, test_user.id, ws.id, "Stale B")+ await _txn(+ session, test_user.id, ws.id, source,+ amount="300.00", kind="debit", when=TODAY, description="VIREMENT 1",+ )+ await _txn(+ session, test_user.id, ws.id, source,+ amount="300.00", kind="debit", when=TODAY, description="VIREMENT 2",+ )+ arriving = await _txn(+ session, test_user.id, ws.id, target,+ amount="300.00", kind="credit", when=TODAY, description="RECU",+ )++ # Ambiguous, so it becomes a question rather than a link.+ assert await detect_transfer_pairs(session, ws.id) == 0+ await session.commit()+ queue = await _pending(session, ws.id)+ assert queue, "expected the ambiguous pair to be queued"++ # Somebody corrects the amount before answering.+ arriving.amount = Decimal("999.00")+ await session.commit()++ resp = await client.post(+ f"/api/reconciliation/suggestions/{queue[0].id}/accept", headers=auth_headers+ )+ assert resp.status_code == 400, resp.text+ assert resp.json()["detail"]["code"] == "suggestion_stale"++ await session.refresh(arriving)+ assert arriving.transfer_pair_id is Nonediff --git a/frontend/src/components/reconciliation-pair.tsx b/frontend/src/components/reconciliation-pair.tsxindex 5624ae73..d2f59bd6 100644--- a/frontend/src/components/reconciliation-pair.tsx+++ b/frontend/src/components/reconciliation-pair.tsx@@ -30,7 +30,11 @@ import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { cn } from '@/lib/utils'export interface PairSide {- kind: 'invoice' | 'recurring'+ /** `transaction` is the other leg of a transfer. It is not a promise+ * anybody wrote down, which is why it reads differently below: there+ * is nothing outstanding to subtract from, only two records asking+ * whether they are the same money. */+ kind: 'invoice' | 'recurring' | 'transaction'id: stringlabel?: string | null/** What this movement puts, or would put, against this promise. */@@ -98,6 +102,31 @@ function PromiseLine({}) {const { t } = useTranslation()const { data: invoice } = useInvoice(side.id, open && side.kind === 'invoice')+ const { data: leg } = useQuery<Transaction>({+ queryKey: ['transaction', side.id],+ queryFn: () => transactionsApi.get(side.id),+ enabled: open && side.kind === 'transaction',+ })++ if (side.kind === 'transaction') {+ // The account, then what it did and when. Never the description: on+ // the leg that matters it is a reference number, and the question+ // being asked is about two accounts.+ return (+ <div className="space-y-0.5">+ <p className="text-sm font-medium text-foreground truncate">+ {side.label ?? t('reconciliation.pair.otherLeg')}+ </p>+ <Facts+ items={[+ leg && showDate(leg.date),+ leg && money(leg.amount, leg.currency),+ leg?.description,+ ]}+ />+ </div>+ )+ }if (side.kind !== 'invoice') {return (@@ -190,6 +219,11 @@ export function ReconciliationPair({const outstanding = Number(firstInvoice?.balance ?? 0)const remaining = outstanding - appliedconst singleInvoice = sides.length === 1 && first?.kind === 'invoice'+ // A transfer has no balance to subtract from, so the three-figure+ // arithmetic above would be answering a question nobody asked. What+ // matters is the two amounts side by side, because when they differ+ // the difference is the whole reason this is a question.+ const isTransfer = first?.kind === 'transaction'return (<div className="mt-3 pt-3 border-t border-border">@@ -225,6 +259,21 @@ export function ReconciliationPair({/>)}</>+ ) : isTransfer ? (+ <>+ <Figure+ value={money(applied)}+ caption={t('reconciliation.pair.otherLegAmount')}+ tone="quiet"+ />+ {transaction && (+ <Figure+ value={money(transaction.amount, transaction.currency)}+ caption={t('reconciliation.pair.thisLegAmount')}+ tone="applied"+ />+ )}+ </>) : (<><Figure@@ -250,7 +299,7 @@ export function ReconciliationPair({<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')}+ {t(isTransfer ? 'reconciliation.pair.otherLeg' : 'reconciliation.pair.owed')}</p>{sides.map((side) => (<PromiseLine@@ -265,22 +314,35 @@ export function ReconciliationPair({<div className="space-y-2 sm:pl-5"><p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider">- {t('reconciliation.pair.arrived')}+ {t(isTransfer ? 'reconciliation.pair.thisLeg' : 'reconciliation.pair.arrived')}</p>{transaction ? (<div className="space-y-0.5">+ {/* For a transfer both columns lead with the account, so the+ two sides read as one comparison. Leading with the+ description on this side and the account on the other+ asked the reader to hold two different shapes in their+ head and work out which field to compare with which. */}<p className="text-sm font-medium text-foreground truncate">- {transaction.description}+ {isTransfer ? (accountName ?? transaction.description) : 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,- ]}+ items={+ isTransfer+ ? [+ showDate(transaction.date),+ money(transaction.amount, transaction.currency),+ transaction.description,+ ]+ : [+ 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>) : (diff --git a/frontend/src/components/reconciliation-queue.tsx b/frontend/src/components/reconciliation-queue.tsxindex 543f94f3..d38622ac 100644--- a/frontend/src/components/reconciliation-queue.tsx+++ b/frontend/src/components/reconciliation-queue.tsx@@ -16,17 +16,18 @@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 { reconciliation as reconciliationApi, accounts as accountsApi } 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 type { Account, 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'+import { cn } from '@/lib/utils'function SectionCard({ children }: { children: React.ReactNode }) {return (@@ -36,11 +37,42 @@ function SectionCard({ children }: { children: React.ReactNode }) {)}+/** What kind of question this row is.+ *+ * The queue holds several kinds at once, and until you know which one+ * you are looking at, the sentence underneath does not parse: *may be+ * the other half of Nu* and *may settle invoice 41* are different acts+ * with different consequences. Colour and word together, because colour+ * alone is not a label anybody can read out loud. */+function KindBadge({ kind }: { kind: ReconciliationSuggestion['expectation_kind'] }) {+ const { t } = useTranslation()+ const tone =+ kind === 'transaction'+ ? 'bg-sky-50 text-sky-700 dark:bg-sky-950 dark:text-sky-300'+ : kind === 'invoice'+ ? 'bg-violet-50 text-violet-700 dark:bg-violet-950 dark:text-violet-300'+ : 'bg-teal-50 text-teal-700 dark:bg-teal-950 dark:text-teal-300'+ return (+ <span+ className={cn(+ 'shrink-0 text-[10px] font-semibold px-1.5 py-0.5 rounded-full',+ tone,+ )}+ >+ {t(`reconciliation.queue.kind.${kind}`)}+ </span>+ )+}+/** The evidence, as short claims a reader can agree or disagree with. */function Evidence({ suggestion }: { suggestion: ReconciliationSuggestion }) {const { t } = useTranslation()const { scores } = suggestionconst claims: { label: string; good: boolean }[] = []+ // Both legs of a transfer are the reader's own accounts, so there is no+ // payer to recognise and the chip would say *payer not identified* on+ // every transfer row, forever, meaning nothing.+ const payerMatters = suggestion.expectation_kind !== 'transaction'if (scores.amount_exact !== undefined) {claims.push({@@ -53,7 +85,7 @@ function Evidence({ suggestion }: { suggestion: ReconciliationSuggestion }) {good: !!scores.amount_exact,})}- if (scores.same_counterparty !== undefined) {+ if (payerMatters && scores.same_counterparty !== undefined) {claims.push({label: scores.same_counterparty? t('reconciliation.evidence.knownPayer')@@ -66,7 +98,7 @@ function Evidence({ suggestion }: { suggestion: ReconciliationSuggestion }) {label:scores.days_apart === 0? t('reconciliation.evidence.sameDay')- : t('reconciliation.evidence.daysApart', { days: Math.abs(scores.days_apart) }),+ : t('reconciliation.evidence.daysApart', { count: Math.abs(scores.days_apart) }),good: Math.abs(scores.days_apart) <= 3,})}@@ -100,6 +132,14 @@ export function ReconciliationQueue({ canWrite }: { canWrite: boolean }) {queryKey: ['reconciliation-suggestions'],queryFn: reconciliationApi.suggestions,})+ // The same cached query the expanded row already uses, so naming the+ // account on every row costs nothing extra.+ const { data: accounts = [] } = useQuery<Account[]>({+ queryKey: ['accounts'],+ queryFn: () => accountsApi.list(),+ })+ const accountName = (id: string | null | undefined) =>+ id ? accounts.find((account) => account.id === id)?.name : undefined// Deciding is a comparison, and the evidence chips describe an invoice// without ever showing it. Expanding the row puts both halves on screen@@ -149,19 +189,41 @@ export function ReconciliationQueue({ canWrite }: { canWrite: boolean }) {><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 className="text-sm font-medium text-foreground flex items-center gap-2">+ <span className="truncate">+ {suggestion.transaction?.description ??+ t('reconciliation.queue.aPayment')}+ </span>+ <KindBadge kind={suggestion.expectation_kind} /></p><p className="text-xs text-muted-foreground mt-0.5">{suggestion.transaction?.date? showDate(suggestion.transaction.date): ''}+ {/* Which of the reader's accounts this row sits on.+ The sentence that follows names the other side,+ and without this one the reader has to open the+ row to find out where they are standing. */}+ {accountName(suggestion.transaction?.account_id) && (+ <>+ {' · '}+ <span className="font-medium text-foreground">+ {accountName(suggestion.transaction?.account_id)}+ </span>+ </>+ )}{' · '}{t(suggestion.expectation_kind === 'invoice'? 'reconciliation.queue.maySettle'- : 'reconciliation.queue.mayBe',+ : suggestion.expectation_kind === 'transaction'+ // "may settle" and "may be" both read as one+ // record explaining another. Two legs of a+ // transfer are neither: they are the same money+ // seen twice, and the row has to say so or the+ // reader answers a question we did not ask.+ ? 'reconciliation.queue.mayPairWith'+ : 'reconciliation.queue.mayBe',{// One payment can answer several promises, and the// question is the whole question, so the row namesdiff --git a/frontend/src/components/reconciliation-rules.tsx b/frontend/src/components/reconciliation-rules.tsxindex 5ce64c0c..9d7bd4fe 100644--- a/frontend/src/components/reconciliation-rules.tsx+++ b/frontend/src/components/reconciliation-rules.tsx@@ -41,6 +41,7 @@ import type {} from '@/types'import { Plus, RotateCcw, Trash2, Zap, HelpCircle, ChevronUp, ChevronDown, Power, Download, Upload } from 'lucide-react'import { cn } from '@/lib/utils'+import { ACCOUNT_TYPE_CONFIG } from '@/lib/account-type-config'import { DeleteConfirmationDialog } from '@/components/delete-confirmation-dialog'/** Names for the rules we ship. Kept here rather than sent by the API so@@ -54,6 +55,9 @@ const SHIPPED_NAME: Record<string, string> = {same_client_several_invoices: 'reconciliation.rule.severalInvoices',similar_description: 'reconciliation.rule.similarDescription',same_account_exact: 'reconciliation.rule.sameAccountExact',+ destination_named_in_description: 'reconciliation.rule.destinationNamed',+ exact_amount_nearby: 'reconciliation.rule.exactAmountNearby',+ close_amount_wider_window: 'reconciliation.rule.closeAmountWiderWindow',}/** What the file says it is. A categorization export dropped into the@@ -62,15 +66,33 @@ const SHIPPED_NAME: Record<string, string> = {const POLICY_FORMAT = 'securo-reconciliation-rules'const NODE_TITLE: Record<string, string> = {+ 'reconciliation.match_transfer': 'reconciliation.node.transfers','reconciliation.match_invoice': 'reconciliation.node.invoices','reconciliation.match_recurring': 'reconciliation.node.recurring',}const NODE_HINT: Record<string, string> = {+ 'reconciliation.match_transfer': 'reconciliation.node.transfersHint','reconciliation.match_invoice': 'reconciliation.node.invoicesHint','reconciliation.match_recurring': 'reconciliation.node.recurringHint',}+/** What each set is called when it is a card of its own, rather than a+ * strip inside one. A strip could lean on the heading above it for the+ * word *rules*; a card has to carry its own name, and it has to say+ * what it decides rather than which machinery decides it. */+const CARD_TITLE: Record<string, string> = {+ 'reconciliation.match_transfer': 'reconciliation.card.transfers',+ 'reconciliation.match_invoice': 'reconciliation.card.invoices',+ 'reconciliation.match_recurring': 'reconciliation.card.recurring',+}++const CARD_HINT: Record<string, string> = {+ 'reconciliation.match_transfer': 'reconciliation.card.transfersHint',+ 'reconciliation.match_invoice': 'reconciliation.card.invoicesHint',+ 'reconciliation.match_recurring': 'reconciliation.card.recurringHint',+}+/** The whole order with two entries exchanged.** Returns every id, not the pair that moved, because that is what the@@ -263,6 +285,17 @@ function conditionSummary(if (when.counterparty === 'same_payee') parts.push(t('reconciliation.cond.samePayee'))if (when.same_account) parts.push(t('reconciliation.cond.sameAccount'))+ if (when.different_account) parts.push(t('reconciliation.cond.differentAccount'))+ if (when.account_types?.length)+ parts.push(+ t('reconciliation.cond.accountTypes', {+ kinds: when.account_types+ .map((kind) => t(ACCOUNT_TYPE_CONFIG[kind]?.label ?? kind))+ .join(', '),+ }),+ )+ if (when.account_name_in_description)+ parts.push(t('reconciliation.cond.accountNamed'))if (when.amount?.match === 'exact') parts.push(t('reconciliation.cond.amountExact'))else if (when.amount?.match === 'tolerance')@@ -289,6 +322,12 @@ function conditionSummary(t('reconciliation.cond.similarity', { min: when.description_similarity.min }),)+ // Last, because both answer the same question and it is the one asked+ // after everything else has already fitted: several candidates got+ // this far, now what?+ if (when.tie_break === 'closest_date') parts.push(t('reconciliation.cond.closestDate'))+ if (when.unique_candidate) parts.push(t('reconciliation.cond.uniqueCandidate'))+return parts.join(' · ') || t('reconciliation.cond.none')}@@ -403,6 +442,28 @@ const EMPTY: ReconciliationConditions = {date: { before_days: 5, after_days: 30 },}+const TRANSFER_NODE = 'reconciliation.match_transfer'++/** What a brand new rule starts as, which is not the same in every set.+ *+ * A transfer is by definition money crossing between two accounts, so a+ * rule written here without `different_account` is not a loose transfer+ * rule: it is one that would pair a debit and a credit sitting on the+ * *same* account, which is never a transfer and is sometimes a+ * correction. The window starts at the two days the shipped rules use+ * rather than the month an invoice is allowed, because a transfer that+ * takes a month did not happen. */+function blankFor(node: string): ReconciliationConditions {+ if (node !== TRANSFER_NODE) return EMPTY+ return {+ different_account: true,+ amount: { match: 'exact' },+ date: { before_days: 2, after_days: 2 },+ tie_break: 'closest_date',+ unique_candidate: true,+ }+}+function RuleEditor({ open, node, rule, onClose }: EditorProps) {const { t } = useTranslation()const queryClient = useQueryClient()@@ -419,8 +480,13 @@ function RuleEditor({ open, node, rule, onClose }: EditorProps) {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)+ // A transfer rule runs at any moment, because both its legs are money+ // moving. Seeding a new one with 'both' keeps the field it cannot show+ // from sending a value that would quietly narrow it.+ const [trigger, setTrigger] = useState<Trigger>(+ rule?.trigger ?? (node === TRANSFER_NODE ? 'both' : 'money_arrives'),+ )+ const [when, setWhen] = useState<ReconciliationConditions>(rule?.when ?? blankFor(node))// 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.@@ -435,8 +501,8 @@ function RuleEditor({ open, node, rule, onClose }: EditorProps) {setSeeded(key)setName(rule?.name ?? '')setOutcome(rule?.outcome ?? 'suggest')- setTrigger(rule?.trigger ?? 'money_arrives')- setWhen(rule?.when ?? EMPTY)+ setTrigger(rule?.trigger ?? (node === TRANSFER_NODE ? 'both' : 'money_arrives'))+ setWhen(rule?.when ?? blankFor(node))}const save = useMutation({@@ -504,7 +570,14 @@ function RuleEditor({ open, node, rule, onClose }: EditorProps) {/>,)}- {field(+ {/* Not for transfers. The two moments are *money arrived* and+ *a document was written*, and a transfer has only the+ first: both its legs are money moving, and there is no+ document to look back from. Offering the choice would be+ offering a radio button whose second option can never be+ the right answer. */}+ {node !== TRANSFER_NODE &&+ field(t('reconciliation.field.trigger'),t('reconciliation.field.triggerHint'),<div className="space-y-1.5">@@ -722,9 +795,93 @@ function RuleEditor({ open, node, rule, onClose }: EditorProps) {<Stepindex={3}title={t('reconciliation.step.match')}- hint={t('reconciliation.step.matchHint')}+ hint={t(node === TRANSFER_NODE ? 'reconciliation.step.matchHintTransfer' : 'reconciliation.step.matchHint')}>- {field(+ {/* The signals only a transfer has. Shown for this set alone+ because they are meaningless anywhere else: an invoice has+ no second account to be named by, and asking about credit+ cards in the invoice editor would be a field that can+ never do anything. */}+ {node === TRANSFER_NODE &&+ field(+ t('reconciliation.field.transferSignals'),+ t('reconciliation.field.transferSignalsHint'),+ <div className="space-y-1.5">+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">+ <input+ type="checkbox"+ checked={!!when.account_name_in_description}+ onChange={(e) =>+ setWhen({+ ...when,+ account_name_in_description: e.target.checked || undefined,+ })+ }+ />+ {t('reconciliation.cond.accountNamed')}+ </label>+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">+ <input+ type="checkbox"+ checked={when.tie_break === 'closest_date'}+ onChange={(e) =>+ setWhen({+ ...when,+ tie_break: e.target.checked ? 'closest_date' : undefined,+ })+ }+ />+ {t('reconciliation.cond.closestDate')}+ </label>+ <label className="flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">+ <input+ type="checkbox"+ checked={!!when.unique_candidate}+ onChange={(e) =>+ setWhen({+ ...when,+ unique_candidate: e.target.checked || undefined,+ })+ }+ />+ {t('reconciliation.cond.uniqueCandidate')}+ </label>+ <div className="pt-1">+ <p className="text-xs text-muted-foreground mb-1">+ {t('reconciliation.field.accountTypes')}+ </p>+ <div className="flex flex-wrap gap-x-3 gap-y-1">+ {(Object.keys(ACCOUNT_TYPE_CONFIG) as (keyof typeof ACCOUNT_TYPE_CONFIG)[]).map(+ (kind) => (+ <label+ key={kind}+ className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer"+ >+ <input+ type="checkbox"+ checked={!!when.account_types?.includes(kind as never)}+ onChange={(e) => {+ const current = when.account_types ?? []+ const next = e.target.checked+ ? [...current, kind as never]+ : current.filter((item) => item !== kind)+ setWhen({+ ...when,+ account_types: next.length ? next : undefined,+ })+ }}+ />+ {t(ACCOUNT_TYPE_CONFIG[kind].label)}+ </label>+ ),+ )}+ </div>+ </div>+ </div>,+ )}++ {node !== TRANSFER_NODE &&+ field(t('reconciliation.field.counterparty'),null,<select@@ -741,7 +898,7 @@ function RuleEditor({ open, node, rule, onClose }: EditorProps) {{field(t('reconciliation.field.amountMatch'),- t('reconciliation.field.amountMatchHint'),+ t(node === TRANSFER_NODE ? 'reconciliation.field.amountMatchHintTransfer' : 'reconciliation.field.amountMatchHint'),<><div className="flex gap-2"><select@@ -883,7 +1040,7 @@ function RuleEditor({ open, node, rule, onClose }: EditorProps) {{field(t('reconciliation.field.window'),- t('reconciliation.field.windowHint'),+ t(node === TRANSFER_NODE ? 'reconciliation.field.windowHintTransfer' : 'reconciliation.field.windowHint'),<div className="flex gap-2"><div className="flex-1"><span className="text-xs text-muted-foreground">@@ -980,8 +1137,13 @@ export function ReconciliationRules({ canWrite }: { canWrite: boolean }) {const [pending, setPending] = useState<{file: ReconciliationPolicyFilename: string+ /** Which card the file was dropped on. The import is scoped to it,+ * so a file carrying every set cannot rewrite the invoice rules+ * from a button sitting under *Transfers*. */+ node: string} | null>(null)const fileInput = useRef<HTMLInputElement>(null)+ const importTarget = useRef<string | null>(null)const { data: nodes } = useQuery<ReconciliationNode[]>({queryKey: ['reconciliation-rules'],@@ -1039,14 +1201,14 @@ export function ReconciliationRules({ canWrite }: { canWrite: boolean }) {})const exporting = useMutation({- mutationFn: () => reconciliationApi.exportRules(),+ mutationFn: (node: string) => reconciliationApi.exportRules(node),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),+ mutationFn: ({ file, node }: { file: ReconciliationPolicyFile; node: string }) =>+ reconciliationApi.importRules(file, true, node),onSuccess: (result) => {void queryClient.invalidateQueries({ queryKey: ['reconciliation-rules'] })setPending(null)@@ -1064,7 +1226,11 @@ export function ReconciliationRules({ canWrite }: { canWrite: boolean }) {toast.error(t('reconciliation.invalidImportFile'))return}- setPending({ file: parsed, name: file.name })+ setPending({+ file: parsed,+ name: file.name,+ node: importTarget.current ?? '',+ })} catch {toast.error(t('reconciliation.invalidImportFile'))}@@ -1072,125 +1238,85 @@ export function ReconciliationRules({ canWrite }: { canWrite: boolean }) {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.+ // Nothing here is live for this workspace.if (!nodes.some((group) => group.active)) return nullreturn (<>- {/* 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.+ {/* **One card per set, not one card for matching.**+ *+ * This was one card with the sets as muted strips inside it, under+ * a heading that said *reconciliation*. It failed the first time+ * somebody went looking: they scanned the page for transfer rules,+ * found a card about reconciliation, and stopped. The question+ * they asked next is the one that settles it: *is a transfer a+ * reconciliation?* Nobody should have to decide that to find a+ * switch.+ *+ * So each set is named for what it decides and carries its own+ * frame, its own button and its own file. Transfers first, because+ * it is the set every workspace has. */}+ {nodes.map((group) => (+ <SectionCard key={group.node}>+ <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 flex items-center gap-2">+ {t(CARD_TITLE[group.node] ?? NODE_TITLE[group.node] ?? group.node)}+ {!group.active && (+ <span className="text-[10px] font-semibold bg-muted text-muted-foreground px-1.5 py-0.5 rounded-full">+ {t('reconciliation.node.inactive')}+ </span>+ )}+ </p>+ <p className="text-xs text-muted-foreground mt-0.5">+ {t(CARD_HINT[group.node] ?? NODE_HINT[group.node] ?? '')}+ </p>+ </div>+ {/* A policy is worth more than one workspace. Somebody who has+ worked out how their banks actually behave should be able+ to hand that to the next machine without retyping eleven+ thresholds. Scoped to this set, so the file says what the+ heading above it says. */}+ <div className="flex items-center gap-1.5 shrink-0"><Buttonsize="sm"- className="gap-1.5 h-8 order-last"- onClick={() => setEditing({ node: single.node, rule: null })}+ variant="outline"+ className="gap-1.5 h-8"+ onClick={() => exporting.mutate(group.node)}+ disabled={exporting.isPending}>- <Plus size={13} />- <span className="hidden sm:inline">{t('rules.add')}</span>+ <Download size={12} />+ <span className="hidden sm:inline">{t('rules.export')}</span></Button>- )}- {canWrite && (- <>+ {canWrite && (<Buttonsize="sm"variant="outline"className="gap-1.5 h-8"- onClick={() => fileInput.current?.click()}+ onClick={() => {+ importTarget.current = group.node+ 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>- )}+ {canWrite && (+ // Last and solid, the same place, shape and word as on+ // the categorization card above.+ <Button+ size="sm"+ 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>- )}<div className="divide-y divide-border">{group.rules.map((rule, index) => (@@ -1359,9 +1485,24 @@ export function ReconciliationRules({ canWrite }: { canWrite: boolean }) {))}</div>)}- </div>+ </SectionCard>))}- </SectionCard>++ {/* One input for every card. Which card asked is held on a ref set+ just before the click, because the file dialog is the browser's+ and carries nothing of ours back. */}+ <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 = ''+ }}+ /><DeleteConfirmationDialogopen={deleting !== null}@@ -1413,7 +1554,9 @@ export function ReconciliationRules({ canWrite }: { canWrite: boolean }) {<Buttontype="button"variant="destructive"- onClick={() => { if (pending) importing.mutate(pending.file) }}+ onClick={() => {+ if (pending) importing.mutate({ file: pending.file, node: pending.node })+ }}disabled={!pending || importing.isPending}>{t('rules.confirmOverwriteImport')}diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 077def0e..25ad3657 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -1054,15 +1054,22 @@ export const reconciliation = {`/reconciliation/rules/${encodeURIComponent(node)}/${encodeURIComponent(id)}/reset`,)},- exportRules: async (): Promise<void> => {+ /** `node` narrows the file to one set. Each set is its own card with+ * its own button, and a button under one heading that hands over+ * another set's rules is a button that lies. */+ exportRules: async (node?: string): Promise<void> => {const { data } = await api.get('/reconciliation/rules/export', {responseType: 'blob',+ params: node ? { node } : undefined,})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`+ // The set in the filename, so two exports do not overwrite each+ // other in the downloads folder on the same day.+ const set = node ? `-${node.split('.').pop()}` : ''+ a.download = `securo-reconciliation-rules${set}-${new Date().toISOString().slice(0, 10)}.json`document.body.appendChild(a)a.click()document.body.removeChild(a)@@ -1073,11 +1080,13 @@ export const reconciliation = {importRules: async (payload: ReconciliationPolicyFile,overwrite = false,+ node?: string,): Promise<{ imported: number; skipped: number }> => {- const { data } = await api.post('/reconciliation/rules/import', {- payload,- overwrite,- })+ const { data } = await api.post(+ '/reconciliation/rules/import',+ { payload, overwrite },+ { params: node ? { node } : undefined },+ )return data},/** What matching did, newest first. `expectationId` narrows it todiff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex e098775b..2f18745f 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -2267,7 +2267,9 @@"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"+ "inactive": "Hier nicht in Gebrauch",+ "transfers": "Überweisungen",+ "transfersHint": "zwischen Ihren eigenen Konten"},"rule": {"sameClientExact": "Bekannte Person, exakter Betrag",@@ -2277,7 +2279,10 @@"sameAccountExact": "Gleiches Konto, exakter Betrag","unknown": "Regel","partPayment": "Bekannte Person, Teil des Betrags",- "severalInvoices": "Bekannte Person, mehrere Rechnungen auf einmal"+ "severalInvoices": "Bekannte Person, mehrere Rechnungen auf einmal",+ "destinationNamed": "Die Beschreibung nennt das andere Konto",+ "exactAmountNearby": "Exakter Betrag, naher Termin",+ "closeAmountWiderWindow": "Ähnlicher Betrag, größeres Fenster"},"outcome": {"link": "Verknüpft selbst",@@ -2305,7 +2310,12 @@"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"+ "amountSet": "bis zu {{count}} Rechnungen ergeben die Summe",+ "differentAccount": "zwei verschiedene Konten",+ "accountTypes": "eine Seite ist ein Konto vom Typ {{kinds}}",+ "accountNamed": "eine der Beschreibungen nennt das andere Konto",+ "closestDate": "das nächstliegende Datum gewinnt",+ "uniqueCandidate": "nur ein Kandidat passt"},"newRule": "Neue Abgleichregel","saved": "Regel gespeichert",@@ -2348,7 +2358,12 @@"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."+ "amountBandHint": "Über die Zahlung selbst: eine Größe, die diese Regel behandeln soll oder eben nicht.",+ "transferSignals": "Was es zu einer Überweisung macht",+ "transferSignalsHint": "Die beiden Seiten liegen immer auf verschiedenen Konten. Hier legen Sie fest, was sonst noch zutreffen muss, bevor dem Paar vertraut wird.",+ "accountTypes": "Nur wenn eine Seite eines davon ist",+ "amountMatchHintTransfer": "Verglichen mit der anderen Seite, in derselben Währung. Verschiedene Währungen werden nie von allein gepaart; Sie können die beiden Seiten weiterhin von Hand verknüpfen.",+ "windowHintTransfer": "Geld kommt selten am selben Tag an, an dem es abging. Beide Seiten zählen ab dem anderen Eintrag, zwei Tage je Seite decken also ein Wochenende ab."},"counterparty": {"any": "Beliebig",@@ -2378,7 +2393,13 @@"declineHint": "Passt nicht. Dieses Paar wird nicht erneut vorgeschlagen.","linked": "Verknüpft","declined": "Verworfen. Wir fragen nicht noch einmal",- "covers": "deckt"+ "covers": "deckt",+ "mayPairWith": "könnte die andere Hälfte von {{name}} sein",+ "kind": {+ "transaction": "Überweisung",+ "invoice": "Rechnung",+ "recurring": "Wiederkehrend"+ }},"evidence": {"amountExact": "Betrag stimmt genau",@@ -2386,7 +2407,8 @@"knownPayer": "bekannte Person","unknownPayer": "Person nicht erkannt","sameDay": "gleicher Tag",- "daysApart": "{{days}} Tage Abstand"+ "daysApart_one": "{{count}} Tag Abstand",+ "daysApart_other": "{{count}} Tage Abstand"},"direction": {"any": "Egal",@@ -2398,7 +2420,8 @@"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"+ "matchHint": "Wie genau Zahlung und Versprechen zusammenpassen müssen",+ "matchHintTransfer": "Wie nah die beiden Einträge beieinander liegen müssen"},"trigger": {"money_arrives": "Wenn Geld eingeht oder abgeht",@@ -2427,8 +2450,6 @@},"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",@@ -2443,7 +2464,11 @@"thePayment": "die Zahlung","acrossInvoices": "auf {{count}} Rechnungen","dueOn": "fällig {{date}}",- "totalOf": "Gesamt {{amount}}"+ "totalOf": "Gesamt {{amount}}",+ "otherLeg": "Die andere Seite",+ "thisLeg": "Diese Seite",+ "otherLegAmount": "auf der anderen Seite",+ "thisLegAmount": "auf dieser Seite"},"discarded": "Aus diesem Arbeitsbereich gelöscht:","noneLeft": "Keine Abgleichsregeln mehr in dieser Gruppe. Hier wird nichts automatisch zugeordnet.",@@ -2454,6 +2479,14 @@"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."+ "importOverwriteWarning": "Der Import ersetzt die Abgleichsregeln dieses Arbeitsbereichs samt ihrer Reihenfolge. Das lässt sich nicht rückgängig machen.",+ "card": {+ "transfers": "Überweisungsregeln",+ "transfersHint": "Wie wir entscheiden, dass zwei Einträge eine Überweisung zwischen Ihren Konten sind.",+ "invoices": "Rechnungsregeln",+ "invoicesHint": "Wie wir entscheiden, welche Zahlung welche Rechnung begleicht.",+ "recurring": "Regeln für Wiederkehrendes",+ "recurringHint": "Wie wir entscheiden, dass eine Buchung die erwartete Rechnung ist."+ }}}diff --git a/frontend/src/locales/el.json b/frontend/src/locales/el.jsonindex 45a20211..9836782d 100644--- a/frontend/src/locales/el.json+++ b/frontend/src/locales/el.json@@ -2266,7 +2266,9 @@"invoicesHint": "σε σχέση με όσα έχετε να εισπράξετε και να πληρώσετε","recurring": "Επαναλαμβανόμενα","recurringHint": "σε σχέση με όσα ήδη περιμένατε",- "inactive": "Δεν χρησιμοποιείται εδώ"+ "inactive": "Δεν χρησιμοποιείται εδώ",+ "transfers": "Μεταφορές",+ "transfersHint": "μεταξύ των δικών σας λογαριασμών"},"rule": {"sameClientExact": "Γνωστό πρόσωπο, ακριβές ποσό",@@ -2276,7 +2278,10 @@"sameAccountExact": "Ίδιος λογαριασμός, ακριβές ποσό","unknown": "Άγνωστος κανόνας","partPayment": "Γνωστό πρόσωπο, μέρος του ποσού",- "severalInvoices": "Γνωστό πρόσωπο, πολλά τιμολόγια μαζί"+ "severalInvoices": "Γνωστό πρόσωπο, πολλά τιμολόγια μαζί",+ "destinationNamed": "Η περιγραφή αναφέρει τον άλλο λογαριασμό",+ "exactAmountNearby": "Ακριβές ποσό, κοντινή ημερομηνία",+ "closeAmountWiderWindow": "Κοντινό ποσό, ευρύτερο παράθυρο"},"outcome": {"link": "Συνδέει μόνο του",@@ -2304,7 +2309,12 @@"onArrival": "όταν τα χρήματα μπαίνουν ή βγαίνουν","onIssue": "όταν εκδίδεται τιμολόγιο","amountPartial": "το ποσό καλύπτει μέρος του οφειλόμενου",- "amountSet": "έως {{count}} τιμολόγια αθροίζουν σε αυτό το ποσό"+ "amountSet": "έως {{count}} τιμολόγια αθροίζουν σε αυτό το ποσό",+ "differentAccount": "δύο διαφορετικοί λογαριασμοί",+ "accountTypes": "η μία πλευρά είναι λογαριασμός τύπου {{kinds}}",+ "accountNamed": "μία από τις περιγραφές αναφέρει τον άλλο λογαριασμό",+ "closestDate": "κερδίζει η πιο κοντινή ημερομηνία",+ "uniqueCandidate": "ταιριάζει μόνο ένας υποψήφιος"},"newRule": "Νέος κανόνας αντιστοίχισης","saved": "Ο κανόνας αποθηκεύτηκε",@@ -2347,7 +2357,12 @@"triggerHint": "Η αντιστοίχιση γίνεται σε δύο στιγμές, και τα στοιχεία δεν είναι τα ίδια.","amountMatch": "Πώς συγκρίνεται το ποσό","amountMatchHint": "Σε σχέση με το υπόλοιπο του τιμολογίου.",- "amountBandHint": "Για την ίδια την πληρωμή: ένα μέγεθος που θέλετε, ή δεν θέλετε, να χειρίζεται αυτός ο κανόνας."+ "amountBandHint": "Για την ίδια την πληρωμή: ένα μέγεθος που θέλετε, ή δεν θέλετε, να χειρίζεται αυτός ο κανόνας.",+ "transferSignals": "Τι το κάνει μεταφορά",+ "transferSignalsHint": "Οι δύο πλευρές είναι πάντα σε διαφορετικούς λογαριασμούς. Εδώ λέτε τι άλλο πρέπει να ισχύει πριν εμπιστευτούμε το ζεύγος.",+ "accountTypes": "Μόνο όταν η μία πλευρά είναι μία από αυτές",+ "amountMatchHintTransfer": "Σε σύγκριση με την άλλη πλευρά, στο ίδιο νόμισμα. Διαφορετικά νομίσματα δεν ταιριάζουν ποτέ μόνα τους· μπορείτε ακόμη να συνδέσετε τις δύο πλευρές με το χέρι.",+ "windowHintTransfer": "Τα χρήματα σπάνια φτάνουν την ίδια μέρα που έφυγαν. Και οι δύο πλευρές μετρούν από την άλλη εγγραφή, οπότε δύο μέρες εκατέρωθεν καλύπτουν ένα σαββατοκύριακο."},"counterparty": {"any": "Οποιοσδήποτε",@@ -2377,7 +2392,13 @@"declineHint": "Δεν ταιριάζει. Δεν θα προταθεί ξανά.","linked": "Συνδέθηκε","declined": "Απορρίφθηκε. Δεν θα ρωτήσουμε ξανά",- "covers": "καλύπτει"+ "covers": "καλύπτει",+ "mayPairWith": "μπορεί να είναι το άλλο μισό του {{name}}",+ "kind": {+ "transaction": "Μεταφορά",+ "invoice": "Τιμολόγιο",+ "recurring": "Επαναλαμβανόμενο"+ }},"evidence": {"amountExact": "ακριβές ποσό",@@ -2385,7 +2406,8 @@"knownPayer": "γνωστό πρόσωπο","unknownPayer": "το πρόσωπο δεν αναγνωρίστηκε","sameDay": "ίδια ημέρα",- "daysApart": "{{days}} ημέρες διαφορά"+ "daysApart_one": "{{count}} ημέρα διαφορά",+ "daysApart_other": "{{count}} ημέρες διαφορά"},"direction": {"any": "Οποιαδήποτε",@@ -2397,7 +2419,8 @@"which": "Σε ποια χρήματα κοιτάζει","whichHint": "Αφήστε τα όλα κενά και κοιτάζει σε όλα","match": "Τι μετράει ως αντιστοίχιση",- "matchHint": "Σε σχέση με το τιμολόγιο"+ "matchHint": "Σε σχέση με το τιμολόγιο",+ "matchHintTransfer": "Πόσο κοντά πρέπει να είναι οι δύο εγγραφές"},"trigger": {"money_arrives": "Όταν τα χρήματα μπαίνουν ή βγαίνουν",@@ -2426,8 +2449,6 @@},"moveUp": "Μετακίνηση πάνω","moveDown": "Μετακίνηση κάτω",- "matchingTitle": "Κανόνες αντιστοίχισης",- "matchingHint": "Πώς κάθε πληρωμή συνδέεται με αυτό που εξοφλεί.","pair": {"owed": "Οφείλεται","arrived": "Τι κινήθηκε",@@ -2442,7 +2463,11 @@"thePayment": "Η πληρωμή","acrossInvoices": "σε {{count}} τιμολόγια","dueOn": "λήγει στις {{date}}",- "totalOf": "σύνολο {{amount}}"+ "totalOf": "σύνολο {{amount}}",+ "otherLeg": "Η άλλη πλευρά",+ "thisLeg": "Αυτή η πλευρά",+ "otherLegAmount": "στην άλλη πλευρά",+ "thisLegAmount": "σε αυτήν την πλευρά"},"discarded": "Διαγράφηκαν από αυτόν τον χώρο:","noneLeft": "Δεν έμεινε κανένας κανόνας αντιστοίχισης σε αυτό το σύνολο. Τίποτα εδώ δεν αντιστοιχίζεται αυτόματα.",@@ -2453,6 +2478,14 @@"invalidImportFile": "Αυτό δεν είναι αρχείο κανόνων αντιστοίχισης","importConfirmTitle": "Εισαγωγή κανόνων αντιστοίχισης;","importConfirmDescription": "Το αρχείο {{file}} περιέχει {{count}} κανόνες.",- "importOverwriteWarning": "Η εισαγωγή αντικαθιστά τους κανόνες αντιστοίχισης αυτού του χώρου, μαζί με τη σειρά τους. Δεν αναιρείται."+ "importOverwriteWarning": "Η εισαγωγή αντικαθιστά τους κανόνες αντιστοίχισης αυτού του χώρου, μαζί με τη σειρά τους. Δεν αναιρείται.",+ "card": {+ "transfers": "Κανόνες Μεταφορών",+ "transfersHint": "Πώς αποφασίζουμε ότι δύο εγγραφές είναι η ίδια μεταφορά μεταξύ των λογαριασμών σας.",+ "invoices": "Κανόνες Τιμολογίων",+ "invoicesHint": "Πώς αποφασίζουμε ποια πληρωμή εξοφλεί ποιο τιμολόγιο.",+ "recurring": "Κανόνες Επαναλαμβανόμενων",+ "recurringHint": "Πώς αποφασίζουμε ότι μια χρέωση είναι ο λογαριασμός που ήδη περιμένατε."+ }}}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex e6f467c0..d51db3f2 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -2266,7 +2266,9 @@"invoicesHint": "against what you have to receive and to pay","recurring": "Recurring","recurringHint": "against what you were already expecting",- "inactive": "Not in use here"+ "inactive": "Not in use here",+ "transfers": "Transfers",+ "transfersHint": "between your own accounts"},"rule": {"sameClientExact": "Known person, exact amount",@@ -2276,7 +2278,10 @@"sameAccountExact": "Same account, exact amount","unknown": "Rule","partPayment": "Known person, part of the amount",- "severalInvoices": "Known person, several invoices at once"+ "severalInvoices": "Known person, several invoices at once",+ "destinationNamed": "The description names the other account",+ "exactAmountNearby": "Exact amount, nearby date",+ "closeAmountWiderWindow": "Close amount, wider window"},"outcome": {"link": "Links",@@ -2304,7 +2309,12 @@"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"+ "amountSet": "up to {{count}} invoices add up to it",+ "differentAccount": "two different accounts",+ "accountTypes": "one side is a {{kinds}} account",+ "accountNamed": "one description names the other account",+ "closestDate": "the closest date wins",+ "uniqueCandidate": "only one candidate fits"},"newRule": "New matching rule","saved": "Rule saved",@@ -2347,7 +2357,12 @@"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."+ "amountBandHint": "About the payment itself: a size you do or do not want this rule handling.",+ "transferSignals": "What makes it a transfer",+ "transferSignalsHint": "The two legs are always on different accounts. These say what else has to be true before the pair is trusted.",+ "accountTypes": "Only when one side is one of these",+ "amountMatchHintTransfer": "Compared against the other leg, in the same currency. Different currencies never pair on their own; you can still link the two legs by hand.",+ "windowHintTransfer": "Money rarely lands on the day it left. Both sides are counted from the other record, so two days either way covers a weekend."},"counterparty": {"any": "Anyone",@@ -2377,7 +2392,13 @@"declineHint": "Not a match. This pair will not be suggested again.","linked": "Linked","declined": "Dismissed. We will not ask again",- "covers": "covers"+ "covers": "covers",+ "mayPairWith": "may be the other half of {{name}}",+ "kind": {+ "transaction": "Transfer",+ "invoice": "Invoice",+ "recurring": "Recurring"+ }},"evidence": {"amountExact": "amount matches exactly",@@ -2385,7 +2406,8 @@"knownPayer": "known person","unknownPayer": "person not identified","sameDay": "same day",- "daysApart": "{{days}} days apart"+ "daysApart_one": "{{count}} day apart",+ "daysApart_other": "{{count}} days apart"},"direction": {"any": "Either",@@ -2397,7 +2419,8 @@"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"+ "matchHint": "How closely the payment and the promise have to fit",+ "matchHintTransfer": "How close the two records have to be"},"trigger": {"money_arrives": "When money comes in or goes out",@@ -2426,8 +2449,6 @@},"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",@@ -2442,7 +2463,11 @@"thePayment": "the payment","acrossInvoices": "across {{count}} invoices","dueOn": "due {{date}}",- "totalOf": "{{amount}} total"+ "totalOf": "{{amount}} total",+ "otherLeg": "The other leg",+ "thisLeg": "This one",+ "otherLegAmount": "on the other leg",+ "thisLegAmount": "on this one"},"discarded": "Deleted from this workspace:","noneLeft": "No matching rules left in this set. Nothing here is matched automatically.",@@ -2453,6 +2478,14 @@"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."+ "importOverwriteWarning": "Importing replaces the matching rules this workspace has now, including their order. This cannot be undone.",+ "card": {+ "transfers": "Transfer rules",+ "transfersHint": "How we decide that two records are one transfer between your own accounts.",+ "invoices": "Invoice rules",+ "invoicesHint": "How we decide which payment settles which invoice.",+ "recurring": "Recurring rules",+ "recurringHint": "How we decide that a charge is the bill you were already expecting."+ }}}diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 39ac1f18..3480afd2 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -2267,7 +2267,9 @@"invoicesHint": "contra lo que tienes que cobrar y pagar","recurring": "Recurrentes","recurringHint": "contra lo que ya esperabas",- "inactive": "No se usa aquí"+ "inactive": "No se usa aquí",+ "transfers": "Transferencias",+ "transfersHint": "entre tus propias cuentas"},"rule": {"sameClientExact": "Persona conocida, importe exacto",@@ -2277,7 +2279,10 @@"sameAccountExact": "Misma cuenta, importe exacto","unknown": "Regla","partPayment": "Persona conocida, parte del importe",- "severalInvoices": "Persona conocida, varias facturas a la vez"+ "severalInvoices": "Persona conocida, varias facturas a la vez",+ "destinationNamed": "La descripción nombra la otra cuenta",+ "exactAmountNearby": "Importe exacto, fecha cercana",+ "closeAmountWiderWindow": "Importe aproximado, ventana más amplia"},"outcome": {"link": "Vincula solo",@@ -2305,9 +2310,14 @@"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"+ "amountSet": "hasta {{count}} facturas suman ese importe",+ "differentAccount": "dos cuentas distintas",+ "accountTypes": "uno de los lados es una cuenta de tipo {{kinds}}",+ "accountNamed": "una de las descripciones nombra la otra cuenta",+ "closestDate": "gana la fecha más cercana",+ "uniqueCandidate": "solo un candidato encaja"},- "newRule": "Nueva regla de conciliación",+ "newRule": "Nueva regla de vínculo","saved": "Regla guardada","reset": "Regla restaurada","restore": "Volver al valor por defecto",@@ -2345,10 +2355,15 @@"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.",+ "triggerHint": "El vínculo 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."+ "amountBandHint": "Sobre el pago en sí: un tamaño que quieres, o no, que esta regla trate.",+ "transferSignals": "Qué la convierte en una transferencia",+ "transferSignalsHint": "Los dos lados siempre están en cuentas distintas. Aquí dices qué más debe cumplirse antes de confiar en el par.",+ "accountTypes": "Solo cuando uno de los lados sea uno de estos",+ "amountMatchHintTransfer": "Comparado con el otro lado, en la misma moneda. Monedas distintas nunca se emparejan solas; aún puedes vincular los dos lados a mano.",+ "windowHintTransfer": "El dinero rara vez llega el mismo día que salió. Los dos lados se cuentan desde el otro registro, así que dos días a cada lado cubren un fin de semana."},"counterparty": {"any": "Cualquiera",@@ -2369,7 +2384,7 @@},"queue": {"title": "Esperándote",- "hint": "Conciliaciones que necesitan tu confirmación.",+ "hint": "Vínculos que necesitan tu confirmación.","empty": "Nada que revisar. Todo coincidió solo.","aPayment": "Un pago","maySettle": "puede saldar {{name}}",@@ -2378,7 +2393,13 @@"declineHint": "No es esto. Este par no se volverá a sugerir.","linked": "Vinculado","declined": "Descartado: no volveremos a preguntar",- "covers": "cubre"+ "covers": "cubre",+ "mayPairWith": "puede ser la otra mitad de {{name}}",+ "kind": {+ "transaction": "Transferencia",+ "invoice": "Factura",+ "recurring": "Recurrente"+ }},"evidence": {"amountExact": "el importe coincide exactamente",@@ -2386,7 +2407,8 @@"knownPayer": "persona conocida","unknownPayer": "persona no identificada","sameDay": "mismo día",- "daysApart": "{{days}} días de diferencia"+ "daysApart_one": "{{count}} día de diferencia",+ "daysApart_other": "{{count}} días de diferencia"},"direction": {"any": "Cualquiera",@@ -2398,7 +2420,8 @@"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"+ "matchHint": "Cuán cerca deben estar el pago y la promesa",+ "matchHintTransfer": "Qué tan cerca tienen que estar los dos registros"},"trigger": {"money_arrives": "Cuando el dinero entra o sale",@@ -2409,7 +2432,7 @@"bothHint": "La regla vale en los dos sentidos."},"history": {- "title": "Qué hizo la conciliación",+ "title": "Qué hizo el vínculo automático","hint": "Lo más reciente primero.","byPerson": "por ti","byRules": "por las reglas",@@ -2423,12 +2446,10 @@"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."+ "empty": "Nada aún. Esto se llena a medida que el vínculo automático conecta, 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ó",@@ -2443,17 +2464,29 @@"thePayment": "el pago","acrossInvoices": "en {{count}} facturas","dueOn": "vence {{date}}",- "totalOf": "total de {{amount}}"+ "totalOf": "total de {{amount}}",+ "otherLeg": "El otro lado",+ "thisLeg": "Este lado",+ "otherLegAmount": "en el otro lado",+ "thisLegAmount": "en este lado"},"discarded": "Eliminadas de este espacio:",- "noneLeft": "No queda ninguna regla de conciliación en este conjunto. Aquí no se concilia nada automáticamente.",+ "noneLeft": "No queda ninguna regla en este conjunto. Aquí no se vincula 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",+ "exported": "Reglas de vínculo descargadas","imported": "{{imported}} reglas importadas ({{skipped}} omitidas)",- "invalidImportFile": "Ese no es un archivo de reglas de conciliación",- "importConfirmTitle": "¿Importar reglas de conciliación?",+ "invalidImportFile": "Ese no es un archivo de reglas de vínculo",+ "importConfirmTitle": "¿Importar reglas de vínculo?","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."+ "importOverwriteWarning": "La importación reemplaza las reglas de este conjunto, incluido su orden. No se puede deshacer.",+ "card": {+ "transfers": "Reglas de Transferencia",+ "transfersHint": "Cómo decidimos que dos registros son la misma transferencia entre tus cuentas.",+ "invoices": "Reglas de Factura",+ "invoicesHint": "Cómo decidimos qué pago salda qué factura.",+ "recurring": "Reglas de Recurrentes",+ "recurringHint": "Cómo decidimos que un cargo es la cuenta que ya esperabas."+ }}}diff --git a/frontend/src/locales/fr.json b/frontend/src/locales/fr.jsonindex 2d68b734..d72897cb 100644--- a/frontend/src/locales/fr.json+++ b/frontend/src/locales/fr.json@@ -2267,7 +2267,9 @@"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"+ "inactive": "Non utilisée ici",+ "transfers": "Virements",+ "transfersHint": "entre vos propres comptes"},"rule": {"sameClientExact": "Personne connue, montant exact",@@ -2277,7 +2279,10 @@"sameAccountExact": "Même compte, montant exact","unknown": "Règle","partPayment": "Personne connue, une partie du montant",- "severalInvoices": "Personne connue, plusieurs factures à la fois"+ "severalInvoices": "Personne connue, plusieurs factures à la fois",+ "destinationNamed": "La description nomme l'autre compte",+ "exactAmountNearby": "Montant exact, date proche",+ "closeAmountWiderWindow": "Montant proche, fenêtre élargie"},"outcome": {"link": "Rattache seule",@@ -2305,9 +2310,14 @@"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"+ "amountSet": "jusqu'à {{count}} factures en font le total",+ "differentAccount": "deux comptes différents",+ "accountTypes": "un des côtés est un compte de type {{kinds}}",+ "accountNamed": "une des descriptions nomme l'autre compte",+ "closestDate": "la date la plus proche l'emporte",+ "uniqueCandidate": "un seul candidat convient"},- "newRule": "Nouvelle règle de rapprochement",+ "newRule": "Nouvelle règle de correspondance","saved": "Règle enregistrée","reset": "Règle rétablie","restore": "Revenir au réglage par défaut",@@ -2345,10 +2355,15 @@"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.",+ "triggerHint": "La correspondance 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."+ "amountBandHint": "À propos du paiement lui-même : une taille que vous voulez, ou non, voir traitée par cette règle.",+ "transferSignals": "Ce qui en fait un virement",+ "transferSignalsHint": "Les deux côtés sont toujours sur des comptes différents. Ici vous dites quoi d'autre doit être vrai avant de faire confiance à la paire.",+ "accountTypes": "Seulement quand un des côtés est l'un de ceux-ci",+ "amountMatchHintTransfer": "Comparé à l'autre côté, dans la même devise. Des devises différentes ne s'apparient jamais seules ; vous pouvez toujours relier les deux côtés à la main.",+ "windowHintTransfer": "L'argent arrive rarement le jour où il est parti. Les deux côtés se comptent depuis l'autre écriture, donc deux jours de chaque côté couvrent un week-end."},"counterparty": {"any": "N'importe qui",@@ -2369,7 +2384,7 @@},"queue": {"title": "En attente de vous",- "hint": "Rapprochements qui attendent votre confirmation.",+ "hint": "Correspondances qui attendent votre confirmation.","empty": "Rien à vérifier. Tout a été rapproché tout seul.","aPayment": "Un paiement","maySettle": "règle peut-être {{name}}",@@ -2378,7 +2393,13 @@"declineHint": "Ce n'est pas ça. Cette paire ne sera plus proposée.","linked": "Rattaché","declined": "Écarté. Nous ne redemanderons pas",- "covers": "couvre"+ "covers": "couvre",+ "mayPairWith": "est peut-être l'autre moitié de {{name}}",+ "kind": {+ "transaction": "Virement",+ "invoice": "Facture",+ "recurring": "Récurrent"+ }},"evidence": {"amountExact": "le montant correspond exactement",@@ -2386,7 +2407,8 @@"knownPayer": "personne connue","unknownPayer": "personne non identifiée","sameDay": "même jour",- "daysApart": "{{days}} jours d'écart"+ "daysApart_one": "{{count}} jour d'écart",+ "daysApart_other": "{{count}} jours d'écart"},"direction": {"any": "Peu importe",@@ -2397,8 +2419,9 @@"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"+ "match": "Quand cela compte comme une correspondance",+ "matchHint": "À quel point le paiement et la promesse doivent correspondre",+ "matchHintTransfer": "À quel point les deux écritures doivent se rapprocher"},"trigger": {"money_arrives": "Quand l'argent entre ou sort",@@ -2409,7 +2432,7 @@"bothHint": "La règle vaut dans les deux sens."},"history": {- "title": "Ce que le rapprochement a fait",+ "title": "Ce que la correspondance automatique a fait","hint": "Du plus récent.","byPerson": "par vous","byRules": "par les règles",@@ -2423,12 +2446,10 @@"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."+ "empty": "Rien pour l'instant. Cela se remplit à mesure que la correspondance 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é",@@ -2443,17 +2464,29 @@"thePayment": "le paiement","acrossInvoices": "sur {{count}} factures","dueOn": "échéance {{date}}",- "totalOf": "total de {{amount}}"+ "totalOf": "total de {{amount}}",+ "otherLeg": "L'autre côté",+ "thisLeg": "Ce côté",+ "otherLegAmount": "sur l'autre côté",+ "thisLegAmount": "sur ce côté"},"discarded": "Supprimées de cet espace :",- "noneLeft": "Plus aucune règle de rapprochement dans cet ensemble. Rien n'est rapproché automatiquement ici.",+ "noneLeft": "Plus aucune règle dans cet ensemble. Rien n'est rattaché 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",+ "exported": "Règles de correspondance 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 ?",+ "invalidImportFile": "Ce n'est pas un fichier de règles de correspondance",+ "importConfirmTitle": "Importer les règles de correspondance ?","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."+ "importOverwriteWarning": "L'import remplace les règles de cet ensemble, y compris leur ordre. C'est irréversible.",+ "card": {+ "transfers": "Règles de Virement",+ "transfersHint": "Comment nous décidons que deux écritures sont un même virement entre vos comptes.",+ "invoices": "Règles de Facture",+ "invoicesHint": "Comment nous décidons quel paiement règle quelle facture.",+ "recurring": "Règles Récurrentes",+ "recurringHint": "Comment nous décidons qu’un prélèvement est la facture que vous attendiez."+ }}}diff --git a/frontend/src/locales/hi.json b/frontend/src/locales/hi.jsonindex a23612c8..87cd4e9c 100644--- a/frontend/src/locales/hi.json+++ b/frontend/src/locales/hi.json@@ -2266,7 +2266,9 @@"invoicesHint": "जो आपको मिलना है और जो चुकाना है, उसके सामने","recurring": "आवर्ती","recurringHint": "जिसकी आप पहले से उम्मीद कर रहे थे, उसके सामने",- "inactive": "यहाँ उपयोग में नहीं"+ "inactive": "यहाँ उपयोग में नहीं",+ "transfers": "स्थानांतरण",+ "transfersHint": "आपके अपने खातों के बीच"},"rule": {"sameClientExact": "ज्ञात व्यक्ति, ठीक वही राशि",@@ -2276,7 +2278,10 @@"sameAccountExact": "वही खाता, ठीक वही राशि","unknown": "नियम","partPayment": "ज्ञात व्यक्ति, राशि का एक हिस्सा",- "severalInvoices": "ज्ञात व्यक्ति, एक साथ कई इनवॉइस"+ "severalInvoices": "ज्ञात व्यक्ति, एक साथ कई इनवॉइस",+ "destinationNamed": "विवरण दूसरे खाते का नाम बताता है",+ "exactAmountNearby": "सटीक राशि, नज़दीकी तारीख",+ "closeAmountWiderWindow": "मिलती-जुलती राशि, चौड़ी अवधि"},"outcome": {"link": "जोड़ता है",@@ -2304,7 +2309,12 @@"onArrival": "जब पैसा आता या जाता है","onIssue": "जब इनवॉइस जारी होता है","amountPartial": "राशि बकाया का एक हिस्सा चुकाती है",- "amountSet": "{{count}} तक इनवॉइस मिलकर यह राशि बनाते हैं"+ "amountSet": "{{count}} तक इनवॉइस मिलकर यह राशि बनाते हैं",+ "differentAccount": "दो अलग-अलग खाते",+ "accountTypes": "एक ओर {{kinds}} खाता है",+ "accountNamed": "किसी एक विवरण में दूसरे खाते का नाम है",+ "closestDate": "सबसे नज़दीकी तारीख जीतती है",+ "uniqueCandidate": "केवल एक ही उम्मीदवार फिट बैठता है"},"newRule": "नया मिलान नियम","saved": "नियम सहेजा गया",@@ -2347,7 +2357,12 @@"triggerHint": "मिलान दो मौकों पर होता है, और दोनों में सबूत एक जैसा नहीं होता।","amountMatch": "राशि कितनी करीब होनी चाहिए","amountMatchHint": "मूल कुल से नहीं, जो अब भी बकाया है उससे तुलना होती है।",- "amountBandHint": "खुद भुगतान के बारे में: वह आकार जो आप इस नियम से संभलवाना चाहते हैं, या नहीं चाहते।"+ "amountBandHint": "खुद भुगतान के बारे में: वह आकार जो आप इस नियम से संभलवाना चाहते हैं, या नहीं चाहते।",+ "transferSignals": "इसे स्थानांतरण क्या बनाता है",+ "transferSignalsHint": "दोनों पक्ष हमेशा अलग-अलग खातों में होते हैं। यहाँ आप बताते हैं कि जोड़े पर भरोसा करने से पहले और क्या सही होना चाहिए।",+ "accountTypes": "केवल जब एक ओर इनमें से कोई हो",+ "amountMatchHintTransfer": "उसी मुद्रा में, दूसरी ओर से तुलना की जाती है। अलग-अलग मुद्राएँ कभी अपने आप नहीं जुड़तीं; आप दोनों ओर को हाथ से जोड़ सकते हैं।",+ "windowHintTransfer": "पैसा शायद ही उसी दिन पहुँचता है जिस दिन निकला। दोनों ओर दूसरी प्रविष्टि से गिने जाते हैं, इसलिए हर ओर दो दिन एक सप्ताहांत को कवर करते हैं।"},"counterparty": {"any": "कोई भी",@@ -2377,7 +2392,13 @@"declineHint": "यह मेल नहीं है। यह जोड़ी दोबारा नहीं सुझाई जाएगी।","linked": "जोड़ा गया","declined": "खारिज किया गया। हम दोबारा नहीं पूछेंगे",- "covers": "शामिल करता है"+ "covers": "शामिल करता है",+ "mayPairWith": "{{name}} का दूसरा हिस्सा हो सकता है",+ "kind": {+ "transaction": "स्थानांतरण",+ "invoice": "चालान",+ "recurring": "आवर्ती"+ }},"evidence": {"amountExact": "राशि बिल्कुल मेल खाती है",@@ -2385,7 +2406,8 @@"knownPayer": "ज्ञात व्यक्ति","unknownPayer": "व्यक्ति की पहचान नहीं","sameDay": "उसी दिन",- "daysApart": "{{days}} दिन का अंतर"+ "daysApart_one": "{{count}} दिन का अंतर",+ "daysApart_other": "{{count}} दिन का अंतर"},"direction": {"any": "कोई भी",@@ -2397,7 +2419,8 @@"which": "यह किस पैसे को देखता है","whichHint": "सब खाली छोड़ें तो यह सब कुछ देखता है","match": "मेल कब माना जाए",- "matchHint": "भुगतान और वादा कितने करीब होने चाहिए"+ "matchHint": "भुगतान और वादा कितने करीब होने चाहिए",+ "matchHintTransfer": "दोनों प्रविष्टियाँ कितनी पास होनी चाहिए"},"trigger": {"money_arrives": "जब पैसा आता या जाता है",@@ -2426,8 +2449,6 @@},"moveUp": "इसे पहले आज़माएँ","moveDown": "इसे बाद में आज़माएँ",- "matchingTitle": "मिलान नियम",- "matchingHint": "हर भुगतान उसी से कैसे जुड़ता है जिसे वह चुकाता है।","pair": {"owed": "क्या बकाया है","arrived": "जो पैसा चला",@@ -2442,7 +2463,11 @@"thePayment": "वह भुगतान","acrossInvoices": "{{count}} इनवॉइस में","dueOn": "देय {{date}}",- "totalOf": "कुल {{amount}}"+ "totalOf": "कुल {{amount}}",+ "otherLeg": "दूसरी ओर",+ "thisLeg": "यह ओर",+ "otherLegAmount": "दूसरी ओर",+ "thisLegAmount": "इस ओर"},"discarded": "इस वर्कस्पेस से हटाए गए:","noneLeft": "इस समूह में कोई मिलान नियम नहीं बचा। यहाँ कुछ भी अपने आप मेल नहीं खाएगा।",@@ -2453,6 +2478,14 @@"invalidImportFile": "यह मिलान नियमों की फ़ाइल नहीं है","importConfirmTitle": "मिलान नियम इंपोर्ट करें?","importConfirmDescription": "फ़ाइल {{file}} में {{count}} नियम हैं।",- "importOverwriteWarning": "इंपोर्ट करने पर इस वर्कस्पेस के मौजूदा मिलान नियम, उनके क्रम सहित, बदल जाएँगे। यह वापस नहीं किया जा सकता।"+ "importOverwriteWarning": "इंपोर्ट करने पर इस वर्कस्पेस के मौजूदा मिलान नियम, उनके क्रम सहित, बदल जाएँगे। यह वापस नहीं किया जा सकता।",+ "card": {+ "transfers": "स्थानांतरण नियम",+ "transfersHint": "हम कैसे तय करते हैं कि दो प्रविष्टियाँ आपके खातों के बीच एक ही स्थानांतरण हैं।",+ "invoices": "चालान नियम",+ "invoicesHint": "हम कैसे तय करते हैं कि कौन सा भुगतान कौन सा चालान चुकाता है।",+ "recurring": "आवर्ती नियम",+ "recurringHint": "हम कैसे तय करते हैं कि कोई शुल्क वही बिल है जिसकी आप पहले से अपेक्षा कर रहे थे।"+ }}}diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 4ddc8cdd..1b1efdd4 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -2267,7 +2267,9 @@"invoicesHint": "rispetto a ciò che devi incassare e pagare","recurring": "Ricorrenti","recurringHint": "rispetto a ciò che già ti aspettavi",- "inactive": "Non usata qui"+ "inactive": "Non usata qui",+ "transfers": "Trasferimenti",+ "transfersHint": "tra i tuoi conti"},"rule": {"sameClientExact": "Persona conosciuta, importo esatto",@@ -2277,7 +2279,10 @@"sameAccountExact": "Stesso conto, importo esatto","unknown": "Regola","partPayment": "Persona conosciuta, parte dell'importo",- "severalInvoices": "Persona conosciuta, più fatture insieme"+ "severalInvoices": "Persona conosciuta, più fatture insieme",+ "destinationNamed": "La descrizione nomina l'altro conto",+ "exactAmountNearby": "Importo esatto, data vicina",+ "closeAmountWiderWindow": "Importo simile, finestra più ampia"},"outcome": {"link": "Collega da sola",@@ -2305,9 +2310,14 @@"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"+ "amountSet": "fino a {{count}} fatture danno quella somma",+ "differentAccount": "due conti diversi",+ "accountTypes": "un lato è un conto di tipo {{kinds}}",+ "accountNamed": "una delle descrizioni nomina l'altro conto",+ "closestDate": "vince la data più vicina",+ "uniqueCandidate": "solo un candidato corrisponde"},- "newRule": "Nuova regola di riconciliazione",+ "newRule": "Nuova regola di corrispondenza","saved": "Regola salvata","reset": "Regola ripristinata","restore": "Torna all'impostazione predefinita",@@ -2345,10 +2355,15 @@"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.",+ "triggerHint": "La corrispondenza 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."+ "amountBandHint": "Sul pagamento in sé: una dimensione che vuoi, o non vuoi, che questa regola tratti.",+ "transferSignals": "Cosa la rende un trasferimento",+ "transferSignalsHint": "I due lati sono sempre su conti diversi. Qui dici cos'altro deve essere vero prima di fidarti della coppia.",+ "accountTypes": "Solo quando un lato è uno di questi",+ "amountMatchHintTransfer": "Confrontato con l'altro lato, nella stessa valuta. Valute diverse non si abbinano mai da sole; puoi comunque collegare i due lati a mano.",+ "windowHintTransfer": "Il denaro raramente arriva il giorno in cui è partito. I due lati si contano dall'altro movimento, quindi due giorni per parte coprono un fine settimana."},"counterparty": {"any": "Chiunque",@@ -2369,7 +2384,7 @@},"queue": {"title": "In attesa di te",- "hint": "Riconciliazioni che aspettano una tua conferma.",+ "hint": "Corrispondenze che aspettano una tua conferma.","empty": "Niente da rivedere. Ha combaciato tutto da solo.","aPayment": "Un pagamento","maySettle": "potrebbe saldare {{name}}",@@ -2378,7 +2393,13 @@"declineHint": "Non è questo. Questa coppia non verrà più suggerita.","linked": "Collegato","declined": "Scartato: non lo chiederemo più",- "covers": "copre"+ "covers": "copre",+ "mayPairWith": "può essere l'altra metà di {{name}}",+ "kind": {+ "transaction": "Trasferimento",+ "invoice": "Fattura",+ "recurring": "Ricorrente"+ }},"evidence": {"amountExact": "l'importo corrisponde esattamente",@@ -2386,7 +2407,8 @@"knownPayer": "persona conosciuta","unknownPayer": "persona non identificata","sameDay": "stesso giorno",- "daysApart": "{{days}} giorni di differenza"+ "daysApart_one": "{{count}} giorno di differenza",+ "daysApart_other": "{{count}} giorni di differenza"},"direction": {"any": "Indifferente",@@ -2398,7 +2420,8 @@"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"+ "matchHint": "Quanto devono combaciare il pagamento e la promessa",+ "matchHintTransfer": "Quanto devono essere vicini i due movimenti"},"trigger": {"money_arrives": "Quando il denaro entra o esce",@@ -2409,7 +2432,7 @@"bothHint": "La regola vale in tutti e due i versi."},"history": {- "title": "Cosa ha fatto la riconciliazione",+ "title": "Cosa ha fatto la corrispondenza automatica","hint": "Dalle più recenti.","byPerson": "da te","byRules": "dalle regole",@@ -2423,12 +2446,10 @@"expired": "Suggerimento scaduto: {{name}}","unlinked": "Scollegato da {{name}}"},- "empty": "Ancora niente. Si riempie man mano che la riconciliazione collega, chiede e riceve risposta."+ "empty": "Ancora niente. Si riempie man mano che la corrispondenza 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",@@ -2443,17 +2464,29 @@"thePayment": "il pagamento","acrossInvoices": "su {{count}} fatture","dueOn": "scade {{date}}",- "totalOf": "totale di {{amount}}"+ "totalOf": "totale di {{amount}}",+ "otherLeg": "L'altro lato",+ "thisLeg": "Questo lato",+ "otherLegAmount": "sull'altro lato",+ "thisLegAmount": "su questo lato"},"discarded": "Eliminate da questo spazio:",- "noneLeft": "Nessuna regola di riconciliazione in questo insieme. Qui non viene riconciliato nulla in automatico.",+ "noneLeft": "Nessuna regola in questo insieme. Qui non viene collegato 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",+ "exported": "Regole di corrispondenza scaricate","imported": "{{imported}} regole importate ({{skipped}} ignorate)",- "invalidImportFile": "Questo non è un file di regole di riconciliazione",- "importConfirmTitle": "Importare le regole di riconciliazione?",+ "invalidImportFile": "Questo non è un file di regole di corrispondenza",+ "importConfirmTitle": "Importare le regole di corrispondenza?","importConfirmDescription": "Il file {{file}} contiene {{count}} regole.",- "importOverwriteWarning": "L'importazione sostituisce le regole di riconciliazione di questo spazio, incluso il loro ordine. Non è reversibile."+ "importOverwriteWarning": "L'importazione sostituisce le regole di questo insieme, incluso il loro ordine. Non è reversibile.",+ "card": {+ "transfers": "Regole di Trasferimento",+ "transfersHint": "Come decidiamo che due movimenti sono lo stesso trasferimento tra i tuoi conti.",+ "invoices": "Regole di Fattura",+ "invoicesHint": "Come decidiamo quale pagamento salda quale fattura.",+ "recurring": "Regole Ricorrenti",+ "recurringHint": "Come decidiamo che un addebito è la bolletta che stavi già aspettando."+ }}}diff --git a/frontend/src/locales/ja.json b/frontend/src/locales/ja.jsonindex 874deffb..046853c6 100644--- a/frontend/src/locales/ja.json+++ b/frontend/src/locales/ja.json@@ -2266,7 +2266,9 @@"invoicesHint": "受け取る分と支払う分に対して","recurring": "定期取引","recurringHint": "すでに予定していたものに対して",- "inactive": "ここでは使いません"+ "inactive": "ここでは使いません",+ "transfers": "振替",+ "transfersHint": "自分の口座のあいだ"},"rule": {"sameClientExact": "既知の相手、金額が一致",@@ -2276,7 +2278,10 @@"sameAccountExact": "同じ口座、金額が一致","unknown": "ルール","partPayment": "既知の相手、金額の一部",- "severalInvoices": "既知の相手、複数の請求書をまとめて"+ "severalInvoices": "既知の相手、複数の請求書をまとめて",+ "destinationNamed": "摘要がもう一方の口座名を含む",+ "exactAmountNearby": "金額が一致し、日付が近い",+ "closeAmountWiderWindow": "金額が近く、期間が広い"},"outcome": {"link": "自動連結",@@ -2304,7 +2309,12 @@"onArrival": "入金または出金があったとき","onIssue": "請求書を発行したとき","amountPartial": "金額が未回収分の一部を満たす",- "amountSet": "最大{{count}}件の請求書の合計が一致"+ "amountSet": "最大{{count}}件の請求書の合計が一致",+ "differentAccount": "異なる2つの口座",+ "accountTypes": "一方が{{kinds}}の口座",+ "accountNamed": "いずれかの摘要がもう一方の口座名を含む",+ "closestDate": "最も近い日付が優先",+ "uniqueCandidate": "候補が1件だけ"},"newRule": "新しい照合ルール","saved": "ルールを保存しました",@@ -2347,7 +2357,12 @@"triggerHint": "照合は2つの場面で行われ、手がかりはそれぞれ異なります。","amountMatch": "金額がどれだけ近い必要があるか","amountMatchHint": "元の合計ではなく、未回収の残額と比べます。",- "amountBandHint": "支払いそのものについて。このルールに扱わせたい、あるいは扱わせたくない金額の大きさです。"+ "amountBandHint": "支払いそのものについて。このルールに扱わせたい、あるいは扱わせたくない金額の大きさです。",+ "transferSignals": "振替と見なす条件",+ "transferSignalsHint": "両側は常に別の口座にあります。ここでは、その組み合わせを信頼する前に満たすべき条件を指定します。",+ "accountTypes": "一方が次のいずれかの場合のみ",+ "amountMatchHintTransfer": "同じ通貨で、もう一方と比較します。通貨が異なる場合は自動では組みません。両方を手動で結び付けることはできます。",+ "windowHintTransfer": "お金が出た日に届くことはまれです。両側とももう一方の記録から数えるため、前後2日で週末をまかなえます。"},"counterparty": {"any": "誰でも",@@ -2377,7 +2392,13 @@"declineHint": "一致しません。この組み合わせは二度と提案されません。","linked": "結びつけました","declined": "却下しました。二度と確認しません",- "covers": "がカバーする範囲"+ "covers": "がカバーする範囲",+ "mayPairWith": "{{name}} のもう一方かもしれません",+ "kind": {+ "transaction": "振替",+ "invoice": "請求書",+ "recurring": "定期"+ }},"evidence": {"amountExact": "金額が完全に一致",@@ -2385,7 +2406,8 @@"knownPayer": "既知の相手","unknownPayer": "相手を特定できず","sameDay": "同じ日",- "daysApart": "{{days}}日差"+ "daysApart_one": "{{count}}日差",+ "daysApart_other": "{{count}}日差"},"direction": {"any": "どちらでも",@@ -2397,7 +2419,8 @@"which": "どの入出金を見るか","whichHint": "すべて空欄にすると、すべてを見ます","match": "一致とみなす条件",- "matchHint": "支払いと請求がどれだけ近い必要があるか"+ "matchHint": "支払いと請求がどれだけ近い必要があるか",+ "matchHintTransfer": "2つの記録がどれだけ近い必要があるか"},"trigger": {"money_arrives": "入金または出金があったとき",@@ -2426,8 +2449,6 @@},"moveUp": "これをもっと先に試す","moveDown": "これをもっと後に試す",- "matchingTitle": "照合ルール",- "matchingHint": "各支払いが何を消し込むかを結びつける方法です。","pair": {"owed": "未回収の内容","arrived": "動いたお金",@@ -2442,7 +2463,11 @@"thePayment": "その支払い","acrossInvoices": "請求書{{count}}件にわたって","dueOn": "期日 {{date}}",- "totalOf": "合計 {{amount}}"+ "totalOf": "合計 {{amount}}",+ "otherLeg": "もう一方",+ "thisLeg": "こちら",+ "otherLegAmount": "もう一方の金額",+ "thisLegAmount": "こちらの金額"},"discarded": "このワークスペースで削除済み:","noneLeft": "このセットに照合ルールは残っていません。ここでは自動で照合されません。",@@ -2453,6 +2478,14 @@"invalidImportFile": "照合ルールのファイルではありません","importConfirmTitle": "照合ルールをインポートしますか?","importConfirmDescription": "ファイル{{file}}には{{count}}件のルールが含まれています。",- "importOverwriteWarning": "インポートすると、このワークスペースの現在の照合ルールが順序ごと置き換わります。この操作は取り消せません。"+ "importOverwriteWarning": "インポートすると、このワークスペースの現在の照合ルールが順序ごと置き換わります。この操作は取り消せません。",+ "card": {+ "transfers": "振替のルール",+ "transfersHint": "2つの記録が自分の口座間の同じ振替だと判断する方法。",+ "invoices": "請求書のルール",+ "invoicesHint": "どの入金がどの請求書を消し込むかを判断する方法。",+ "recurring": "定期のルール",+ "recurringHint": "ある引き落としが予定していた支払いだと判断する方法。"+ }}}diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.jsonindex a3e9077b..c3266613 100644--- a/frontend/src/locales/nl.json+++ b/frontend/src/locales/nl.json@@ -2268,7 +2268,9 @@"invoicesHint": "tegenover wat je moet ontvangen en betalen","recurring": "Terugkerend","recurringHint": "tegenover wat je al verwachtte",- "inactive": "Hier niet in gebruik"+ "inactive": "Hier niet in gebruik",+ "transfers": "Overboekingen",+ "transfersHint": "tussen je eigen rekeningen"},"rule": {"sameClientExact": "Bekende persoon, exact bedrag",@@ -2278,7 +2280,10 @@"sameAccountExact": "Zelfde rekening, exact bedrag","unknown": "Regel","partPayment": "Bekende persoon, deel van het bedrag",- "severalInvoices": "Bekende persoon, meerdere facturen tegelijk"+ "severalInvoices": "Bekende persoon, meerdere facturen tegelijk",+ "destinationNamed": "De omschrijving noemt de andere rekening",+ "exactAmountNearby": "Exact bedrag, datum dichtbij",+ "closeAmountWiderWindow": "Bedrag in de buurt, ruimer venster"},"outcome": {"link": "Koppelt zelf",@@ -2306,7 +2311,12 @@"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"+ "amountSet": "tot {{count}} facturen tellen op tot dat bedrag",+ "differentAccount": "twee verschillende rekeningen",+ "accountTypes": "een kant is een rekening van het type {{kinds}}",+ "accountNamed": "een van de omschrijvingen noemt de andere rekening",+ "closestDate": "de dichtstbijzijnde datum wint",+ "uniqueCandidate": "slechts één kandidaat past"},"newRule": "Nieuwe afletterregel","saved": "Regel opgeslagen",@@ -2349,7 +2359,12 @@"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."+ "amountBandHint": "Over de betaling zelf: een omvang die je deze regel wel of niet wilt laten behandelen.",+ "transferSignals": "Wat het een overboeking maakt",+ "transferSignalsHint": "De twee kanten staan altijd op verschillende rekeningen. Hier geef je aan wat er verder waar moet zijn voordat het paar wordt vertrouwd.",+ "accountTypes": "Alleen als een kant een van deze is",+ "amountMatchHintTransfer": "Vergeleken met de andere kant, in dezelfde valuta. Verschillende valuta koppelen nooit vanzelf; je kunt de twee kanten nog steeds handmatig verbinden.",+ "windowHintTransfer": "Geld komt zelden aan op de dag dat het vertrok. Beide kanten tellen vanaf de andere regel, dus twee dagen per kant dekt een weekend."},"counterparty": {"any": "Iedereen",@@ -2379,7 +2394,13 @@"declineHint": "Dit is het niet. Dit paar wordt niet opnieuw voorgesteld.","linked": "Gekoppeld","declined": "Afgewezen. We vragen het niet nog eens",- "covers": "dekt"+ "covers": "dekt",+ "mayPairWith": "kan de andere helft van {{name}} zijn",+ "kind": {+ "transaction": "Overboeking",+ "invoice": "Factuur",+ "recurring": "Terugkerend"+ }},"evidence": {"amountExact": "bedrag klopt precies",@@ -2387,7 +2408,8 @@"knownPayer": "bekende persoon","unknownPayer": "persoon niet herkend","sameDay": "zelfde dag",- "daysApart": "{{days}} dagen verschil"+ "daysApart_one": "{{count}} dag verschil",+ "daysApart_other": "{{count}} dagen verschil"},"direction": {"any": "Maakt niet uit",@@ -2399,7 +2421,8 @@"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"+ "matchHint": "Hoe nauw de betaling en de belofte moeten passen",+ "matchHintTransfer": "Hoe dicht de twee regels bij elkaar moeten liggen"},"trigger": {"money_arrives": "Wanneer geld binnenkomt of weggaat",@@ -2428,8 +2451,6 @@},"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",@@ -2444,7 +2465,11 @@"thePayment": "de betaling","acrossInvoices": "over {{count}} facturen","dueOn": "vervalt {{date}}",- "totalOf": "totaal {{amount}}"+ "totalOf": "totaal {{amount}}",+ "otherLeg": "De andere kant",+ "thisLeg": "Deze kant",+ "otherLegAmount": "aan de andere kant",+ "thisLegAmount": "aan deze kant"},"discarded": "Verwijderd uit deze werkruimte:","noneLeft": "Geen koppelregels meer in deze set. Hier wordt niets automatisch gekoppeld.",@@ -2455,6 +2480,14 @@"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."+ "importOverwriteWarning": "Importeren vervangt de koppelregels van deze werkruimte, inclusief hun volgorde. Dit kan niet ongedaan worden gemaakt.",+ "card": {+ "transfers": "Overboekingsregels",+ "transfersHint": "Hoe we bepalen dat twee regels één overboeking tussen je eigen rekeningen zijn.",+ "invoices": "Factuurregels",+ "invoicesHint": "Hoe we bepalen welke betaling welke factuur voldoet.",+ "recurring": "Regels voor Terugkerend",+ "recurringHint": "Hoe we bepalen dat een afschrijving de rekening is die je al verwachtte."+ }}}diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex fedbe969..6dff588d 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -2372,7 +2372,9 @@"invoicesHint": "wobec tego, co masz otrzymać i zapłacić","recurring": "Cykliczne","recurringHint": "wobec tego, czego już się spodziewałeś",- "inactive": "Tu nieużywane"+ "inactive": "Tu nieużywane",+ "transfers": "Przelewy",+ "transfersHint": "między własnymi kontami"},"rule": {"sameClientExact": "Znana osoba, dokładna kwota",@@ -2382,7 +2384,10 @@"sameAccountExact": "To samo konto, dokładna kwota","unknown": "Reguła","partPayment": "Znana osoba, część kwoty",- "severalInvoices": "Znana osoba, kilka faktur naraz"+ "severalInvoices": "Znana osoba, kilka faktur naraz",+ "destinationNamed": "Opis wskazuje drugie konto",+ "exactAmountNearby": "Dokładna kwota, bliska data",+ "closeAmountWiderWindow": "Zbliżona kwota, szersze okno"},"outcome": {"link": "Wiąże sama",@@ -2410,7 +2415,12 @@"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ę"+ "amountSet": "do {{count}} faktur daje tę sumę",+ "differentAccount": "dwa różne konta",+ "accountTypes": "jedna ze stron to konto typu {{kinds}}",+ "accountNamed": "jeden z opisów wskazuje drugie konto",+ "closestDate": "wygrywa najbliższa data",+ "uniqueCandidate": "pasuje tylko jeden kandydat"},"newRule": "Nowa reguła dopasowania","saved": "Reguła zapisana",@@ -2453,7 +2463,12 @@"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."+ "amountBandHint": "O samej płatności: wielkość, którą ta reguła ma obsługiwać albo nie.",+ "transferSignals": "Co czyni z tego przelew",+ "transferSignalsHint": "Obie strony zawsze są na różnych kontach. Tutaj określasz, co jeszcze musi się zgadzać, zanim zaufamy tej parze.",+ "accountTypes": "Tylko gdy jedna ze stron jest jedną z tych",+ "amountMatchHintTransfer": "Porównywane z drugą stroną, w tej samej walucie. Różne waluty nigdy nie łączą się same; nadal możesz powiązać obie strony ręcznie.",+ "windowHintTransfer": "Pieniądze rzadko docierają tego samego dnia, w którym wyszły. Obie strony liczą się od drugiego zapisu, więc dwa dni z każdej strony obejmują weekend."},"counterparty": {"any": "Ktokolwiek",@@ -2483,7 +2498,13 @@"declineHint": "To nie to. Ta para nie będzie już proponowana.","linked": "Powiązano","declined": "Odrzucono. Nie zapytamy ponownie",- "covers": "pokrywa"+ "covers": "pokrywa",+ "mayPairWith": "może być drugą połową {{name}}",+ "kind": {+ "transaction": "Przelew",+ "invoice": "Faktura",+ "recurring": "Cykliczne"+ }},"evidence": {"amountExact": "kwota zgadza się dokładnie",@@ -2491,7 +2512,10 @@"knownPayer": "znana osoba","unknownPayer": "osoba nierozpoznana","sameDay": "ten sam dzień",- "daysApart": "różnica {{days}} dni"+ "daysApart_one": "różnica {{count}} dnia",+ "daysApart_few": "różnica {{count}} dni",+ "daysApart_many": "różnica {{count}} dni",+ "daysApart_other": "różnica {{count}} dni"},"direction": {"any": "Obojętnie",@@ -2503,7 +2527,8 @@"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"+ "matchHint": "Jak blisko muszą być płatność i zobowiązanie",+ "matchHintTransfer": "Jak blisko siebie muszą być oba zapisy"},"trigger": {"money_arrives": "Gdy pieniądze wpływają lub wypływają",@@ -2532,8 +2557,6 @@},"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",@@ -2548,7 +2571,11 @@"thePayment": "płatność","acrossInvoices": "na {{count}} faktur","dueOn": "termin {{date}}",- "totalOf": "razem {{amount}}"+ "totalOf": "razem {{amount}}",+ "otherLeg": "Druga strona",+ "thisLeg": "Ta strona",+ "otherLegAmount": "po drugiej stronie",+ "thisLegAmount": "po tej stronie"},"discarded": "Usunięte z tej przestrzeni:","noneLeft": "W tym zestawie nie ma już reguł dopasowania. Nic nie jest tu dopasowywane automatycznie.",@@ -2559,6 +2586,14 @@"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ąć."+ "importOverwriteWarning": "Import zastępuje reguły dopasowania tej przestrzeni wraz z ich kolejnością. Tego nie da się cofnąć.",+ "card": {+ "transfers": "Reguły Przelewów",+ "transfersHint": "Jak ustalamy, że dwa zapisy to ten sam przelew między twoimi kontami.",+ "invoices": "Reguły Faktur",+ "invoicesHint": "Jak ustalamy, która płatność rozlicza którą fakturę.",+ "recurring": "Reguły Cyklicznych",+ "recurringHint": "Jak ustalamy, że obciążenie to rachunek, którego już oczekiwałeś."+ }}}diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex d1017b81..afccb735 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -2267,7 +2267,9 @@"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"+ "inactive": "Não usada aqui",+ "transfers": "Transferências",+ "transfersHint": "entre as suas próprias contas"},"rule": {"sameClientExact": "Pessoa conhecida, valor exato",@@ -2277,7 +2279,10 @@"sameAccountExact": "Mesma conta, valor exato","unknown": "Regra","partPayment": "Pessoa conhecida, parte do valor",- "severalInvoices": "Pessoa conhecida, várias faturas de uma vez"+ "severalInvoices": "Pessoa conhecida, várias faturas de uma vez",+ "destinationNamed": "A descrição nomeia a outra conta",+ "exactAmountNearby": "Valor exato, data próxima",+ "closeAmountWiderWindow": "Valor aproximado, janela maior"},"outcome": {"link": "Liga sozinho",@@ -2305,9 +2310,14 @@"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"+ "amountSet": "até {{count}} faturas somam esse valor",+ "differentAccount": "duas contas diferentes",+ "accountTypes": "um dos lados é uma conta do tipo {{kinds}}",+ "accountNamed": "uma das descrições nomeia a outra conta",+ "closestDate": "a data mais próxima vence",+ "uniqueCandidate": "só um candidato serve"},- "newRule": "Nova regra de conciliação",+ "newRule": "Nova regra de vínculo","saved": "Regra salva","reset": "Regra restaurada","restore": "Voltar ao padrão",@@ -2345,10 +2355,15 @@"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.",+ "triggerHint": "O vínculo 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."+ "amountBandHint": "Sobre o pagamento em si: um tamanho que você quer, ou não quer, que esta regra trate.",+ "transferSignals": "O que faz disso uma transferência",+ "transferSignalsHint": "Os dois lados estão sempre em contas diferentes. Aqui você diz o que mais precisa ser verdade antes de confiar no par.",+ "accountTypes": "Só quando um dos lados for um destes",+ "amountMatchHintTransfer": "Comparado com o outro lado, na mesma moeda. Moedas diferentes nunca casam sozinhas; você ainda pode ligar as duas pontas à mão.",+ "windowHintTransfer": "O dinheiro raramente cai no dia em que saiu. Os dois lados contam a partir do outro registro, então dois dias para cada lado cobrem um fim de semana."},"counterparty": {"any": "Qualquer um",@@ -2369,7 +2384,7 @@},"queue": {"title": "Esperando você",- "hint": "Conciliações que precisam da sua confirmação.",+ "hint": "Vínculos que precisam da sua confirmação.","empty": "Nada para revisar. Tudo casou sozinho.","aPayment": "Um pagamento","maySettle": "pode quitar {{name}}",@@ -2378,7 +2393,13 @@"declineHint": "Não é isso. Este par não será sugerido de novo.","linked": "Ligado","declined": "Descartado. Não perguntamos de novo",- "covers": "cobre"+ "covers": "cobre",+ "mayPairWith": "pode ser a outra metade de {{name}}",+ "kind": {+ "transaction": "Transferência",+ "invoice": "Fatura",+ "recurring": "Recorrente"+ }},"evidence": {"amountExact": "valor bate exatamente",@@ -2386,7 +2407,8 @@"knownPayer": "pessoa conhecida","unknownPayer": "pessoa não identificada","sameDay": "mesmo dia",- "daysApart": "{{days}} dias de diferença"+ "daysApart_one": "{{count}} dia de diferença",+ "daysApart_other": "{{count}} dias de diferença"},"direction": {"any": "Tanto faz",@@ -2398,7 +2420,8 @@"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"+ "matchHint": "O quão perto o pagamento e a promessa precisam estar",+ "matchHintTransfer": "O quão perto os dois registros precisam estar"},"trigger": {"money_arrives": "Quando o dinheiro entra ou sai",@@ -2409,7 +2432,7 @@"bothHint": "A regra vale nos dois sentidos."},"history": {- "title": "O que a conciliação fez",+ "title": "O que o vínculo automático fez","hint": "Mais recentes primeiro.","byPerson": "por você","byRules": "pelas regras",@@ -2423,12 +2446,10 @@"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."+ "empty": "Nada ainda. Isto se preenche conforme o vínculo automático liga, pergunta e é respondido."},"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",@@ -2443,17 +2464,29 @@"thePayment": "o pagamento","acrossInvoices": "em {{count}} faturas","dueOn": "vence {{date}}",- "totalOf": "total de {{amount}}"+ "totalOf": "total de {{amount}}",+ "otherLeg": "A outra ponta",+ "thisLeg": "Esta ponta",+ "otherLegAmount": "na outra ponta",+ "thisLegAmount": "nesta ponta"},"discarded": "Excluídas deste espaço:",- "noneLeft": "Nenhuma regra de conciliação neste conjunto. Nada aqui é conciliado automaticamente.",+ "noneLeft": "Nenhuma regra neste conjunto. Nada aqui é vinculado 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",+ "exported": "Regras de vínculo baixadas","imported": "{{imported}} regras importadas ({{skipped}} ignoradas)",- "invalidImportFile": "Este não é um arquivo de regras de conciliação",- "importConfirmTitle": "Importar regras de conciliação?",+ "invalidImportFile": "Este não é um arquivo de regras de vínculo",+ "importConfirmTitle": "Importar regras de vínculo?","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."+ "importOverwriteWarning": "A importação substitui as regras deste conjunto, inclusive a ordem delas. Não dá para desfazer.",+ "card": {+ "transfers": "Regras de Transferência",+ "transfersHint": "Como decidimos que dois registros são a mesma transferência entre as suas contas.",+ "invoices": "Regras de Fatura",+ "invoicesHint": "Como decidimos qual pagamento quita qual fatura.",+ "recurring": "Regras de Recorrentes",+ "recurringHint": "Como decidimos que uma cobrança é a conta que você já esperava."+ }}}diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.jsonindex 237259f9..fbf1bb29 100644--- a/frontend/src/locales/pt-PT.json+++ b/frontend/src/locales/pt-PT.json@@ -2267,7 +2267,9 @@"invoicesHint": "contra o que tem a receber e a pagar","recurring": "Recorrentes","recurringHint": "contra o que já estava à espera",- "inactive": "Não usada aqui"+ "inactive": "Não usada aqui",+ "transfers": "Transferências",+ "transfersHint": "entre as suas próprias contas"},"rule": {"sameClientExact": "Pessoa conhecida, valor exato",@@ -2277,7 +2279,10 @@"sameAccountExact": "Mesma conta, valor exato","unknown": "Regra","partPayment": "Pessoa conhecida, parte do valor",- "severalInvoices": "Pessoa conhecida, várias faturas de uma vez"+ "severalInvoices": "Pessoa conhecida, várias faturas de uma vez",+ "destinationNamed": "A descrição nomeia a outra conta",+ "exactAmountNearby": "Valor exato, data próxima",+ "closeAmountWiderWindow": "Valor aproximado, janela maior"},"outcome": {"link": "Liga sozinho",@@ -2305,9 +2310,14 @@"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"+ "amountSet": "até {{count}} faturas somam esse valor",+ "differentAccount": "duas contas diferentes",+ "accountTypes": "um dos lados é uma conta do tipo {{kinds}}",+ "accountNamed": "uma das descrições nomeia a outra conta",+ "closestDate": "a data mais próxima vence",+ "uniqueCandidate": "só um candidato serve"},- "newRule": "Nova regra de conciliação",+ "newRule": "Nova regra de vínculo","saved": "Regra guardada","reset": "Regra restaurada","restore": "Voltar ao valor por omissão",@@ -2345,10 +2355,15 @@"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.",+ "triggerHint": "O vínculo 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."+ "amountBandHint": "Sobre o pagamento em si: um tamanho que quer, ou não, que esta regra trate.",+ "transferSignals": "O que faz disto uma transferência",+ "transferSignalsHint": "Os dois lados estão sempre em contas diferentes. Aqui indica o que mais precisa de ser verdade antes de confiar no par.",+ "accountTypes": "Só quando um dos lados for um destes",+ "amountMatchHintTransfer": "Comparado com o outro lado, na mesma moeda. Moedas diferentes nunca casam sozinhas; ainda pode ligar as duas pontas à mão.",+ "windowHintTransfer": "O dinheiro raramente chega no dia em que saiu. Os dois lados contam a partir do outro registo, por isso dois dias para cada lado cobrem um fim de semana."},"counterparty": {"any": "Qualquer um",@@ -2369,7 +2384,7 @@},"queue": {"title": "À sua espera",- "hint": "Conciliações que precisam da sua confirmação.",+ "hint": "Vínculos que precisam da sua confirmação.","empty": "Nada para rever. Correspondeu tudo sozinho.","aPayment": "Um pagamento","maySettle": "pode liquidar {{name}}",@@ -2378,7 +2393,13 @@"declineHint": "Não é isso. Este par não voltará a ser sugerido.","linked": "Ligado","declined": "Descartado. Não voltamos a perguntar",- "covers": "cobre"+ "covers": "cobre",+ "mayPairWith": "pode ser a outra metade de {{name}}",+ "kind": {+ "transaction": "Transferência",+ "invoice": "Fatura",+ "recurring": "Recorrente"+ }},"evidence": {"amountExact": "o valor corresponde exatamente",@@ -2386,7 +2407,8 @@"knownPayer": "pessoa conhecida","unknownPayer": "pessoa não identificada","sameDay": "mesmo dia",- "daysApart": "{{days}} dias de diferença"+ "daysApart_one": "{{count}} dia de diferença",+ "daysApart_other": "{{count}} dias de diferença"},"direction": {"any": "Tanto faz",@@ -2398,7 +2420,8 @@"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"+ "matchHint": "Quão perto o pagamento e a promessa têm de estar",+ "matchHintTransfer": "O quão perto os dois registos precisam de estar"},"trigger": {"money_arrives": "Quando o dinheiro entra ou sai",@@ -2409,7 +2432,7 @@"bothHint": "A regra vale nos dois sentidos."},"history": {- "title": "O que a conciliação fez",+ "title": "O que o vínculo automático fez","hint": "Mais recentes primeiro.","byPerson": "por si","byRules": "pelas regras",@@ -2423,12 +2446,10 @@"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."+ "empty": "Nada ainda. Isto preenche-se à medida que o vínculo automático liga, pergunta e é respondido."},"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",@@ -2443,17 +2464,29 @@"thePayment": "o pagamento","acrossInvoices": "em {{count}} faturas","dueOn": "vence {{date}}",- "totalOf": "total de {{amount}}"+ "totalOf": "total de {{amount}}",+ "otherLeg": "A outra ponta",+ "thisLeg": "Esta ponta",+ "otherLegAmount": "na outra ponta",+ "thisLegAmount": "nesta ponta"},"discarded": "Eliminadas deste espaço:",- "noneLeft": "Nenhuma regra de conciliação neste conjunto. Nada aqui é conciliado automaticamente.",+ "noneLeft": "Nenhuma regra neste conjunto. Nada aqui é vinculado 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",+ "exported": "Regras de vínculo transferidas","imported": "{{imported}} regras importadas ({{skipped}} ignoradas)",- "invalidImportFile": "Este não é um ficheiro de regras de conciliação",- "importConfirmTitle": "Importar regras de conciliação?",+ "invalidImportFile": "Este não é um ficheiro de regras de vínculo",+ "importConfirmTitle": "Importar regras de vínculo?","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."+ "importOverwriteWarning": "A importação substitui as regras deste conjunto, incluindo a ordem. Não é possível anular.",+ "card": {+ "transfers": "Regras de Transferência",+ "transfersHint": "Como decidimos que dois registos são a mesma transferência entre as suas contas.",+ "invoices": "Regras de Fatura",+ "invoicesHint": "Como decidimos qual pagamento liquida qual fatura.",+ "recurring": "Regras de Recorrentes",+ "recurringHint": "Como decidimos que uma cobrança é a conta que já esperava."+ }}}diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 31cf7db2..4fb290a2 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -2279,7 +2279,9 @@"invoicesHint": "с тем, что вам должны и что должны вы","recurring": "Регулярные","recurringHint": "с тем, что вы уже ожидали",- "inactive": "Здесь не используется"+ "inactive": "Здесь не используется",+ "transfers": "Переводы",+ "transfersHint": "между своими счетами"},"rule": {"sameClientExact": "Известный человек, точная сумма",@@ -2289,7 +2291,10 @@"sameAccountExact": "Тот же счёт, точная сумма","unknown": "Правило","partPayment": "Известный человек, часть суммы",- "severalInvoices": "Известный человек, несколько счетов сразу"+ "severalInvoices": "Известный человек, несколько счетов сразу",+ "destinationNamed": "Описание называет другой счёт",+ "exactAmountNearby": "Точная сумма, близкая дата",+ "closeAmountWiderWindow": "Близкая сумма, более широкое окно"},"outcome": {"link": "Связывает само",@@ -2317,7 +2322,12 @@"onArrival": "когда деньги приходят или уходят","onIssue": "когда выставляется счёт","amountPartial": "сумма покрывает часть долга",- "amountSet": "до {{count}} счетов дают эту сумму"+ "amountSet": "до {{count}} счетов дают эту сумму",+ "differentAccount": "два разных счёта",+ "accountTypes": "одна из сторон — счёт типа {{kinds}}",+ "accountNamed": "одно из описаний называет другой счёт",+ "closestDate": "побеждает ближайшая дата",+ "uniqueCandidate": "подходит только один кандидат"},"newRule": "Новое правило сопоставления","saved": "Правило сохранено",@@ -2360,7 +2370,12 @@"triggerHint": "Сопоставление происходит в два момента, и доказательства в них разные.","amountMatch": "Насколько точной должна быть сумма","amountMatchHint": "Сравнивается с остатком долга, а не с исходной суммой.",- "amountBandHint": "О самом платеже: размер, который это правило должно обрабатывать или нет."+ "amountBandHint": "О самом платеже: размер, который это правило должно обрабатывать или нет.",+ "transferSignals": "Что делает это переводом",+ "transferSignalsHint": "Обе стороны всегда на разных счетах. Здесь вы указываете, что ещё должно совпасть, прежде чем доверять паре.",+ "accountTypes": "Только когда одна из сторон — одна из этих",+ "amountMatchHintTransfer": "Сравнивается с другой стороной, в той же валюте. Разные валюты никогда не сопоставляются сами; связать обе стороны вручную по-прежнему можно.",+ "windowHintTransfer": "Деньги редко приходят в тот же день, когда ушли. Обе стороны считаются от другой записи, поэтому два дня с каждой стороны покрывают выходные."},"counterparty": {"any": "Любой",@@ -2390,7 +2405,13 @@"declineHint": "Не то. Эту пару больше не предложим.","linked": "Связано","declined": "Отклонено. Больше не спросим",- "covers": "покрывает"+ "covers": "покрывает",+ "mayPairWith": "возможно, это вторая половина {{name}}",+ "kind": {+ "transaction": "Перевод",+ "invoice": "Счёт",+ "recurring": "Повторяющийся"+ }},"evidence": {"amountExact": "сумма совпадает точно",@@ -2398,7 +2419,10 @@"knownPayer": "известный человек","unknownPayer": "человек не определён","sameDay": "тот же день",- "daysApart": "разница {{days}} дней"+ "daysApart_one": "разница {{count}} день",+ "daysApart_few": "разница {{count}} дня",+ "daysApart_many": "разница {{count}} дней",+ "daysApart_other": "разница {{count}} дней"},"direction": {"any": "Неважно",@@ -2410,7 +2434,8 @@"which": "На какие деньги оно смотрит","whichHint": "Оставьте всё пустым, и оно смотрит на все","match": "Когда это считается совпадением",- "matchHint": "Насколько близко должны сойтись платёж и обязательство"+ "matchHint": "Насколько близко должны сойтись платёж и обязательство",+ "matchHintTransfer": "Насколько близко должны быть две записи"},"trigger": {"money_arrives": "Когда деньги приходят или уходят",@@ -2439,8 +2464,6 @@},"moveUp": "Проверять это раньше","moveDown": "Проверять это позже",- "matchingTitle": "Правила сопоставления",- "matchingHint": "Как каждый платёж связывается с тем, что он закрывает.","pair": {"owed": "Что причитается","arrived": "Что прошло",@@ -2455,7 +2478,11 @@"thePayment": "платёж","acrossInvoices": "на {{count}} счетов","dueOn": "срок {{date}}",- "totalOf": "итого {{amount}}"+ "totalOf": "итого {{amount}}",+ "otherLeg": "Другая сторона",+ "thisLeg": "Эта сторона",+ "otherLegAmount": "на другой стороне",+ "thisLegAmount": "на этой стороне"},"discarded": "Удалены из этого пространства:","noneLeft": "В этом наборе не осталось правил сопоставления. Здесь ничего не сопоставляется автоматически.",@@ -2466,6 +2493,14 @@"invalidImportFile": "Это не файл правил сопоставления","importConfirmTitle": "Импортировать правила сопоставления?","importConfirmDescription": "Файл {{file}} содержит правил: {{count}}.",- "importOverwriteWarning": "Импорт заменит правила сопоставления этого пространства вместе с их порядком. Отменить нельзя."+ "importOverwriteWarning": "Импорт заменит правила сопоставления этого пространства вместе с их порядком. Отменить нельзя.",+ "card": {+ "transfers": "Правила переводов",+ "transfersHint": "Как мы решаем, что две записи — это один перевод между вашими счетами.",+ "invoices": "Правила счетов",+ "invoicesHint": "Как мы решаем, какой платёж закрывает какой счёт.",+ "recurring": "Правила повторяющихся",+ "recurringHint": "Как мы решаем, что списание — это счёт, который вы уже ждали."+ }}}diff --git a/frontend/src/locales/sk.json b/frontend/src/locales/sk.jsonindex 2b2aec56..16e625b9 100644--- a/frontend/src/locales/sk.json+++ b/frontend/src/locales/sk.json@@ -2406,7 +2406,9 @@"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"+ "inactive": "Tu sa nepoužíva",+ "transfers": "Prevody",+ "transfersHint": "medzi vlastnými účtami"},"rule": {"sameClientExact": "Známa osoba, presná suma",@@ -2416,7 +2418,10 @@"sameAccountExact": "Rovnaký účet, presná suma","unknown": "Pravidlo","partPayment": "Známa osoba, časť sumy",- "severalInvoices": "Známa osoba, viac faktúr naraz"+ "severalInvoices": "Známa osoba, viac faktúr naraz",+ "destinationNamed": "Popis uvádza druhý účet",+ "exactAmountNearby": "Presná suma, blízky dátum",+ "closeAmountWiderWindow": "Podobná suma, širšie okno"},"outcome": {"link": "Spáruje samo",@@ -2444,7 +2449,12 @@"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"+ "amountSet": "až {{count}} faktúr dá túto sumu",+ "differentAccount": "dva rôzne účty",+ "accountTypes": "jedna strana je účet typu {{kinds}}",+ "accountNamed": "jeden z popisov uvádza druhý účet",+ "closestDate": "vyhráva najbližší dátum",+ "uniqueCandidate": "vyhovuje len jeden kandidát"},"newRule": "Nové pravidlo párovania","saved": "Pravidlo uložené",@@ -2487,7 +2497,12 @@"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."+ "amountBandHint": "O samotnej platbe: veľkosť, ktorú má toto pravidlo riešiť alebo nie.",+ "transferSignals": "Čo z toho robí prevod",+ "transferSignalsHint": "Obe strany sú vždy na rôznych účtoch. Tu určíte, čo ešte musí platiť, kým páru dôverujeme.",+ "accountTypes": "Len keď je jedna strana jednou z týchto",+ "amountMatchHintTransfer": "Porovnáva sa s druhou stranou, v tej istej mene. Rôzne meny sa nikdy nespárujú samy; obe strany stále môžete prepojiť ručne.",+ "windowHintTransfer": "Peniaze málokedy dorazia v deň, keď odišli. Obe strany sa počítajú od druhého záznamu, takže dva dni na každú stranu pokryjú víkend."},"counterparty": {"any": "Ktokoľvek",@@ -2517,7 +2532,13 @@"declineHint": "Toto to nie je. Tento pár už nebudeme navrhovať.","linked": "Spárované","declined": "Zamietnuté. Už sa nespýtame",- "covers": "pokrýva"+ "covers": "pokrýva",+ "mayPairWith": "môže byť druhou polovicou {{name}}",+ "kind": {+ "transaction": "Prevod",+ "invoice": "Faktúra",+ "recurring": "Opakované"+ }},"evidence": {"amountExact": "suma sedí presne",@@ -2525,7 +2546,10 @@"knownPayer": "známa osoba","unknownPayer": "osoba neurčená","sameDay": "rovnaký deň",- "daysApart": "rozdiel {{days}} dní"+ "daysApart_one": "rozdiel {{count}} deň",+ "daysApart_few": "rozdiel {{count}} dni",+ "daysApart_many": "rozdiel {{count}} dňa",+ "daysApart_other": "rozdiel {{count}} dní"},"direction": {"any": "Je to jedno",@@ -2537,7 +2561,8 @@"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úť"+ "matchHint": "Ako presne si musia platba a záväzok sadnúť",+ "matchHintTransfer": "Ako blízko musia byť oba záznamy"},"trigger": {"money_arrives": "Keď peniaze prídu alebo odídu",@@ -2566,8 +2591,6 @@},"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",@@ -2582,7 +2605,11 @@"thePayment": "platba","acrossInvoices": "na {{count}} faktúr","dueOn": "splatnosť {{date}}",- "totalOf": "spolu {{amount}}"+ "totalOf": "spolu {{amount}}",+ "otherLeg": "Druhá strana",+ "thisLeg": "Táto strana",+ "otherLegAmount": "na druhej strane",+ "thisLegAmount": "na tejto strane"},"discarded": "Odstránené z tohto priestoru:","noneLeft": "V tejto skupine už nie sú žiadne pravidlá párovania. Nič sa tu nepáruje automaticky.",@@ -2593,6 +2620,14 @@"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ť."+ "importOverwriteWarning": "Import nahradí pravidlá párovania tohto priestoru vrátane ich poradia. Nedá sa to vrátiť.",+ "card": {+ "transfers": "Pravidlá prevodov",+ "transfersHint": "Ako určujeme, že dva záznamy sú ten istý prevod medzi vašimi účtami.",+ "invoices": "Pravidlá faktúr",+ "invoicesHint": "Ako určujeme, ktorá platba vyrovnáva ktorú faktúru.",+ "recurring": "Pravidlá opakovaných",+ "recurringHint": "Ako určujeme, že odpis je účet, ktorý ste už očakávali."+ }}}diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 2ff5de99..92be82f3 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -2279,7 +2279,9 @@"invoicesHint": "з тим, що вам винні і що винні ви","recurring": "Регулярні","recurringHint": "з тим, що ви вже очікували",- "inactive": "Тут не використовується"+ "inactive": "Тут не використовується",+ "transfers": "Перекази",+ "transfersHint": "між власними рахунками"},"rule": {"sameClientExact": "Відома особа, точна сума",@@ -2289,7 +2291,10 @@"sameAccountExact": "Той самий рахунок, точна сума","unknown": "Правило","partPayment": "Відома особа, частина суми",- "severalInvoices": "Відома особа, кілька рахунків одразу"+ "severalInvoices": "Відома особа, кілька рахунків одразу",+ "destinationNamed": "Опис називає інший рахунок",+ "exactAmountNearby": "Точна сума, близька дата",+ "closeAmountWiderWindow": "Близька сума, ширше вікно"},"outcome": {"link": "Зв’язує саме",@@ -2317,7 +2322,12 @@"onArrival": "коли гроші приходять або йдуть","onIssue": "коли виставляється рахунок","amountPartial": "сума покриває частину боргу",- "amountSet": "до {{count}} рахунків дають цю суму"+ "amountSet": "до {{count}} рахунків дають цю суму",+ "differentAccount": "два різні рахунки",+ "accountTypes": "одна зі сторін — рахунок типу {{kinds}}",+ "accountNamed": "один з описів називає інший рахунок",+ "closestDate": "перемагає найближча дата",+ "uniqueCandidate": "підходить лише один кандидат"},"newRule": "Нове правило зіставлення","saved": "Правило збережено",@@ -2360,7 +2370,12 @@"triggerHint": "Зіставлення відбувається у два моменти, і докази в них різні.","amountMatch": "Наскільки точною має бути сума","amountMatchHint": "Порівнюється із залишком боргу, а не з початковою сумою.",- "amountBandHint": "Про сам платіж: розмір, який це правило має опрацьовувати чи ні."+ "amountBandHint": "Про сам платіж: розмір, який це правило має опрацьовувати чи ні.",+ "transferSignals": "Що робить це переказом",+ "transferSignalsHint": "Обидві сторони завжди на різних рахунках. Тут ви вказуєте, що ще має збігтися, перш ніж довіряти парі.",+ "accountTypes": "Лише коли одна зі сторін — одна з цих",+ "amountMatchHintTransfer": "Порівнюється з іншою стороною, у тій самій валюті. Різні валюти ніколи не зіставляються самі; зв’язати обидві сторони вручну досі можна.",+ "windowHintTransfer": "Гроші рідко надходять того самого дня, коли пішли. Обидві сторони рахуються від іншого запису, тож два дні з кожного боку покривають вихідні."},"counterparty": {"any": "Будь-хто",@@ -2390,7 +2405,13 @@"declineHint": "Не те. Цю пару більше не пропонуватимемо.","linked": "Зв’язано","declined": "Відхилено. Більше не запитаємо",- "covers": "покриває"+ "covers": "покриває",+ "mayPairWith": "можливо, це друга половина {{name}}",+ "kind": {+ "transaction": "Переказ",+ "invoice": "Рахунок",+ "recurring": "Повторюваний"+ }},"evidence": {"amountExact": "сума збігається точно",@@ -2398,7 +2419,10 @@"knownPayer": "відома особа","unknownPayer": "особу не визначено","sameDay": "той самий день",- "daysApart": "різниця {{days}} днів"+ "daysApart_one": "різниця {{count}} день",+ "daysApart_few": "різниця {{count}} дні",+ "daysApart_many": "різниця {{count}} днів",+ "daysApart_other": "різниця {{count}} днів"},"direction": {"any": "Байдуже",@@ -2410,7 +2434,8 @@"which": "На які гроші воно дивиться","whichHint": "Залиште все порожнім, і воно дивиться на всі","match": "Коли це вважається збігом",- "matchHint": "Наскільки близько мають зійтися платіж і зобов’язання"+ "matchHint": "Наскільки близько мають зійтися платіж і зобов’язання",+ "matchHintTransfer": "Наскільки близько мають бути два записи"},"trigger": {"money_arrives": "Коли гроші приходять або йдуть",@@ -2439,8 +2464,6 @@},"moveUp": "Перевіряти це раніше","moveDown": "Перевіряти це пізніше",- "matchingTitle": "Правила зіставлення",- "matchingHint": "Як кожен платіж пов'язується з тим, що він закриває.","pair": {"owed": "Що належить","arrived": "Що пройшло",@@ -2455,7 +2478,11 @@"thePayment": "платіж","acrossInvoices": "на {{count}} рахунків","dueOn": "термін {{date}}",- "totalOf": "разом {{amount}}"+ "totalOf": "разом {{amount}}",+ "otherLeg": "Інша сторона",+ "thisLeg": "Ця сторона",+ "otherLegAmount": "на іншій стороні",+ "thisLegAmount": "на цій стороні"},"discarded": "Видалені з цього простору:","noneLeft": "У цьому наборі не лишилося правил зіставлення. Тут нічого не зіставляється автоматично.",@@ -2466,6 +2493,14 @@"invalidImportFile": "Це не файл правил зіставлення","importConfirmTitle": "Імпортувати правила зіставлення?","importConfirmDescription": "Файл {{file}} містить правил: {{count}}.",- "importOverwriteWarning": "Імпорт замінює правила зіставлення цього простору разом з їхнім порядком. Скасувати не можна."+ "importOverwriteWarning": "Імпорт замінює правила зіставлення цього простору разом з їхнім порядком. Скасувати не можна.",+ "card": {+ "transfers": "Правила переказів",+ "transfersHint": "Як ми визначаємо, що два записи — це один переказ між вашими рахунками.",+ "invoices": "Правила рахунків",+ "invoicesHint": "Як ми визначаємо, який платіж закриває який рахунок.",+ "recurring": "Правила повторюваних",+ "recurringHint": "Як ми визначаємо, що списання — це рахунок, на який ви вже чекали."+ }}}diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsxindex 5180dd82..084ef12e 100644--- a/frontend/src/pages/rules.tsx+++ b/frontend/src/pages/rules.tsx@@ -160,7 +160,7 @@ const FILTER_CONTROL_CLASS = 'h-7 rounded-md border border-border bg-backgroundexport default function RulesPage() {const { t } = useTranslation()const queryClient = useQueryClient()- const { canWrite, hasModule } = useWorkspace()+ const { canWrite } = useWorkspace()const [dialogOpen, setDialogOpen] = useState(false)const [packsDialogOpen, setPacksDialogOpen] = useState(false)const [importDialogOpen, setImportDialogOpen] = useState(false)@@ -407,12 +407,12 @@ export default function RulesPage() {// 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')+ // Matching used to serve only sets that belonged to a module, so a+ // personal workspace had no rules here, no queue and no history, and+ // the tabs were hidden rather than left empty. Transfer pairing+ // changed that: it runs for everybody, it has always run, and it is+ // now written down where its owner can read it. So there is no+ // workspace without matching any more, and nothing left to hide.// 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@@ -421,9 +421,7 @@ export default function RulesPage() {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 tab: 'rules' | 'queue' | 'history' = askedconst setTab = (next: 'rules' | 'queue' | 'history') => {// `replace`, so the back button leaves the page rather than walking// back through tabs somebody clicked on the way.@@ -435,7 +433,6 @@ export default function RulesPage() {const { data: pending } = useQuery({queryKey: ['reconciliation-suggestions'],queryFn: reconciliationApi.suggestions,- enabled: matching,})return (@@ -449,7 +446,7 @@ export default function RulesPage() {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@@ -468,13 +465,13 @@ export default function RulesPage() {</span>),},- { value: 'history' as const, label: t('rules.tab.history') }] : []),+ { value: 'history' as const, label: t('rules.tab.history') },]}/></div>- {matching && tab === 'queue' && <ReconciliationQueue canWrite={canWrite} />}- {matching && tab === 'history' && <ReconciliationHistory />}+ {tab === 'queue' && <ReconciliationQueue canWrite={canWrite} />}+ {tab === 'history' && <ReconciliationHistory />}<div className={tab === 'rules' ? '' : 'hidden'}><SectionCard>@@ -695,11 +692,10 @@ export default function RulesPage() {{/* Matching rules below categorization rules, because they are thesame promise made twice: the software decides things about yourmoney, 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. */}+ One card per set, and transfers leads, because that is the set+ every workspace has whether or not it ever asked for one. */}<div className="mt-6 space-y-6">- {matching && <ReconciliationRules canWrite={canWrite} />}+ <ReconciliationRules canWrite={canWrite} /></div></div>diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex 893ca4a9..ad36e088 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -1386,6 +1386,23 @@ export interface ReconciliationConditions {foreign?: boolean}same_account?: boolean+ /** The defining condition of a transfer: the two legs are on different+ * accounts. The inverse of `same_account`, and its own key so a rule+ * reads as a list of things that must be true. */+ different_account?: boolean+ /** Only pairs where one of the two legs sits on an account of this+ * kind. Either leg is enough: a rule that exists to be careful about+ * credit cards has to fire whichever end the card is on. */+ account_types?: ('checking' | 'savings' | 'credit_card' | 'investment' | 'wallet')[]+ /** One side's statement text has to name the other side's account. The+ * signal that tells two same-day transfers of the same amount apart,+ * when one line reads "To FORTUNEO ACCOUNT" and the other does not. */+ account_name_in_description?: boolean+ /** How to separate candidates that all fit. `closest_date` takes the+ * nearest in time and only gives up when nothing separates them, which+ * is different from `unique_candidate` refusing whenever there is more+ * than one. */+ tie_break?: 'closest_date'unique_candidate?: boolean}@@ -1469,7 +1486,7 @@ export interface ReconciliationSuggestion {id: stringnode: stringstrategy_id: string- expectation_kind: 'invoice' | 'recurring'+ expectation_kind: 'invoice' | 'recurring' | 'transaction'expectation_id: stringexpectation_label?: string | nullamount: string@@ -1489,7 +1506,7 @@ export interface ReconciliationSuggestion {* case; several when one payment is offered against several invoices,* which is answered whole or not at all. */covers: {- expectation_kind: 'invoice' | 'recurring'+ expectation_kind: 'invoice' | 'recurring' | 'transaction'expectation_id: stringlabel?: string | nullamount: string@@ -1501,6 +1518,10 @@ export interface ReconciliationSuggestion {currency?: string | nulldate: stringtype: string+ /** Which account the money moved on. With transfers in the queue the+ * question is about accounts, so a row naming only the other side+ * leaves the reader to work out which of theirs this one is. */+ account_id?: string | null} | null}@@ -1514,7 +1535,7 @@ export interface ReconciliationHistoryEvent {id: stringat: stringaction: 'linked' | 'suggested' | 'accepted' | 'declined' | 'expired' | 'unlinked'- expectation_kind: 'invoice' | 'recurring'+ expectation_kind: 'invoice' | 'recurring' | 'transaction'expectation_id: stringexpectation_label?: string | nullamount: string