Files
accounted/lib/invoices/__tests__/voucher-matching-fx.test.ts
T
MattssonandClaude Fable 5 f24b26a139 fix: similar-sweep currency remediation, security hardening and v1 API fixes (#1215)
* fix(security): gate replace_sie_import behind owner/admin membership

The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no
company_members lookup, no auth.uid() reference and no unauthorized raise,
while setting gnubok.allow_delete to disarm the BFL immutability and
retention triggers. Any caller holding a company_id and an import id could
hard delete another tenant's verifikationer. Confirmed live in production.

Applies the same fail closed owner/admin guard that undo_sie_import already
carries (migration 20260624120000), resolving the actor from
COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then
revokes EXECUTE from PUBLIC and anon. search_path and the raised
statement_timeout are restated, since CREATE OR REPLACE drops settings that
are not repeated.

userId is a required parameter on replaceSIEImport: the service client has a
NULL auth.uid(), so a caller without an explicit actor now fails to compile
rather than hitting the closed gate at runtime.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(security): validate arcim OAuth callback state server side

The callback route is skipAuth and decoded the state parameter as plain
base64url JSON, trusting consentId and provider from it. A one time code was
minted at flow start and never read. An unauthenticated attacker who learned
a consent id could run an OAuth flow on their own provider account and post
the callback with a forged state, landing their tokens on another tenant's
consent, so the victim's next migration imported the attacker's ledger.

State is now an opaque randomBytes(32) pointer to a provider_otc row,
consumed by a single atomic UPDATE guarded on used_at IS NULL and
expires_at, so a replay loses the row lock race and updates nothing.
provider is read from provider_consents rather than trusted from the client.
provider_otc already existed for exactly this purpose and was never wired up.

Also scopes getConsent to an owning company, closing a cross tenant status
oracle where the preview and migrate paths echoed a consent's status before
the scoped check ran.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(security): scope documents storage to company_id (phase A)

The documents bucket policies matched on auth.uid(), and upload keys were
documents/{userId}/..., so company membership was never consulted. Removing a
member revoked nothing: their session still authenticated and they kept
direct Storage read access to every receipt, supplier invoice and bank
statement they had uploaded. The same bug was fixed for sie-files in
20260416120000; this bucket was left behind.

Phase A is additive. Company scoped policies are added alongside the
uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and
reads accept either layout so nothing breaks mid migration. Phase C, which
drops the old policies, is gated on the backfill reporting zero remaining
legacy prefix objects.

The policy compares the company segment as text rather than casting to uuid
the way sie-files does: this bucket holds keys whose second segment is not a
uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix
qual runs before the cast, so a planner reordering would raise 22P02 and fail
the whole query instead of filtering the row out.

deleteDocument now removes both candidate keys. Removing only the stored
pointer would leave a readable orphan copy of a document the user asked to
erase.

The backfill script is included but has never been run. It defaults to dry
run, refuses .env.local by name, and verifies each copy is readable and
SHA-256 identical before repointing the row.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(security): enforce events:read scope and membership on /api/events

This was the only one of the three validateApiKey call sites with no
downstream guard: v1 and the MCP server both check scope and re-verify
company membership, this route did neither. An events:read scope existed and
was documented as gating the endpoint but was never called, so a legacy key
falling back to DEFAULT_SCOPES read the full log. The bound company id went
straight from the api_keys row into a service role query, so a key whose user
had been removed from the company kept reading.

Adds the scope check before any database access, re-verifies company_members
with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead
of ignoring it, applies minimisePayload so the pull surface can never return
a wider payload than the push surface, and replaces the three flat error
strings with the canonical envelope.

Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is
gated on mutations in with-api-v1, so a read gets the same treatment as every
other v1 read endpoint.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* perf(bookkeeping): sweep remaining journal_entries!inner embeds

A previous refactor removed this pattern from lib/reports and introduced
fetchEntryLines, but the class was never swept. Seventeen sites remained and
had become the top application consumer of production database time:
measured across the resulting query shapes, 32,694 calls and 25,848 seconds
of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at
7,962ms against the 8s statement_timeout, which surfaced to users as 500s on
the booking path.

PostgREST compiles an embed with filters on the embedded side into a
correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops
Postgres reordering the join, so each query walked the whole
journal_entry_lines table across all tenants. Driving from the entries side
instead turns that into two indexed round trips.

Converted sites keep their existing shape: the helper reattaches the parent
entry under the same key the embed produced. Several conversions also remove
a latent silent truncation where an unpaginated query was capped at
PostgREST's 1000 row ceiling.

Two deliberate exceptions. The free text ilike legs of the MCP display query
stay on the embed, because each is capped at legLimit and that cap drives the
truncation contract the tool reports, while the helper is unbounded. The
accounts route moves to the existing get_account_usage_counts RPC instead,
since its embed was a head count and the helper returns rows.

commitEntry's write path is untouched: the change there is confined to the
read query of the pre-commit dimension rule check.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(api): anchor v1 list cursors on created_at

Page two returned page one, forever, while still advertising a fresh
next_cursor. The three routes sorted by and encoded a Postgres date column,
which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor
timestamp as full ISO-8601 and returned null, so the keyset filter was never
applied and has_more never went false. An integrator syncing verifikat looped
on the newest rows indefinitely.

The transactions route already solved this and its comment names the trap;
the fix was never ported. All three now order and encode on created_at with
an id tie break, matching the transactions keyset predicate exactly.
ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change
sort semantics on the route that currently works.

Default ordering therefore moves from business date to insert order. Every
business date is still on the row, and the invoices list gains date_from and
date_to filters so a date range is still reachable; the other two already had
them.

The tests use an in-memory PostgREST that actually evaluates the filters,
because the repo's pass-through mock cannot catch this class of bug: the bug
is that the filter is never sent. They walk to exhaustion with a hard
iteration cap, so an unterminated walk fails instead of hanging.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(api): separate dry run from commit in the idempotency hash

The request hash was built from url.pathname, which excludes the query
string, so a dry run and its commit hashed identically. Following the flow
documented in dry-run.ts, re-issuing the request with the same
Idempotency-Key returned the cached preview with Idempotent-Replayed set and
wrote nothing, while reporting 200. An agent or integrator saw success for a
write that never happened.

dry_run is folded into the hash only when true, not as an unconditional
boolean. Including it as false would change the hash of every ordinary write,
and with a 24h idempotency TTL any key in flight across the deploy would fail
the request_hash comparison and 409 on a legitimate retry. Both hash call
sites now go through one shared helper so they cannot drift into a permanent
cache miss, and dry run responses are no longer stored at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* ci: install the Bedrock SDK out of tree in the compliance review

The Swedish accounting compliance gate had failed ten consecutive runs and so
was posting nothing. With --no-package-lock npm discarded the lockfile and
re-resolved the whole tree from package.json, floating @hookform/resolvers to
5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0.

Installing into the parent of the checkout resolves only that one package, so
an unrelated peer conflict can never take the gate down again. Node still
finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH
would not have worked, as it is CommonJS only. --legacy-peer-deps was
rejected because it masks future genuine peer conflicts and still reifies the
full tree.

The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that
package.json and check:guards enforce after the streaming outage. That drift
went unnoticed because the pin guard only inspects package.json and the
lockfile, never workflow files.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* build(docker): generate crontabs from vercel.json

vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were
byte identical to each other. Self hosted deployments therefore never sent
recurring invoices, never dispatched webhooks and never cleaned up
idempotency keys. tax-deadlines also ran once a year on 2 January instead of
daily, and documents/verify weekly instead of daily.

Extension crons are included rather than excluded. The Dockerfile copies the
whole tree before building, so every extension cron route is compiled into
the image regardless of the enabled preset, and each returns 200 when its
extension is unconfigured, so curl -sf logs no failure. Two such entries were
already present in the crontab for extensions absent from the preset, which
settles the intent.

documents/verify is treated as drift rather than a self hosted concession:
the weekly cadence was present in the hosted crontab too, and the run is
capped at 200 documents walking a nulls-first queue, so weekly drains the
integrity queue seven times slower on a check that exists for BFL retention.

webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day
on self hosted. A gentler tick would silently stretch the first retry, since
the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line
place to change that.

A parity test asserts the path sets match minus a documented exclusion list,
and ratchets three cron routes that are currently scheduled nowhere so they
are named rather than silently rotting.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(observability): add a provider agnostic error sink

There is no error tracking in this codebase: logs go to console and Vercel
retention and nowhere else, nothing alerts on the 16 cron jobs, and seven
code comments across lib, app, components and extensions asserted that Sentry
captures errors when Sentry is not a dependency. The two most recent bug
fixes on this repo were both discovered by customer email.

This adds the sink, not a vendor. No dependency is taken: the interface has a
no-op default and a registration point, so behaviour is unchanged until an
adapter is registered. Releases are tagged from the build id already inlined
by next.config.ts.

Redaction moved out of lib/logger.ts into a leaf module that both the logger
and the sink import, so there is one denylist and no path from application
data to a third party can skip the personnummer regex, including direct sink
calls that bypass the logger. That matters here because these logs carry
personnummer and financial data.

verifyCronSecret now reports its own 401s, which covers all 16 jobs without
touching a route file and catches the case where CRON_SECRET is rotated
without updating the scheduler and every job silently 401s forever. The
threshold is one failure rather than the backup alert's three: suppressing
the first occurrence is precisely how an outage stays invisible.

The seven misleading comments are corrected to describe what the code
actually does, including the two cases that still are not covered: the client
side one, since the sink is server side, and a warn level call that is not
forwarded.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: remediate the 2026-07-26 similar-sweep findings across all surfaces

Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with
one agent per finding; every behavioural fix carries a regression test proven
to fail at HEAD. Full status, corrections to the sweep, refusals and open
decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md.

Structural roots closed:
- resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking
  1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING
- ledger-line-amount.ts: journal_entry_lines.currency labels the document,
  not the amount; SQL pre-filter decoy proven and fixed
- sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the
  exploitable salary payslip-line PATCH and KPI preferences sinks fixed
- tests/schema: migration-replay phantom-column guard (13k+ refs, closed
  CHECK sets, onConflict targets); found 28 real defects, all fixed, all
  four baselines now empty
- three new ratchet guards: sek-labelled-amount, cross-extension-import,
  ungated-extension-route

Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap),
RC input VAT mismatch wired on web + both MCP callers, missing-underlag
resource delegates to the shared RPC predicate, push-notifications consent
polarity fail-closed, deadlines undo honours requested state, silent-failure
and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/
Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites
with isSwedishUserMessage extended.

