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>
This commit is contained in:
Mattsson
2026-07-27 03:34:56 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent a43a8b03cf
commit f24b26a139
536 changed files with 68921 additions and 4851 deletions
@@ -11,7 +11,7 @@ let results: Array<{ data?: unknown; error?: unknown; count?: number | null }>
function makeBuilder() {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'insert', 'update', 'delete', 'lte', 'gte', 'in', 'not', 'or', 'order', 'limit', 'is']) {
for (const m of ['select', 'eq', 'insert', 'update', 'delete', 'lte', 'gte', 'in', 'not', 'or', 'order', 'limit', 'is', 'range']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
@@ -29,7 +29,15 @@ function makeClient() {
}
}
import { lockPeriod, unlockPeriod, closePeriod, createNextPeriod, findNextPeriod } from '../period-service'
import {
lockPeriod,
unlockPeriod,
closePeriod,
createNextPeriod,
findNextPeriod,
resolvePeriodStatusForDate,
} from '../period-service'
import { getStructuredError } from '@/lib/errors/get-structured-error'
beforeEach(() => {
vi.clearAllMocks()
@@ -45,7 +53,8 @@ describe('lockPeriod', () => {
results = [
{ data: period, error: null }, // fetch
{ count: 0, data: null, error: null }, // uncategorized tx count check
{ count: 0, data: null, error: null }, // guard leg 1: untriaged count
{ data: [], error: null }, // guard leg 2: business-unbooked candidates
{ data: lockedPeriod, error: null }, // update
]
@@ -73,6 +82,522 @@ describe('lockPeriod', () => {
})
})
// ============================================================
// lockPeriod: unbooked-transaction guard
//
// These use a filter-aware client that records the filters the guard
// actually applies and evaluates them against in-memory tables, so the
// assertions turn on which rows the predicate matches rather than on a
// canned count handed back by the mock. Both anchoring locations that
// keep journal_entry_id NULL (transaction_voucher_links, the two payment
// tables) are modelled, because the guard must not block on those.
// ============================================================
type Row = Record<string, unknown>
interface FilterSpec {
col: string
op: 'eq' | 'is' | 'gte' | 'lte' | 'in'
val: unknown
}
/** The dead predicate this guard used to run, kept as a regression fixture. */
const OLD_DEAD_GUARD: FilterSpec[] = [
{ col: 'journal_entry_id', op: 'is', val: null },
{ col: 'is_business', op: 'eq', val: true },
]
function matchesAll(row: Row, specs: FilterSpec[]): boolean {
return specs.every((s) => {
const v = row[s.col]
if (s.op === 'gte') return String(v) >= String(s.val)
if (s.op === 'lte') return String(v) <= String(s.val)
if (s.op === 'in') return Array.isArray(s.val) && s.val.includes(v)
return v === s.val
})
}
const GUARD_TABLES = [
'transactions',
'transaction_voucher_links',
'invoice_payments',
'supplier_invoice_payments',
] as const
interface GuardStore {
transactions?: Row[]
transaction_voucher_links?: Row[]
invoice_payments?: Row[]
supplier_invoice_payments?: Row[]
/** Table name -> PostgREST error message to return instead of rows. */
failOn?: Partial<Record<(typeof GUARD_TABLES)[number], string>>
}
/**
* Client whose guard-table reads are predicate-evaluated against `store`.
* `fiscal_periods` still comes from the sequential `results` queue.
*
* `.range(from, to)` slices the matched rows exactly like PostgREST pages
* them, so a fetchAllRows caller is actually exercised page by page; a query
* that never calls `.range()` gets everything back at once (the old
* cap-oblivious behaviour a real PostgREST would truncate at 1000 rows).
*/
function makeGuardClient(store: GuardStore) {
const queries: Array<{
table: string
specs: FilterSpec[]
orderedBy: string | null
range: { from: number; to: number } | null
}> = []
function guardBuilder(table: (typeof GUARD_TABLES)[number]) {
const specs: FilterSpec[] = []
const record: (typeof queries)[number] = { table, specs, orderedBy: null, range: null }
queries.push(record)
let head = false
const b: Record<string, unknown> = {}
b.select = vi.fn((_cols?: string, opts?: { head?: boolean }) => {
head = opts?.head === true
return b
})
for (const op of ['eq', 'is', 'gte', 'lte', 'in'] as const) {
b[op] = vi.fn((col: string, val: unknown) => {
specs.push({ col, op, val })
return b
})
}
b.order = vi.fn((col: string) => {
record.orderedBy = col
return b
})
b.range = vi.fn((from: number, to: number) => {
record.range = { from, to }
return b
})
b.then = (resolve: (v: unknown) => void) => {
const failure = store.failOn?.[table]
if (failure) return resolve({ data: null, count: null, error: { message: failure } })
let matched = (store[table] ?? []).filter((r) => matchesAll(r, specs))
if (record.orderedBy) {
const col = record.orderedBy
matched = [...matched].sort((a, c) => String(a[col]).localeCompare(String(c[col])))
}
if (record.range) {
matched = matched.slice(record.range.from, record.range.to + 1)
}
return resolve(
head
? { count: matched.length, data: null, error: null }
: { data: matched, count: null, error: null },
)
}
return b
}
const client = {
from: vi.fn((table: string) =>
(GUARD_TABLES as readonly string[]).includes(table)
? guardBuilder(table as (typeof GUARD_TABLES)[number])
: makeBuilder(),
),
rpc: vi.fn(),
}
return { client, queries }
}
function openPeriod() {
return makeFiscalPeriod({
id: 'fp-1',
locked_at: null,
is_closed: false,
period_start: '2026-01-01',
period_end: '2026-12-31',
})
}
function tx(overrides: Row): Row {
return {
company_id: 'company-1',
date: '2026-03-15',
is_business: null,
is_ignored: false,
journal_entry_id: null,
...overrides,
}
}
/** Queue for a lock that is expected to succeed: fetch, then update. */
function expectLockToSucceed(period: object) {
results = [
{ data: period, error: null },
{ data: { ...period, locked_at: '2026-12-31T23:59:59Z' }, error: null },
]
}
describe('lockPeriod: unbooked transaction guard', () => {
it('refuses to lock a period that still holds untriaged bank transactions', async () => {
results = [{ data: openPeriod(), error: null }]
// Not yet triaged: is_business IS NULL, not ignored.
const { client } = makeGuardClient({
transactions: [
tx({ id: 't1' }),
tx({ id: 't2', date: '2026-07-01' }),
tx({ id: 't3', date: '2026-11-30' }),
],
})
await expect(lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
/3 banktransaktion\(er\)[\s\S]*3 ej hanterade/,
)
})
it('refuses to lock when a transaction is triaged as a business event but has no verifikat', async () => {
// The stronger BFL 5 kap 2 § case: the user has already confirmed this is
// the company's affärshändelse, and a lock would strand it.
results = [{ data: openPeriod(), error: null }]
const { client } = makeGuardClient({
transactions: [
tx({ id: 'b1', is_business: true, journal_entry_id: null }),
tx({ id: 'b2', is_business: true, journal_entry_id: null, date: '2026-09-09' }),
],
})
await expect(lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
/2 banktransaktion\(er\)[\s\S]*2 markerade som affärshändelse men utan verifikat/,
)
})
it('breaks the count down per reason when both kinds are present', async () => {
results = [{ data: openPeriod(), error: null }]
const { client } = makeGuardClient({
transactions: [
tx({ id: 'u1' }),
tx({ id: 'u2' }),
tx({ id: 'b1', is_business: true, journal_entry_id: null }),
],
})
let thrown: Error | undefined
try {
await lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')
} catch (e) {
thrown = e as Error
}
const message = thrown?.message ?? ''
expect(message).toContain('3 banktransaktion(er)')
expect(message).toContain('2 ej hanterade')
expect(message).toContain('1 markerade som affärshändelse men utan verifikat')
})
it('ignores untriaged transactions dated outside the period', async () => {
expectLockToSucceed(openPeriod())
const { client } = makeGuardClient({
transactions: [
tx({ id: 'before', date: '2025-12-31' }),
tx({ id: 'after', date: '2027-01-01' }),
tx({ id: 'biz-before', date: '2025-06-01', is_business: true }),
],
})
const result = await lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')
expect(result.locked_at).toBeTruthy()
})
it('locks a period whose transactions are all explicitly marked private', async () => {
expectLockToSucceed(openPeriod())
// is_business = false is privat uttag: triaged and deliberately excluded.
// Neither leg of the guard may count it, with or without a journal entry.
const { client } = makeGuardClient({
transactions: [
tx({ id: 'p1', is_business: false, journal_entry_id: 'je-1' }),
tx({ id: 'p2', is_business: false, journal_entry_id: null }),
],
})
const result = await lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')
expect(result.locked_at).toBeTruthy()
})
it('locks a clean period: booked, private and ignored rows do not block', async () => {
expectLockToSucceed(openPeriod())
const { client } = makeGuardClient({
transactions: [
// Booked the 1:1 way.
tx({ id: 'b1', is_business: true, journal_entry_id: 'je-1' }),
// Bulk-booked: anchored via transaction_voucher_links, journal_entry_id
// stays NULL (lib/transactions/is-booked.ts).
tx({ id: 'b2', is_business: true, journal_entry_id: null }),
// Multi-allocated across customer invoices.
tx({ id: 'b3', is_business: true, journal_entry_id: null }),
// Multi-allocated across supplier invoices.
tx({ id: 'b4', is_business: true, journal_entry_id: null }),
// Triaged as private.
tx({ id: 'p1', is_business: false, journal_entry_id: 'je-2' }),
// Explicitly suppressed: "never going to book it".
tx({ id: 'i1', is_business: null, is_ignored: true }),
],
transaction_voucher_links: [{ transaction_id: 'b2' }],
invoice_payments: [{ transaction_id: 'b3' }],
supplier_invoice_payments: [{ transaction_id: 'b4' }],
})
const result = await lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')
expect(result.locked_at).toBeTruthy()
})
it('paginates the business-unbooked candidate fetch past the 1000-row PostgREST page cap', async () => {
// Bulk-booked transactions keep journal_entry_id NULL, so >1000 candidates
// is realistic. A bare .select() would silently stop at 1000 rows; the
// guard must page through all 1500 and refuse with the full count.
results = [{ data: openPeriod(), error: null }]
const rows = Array.from({ length: 1500 }, (_, i) =>
tx({ id: `t${String(i).padStart(4, '0')}`, is_business: true, journal_entry_id: null }),
)
const { client, queries } = makeGuardClient({ transactions: rows })
await expect(lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
/1500 banktransaktion\(er\)[\s\S]*1500 markerade som affärshändelse men utan verifikat/,
)
// The candidate fetch (non-head transactions reads) is paginated with a
// stable unique order, per the fetch-all.ts ordering invariant.
const candidatePages = queries.filter((q) => q.table === 'transactions' && q.range !== null)
expect(candidatePages.length).toBeGreaterThanOrEqual(2)
for (const page of candidatePages) {
expect(page.orderedBy).toBe('id')
}
expect(candidatePages[0].range).toEqual({ from: 0, to: 999 })
expect(candidatePages[1].range).toEqual({ from: 1000, to: 1999 })
})
it('anchored rows beyond the first page still reduce the blocking count', async () => {
// 1200 candidates, of which the LAST 100 (sorted by id, i.e. entirely on
// page 2) are bulk-booked via transaction_voucher_links. Without
// pagination those rows were never fetched, so their anchoring never
// mattered; with it, 1200 - 100 = 1100 genuinely unbooked rows block.
results = [{ data: openPeriod(), error: null }]
const rows = Array.from({ length: 1200 }, (_, i) =>
tx({ id: `t${String(i).padStart(4, '0')}`, is_business: true, journal_entry_id: null }),
)
const anchoredIds = rows.slice(1100).map((r) => r.id as string)
const { client } = makeGuardClient({
transactions: rows,
transaction_voucher_links: anchoredIds.map((id) => ({ transaction_id: id })),
})
await expect(lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
/1100 banktransaktion\(er\)[\s\S]*1100 markerade som affärshändelse men utan verifikat/,
)
})
it('regression: the old journal_entry_id IS NULL + is_business = true guard let untriaged rows through', async () => {
results = [{ data: openPeriod(), error: null }]
const untriaged = [tx({ id: 't1' }), tx({ id: 't2' }), tx({ id: 't3' })]
// The old predicate matches none of them: triage is what sets is_business,
// so "unbooked AND is_business = true" can never describe an untriaged row.
// With that as the only guard, locking a period holding 40 untriaged
// transactions succeeded and the trigger then froze them in place.
expect(untriaged.filter((r) => matchesAll(r, OLD_DEAD_GUARD))).toHaveLength(0)
// The guard as it stands now does catch them.
const { client, queries } = makeGuardClient({ transactions: untriaged })
await expect(lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
/saknar bokföring/,
)
// Leg 1 is the canonical worklist predicate, not the old one.
const legOne = queries.find((q) => q.table === 'transactions')?.specs ?? []
expect(legOne).toEqual(
expect.arrayContaining([
{ col: 'is_business', op: 'is', val: null },
{ col: 'is_ignored', op: 'eq', val: false },
]),
)
expect(legOne).not.toContainEqual({ col: 'journal_entry_id', op: 'is', val: null })
})
it('refuses to lock when the untriaged count query errors, rather than waving the lock through', async () => {
results = [{ data: openPeriod(), error: null }]
const { client } = makeGuardClient({
transactions: [],
failOn: { transactions: 'connection reset' },
})
await expect(lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
/Kunde inte kontrollera obokförda banktransaktioner/,
)
})
it('refuses to lock when an anchor lookup errors: a half-run guard is no guard', async () => {
results = [{ data: openPeriod(), error: null }]
const { client } = makeGuardClient({
transactions: [tx({ id: 'b1', is_business: true, journal_entry_id: null })],
failOn: { transaction_voucher_links: 'statement timeout' },
})
await expect(lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')).rejects.toThrow(
/Kunde inte kontrollera obokförda banktransaktioner/,
)
})
it('the infra failure message is NOT mapped to the unbooked-transactions code', async () => {
// An unreachable DB must not send an agent off remediating transactions.
results = [{ data: openPeriod(), error: null }]
const { client } = makeGuardClient({
transactions: [],
failOn: { transactions: 'connection reset' },
})
let thrown: Error | undefined
try {
await lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')
} catch (e) {
thrown = e as Error
}
expect(thrown?.message ?? '').not.toContain('saknar bokföring')
expect(getStructuredError(thrown as Error).code).not.toBe('PERIOD_HAS_UNBOOKED_TRANSACTIONS')
})
// Both legs must produce a message the two mappers recognise. The
// untriaged-only case is the trap: its breakdown clause never says
// "affärstransaktion", so the inferCode() regex has to be satisfied by the
// fixed part of the sentence.
it.each([
['untriaged only', [tx({ id: 't1' }), tx({ id: 't2' })]],
[
'business-unbooked only',
[
tx({ id: 'b1', is_business: true, journal_entry_id: null }),
tx({ id: 'b2', is_business: true, journal_entry_id: null }),
],
],
])('throws a message both error mappers still recognise (%s)', async (_label, rows) => {
results = [{ data: openPeriod(), error: null }]
const { client } = makeGuardClient({ transactions: rows as Row[] })
let thrown: Error | undefined
try {
await lockPeriod(client as never, 'company-1', 'user-1', 'fp-1')
} catch (e) {
thrown = e as Error
}
expect(thrown).toBeInstanceOf(Error)
const message = thrown?.message ?? ''
// Both lock routes: substring match -> PERIOD_HAS_UNBOOKED_TRANSACTIONS (400).
expect(message).toContain('saknar bokföring')
// MCP/agent surfaces: inferCode() in lib/errors/get-structured-error.ts.
expect(getStructuredError(thrown as Error).code).toBe('PERIOD_HAS_UNBOOKED_TRANSACTIONS')
// Actionable: how many, why, and where to go.
expect(message).toContain('2 banktransaktion(er)')
expect(message).toContain('Transaktioner')
})
})
// ============================================================
// resolvePeriodStatusForDate: the shared lock helper must fail CLOSED.
// A swallowed PostgREST error used to be reported as `open`, which every
// caller reads as "this date is writable".
// ============================================================
describe('resolvePeriodStatusForDate', () => {
it('reports a verified open period', async () => {
results = [
{ data: { bookkeeping_locked_through: null }, error: null },
{ data: { id: 'fp-1', is_closed: false, locked_at: null }, error: null },
]
const status = await resolvePeriodStatusForDate(makeClient() as never, 'company-1', '2026-03-01')
expect(status).toEqual({ period_id: 'fp-1', status: 'open', lock_date: null })
})
it('keeps "no covering period" distinguishable: open with a null period_id and no failure flag', async () => {
results = [
{ data: { bookkeeping_locked_through: null }, error: null },
{ data: null, error: null },
]
const status = await resolvePeriodStatusForDate(makeClient() as never, 'company-1', '2026-03-01')
expect(status.status).toBe('open')
expect(status.period_id).toBeNull()
expect(status.lookup_failed).toBeUndefined()
})
it('fails closed when the company_settings lookup errors', async () => {
results = [{ data: null, error: { message: 'PGRST301 JWT expired' } }]
const status = await resolvePeriodStatusForDate(makeClient() as never, 'company-1', '2026-03-01')
expect(status.status).not.toBe('open')
expect(status).toEqual({
period_id: null,
status: 'locked',
lock_date: null,
lookup_failed: true,
})
})
it('fails closed when the fiscal_periods lookup errors', async () => {
results = [
{ data: { bookkeeping_locked_through: null }, error: null },
// e.g. two overlapping periods cover the date: .maybeSingle() errors.
{ data: null, error: { message: 'JSON object requested, multiple rows returned' } },
]
const status = await resolvePeriodStatusForDate(makeClient() as never, 'company-1', '2026-03-01')
expect(status.status).not.toBe('open')
expect(status.lookup_failed).toBe(true)
expect(status.period_id).toBeNull()
})
it('still resolves the company lock date layer without touching the period lookup verdict', async () => {
results = [
{ data: { bookkeeping_locked_through: '2026-06-30' }, error: null },
// Refinement lookup fails: verdict is already locked, so this is non-fatal.
{ data: null, error: { message: 'timeout' } },
]
const status = await resolvePeriodStatusForDate(makeClient() as never, 'company-1', '2026-03-01')
expect(status.status).toBe('locked')
expect(status.lock_date).toBe('2026-06-30')
expect(status.lookup_failed).toBeUndefined()
})
it('reports closed and locked periods unchanged', async () => {
results = [
{ data: { bookkeeping_locked_through: null }, error: null },
{ data: { id: 'fp-1', is_closed: true, locked_at: null }, error: null },
]
await expect(
resolvePeriodStatusForDate(makeClient() as never, 'company-1', '2026-03-01'),
).resolves.toEqual({ period_id: 'fp-1', status: 'closed', lock_date: null })
resultIdx = 0
results = [
{ data: { bookkeeping_locked_through: null }, error: null },
{ data: { id: 'fp-2', is_closed: false, locked_at: '2026-01-31T00:00:00Z' }, error: null },
]
await expect(
resolvePeriodStatusForDate(makeClient() as never, 'company-1', '2026-03-01'),
).resolves.toEqual({
period_id: 'fp-2',
status: 'locked',
lock_date: '2026-01-31T00:00:00Z',
})
})
})
describe('closePeriod', () => {
it('requires period is locked and has closing_entry_id', async () => {
const period = makeFiscalPeriod({
@@ -11,7 +11,7 @@ let results: Array<{ data?: unknown; error?: unknown; count?: number | null }>
function makeBuilder() {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'insert', 'update', 'delete', 'lte', 'gte', 'in', 'neq', 'not', 'or', 'order', 'limit', 'is']) {
for (const m of ['select', 'eq', 'insert', 'update', 'delete', 'lte', 'gte', 'in', 'neq', 'not', 'or', 'order', 'limit', 'is', 'range']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
@@ -20,6 +20,176 @@ function makeBuilder() {
return b
}
// ============================================================
// Filter-aware mock, used by the balansdagen FX readiness tests
// ============================================================
type Row = Record<string, unknown>
interface SeededTables {
fiscal_periods?: Row[]
journal_entries?: Row[]
voucher_sequences?: Row[]
invoices?: Row[]
supplier_invoices?: Row[]
invoice_payments?: Row[]
supplier_invoice_payments?: Row[]
}
/**
* Resolves each query by actually applying its filters to a seeded table,
* unlike the positional queue above which hands back a fixed row set no matter
* what was asked for.
*
* The FX readiness check is entirely a question about WHICH rows a query
* selects: status at balansdagen vs status now, `entry_date` on the
* revaluation verifikat, presence of `exchange_rate`. A queue mock answers all
* of those identically and so cannot tell the old behaviour from the new one.
*/
function makeFilteringClient(tables: SeededTables, failTable?: string) {
return {
from: vi.fn((table: string) => {
const eqs: Array<[string, unknown]> = []
const neqs: Array<[string, unknown]> = []
const ins: Array<[string, unknown[]]> = []
const ltes: Array<[string, string]> = []
const notNull: string[] = []
let head = false
let orderColumn: string | null = null
let orderAscending = true
let limitN: number | null = null
let rangeFrom: number | null = null
let rangeTo: number | null = null
function matching(): Row[] {
if (failTable === table) throw new Error(`simulated query failure on ${table}`)
const out = (tables[table as keyof SeededTables] ?? []).filter(
(r) =>
eqs.every(([c, v]) => r[c] === v) &&
neqs.every(([c, v]) => r[c] !== v) &&
ins.every(([c, vs]) => vs.includes(r[c])) &&
ltes.every(([c, v]) => String(r[c] ?? '') <= v) &&
notNull.every((c) => r[c] != null)
)
if (orderColumn) {
const col = orderColumn
out.sort((a, b2) => {
const av = a[col] as string | number
const bv = b2[col] as string | number
if (av === bv) return 0
return (av < bv ? -1 : 1) * (orderAscending ? 1 : -1)
})
}
return limitN == null ? out : out.slice(0, limitN)
}
function resolve() {
const all = matching()
const paged = rangeFrom == null ? all : all.slice(rangeFrom, (rangeTo ?? 0) + 1)
return { data: head ? null : paged, error: null, count: all.length }
}
const b: Record<string, unknown> = {}
b.select = vi.fn((_cols?: string, opts?: { head?: boolean }) => {
head = opts?.head === true
return b
})
b.eq = vi.fn((c: string, v: unknown) => { eqs.push([c, v]); return b })
b.neq = vi.fn((c: string, v: unknown) => { neqs.push([c, v]); return b })
b.in = vi.fn((c: string, v: unknown[]) => { ins.push([c, v]); return b })
b.lte = vi.fn((c: string, v: string) => { ltes.push([c, v]); return b })
b.not = vi.fn((c: string, op: string, v: unknown) => {
if (op === 'is' && v === null) notNull.push(c)
return b
})
b.order = vi.fn((c: string, opts?: { ascending?: boolean }) => {
orderColumn = c
orderAscending = opts?.ascending !== false
return b
})
b.limit = vi.fn((n: number) => { limitN = n; return b })
b.range = vi.fn((from: number, to: number) => { rangeFrom = from; rangeTo = to; return b })
for (const m of ['gte', 'is', 'or', 'insert', 'update', 'delete']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.single = vi.fn(async () => ({ data: matching()[0] ?? null, error: null }))
b.maybeSingle = vi.fn(async () => ({ data: matching()[0] ?? null, error: null }))
b.then = (done: (v: unknown) => void) => done(resolve())
return b
}),
rpc: vi.fn(async () => ({ data: [], error: null })),
}
}
const FX_PERIOD_END = '2024-12-31'
/**
* Baseline books that pass every non-FX readiness gate: one posted verifikat,
* no drafts, no voucher gaps, sequence counter reconciled.
*/
function fxBaseTables(extra: SeededTables = {}): SeededTables {
return {
fiscal_periods: [
makeFiscalPeriod({
id: 'fp-1',
company_id: 'company-1',
is_closed: false,
closing_entry_id: null,
period_end: FX_PERIOD_END,
}) as unknown as Row,
],
voucher_sequences: [
{ company_id: 'company-1', fiscal_period_id: 'fp-1', voucher_series: 'A', last_number: 10 },
],
journal_entries: [
{
company_id: 'company-1',
fiscal_period_id: 'fp-1',
voucher_series: 'A',
voucher_number: 10,
status: 'posted',
source_type: 'manual',
entry_date: '2024-06-01',
},
...(extra.journal_entries ?? []),
],
invoices: extra.invoices ?? [],
supplier_invoices: extra.supplier_invoices ?? [],
invoice_payments: extra.invoice_payments ?? [],
supplier_invoice_payments: extra.supplier_invoice_payments ?? [],
}
}
/** A posted currency_revaluation verifikat dated `entryDate`. */
function revaluationEntry(entryDate: string): Row {
return {
company_id: 'company-1',
fiscal_period_id: 'fp-1',
voucher_series: 'A',
voucher_number: 5,
status: 'posted',
source_type: 'currency_revaluation',
entry_date: entryDate,
}
}
/** An open EUR customer invoice. `exchange_rate: null` = never converted. */
function fxInvoice(overrides: Row = {}): Row {
return {
id: `inv-${Math.random().toString(36).slice(2, 10)}`,
company_id: 'company-1',
status: 'sent',
currency: 'EUR',
exchange_rate: 11.2,
invoice_date: '2024-11-15',
total: 1000,
paid_amount: 0,
remaining_amount: 1000,
paid_at: null,
...overrides,
}
}
function makeClient() {
return {
from: vi.fn().mockImplementation(() => makeBuilder()),
@@ -76,9 +246,7 @@ describe('validateYearEndReadiness', () => {
function noGapResults(period: ReturnType<typeof makeFiscalPeriod>, overrides: {
draftCount?: number
postedCount?: number
revalCount?: number
fxReceivables?: number
fxPayables?: number
balansdagenRevalCount?: number
} = {}) {
return [
{ data: period, error: null }, // fetch period (.single)
@@ -90,9 +258,9 @@ describe('validateYearEndReadiness', () => {
{ data: { voucher_number: 10 }, error: null }, // reconciliation: journal_entries max (.maybeSingle)
// trial balance mocked separately
{ data: null, error: null, count: overrides.postedCount ?? 5 }, // count posted (thenable)
{ data: null, error: null, count: overrides.revalCount ?? 0 }, // count revaluation (thenable)
{ data: null, error: null, count: overrides.fxReceivables ?? 0 }, // fx receivables (thenable)
{ data: null, error: null, count: overrides.fxPayables ?? 0 }, // fx payables (thenable)
{ data: null, error: null, count: overrides.balansdagenRevalCount ?? 0 }, // revaluation dated on balansdagen (thenable)
{ data: null, error: null }, // open FX receivables: no rows (fetchAllRows)
{ data: null, error: null }, // open FX payables: no rows (fetchAllRows)
]
}
@@ -398,6 +566,237 @@ describe('validateYearEndReadiness', () => {
})
})
describe('validateYearEndReadiness: open FX items at balansdagen (ÅRL 4 kap. 13 §)', () => {
beforeEach(() => {
vi.mocked(generateTrialBalance).mockResolvedValue({
rows: [],
isBalanced: true,
totalDebit: 10000,
totalCredit: 10000,
} as never)
vi.mocked(findNextPeriod).mockResolvedValue(null as never)
})
const revaluationWarning = (w: string) => w.includes('har inte omvärderats till balansdagskurs')
const missingRateWarning = (w: string) => w.includes('saknar valutakurs')
it('does not let one interim revaluation hide items still open on balansdagen', async () => {
// A single revaluation run in June. Twelve invoices were still outstanding
// on 31 December and none of them were valued at the balansdagen rate.
const supabase = makeFilteringClient(
fxBaseTables({
journal_entries: [revaluationEntry('2024-06-30')],
invoices: Array.from({ length: 12 }, (_, i) => fxInvoice({ id: `inv-${i}` })),
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.filter(revaluationWarning)).toHaveLength(1)
expect(result.warnings.find(revaluationWarning)).toContain('12 post(er)')
expect(result.warnings.find(revaluationWarning)).toContain(FX_PERIOD_END)
// Advisory, not a blocker: executeYearEndClosing revalues in its step 2.
expect(result.ready).toBe(true)
})
it('counts items with no exchange rate at all and states the different remedy', async () => {
const supabase = makeFilteringClient(
fxBaseTables({
invoices: [
fxInvoice({ id: 'inv-a', exchange_rate: null }),
fxInvoice({ id: 'inv-b', exchange_rate: null }),
fxInvoice({ id: 'inv-c', exchange_rate: 0 }),
],
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
// These are invisible to the revaluation, so they get their own warning
// with its own remedy, and they are never folded into the other count.
const missing = result.warnings.find(missingRateWarning)
expect(missing).toBeDefined()
expect(missing).toContain('3 post(er)')
expect(missing).toContain('Registrera kursen på fakturan')
expect(result.warnings.filter(revaluationWarning)).toHaveLength(0)
expect(result.ready).toBe(true)
})
it('separates the two states when both are present', async () => {
const supabase = makeFilteringClient(
fxBaseTables({
invoices: [
fxInvoice({ id: 'inv-rate-1' }),
fxInvoice({ id: 'inv-rate-2' }),
fxInvoice({ id: 'inv-norate', exchange_rate: null }),
],
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.find(missingRateWarning)).toContain('1 post(er)')
expect(result.warnings.find(revaluationWarning)).toContain('2 post(er)')
})
it('still reports a clean company as ready with no FX warning', async () => {
const supabase = makeFilteringClient(fxBaseTables())
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.ready).toBe(true)
expect(result.warnings.filter((w: string) => w.includes('valuta'))).toHaveLength(0)
})
it('counts an invoice paid after balansdagen: it was open on the balance sheet date', async () => {
// Status today is 'paid', status on 31 December was open. ÅRL 4 kap. 13 §
// values the item at balansdagen, so it must still be counted.
const supabase = makeFilteringClient(
fxBaseTables({
invoices: [
fxInvoice({
id: 'inv-late-paid',
status: 'paid',
invoice_date: '2024-10-01',
total: 5000,
paid_amount: 5000,
remaining_amount: 0,
paid_at: '2025-03-10',
}),
],
invoice_payments: [
{
id: 'pay-1',
company_id: 'company-1',
invoice_id: 'inv-late-paid',
amount: 5000,
payment_date: '2025-03-10',
},
],
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.find(revaluationWarning)).toContain('1 post(er)')
})
it('counts a partially paid FX invoice: its unpaid remainder was open on balansdagen', async () => {
// payment-sync sets 'partially_paid' on partial settlements. The old
// status list ('sent'/'overdue'/'paid') never matched it, so the readiness
// check reported no exposure for a receivable whose 600 EUR remainder
// still had to be valued at balansdagskurs (ÅRL 4 kap. 13 §).
const supabase = makeFilteringClient(
fxBaseTables({
invoices: [
fxInvoice({
id: 'inv-partial',
status: 'partially_paid',
total: 1000,
paid_amount: 400,
remaining_amount: 600,
}),
],
invoice_payments: [
{
id: 'pay-partial',
company_id: 'company-1',
invoice_id: 'inv-partial',
amount: 400,
payment_date: '2024-12-01',
},
],
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.find(revaluationWarning)).toContain('1 post(er)')
})
it('ignores an invoice issued after balansdagen even though it is open today', async () => {
// The mirror image: open now, did not exist on the balance sheet date.
const supabase = makeFilteringClient(
fxBaseTables({
invoices: [fxInvoice({ id: 'inv-next-year', invoice_date: '2025-02-01' })],
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.filter((w: string) => w.includes('valuta'))).toHaveLength(0)
})
it('counts open FX payables as well as receivables', async () => {
const supabase = makeFilteringClient(
fxBaseTables({
supplier_invoices: [
{
id: 'si-1',
company_id: 'company-1',
status: 'approved',
currency: 'USD',
exchange_rate: 10.4,
invoice_date: '2024-09-01',
total: 2000,
paid_amount: 0,
remaining_amount: 2000,
paid_at: null,
},
{
id: 'si-2',
company_id: 'company-1',
status: 'registered',
currency: 'USD',
exchange_rate: null,
invoice_date: '2024-09-02',
total: 800,
paid_amount: 0,
remaining_amount: 800,
paid_at: null,
},
],
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.find(revaluationWarning)).toContain('1 post(er)')
expect(result.warnings.find(missingRateWarning)).toContain('1 post(er)')
})
it('suppresses only the revaluation warning when a balansdagen revaluation exists', async () => {
const supabase = makeFilteringClient(
fxBaseTables({
journal_entries: [revaluationEntry(FX_PERIOD_END)],
invoices: [
fxInvoice({ id: 'inv-rate-1' }),
fxInvoice({ id: 'inv-rate-2' }),
fxInvoice({ id: 'inv-norate', exchange_rate: null }),
],
})
)
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(result.warnings.filter(revaluationWarning)).toHaveLength(0)
// The posted revaluation provably did not include the unconverted row:
// previewCurrencyRevaluation partitions it out. So it stays warned about.
expect(result.warnings.find(missingRateWarning)).toContain('1 post(er)')
})
it('says the check did not run rather than reporting no exposure when it fails', async () => {
const supabase = makeFilteringClient(fxBaseTables(), 'invoices')
const result = await validateYearEndReadiness(supabase as never, 'company-1', 'user-1', 'fp-1')
expect(
result.warnings.some((w: string) => w.includes('kunde inte genomföras'))
).toBe(true)
expect(result.ready).toBe(true)
})
})
describe('previewYearEndClosing', () => {
it('calculates net result from class 3-8 accounts', async () => {
results = [
+261 -16
View File
@@ -1,8 +1,141 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { eventBus } from '@/lib/events'
import { createLogger } from '@/lib/logger'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import { validatePeriodDuration } from '@/lib/bookkeeping/validate-period-duration'
import type { FiscalPeriod, PeriodStatus } from '@/types'
const log = createLogger('period-service')
/**
* The two ways a bank transaction can still owe the period a verifikation.
*
* Triage is the act of answering "is this an affärshändelse for the company?".
* The three answers, and what each means for a period lock:
*
* is_business IS NULL, is_ignored = false -> NOT TRIAGED. Nobody has looked
* at it. Counted as `untriaged`; blocks.
* is_business = true -> TRIAGED AS A BUSINESS EVENT. It
* owes a verifikation. Blocks unless it already has one (see below);
* counted as `businessUnbooked` when it does not.
* is_business = false -> TRIAGED AND EXCLUDED (privat
* uttag / not the company's affär). Never blocks: there is nothing to
* bokföra, and holding a lock hostage to a private coffee is over-
* blocking, not compliance.
* is_ignored = true -> TRIAGED AND EXCLUDED, the user's
* explicit "hide this, never going to book it" (migration
* 20260529190000). Never blocks. The column is NOT NULL DEFAULT false,
* so `.eq('is_ignored', false)` cannot silently drop rows.
*
* "Already has a verifikation" is deliberately NOT `journal_entry_id IS NOT
* NULL`. That column only covers the 1:1 case; bulk-booked (N tx -> 1 JE, via
* transaction_voucher_links) and multi-allocated (invoice_payments /
* supplier_invoice_payments) transactions stay NULL while being anchored to a
* real verifikat. See lib/transactions/is-booked.ts and its Postgres mirror
* public.is_transaction_booked(uuid); this helper reproduces all three
* locations so the guard does not block on already-booked rows.
*/
export interface UnbookedInPeriod {
/** Never triaged: is_business IS NULL AND is_ignored = false. */
untriaged: number
/** Triaged as a business event but anchored to no verifikat at all. */
businessUnbooked: number
}
/** PostgREST rejects very long URLs, so `.in()` lists are chunked. */
const ANCHOR_LOOKUP_CHUNK = 200
/**
* Count the bank transactions in [periodStart, periodEnd] that a period lock
* would strand. Throws on any query failure so the caller can fail closed:
* never return 0 for a check that did not actually run.
*/
export async function countUnbookedInPeriod(
supabase: SupabaseClient,
companyId: string,
periodStart: string,
periodEnd: string,
): Promise<UnbookedInPeriod> {
// Leg 1: never triaged. This is the canonical "att bokföra" predicate from
// lib/worklist/categories.ts, so the number here reconciles with the
// "N st att bokföra" badge instead of being a second, unexplainable count.
// Served by the partial index idx_transactions_company_unbooked.
const { count: untriaged, error: untriagedError } = await supabase
.from('transactions')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.is('is_business', null)
.eq('is_ignored', false)
.gte('date', periodStart)
.lte('date', periodEnd)
if (untriagedError) {
throw new Error(`untriaged transaction count failed: ${untriagedError.message}`)
}
// Leg 2: triaged as a business event, but no verifikat anywhere. The user has
// already confirmed this is the company's affärshändelse, so a lock strands
// it just as hard as an untriaged one, only with less excuse. Fetch the ids
// and subtract the ones anchored via the non-denormalized locations.
//
// Paginated via fetchAllRows with a stable id order: PostgREST silently caps
// a bare select at 1000 rows, and this candidate set is NOT bounded in
// practice, because bulk-booked transactions keep journal_entry_id NULL
// (anchored only via transaction_voucher_links). An unpaginated read would
// drop every candidate past row 1000, under-counting businessUnbooked and
// letting a period lock while genuinely unbooked affärshändelser are
// stranded in it (BFL 5 kap 2 §).
let candidates: Array<{ id?: string }>
try {
candidates = await fetchAllRows<{ id?: string }>(({ from, to }) =>
supabase
.from('transactions')
.select('id')
.eq('company_id', companyId)
.eq('is_business', true)
.eq('is_ignored', false)
.is('journal_entry_id', null)
.gte('date', periodStart)
.lte('date', periodEnd)
.order('id', { ascending: true })
.range(from, to)
)
} catch (err) {
throw new Error(
`business transaction lookup failed: ${err instanceof Error ? err.message : String(err)}`
)
}
const candidateIds = candidates
.map((row) => row.id)
.filter((id): id is string => typeof id === 'string')
if (candidateIds.length === 0) {
return { untriaged: untriaged ?? 0, businessUnbooked: 0 }
}
const anchored = new Set<string>()
for (const table of ['transaction_voucher_links', 'invoice_payments', 'supplier_invoice_payments'] as const) {
for (let i = 0; i < candidateIds.length; i += ANCHOR_LOOKUP_CHUNK) {
const chunk = candidateIds.slice(i, i + ANCHOR_LOOKUP_CHUNK)
const { data, error } = await supabase
.from(table)
.select('transaction_id')
.in('transaction_id', chunk)
if (error) {
throw new Error(`${table} anchor lookup failed: ${error.message}`)
}
for (const row of data ?? []) {
const id = (row as { transaction_id?: string | null }).transaction_id
if (id) anchored.add(id)
}
}
}
return {
untriaged: untriaged ?? 0,
businessUnbooked: candidateIds.filter((id) => !anchored.has(id)).length,
}
}
/**
* Lock a fiscal period: prevents new journal entries from being posted.
* Requires: period exists, belongs to company, not already locked/closed.
@@ -34,19 +167,68 @@ export async function lockPeriod(
throw new Error('Period is already locked')
}
// Check for uncategorized business transactions in this period
const { count: unbookedCount } = await supabase
.from('transactions')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.is('journal_entry_id', null)
.eq('is_business', true)
.gte('date', period.period_start)
.lte('date', period.period_end)
if (unbookedCount && unbookedCount > 0) {
// Refuse to lock while the period still holds bank transactions that would be
// stranded. BFL 5 kap 2 § requires every affärshändelse to be bokförd in the
// period it belongs to; once locked_at is set the enforce_period_lock trigger
// makes these rows unbookable in place, leaving affärshändelser that can only
// be entered by unlocking again or via a rättelse.
//
// Hard block, not an advisory warning with a bypass. There is no legitimate
// "lock anyway" case: locking is a voluntary internal control with no legal
// deadline, while the affärshändelser it would strand do have one (BFL 5 kap
// 2 §: kontant senast nästa arbetsdag, övrigt "så snart det kan ske").
// Every escape hatch the user could want is already an exit from the
// predicate and is named in the message: book it, mark it privat, or mark it
// ignored. Locking first and unlocking later is strictly worse, because the
// unlock lands in the immutable audit_log as a control override.
let unbooked: UnbookedInPeriod
try {
unbooked = await countUnbookedInPeriod(
supabase,
companyId,
period.period_start,
period.period_end,
)
} catch (err) {
// Fail closed. A guard that cannot run must not wave the lock through:
// that is exactly how the previous dead predicate went unnoticed.
log.error('unbooked-transaction guard failed, refusing to lock', {
companyId,
fiscalPeriodId,
reason: err instanceof Error ? err.message : String(err),
})
throw new Error(
`Kan inte låsa period: ${unbookedCount} affärstransaktion(er) saknar bokföring. Bokför alla transaktioner innan perioden låses.`
'Kunde inte kontrollera obokförda banktransaktioner i perioden. Perioden lämnas olåst. Försök igen.'
)
}
const blockingCount = unbooked.untriaged + unbooked.businessUnbooked
if (blockingCount > 0) {
// Message wording is load-bearing for two separate matchers; keep both
// phrases when editing:
// - "saknar bokföring" -> both lock routes map this to the
// PERIOD_HAS_UNBOOKED_TRANSACTIONS envelope (400) instead of a 500
// (app/api/bookkeeping/fiscal-periods/[id]/lock/route.ts and
// app/api/v1/companies/[companyId]/fiscal-periods/[id]/lock/route.ts)
// - /Kan inte låsa period:.*affärstransaktion/ -> inferCode() in
// lib/errors/get-structured-error.ts derives the same code for the
// MCP/agent surfaces, which have no HTTP envelope to read. The word
// "affärstransaktion" therefore has to appear unconditionally, not
// only in the breakdown clause that the untriaged-only case omits.
// The infra message above deliberately matches neither: an unreachable DB
// must not send an agent off remediating transactions.
const breakdown = [
unbooked.untriaged > 0 ? `${unbooked.untriaged} ej hanterade` : null,
unbooked.businessUnbooked > 0
? `${unbooked.businessUnbooked} markerade som affärshändelse men utan verifikat`
: null,
]
.filter(Boolean)
.join(', ')
throw new Error(
`Kan inte låsa period: ${blockingCount} banktransaktion(er) i perioden saknar bokföring ` +
`(${breakdown}). Alla affärstransaktioner måste vara bokförda innan perioden låses. ` +
`Gå till Transaktioner, bokför dem eller markera dem som privata eller ignorerade, och lås perioden därefter.`
)
}
@@ -435,9 +617,54 @@ export interface PeriodStatusForDate {
/**
* For `locked` status: either the period's `locked_at` timestamp (ISO) or the
* company-wide `bookkeeping_locked_through` date (ISO), whichever applies.
* `null` for open/closed.
* `null` for open/closed, and `null` when `lookup_failed` is true.
*/
lock_date: string | null
/**
* True when the lock lookup itself failed (PostgREST error, an overlapping
* fiscal_periods pair breaking `.maybeSingle()`, a network blip). `status`
* is then reported as `'locked'`, because a period whose state we could not
* read must never be presented as writable.
*
* Keep the three cases distinguishable, callers treat them differently:
* { status: 'open', period_id: <id> } -> verified open
* { status: 'open', period_id: null } -> verified: no
* covering period exists at all. Not an error: the engine's
* ensure-period helper creates one on write.
* { status: 'locked', period_id: null, lookup_failed } -> unverified.
* Nothing is known about the date. Retryable; a genuinely locked
* period always carries a real period_id or lock_date.
*
* Deliberately an additive optional field rather than a fourth
* `PeriodStatusValue`: the union is consumed as an exhaustive
* `Record<PeriodStatusValue, string>` in lib/agent/intents/bokslut-step.ts,
* so widening it would break unrelated callers at compile time.
*/
lookup_failed?: boolean
}
/**
* Fail-closed verdict for a lock lookup that could not be completed.
*
* Reported as `locked` on purpose. The alternative (`open`) is the bug this
* exists to prevent: every caller of resolvePeriodStatusForDate uses the
* result to decide whether a write into a period is allowed, so a swallowed
* query error used to read as "go ahead" on the storno, MCP staging, agent
* draft and pending-operation commit paths.
*/
function periodLookupFailed(
companyId: string,
date: string,
stage: 'company_settings' | 'fiscal_periods',
error: { message?: string } | null,
): PeriodStatusForDate {
log.error('period status lookup failed, failing closed', {
companyId,
date,
stage,
reason: error?.message,
})
return { period_id: null, status: 'locked', lock_date: null, lookup_failed: true }
}
/**
@@ -451,6 +678,11 @@ export interface PeriodStatusForDate {
* Returned shape is the canonical `period_status` envelope threaded into MCP
* tool responses so agents and widgets can disable writes without round-trips.
*
* Fails CLOSED: if either lookup errors we report `locked` with
* `lookup_failed: true` rather than `open`. Never reintroduce a bare
* `const { data } = await ...` here; dropping the `error` is what turned this
* shared helper into a fail-open on every write path that consults it.
*
* Mirrors lib/api/v1/check-period-lock.ts (used by the v1 REST surface). The
* two helpers share the same query pattern; if either changes, update both.
*/
@@ -460,14 +692,21 @@ export async function resolvePeriodStatusForDate(
date: string,
): Promise<PeriodStatusForDate> {
// Layer 1: company-wide lock date.
const { data: settings } = await supabase
const { data: settings, error: settingsError } = await supabase
.from('company_settings')
.select('bookkeeping_locked_through')
.eq('company_id', companyId)
.maybeSingle()
if (settingsError) {
// Unknown company lock date: the date could be behind it. Fail closed.
return periodLookupFailed(companyId, date, 'company_settings', settingsError)
}
const lockThrough = settings?.bookkeeping_locked_through ?? null
if (lockThrough && date <= lockThrough) {
// Find the covering period if any: useful for widget greying.
// Find the covering period if any: useful for widget greying. An error
// here is deliberately non-fatal: the verdict is already `locked` on the
// company lock date alone, so a failed refinement can only cost the
// period_id, never flip the answer to open.
const { data: period } = await supabase
.from('fiscal_periods')
.select('id')
@@ -479,7 +718,7 @@ export async function resolvePeriodStatusForDate(
}
// Layer 2: fiscal period status.
const { data: period } = await supabase
const { data: period, error: periodError } = await supabase
.from('fiscal_periods')
.select('id, is_closed, locked_at')
.eq('company_id', companyId)
@@ -487,6 +726,12 @@ export async function resolvePeriodStatusForDate(
.gte('period_end', date)
.maybeSingle()
if (periodError) {
// Distinct from `!period` below: that is "verified, no covering period
// exists"; this is "we do not know what period covers this date".
return periodLookupFailed(companyId, date, 'fiscal_periods', periodError)
}
if (!period) {
// No covering period: treated as open at this layer; the engine's own
// ensure-period helper will create one. Agents should still warn the user.
+212 -24
View File
@@ -6,6 +6,13 @@ import { createLogger } from '@/lib/logger'
const log = createLogger('year-end-service')
import { generateTrialBalance } from '@/lib/reports/trial-balance'
import { fetchAllRows } from '@/lib/supabase/fetch-all'
import {
fetchPaymentsAsOf,
outstandingAsOf,
todayIsoDate,
type PaymentsAsOf,
} from '@/lib/reports/reskontra-payments'
import { lockPeriod, closePeriod, createNextPeriod, findNextPeriod } from './period-service'
import { generateResultAppropriation } from './result-appropriation-service'
import {
@@ -218,38 +225,62 @@ export async function validateYearEndReadiness(
warnings.push('Inga bokförda verifikationer i perioden')
}
// Check: foreign currency items exist but haven't been revalued
const { count: revalCount } = await supabase
// Check: foreign-currency items open on balansdagen (ÅRL 4 kap. 13 §).
//
// Only a revaluation dated ON balansdagen discharges the duty. The previous
// gate accepted any currency_revaluation verifikat anywhere in the period,
// so one interim run (a June month-end revaluation) silenced the check for
// every item still outstanding on 31 December: "we already did one, so stop
// looking". An interim revaluation says nothing about the balansdagen value.
const { count: balansdagenRevalCount } = await supabase
.from('journal_entries')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.eq('fiscal_period_id', fiscalPeriodId)
.eq('source_type', 'currency_revaluation')
.eq('status', 'posted')
.eq('entry_date', period.period_end)
if ((revalCount ?? 0) === 0) {
// Check if there are any open foreign currency items
const { count: fxReceivables } = await supabase
.from('invoices')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.in('status', ['sent', 'overdue'])
.neq('currency', 'SEK')
.not('exchange_rate', 'is', null)
// Both states below are warnings, never blockers: nothing in the bokslut
// rules makes an unvalued FX item a bar to closing, and executeYearEndClosing
// runs the revaluation itself in step 2. Escalating would block a close that
// the very next step performs.
try {
const openFx = await countOpenFxItemsAtBalansdagen(supabase, companyId, period.period_end)
const { count: fxPayables } = await supabase
.from('supplier_invoices')
.select('id', { count: 'exact', head: true })
.eq('company_id', companyId)
.in('status', ['registered', 'approved', 'overdue', 'partially_paid'])
.neq('currency', 'SEK')
.not('exchange_rate', 'is', null)
if (((fxReceivables ?? 0) + (fxPayables ?? 0)) > 0) {
// Loudest case first. A row with no exchange_rate is invisible to the
// revaluation: previewCurrencyRevaluation partitions it into
// `unconvertedFx` and drops it, so re-running the year-end will never
// value it. It needs a rate on the invoice, and these rows are typically
// the largest unmeasured exposure precisely because nothing warns on them.
// The old query's `.not('exchange_rate','is',null)`, inherited from the
// revaluation code, excluded exactly this case: a company whose only open
// FX items were unconverted got no warning at all.
if (openFx.unconverted > 0) {
warnings.push(
'Öppna poster i utländsk valuta har inte omvärderats (ÅRL 4:13)'
`${openFx.unconverted} post(er) i utländsk valuta var öppna på balansdagen ${period.period_end} men saknar valutakurs: de kan inte värderas till balansdagskurs (ÅRL 4 kap. 13 §) och utelämnas ur omvärderingen. Registrera kursen på fakturan.`
)
}
// Separate state, separate remedy: these can be valued, they just have not
// been yet. Suppressed only by a revaluation dated on balansdagen.
if (openFx.revaluable > 0 && (balansdagenRevalCount ?? 0) === 0) {
warnings.push(
`${openFx.revaluable} post(er) i utländsk valuta var öppna på balansdagen ${period.period_end} och har inte omvärderats till balansdagskurs (ÅRL 4 kap. 13 §)`
)
}
} catch (err) {
// A failed lookup must not read as "no FX exposure". Say the check did not
// run rather than let silence pass for a clean bill of health.
log.error('year-end: could not measure open FX items at balansdagen', err as Error, {
operation: 'year_end.fx_readiness',
companyId,
entityType: 'fiscal_period',
entityId: fiscalPeriodId,
})
warnings.push(
'Kontrollen av öppna poster i utländsk valuta (ÅRL 4 kap. 13 §) kunde inte genomföras: stäm av dem manuellt innan bokslut'
)
}
// Check: continuity_verified flag from prior year-end
@@ -656,9 +687,10 @@ export async function executeYearEndClosing(
)
} catch (err) {
resultAppropriationFailed = true
// alert:true marks this for out-of-band alerting (the log sink / Sentry
// integration filters on it): a silent accounting failure must not wait
// for a manual audit. The new period now opens with 2099 still carrying the
// alert:true routes this to the observability sink (lib/observability) in
// addition to the log line: a silent accounting failure must not wait for
// a manual audit. The sink is a no-op until a provider is configured, so
// today this reaches the JSON log only. The new period now opens with 2099 still carrying the
// prior result; resultAppropriationFailed below drives a UI warning and the
// catch-up script (scripts/repair-result-appropriation.ts) posts the fix.
log.error('year-end: result appropriation omföring failed (non-fatal)', err as Error, {
@@ -798,6 +830,162 @@ export async function generateOpeningBalances(
return openingEntry
}
/**
* Open foreign-currency items as they stood on balansdagen, split by whether
* the ÅRL 4 kap. 13 § valuation can reach them at all. The two states have
* different remedies, so they are counted apart rather than summed.
*/
interface OpenFxAtBalansdagen {
/** Carries a usable exchange_rate: revaluable to the balansdagen rate. */
revaluable: number
/**
* No exchange_rate on file, so there is no original SEK value to revalue
* from. Counted rather than dropped, the same contract `unconverted_fx_count`
* carries on the reskontra reports (lib/reports/supplier-ledger.ts): an
* excluded row has to show up as a number somewhere.
*/
unconverted: number
}
/** The subset of an invoice row this check reads. */
interface FxLedgerRow {
id: string
status: string | null
currency: string | null
exchange_rate: number | string | null
total: number | string | null
paid_amount: number | string | null
remaining_amount: number | string | null
paid_at: string | null
}
/** A stored rate is usable only when present and strictly positive. */
function hasUsableFxRate(rate: number | string | null | undefined): boolean {
return rate != null && Number(rate) > 0
}
/**
* Count the foreign-currency receivables and payables that were still open on
* balansdagen.
*
* Measured AS OF balansdagen, not as of now. ÅRL 4 kap. 13 § values monetary
* items at the balance-sheet date, so an invoice settled in March of the
* following year was still an open FX item on 31 December and still had to be
* valued there; the live `status` column only says what is open today. For a
* historical balansdagen the population is therefore widened to invoices dated
* on or before it (including ones settled since) and the outstanding amount is
* recomputed from the payment history, the same reconstruction the reskontra
* reports use (lib/reports/ar-ledger.ts, lib/reports/supplier-ledger.ts). For
* today or a future balansdagen the stored open-invoice state IS the as-of
* state, so no reconstruction is attempted.
*
* Limits, inherited from `outstandingAsOf` and identical to what the reskontra
* reports already accept: an invoice with no payment rows and no `paid_at`
* cannot be dated, so its live outstanding is assumed to have stood at
* balansdagen; and an invoice cancelled or credited since is treated as never
* having been open, because neither event carries a reliable date. The status
* population is kept identical to what the revaluation engine actually acts on
* (`getOpenForeignCurrencyReceivables` / `...Payables`), so the warning never
* points at rows for which no remedy exists.
*/
async function countOpenFxItemsAtBalansdagen(
supabase: SupabaseClient,
companyId: string,
balansdagen: string
): Promise<OpenFxAtBalansdagen> {
const isHistorical = balansdagen < todayIsoDate()
const columns =
'id, status, currency, exchange_rate, total, paid_amount, remaining_amount, paid_at'
const receivables = await fetchAllRows<FxLedgerRow>(
({ from, to }) => {
const base = supabase
.from('invoices')
.select(columns)
.eq('company_id', companyId)
.neq('currency', 'SEK')
// 'partially_paid' is a live status for customer invoices (payment-sync
// sets it on partial settlements); the unpaid remainder was open on
// balansdagen just like a 'sent' invoice. Kept in lockstep with
// getOpenForeignCurrencyReceivables so this warning never points at
// rows the revaluation engine cannot see.
const scoped = isHistorical
? base
.in('status', ['sent', 'overdue', 'partially_paid', 'paid'])
.lte('invoice_date', balansdagen)
: base.in('status', ['sent', 'overdue', 'partially_paid'])
// Stable total order for correct paging (see fetch-all.ts).
return scoped.order('id', { ascending: true }).range(from, to)
},
{ dedupeBy: (r) => r.id }
)
const payables = await fetchAllRows<FxLedgerRow>(
({ from, to }) => {
const base = supabase
.from('supplier_invoices')
.select(columns)
.eq('company_id', companyId)
.neq('currency', 'SEK')
const scoped = isHistorical
? base
.in('status', ['registered', 'approved', 'overdue', 'partially_paid', 'paid'])
.lte('invoice_date', balansdagen)
: base.in('status', ['registered', 'approved', 'overdue', 'partially_paid'])
return scoped.order('id', { ascending: true }).range(from, to)
},
{ dedupeBy: (r) => r.id }
)
// Payment history is only needed to walk a since-settled invoice back to what
// it owed on balansdagen, and only when there is something to walk back.
const receivablePayments =
isHistorical && receivables.length > 0
? await fetchPaymentsAsOf(supabase, 'invoice_payments', 'invoice_id', companyId, balansdagen)
: null
const payablePayments =
isHistorical && payables.length > 0
? await fetchPaymentsAsOf(
supabase,
'supplier_invoice_payments',
'supplier_invoice_id',
companyId,
balansdagen
)
: null
const counts: OpenFxAtBalansdagen = { revaluable: 0, unconverted: 0 }
function tally(
rows: FxLedgerRow[],
payments: PaymentsAsOf | null,
liveOutstanding: (row: FxLedgerRow) => number
): void {
for (const row of rows) {
const total = Number(row.total) || 0
const live = liveOutstanding(row)
const outstanding = payments
? outstandingAsOf(row, total, live, payments, balansdagen)
: live
// Settled on or before balansdagen: nothing was open to value.
if (outstanding <= 0) continue
if (hasUsableFxRate(row.exchange_rate)) counts.revaluable += 1
else counts.unconverted += 1
}
}
// Each side uses its own reskontra's definition of outstanding so these
// counts reconcile with what the user sees there: kundreskontran derives it
// from paid_amount, leverantörsreskontran reads the maintained
// remaining_amount.
tally(receivables, receivablePayments, (r) =>
roundOre((Number(r.total) || 0) - (Number(r.paid_amount) || 0))
)
tally(payables, payablePayments, (r) => Number(r.remaining_amount) || 0)
return counts
}
/**
* Best-effort reversal used by executeYearEndClosing's rollback paths.
*
@@ -55,8 +55,16 @@ vi.mock('@/lib/auth/api-keys', () => ({
import {
uploadDocument,
createNewVersion,
deleteDocument,
verifyIntegrity,
validateDocumentMagicBytes,
buildDocumentStoragePath,
isCompanyScopedDocumentPath,
companyScopedDocumentPath,
legacyDocumentPath,
documentStoragePathCandidates,
downloadDocumentObject,
createDocumentSignedUrl,
_resetBucketVerified,
} from '../document-service'
@@ -257,6 +265,51 @@ describe('uploadDocument', () => {
})
)
})
it('writes to the company-scoped key, not the legacy uploader-scoped key', async () => {
results = [{ data: makeDocumentAttachment({ id: 'doc-1' }), error: null }]
const upload = vi.fn().mockResolvedValue({ data: {}, error: null })
const supabase = makeClient({ upload })
await uploadDocument(supabase as never, 'user-1', 'company-1', {
name: 'kvitto.pdf',
buffer: pdfBuffer(),
type: 'application/pdf',
})
const key = upload.mock.calls[0]![0] as string
expect(key).toMatch(/^documents\/company-1\/user-1\/\d+_kvitto\.pdf$/)
// The legacy layout put userId directly under `documents/`, which left
// company_id out of the RLS-visible path entirely.
expect(key).not.toMatch(/^documents\/user-1\//)
})
it('cleans up the uploaded object via the service-role client when the record insert fails', async () => {
// The documents bucket is WORM (no DELETE policy): a caller-bound
// remove() is silently blocked by RLS, so the failed-upload cleanup must
// run on the service-role client or the object is orphaned forever.
results = [{ data: null, error: { message: 'insert exploded' } }]
const serviceRemove = vi.fn().mockResolvedValue({ data: [], error: null })
serviceClientOverride = makeClient({ remove: serviceRemove })
const callerRemove = vi.fn().mockResolvedValue({ data: [], error: null })
const upload = vi.fn().mockResolvedValue({ data: {}, error: null })
const supabase = makeClient({ upload, remove: callerRemove })
await expect(
uploadDocument(supabase as never, 'user-1', 'company-1', {
name: 'kvitto.pdf',
buffer: pdfBuffer(),
type: 'application/pdf',
}),
).rejects.toThrow(/Failed to create document record/)
const uploadedKey = upload.mock.calls[0]![0] as string
expect(serviceRemove).toHaveBeenCalledWith([uploadedKey])
expect(callerRemove).not.toHaveBeenCalled()
})
})
describe('createNewVersion', () => {
@@ -275,8 +328,9 @@ describe('createNewVersion', () => {
})
results = [
{ data: current, error: null }, // fetch current
{ data: newVersion, error: null }, // insert new version
{ data: { company_id: 'company-1' }, error: null }, // resolve owning company
{ data: current, error: null }, // create_document_version RPC
{ data: newVersion, error: null }, // fetch new version row
]
const supabase = makeClient()
@@ -290,6 +344,279 @@ describe('createNewVersion', () => {
expect(result.original_id).toBe('doc-1')
expect(result.is_current_version).toBe(true)
})
it('writes the new version under the ORIGINAL document company prefix', async () => {
results = [
{ data: { company_id: 'company-1' }, error: null },
{ data: 'doc-2', error: null },
{ data: makeDocumentAttachment({ id: 'doc-2', version: 2 }), error: null },
]
const upload = vi.fn().mockResolvedValue({ data: {}, error: null })
const supabase = makeClient({ upload })
await createNewVersion(supabase as never, 'user-1', 'doc-1', {
name: 'test-v2.pdf',
buffer: pdfBuffer('new content'),
type: 'application/pdf',
})
expect(upload.mock.calls[0]![0]).toMatch(
/^documents\/company-1\/user-1\/\d+_test-v2\.pdf$/,
)
})
it('refuses to upload when the original document cannot be resolved', async () => {
results = [{ data: null, error: null }]
const upload = vi.fn().mockResolvedValue({ data: {}, error: null })
const supabase = makeClient({ upload })
await expect(
createNewVersion(supabase as never, 'user-1', 'doc-missing', {
name: 'test-v2.pdf',
buffer: pdfBuffer('new content'),
type: 'application/pdf',
}),
).rejects.toThrow(/original document not found/)
expect(upload).not.toHaveBeenCalled()
})
it('cleans up the uploaded object via the service-role client when the version RPC fails', async () => {
results = [
{ data: { company_id: 'company-1' }, error: null }, // resolve owning company
{ data: null, error: { message: 'rpc exploded' } }, // create_document_version RPC
]
const serviceRemove = vi.fn().mockResolvedValue({ data: [], error: null })
serviceClientOverride = makeClient({ remove: serviceRemove })
const callerRemove = vi.fn().mockResolvedValue({ data: [], error: null })
const upload = vi.fn().mockResolvedValue({ data: {}, error: null })
const supabase = makeClient({ upload, remove: callerRemove })
await expect(
createNewVersion(supabase as never, 'user-1', 'doc-1', {
name: 'test-v2.pdf',
buffer: pdfBuffer('new content'),
type: 'application/pdf',
}),
).rejects.toThrow(/Failed to create new version: rpc exploded/)
// WORM bucket: the cleanup must go through the service-role client, not
// the caller-bound client (whose remove() RLS silently blocks).
const uploadedKey = upload.mock.calls[0]![0] as string
expect(serviceRemove).toHaveBeenCalledWith([uploadedKey])
expect(callerRemove).not.toHaveBeenCalled()
})
})
describe('storage key layout helpers', () => {
const company = '11111111-1111-4111-8111-111111111111'
const user = '22222222-2222-4222-8222-222222222222'
it('builds a company-scoped key and sanitizes the filename', () => {
// sanitizeFileName replaces non-ASCII with '_', collapses runs, and trims
// leading/trailing underscores: "Kvitto å ä ö" ends up as "Kvitto".
expect(buildDocumentStoragePath(company, user, 'Kvitto å ä ö.pdf', 1700000000000)).toBe(
`documents/${company}/${user}/1700000000000_Kvitto.pdf`,
)
expect(buildDocumentStoragePath(company, user, 'faktura 2026-05.pdf', 1700000000000)).toBe(
`documents/${company}/${user}/1700000000000_faktura_2026-05.pdf`,
)
})
it('recognises company-scoped keys', () => {
expect(isCompanyScopedDocumentPath(`documents/${company}/${user}/1_a.pdf`, company)).toBe(true)
expect(isCompanyScopedDocumentPath(`documents/${user}/1_a.pdf`, company)).toBe(false)
})
it('translates legacy to company-scoped and back', () => {
const legacy = `documents/${user}/1_a.pdf`
const scoped = `documents/${company}/${user}/1_a.pdf`
expect(companyScopedDocumentPath(legacy, company)).toBe(scoped)
expect(legacyDocumentPath(scoped, company)).toBe(legacy)
// Already in the target layout: no translation offered.
expect(companyScopedDocumentPath(scoped, company)).toBeNull()
expect(legacyDocumentPath(legacy, company)).toBeNull()
})
it('offers no alternate for keys outside the documents/ root', () => {
// The MCP audit-package tool writes `{userId}/audit-packages/...`, which
// is not a document_attachments key and must never be rewritten.
const foreign = `${user}/audit-packages/1_archive.zip`
expect(companyScopedDocumentPath(foreign, company)).toBeNull()
expect(documentStoragePathCandidates(foreign, company)).toEqual([foreign])
})
it('lists the stored pointer first, then the alternate layout', () => {
const legacy = `documents/${user}/1_a.pdf`
const scoped = `documents/${company}/${user}/1_a.pdf`
expect(documentStoragePathCandidates(legacy, company)).toEqual([legacy, scoped])
expect(documentStoragePathCandidates(scoped, company)).toEqual([scoped, legacy])
// No companyId: nothing to derive, stored pointer only.
expect(documentStoragePathCandidates(legacy, null)).toEqual([legacy])
})
})
describe('dual-layout read helpers', () => {
const company = 'company-1'
const user = 'user-1'
const legacy = `documents/${user}/1_a.pdf`
const scoped = `documents/${company}/${user}/1_a.pdf`
it('downloadDocumentObject falls back to the company-scoped key', async () => {
const download = vi.fn(async (path: string) =>
path === scoped
? { data: new Blob(['ok']), error: null }
: { data: null, error: { message: 'Object not found' } },
)
const supabase = makeClient({ download })
const result = await downloadDocumentObject(supabase as never, legacy, company)
expect(result.blob).not.toBeNull()
expect(result.resolvedPath).toBe(scoped)
expect(download).toHaveBeenCalledTimes(2)
expect(download.mock.calls[0]![0]).toBe(legacy)
})
it('downloadDocumentObject falls back to the legacy key', async () => {
const download = vi.fn(async (path: string) =>
path === legacy
? { data: new Blob(['ok']), error: null }
: { data: null, error: { message: 'Object not found' } },
)
const supabase = makeClient({ download })
const result = await downloadDocumentObject(supabase as never, scoped, company)
expect(result.resolvedPath).toBe(legacy)
})
it('downloadDocumentObject reports the stored-pointer error when both fail', async () => {
const download = vi.fn(async (path: string) => ({
data: null,
error: { message: `missing:${path}` },
}))
const supabase = makeClient({ download })
const result = await downloadDocumentObject(supabase as never, legacy, company)
expect(result.blob).toBeNull()
expect(result.resolvedPath).toBeNull()
expect(result.error?.message).toBe(`missing:${legacy}`)
})
it('createDocumentSignedUrl falls back to the alternate layout', async () => {
const createSignedUrl = vi.fn(async (path: string) =>
path === scoped
? { data: { signedUrl: 'https://example.com/signed' }, error: null }
: { data: null, error: { message: 'Object not found' } },
)
const supabase = makeClient({ createSignedUrl })
const result = await createDocumentSignedUrl(supabase as never, legacy, company, 3600)
expect(result.signedUrl).toBe('https://example.com/signed')
expect(result.resolvedPath).toBe(scoped)
})
})
describe('deleteDocument', () => {
it('removes BOTH key layouts via the service-role client so no readable orphan copy survives', async () => {
const company = 'company-1'
const legacy = 'documents/user-1/1_a.pdf'
results = [
{
data: {
id: 'doc-1',
file_name: 'a.pdf',
storage_path: legacy,
journal_entry_id: null,
user_id: 'user-1',
},
error: null,
},
{ data: null, error: null }, // delete
]
const serviceRemove = vi.fn().mockResolvedValue({ data: [], error: null })
serviceClientOverride = makeClient({ remove: serviceRemove })
const callerRemove = vi.fn().mockResolvedValue({ data: [], error: null })
const supabase = makeClient({ remove: callerRemove })
const result = await deleteDocument(supabase as never, company, 'doc-1')
expect(result.ok).toBe(true)
expect(serviceRemove).toHaveBeenCalledWith([legacy, `documents/${company}/user-1/1_a.pdf`])
// The documents bucket is WORM (no DELETE policy on storage.objects): a
// caller-bound remove() is silently blocked by RLS and reports success
// without deleting, so it must never be used for the removal.
expect(callerRemove).not.toHaveBeenCalled()
})
it('does not touch storage when the company-filtered fetch finds nothing (authz-first)', async () => {
results = [{ data: null, error: null }]
const serviceRemove = vi.fn().mockResolvedValue({ data: [], error: null })
serviceClientOverride = makeClient({ remove: serviceRemove })
const result = await deleteDocument(makeClient() as never, 'company-1', 'doc-1')
expect(result).toMatchObject({ ok: false, reason: 'not_found', status: 404 })
expect(serviceRemove).not.toHaveBeenCalled()
})
it('refuses to delete a document linked to a journal entry (BFL 7 kap 2§)', async () => {
results = [
{
data: {
id: 'doc-1',
file_name: 'a.pdf',
storage_path: 'documents/user-1/1_a.pdf',
journal_entry_id: 'entry-1',
user_id: 'user-1',
},
error: null,
},
]
const serviceRemove = vi.fn().mockResolvedValue({ data: [], error: null })
serviceClientOverride = makeClient({ remove: serviceRemove })
const callerRemove = vi.fn().mockResolvedValue({ data: [], error: null })
const supabase = makeClient({ remove: callerRemove })
const result = await deleteDocument(supabase as never, 'company-1', 'doc-1')
expect(result).toMatchObject({ ok: false, reason: 'linked_to_entry', status: 409 })
expect(callerRemove).not.toHaveBeenCalled()
expect(serviceRemove).not.toHaveBeenCalled()
})
it('keeps the storage objects when the DB row delete is blocked by the trigger', async () => {
results = [
{
data: {
id: 'doc-1',
file_name: 'a.pdf',
storage_path: 'documents/user-1/1_a.pdf',
journal_entry_id: null,
user_id: 'user-1',
},
error: null,
},
{ data: null, error: { message: 'blocked by Bokföringslagen retention trigger' } },
]
const serviceRemove = vi.fn().mockResolvedValue({ data: [], error: null })
serviceClientOverride = makeClient({ remove: serviceRemove })
const result = await deleteDocument(makeClient() as never, 'company-1', 'doc-1')
expect(result).toMatchObject({ ok: false, reason: 'linked_to_entry', status: 409 })
expect(serviceRemove).not.toHaveBeenCalled()
})
})
describe('verifyIntegrity', () => {
+200 -14
View File
@@ -32,6 +32,141 @@ function sanitizeFileName(name: string): string {
return sanitizedBase + sanitizedExt
}
/**
* Storage key layout for the `documents` bucket.
*
* NEW (company-scoped, written since 20260726092000):
* documents/{companyId}/{userId}/{timestamp}_{filename}
*
* LEGACY (uploader-scoped, written before that migration):
* documents/{userId}/{timestamp}_{filename}
*
* The legacy layout carried no company_id, so the storage RLS policy could
* only scope on auth.uid(): an ex-member kept direct Storage access to every
* document they had uploaded even after their company_members row was
* deleted. The company-scoped layout lets the policy check
* public.user_company_ids() instead.
*
* Both layouts coexist until the Phase B backfill
* (scripts/backfill-document-storage-paths.ts) has re-homed every legacy
* object. Read paths must therefore tolerate both: use
* documentStoragePathCandidates() (or the downloadDocumentObject /
* createDocumentSignedUrl helpers below) rather than trusting the stored
* pointer to be the only key that resolves.
*/
export const DOCUMENTS_BUCKET = 'documents'
const DOCUMENTS_PATH_ROOT = 'documents'
/** Build a company-scoped storage key for a new upload. */
export function buildDocumentStoragePath(
companyId: string,
userId: string,
fileName: string,
timestamp: number = Date.now()
): string {
return `${DOCUMENTS_PATH_ROOT}/${companyId}/${userId}/${timestamp}_${sanitizeFileName(fileName)}`
}
/** True when the key already sits under the company-scoped prefix. */
export function isCompanyScopedDocumentPath(storagePath: string, companyId: string): boolean {
return storagePath.startsWith(`${DOCUMENTS_PATH_ROOT}/${companyId}/`)
}
/**
* Translate a legacy `documents/{userId}/...` key into its company-scoped
* equivalent. Returns null when the key is not in the legacy layout (already
* company-scoped, or one of the non-document shapes the bucket also holds,
* e.g. the MCP audit-package `{userId}/audit-packages/...` keys).
*/
export function companyScopedDocumentPath(
storagePath: string,
companyId: string
): string | null {
if (isCompanyScopedDocumentPath(storagePath, companyId)) return null
const prefix = `${DOCUMENTS_PATH_ROOT}/`
if (!storagePath.startsWith(prefix)) return null
return `${prefix}${companyId}/${storagePath.slice(prefix.length)}`
}
/**
* Translate a company-scoped key back into its legacy `documents/{userId}/...`
* equivalent. Returns null when the key is not company-scoped.
*/
export function legacyDocumentPath(storagePath: string, companyId: string): string | null {
const prefix = `${DOCUMENTS_PATH_ROOT}/${companyId}/`
if (!storagePath.startsWith(prefix)) return null
return `${DOCUMENTS_PATH_ROOT}/${storagePath.slice(prefix.length)}`
}
/**
* Every key that could hold the bytes for a document row, most likely first.
* The stored pointer always wins; the alternate layout is the fallback for
* the window in which the Phase B backfill has moved (or not yet moved) an
* object relative to the DB pointer.
*/
export function documentStoragePathCandidates(
storagePath: string,
companyId: string | null | undefined
): string[] {
const candidates = [storagePath]
if (companyId) {
const alternate =
companyScopedDocumentPath(storagePath, companyId) ??
legacyDocumentPath(storagePath, companyId)
if (alternate && alternate !== storagePath) candidates.push(alternate)
}
return candidates
}
type StorageErrorLike = { message?: string } | null
/**
* Download a document object, tolerating both key layouts.
*
* Returns the resolved key alongside the blob so callers can log or repair
* a stale `document_attachments.storage_path` pointer. When every candidate
* fails, the FIRST error is returned: it refers to the stored pointer, which
* is the actionable one.
*/
export async function downloadDocumentObject(
supabase: SupabaseClient,
storagePath: string,
companyId: string | null | undefined
): Promise<{ blob: Blob | null; error: StorageErrorLike; resolvedPath: string | null }> {
let firstError: StorageErrorLike = null
for (const candidate of documentStoragePathCandidates(storagePath, companyId)) {
const { data, error } = await supabase.storage.from(DOCUMENTS_BUCKET).download(candidate)
if (!error && data) {
return { blob: data as Blob, error: null, resolvedPath: candidate }
}
firstError ??= (error as StorageErrorLike) ?? { message: 'download returned no data' }
}
return { blob: null, error: firstError, resolvedPath: null }
}
/**
* Create a signed URL for a document object, tolerating both key layouts.
* Same fallback contract as downloadDocumentObject().
*/
export async function createDocumentSignedUrl(
supabase: SupabaseClient,
storagePath: string,
companyId: string | null | undefined,
expiresInSeconds: number
): Promise<{ signedUrl: string | null; error: StorageErrorLike; resolvedPath: string | null }> {
let firstError: StorageErrorLike = null
for (const candidate of documentStoragePathCandidates(storagePath, companyId)) {
const { data, error } = await supabase.storage
.from(DOCUMENTS_BUCKET)
.createSignedUrl(candidate, expiresInSeconds)
if (!error && data?.signedUrl) {
return { signedUrl: data.signedUrl, error: null, resolvedPath: candidate }
}
firstError ??= (error as StorageErrorLike) ?? { message: 'createSignedUrl returned no data' }
}
return { signedUrl: null, error: firstError, resolvedPath: null }
}
export const MAX_DOCUMENT_SIZE = 10 * 1024 * 1024 // 10 MB
export const ALLOWED_DOCUMENT_TYPES = [
'application/pdf',
@@ -220,9 +355,9 @@ export async function uploadDocument(
// Compute SHA-256 hash
const sha256Hash = await computeSHA256(file.buffer)
// Generate storage path
const timestamp = Date.now()
const storagePath = `documents/${userId}/${timestamp}_${sanitizeFileName(file.name)}`
// Company-scoped storage key: the tenant id must be IN the key so the
// storage RLS policy can revoke access when a membership is removed.
const storagePath = buildDocumentStoragePath(companyId, userId, file.name)
// Upload to Supabase Storage
const { error: uploadError } = await supabase.storage
@@ -259,8 +394,16 @@ export async function uploadDocument(
.single()
if (error) {
// Clean up uploaded file on record creation failure
await supabase.storage.from('documents').remove([storagePath])
// Clean up the just-uploaded object on record creation failure. The
// documents bucket is WORM by design: storage.objects has NO DELETE
// policy, so remove() on the caller's cookie-bound client is silently
// blocked by RLS (it reports success without deleting anything) and the
// object would linger as an orphan. Only the service role can actually
// remove it. Authorization: the key was built by this very call for the
// caller's own failed upload, and no DB row references it.
await createServiceClientNoCookies()
.storage.from(DOCUMENTS_BUCKET)
.remove([storagePath])
throw new Error(`Failed to create document record: ${error.message}`)
}
@@ -298,9 +441,27 @@ export async function createNewVersion(
// Compute SHA-256 hash
const sha256Hash = await computeSHA256(file.buffer)
// The new version must land under the SAME company prefix as the document
// it supersedes. The caller (POST /api/documents/:id/versions) does not
// pass a companyId, so resolve it from the original row: the read goes
// through the user-scoped client, so RLS already blocks a cross-tenant id,
// and create_document_version re-checks membership server-side.
const { data: original, error: originalError } = await supabase
.from('document_attachments')
.select('company_id')
.eq('id', originalId)
.maybeSingle()
if (originalError || !original?.company_id) {
throw new Error('Failed to create new version: original document not found')
}
// Upload new file to Storage
const timestamp = Date.now()
const storagePath = `documents/${userId}/${timestamp}_${sanitizeFileName(file.name)}`
const storagePath = buildDocumentStoragePath(
original.company_id as string,
userId,
file.name
)
const { error: uploadError } = await supabase.storage
.from('documents')
@@ -325,8 +486,15 @@ export async function createNewVersion(
})
if (rpcError) {
// Clean up uploaded file on RPC failure
await supabase.storage.from('documents').remove([storagePath])
// Clean up the uploaded file on RPC failure. Service-role client for the
// same reason as in uploadDocument: the WORM bucket has no DELETE policy,
// so a caller-bound remove() is silently blocked by RLS and the object
// would be orphaned. The original-document fetch above (user-scoped, RLS)
// plus the failed RPC are the authorization context; the key was created
// by this call and nothing references it.
await createServiceClientNoCookies()
.storage.from(DOCUMENTS_BUCKET)
.remove([storagePath])
throw new Error(`Failed to create new version: ${rpcError.message}`)
}
@@ -452,7 +620,21 @@ export async function deleteDocument(
}
if (doc.storage_path) {
await supabase.storage.from('documents').remove([doc.storage_path])
// Remove BOTH key layouts. During the Phase B backfill a document can
// briefly exist under the legacy and the company-scoped key at once;
// removing only the stored pointer would leave a readable orphan copy of
// a document the user asked to erase.
//
// The removal runs on the service-role client: the documents bucket is
// WORM by design (storage.objects has no DELETE policy), so the caller's
// cookie-bound client is silently blocked by RLS and remove() reports
// success while both objects survive, readable by every company member
// under the company-scoped SELECT policy. Authorization already happened
// above: the company-filtered row fetch plus the row delete that just
// succeeded (with block_document_deletion() as the DB-level backstop).
await createServiceClientNoCookies()
.storage.from(DOCUMENTS_BUCKET)
.remove(documentStoragePathCandidates(doc.storage_path, companyId))
}
await eventBus.emit({
@@ -491,11 +673,15 @@ export async function verifyIntegrity(
// Download via the service-role client: the storage SELECT policy only
// covers the uploader's own folder (documents/{uid}/...), so a caller-bound
// client cannot read colleague-uploaded files. The company-filtered row
// fetch above (RLS on document_attachments) is the authorization.
// fetch above (RLS on document_attachments) is the authorization. The
// helper tolerates the legacy and the company-scoped key layout while the
// Phase B backfill is in flight.
const serviceClient = createServiceClientNoCookies()
const { data: fileData, error: downloadError } = await serviceClient.storage
.from('documents')
.download(doc.storage_path)
const { blob: fileData, error: downloadError } = await downloadDocumentObject(
serviceClient,
doc.storage_path,
companyId
)
if (downloadError || !fileData) {
throw new Error(`Failed to download document: ${downloadError?.message}`)
@@ -1,111 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { makeTaxCode } from '@/tests/helpers'
// ============================================================
// Mock: separate client (no .then) from query builder (thenable)
// ============================================================
let resultIdx: number
let results: Array<{ data?: unknown; error?: unknown; count?: number | null }>
function makeBuilder() {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'insert', 'update', 'delete', 'lte', 'gte', 'in', 'not', 'or', 'order', 'limit', 'is']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.single = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
b.maybeSingle = vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null })
b.then = (resolve: (v: unknown) => void) => resolve(results[resultIdx++] ?? { data: null, error: null })
return b
}
function makeClient() {
return {
from: vi.fn().mockImplementation(() => makeBuilder()),
rpc: vi.fn().mockImplementation(async () => results[resultIdx++] ?? { data: null, error: null }),
}
}
import { getTaxCodeByCode, calculateMomsFromTaxCodes } from '../tax-code-service'
beforeEach(() => {
vi.clearAllMocks()
resultIdx = 0
results = []
})
describe('getTaxCodeByCode', () => {
it('prefers user code over system code', async () => {
const userCode = makeTaxCode({
id: 'tc-user',
user_id: 'user-1',
code: 'MP1',
description: 'Custom 25% moms',
rate: 25,
})
results = [{ data: userCode, error: null }]
const supabase = makeClient()
const result = await getTaxCodeByCode(supabase as never, 'user-1', 'MP1')
expect(result).not.toBeNull()
expect(result!.user_id).toBe('user-1')
expect(result!.description).toBe('Custom 25% moms')
})
it('returns null when code does not exist', async () => {
results = [{ data: null, error: { code: 'PGRST116' } }]
const supabase = makeClient()
const result = await getTaxCodeByCode(supabase as never, 'user-1', 'NONEXISTENT')
expect(result).toBeNull()
})
})
describe('calculateMomsFromTaxCodes', () => {
it('aggregates correctly to moms boxes', async () => {
const mp1 = makeTaxCode({
code: 'MP1',
rate: 25,
moms_basis_boxes: ['05'],
moms_tax_boxes: ['10'],
moms_input_boxes: [],
is_output_vat: true,
})
const ip1 = makeTaxCode({
code: 'IP1',
rate: 25,
moms_basis_boxes: [],
moms_tax_boxes: [],
moms_input_boxes: ['48'],
is_output_vat: false,
})
const lines = [
{ tax_code: 'MP1', debit_amount: 0, credit_amount: 10000, journal_entry_id: 'je1', journal_entries: {} },
{ tax_code: 'MP1', debit_amount: 0, credit_amount: 5000, journal_entry_id: 'je2', journal_entries: {} },
{ tax_code: 'IP1', debit_amount: 2500, credit_amount: 0, journal_entry_id: 'je3', journal_entries: {} },
]
results = [
// 0: journal lines query (thenable: no .single())
{ data: lines, error: null },
// 1: getTaxCodes query (thenable: no .single())
{ data: [mp1, ip1], error: null },
]
const supabase = makeClient()
const result = await calculateMomsFromTaxCodes(supabase as never, 'user-1', '2024-01-01', '2024-12-31')
expect(result.length).toBeGreaterThan(0)
// Results should be sorted by box
for (let i = 1; i < result.length; i++) {
expect(result[i].box >= result[i - 1].box).toBe(true)
}
// Check that we have the expected boxes
const boxes = result.map((r) => r.box)
expect(boxes).toContain('05')
expect(boxes).toContain('10')
expect(boxes).toContain('48')
})
})
-165
View File
@@ -1,165 +0,0 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { TaxCode } from '@/types'
/**
* Tax Code Service
*
* Manages decoupled tax codes for momsdeklaration.
* Tax codes map journal entry lines to specific moms rutor (boxes)
* on the Swedish VAT declaration form.
*/
/**
* Get all active tax codes for a user (including system codes)
*/
export async function getTaxCodes(supabase: SupabaseClient, userId: string): Promise<TaxCode[]> {
const { data, error } = await supabase
.from('tax_codes')
.select('*')
.or(`company_id.eq.${userId},company_id.is.null`)
.order('code')
if (error) {
throw new Error(`Failed to fetch tax codes: ${error.message}`)
}
return (data as TaxCode[]) || []
}
/**
* Get a single tax code by code string
*/
export async function getTaxCodeByCode(
supabase: SupabaseClient,
userId: string,
code: string
): Promise<TaxCode | null> {
// Prefer user-specific code over system code
const { data, error } = await supabase
.from('tax_codes')
.select('*')
.eq('code', code)
.or(`company_id.eq.${userId},company_id.is.null`)
.order('user_id', { ascending: false, nullsFirst: false })
.limit(1)
.single()
if (error) {
return null
}
return data as TaxCode
}
/**
* Moms box result from tax code aggregation
*/
export interface MomsBoxResult {
/** Ruta number (e.g. '05', '10', '48') */
box: string
/** Sum of amounts for this box */
amount: number
}
/**
* Calculate momsdeklaration from journal entry lines grouped by tax_code,
* then mapped via the tax_codes table to moms boxes.
*
* This is the new, tax-code-driven approach that replaces the hardcoded
* category-based VAT calculation.
*/
export async function calculateMomsFromTaxCodes(
supabase: SupabaseClient,
userId: string,
periodStart: string,
periodEnd: string
): Promise<MomsBoxResult[]> {
// Fetch journal entry lines with tax_code in the period
const { data: lines, error: linesError } = await supabase
.from('journal_entry_lines')
.select(`
tax_code,
debit_amount,
credit_amount,
journal_entry_id,
journal_entries!inner (
user_id,
entry_date,
status,
fiscal_period_id
)
`)
.not('tax_code', 'is', null)
.eq('journal_entries.company_id', userId)
.eq('journal_entries.status', 'posted')
.gte('journal_entries.entry_date', periodStart)
.lte('journal_entries.entry_date', periodEnd)
if (linesError) {
throw new Error(`Failed to fetch journal lines: ${linesError.message}`)
}
// Fetch all tax codes for lookup
const taxCodes = await getTaxCodes(supabase, userId)
const taxCodeMap = new Map<string, TaxCode>()
for (const tc of taxCodes) {
// User codes take precedence over system codes
if (!taxCodeMap.has(tc.code) || tc.user_id) {
taxCodeMap.set(tc.code, tc)
}
}
// Aggregate amounts by moms box
const boxTotals = new Map<string, number>()
for (const line of lines || []) {
if (!line.tax_code) continue
const taxCode = taxCodeMap.get(line.tax_code)
if (!taxCode) continue
const netAmount = Number(line.debit_amount || 0) - Number(line.credit_amount || 0)
const absAmount = Math.abs(netAmount)
// For output VAT: debit_amount goes to basis boxes, tax amount to tax boxes
// For input VAT: the amount goes to input boxes
const allBoxes = [
...taxCode.moms_basis_boxes,
...taxCode.moms_tax_boxes,
...taxCode.moms_input_boxes,
]
for (const box of allBoxes) {
const current = boxTotals.get(box) || 0
boxTotals.set(box, current + absAmount)
}
}
// Convert to result array
const results: MomsBoxResult[] = []
for (const [box, amount] of boxTotals) {
results.push({
box,
amount: Math.round(amount * 100) / 100,
})
}
return results.sort((a, b) => a.box.localeCompare(b.box))
}
/**
* Seed tax codes for a user by calling the database function
*/
export async function seedTaxCodes(supabase: SupabaseClient, userId: string): Promise<void> {
const { error } = await supabase.rpc('seed_tax_codes_for_user', {
p_user_id: userId,
})
if (error) {
throw new Error(`Failed to seed tax codes: ${error.message}`)
}
}