Files
accounted/lib/bookkeeping/__tests__/invoice-payment-lines.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

607 lines
28 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, it, expect } from 'vitest'
import {
buildInvoicePaymentClearingLines,
InvoiceBookingRateMissingError,
MATCH_INVOICE_BOOKING_RATE_MISSING,
} from '../invoice-payment-lines'
import { getErrorMessage } from '@/lib/errors/get-error-message'
describe('buildInvoicePaymentClearingLines', () => {
describe('same currency (SEK invoice + SEK tx)', () => {
it('full payment: 1930 = 1510 = tx amount, no FX line', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: 1250, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1250, total: 1250, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(1250)
expect(result.arSek).toBe(1250)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 1250, credit_amount: 0 })
expect(result.lines[1]).toMatchObject({ account_number: '1510', debit_amount: 0, credit_amount: 1250 })
})
it('partial payment: 1930 = 1510 = tx amount (the actual SEK received)', () => {
// Scenario from the user: invoice 1 250, prior 230 partial, now 1 000 hits.
// 1930/1510 must equal 1 000 (not 1 250). After this verifikat the invoice
// remaining is 20 SEK and status stays partially_paid (handled by the
// caller, not this helper).
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1020, total: 1250, paid_amount: 230 },
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(1000)
expect(result.arSek).toBe(1000)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
})
it('expense tx (negative amount) treats absolute SEK value', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: -500, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 500, total: 500, paid_amount: 0 },
'desc',
)
expect(result.bankSek).toBe(500)
expect(result.arSek).toBe(500)
})
})
describe('cross currency (USD invoice + SEK tx)', () => {
it('bank received MORE SEK than booked: gain to 3960', () => {
// Invoice 100 USD booked at 10.00 (1000 SEK on 1510)
// Bank receives 1100 SEK (rate moved to 11.00 by payment date)
// FX gain = 100 SEK → 3960 credit
const result = buildInvoicePaymentClearingLines(
{ amount: 1100, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'USD', exchange_rate: 10, remaining_amount: 100, total: 100, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(1100)
expect(result.arSek).toBe(1000)
expect(result.fxDiffSek).toBe(-100)
expect(result.lines).toHaveLength(3)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 1100 })
expect(result.lines[1]).toMatchObject({ account_number: '1510', credit_amount: 1000 })
expect(result.lines[2]).toMatchObject({
account_number: '3960',
credit_amount: 100,
line_description: 'Valutakursvinst',
})
// Balanced
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('ambiguous loss scenario (bank < SEK booked) is treated as partial: defers FX', () => {
// Invoice 100 USD booked at 10.50 (1050 SEK on 1510)
// Bank receives 1000 SEK: could be (a) partial payment that didn't
// cover the full USD amount, or (b) full payment at a worse FX rate.
// From a SEK-only bank tx we can't distinguish; defaulting to "partial"
// is the safer choice (no premature 1510 zeroing). If the user knows
// it's actually a full-clear-with-loss, they use mark-paid with an
// explicit exchange_rate_difference instead.
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'USD', exchange_rate: 10.5, remaining_amount: 100, total: 100, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(1000)
expect(result.arSek).toBe(1000)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
})
it('partial cross-currency WITH paidInInvoiceCurrency: posts proportional 1510 credit + FX-diff line', () => {
// The proper-FX path (round-10): caller supplies the invoice-currency
// equivalent of the bank payment, computed at today's Riksbanken rate.
// The helper credits 1510 by that × invoice.exchange_rate (the
// booking rate) and posts the FX-diff line so the verifikat balances.
//
// Scenario: 1000 SEK bank tx, invoice 140 USD @ 9.30 (booked). Today
// Riksbanken rate: 10.45. paidInInvoiceCurrency = 1000/10.45 = 95.6938.
// arSek = 95.6938 × 9.30 = 889.95. fxDiff = 889.95 - 1000 = -110.05
// (negative → gain → 3960 Cr 110.05).
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'USD', exchange_rate: 9.3, remaining_amount: 140, total: 140, paid_amount: 0 },
'Inbetalning kundfaktura',
95.6938, // paidInInvoiceCurrency
)
expect(result.bankSek).toBe(1000)
expect(result.arSek).toBeCloseTo(889.95, 1)
expect(result.fxDiffSek).toBeCloseTo(-110.05, 1)
expect(result.lines).toHaveLength(3)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 1000 })
expect(result.lines[1]).toMatchObject({ account_number: '1510' })
expect(result.lines[2]).toMatchObject({
account_number: '3960',
line_description: 'Valutakursvinst',
})
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.abs(debit - credit)).toBeLessThanOrEqual(0.005)
})
it('cross-currency WITH paidInInvoiceCurrency, bank < booked: loss to 7960', () => {
// Mirror of the gain case above with the opposite sign: guards the
// kursförlust branch the route's gain-only assertion never reaches
// (Swedish compliance review, PR #615). Invoice 100 USD booked at 9.30
// (930 SEK on 1510); the 100 USD settlement only fetched 900 SEK at the
// weaker 9.00 payment-date rate. arSek = 100 × 9.30 = 930.
// fxDiff = 930 − 900 = +30 (positive → kursförlust → 7960 Dr 30).
const result = buildInvoicePaymentClearingLines(
{ amount: 900, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'USD', exchange_rate: 9.3, remaining_amount: 100, total: 100, paid_amount: 0 },
'Inbetalning kundfaktura',
100, // paidInInvoiceCurrency (full settlement at today's 9.00 rate)
)
expect(result.bankSek).toBe(900)
expect(result.arSek).toBeCloseTo(930, 2)
expect(result.fxDiffSek).toBeCloseTo(30, 2)
expect(result.lines).toHaveLength(3)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 900 })
expect(result.lines[1]).toMatchObject({ account_number: '1510', credit_amount: 930 })
expect(result.lines[2]).toMatchObject({
account_number: '7960',
debit_amount: 30,
line_description: 'Valutakursförlust',
})
// Balanced to the öre: Dr 900 + 30 = 930 = Cr 930.
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.abs(debit - credit)).toBeLessThanOrEqual(0.005)
})
it('partial cross-currency payment defers FX: bank-leg = AR-leg = bankSek, no 3960/7960 line', () => {
// Invoice 140 USD @ 15.30 (2142 SEK booked on 1510)
// Bank receives 230 SEK: way below the 2142 remaining. If we credited
// the full 2142 to 1510 we'd zero the GL balance while the invoice row
// stayed partially_paid (BFL 5 kap 4-5§ violation). Defer FX to the
// final settlement that closes the invoice.
const result = buildInvoicePaymentClearingLines(
{ amount: 230, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'USD', exchange_rate: 15.3, remaining_amount: 140, total: 140, paid_amount: 0 },
'Delbetalning kundfaktura',
)
expect(result.bankSek).toBe(230)
expect(result.arSek).toBe(230)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 230 })
expect(result.lines[1]).toMatchObject({ account_number: '1510', credit_amount: 230 })
})
it('exact match: no FX line', () => {
// Invoice 100 USD @ 10.00 (1000 SEK booked); bank receives 1000 SEK
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'USD', exchange_rate: 10, remaining_amount: 100, total: 100, paid_amount: 0 },
'desc',
)
expect(result.bankSek).toBe(1000)
expect(result.arSek).toBe(1000)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
})
it('sub-öre FX diff is suppressed (within floating-point tolerance)', () => {
// 100.001 USD × 10 = 1000.01, but bookkeeping rounds at the line level
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: null, currency: 'SEK', exchange_rate: null },
{
currency: 'USD',
exchange_rate: 10,
remaining_amount: 100.0001,
total: 100.0001,
paid_amount: 0,
},
'desc',
)
expect(Math.abs(result.fxDiffSek)).toBeLessThanOrEqual(0.005)
expect(result.lines).toHaveLength(2)
})
})
describe('öresavrundning (pure SEK, sub-krona difference → 3740)', () => {
it('customer paid a sub-krona SHORT: clears full 1510, books 3740 debit (förlust)', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1000.25, total: 1000.25, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.arSek).toBe(1000.25) // full remaining cleared → invoice settles
expect(result.oreRoundingSek).toBe(0.25)
expect(result.lines).toHaveLength(3)
expect(result.lines.find((l) => l.account_number === '1930')?.debit_amount).toBe(1000)
expect(result.lines.find((l) => l.account_number === '1510')?.credit_amount).toBe(1000.25)
expect(result.lines.find((l) => l.account_number === '3740')?.debit_amount).toBe(0.25)
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('customer paid a sub-krona OVER: clears full 1510, books 3740 credit (vinst)', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: 1000.25, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1000, total: 1000, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.arSek).toBe(1000)
expect(result.oreRoundingSek).toBe(-0.25)
expect(result.lines.find((l) => l.account_number === '3740')?.credit_amount).toBe(0.25)
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('a ≥1 kr shortfall stays a partial (no 3740, AR = bank)', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: 600, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1000, total: 1000, paid_amount: 0 },
'Delbetalning kundfaktura',
)
expect(result.arSek).toBe(600)
expect(result.oreRoundingSek).toBe(0)
expect(result.lines).toHaveLength(2)
})
})
describe('same currency foreign (USD invoice + USD tx)', () => {
it('clears 1510 at the booking rate and books the realized kursdiff, using tx amount_sek for the bank-leg', () => {
// USD-denominated bank account paying a USD invoice: ingest converts
// tx → SEK using the bank-date rate (amount_sek = 1 100). The 100 USD
// receivable was BOOKED at 10,00 (1 000 kr on 1510), so:
// arSek = 100 × 10,00 = 1 000,00
// fxDiffSek = 1 000,00 − 1 100,00 = −100,00 → kursvinst → 3960 Cr 100
const result = buildInvoicePaymentClearingLines(
{ amount: 100, amount_sek: 1100, currency: 'USD', exchange_rate: 11 },
{ currency: 'USD', exchange_rate: 10, remaining_amount: 100, total: 100, paid_amount: 0 },
'desc',
)
expect(result.bankSek).toBe(1100)
expect(result.arSek).toBe(1000)
expect(result.fxDiffSek).toBe(-100)
expect(result.lines).toHaveLength(3)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 1100 })
expect(result.lines[1]).toMatchObject({ account_number: '1510', credit_amount: 1000 })
expect(result.lines[2]).toMatchObject({
account_number: '3960',
credit_amount: 100,
line_description: 'Valutakursvinst',
})
// Balanced: Dr 1100 = Cr 1000 + 100.
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
})
describe('missing invoice booking rate (foreign invoice, no exchange_rate)', () => {
// Reported case: a 1 000 EUR invoice settled by an 11 496,70 kr deposit
// while invoice.exchange_rate was never populated. The old `?? 1` valued
// the receivable at 1 000 (EUR read as SEK) and posted
// 11 496,70 − 1 000 = 10 496,70 kr to 3960 as a phantom kursvinst:
// revenue understated and FX gain overstated by the whole amount, with a
// verifikat that balanced so no trigger fired. Per ML 8 kap 21-23§ the
// receivable is valued at the rate on the taxable event and the FX
// difference is the movement between that rate and the settlement rate:
// with no booking rate there is no difference to compute, only a guess.
const EUR_INVOICE_NO_RATE = {
currency: 'EUR',
exchange_rate: null,
remaining_amount: 1000,
total: 1000,
paid_amount: 0,
}
const BANK_11496_70 = {
amount: 11496.7,
amount_sek: null,
currency: 'SEK',
exchange_rate: null,
}
it('fallback path (no paidInInvoiceCurrency): throws instead of booking a 10 496,70 phantom 3960 gain', () => {
expect(() =>
buildInvoicePaymentClearingLines(
BANK_11496_70,
EUR_INVOICE_NO_RATE,
'Inbetalning kundfaktura',
),
).toThrow(InvoiceBookingRateMissingError)
})
it('spot-rate path (with paidInInvoiceCurrency): throws too', () => {
// paidInInvoiceCurrency = 11496.70 / 11.4967 = 1000 EUR. Without the
// BOOKING rate the AR leg is still unknown, so this path must fail
// exactly like the fallback: it used the same `?? 1`.
expect(() =>
buildInvoicePaymentClearingLines(
BANK_11496_70,
EUR_INVOICE_NO_RATE,
'Inbetalning kundfaktura',
1000,
),
).toThrow(InvoiceBookingRateMissingError)
})
it('carries the structured code and the offending currency/rate', () => {
try {
buildInvoicePaymentClearingLines(BANK_11496_70, EUR_INVOICE_NO_RATE, 'desc')
expect.unreachable('should have thrown')
} catch (err) {
const e = err as InvoiceBookingRateMissingError
expect(e.code).toBe(MATCH_INVOICE_BOOKING_RATE_MISSING)
expect(e.invoiceCurrency).toBe('EUR')
expect(e.exchangeRate).toBeNull()
}
})
it('resolves to the actionable Swedish message (registry wiring)', () => {
const err = new InvoiceBookingRateMissingError('EUR', null)
const message = getErrorMessage(err)
expect(message).toContain('växelkurs')
// Never the raw English engine text.
expect(message).not.toContain('exchange rate')
})
it('a zero or absurd rate is as unusable as null', () => {
for (const rate of [0, -9.3, 1e6]) {
expect(() =>
buildInvoicePaymentClearingLines(
BANK_11496_70,
{ ...EUR_INVOICE_NO_RATE, exchange_rate: rate },
'desc',
),
).toThrow(InvoiceBookingRateMissingError)
}
})
it('WITH a booking rate the same settlement books a real kursvinst on 3960', () => {
// 1 000 EUR booked at 11,30 (11 300 kr on 1510); the bank credited
// 11 496,70 kr. Real gain = 196,70 kr, not 10 496,70.
const result = buildInvoicePaymentClearingLines(
BANK_11496_70,
{ ...EUR_INVOICE_NO_RATE, exchange_rate: 11.3 },
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(11496.7)
expect(result.arSek).toBe(11300)
expect(result.fxDiffSek).toBe(-196.7)
expect(result.lines).toHaveLength(3)
expect(result.lines[2]).toMatchObject({
account_number: '3960',
debit_amount: 0,
credit_amount: 196.7,
line_description: 'Valutakursvinst',
})
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('WITH a booking rate above the settlement rate it books a kursförlust on 7960', () => {
// Same 1 000 EUR settled for 11 496,70 kr, but booked at 11,60
// (11 600 kr on 1510): the 1 000 EUR fetched 103,30 kr less than booked.
const result = buildInvoicePaymentClearingLines(
BANK_11496_70,
{ ...EUR_INVOICE_NO_RATE, exchange_rate: 11.6 },
'Inbetalning kundfaktura',
1000,
)
expect(result.bankSek).toBe(11496.7)
expect(result.arSek).toBe(11600)
expect(result.fxDiffSek).toBe(103.3)
expect(result.lines[2]).toMatchObject({
account_number: '7960',
debit_amount: 103.3,
credit_amount: 0,
line_description: 'Valutakursförlust',
})
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('a SEK invoice with no exchange_rate is completely unaffected', () => {
// "Currency is SEK" and "rate is missing" are different conditions: a
// SEK receivable already carries its SEK value, so no rate is consulted
// and nothing may throw. exchange_rate is null on every SEK invoice.
const result = buildInvoicePaymentClearingLines(
{ amount: 11496.7, amount_sek: null, currency: 'SEK', exchange_rate: null },
{
currency: 'SEK',
exchange_rate: null,
remaining_amount: 11496.7,
total: 11496.7,
paid_amount: 0,
},
'Inbetalning kundfaktura',
)
expect(result.arSek).toBe(11496.7)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
})
it('a SEK invoice paid from a foreign-currency bank account still needs no invoice rate', () => {
// !invoiceIsForeign branch: the tx side carries its own rate/amount_sek.
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: 11496.7, currency: 'EUR', exchange_rate: 11.4967 },
{
currency: 'SEK',
exchange_rate: null,
remaining_amount: 11496.7,
total: 11496.7,
paid_amount: 0,
},
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(11496.7)
expect(result.arSek).toBe(11496.7)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
})
it('a same-currency foreign settlement (EUR invoice, EUR tx) also requires the booking rate', () => {
// Without the booking rate the SEK value the receivable was posted at
// is unknown, so neither the 1510 credit nor the kursdiff is computable.
// The old shape (arSek = bankSek, fxDiffSek = 0) credited 1510 at the
// settlement-date value and stranded the realized kursdiff there.
expect(() =>
buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: 11496.7, currency: 'EUR', exchange_rate: 11.4967 },
{ ...EUR_INVOICE_NO_RATE },
'Inbetalning kundfaktura',
),
).toThrow(InvoiceBookingRateMissingError)
})
})
describe('same-currency foreign settlement (EUR invoice, EUR tx) with a booking rate', () => {
it('clears 1510 at the booking rate and books the realized kursvinst on 3960', () => {
// 1 000 EUR booked at 11,30 → 1510 was debited 11 300,00 at issuance.
// The EUR receipt is worth 11 496,70 kr on the bank date.
// arSek = 1 000 × 11,30 = 11 300,00
// fxDiffSek = 11 300,00 − 11 496,70 = −196,70 → kursvinst → 3960 Cr
// Balanced: Dr 11 496,70 = Cr 11 300,00 + 196,70.
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: 11496.7, currency: 'EUR', exchange_rate: 11.4967 },
{ currency: 'EUR', exchange_rate: 11.3, remaining_amount: 1000, total: 1000, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(11496.7)
expect(result.arSek).toBe(11300)
expect(result.fxDiffSek).toBe(-196.7)
expect(result.lines).toHaveLength(3)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 11496.7 })
expect(result.lines[1]).toMatchObject({ account_number: '1510', credit_amount: 11300 })
expect(result.lines[2]).toMatchObject({
account_number: '3960',
debit_amount: 0,
credit_amount: 196.7,
line_description: 'Valutakursvinst',
})
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('books the realized kursförlust on 7960 when the booking rate was higher', () => {
// Same 1 000 EUR settlement worth 11 496,70 kr, but booked at 11,60:
// arSek = 1 000 × 11,60 = 11 600,00
// fxDiffSek = 11 600,00 − 11 496,70 = +103,30 → kursförlust → 7960 Dr
// Balanced: Dr 11 496,70 + 103,30 = 11 600,00 = Cr 11 600,00.
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: 11496.7, currency: 'EUR', exchange_rate: 11.4967 },
{ currency: 'EUR', exchange_rate: 11.6, remaining_amount: 1000, total: 1000, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.bankSek).toBe(11496.7)
expect(result.arSek).toBe(11600)
expect(result.fxDiffSek).toBe(103.3)
expect(result.lines[2]).toMatchObject({
account_number: '7960',
debit_amount: 103.3,
credit_amount: 0,
line_description: 'Valutakursförlust',
})
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('a partial same-currency payment credits 1510 proportionally with an accurate FX line', () => {
// 400 of 1 000 EUR paid; booked at 11,30. Bank-date value 4 598,68 kr
// (400 × 11,4967). arSek = 400 × 11,30 = 4 520,00.
// fxDiffSek = 4 520,00 − 4 598,68 = −78,68 → 3960 Cr 78,68.
// Balanced: Dr 4 598,68 = Cr 4 520,00 + 78,68. Same partial-payment
// contract as the preferred cross-currency path: 1510 moves in step
// with the AR sub-ledger and the realized kursdiff is booked now.
const result = buildInvoicePaymentClearingLines(
{ amount: 400, amount_sek: 4598.68, currency: 'EUR', exchange_rate: 11.4967 },
{ currency: 'EUR', exchange_rate: 11.3, remaining_amount: 1000, total: 1000, paid_amount: 0 },
'Delbetalning kundfaktura',
)
expect(result.bankSek).toBe(4598.68)
expect(result.arSek).toBe(4520)
expect(result.fxDiffSek).toBe(-78.68)
expect(result.lines).toHaveLength(3)
expect(result.lines[2]).toMatchObject({ account_number: '3960', credit_amount: 78.68 })
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
it('no FX line when the settlement-date value equals the booked value', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: 11300, currency: 'EUR', exchange_rate: 11.3 },
{ currency: 'EUR', exchange_rate: 11.3, remaining_amount: 1000, total: 1000, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.arSek).toBe(11300)
expect(result.fxDiffSek).toBe(0)
expect(result.lines).toHaveLength(2)
})
})
describe('paymentAccount parameter (settlement-account resolution)', () => {
it('defaults the bank leg to 1930 when paymentAccount is not passed (backward compat)', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: 1250, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1250, total: 1250, paid_amount: 0 },
'Inbetalning kundfaktura',
)
expect(result.lines[0]).toMatchObject({ account_number: '1930', debit_amount: 1250 })
})
it('books the bank leg to the resolved account when paymentAccount is passed', () => {
const result = buildInvoicePaymentClearingLines(
{ amount: 1250, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1250, total: 1250, paid_amount: 0 },
'Inbetalning kundfaktura',
undefined,
'1940',
)
expect(result.lines[0]).toMatchObject({ account_number: '1940', debit_amount: 1250 })
// The AR leg (1510) is untouched by the payment-account override.
expect(result.lines[1]).toMatchObject({ account_number: '1510', credit_amount: 1250 })
})
it('a non-1930 paymentAccount does not affect the FX-diff line', () => {
// Cross-currency full clear: bank received more SEK than booked → 3960 gain.
const result = buildInvoicePaymentClearingLines(
{ amount: 1100, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'USD', exchange_rate: 10, remaining_amount: 100, total: 100, paid_amount: 0 },
'desc',
100,
'1940',
)
expect(result.lines[0]).toMatchObject({ account_number: '1940', debit_amount: 1100 })
const fxLine = result.lines.find((l) => l.account_number === '3960')
expect(fxLine).toMatchObject({ credit_amount: 100 })
})
it('a non-1930 paymentAccount does not affect the öresavrundning (3740) line', () => {
// Pure-SEK sub-krona short, same shape as the öresavrundning describe
// block above, but resolved to a non-primary bank account.
const result = buildInvoicePaymentClearingLines(
{ amount: 1000, amount_sek: null, currency: 'SEK', exchange_rate: null },
{ currency: 'SEK', exchange_rate: null, remaining_amount: 1000.25, total: 1000.25, paid_amount: 0 },
'Inbetalning kundfaktura',
undefined,
'1940',
)
expect(result.lines.find((l) => l.account_number === '1940')?.debit_amount).toBe(1000)
expect(result.lines.find((l) => l.account_number === '1930')).toBeUndefined()
expect(result.lines.find((l) => l.account_number === '1510')?.credit_amount).toBe(1000.25)
expect(result.lines.find((l) => l.account_number === '3740')?.debit_amount).toBe(0.25)
const debit = result.lines.reduce((s, l) => s + l.debit_amount, 0)
const credit = result.lines.reduce((s, l) => s + l.credit_amount, 0)
expect(Math.round((debit - credit) * 100)).toBe(0)
})
})
})