Files
accounted/lib/reconciliation/__tests__/bank-reconciliation.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

1711 lines
66 KiB
TypeScript

/**
* Tests for the bank reconciliation engine.
*
* Covers: matching algorithm (4 passes), direction compatibility,
* greedy assignment, dry run, manual link/unlink, status calculation.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
tryReconcileTransaction,
runReconciliation,
manualLink,
unlinkReconciliation,
getReconciliationStatus,
scopeTransactionsToAccount,
ledgerLineAmountIn,
} from '../bank-reconciliation'
import type { UnlinkedGLLine } from '../bank-reconciliation'
import { makeTransaction } from '@/tests/helpers'
import { eventBus } from '@/lib/events/bus'
vi.mock('@/lib/supabase/server')
// ============================================================
// Helpers
// ============================================================
function makeGLLine(overrides: Partial<UnlinkedGLLine> = {}): UnlinkedGLLine {
return {
line_id: `line-${Math.random().toString(36).slice(2, 8)}`,
journal_entry_id: `je-${Math.random().toString(36).slice(2, 8)}`,
debit_amount: 0,
credit_amount: 0,
line_description: null,
entry_date: '2024-06-15',
voucher_number: 1,
voucher_series: 'A',
entry_description: 'Test entry',
source_type: 'import',
...overrides,
}
}
// ============================================================
// ledgerLineAmountIn: the single definition of "this ledger line's amount,
// expressed in the currency the account is being reconciled in"
// ============================================================
describe('ledgerLineAmountIn', () => {
it('nets debit against credit on SEK, ignoring the currency LABEL', () => {
// The headline trap: currency-utils stamps `currency: 'EUR'` +
// amount_in_currency onto a line whose debit_amount is SEK (a EUR supplier
// invoice paid from a SEK account). Reconciling that account in SEK must
// use the SEK columns and ignore the label entirely.
expect(ledgerLineAmountIn({ debit_amount: 1150, credit_amount: 0 }, 'SEK')).toBe(1150)
expect(ledgerLineAmountIn({ debit_amount: 0, credit_amount: 1150 }, 'SEK')).toBe(-1150)
expect(
ledgerLineAmountIn(
{ debit_amount: 1150, credit_amount: 0, currency: 'EUR', amount_in_currency: 100 },
'SEK',
),
).toBe(1150)
})
it('never returns null on SEK: the 95% path always has an answer', () => {
expect(ledgerLineAmountIn({ debit_amount: null, credit_amount: null }, 'SEK')).toBe(0)
expect(ledgerLineAmountIn({ debit_amount: '250.50', credit_amount: '0' }, 'SEK')).toBe(250.5)
})
it('returns the FOREIGN amount, not the SEK figure, on a foreign account', () => {
// 100 EUR booked at 11.50: debit_amount is the 1150 SEK conversion.
// Reconciling the EUR account must yield 100, never 1150.
expect(
ledgerLineAmountIn(
{ debit_amount: 1150, credit_amount: 0, currency: 'EUR', amount_in_currency: 100 },
'EUR',
),
).toBe(100)
expect(
ledgerLineAmountIn(
{ debit_amount: 0, credit_amount: 1150, currency: 'EUR', amount_in_currency: 100 },
'EUR',
),
).toBe(-100)
})
it('takes direction from the debit/credit side, magnitude from amount_in_currency', () => {
// Some rows carry a negatively-signed amount_in_currency; the ledger side is
// authoritative for direction, so the sign must not be applied twice.
expect(
ledgerLineAmountIn(
{ debit_amount: 0, credit_amount: 1150, currency: 'EUR', amount_in_currency: -100 },
'EUR',
),
).toBe(-100)
})
it('returns null (never the SEK figure) when the line carries no amount in that currency', () => {
// No rate on the row: a SIE-imported or pre-FX line on a EUR account. There
// is nothing to convert with, so the caller must report it, not guess.
expect(ledgerLineAmountIn({ debit_amount: 1150, credit_amount: 0 }, 'EUR')).toBeNull()
expect(
ledgerLineAmountIn({ debit_amount: 1150, credit_amount: 0, currency: 'SEK' }, 'EUR'),
).toBeNull()
expect(
ledgerLineAmountIn(
{ debit_amount: 1150, credit_amount: 0, currency: 'EUR', amount_in_currency: null },
'EUR',
),
).toBeNull()
// Wrong label: a USD line on a EUR account carries no EUR amount.
expect(
ledgerLineAmountIn(
{ debit_amount: 1150, credit_amount: 0, currency: 'USD', amount_in_currency: 110 },
'EUR',
),
).toBeNull()
})
})
// ============================================================
// scopeTransactionsToAccount: the per-account query filter
// ============================================================
describe('scopeTransactionsToAccount', () => {
// Records every filter call and returns itself so the chain can continue.
function makeQueryStub() {
const calls: { method: string; args: unknown[] }[] = []
const self = {
eq: (...args: unknown[]) => {
calls.push({ method: 'eq', args })
return self
},
or: (...args: unknown[]) => {
calls.push({ method: 'or', args })
return self
},
}
return { self, calls }
}
it('scopes by currency AND (this account OR legacy NULL) using a flat two-term or', () => {
const { self, calls } = makeQueryStub()
const id = '11111111-1111-1111-1111-111111111111'
scopeTransactionsToAccount(self as never, id, 'SEK')
// currency is constrained even on the bound branch (a cash account has one
// currency), which lets us avoid the fragile nested and() form.
expect(calls).toContainEqual({ method: 'eq', args: ['currency', 'SEK'] })
expect(calls).toContainEqual({
method: 'or',
args: [`cash_account_id.eq.${id},cash_account_id.is.null`],
})
// Regression guard: the old nested `and(cash_account_id.is.null,currency.eq.X)`
// silently returned ZERO rows mid-backfill: it must never come back.
const orCall = calls.find((c) => c.method === 'or')
expect(String(orCall?.args[0])).not.toContain('and(')
})
it('scopes strictly to the account (no NULL fallback) when includeUnassigned is false', () => {
const { self, calls } = makeQueryStub()
const id = '22222222-2222-2222-2222-222222222222'
// includeUnassigned=false is the non-primary account case: a secondary
// same-currency account (e.g. a 1931 savings account) must NOT pull in the
// company's unassigned NULL rows: those belong to the primary account.
// Double-counting them inflated the secondary account's bank total and
// showed a large bogus difference ("1930 works, the other accounts go wonky").
scopeTransactionsToAccount(self as never, id, 'SEK', false)
expect(calls).toEqual([
{ method: 'eq', args: ['currency', 'SEK'] },
{ method: 'eq', args: ['cash_account_id', id] },
])
// No OR: the IS NULL fallback must not appear for a non-primary account.
expect(calls.find((c) => c.method === 'or')).toBeUndefined()
})
it('falls back to a pure currency filter when no cash account id is given', () => {
const { self, calls } = makeQueryStub()
scopeTransactionsToAccount(self as never, undefined, 'EUR')
expect(calls).toEqual([{ method: 'eq', args: ['currency', 'EUR'] }])
})
it('rejects a non-ISO currency (PostgREST filter-injection guard)', () => {
const { self } = makeQueryStub()
expect(() =>
scopeTransactionsToAccount(self as never, undefined, 'SEK; drop' as never),
).toThrow()
})
it('rejects a non-uuid cash account id', () => {
const { self } = makeQueryStub()
expect(() => scopeTransactionsToAccount(self as never, 'not-a-uuid', 'SEK')).toThrow()
})
})
// ============================================================
// tryReconcileTransaction: in-memory matching
// ============================================================
describe('tryReconcileTransaction', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
// ------------------------------------------------------------------
// Pass 1: Exact amount + exact date
// ------------------------------------------------------------------
it('matches income transaction with exact amount and date (debit on 1930)', () => {
const tx = makeTransaction({ amount: 5000, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({ debit_amount: 5000, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).not.toBeNull()
expect(result!.method).toBe('auto_exact')
expect(result!.confidence).toBe(0.95)
})
it('matches expense transaction with exact amount and date (credit on 1930)', () => {
const tx = makeTransaction({ amount: -1200, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({ credit_amount: 1200, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).not.toBeNull()
expect(result!.method).toBe('auto_exact')
expect(result!.confidence).toBe(0.95)
})
// ------------------------------------------------------------------
// Pass 2: Exact amount + OCR/reference match (within ±90 days)
// ------------------------------------------------------------------
it('matches on exact amount with OCR reference match within 90 days', () => {
const tx = makeTransaction({
amount: 3500,
date: '2024-06-20',
currency: 'SEK',
reference: '12345678',
})
const line = makeGLLine({
debit_amount: 3500,
entry_date: '2024-06-10',
entry_description: 'Payment ref 12345678',
})
const result = tryReconcileTransaction(tx, [line])
expect(result).not.toBeNull()
expect(result!.method).toBe('auto_reference')
expect(result!.confidence).toBe(0.90)
})
// Regression: viktor@frnzn.com: recurring monthly bank fee from 2026 was
// wrongly reconciled to a 2024 SIE-imported voucher because description +
// amount collided. auto_reference must require a real OCR token AND a
// bounded date window: description alone, no date check, is not enough.
it('does NOT match recurring charge across years on description alone', () => {
const tx = makeTransaction({
amount: -149,
date: '2026-01-31',
currency: 'SEK',
description: 'Månadsavgift Baspaket',
reference: null,
})
const line = makeGLLine({
credit_amount: 149,
entry_date: '2024-03-31',
entry_description: 'Bankavgifter Månadsavgift Baspaket',
})
const result = tryReconcileTransaction(tx, [line])
expect(result).toBeNull()
})
it('does NOT match on OCR reference when dates are >90 days apart', () => {
const tx = makeTransaction({
amount: 3500,
date: '2026-06-20',
currency: 'SEK',
reference: '12345678',
})
const line = makeGLLine({
debit_amount: 3500,
entry_date: '2024-06-10',
entry_description: 'Payment ref 12345678',
})
const result = tryReconcileTransaction(tx, [line])
expect(result).toBeNull()
})
// ------------------------------------------------------------------
// Pass 3: Exact amount + date within ±3 days
// ------------------------------------------------------------------
it('matches on exact amount within 3 day date range', () => {
const tx = makeTransaction({ amount: 750, date: '2024-06-17', currency: 'SEK' })
const line = makeGLLine({ debit_amount: 750, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).not.toBeNull()
expect(result!.method).toBe('auto_date_range')
expect(result!.confidence).toBe(0.85)
})
it('does not match when date difference exceeds 3 days', () => {
const tx = makeTransaction({ amount: 750, date: '2024-06-20', currency: 'SEK' })
const line = makeGLLine({ debit_amount: 750, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
// 5 days apart, no reference, different dates: no match
expect(result).toBeNull()
})
// ------------------------------------------------------------------
// Pass 4: Fuzzy amount (±0.01) + exact date
// ------------------------------------------------------------------
it('matches on fuzzy amount with exact date', () => {
const tx = makeTransaction({ amount: -999.99, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({ credit_amount: 1000, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).not.toBeNull()
expect(result!.method).toBe('auto_fuzzy')
expect(result!.confidence).toBe(0.75)
})
it('does not match when fuzzy amount exceeds 0.01 tolerance', () => {
const tx = makeTransaction({ amount: -999.98, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({ credit_amount: 1000, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).toBeNull()
})
// ------------------------------------------------------------------
// Direction mismatch rejection
// ------------------------------------------------------------------
it('rejects income transaction against credit line (direction mismatch)', () => {
const tx = makeTransaction({ amount: 1000, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({ credit_amount: 1000, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).toBeNull()
})
it('rejects expense transaction against debit line (direction mismatch)', () => {
const tx = makeTransaction({ amount: -500, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({ debit_amount: 500, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).toBeNull()
})
// ------------------------------------------------------------------
// Non-SEK transactions
// ------------------------------------------------------------------
it('skips non-SEK transactions', () => {
const tx = makeTransaction({ amount: 100, date: '2024-06-15', currency: 'EUR' })
const line = makeGLLine({ debit_amount: 100, entry_date: '2024-06-15' })
const result = tryReconcileTransaction(tx, [line])
expect(result).toBeNull()
})
// The currency check must gate BOTH sides. Gating only the transaction left a
// foreign bank amount being compared against a ledger figure that is always
// SEK, so a same-magnitude coincidence in the wrong unit scored auto_exact.
it('does NOT match a foreign bank row to a same-magnitude SEK ledger leg', () => {
const tx = makeTransaction({ amount: 100, date: '2024-06-15', currency: 'EUR' })
// A plain SEK booking: 100 kr on the same date. Same number, wrong unit.
const sekLine = makeGLLine({
debit_amount: 100,
entry_date: '2024-06-15',
currency: 'SEK',
})
const result = tryReconcileTransaction(tx, [sekLine], 'EUR')
expect(result).toBeNull()
})
it('matches a EUR bank row against the EUR amount recorded on the ledger line', () => {
const tx = makeTransaction({ amount: 100, date: '2024-06-15', currency: 'EUR' })
// 100 EUR at 11.50: the ledger columns hold the 1150 SEK conversion.
const eurLine = makeGLLine({
debit_amount: 1150,
entry_date: '2024-06-15',
currency: 'EUR',
amount_in_currency: 100,
})
const result = tryReconcileTransaction(tx, [eurLine], 'EUR')
expect(result).not.toBeNull()
expect(result!.method).toBe('auto_exact')
})
it('still matches a SEK payment of a EUR invoice on the SEK account (label is not the unit)', () => {
// Regression guard for the 95% path: currency-utils labels this line 'EUR'
// while debit_amount is SEK. Reconciling 1930 in SEK must be unaffected.
const tx = makeTransaction({ amount: 1150, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({
debit_amount: 1150,
entry_date: '2024-06-15',
currency: 'EUR',
amount_in_currency: 100,
})
const result = tryReconcileTransaction(tx, [line])
expect(result).not.toBeNull()
expect(result!.method).toBe('auto_exact')
})
// ------------------------------------------------------------------
// Empty pool
// ------------------------------------------------------------------
it('returns null for empty GL line pool', () => {
const tx = makeTransaction({ amount: 100, date: '2024-06-15', currency: 'SEK' })
const result = tryReconcileTransaction(tx, [])
expect(result).toBeNull()
})
// ------------------------------------------------------------------
// Priority: highest confidence wins
// ------------------------------------------------------------------
it('prefers exact match over date range match', () => {
const tx = makeTransaction({ amount: 1000, date: '2024-06-15', currency: 'SEK' })
const exactLine = makeGLLine({
line_id: 'exact',
debit_amount: 1000,
entry_date: '2024-06-15',
})
const rangeLine = makeGLLine({
line_id: 'range',
debit_amount: 1000,
entry_date: '2024-06-14',
})
const result = tryReconcileTransaction(tx, [rangeLine, exactLine])
expect(result).not.toBeNull()
expect(result!.glLine.line_id).toBe('exact')
expect(result!.method).toBe('auto_exact')
})
// ------------------------------------------------------------------
// No double-matching when using greedy algorithm
// ------------------------------------------------------------------
it('each GL line can only match once in a pool', () => {
const tx1 = makeTransaction({ id: 'tx-1', amount: 1000, date: '2024-06-15', currency: 'SEK' })
const tx2 = makeTransaction({ id: 'tx-2', amount: 1000, date: '2024-06-15', currency: 'SEK' })
const line = makeGLLine({ debit_amount: 1000, entry_date: '2024-06-15' })
// First transaction matches
const result1 = tryReconcileTransaction(tx1, [line])
expect(result1).not.toBeNull()
// Second transaction against the same single line also matches individually
const result2 = tryReconcileTransaction(tx2, [line])
expect(result2).not.toBeNull()
// But in the batch reconciliation (greedyMatch), only one would be assigned
// This is tested in runReconciliation tests
})
})
// ============================================================
// runReconciliation: batch matching with DB calls
// ============================================================
describe('runReconciliation', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
function createQueueMockSupabase() {
const resultQueue: { data: unknown; error: unknown }[] = []
const enqueue = (...results: { data?: unknown; error?: unknown }[]) => {
for (const r of results) {
resultQueue.push({ data: r.data ?? null, error: r.error ?? null })
}
}
const buildChain = (): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
if (prop === 'then') {
const next = resultQueue.shift() ?? { data: null, error: null }
return (resolve: (v: unknown) => void) => resolve(next)
}
return (..._args: unknown[]) => buildChain()
},
}
return new Proxy({}, handler)
}
const supabase = {
from: vi.fn().mockImplementation(() => buildChain()),
rpc: vi.fn().mockImplementation(() => buildChain()),
}
return { supabase, enqueue }
}
it('returns empty matches when no unmatched transactions exist', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// RPC: get_unlinked_1930_lines returns empty
enqueue({ data: [] })
// from('transactions').select: unmatched
enqueue({ data: [] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1')
expect(result.matches).toEqual([])
expect(result.applied).toBe(0)
})
it('dry run returns matches without applying', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({ id: 'tx-1', amount: 1000, date: '2024-06-15', currency: 'SEK' })
const glLine: UnlinkedGLLine = makeGLLine({
line_id: 'line-1',
journal_entry_id: 'je-1',
debit_amount: 1000,
entry_date: '2024-06-15',
})
// RPC returns GL lines
enqueue({ data: [glLine] })
// from('transactions') returns unmatched transactions
enqueue({ data: [tx] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', { dryRun: true })
expect(result.matches).toHaveLength(1)
expect(result.matches[0].method).toBe('auto_exact')
expect(result.applied).toBe(0)
})
it('applies matches when not dry run', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({ id: 'tx-1', amount: -500, date: '2024-06-15', currency: 'SEK' })
const glLine: UnlinkedGLLine = makeGLLine({
line_id: 'line-1',
journal_entry_id: 'je-1',
credit_amount: 500,
entry_date: '2024-06-15',
})
// RPC returns GL lines
enqueue({ data: [glLine] })
// from('transactions') returns unmatched transactions
enqueue({ data: [tx] })
// Update transaction with link: .select('id') returns the updated row
enqueue({ data: [{ id: 'tx-1' }] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', { dryRun: false })
expect(result.matches).toHaveLength(1)
expect(result.applied).toBe(1)
expect(result.errors).toBe(0)
})
it('counts a conflicted apply (0 rows updated) as an error, not applied', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({ id: 'tx-1', amount: -500, date: '2024-06-15', currency: 'SEK' })
const glLine: UnlinkedGLLine = makeGLLine({
line_id: 'line-1',
journal_entry_id: 'je-1',
credit_amount: 500,
entry_date: '2024-06-15',
})
enqueue({ data: [glLine] })
enqueue({ data: [tx] })
// Optimistic-lock guard: a concurrent linker got there first: the
// .is('journal_entry_id', null) filter matches zero rows.
enqueue({ data: [] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', { dryRun: false })
expect(result.applied).toBe(0)
expect(result.errors).toBe(1)
})
it('applies only the pairs in applyOnly, intersected with the fresh match run', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx1 = makeTransaction({ id: 'tx-1', amount: 1000, date: '2024-06-15', currency: 'SEK' })
const tx2 = makeTransaction({ id: 'tx-2', amount: -500, date: '2024-06-15', currency: 'SEK' })
const line1 = makeGLLine({
line_id: 'line-1',
journal_entry_id: 'je-1',
debit_amount: 1000,
entry_date: '2024-06-15',
})
const line2 = makeGLLine({
line_id: 'line-2',
journal_entry_id: 'je-2',
credit_amount: 500,
entry_date: '2024-06-15',
})
enqueue({ data: [line1, line2] })
enqueue({ data: [tx1, tx2] })
// Only ONE update should run: for the single selected pair.
enqueue({ data: [{ id: 'tx-2' }] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
dryRun: false,
applyOnly: [
{ transactionId: 'tx-2', journalEntryId: 'je-2' },
// A pair the matcher never proposed must be ignored, not applied.
{ transactionId: 'tx-99', journalEntryId: 'je-99' },
],
})
expect(result.matches).toHaveLength(1)
expect(result.matches[0].transaction.id).toBe('tx-2')
expect(result.applied).toBe(1)
expect(result.errors).toBe(0)
})
it('skips matches below confidenceThreshold in apply mode but still reports them', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// auto_exact (0.95): above the 0.9 floor, must apply.
const txExact = makeTransaction({ id: 'tx-exact', amount: 1000, date: '2024-06-15', currency: 'SEK' })
const lineExact = makeGLLine({
line_id: 'line-exact',
journal_entry_id: 'je-exact',
debit_amount: 1000,
entry_date: '2024-06-15',
})
// auto_fuzzy (0.75): below the 0.9 floor, must be skipped, not applied.
const txFuzzy = makeTransaction({ id: 'tx-fuzzy', amount: -999.99, date: '2024-06-15', currency: 'SEK' })
const lineFuzzy = makeGLLine({
line_id: 'line-fuzzy',
journal_entry_id: 'je-fuzzy',
credit_amount: 1000,
entry_date: '2024-06-15',
})
enqueue({ data: [lineExact, lineFuzzy] })
enqueue({ data: [txExact, txFuzzy] })
// Exactly ONE update runs: the exact match. If the fuzzy match were
// applied too, the queue would be short and this enqueue insufficient.
enqueue({ data: [{ id: 'tx-exact' }] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
dryRun: false,
confidenceThreshold: 0.9,
})
// Both matches are REPORTED (skipped is not silently dropped) ...
expect(result.matches).toHaveLength(2)
// ... but only the high-confidence one is applied.
expect(result.applied).toBe(1)
expect(result.errors).toBe(0)
expect(result.skippedBelowThreshold).toBe(1)
const skipped = result.matches.find((m) => m.transaction.id === 'tx-fuzzy')
expect(skipped?.method).toBe('auto_fuzzy')
})
it('applies a match exactly at the threshold (floor is inclusive)', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// auto_date_range scores exactly 0.85: with threshold 0.85 it must apply.
const tx = makeTransaction({ id: 'tx-1', amount: 750, date: '2024-06-17', currency: 'SEK' })
const line = makeGLLine({
line_id: 'line-1',
journal_entry_id: 'je-1',
debit_amount: 750,
entry_date: '2024-06-15',
})
enqueue({ data: [line] })
enqueue({ data: [tx] })
enqueue({ data: [{ id: 'tx-1' }] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
dryRun: false,
confidenceThreshold: 0.85,
})
expect(result.applied).toBe(1)
expect(result.skippedBelowThreshold).toBe(0)
})
it('dry run is unaffected by confidenceThreshold: every proposal is returned', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const txFuzzy = makeTransaction({ id: 'tx-fuzzy', amount: -999.99, date: '2024-06-15', currency: 'SEK' })
const lineFuzzy = makeGLLine({
line_id: 'line-fuzzy',
journal_entry_id: 'je-fuzzy',
credit_amount: 1000,
entry_date: '2024-06-15',
})
enqueue({ data: [lineFuzzy] })
enqueue({ data: [txFuzzy] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
dryRun: true,
confidenceThreshold: 0.9,
})
// The preview always shows the full proposal set: filtering happens only
// on apply, so the user can still review + tick fuzzy matches manually.
expect(result.matches).toHaveLength(1)
expect(result.matches[0].method).toBe('auto_fuzzy')
expect(result.applied).toBe(0)
expect(result.skippedBelowThreshold).toBe(0)
})
it('applies every match, including fuzzy, when no threshold is given (legacy behavior)', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const txFuzzy = makeTransaction({ id: 'tx-fuzzy', amount: -999.99, date: '2024-06-15', currency: 'SEK' })
const lineFuzzy = makeGLLine({
line_id: 'line-fuzzy',
journal_entry_id: 'je-fuzzy',
credit_amount: 1000,
entry_date: '2024-06-15',
})
enqueue({ data: [lineFuzzy] })
enqueue({ data: [txFuzzy] })
enqueue({ data: [{ id: 'tx-fuzzy' }] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
dryRun: false,
})
expect(result.applied).toBe(1)
expect(result.errors).toBe(0)
expect(result.skippedBelowThreshold).toBe(0)
})
it('ignores applyOnly on dry runs and returns the full match set', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx1 = makeTransaction({ id: 'tx-1', amount: 1000, date: '2024-06-15', currency: 'SEK' })
const line1 = makeGLLine({
line_id: 'line-1',
journal_entry_id: 'je-1',
debit_amount: 1000,
entry_date: '2024-06-15',
})
enqueue({ data: [line1] })
enqueue({ data: [tx1] })
const result = await runReconciliation(supabase as never, 'company-1', 'user-1', {
dryRun: true,
applyOnly: [],
})
expect(result.matches).toHaveLength(1)
expect(result.applied).toBe(0)
})
})
// ============================================================
// manualLink
// ============================================================
describe('manualLink', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
function createQueueMockSupabase() {
const resultQueue: { data: unknown; error: unknown }[] = []
const enqueue = (...results: { data?: unknown; error?: unknown }[]) => {
for (const r of results) {
resultQueue.push({ data: r.data ?? null, error: r.error ?? null })
}
}
const buildChain = (): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
if (prop === 'then') {
const next = resultQueue.shift() ?? { data: null, error: null }
return (resolve: (v: unknown) => void) => resolve(next)
}
return (..._args: unknown[]) => buildChain()
},
}
return new Proxy({}, handler)
}
const supabase = {
from: vi.fn().mockImplementation(() => buildChain()),
rpc: vi.fn().mockImplementation(() => buildChain()),
}
return { supabase, enqueue }
}
it('rejects when transaction not found', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// Transaction query returns null
enqueue({ data: null, error: { message: 'Not found' } })
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1')
expect(result.success).toBe(false)
expect(result.error).toBe('Transaktionen kunde inte hittas.')
})
it('rejects when transaction is already linked to a LIVE (posted) entry', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({ id: 'tx-1', journal_entry_id: 'je-existing' })
// Transaction found, still pointing at a live posted verifikat
enqueue({ data: tx })
enqueue({ data: { status: 'posted' } }) // hasLiveJournalEntryLink: prior link is live
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1')
expect(result.success).toBe(false)
expect(result.error).toBe('Transaktionen är redan kopplad till en verifikation.')
})
it('re-links a transaction stranded on a reversed entry (#988)', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// Still carries a pointer at a status='reversed' entry (storno/correction
// left it behind). The UI shows it as "utan koppling", so manualLink must
// treat it as free and overwrite the stale pointer.
const tx = makeTransaction({ id: 'tx-1', journal_entry_id: 'je-reversed' })
enqueue({ data: tx }) // tx fetch
enqueue({ data: { status: 'reversed' } }) // hasLiveJournalEntryLink: stale link
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } }) // target JE fetch
enqueue({ data: [{ debit_amount: 1000, credit_amount: 0, account_number: '1930' }] }) // line on 1930
enqueue({ data: [{ id: 'tx-1' }] }) // UPDATE .eq(stale id) → 1 row overwritten
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1', '1930')
expect(result.success).toBe(true)
})
it('rejects when journal entry has no line on the selected account', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({ id: 'tx-1', journal_entry_id: null })
// Transaction found (cash_account_id null → cross-check skipped)
enqueue({ data: tx })
// Journal entry found
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
// No line on the selected account
enqueue({ data: [] })
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1', '1930')
expect(result.success).toBe(false)
expect(result.error).toBe('Verifikationen saknar rad på 1930')
})
it('rejects when the transaction belongs to a different cash account', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({
id: 'tx-1',
journal_entry_id: null,
cash_account_id: 'ca-1931',
})
// Transaction found (bound to a cash account)
enqueue({ data: tx })
// Journal entry found + posted
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
// Cross-check: this cash account maps to 1931, but we're reconciling 1930
enqueue({ data: { ledger_account: '1931' } })
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1', '1930')
expect(result.success).toBe(false)
expect(result.error).toBe('Transaktionen hör till 1931, inte 1930')
})
it('succeeds when all validations pass (line on selected account)', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({ id: 'tx-1', journal_entry_id: null })
// Transaction found (cash_account_id null → cross-check skipped)
enqueue({ data: tx })
// Journal entry found
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
// Line exists on the selected account
enqueue({ data: [{ debit_amount: 1000, credit_amount: 0, account_number: '1930' }] })
// Update succeeds: .select('id') returns the updated row
enqueue({ data: [{ id: 'tx-1' }] })
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1', '1930')
expect(result.success).toBe(true)
})
it('rejects when a concurrent linker won the race (0 rows updated)', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({ id: 'tx-1', journal_entry_id: null })
enqueue({ data: tx })
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
enqueue({ data: [{ debit_amount: 1000, credit_amount: 0, account_number: '1930' }] })
// The .is('journal_entry_id', null) optimistic-lock filter matched nothing:
// another session linked the transaction between our read and this write.
enqueue({ data: [] })
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1', '1930')
expect(result.success).toBe(false)
expect(result.error).toBe('Transaktionen är redan kopplad till en verifikation.')
})
it('succeeds for a bound transaction when the account matches', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
const tx = makeTransaction({
id: 'tx-1',
journal_entry_id: null,
cash_account_id: 'ca-1930',
})
enqueue({ data: tx })
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
// Cross-check: cash account maps to the account being reconciled
enqueue({ data: { ledger_account: '1930' } })
// Line exists on 1930
enqueue({ data: [{ debit_amount: 1000, credit_amount: 0, account_number: '1930' }] })
// Update succeeds: .select('id') returns the updated row
enqueue({ data: [{ id: 'tx-1' }] })
const result = await manualLink(supabase as never, 'company-1', 'tx-1', 'je-1', 'user-1', '1930')
expect(result.success).toBe(true)
})
it('allows N:1, does not reject when the verifikat already has a linked transaction', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// This transaction is itself unlinked; the TARGET entry already has another
// transaction pointing at it. manualLink no longer queries for / rejects
// that: several bank transactions may settle one verifikat (a salary run
// paid in multiple transfers). The only per-transaction guard is that THIS
// transaction isn't already linked (tx.journal_entry_id), still enforced.
const tx = makeTransaction({ id: 'tx-2', journal_entry_id: null })
enqueue({ data: tx })
enqueue({ data: { id: 'je-1', user_id: 'company-1', status: 'posted' } })
enqueue({ data: [{ debit_amount: 1000, credit_amount: 0, account_number: '1930' }] })
// Update succeeds: note there is NO existing-link lookup in the sequence.
enqueue({ data: [{ id: 'tx-2' }] })
const result = await manualLink(supabase as never, 'company-1', 'tx-2', 'je-1', 'user-1', '1930')
expect(result.success).toBe(true)
})
})
// ============================================================
// unlinkReconciliation
// ============================================================
describe('unlinkReconciliation', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
function createQueueMockSupabase() {
const resultQueue: { data: unknown; error: unknown }[] = []
const enqueue = (...results: { data?: unknown; error?: unknown }[]) => {
for (const r of results) {
resultQueue.push({ data: r.data ?? null, error: r.error ?? null })
}
}
const buildChain = (): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
if (prop === 'then') {
const next = resultQueue.shift() ?? { data: null, error: null }
return (resolve: (v: unknown) => void) => resolve(next)
}
return (..._args: unknown[]) => buildChain()
},
}
return new Proxy({}, handler)
}
const supabase = {
from: vi.fn().mockImplementation(() => buildChain()),
rpc: vi.fn().mockImplementation(() => buildChain()),
}
return { supabase, enqueue }
}
it('rejects when transaction has no reconciliation_method (categorization entry)', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// Transaction found with journal_entry_id but no reconciliation_method
enqueue({
data: {
id: 'tx-1',
journal_entry_id: 'je-1',
reconciliation_method: null,
},
})
const result = await unlinkReconciliation(supabase as never, 'company-1', 'tx-1', 'user-1')
expect(result.success).toBe(false)
expect(result.error).toContain('Cannot unlink')
})
it('succeeds when reconciliation_method is set', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// Transaction found with reconciliation_method
enqueue({
data: {
id: 'tx-1',
journal_entry_id: 'je-1',
reconciliation_method: 'auto_exact',
},
})
// Update succeeds
enqueue({ data: null, error: null })
const result = await unlinkReconciliation(supabase as never, 'company-1', 'tx-1', 'user-1')
expect(result.success).toBe(true)
})
it('attributes the audit log row to the acting user, not the company', async () => {
// Regression: unlinkReconciliation used to pass companyId where
// logMatchEvent expects userId, so payment_match_log.user_id recorded the
// company UUID (or the insert failed its FK silently).
const inserts: Record<string, unknown>[] = []
const resultQueue: { data: unknown; error: unknown }[] = [
{
data: { id: 'tx-1', journal_entry_id: 'je-1', reconciliation_method: 'manual' },
error: null,
},
{ data: null, error: null }, // update
]
const buildChain = (table?: string): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
if (prop === 'then') {
const next = resultQueue.shift() ?? { data: null, error: null }
return (resolve: (v: unknown) => void) => resolve(next)
}
if (prop === 'insert') {
return (row: Record<string, unknown>) => {
if (table === 'payment_match_log') inserts.push(row)
return buildChain(table)
}
}
return (..._args: unknown[]) => buildChain(table)
},
}
return new Proxy({}, handler)
}
const supabase = {
from: vi.fn().mockImplementation((table: string) => buildChain(table)),
rpc: vi.fn().mockImplementation(() => buildChain()),
}
const result = await unlinkReconciliation(supabase as never, 'company-1', 'tx-1', 'user-1')
expect(result.success).toBe(true)
expect(inserts).toHaveLength(1)
expect(inserts[0].user_id).toBe('user-1')
})
})
// ============================================================
// getReconciliationStatus: IB exclusion (PR 3 of #443)
// ============================================================
describe('getReconciliationStatus', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
function createQueueMockSupabase() {
const resultQueue: { data: unknown; error: unknown }[] = []
const enqueue = (...results: { data?: unknown; error?: unknown }[]) => {
for (const r of results) resultQueue.push({ data: r.data ?? null, error: r.error ?? null })
}
const buildChain = (): unknown => {
const handler: ProxyHandler<object> = {
get(_target, prop) {
if (prop === 'then') {
const next = resultQueue.shift() ?? { data: null, error: null }
return (resolve: (v: unknown) => void) => resolve(next)
}
return (..._args: unknown[]) => buildChain()
},
}
return new Proxy({}, handler)
}
const supabase = {
from: vi.fn().mockImplementation(() => buildChain()),
rpc: vi.fn().mockImplementation(() => buildChain()),
}
return { supabase, enqueue }
}
it('reports is_reconciled=true when only the IB voucher is unmatched on 1930', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// 1) transactions: 1000 SEK matched (journal_entry_id set)
enqueue({
data: [{ amount: 1000, journal_entry_id: 'je-tx', reconciliation_method: 'auto_exact' }],
})
// 2) journal_entry_lines: 50,000 IB debit + 1000 matched debit on 1930
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-gen1', status: 'posted', source_type: 'opening_balance' },
{ id: 'je-gen2', status: 'posted', source_type: 'bank_import' },
],
})
enqueue({
data: [
{ debit_amount: 50000, credit_amount: 0, journal_entry_id: 'je-gen1' },
{ debit_amount: 1000, credit_amount: 0, journal_entry_id: 'je-gen2' },
],
})
// 3) RPC get_unlinked_1930_lines: returns empty (RPC excludes IB after migration)
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.gl_1930_balance).toBe(51000) // includes IB
expect(status.gl_1930_period_movement).toBe(1000) // excludes IB
expect(status.gl_1930_opening_balance).toBe(50000)
expect(status.bank_transaction_total).toBe(1000)
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
expect(status.unmatched_gl_line_count).toBe(0)
})
it('reports is_reconciled=false and a non-zero difference when a real bank tx is unmatched', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
// 1) transactions: 1500 total, only 1000 matched
enqueue({
data: [
{ amount: 1000, journal_entry_id: 'je-1', reconciliation_method: null },
{ amount: 500, journal_entry_id: null, reconciliation_method: null },
],
})
// 2) GL lines: 50,000 IB + 1000 booked
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-gen3', status: 'posted', source_type: 'opening_balance' },
{ id: 'je-gen4', status: 'posted', source_type: 'bank_import' },
],
})
enqueue({
data: [
{ debit_amount: 50000, credit_amount: 0, journal_entry_id: 'je-gen3' },
{ debit_amount: 1000, credit_amount: 0, journal_entry_id: 'je-gen4' },
],
})
// 3) RPC: empty
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.bank_transaction_total).toBe(1500)
expect(status.gl_1930_period_movement).toBe(1000)
expect(status.gl_1930_opening_balance).toBe(50000)
expect(status.difference).toBe(500) // bank > GL period movement
expect(status.is_reconciled).toBe(false)
expect(status.unmatched_transaction_count).toBe(1)
})
it('handles companies with no IB on 1930 (period_movement === gl_balance)', async () => {
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({ data: [{ amount: 100, journal_entry_id: 'je-1', reconciliation_method: 'auto_exact' }] })
// Two-step entry-lines fetch: entries page first, then lines by entry id.
enqueue({ data: [{ id: 'je-1', status: 'posted', source_type: 'bank_import' }] })
enqueue({
data: [{ debit_amount: 100, credit_amount: 0, journal_entry_id: 'je-1' }],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.gl_1930_opening_balance).toBe(0)
expect(status.gl_1930_period_movement).toBe(100)
expect(status.gl_1930_balance).toBe(100)
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
})
it('splits IB from period movement via the reattached parent entry', async () => {
// The two-step entry-lines fetch reattaches the parent entry object on
// each line under `journal_entries`; entryOf() reads source_type from it
// to split the IB summary out of the period movement.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({ data: [] })
// Two-step entry-lines fetch: entries page first, then lines by entry id.
enqueue({
data: [
{ id: 'je-ib', status: 'posted', source_type: 'opening_balance' },
{ id: 'je-mv', status: 'posted', source_type: 'bank_import' },
],
})
enqueue({
data: [
{ debit_amount: 1000, credit_amount: 0, journal_entry_id: 'je-ib' },
{ debit_amount: 200, credit_amount: 0, journal_entry_id: 'je-mv' },
],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.gl_1930_opening_balance).toBe(1000)
expect(status.gl_1930_period_movement).toBe(200)
})
it('reconciles a corrected bank receipt and keeps gl_1930_balance equal to the balance sheet', async () => {
// A +25000 deposit was booked to the wrong counter-account, then corrected
// via the storno flow: the original flips to 'reversed', a storno (credit
// 25000) and a correction (debit 25000) are posted, and correctEntry
// re-points the bank transaction to the live correction (je-corr).
//
// Reconciliation now sums posted+reversed on 1930, exactly as the trial
// balance / balance sheet do, so the cluster nets to the true +25000 and
// the period reconciles. gl_1930_balance must equal what the balansräkning
// shows for 1930 (the bug this widget used to have was the two disagreeing).
const { supabase, enqueue } = createQueueMockSupabase()
// 1) transactions: the +25000 deposit, re-pointed to the correction
enqueue({
data: [{ amount: 25000, journal_entry_id: 'je-corr', reconciliation_method: 'manual' }],
})
// 2) GL lines on 1930: reversed original (debit 25000), storno (credit
// 25000), correction (debit 25000). All three are summed. Served via
// the two-step entry-lines fetch: entries page, then lines by entry id.
enqueue({
data: [
{ id: 'je-orig', status: 'reversed', source_type: 'bank_transaction' },
{ id: 'je-storno', status: 'posted', source_type: 'storno' },
{ id: 'je-corr', status: 'posted', source_type: 'correction' },
],
})
const lines = [
{ debit_amount: 25000, credit_amount: 0, journal_entry_id: 'je-orig' },
{ debit_amount: 0, credit_amount: 25000, journal_entry_id: 'je-storno' },
{ debit_amount: 25000, credit_amount: 0, journal_entry_id: 'je-corr' },
]
enqueue({ data: lines })
// 3) RPC: empty
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
// Balance-sheet-equivalent: posted+reversed summed = 25000 - 25000 + 25000.
const balanceSheet1930 = lines.reduce(
(s, l) => s + l.debit_amount - l.credit_amount,
0,
)
expect(status.gl_1930_balance).toBe(balanceSheet1930) // 25000: matches BS
expect(status.gl_1930_correction_adjustment).toBe(0) // storno + correction net
expect(status.gl_1930_period_movement).toBe(25000)
expect(status.bank_transaction_total).toBe(25000)
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
})
it('reconciles an amount correction even though the correction adjustment is non-zero', async () => {
// Regression for the de-reconcile bug: a 25000 receipt was booked as 24000,
// then corrected to 25000. The storno (credit 24000) and correction (debit
// 25000) net to +1000 on 1930, and correctEntry re-points the real 25000
// feed transaction to the correction. The OLD code subtracted that +1000
// correction bucket from the movement while still counting the re-pointed
// 25000 transaction → a phantom 1000 diff. The unified inclusion rule nets
// it correctly: gl_balance = 25000 = the feed, difference = 0.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [{ amount: 25000, journal_entry_id: 'je-corr', reconciliation_method: 'manual' }],
})
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-orig', status: 'reversed', source_type: 'bank_transaction' },
{ id: 'je-storno', status: 'posted', source_type: 'storno' },
{ id: 'je-corr', status: 'posted', source_type: 'correction' },
],
})
enqueue({
data: [
{ debit_amount: 24000, credit_amount: 0, journal_entry_id: 'je-orig' },
{ debit_amount: 0, credit_amount: 24000, journal_entry_id: 'je-storno' },
{ debit_amount: 25000, credit_amount: 0, journal_entry_id: 'je-corr' },
],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.gl_1930_balance).toBe(25000)
expect(status.gl_1930_correction_adjustment).toBe(1000) // -24000 + 25000
expect(status.gl_1930_period_movement).toBe(25000)
expect(status.bank_transaction_total).toBe(25000)
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
})
it('reconciles a legacy deposit still linked to the reversed original (no special-case drop)', async () => {
// Pre-relink data: the +25000 deposit was matched, the entry corrected, but
// the transaction was never re-pointed and still references the reversed
// original. With posted+reversed summed on the GL side and NO reversed-link
// dropping on the bank side, this still nets to zero: symmetric without any
// special case.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [{ amount: 25000, journal_entry_id: 'je-orig', reconciliation_method: 'manual' }],
})
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-orig', status: 'reversed', source_type: 'bank_transaction' },
{ id: 'je-storno', status: 'posted', source_type: 'storno' },
{ id: 'je-corr', status: 'posted', source_type: 'correction' },
],
})
enqueue({
data: [
{ debit_amount: 25000, credit_amount: 0, journal_entry_id: 'je-orig' },
{ debit_amount: 0, credit_amount: 25000, journal_entry_id: 'je-storno' },
{ debit_amount: 25000, credit_amount: 0, journal_entry_id: 'je-corr' },
],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.bank_transaction_total).toBe(25000) // counted, not dropped
expect(status.gl_1930_period_movement).toBe(25000)
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
})
it('flags a book-only entry that moves the bank balance with no feed counterpart', async () => {
// Intentional behaviour: a manual posting that moves 1930 without a matching
// bank-feed transaction (e.g. interest the feed import missed, booked debit
// 1930 / credit 8310) is a genuine reconciliation break: the GL balance no
// longer matches the statement. It must surface as a difference, not be
// silently swept under a "correction" exclusion.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({ data: [] }) // no bank-feed transactions
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-manual', status: 'posted', source_type: 'manual' },
],
})
enqueue({
data: [
{ debit_amount: 500, credit_amount: 0, journal_entry_id: 'je-manual' },
],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.gl_1930_period_movement).toBe(500)
expect(status.bank_transaction_total).toBe(0)
expect(status.difference).toBe(-500)
expect(status.is_reconciled).toBe(false)
})
it('floors a full-history window at the IB date so a prior period cannot count the IB (issue #751)', async () => {
// Real-world repro: the widget's date filter defaults to "full history"
// (no dateFrom). A company with two fiscal periods has prior-period (2025)
// movements on the account that net to EXACTLY the opening balance, plus the
// new period's IB entry dated on period start. Summing the whole history and
// only subtracting the IB *summary* leaves the prior-period *detail* in the
// movement while the bank feed only covers the current period: a phantom
// difference equal to the IB. The server now floors the window at the most
// recent IB date on the account, clamping BOTH sides to the current period.
const { supabase, enqueue } = createQueueMockSupabase()
// 1) transactions: a prior-period feed line (6000, 2025) + the current
// period's feed (5000, 2026). The floor must drop the 2025 one.
enqueue({
data: [
{ date: '2025-03-31', amount: 6000, journal_entry_id: 'je-p', reconciliation_method: 'manual' },
{ date: '2026-02-15', amount: 5000, journal_entry_id: 'je-c', reconciliation_method: 'manual' },
],
})
// 2) GL lines on the account: prior-period movements (6000 + 4000 = 10000,
// dated 2025) that net to the IB, the IB itself (10000, dated 2026-01-01),
// and the current period's movement (5000, dated 2026).
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-p1', status: 'posted', source_type: 'import', entry_date: '2025-03-31' },
{ id: 'je-p2', status: 'posted', source_type: 'import', entry_date: '2025-09-30' },
{ id: 'je-ib', status: 'posted', source_type: 'opening_balance', entry_date: '2026-01-01' },
{ id: 'je-c1', status: 'posted', source_type: 'bank_transaction', entry_date: '2026-02-15' },
],
})
enqueue({
data: [
{ debit_amount: 6000, credit_amount: 0, journal_entry_id: 'je-p1' },
{ debit_amount: 4000, credit_amount: 0, journal_entry_id: 'je-p2' },
{ debit_amount: 10000, credit_amount: 0, journal_entry_id: 'je-ib' },
{ debit_amount: 5000, credit_amount: 0, journal_entry_id: 'je-c1' },
],
})
// 3) RPC: empty
enqueue({ data: [] })
// No dateFrom: the "full history" default that triggers the bug.
const status = await getReconciliationStatus(supabase as never, 'company-1')
// Both sides clamped to >= 2026-01-01 (the IB date): only the IB + the
// current-period movement remain on the GL side; only the 2026 feed remains
// on the bank side. The prior period (which equalled the IB) is excluded.
expect(status.gl_1930_balance).toBe(15000) // IB 10000 + 5000 (NOT 25000)
expect(status.gl_1930_period_movement).toBe(5000) // IB excluded
expect(status.gl_1930_opening_balance).toBe(10000) // UI "räknas inte" note stays truthful
expect(status.bank_transaction_total).toBe(5000) // 2025 feed floored out
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
})
it('floors at the IB date even when the caller passes a dateFrom earlier than the IB', async () => {
// Safety net for a manual date override / direct API call: clearing the date
// filter (or setting it before the IB) must not resurrect the phantom diff.
// effectiveFrom = max(dateFrom, ibDate), so an earlier dateFrom is raised.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [
{ date: '2025-05-01', amount: 8000, journal_entry_id: 'je-p', reconciliation_method: 'manual' },
{ date: '2026-04-10', amount: 3000, journal_entry_id: 'je-c', reconciliation_method: 'manual' },
],
})
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-p1', status: 'posted', source_type: 'import', entry_date: '2025-05-01' },
{ id: 'je-ib', status: 'posted', source_type: 'opening_balance', entry_date: '2026-01-01' },
{ id: 'je-c1', status: 'posted', source_type: 'bank_transaction', entry_date: '2026-04-10' },
],
})
enqueue({
data: [
{ debit_amount: 8000, credit_amount: 0, journal_entry_id: 'je-p1' },
{ debit_amount: 8000, credit_amount: 0, journal_entry_id: 'je-ib' },
{ debit_amount: 3000, credit_amount: 0, journal_entry_id: 'je-c1' },
],
})
enqueue({ data: [] })
// dateFrom deliberately before the IB date.
const status = await getReconciliationStatus(supabase as never, 'company-1', '2025-01-01')
expect(status.gl_1930_period_movement).toBe(3000) // IB + prior detail both excluded
expect(status.gl_1930_opening_balance).toBe(8000)
expect(status.bank_transaction_total).toBe(3000) // 2025 feed floored out
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
})
it('reconciles a mid-period window (dateFrom after the IB date) on movements alone', async () => {
// Per-month reconciliation: the user scopes to March, after the fiscal-year
// IB (2026-01-01). effectiveFrom = max(dateFrom, ibDate) = the March dateFrom,
// so the IB and Jan/Feb movements are correctly excluded: they belong to the
// opening position of a March window, not its movements. gl_1930_opening_balance
// is 0 here BY DESIGN: a mid-period window contains no fiscal-year IB, so the
// "räknas inte" note is simply absent (not misleadingly zero). The window
// reconciles on March's movements vs March's feed.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [
{ date: '2026-02-10', amount: 2000, journal_entry_id: 'je-feb', reconciliation_method: 'manual' },
{ date: '2026-03-15', amount: 3000, journal_entry_id: 'je-mar', reconciliation_method: 'manual' },
],
})
// Two-step entry-lines fetch: entries page first, then lines by entry id
// (parents reattached under journal_entries by the helper).
enqueue({
data: [
{ id: 'je-ib', status: 'posted', source_type: 'opening_balance', entry_date: '2026-01-01' },
{ id: 'je-feb1', status: 'posted', source_type: 'import', entry_date: '2026-02-10' },
{ id: 'je-mar1', status: 'posted', source_type: 'import', entry_date: '2026-03-15' },
],
})
enqueue({
data: [
{ debit_amount: 9000, credit_amount: 0, journal_entry_id: 'je-ib' },
{ debit_amount: 2000, credit_amount: 0, journal_entry_id: 'je-feb1' },
{ debit_amount: 3000, credit_amount: 0, journal_entry_id: 'je-mar1' },
],
})
enqueue({ data: [] })
// dateFrom in March: after the 2026-01-01 IB.
const status = await getReconciliationStatus(supabase as never, 'company-1', '2026-03-01')
expect(status.gl_1930_opening_balance).toBe(0) // IB not part of a March window
expect(status.gl_1930_period_movement).toBe(3000) // only March movements
expect(status.bank_transaction_total).toBe(3000) // only March feed
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
})
// ----------------------------------------------------------------
// Avstämt requires BOTH a zero net difference AND nothing unidentified
// ----------------------------------------------------------------
it('is NOT reconciled when two unmatched transactions offset each other', async () => {
// +500 and -500 net to zero against a zero period movement, so the old
// net-difference test called this avstämt while BOTH rows were still
// unbooked affärshändelser, each owing its own verifikation identifying
// belopp and motpart (BFL 5 kap 1-2 §, 6-7 §). Offsetting two unknowns is
// not knowing either one (ÅRL 2 kap: individuell värdering,
// bruttoredovisning): the account is not avstämt until both are booked.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [
{ date: '2026-03-05', amount: 500, journal_entry_id: null, reconciliation_method: null },
{ date: '2026-03-06', amount: -500, journal_entry_id: null, reconciliation_method: null },
],
})
// Only the IB on the ledger: period movement is 0, matching the bank net.
enqueue({
data: [{ id: 'je-ib', status: 'posted', source_type: 'opening_balance', entry_date: '2026-01-01' }],
})
enqueue({ data: [{ debit_amount: 50000, credit_amount: 0, journal_entry_id: 'je-ib' }] })
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.difference).toBe(0)
expect(status.unmatched_transaction_count).toBe(2)
expect(status.is_reconciled).toBe(false)
})
// ----------------------------------------------------------------
// Foreign-currency accounts are reconciled in their OWN currency
// ----------------------------------------------------------------
it('reconciles a EUR cash account in EUR, not against its SEK ledger figures', async () => {
// 100 EUR booked at 11.50: debit_amount holds the 1150 SEK conversion while
// the EUR amount sits in amount_in_currency. Summing the SEK column against
// a EUR bank feed produced a difference roughly the size of the exchange
// rate, so a foreign cash account could never show is_reconciled.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [{ date: '2026-03-05', amount: 100, journal_entry_id: 'je-eur', reconciliation_method: 'manual' }],
})
enqueue({
data: [{ id: 'je-eur', status: 'posted', source_type: 'import', entry_date: '2026-03-05' }],
})
enqueue({
data: [
{
debit_amount: 1150,
credit_amount: 0,
currency: 'EUR',
amount_in_currency: 100,
journal_entry_id: 'je-eur',
},
],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(
supabase as never,
'company-1',
undefined,
undefined,
'1932',
'EUR',
)
expect(status.currency).toBe('EUR')
expect(status.gl_1930_period_movement).toBe(100) // EUR, not 1150 SEK
expect(status.bank_transaction_total).toBe(100)
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
expect(status.not_reconcilable_reason).toBeNull()
expect(status.unconvertible_gl_line_count).toBe(0)
})
it('reports not-reconcilable-yet when a foreign account has lines with no amount in that currency', async () => {
// A SIE-imported / pre-FX line on the EUR account: only a SEK figure, no
// per-row rate. There is nothing honest to convert with, so the window must
// say so instead of quietly treating 1150 SEK as 1150 EUR.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [{ date: '2026-03-05', amount: 100, journal_entry_id: 'je-eur', reconciliation_method: 'manual' }],
})
enqueue({
data: [{ id: 'je-eur', status: 'posted', source_type: 'import', entry_date: '2026-03-05' }],
})
enqueue({
data: [{ debit_amount: 1150, credit_amount: 0, currency: 'SEK', journal_entry_id: 'je-eur' }],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(
supabase as never,
'company-1',
undefined,
undefined,
'1932',
'EUR',
)
expect(status.unconvertible_gl_line_count).toBe(1)
expect(status.not_reconcilable_reason).toBe('gl_lines_missing_currency_amount')
expect(status.is_reconciled).toBe(false)
})
it('leaves a SEK account untouched when its lines carry a foreign LABEL', async () => {
// 95%-path regression guard: a SEK payment of a EUR supplier invoice is
// labelled 'EUR' on the line while debit/credit are SEK. Reconciling 1930
// in SEK must use the SEK columns and never flag it as unconvertible.
const { supabase, enqueue } = createQueueMockSupabase()
enqueue({
data: [{ date: '2026-03-05', amount: -1150, journal_entry_id: 'je-1', reconciliation_method: 'manual' }],
})
enqueue({
data: [{ id: 'je-1', status: 'posted', source_type: 'import', entry_date: '2026-03-05' }],
})
enqueue({
data: [
{
debit_amount: 0,
credit_amount: 1150,
currency: 'EUR',
amount_in_currency: 100,
journal_entry_id: 'je-1',
},
],
})
enqueue({ data: [] })
const status = await getReconciliationStatus(supabase as never, 'company-1')
expect(status.currency).toBe('SEK')
expect(status.gl_1930_period_movement).toBe(-1150)
expect(status.difference).toBe(0)
expect(status.is_reconciled).toBe(true)
expect(status.unconvertible_gl_line_count).toBe(0)
expect(status.not_reconcilable_reason).toBeNull()
})
})