Also includes the parallel session's MCP invoice tools (update_invoice,
recurring schedules, invoice deliveries) which share files with the sweep
work and are verified green together.

13 new migrations are NOT applied anywhere; they apply via branch merge.
20260726120000 backfills 1247 supplier-invoice rows. pg tests for new
DDL are written but unrun (no local Postgres).

Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0
errors, check:guards passing, MCP payload 57475/57500.

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

* fix(migrations): rename replace_sie_import migration off main's 20260726090000 version

origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping
our replace_sie_import migration on the same version would abort the Supabase
apply with a schema_migrations_pkey duplicate at merge time.

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

* fix(review): remediate pre-publish deep-review findings across all slices

A 13-agent review of the full branch diff surfaced 1 critical, 5 high and
~45 further findings; this commit resolves them in one pass:

- replace_sie_import / undo_sie_import: p_user_id honored only for
  service_role callers; any other caller is pinned to auth.uid()
  (impersonation gate bypass), authz raise errcode 42501 mapped to a
  Swedish 403 in the route, new caller-guard migration for undo
- bulk_book_transactions refuses homogeneous non-SEK batches instead of
  writing foreign magnitudes into SEK ledger columns
- credit-note cap trigger: company-match on credited_invoice_id, no
  cross-tenant figures in exception text
- link_voucher RPCs resolve NULL invoice currency as SEK end to end
- personal-number ciphertext CHECK split into NOT VALID + VALIDATE
- same-currency foreign settlements clear 1510 at booking rate and book
  realized diff to 3960/7960; rate-less foreign write paths refuse
- receivables revaluation covers partially_paid and outstanding amounts
- period lock guard paginates candidates past the PostgREST 1000 cap
- documents: service-client storage removals after authz, dual-layout
  reads in integrity cron and archive export, backfill delete-source
  sweep actually deletes with hash verification and shared-key grouping
- invoice matching normalizes NULL/lowercase currencies (regression),
  duplicate candidates stop claiming amount matches they never ran
