Files
accounted/components/bookkeeping/MatchTransactionInvoicePreview.tsx
T
Jakob Wennberg cce0de5704 feat(mcp): already-explained voucher guard at stage and commit for match_batch_allocate (#2294) (#2346)
* feat(mcp): already-explained voucher guard at stage and commit for match_batch_allocate

The dashboard match-batch route refused BATCH_TX_POSSIBLE_DUPLICATE when
posted, unlinked vouchers already summed to the bank row (PR #2300), but the
MCP door (gnubok_match_batch_allocate staging + commitMatchBatchAllocate)
called the RPC with no guard, so an agent could book a Bankgirot aggregate a
second time. The detector existed once; the guard lived in one door.

One shared decision helper, lib/invoices/already-explained-guard.ts, now
sits on top of the existing detectors (no fork) and is called by the
dashboard route, the MCP staging tools and the commit executors:

- gnubok_match_batch_allocate refuses to stage, coded
  BATCH_TX_POSSIBLE_DUPLICATE, naming the vouchers, the reconcile_match /
  link_transaction_to_journal_entry call that resolves the row, and the
  exact force + expected_journal_entry_ids binding.
- commitMatchBatchAllocate runs the same guard before the RPC and
  re-validates a staged force binding against the set detected at commit,
  so a stale approval cannot book a duplicate; 409 auto-rejects with the
  vouchers in result_data.
- force + expected_journal_entry_ids on the tool mirror MatchBatchSchema;
  an honoured override stages with a compliance_warning and, after the
  booking succeeds, writes BankTransactionDuplicateDismissed to
  behandlingshistorik (dashboard route included; it only logged before).
- gnubok_match_transaction_to_invoice and commitMatchTransactionInvoice get
  the dashboard's 1:1 soft-duplicate guard (MATCH_INVOICE_POSSIBLE_DUPLICATE
  / MATCH_INVOICE_FORCE_CANDIDATE_MISMATCH) with force +
  expected_journal_entry_id; at commit it runs before the storno.
- Registry: both duplicate codes gain retryable: false and a remediation.

Catalog payload held under the 60K ceiling by trimming the two tools' own
descriptions (59 988 measured, ledger entry in payload-size.bench.test.ts).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6

* docs(decisions): record the 2026-09-06 ten-issue batch's first-principles choices

Carries the DECISIONS.md lines for PRs #2337 #2339 #2340 #2341 #2342 #2343 #2344 #2345 #2346 #2347 in one place so the ten branches do not conflict on this file.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019SaJfqNi4VmsG8FMKq99G6

* fix(mcp): refuse an unverifiable forced override, surface a failed duplicate check, validate the binding (#2294 review)

Review round on PR #2346 (CodeRabbit + compliance):

- guardAlreadyExplained returned 'clear' when the detector threw even with
  force=true, so a forced 1:N override could book without re-validating
  expected_journal_entry_ids and left no behandlingshistorik record. It now
  returns a distinct 'unverifiable' outcome under force (mirrors
  guardDuplicatePaymentVoucher); the dashboard route, the MCP staging tool
  and the commit executor all refuse it with the new registry code
  BATCH_TX_EXPLAINED_CHECK_FAILED (409, retryable, remediation). Regression
  tests on every caller.
- A detector failure without force still fails open at stage time, but no
  longer silently: the tools track onDetectError and stage a
  complianceNote, so preview_data.compliance_warning is set on both
  match_batch_allocate (GenericPreview renders it) and
  match_transaction_invoice (MatchTransactionInvoicePreview now renders
  data.compliance_warning through AttnLine).
- expected_journal_entry_ids / expected_journal_entry_id are validated at
  the MCP boundary (array of 1 to 10 non-empty strings / non-empty string)
  and refused with VALIDATION_ERROR instead of being silently filtered.
  No schema description text added: catalog payload unchanged.
- RoPA: .compliance/ropa.yaml gains bookkeeping.duplicate_dismissal_history
  for the BankTransactionDuplicateDismissed record (Art. 6(1)(c), BFNAR
  2013:2 p. 9.16, retention per BFL 7 kap, stored in processing_history).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 18:56:36 +02:00

103 lines
4.1 KiB
TypeScript

'use client'
import { ArrowDown } from 'lucide-react'
import { AttnLine } from '@/components/ui/attn-line'
import { formatCurrency, formatDate } from '@/lib/utils'
interface MatchTransactionInvoicePreviewProps {
data: Record<string, unknown>
}
/**
* Two-card preview for `match_transaction_invoice` operations. Mirrors
* AttachDocumentPreview's layout so reviewers learn one matching idiom.
*/
export function MatchTransactionInvoicePreview({ data }: MatchTransactionInvoicePreviewProps) {
const txDescription = (data.transaction_description as string) || '-'
const txAmount = data.transaction_amount as number | undefined
const txCurrency = (data.transaction_currency as string) || 'SEK'
const txDate = data.transaction_date as string | undefined
const invoiceNumber = (data.invoice_number as string) || '-'
const invoiceTotal = data.invoice_total as number | undefined
const invoiceCurrency = (data.invoice_currency as string) || txCurrency
const invoiceDate = data.invoice_date as string | undefined
const customerName = data.customer_name as string | undefined
// Staged by the MCP tool when the duplicate check could not run, or when
// force=true books over a voucher that already looks like this payment
// (issue #2294). The server owns the wording; rendered verbatim so the
// /pending card and the agent read the same warning.
const complianceWarning =
typeof data.compliance_warning === 'string' && data.compliance_warning.trim()
? data.compliance_warning
: null
// BFL 5 kap 4§ requires bookings to be made "so soon as possible" relative
// to the affärshändelse, so a transaction and invoice that diverge by more
// than a calendar month deserve a second look before the reviewer approves
// the match. The threshold is editorial, not legislated: it just nudges
// the reviewer; it doesn't block.
const showDateDriftHint =
txDate &&
invoiceDate &&
Math.abs(new Date(txDate).getTime() - new Date(invoiceDate).getTime()) > 31 * 24 * 60 * 60 * 1000
return (
<div className="space-y-3 text-sm">
{complianceWarning && <AttnLine>{complianceWarning}</AttnLine>}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<PreviewCard label="Transaktion">
{txDate && <Row label="Datum" value={formatDate(txDate)} tabular />}
<Row label="Beskrivning" value={txDescription} />
<Row
label="Belopp"
value={typeof txAmount === 'number' ? formatCurrency(txAmount, txCurrency) : '-'}
tabular
/>
</PreviewCard>
<PreviewCard label="Faktura">
<Row label="Nummer" value={invoiceNumber} tabular />
{invoiceDate && <Row label="Fakturadatum" value={formatDate(invoiceDate)} tabular />}
{customerName && <Row label="Kund" value={customerName} />}
{typeof invoiceTotal === 'number' && (
<Row label="Totalt" value={formatCurrency(invoiceTotal, invoiceCurrency)} tabular />
)}
</PreviewCard>
</div>
<div className="flex items-center justify-center text-xs text-muted-foreground">
<ArrowDown className="h-3.5 w-3.5 mr-1" />
matchas mot fakturan
</div>
{showDateDriftHint && (
<p className="text-xs text-muted-foreground">
Transaktionsdatum och fakturadatum skiljer sig med mer än en månad: kontrollera att
matchningen avser rätt affärshändelse.
</p>
)}
</div>
)
}
function PreviewCard({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="rounded-lg border border-border p-3 space-y-1.5">
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
{label}
</p>
{children}
</div>
)
}
function Row({ label, value, tabular }: { label: string; value: string; tabular?: boolean }) {
return (
<div className="flex justify-between gap-3">
<span className="text-xs text-muted-foreground shrink-0">{label}</span>
<span className={`text-sm ${tabular ? 'tabular-nums' : ''} text-right truncate`}>{value}</span>
</div>
)
}