- match-invoice aborts on any booking failure (no paid-without-verifikat)
- refresh-exchange-rate reverts on concurrent booking (TOCTOU window)
- KPI preferences upsert arbiter aligned to the company-scoped constraint
- personnummer_last4 stripped from all salary responses incl. MCP tools
- worked-hours batch restores destroyed rows on conflict and error paths
- MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit
  on tag_journal_lines overflow, auto_send schedules stage as high risk
- observability sink redacts emails/IBANs/API keys and keeps redacted
  stacks in prod; assorted small guards (safe-return-to /@, dry_run=True,
  cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings
  call removed)

Full dispositions, deferred items and hand-verified accounting numbers
are documented in the PR body and DECISIONS.md.

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

* feat(personnummer): implement masking and encryption for personal numbers with tests

* fix(review): address CI and compliance-bot findings for PR #1215

pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role
GUC, so both service-role simulations (runAsServiceRole and the
invoice-delivery test's local helper) never satisfied auth.role() =
'service_role' and every legitimate p_user_id path failed closed; the
shared helper now sets both GUC shapes plus SET LOCAL ROLE with a
fail-loud sanity check, and the delivery test reuses it. The link-voucher
migration had recreated both RPCs from pre-rewrite file text,
reintroducing the NULL-unsafe membership pattern the
null-safe-tenant-guards ratchet bans; both guards now use
public.caller_is_company_member() with all currency changes preserved.

Compliance bots: the customers export now emits the standard masked form
instead of raw AES-256-GCM ciphertext in the Org-/personnummer column,
and maskCustomerRow returns a non-round-trippable placeholder on decrypt
failure instead of 500ing the list. MCP parity: gnubok_lock_period's
staging pre-check now runs the exact countUnbookedInPeriod the commit
path enforces (exported from period-service; local mirror deleted), and
gnubok_agi_status resolves AGI state run-scoped so a correction run no
longer renders as already filed.

Declined with evidence: PR-Agent's opening-balances null-zeroing concern
(all mergeable columns are NOT NULL with defaults per 20260713101000).

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

* fix(review): address codex review findings on PR #1215

- restore 20260726140000 to its preview-recorded content and restate the
  NULL-safe tenant guard under 20260727130000: a recorded migration version
  never re-runs, so the in-place edit could not reach the preview branch
- replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap
  warning texts and update the pinned test expectations
- drop the em dash in the fiscal-periods route comment
- strip trailing whitespace in import-existing.test.ts

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

* test(reports): raise timeout on real PDF render tests

renderToBuffer does real @react-pdf layout work and exceeds the 5s
default when the full suite saturates the CPU; tests pass in isolation.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 03:34:56 +02:00

1113 lines
38 KiB
TypeScript

/**
* Foreign-currency voucher matching, both sides of the sub-ledger.
*
* THE BUG THESE COVER: `journal_entry_lines.currency` labels the DOCUMENT, not
* the AMOUNT. `lib/bookkeeping/currency-utils.ts#buildCurrencyMetadata` stamps
* `currency: 'EUR'` + `amount_in_currency` onto a line whose debit/credit
* columns hold SEK. So every "the currencies match, so these amounts are
* comparable" guard passed on exactly the FX rows it existed to catch, and then
* compared a SEK ledger figure against a remainder quoted in the invoice's
* currency.
*
* The customer-invoice matcher made it worse than a bad score: the amount band
* is pushed into SQL, so a SEK `credit_amount` was bounded by a EUR band and
* the one correct voucher was dropped BEFORE scoring ever ran, leaving only
* same-magnitude coincidences behind. That is why the candidate query here runs
* against a mock that actually APPLIES the filters (see
* {@link createFilteringSupabase}) instead of a queued mock that ignores them:
* a queued mock cannot tell a correct pre-filter from a broken one.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest'
import {
findMatchingVouchersForInvoice,
validateVoucherForInvoiceLink,
} from '../voucher-matching'
import {
findMatchingVouchersForSupplierInvoice,
validateVoucherForSupplierInvoiceLink,
} from '../supplier-voucher-matching'
import { makeInvoice, makeSupplierInvoice, createQueuedMockSupabase } from '@/tests/helpers'
// ============================================================
// A mock that actually executes the filters
// ============================================================
type FilterOp = 'eq' | 'gt' | 'gte' | 'lte' | 'like'
interface RecordedFilter {
op: FilterOp
column: string
value: unknown
}
/**
* A `.or('col.op.val,col.op.val', { referencedTable })` call: the conditions
* are ORed with each other and the whole group ANDs with the other filters,
* exactly as PostgREST composes it. The FX prefilter's two-sided floor band
* (floor <= |amount_in_currency| <= ceil) rides on this shape, so the mock has
* to execute it rather than swallow it.
*/
interface RecordedOrGroup {
op: 'or'
conditions: RecordedFilter[]
}
type AnyRecordedFilter = RecordedFilter | RecordedOrGroup
interface FixtureLine {
id: string
account_number: string
debit_amount: number
credit_amount: number
currency: string | null
/** Omitted entirely on rows that predate the FX columns. */
amount_in_currency?: number | string | null
}
interface FixtureEntry {
id: string
voucher_series: string
voucher_number: number
entry_date: string
description: string
status: string
source_type: string
fiscal_period_id: string
company_id: string
journal_entry_lines: FixtureLine[]
}
/**
* SQL comparison semantics, including the part that carries this whole test
* file: a comparison against NULL is UNKNOWN, so the row does NOT survive a
* WHERE clause. A line with no `amount_in_currency` therefore drops out of the
* foreign band by itself, which is correct: it carries no rate, so it cannot be
* expressed in the invoice's currency at all.
*/
function valueMatches(value: unknown, filter: RecordedFilter): boolean {
if (value === null || value === undefined) return false
if (filter.op === 'like') {
const pattern = String(filter.value)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/%/g, '.*')
return new RegExp(`^${pattern}$`).test(String(value))
}
if (filter.op === 'eq') return value === filter.value
// Ordered comparisons run numerically on numerics and lexically otherwise,
// which is what Postgres does per column type. `entry_date` ranges arrive as
// ISO date strings, where lexical order IS chronological order.
const numA = Number(value)
const numB = Number(filter.value)
const numeric = !Number.isNaN(numA) && !Number.isNaN(numB)
const a: number | string = numeric ? numA : String(value)
const b: number | string = numeric ? numB : String(filter.value)
if (filter.op === 'gt') return a > b
if (filter.op === 'gte') return a >= b
return a <= b
}
const EMBED_PREFIX = 'journal_entry_lines.'
/** Whether a recorded filter (or every branch of an or-group) targets the embed. */
function targetsEmbeddedLines(f: AnyRecordedFilter): boolean {
if (f.op === 'or') return f.conditions.every((c) => c.column.startsWith(EMBED_PREFIX))
return f.column.startsWith(EMBED_PREFIX)
}
function stripEmbedPrefix(f: RecordedFilter): RecordedFilter {
return f.column.startsWith(EMBED_PREFIX)
? { ...f, column: f.column.slice(EMBED_PREFIX.length) }
: f
}
/** One filter (or one or-group: any branch suffices) against one row. */
function rowSatisfies(row: Record<string, unknown>, f: AnyRecordedFilter): boolean {
if (f.op === 'or') return f.conditions.some((c) => rowSatisfies(row, c))
return valueMatches(row[f.column], f)
}
/**
* Apply the recorded filters the way PostgREST does for
* `journal_entries?select=...,journal_entry_lines!inner(...)`:
* plain columns filter the entries, `journal_entry_lines.*` columns filter the
* EMBEDDED rows, and because the embed is `!inner` an entry whose lines are all
* filtered away disappears from the result entirely. That last part is the
* mechanism the bug rode in on.
*/
function applyEntryFilters(entries: FixtureEntry[], filters: AnyRecordedFilter[]): FixtureEntry[] {
const entryFilters = filters.filter((f) => !targetsEmbeddedLines(f))
const lineFilters = filters.filter(targetsEmbeddedLines).map((f): AnyRecordedFilter =>
f.op === 'or'
? { ...f, conditions: f.conditions.map(stripEmbedPrefix) }
: stripEmbedPrefix(f)
)
const result: FixtureEntry[] = []
for (const entry of entries) {
const entryOk = entryFilters.every((f) =>
rowSatisfies(entry as unknown as Record<string, unknown>, f)
)
if (!entryOk) continue
const lines = entry.journal_entry_lines.filter((line) =>
lineFilters.every((f) => rowSatisfies(line as unknown as Record<string, unknown>, f))
)
if (lines.length === 0) continue
result.push({ ...entry, journal_entry_lines: lines })
}
return result
}
interface FilteringMockConfig {
accountingMethod?: 'accrual' | 'cash'
entries: FixtureEntry[]
/** Rows returned by the invoice_payments / supplier_invoice_payments dedup. */
existingLinks?: { journal_entry_id: string }[]
periods?: { id: string; is_closed: boolean; locked_at: string | null }[]
}
/**
* Minimal PostgREST stand-in for the two matcher call graphs. Records the
* filters per query and resolves them against `config.entries` at await time,
* so the assertions below are about which vouchers SURVIVE, not about which
* filter strings were typed.
*/
function createFilteringSupabase(config: FilteringMockConfig) {
const queries: { table: string; columns: string; filters: AnyRecordedFilter[] }[] = []
function chainFor(table: string) {
const filters: AnyRecordedFilter[] = []
const record = { table, columns: '', filters }
queries.push(record)
const findEntry = () => {
const idFilter = filters.find(
(f): f is RecordedFilter => f.op === 'eq' && f.column === 'id'
)
const entry = config.entries.find((e) => e.id === idFilter?.value)
if (!entry) return null
const { journal_entry_lines: _lines, ...rest } = entry
return rest
}
const resolveList = (): { data: unknown; error: null } => {
switch (table) {
case 'journal_entries': {
// The two-step fetch (lib/bookkeeping/entry-lines.ts) asks for bare
// entries; the embed path asks for entries WITH lines. Both are
// filtered identically; only the shape differs.
const matched = applyEntryFilters(config.entries, filters)
if (record.columns.includes('journal_entry_lines')) {
return { data: matched, error: null }
}
return {
data: matched.map(({ journal_entry_lines: _l, ...rest }) => rest),
error: null,
}
}
case 'journal_entry_lines': {
// Second leg of the two-step fetch, plus the validators' direct read.
const idFilter = filters.find(
(f): f is RecordedFilter =>
f.op !== 'or' && f.column === 'journal_entry_id' && (f.op === 'eq' || f.op === 'like')
)
const inIds = (record as { inIds?: string[] }).inIds
const scoped = config.entries.filter((e) =>
idFilter ? e.id === idFilter.value : (inIds ?? [e.id]).includes(e.id)
)
const lineFilters = filters.filter(
(f): f is RecordedFilter =>
f.op !== 'or' && f.column !== 'journal_entry_id' && !f.column.startsWith(EMBED_PREFIX)
)
const lines = scoped.flatMap((e) =>
e.journal_entry_lines
.filter((line) =>
lineFilters.every((f) =>
valueMatches((line as unknown as Record<string, unknown>)[f.column], f)
)
)
.map((line) => ({ ...line, journal_entry_id: e.id }))
)
return { data: lines, error: null }
}
case 'invoice_payments':
case 'supplier_invoice_payments':
return { data: config.existingLinks ?? [], error: null }
case 'fiscal_periods':
return {
data:
config.periods ??
[...new Set(config.entries.map((e) => e.fiscal_period_id))].map((id) => ({
id,
is_closed: false,
locked_at: null,
})),
error: null,
}
default:
return { data: [], error: null }
}
}
const resolveSingle = (): { data: unknown; error: null } => {
if (table === 'company_settings') {
return { data: { accounting_method: config.accountingMethod ?? 'accrual' }, error: null }
}
if (table === 'journal_entries') return { data: findEntry(), error: null }
return { data: null, error: null }
}
const chain: Record<string, unknown> = {}
for (const op of ['eq', 'gt', 'gte', 'lte', 'like'] as FilterOp[]) {
chain[op] = (column: string, value: unknown) => {
filters.push({ op, column, value })
return chain
}
}
chain.select = (columns?: string) => {
record.columns = String(columns ?? '')
return chain
}
chain.in = (column: string, values: string[]) => {
if (column === 'journal_entry_id') (record as { inIds?: string[] }).inIds = values
return chain
}
// `.or()` is parsed and EXECUTED, not swallowed: the FX prefilter's floor
// band lives in an or-group, and a mock that ignores it cannot tell a
// correct two-sided band from no band at all.
chain.or = (filterString: string, opts?: { referencedTable?: string; foreignTable?: string }) => {
const prefix = opts?.referencedTable ?? opts?.foreignTable
const conditions: RecordedFilter[] = String(filterString)
.split(',')
.map((part) => {
const [column, op, ...valueParts] = part.split('.')
return {
op: op as FilterOp,
column: prefix ? `${prefix}.${column}` : column,
value: valueParts.join('.'),
}
})
filters.push({ op: 'or', conditions })
return chain
}
for (const op of ['order', 'range', 'limit', 'not', 'is']) {
chain[op] = () => chain
}
chain.maybeSingle = () => Promise.resolve(resolveSingle())
chain.single = () => Promise.resolve(resolveSingle())
chain.then = (onOk: (v: unknown) => unknown, onErr?: (e: unknown) => unknown) =>
Promise.resolve(resolveList()).then(onOk, onErr)
return chain
}
return {
supabase: { from: vi.fn((table: string) => chainFor(table)), rpc: vi.fn() },
queries,
}
}
// ============================================================
// Fixtures: one EUR invoice, three vouchers competing for it
// ============================================================
/** 1000 EUR outstanding, booked at 11.50 SEK/EUR = 11 500 kr. */
function eurInvoice() {
return makeInvoice({
id: 'inv-eur',
invoice_number: 'F-9001',
currency: 'EUR',
total: 1000,
total_sek: 11500,
exchange_rate: 11.5,
remaining_amount: 1000,
paid_amount: null,
status: 'sent',
invoice_date: '2026-06-01',
due_date: '2026-06-30',
})
}
function entry(
id: string,
voucherNumber: number,
description: string,
lines: FixtureLine[]
): FixtureEntry {
return {
id,
voucher_series: 'A',
voucher_number: voucherNumber,
entry_date: '2026-06-28',
description,
status: 'posted',
source_type: 'manual',
fiscal_period_id: 'fp-1',
company_id: 'company-1',
journal_entry_lines: lines,
}
}
/**
* The RIGHT voucher: the 1000 EUR payment. `credit_amount` is the SEK figure
* (11 500 kr), `amount_in_currency` is the 1000 EUR the invoice is quoted in.
*/
const correctEurVoucher = entry('je-correct', 11, 'Inbetalning utländsk kund', [
{
id: 'l-correct-ar',
account_number: '1510',
debit_amount: 0,
credit_amount: 11500,
currency: 'EUR',
amount_in_currency: 1000,
},
{
id: 'l-correct-bank',
account_number: '1930',
debit_amount: 11500,
credit_amount: 0,
currency: 'EUR',
amount_in_currency: 1000,
},
])
/**
* The DECOY: an unrelated 87 EUR payment, which happens to be ~1000 kr. Its SEK
* `credit_amount` sits inside a band built from a EUR remainder, so the broken
* pre-filter kept precisely this one and threw away the voucher above.
*/
const decoySameMagnitudeVoucher = entry('je-decoy', 12, 'Inbetalning smabelopp', [
{
id: 'l-decoy-ar',
account_number: '1510',
debit_amount: 0,
credit_amount: 1000.5,
currency: 'EUR',
amount_in_currency: 87,
},
])
/** A plain 1000 kr domestic payment: same magnitude, wrong unit, no rate. */
const domesticSekVoucher = entry('je-sek', 13, 'Inbetalning inrikes', [
{
id: 'l-sek-ar',
account_number: '1510',
debit_amount: 0,
credit_amount: 1000,
currency: 'SEK',
},
])
// ============================================================
// findMatchingVouchersForInvoice: the SQL pre-filter
// ============================================================
describe('findMatchingVouchersForInvoice: foreign-currency invoices', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('does not exclude the correct EUR voucher in the SQL pre-filter', async () => {
const { supabase } = createFilteringSupabase({
entries: [correctEurVoucher, decoySameMagnitudeVoucher, domesticSekVoucher],
})
const result = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
eurInvoice() as never
)
expect(result.map((c) => c.journal_entry_id)).toContain('je-correct')
})
it('quotes the matched amount in the invoice currency, not the SEK column', async () => {
const { supabase } = createFilteringSupabase({ entries: [correctEurVoucher] })
const [candidate] = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
eurInvoice() as never
)
// 1000 EUR, the figure the invoice's 1000 EUR remainder can be compared
// with. 11 500 here would be the SEK column leaking through.
expect(candidate.ar_credit_amount).toBe(1000)
expect(candidate.currency).toBe('EUR')
})
it('prefers the correct voucher over a same-magnitude decoy', async () => {
const { supabase } = createFilteringSupabase({
entries: [decoySameMagnitudeVoucher, correctEurVoucher],
})
const result = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
eurInvoice() as never
)
expect(result[0].journal_entry_id).toBe('je-correct')
// 87 EUR is not a plausible settlement of a 1000 EUR invoice at all: it
// must not merely rank lower, it must not be offered.
expect(result.map((c) => c.journal_entry_id)).not.toContain('je-decoy')
})
it('never offers a rate-less domestic voucher for a EUR invoice', async () => {
const { supabase } = createFilteringSupabase({ entries: [domesticSekVoucher] })
const result = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
eurInvoice() as never
)
expect(result).toEqual([])
})
it('bounds amount_in_currency and matches the currency label, not the SEK column', async () => {
const { supabase, queries } = createFilteringSupabase({ entries: [correctEurVoucher] })
await findMatchingVouchersForInvoice(supabase as never, 'company-1', eurInvoice() as never)
const candidateQuery = queries.find(
(q) => q.table === 'journal_entries' && q.columns.includes('journal_entry_lines')
)
const banded = candidateQuery!.filters
.filter((f): f is RecordedFilter => f.op === 'gte' || f.op === 'lte')
.map((f) => f.column)
expect(banded).toContain('journal_entry_lines.amount_in_currency')
expect(banded).not.toContain('journal_entry_lines.credit_amount')
expect(candidateQuery!.filters).toEqual(
expect.arrayContaining([
{ op: 'eq', column: 'journal_entry_lines.currency', value: 'EUR' },
])
)
// Both FX columns must be projected or every line is unconvertible.
expect(candidateQuery!.columns).toContain('amount_in_currency')
expect(candidateQuery!.columns).toContain('currency')
})
it('applies the fuzzy floor to the FX band on both signs', async () => {
// The SEK path has always banded [floor, ceil]; the FX path only kept the
// ceiling, so every small same-currency line survived the prefilter and
// could crowd the exact-amount voucher out of the .limit(limit * 10) cap
// before scoring. The floor arrives as an or-group so negatively-stored
// foreign figures stay in: floor <= |amount_in_currency| <= ceil.
const { supabase, queries } = createFilteringSupabase({ entries: [correctEurVoucher] })
await findMatchingVouchersForInvoice(supabase as never, 'company-1', eurInvoice() as never)
const candidateQuery = queries.find(
(q) => q.table === 'journal_entries' && q.columns.includes('journal_entry_lines')
)
const orGroups = candidateQuery!.filters.filter(
(f): f is RecordedOrGroup => f.op === 'or'
)
expect(orGroups).toHaveLength(1)
// hi = lo = 1000 EUR, pad = min(1000 * 0.01, 500) + 0.02 → floor 989.98.
expect(orGroups[0].conditions).toEqual(
expect.arrayContaining([
{ op: 'gte', column: 'journal_entry_lines.amount_in_currency', value: '989.98' },
{ op: 'lte', column: 'journal_entry_lines.amount_in_currency', value: '-989.98' },
])
)
})
it('keeps a negatively-stored foreign figure inside the floored band', async () => {
// A few production rows store amount_in_currency with a negative sign; the
// direction comes off the debit/credit side. The floor must not evict them.
const negativeStored = entry('je-negative', 18, 'Inbetalning utländsk kund', [
{
id: 'l-negative',
account_number: '1510',
debit_amount: 0,
credit_amount: 11500,
currency: 'EUR',
amount_in_currency: -1000,
},
])
const { supabase } = createFilteringSupabase({ entries: [negativeStored] })
const result = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
eurInvoice() as never
)
expect(result.map((c) => c.journal_entry_id)).toContain('je-negative')
})
it('the floor keeps a small sibling line from polluting the matched sum', async () => {
// One voucher whose 151x legs are the real 1000 EUR settlement plus an
// unrelated small 87 EUR credit. Without the floor both lines passed the
// prefilter, the matched sum became 1087 EUR and the one correct voucher
// scored as a no-match. With the floor the small line drops in SQL and the
// voucher matches on its 1000 EUR leg.
const withSmallSibling = entry('je-sibling', 19, 'Inbetalning utländsk kund', [
{
id: 'l-sib-main',
account_number: '1510',
debit_amount: 0,
credit_amount: 11500,
currency: 'EUR',
amount_in_currency: 1000,
},
{
id: 'l-sib-small',
account_number: '1510',
debit_amount: 0,
credit_amount: 1000.5,
currency: 'EUR',
amount_in_currency: 87,
},
])
const { supabase } = createFilteringSupabase({ entries: [withSmallSibling] })
const result = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
eurInvoice() as never
)
expect(result.map((c) => c.journal_entry_id)).toContain('je-sibling')
expect(result[0].ar_credit_amount).toBe(1000)
})
})
// ============================================================
// SEK-only companies: the 95% path must not move at all
// ============================================================
describe('findMatchingVouchersForInvoice: SEK is untouched', () => {
beforeEach(() => {
vi.clearAllMocks()
})
function sekInvoice() {
return makeInvoice({
id: 'inv-sek',
invoice_number: 'F-9002',
currency: 'SEK',
total: 1000,
remaining_amount: 1000,
paid_amount: null,
status: 'sent',
invoice_date: '2026-06-01',
due_date: '2026-06-30',
})
}
it('still matches a plain SEK voucher on the raw ledger column', async () => {
const { supabase } = createFilteringSupabase({ entries: [domesticSekVoucher] })
const [candidate] = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
sekInvoice() as never
)
expect(candidate.journal_entry_id).toBe('je-sek')
expect(candidate.ar_credit_amount).toBe(1000)
})
it('keeps the amount band on the SEK column and adds no currency filter', async () => {
const { supabase, queries } = createFilteringSupabase({ entries: [domesticSekVoucher] })
await findMatchingVouchersForInvoice(supabase as never, 'company-1', sekInvoice() as never)
const candidateQuery = queries.find(
(q) => q.table === 'journal_entries' && q.columns.includes('journal_entry_lines')
)
const banded = candidateQuery!.filters
.filter((f): f is RecordedFilter => f.op === 'gte' || f.op === 'lte')
.map((f) => f.column)
expect(banded).toContain('journal_entry_lines.credit_amount')
expect(banded).not.toContain('journal_entry_lines.amount_in_currency')
expect(
candidateQuery!.filters.some(
(f) => f.op !== 'or' && f.column === 'journal_entry_lines.currency'
)
).toBe(false)
// The SEK band is expressed as plain gte/lte on the ledger column: no
// or-group is added (the floor already sits in the gte).
expect(candidateQuery!.filters.some((f) => f.op === 'or')).toBe(false)
})
it('reads the SEK column even when the line is labelled with a foreign document', async () => {
// A SEK invoice settled by a voucher that also carries a EUR document
// label: the ledger column is kronor either way, so the label is irrelevant
// and the match must still happen.
const mixed = entry('je-mixed', 14, 'Inbetalning', [
{
id: 'l-mixed',
account_number: '1510',
debit_amount: 0,
credit_amount: 1000,
currency: 'SEK',
amount_in_currency: null,
},
])
const { supabase } = createFilteringSupabase({ entries: [mixed] })
const [candidate] = await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
sekInvoice() as never
)
expect(candidate.ar_credit_amount).toBe(1000)
})
it('treats a legacy NULL invoice currency as SEK, not as foreign', async () => {
// `invoices.currency` is `text default 'SEK'` and therefore nullable, while
// the TS type says otherwise. A NULL must not test `!== 'SEK'` and send a
// domestic invoice down the amount_in_currency path.
const { supabase, queries } = createFilteringSupabase({ entries: [domesticSekVoucher] })
await findMatchingVouchersForInvoice(
supabase as never,
'company-1',
makeInvoice({
currency: null as unknown as 'SEK',
total: 1000,
remaining_amount: 1000,
paid_amount: null,
due_date: '2026-06-30',
invoice_number: 'F-9003',
}) as never
)
const candidateQuery = queries.find(
(q) => q.table === 'journal_entries' && q.columns.includes('journal_entry_lines')
)
expect(
candidateQuery!.filters.some(
(f) => f.op !== 'or' && f.column === 'journal_entry_lines.currency'
)
).toBe(false)
expect(
candidateQuery!.filters.some(
(f) =>
(f.op === 'or' &&
f.conditions.some((c) => c.column === 'journal_entry_lines.amount_in_currency')) ||
(f.op !== 'or' && f.column === 'journal_entry_lines.amount_in_currency')
)
).toBe(false)
})
})
// ============================================================
// validateVoucherForInvoiceLink: EXCEEDS_REMAINING + payment amount
// ============================================================
describe('validateVoucherForInvoiceLink: foreign-currency invoices', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('accepts the correct EUR voucher instead of EXCEEDS_REMAINING', async () => {
const { supabase } = createFilteringSupabase({ entries: [correctEurVoucher] })
const result = await validateVoucherForInvoiceLink(
supabase as never,
'company-1',
eurInvoice() as never,
'je-correct'
)
// Comparing the 11 500 kr credit against the 1000 EUR remainder rejected
// the one voucher that was actually right.
expect(result.ok).toBe(true)
})
it('writes the payment amount in the invoice currency', async () => {
const { supabase } = createFilteringSupabase({ entries: [correctEurVoucher] })
const result = await validateVoucherForInvoiceLink(
supabase as never,
'company-1',
eurInvoice() as never,
'je-correct'
)
expect(result.ok).toBe(true)
if (!result.ok) return
// Math.min(11500, 1000) = 1000 by accident; Math.min(1000, 1000) = 1000 on
// purpose. The distinguishing figure is arCreditAmount.
expect(result.arCreditAmount).toBe(1000)
expect(result.paymentAmount).toBe(1000)
expect(result.remainingAfter).toBe(0)
expect(result.isFullyPaid).toBe(true)
})
it('reports a partial settlement in the invoice currency', async () => {
// 400 EUR of a 1000 EUR invoice, booked at 11.50 = 4600 kr.
const partial = entry('je-partial', 15, 'Delbetalning', [
{
id: 'l-partial',
account_number: '1510',
debit_amount: 0,
credit_amount: 4600,
currency: 'EUR',
amount_in_currency: 400,
},
])
const { supabase } = createFilteringSupabase({ entries: [partial] })
const result = await validateVoucherForInvoiceLink(
supabase as never,
'company-1',
eurInvoice() as never,
'je-partial'
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.paymentAmount).toBe(400)
expect(result.remainingAfter).toBe(600)
expect(result.isFullyPaid).toBe(false)
})
it('still rejects a voucher that genuinely exceeds the remainder', async () => {
// 1500 EUR against a 1000 EUR remainder: the guard must keep working in the
// invoice's own unit.
const tooBig = entry('je-toobig', 16, 'Inbetalning', [
{
id: 'l-toobig',
account_number: '1510',
debit_amount: 0,
credit_amount: 17250,
currency: 'EUR',
amount_in_currency: 1500,
},
])
const { supabase } = createFilteringSupabase({ entries: [tooBig] })
const result = await validateVoucherForInvoiceLink(
supabase as never,
'company-1',
eurInvoice() as never,
'je-toobig'
)
expect(result.ok).toBe(false)
if (result.ok) return
expect(result.code).toBe('LINK_VOUCHER_AMOUNT_EXCEEDS_REMAINING')
expect(result.details).toMatchObject({ ar_credit: 1500, remaining: 1000 })
})
it('refuses a rate-less AR credit rather than reading it as EUR', async () => {
// A 151x credit with no amount_in_currency carries no figure in EUR. Summing
// only the readable lines would understate the voucher, so this fails closed.
const rateless = entry('je-rateless', 17, 'Inbetalning', [
{
id: 'l-rateless',
account_number: '1510',
debit_amount: 0,
credit_amount: 11500,
currency: 'EUR',
amount_in_currency: null,
},
])
const { supabase } = createFilteringSupabase({ entries: [rateless] })
const result = await validateVoucherForInvoiceLink(
supabase as never,
'company-1',
eurInvoice() as never,
'je-rateless'
)
expect(result.ok).toBe(false)
if (result.ok) return
expect(result.code).toBe('LINK_VOUCHER_CURRENCY_MISMATCH')
})
it('selects currency + amount_in_currency off the lines', async () => {
// The fix is inert if the column list omits them: the sweep has already hit
// that once, via RPCs that projected neither.
const { supabase, queries } = createFilteringSupabase({ entries: [correctEurVoucher] })
await validateVoucherForInvoiceLink(
supabase as never,
'company-1',
eurInvoice() as never,
'je-correct'
)
const lineQuery = queries.find((q) => q.table === 'journal_entry_lines')
expect(lineQuery!.columns).toContain('currency')
expect(lineQuery!.columns).toContain('amount_in_currency')
})
it('SEK: the happy path is unchanged', async () => {
const { supabase } = createFilteringSupabase({ entries: [domesticSekVoucher] })
const result = await validateVoucherForInvoiceLink(
supabase as never,
'company-1',
makeInvoice({
currency: 'SEK',
total: 1000,
remaining_amount: 1000,
paid_amount: null,
status: 'sent',
due_date: '2026-06-30',
invoice_number: 'F-9004',
}) as never,
'je-sek'
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.arCreditAmount).toBe(1000)
expect(result.paymentAmount).toBe(1000)
})
})
// ============================================================
// Supplier side: 244x debits
// ============================================================
/** 1000 EUR supplier invoice, booked at 11.50 = 11 500 kr. */
function eurSupplierInvoice() {
return makeSupplierInvoice({
id: 'sinv-eur',
supplier_invoice_number: 'L-9001',
currency: 'EUR',
total: 1000,
total_sek: 11500,
exchange_rate: 11.5,
remaining_amount: 1000,
paid_amount: 0,
status: 'registered',
invoice_date: '2026-06-01',
due_date: '2026-06-30',
// A number that appears in none of the voucher descriptions below: the OCR
// pass matches on arrival_number and would short-circuit the amount logic
// these tests are about. `arrival_number` is NOT NULL, hence a sentinel.
arrival_number: 999999,
})
}
const correctEurApVoucher = entry('je-ap-correct', 21, 'Betalning utlandsleverantor', [
{
id: 'l-ap-correct',
account_number: '2440',
debit_amount: 11500,
credit_amount: 0,
currency: 'EUR',
amount_in_currency: 1000,
},
])
const domesticApVoucher = entry('je-ap-sek', 22, 'Betalning leverantor', [
{
id: 'l-ap-sek',
account_number: '2440',
debit_amount: 1000,
credit_amount: 0,
currency: 'SEK',
},
])
describe('findMatchingVouchersForSupplierInvoice: foreign-currency invoices', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('quotes the AP debit in the invoice currency', async () => {
const { supabase } = createFilteringSupabase({ entries: [correctEurApVoucher] })
const [candidate] = await findMatchingVouchersForSupplierInvoice(
supabase as never,
'company-1',
eurSupplierInvoice() as never
)
expect(candidate.journal_entry_id).toBe('je-ap-correct')
expect(candidate.ap_debit_amount).toBe(1000)
expect(candidate.currency).toBe('EUR')
})
it('never offers a rate-less domestic AP debit for a EUR invoice', async () => {
const { supabase } = createFilteringSupabase({ entries: [domesticApVoucher] })
const result = await findMatchingVouchersForSupplierInvoice(
supabase as never,
'company-1',
eurSupplierInvoice() as never
)
expect(result).toEqual([])
})
it('narrows the line query to the invoice currency and projects both FX columns', async () => {
const { supabase, queries } = createFilteringSupabase({ entries: [correctEurApVoucher] })
await findMatchingVouchersForSupplierInvoice(
supabase as never,
'company-1',
eurSupplierInvoice() as never
)
const lineQuery = queries.find((q) => q.table === 'journal_entry_lines')
expect(lineQuery!.columns).toContain('amount_in_currency')
expect(lineQuery!.filters).toEqual(
expect.arrayContaining([{ op: 'eq', column: 'currency', value: 'EUR' }])
)
})
it('SEK: matches on the raw column and adds no currency filter', async () => {
const { supabase, queries } = createFilteringSupabase({ entries: [domesticApVoucher] })
const [candidate] = await findMatchingVouchersForSupplierInvoice(
supabase as never,
'company-1',
makeSupplierInvoice({
currency: 'SEK',
total: 1000,
remaining_amount: 1000,
paid_amount: 0,
status: 'registered',
due_date: '2026-06-30',
supplier_invoice_number: 'L-9002',
// A number that appears in none of the voucher descriptions below: the OCR
// pass matches on arrival_number and would short-circuit the amount logic
// these tests are about. `arrival_number` is NOT NULL, hence a sentinel.
arrival_number: 999999,
}) as never
)
expect(candidate.ap_debit_amount).toBe(1000)
const lineQuery = queries.find((q) => q.table === 'journal_entry_lines')
expect(
lineQuery!.filters.some((f) => f.op !== 'or' && f.column === 'currency')
).toBe(false)
})
})
describe('validateVoucherForSupplierInvoiceLink: foreign-currency invoices', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('accepts the correct EUR voucher instead of EXCEEDS_REMAINING', async () => {
const { supabase } = createFilteringSupabase({ entries: [correctEurApVoucher] })
const result = await validateVoucherForSupplierInvoiceLink(
supabase as never,
'company-1',
eurSupplierInvoice() as never,
'je-ap-correct'
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.apDebitAmount).toBe(1000)
expect(result.paymentAmount).toBe(1000)
})
it('still rejects an AP debit that genuinely exceeds the remainder', async () => {
const tooBig = entry('je-ap-toobig', 23, 'Betalning', [
{
id: 'l-ap-toobig',
account_number: '2440',
debit_amount: 17250,
credit_amount: 0,
currency: 'EUR',
amount_in_currency: 1500,
},
])
const { supabase } = createFilteringSupabase({ entries: [tooBig] })
const result = await validateVoucherForSupplierInvoiceLink(
supabase as never,
'company-1',
eurSupplierInvoice() as never,
'je-ap-toobig'
)
expect(result.ok).toBe(false)
if (result.ok) return
expect(result.code).toBe('LINK_SI_VOUCHER_AMOUNT_EXCEEDS_REMAINING')
expect(result.details).toMatchObject({ ap_debit: 1500, remaining: 1000 })
})
it('refuses a rate-less AP debit rather than reading it as EUR', async () => {
const rateless = entry('je-ap-rateless', 24, 'Betalning', [
{
id: 'l-ap-rateless',
account_number: '2440',
debit_amount: 11500,
credit_amount: 0,
currency: 'EUR',
amount_in_currency: null,
},
])
const { supabase } = createFilteringSupabase({ entries: [rateless] })
const result = await validateVoucherForSupplierInvoiceLink(
supabase as never,
'company-1',
eurSupplierInvoice() as never,
'je-ap-rateless'
)
expect(result.ok).toBe(false)
if (result.ok) return
expect(result.code).toBe('LINK_SI_VOUCHER_CURRENCY_MISMATCH')
})
it('SEK: the happy path is unchanged', async () => {
const { supabase } = createFilteringSupabase({ entries: [domesticApVoucher] })
const result = await validateVoucherForSupplierInvoiceLink(
supabase as never,
'company-1',
makeSupplierInvoice({
currency: 'SEK',
total: 1000,
remaining_amount: 1000,
paid_amount: 0,
status: 'registered',
due_date: '2026-06-30',
supplier_invoice_number: 'L-9003',
// A number that appears in none of the voucher descriptions below: the OCR
// pass matches on arrival_number and would short-circuit the amount logic
// these tests are about. `arrival_number` is NOT NULL, hence a sentinel.
arrival_number: 999999,
}) as never,
'je-ap-sek'
)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.apDebitAmount).toBe(1000)
})
})
// ============================================================
// The shared rule itself
// ============================================================
describe('ledgerLineSideAmountIn contract as used here', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('is the same helper bank reconciliation uses', async () => {
// The promotion to lib/bookkeeping/ledger-line-amount.ts must not have left
// bank-reconciliation.ts without its export: a second implementation of
// this rule is how the two sides drift apart again.
const promoted = await import('@/lib/bookkeeping/ledger-line-amount')
const reexported = await import('@/lib/reconciliation/bank-reconciliation')
expect(reexported.ledgerLineAmountIn).toBe(promoted.ledgerLineAmountIn)
})
it('unused queued mock helper stays importable', () => {
// Guards against the shared fixture factory drifting out from under the
// sibling suites in this directory.
expect(typeof createQueuedMockSupabase).toBe('function')
})
})