Check/salary bankid api (#892)

* fix(bankid): harden login/signup flow — polling, signup rollback, metadata merge, enrichment lookup

- middleware: read BankID enrichment from the bankid_enrichment table (the
  extension_data path has been dead since the multi-tenant refactor), so
  company-less BankID users land on /select-company instead of the manual wizard
- BankIdAuth: hard 6-min poll deadline; every failed poll counts toward the
  give-up limit; guard overlapping ticks so completion runs exactly once
  (a double /complete regenerated the magic link and invalidated the first,
  failing logins intermittently); retry clicks wait out the start cooldown
  instead of silently no-oping; Swedish messages for 429/unknown start errors
- bankid/complete: all-or-nothing signup — delete the created user when the
  identity insert, app_metadata update, or magic-link generation fails, so a
  retry starts clean instead of hitting account_exists with an unusable account
- bankid/unlink: read-merge-write app_metadata so has_password survives unlink
  (BankID-only users could otherwise strand themselves with no login method)
- login: BankID "create account" CTA now links to /register instead of
  dismissing the notice; sv.json: fix missing å/ä/ö in settings_bankid strings

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

* docs: move secondary guides into docs/, delete dead root files

Move DOCKER.md, SELF-HOSTING.md, WHITELABEL.md and extensions.md
(renamed EXTENSIONS.md) into a new docs/ folder and update all path
references (README, setup.sh, .dockerignore image rules, docker-publish
workflow comment, _example-branding, lib/branding/service.ts).

Delete two dead root files: customer.json (stray API-test payload) and
findings.md (point-in-time swarm audit export, criticals already filed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Emil <emilmattsson14@gmail.com>

* fix(api): security & correctness hardening + withRouteContext MFA migration across API routes

Audit of ~100 app/api routes. Highlights:

Security
- agent/conversations: list leaked colleagues' titles + message previews
  (company-scoped RLS, no user filter) -> user-scoped
- calendar/feed PUT: raw body into .update() allowed feed_token fixation on a
  public unauthenticated URL -> strict schema, content toggles only
- bokslutsdispositioner: unbounded schablonintaktRate could inflate the
  IL 30 kap 25% periodiseringsfond cap base -> bounded
- agent profile/composer/onboarding: viewers could rewrite the agent profile
  while sibling /verify blocked them -> role-gated

Correctness
- account-totals / listAssets: unbounded queries silently truncated at 1000
  rows (under-counted money; skipped assets at year-end depreciation) ->
  fetchAllRows with stable order (+3 more pagination fixes)
- voucher-gaps: swallowed detect_voucher_gaps RPC errors (BFNAR gap view could
  show "no gaps" when the check never ran) -> surfaced
- 5 phantom-success writes (OK on zero matched rows) fixed
- assets K3 component-sum validated against stale acquisition_cost -> fixed
- invite silent email-send failure -> response carries email_sent;
  deadlines/calendar cast-then-check JSON crashes -> Zod

Convention
- ~44 legacy routes converted to withRouteContext (MFA); added Zod validation,
  corrected status codes, console.* -> lib/logger

Response shapes preserved for existing callers. ~110 new tests.

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

* feat(bookkeeping): save a booking as a reusable template from Bokför direkt

Add a "Spara som mall" action to the manual booking dialog so users can
capture a kontering they just worked out as a booking template — right
where they figured out how something should be booked.

- derive amount-parameterised template lines from the concrete booking
  (settlement = the non-VAT leg nearest the total, 26xx = a VAT line with
  its rate snapped to the nearest standard rate, the rest = business
  ratios; line labels come from the loaded BAS chart)
- extract the shared TemplateForm out of BookingTemplatesPanel so the
  booking dialog reuses the same editor, live preview and convertibility
  hints instead of duplicating them
- save via the existing POST /api/settings/booking-templates endpoint

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

* fix(bokslut): render arsredovisning RR/BR at ÅRL post level — no kontonummer

Bolagsverket rejected a user's filed årsredovisning with "Balansräkning
och resultaträkning ska inte innehålla kontonummer": the PDF built every
statement row as per-account "1930 Företagskonto" lines while the iXBRL
filing path already aggregated to statutory posts, so the two artifacts
diverged.

The PDF statements now derive from the same K2 risbs mapping the iXBRL
document uses (mapTrialBalancesToK2), via a new statement-rows.ts that
emits post-level rows in uppställningsform order for both the K2 and K3
templates. Also fixed along the way:

- Jämförelseår column (ÅRL 3:5 §) — previous-year trial balances now load
  and render; the old PDF had no comparatives at all.
- mapping.warnings (unmapped accounts, RR ≠ 2099, obalans, reclass
  nudges) flow into ArsredovisningData.warnings so the wizard flags a
  non-fileable document before download.
- Flerårsöversikt current/previous year overridden with the mapper's
  strict-3000–3799 Nettoomsattning, mirroring build-input's
  duplicate-fact rule, so the FB table ties to the RR.
- FB eget kapital-table is post-level and drops obeskattade reserver
  (never eget kapital); K3 equity-changes statement uses real prior-year
  opening balances with derived utdelning/nyemission residuals that tie
  the roll-forward exactly to booked UB.
- build-input dedupes warnings now that the PDF path runs the same
  mapping.

Regression test asserts no RR/BR label ever contains a four-digit
account number again.

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

* fix(reports): diagnose untransferred prior-year results behind balance-sheet differens

Prod incident (97 kr): a multi-year SIE migration lacked one year's
omforing av arets resultat; the residual corrupted every later derived
opening balance and Balansrakningen showed a bare "Differens: 97 kr"
with no explanation. Continuity checking cannot catch this failure mode
(prior-year UB and derived IB match per-account by construction) - the
invariant that actually breaks is per-year P&L = 0 for all non-latest
years.

- lib/reports/imbalance-diagnosis.ts: shared detector
  (findUntransferredResults + buildImbalanceDiagnosis)
- Balansrakning/Balansrapport attach imbalance_diagnosis when unbalanced,
  naming the exact culprit years; rendered in web views + PDF; MCP
  gnubok_get_balance_sheet inherits the field via spread
- SIE import: parse-time warning when a completed year's vouchers leave
  a P&L residual, plus a post-import DB walk surfacing culprits as
  warnings and structured details.untransferredResults; the Arcim
  migration workspace previously dropped result.warnings entirely and
  now renders them
- opening-balance/correct: pre-flight the company lock date and return
  409 OB_COMPANY_LOCK_DATE (retryable: false, lock date interpolated in
  the client message) instead of the retryable 500 that invited blind
  retries; catch-path maps a raced trigger rejection to the same code

Diagnosis runs only on unbalanced paths (zero cost when healthy) and
never fails the report or the import. No migration, nothing persisted.

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

* fix: production error remediation — FX rates, deadlines, log levels, correction relink

Batch of fixes for recurring Vercel runtime errors:

- Riksbanken FX rates: persistent read-through cache (exchange_rates
  table), one retry honoring Retry-After on 429/5xx, bounded ingest
  concurrency, and an honest fallback — most recent cached observation
  or null, never a hardcoded rate silently booked into amount_sek.
  Unrated transactions stay repairable via refresh-exchange-rate.
- Tax deadline regeneration inserts replacement rows before deleting
  the superseded set, so a failed insert no longer wipes a company's
  deadlines (the 23502 user_id regression did exactly that). Migration
  makes deadlines.user_id nullable for system-generated rows.
- Route wrappers + errorResponse log 4xx outcomes at warn so only
  genuine 5xx reach Vercel's runtime-error clustering; client-supplied
  /api/log telemetry demoted to warn as well.
- application/json documents (raw PSD2 responses archived per BFL)
  validate as parseable JSON with object/array root instead of always
  failing the magic-byte check.
- correctEntry surfaces document-relink failures to callers, and the
  BFL document-immutability trigger now allows relinking underlag from
  a reversed entry to its correction (migration + pg test).
- Middleware clears stale session cookies on /api requests too, using
  scope 'local' so cleanup doesn't re-trigger the failed token refresh.

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

* fix(skatteverket): persist token health and stop retrying dead consents

Terminal auth errors (SESSION_EXPIRED, REFRESH_EXHAUSTED, MISSING_SCOPE,
TOKEN_CORRUPTED) mark the token row needs_reconsent with the error code
and timestamp — SKV per-flow refresh tokens live 65 minutes, so once
expired nothing recovers without a fresh BankID consent. The AGI
kvittens and skattekonto sync crons skip flagged connections instead of
failing every night, and the settings panel prompts for re-consent
proactively. A successful reconnect resets the row to active.

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

* fix(banking): allocate distinct BAS ledger slots for PSD2 mirror accounts

A bank returning N same-currency accounts used to map them all onto the
currency default (1930/1932/1933/1934), tripping the UNIQUE
(company_id, ledger_account) constraint per-account — swallowed errors
left accounts silently unmirrored. allocatePsd2LedgerAccount now hands
out the currency default first, then free 1931–1959 sub-account slots,
skipping slots held by any existing row.

- Callback persists allocations to accounts_data so the picker pre-fills
  reality; reconnect reuses previously mirrored ledgers instead of
  re-deriving (a user remap to 1935 survives).
- Selection save resolves effective ledgers up front and rejects
  duplicates or cross-connection conflicts with a 400 instead of
  silently skipping the mirror.
- Bank error codes + psu_type are forwarded to the settings page for
  every OAuth error, keying the Handelsbanken corporate fullmakt
  guidance.

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

* fix(agent): stage exact journal lines on categorization previews

Categorization previews only carried debit/credit accounts, the GROSS
amount, and separate VAT rows — read together that looks like an
unbalanced 'gross on cost account + VAT debit' entry, and it misled
both users and agents into rejecting correct proposals. The MCP
preview and the pending-operation PATCH now materialize the exact
lines the commit executor will post (net cost line, VAT line, gross
bank line, SEK) via buildTransactionEntryLines, and PATCH re-derives
them from the new mapping instead of spreading stale staged lines.
ApprovalCard and /pending render the verifikat lines, falling back to
the legacy summary only for operations staged before this fix.

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

* feat(bookkeeping): prune unused imported accounts from the chart

SIE imports routinely bring in hundreds of accounts that were never
used and clutter the kontoplan. New account_usage_counts RPC (one
grouped query instead of a count per account) backs GET
/api/bookkeeping/accounts/usage, and POST /api/bookkeeping/accounts/prune
deletes zero-usage accounts — dry-run first, then an explicit account
list capped at 2000. Accounts with journal lines are skipped, never
deleted. The chart manager shows a usage column and a prune dialog
grouping custom accounts vs unused BAS-seeded ones.

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

* feat(api): carry dimensions through v1 invoice and supplier-invoice surfaces

Credit-note creation now copies default_dimensions and per-line
dimensions from the original, so the reversing journal entry nets
against the same dimension cells instead of dropping them. List/detail
responses expose the dimension fields, and the OpenAPI spec snapshot
follows.

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

* perf: batch serial Supabase round-trips on hot dashboard paths

Every dashboard render pays the layout's query chain, so serialized
awaits are direct wall-clock: the layout, chat conversation, invoice
detail, supplier detail, select-company, and agent-onboarding pages now
run their independent lookups in parallel batches, and
getCompanyCapabilities folds its disabled-config read into the same
round-trip. JournalEntryList hydrates the saved fiscal-year scope
optimistically instead of serializing the first entries fetch behind
the fiscal-periods request. The supplier detail page filters invoices
server-side via a new supplier_id query param instead of fetching the
whole company ledger, and the invoice editor (with its framer-motion
dependency) lazy-loads so it stops shipping with the invoice list
bundle.

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

* feat(salary): one-click runs, payslip delivery, payments settings, run cockpit

Salary P1 batch, driving the 20-click flow toward 3 clicks:

- One-click 'Starta lönekörning': POST /api/salary/runs accepts an
  empty body and resolves defaults server-side — period follows the
  latest non-corrected run, payment date from the new
  salary_pay_day setting, series from the per-source-type map. The
  separate /salary/runs/new page is gone.
- Run detail page rebuilt as a step-railed cockpit (progress rail,
  KPI cards, employee ledger, journal preview) on a deliberately
  wider canvas; components extracted to components/salary/run/.
- Payslip delivery: tokenized public payslip pages (/payslip/[token],
  backed by salary_payslip_links) plus per-employee email send with
  PDF — employees need no account, and the middleware exempts the
  route from auth redirects.
- Payments settings: salary pay day, default bank, and pain.001 vs
  Bankgirot Lön format with per-bank upload instructions and an LB
  sunset warning (banks retire LB during 2026).
- AGI panel: full submission status flows (stale drafts, signing
  links, kvittens polling, error reports); tax payment panel with
  skattekonto shortcut and mark-as-paid.
- Salary calendar bulk editing, employee benefits/tax-card polish,
  municipality tax-table lookup improvements.

messages/sv+en also carry the strings for the account-prune,
skatteverket-reconsent, and banking surfaces committed just before
this.

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

* chore: adopt Next 16 proxy.ts convention + repo housekeeping

- Rename middleware.ts to proxy.ts with the proxy() export (Next 16
  renamed the middleware convention; behavior unchanged).
- Exclude dev_docs/ from tsconfig so stray snippets in planning docs
  don't break the build type-check.
- Ratchet antipatterns-baseline down (raw-route-auth 165 → 119) to
  lock in the withRouteContext migration from 5cfd2b76.
- template-library uses roundOre() instead of inline rounding.
- database.md: drop account_balances from the key-tables list.

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

* fix(bookkeeping): robust service-role detection in correction document relink

relink_documents_to_correction() keyed its service-role branch on auth.role(),
which reads the singular request.jwt.claim.role GUC that PostgREST v10+ and the
pg-real harness no longer populate. Genuine service-role callers (pending-ops
executor / MCP approve) landed in the auth gate and could not relink underlag.
Read the role from the request.jwt.claims JSON directly, mirroring the canonical
link_voucher_rpcs_tenant_guard convention. Validated on staging.

Also: harden the salary run page's error paths (res.json().catch) against
non-JSON error bodies, and roll back the pg-real service-role case in finally so
an aborted transaction cannot poison a pooled connection for the next test.

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

* fix(documents): restore journal_entry_line_id link durability (BFL 7 kap)

Migration 20260704103000 rewrote enforce_document_journal_entry_immutability to
guard journal_entry_id but left journal_entry_line_id to the metadata trigger,
which exempts draft-linked docs -- and the entry-level trigger only fired on
UPDATE OF journal_entry_id, so a line-id-only UPDATE never invoked it at all.
That let a set journal_entry_line_id be cleared to NULL, breaking the "link
durable from first set" invariant (document-immutability.pg regression).

Widen the trigger to fire on journal_entry_line_id too and guard it with the
same uuid-durability rule as journal_entry_id (setting NULL -> uuid stays
allowed; clearing/re-pointing a set value is blocked, status-independent). The
correction-relink GUC path, which legitimately clears line_id when moving
underlag to the posted correction, stays exempt. Validated on staging.

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

---------

Signed-off-by: Emil <emilmattsson14@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-07-05 03:05:09 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent ec27228a8e
commit 2c2743eb79
269 changed files with 17974 additions and 6481 deletions
@@ -0,0 +1,71 @@
-- Salary settings P1: pain.001 becomes the default payment format, plus
-- persisted payroll settings (pay day, default bank).
--
-- Background (dev_docs/payroll-benchmark-2026.md): the Swedish bank
-- infrastructure retires Bankgirot Lön (LB) bank-by-bank during 2026
-- (Swedbank ends "Lön via Bankgirot" 2026-08-01; Handelsbanken stopped
-- accepting salary files to Bankgirot after 2026-05-31). ISO 20022 pain.001
-- is the replacement and is already implemented.
--
-- This migration:
-- 1. Flips the column default for preferred_payment_format to 'pain001'.
-- 2. Conditionally backfills existing companies: only those that have
-- NEVER generated an LB file are flipped (the old 'bg_lb' default was
-- applied blindly by 20260508120000 and encodes no preference for
-- them). Companies with a working LB routine keep 'bg_lb' and get an
-- in-product sunset warning instead.
-- 3. Adds company_settings.salary_pay_day (day of month salaries are paid;
-- drives run-creation defaults and the salary dashboard).
-- 4. Adds company_settings.salary_default_bank (pre-selects bank upload
-- instructions for payment files).
-- ------------------------------------------------------------------
-- 1. New default
-- ------------------------------------------------------------------
ALTER TABLE public.company_settings
ALTER COLUMN preferred_payment_format SET DEFAULT 'pain001';
-- ------------------------------------------------------------------
-- 2. Conditional backfill (idempotent)
-- ------------------------------------------------------------------
UPDATE public.company_settings cs
SET preferred_payment_format = 'pain001'
WHERE cs.preferred_payment_format = 'bg_lb'
AND NOT EXISTS (
SELECT 1 FROM public.salary_runs sr
WHERE sr.company_id = cs.company_id
AND sr.payment_file_format = 'bg_lb'
);
-- ------------------------------------------------------------------
-- 3. salary_pay_day
-- ------------------------------------------------------------------
ALTER TABLE public.company_settings
ADD COLUMN IF NOT EXISTS salary_pay_day integer NOT NULL DEFAULT 25;
ALTER TABLE public.company_settings
DROP CONSTRAINT IF EXISTS company_settings_salary_pay_day_check;
-- 1–28 so the configured day exists in every month (February included).
ALTER TABLE public.company_settings
ADD CONSTRAINT company_settings_salary_pay_day_check
CHECK (salary_pay_day BETWEEN 1 AND 28);
-- ------------------------------------------------------------------
-- 4. salary_default_bank
-- ------------------------------------------------------------------
ALTER TABLE public.company_settings
ADD COLUMN IF NOT EXISTS salary_default_bank text;
ALTER TABLE public.company_settings
DROP CONSTRAINT IF EXISTS company_settings_salary_default_bank_check;
ALTER TABLE public.company_settings
ADD CONSTRAINT company_settings_salary_default_bank_check
CHECK (
salary_default_bank IS NULL
OR salary_default_bank IN ('swedbank', 'seb', 'handelsbanken', 'nordea', 'other')
);
-- Reload PostgREST schema cache.
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,66 @@
-- Secure payslip links.
--
-- Payslips are delivered to employees as emailed LINKS (not PDF attachments —
-- salary data + personnummer must not sit in inboxes). The link token is a
-- credential with a lifecycle (rotation on resend, revocation on correction,
-- expiry), so it lives in its own table — NOT on salary_payslip_deliveries,
-- which is an append-only BFL 7 kap. audit log of delivery attempts.
--
-- One live link per (salary_run_id, employee_id); resending rotates the
-- token (old hash invalidated by overwrite). Raw tokens are never stored —
-- sha256 hex only. The public resolve path uses the service role; there are
-- deliberately NO anon policies.
CREATE TABLE IF NOT EXISTS public.salary_payslip_links (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
salary_run_id uuid NOT NULL REFERENCES public.salary_runs(id) ON DELETE CASCADE,
employee_id uuid NOT NULL REFERENCES public.employees(id) ON DELETE RESTRICT,
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
-- sha256 hex of the raw token; the raw token exists only in the email.
token_hash text NOT NULL UNIQUE,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
last_accessed_at timestamptz,
access_count integer NOT NULL DEFAULT 0,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (salary_run_id, employee_id)
);
ALTER TABLE public.salary_payslip_links ENABLE ROW LEVEL SECURITY;
CREATE POLICY "salary_payslip_links_select"
ON public.salary_payslip_links
FOR SELECT
USING (company_id IN (SELECT public.user_company_ids()));
CREATE POLICY "salary_payslip_links_insert"
ON public.salary_payslip_links
FOR INSERT
WITH CHECK (company_id IN (SELECT public.user_company_ids()));
CREATE POLICY "salary_payslip_links_update"
ON public.salary_payslip_links
FOR UPDATE
USING (company_id IN (SELECT public.user_company_ids()));
-- No DELETE policy — links are revoked (revoked_at), never deleted, so the
-- trail of what was ever reachable stays auditable.
CREATE INDEX idx_payslip_links_run
ON public.salary_payslip_links (salary_run_id);
CREATE INDEX idx_payslip_links_company
ON public.salary_payslip_links (company_id);
CREATE TRIGGER salary_payslip_links_updated_at
BEFORE UPDATE ON public.salary_payslip_links
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,15 @@
-- Drop NOT NULL on deadlines.user_id.
--
-- The multi-tenant company refactor (20260330130000) moved deadlines to
-- company ownership: company_id column + company-scoped RLS, and the tax
-- deadline generator (lib/tax/deadline-generator.ts) stopped sending user_id.
-- The refactor dropped NOT NULL on user_id for audit_log and company_settings
-- (and later fiscal_periods, narrative_signatures) but missed deadlines —
-- since then every auto-generation insert fails with 23502, and because the
-- generator deletes existing system deadlines before inserting, affected
-- companies lost their tax deadlines entirely.
--
-- user_id stays as an optional "created by" attribution for manually created
-- deadlines (app/api/deadlines/route.ts still sends it). Ownership is
-- company_id.
ALTER TABLE public.deadlines ALTER COLUMN user_id DROP NOT NULL;
@@ -0,0 +1,38 @@
-- Persistent read-through cache for Riksbanken exchange rates.
--
-- Before this, every enable-banking sync cron run re-fetched every unique
-- (currency, date) pair straight from Riksbanken — a first sync of one
-- foreign-currency account fired up to ~180 parallel requests at 05:00 and
-- got rate-limited (429). The failure path then silently booked transactions
-- with hardcoded fallback rates (EUR at exactly 11.5).
--
-- Rates are public reference data shared across all tenants — no company_id.
-- rate_date is the date the rate was requested FOR; observation_date is the
-- Riksbanken observation backing it (differs on weekends/holidays, where the
-- most recent prior observation answers the request).
CREATE TABLE IF NOT EXISTS public.exchange_rates (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
currency TEXT NOT NULL CHECK (length(currency) = 3),
rate_date DATE NOT NULL,
rate NUMERIC NOT NULL CHECK (rate > 0),
observation_date DATE NOT NULL,
source TEXT NOT NULL DEFAULT 'riksbanken',
fetched_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (currency, rate_date)
);
ALTER TABLE public.exchange_rates ENABLE ROW LEVEL SECURITY;
-- Readable and insertable by any authenticated user: the cache is filled
-- lazily from whichever request needs a rate first, and the data is public
-- (Riksbanken publishes it). No UPDATE/DELETE policies — a cached
-- (currency, rate_date) observation never changes; conflicting inserts use
-- ignoreDuplicates.
DROP POLICY IF EXISTS "exchange_rates_select" ON public.exchange_rates;
CREATE POLICY "exchange_rates_select" ON public.exchange_rates
FOR SELECT TO authenticated USING (true);
DROP POLICY IF EXISTS "exchange_rates_insert" ON public.exchange_rates;
CREATE POLICY "exchange_rates_insert" ON public.exchange_rates
FOR INSERT TO authenticated WITH CHECK (true);
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,23 @@
-- Connection health for Skatteverket tokens.
--
-- SKV's `per`-flow refresh tokens live 65 minutes, so any daily cron always
-- finds a dead token; and tokens consented before a scope rollout (the AGI
-- `agd` scope is the canonical case) 403 forever until the user re-consents.
-- Neither state was persisted anywhere: the crons retried and error-logged
-- the same broken connections every night, and the UI only discovered the
-- problem after a live failure.
--
-- status:
-- 'active' — believed working; crons attempt it
-- 'needs_reconsent' — a cron or API call hit a terminal auth state
-- (SESSION_EXPIRED / REFRESH_EXHAUSTED / MISSING_SCOPE /
-- TOKEN_CORRUPTED); crons skip it, the UI shows a
-- reconnect prompt proactively. Reset to 'active' by
-- storeTokens() on successful re-consent.
ALTER TABLE public.skatteverket_tokens
ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'active'
CHECK (status IN ('active', 'needs_reconsent')),
ADD COLUMN IF NOT EXISTS last_error_code TEXT,
ADD COLUMN IF NOT EXISTS last_error_at TIMESTAMPTZ;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,242 @@
-- Make correctEntry()'s document relink legal — via a validated RPC.
--
-- Background: relinkDocumentsToEntry (storno-service, added 2026-06-01) moves
-- underlag from a corrected (now 'reversed') entry to its correction so the
-- live verifikat carries its documents. But the immutability triggers that
-- landed 2026-05-06 forbid ANY change to a set journal_entry_id:
-- - enforce_document_journal_entry_immutability blocks unconditionally
-- (its "Reverse the journal entry first" message notwithstanding — it
-- never inspects entry status), and
-- - enforce_document_metadata_immutability additionally blocks when the
-- linked entry is posted OR reversed.
-- The relink therefore failed 100% of the time, its error was swallowed, and
-- every correction of an entry with attached underlag silently stranded the
-- documents on the reversed original.
--
-- Fix, following the gnubok.allow_supersede precedent (20260527130000): a
-- transaction-local GUC (gnubok.allow_correction_relink) that ONLY the
-- SECURITY DEFINER RPC relink_documents_to_correction() sets, after
-- validating that the move follows a genuine correction chain:
-- from-entry status 'reversed', to-entry status 'posted',
-- to.correction_of_id = from.id, same company, caller authorized.
-- The GUC bypass in the triggers is deliberately narrow: journal_entry_id
-- may only move uuid → uuid (never to NULL — that path would be a
-- soft-delete bypass of BFL 7 kap 2§), and every other guarded field stays
-- immutable even with the GUC set.
-- ── 1. Entry-link trigger: allow uuid → uuid under the relink GUC ─────────
CREATE OR REPLACE FUNCTION public.enforce_document_journal_entry_immutability()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
RETURN NEW;
END IF;
IF NEW.journal_entry_id IS NOT DISTINCT FROM OLD.journal_entry_id THEN
RETURN NEW;
END IF;
IF OLD.journal_entry_id IS NULL THEN
RETURN NEW;
END IF;
-- Correction relink: set ONLY by relink_documents_to_correction() after it
-- has validated the correction chain. uuid → uuid moves only; clearing to
-- NULL stays blocked even with the GUC (that would be a delete bypass).
IF current_setting('gnubok.allow_correction_relink', true) = 'true'
AND NEW.journal_entry_id IS NOT NULL THEN
RETURN NEW;
END IF;
IF NEW.journal_entry_id IS NULL OR NEW.journal_entry_id <> OLD.journal_entry_id THEN
RAISE EXCEPTION
'BFL_DOCUMENT_IMMUTABILITY: cannot clear or change journal_entry_id on document % once set (BFL 5 kap 6 §). Reverse the journal entry first.',
OLD.id;
END IF;
RETURN NEW;
END;
$$;
-- ── 2. Metadata trigger: exempt the two link columns under the same GUC ───
CREATE OR REPLACE FUNCTION public.enforce_document_metadata_immutability()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
v_entry_status text;
v_allow_supersede boolean;
v_allow_relink boolean;
BEGIN
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
RETURN NEW;
END IF;
v_allow_supersede := current_setting('gnubok.allow_supersede', true) = 'true';
v_allow_relink := current_setting('gnubok.allow_correction_relink', true) = 'true';
IF OLD.journal_entry_id IS NULL THEN
RETURN NEW;
END IF;
SELECT status INTO v_entry_status
FROM public.journal_entries
WHERE id = OLD.journal_entry_id;
IF v_entry_status IS NULL OR v_entry_status NOT IN ('posted', 'reversed') THEN
RETURN NEW;
END IF;
-- Even with allow_supersede or allow_correction_relink, every field other
-- than the ones each narrow bypass covers remains immutable. A session
-- that obtains a GUC (e.g. via SQL injection) still cannot mutate
-- sha256_hash, storage_path, or any other field the BFL 7 kap audit trail
-- depends on.
IF NEW.file_name IS DISTINCT FROM OLD.file_name
OR NEW.storage_path IS DISTINCT FROM OLD.storage_path
OR NEW.file_size_bytes IS DISTINCT FROM OLD.file_size_bytes
OR NEW.mime_type IS DISTINCT FROM OLD.mime_type
OR NEW.sha256_hash IS DISTINCT FROM OLD.sha256_hash
OR NEW.upload_source IS DISTINCT FROM OLD.upload_source
OR NEW.digitization_date IS DISTINCT FROM OLD.digitization_date
OR NEW.uploaded_by IS DISTINCT FROM OLD.uploaded_by
OR NEW.version IS DISTINCT FROM OLD.version
OR NEW.original_id IS DISTINCT FROM OLD.original_id
OR (NOT v_allow_relink
AND (NEW.journal_entry_id IS DISTINCT FROM OLD.journal_entry_id
OR NEW.journal_entry_line_id IS DISTINCT FROM OLD.journal_entry_line_id))
THEN
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, description)
VALUES (OLD.user_id, OLD.company_id, 'SECURITY_EVENT', 'document_attachments', OLD.id,
'Blocked metadata or link modification of document linked to ' || v_entry_status || ' entry ' || OLD.journal_entry_id);
RAISE EXCEPTION 'Cannot modify metadata or journal entry link of document linked to a % journal entry (BFL 7 kap)', v_entry_status;
END IF;
-- is_current_version and superseded_by_id may only be changed under the
-- supersede GUC. Without it, those flips are also blocked.
IF NOT v_allow_supersede
AND (NEW.is_current_version IS DISTINCT FROM OLD.is_current_version
OR NEW.superseded_by_id IS DISTINCT FROM OLD.superseded_by_id)
THEN
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, description)
VALUES (OLD.user_id, OLD.company_id, 'SECURITY_EVENT', 'document_attachments', OLD.id,
'Blocked is_current_version/superseded_by_id flip without supersede GUC on document linked to ' || v_entry_status || ' entry ' || OLD.journal_entry_id);
RAISE EXCEPTION 'Cannot modify is_current_version of document linked to a % journal entry without supersede GUC (BFL 7 kap)', v_entry_status;
END IF;
RETURN NEW;
END;
$function$;
-- ── 3. The validated relink RPC ────────────────────────────────────────────
CREATE OR REPLACE FUNCTION public.relink_documents_to_correction(
p_user_id uuid,
p_from_entry_id uuid,
p_to_entry_id uuid
)
RETURNS integer
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
v_caller uuid := auth.uid();
v_role text := auth.role();
v_from journal_entries%ROWTYPE;
v_to journal_entries%ROWTYPE;
v_is_member boolean;
v_moved integer;
BEGIN
-- Caller identity. Two legitimate caller shapes:
-- - authenticated user session: auth.uid() present and MUST match
-- p_user_id (the route layer passes the user's own id; a mismatch is
-- always malicious).
-- - service-role (pending-operations executor / MCP approve flow):
-- auth.uid() is NULL, auth.role() = 'service_role'; p_user_id is
-- trusted and still membership-checked below. See
-- undo_sie_import's auth.uid() regression for why service-role
-- callers must not be keyed on auth.uid().
IF v_role = 'service_role' THEN
IF p_user_id IS NULL THEN
RAISE EXCEPTION 'p_user_id is required';
END IF;
ELSIF v_caller IS NOT NULL THEN
IF p_user_id IS DISTINCT FROM v_caller THEN
RAISE EXCEPTION 'p_user_id does not match authenticated user';
END IF;
ELSE
RAISE EXCEPTION 'Authentication required to relink documents';
END IF;
SELECT * INTO v_from FROM public.journal_entries WHERE id = p_from_entry_id;
IF v_from.id IS NULL THEN
RAISE EXCEPTION 'Source entry % not found', p_from_entry_id;
END IF;
SELECT * INTO v_to FROM public.journal_entries WHERE id = p_to_entry_id;
IF v_to.id IS NULL THEN
RAISE EXCEPTION 'Target entry % not found', p_to_entry_id;
END IF;
-- Tenant boundary: both entries in one company, and the acting user must
-- be a member. SECURITY DEFINER bypasses RLS, so enforce it here.
IF v_from.company_id IS DISTINCT FROM v_to.company_id THEN
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, description)
VALUES (p_user_id, v_from.company_id, 'SECURITY_EVENT', 'document_attachments', p_from_entry_id,
'Blocked cross-company document relink attempt to entry ' || p_to_entry_id);
RAISE EXCEPTION 'Entries belong to different companies';
END IF;
SELECT EXISTS (
SELECT 1 FROM public.company_members cm
WHERE cm.company_id = v_from.company_id AND cm.user_id = p_user_id
) INTO v_is_member;
IF NOT v_is_member THEN
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, description)
VALUES (p_user_id, v_from.company_id, 'SECURITY_EVENT', 'document_attachments', p_from_entry_id,
'Blocked document relink by non-member');
RAISE EXCEPTION 'User is not a member of the entries'' company';
END IF;
-- The move is only legal along a genuine correction chain: the target is
-- the posted correction of the reversed source. Anything else is an
-- arbitrary re-link, which BFL 5 kap 6 § forbids.
IF v_from.status <> 'reversed' THEN
RAISE EXCEPTION 'Source entry % is not reversed (status: %)', p_from_entry_id, v_from.status;
END IF;
IF v_to.status <> 'posted' THEN
RAISE EXCEPTION 'Target entry % is not posted (status: %)', p_to_entry_id, v_to.status;
END IF;
IF v_to.correction_of_id IS DISTINCT FROM p_from_entry_id THEN
RAISE EXCEPTION 'Target entry % is not the correction of source entry %', p_to_entry_id, p_from_entry_id;
END IF;
-- Transaction-local: resets automatically at COMMIT/ROLLBACK.
PERFORM set_config('gnubok.allow_correction_relink', 'true', true);
UPDATE public.document_attachments
SET journal_entry_id = p_to_entry_id,
journal_entry_line_id = NULL
WHERE company_id = v_from.company_id
AND journal_entry_id = p_from_entry_id;
GET DIAGNOSTICS v_moved = ROW_COUNT;
IF v_moved > 0 THEN
-- The row chain (correction_of_id) carries the legal traceability; this
-- audit row makes the underlag move visible without joining timelines.
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, actor_id, description)
VALUES (p_user_id, v_from.company_id, 'UPDATE', 'document_attachments', p_from_entry_id, p_user_id,
'Relinked ' || v_moved || ' document(s) from reversed entry ' || p_from_entry_id || ' to correction ' || p_to_entry_id);
END IF;
RETURN v_moved;
END;
$function$;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,38 @@
-- RPC: get_account_usage_counts — per-account posting counts for the
-- kontoplan cleanup flow ("Rensa oanvända konton").
--
-- PostgREST cannot GROUP BY through supabase-js, and paging every
-- journal_entry_line through fetchAllRows to count in JS does not scale for
-- companies with years of history. One SQL aggregate answers "which accounts
-- have ever been posted to, and how many times" in a single round trip.
--
-- Usage covers ALL journal entries regardless of status: a draft line still
-- references the account, so it must count as "used" for deletion purposes.
-- Opening balances need no special case — IB is booked as a verifikat
-- (source_type 'opening_balance'), so its lines are counted here too.
--
-- SECURITY INVOKER: journal_entries/journal_entry_lines RLS is company-scoped
-- via user_company_ids() (20260330130000), so the caller's own membership
-- bounds what is counted; a non-member calling with a foreign company id gets
-- zero rows, not an error.
--
-- pg-test: tests/pg/account-usage-counts-rpc.pg.test.ts
CREATE OR REPLACE FUNCTION public.get_account_usage_counts(p_company_id uuid)
RETURNS TABLE (account_number text, usage_count bigint)
LANGUAGE sql
STABLE
SECURITY INVOKER
SET search_path TO 'public'
AS $$
SELECT l.account_number, count(*)::bigint AS usage_count
FROM public.journal_entry_lines l
JOIN public.journal_entries je ON je.id = l.journal_entry_id
WHERE je.company_id = p_company_id
GROUP BY l.account_number;
$$;
REVOKE ALL ON FUNCTION public.get_account_usage_counts(uuid) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.get_account_usage_counts(uuid) TO authenticated, service_role;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,191 @@
-- Fix service-role detection in relink_documents_to_correction().
--
-- The original (20260704103000) keyed the service-role branch on auth.role().
-- In the supabase/postgres image auth.role() reads the SINGULAR
-- request.jwt.claim.role GUC, which PostgREST v10+ (and the pg-real harness)
-- no longer populate: only the request.jwt.claims JSON object carries the
-- role. So a genuine service-role caller (pending-operations executor / MCP
-- approve flow) whose claims are {"role":"service_role"} with no sub landed in
-- the ELSE branch and got "Authentication required to relink documents",
-- stranding underlag on the reversed original exactly as before the fix.
--
-- Align with the canonical tenant-guard convention
-- (20260615120000_link_voucher_rpcs_tenant_guard.sql): read the role straight
-- from the request.jwt.claims JSON. anon/authenticated sessions stay keyed on
-- auth.uid() (p_user_id must match the JWT subject, no spoofing); service_role
-- and direct/no-claims callers (MCP / API-key / migrations / pg-harness) trust
-- p_user_id, which is still membership-checked below.
--
-- Also fixes a durability regression in 20260704103000: that migration guarded
-- journal_entry_id at the entry-level trigger but delegated journal_entry_line_id
-- to the metadata trigger, which exempts draft-linked documents. That let a set
-- journal_entry_line_id be cleared to NULL on a draft-linked doc, breaking the
-- "link durable from first set" invariant (document-immutability.pg). Restore
-- line-id durability in the entry-level trigger (status-independent), exempting
-- only the correction-relink path, which legitimately clears line_id when it
-- moves the underlag from the reversed original to its posted correction.
-- Entry-level link trigger: journal_entry_id AND journal_entry_line_id are both
-- durable once set. uuid -> uuid moves and the line-id clear happen only under
-- the correction-relink GUC.
CREATE OR REPLACE FUNCTION public.enforce_document_journal_entry_immutability()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
RETURN NEW;
END IF;
-- Correction relink: set ONLY by relink_documents_to_correction() after it
-- has validated the correction chain. It moves journal_entry_id uuid -> uuid
-- and clears journal_entry_line_id to NULL. Both are allowed only here, and
-- only as long as journal_entry_id is not itself cleared (a NULL there would
-- be a soft-delete bypass of BFL 7 kap 2 §).
IF current_setting('gnubok.allow_correction_relink', true) = 'true'
AND NEW.journal_entry_id IS NOT NULL THEN
RETURN NEW;
END IF;
-- journal_entry_id: once set, cannot be cleared or re-pointed.
IF OLD.journal_entry_id IS NOT NULL
AND NEW.journal_entry_id IS DISTINCT FROM OLD.journal_entry_id THEN
RAISE EXCEPTION
'BFL_DOCUMENT_IMMUTABILITY: cannot clear or change journal_entry_id on document % once set (BFL 5 kap 6 §). Reverse the journal entry first.',
OLD.id;
END IF;
-- journal_entry_line_id: same durability. Setting it from NULL -> uuid (a
-- later, more precise link) stays allowed; clearing or re-pointing a set
-- value is blocked, status-independent.
IF OLD.journal_entry_line_id IS NOT NULL
AND NEW.journal_entry_line_id IS DISTINCT FROM OLD.journal_entry_line_id THEN
RAISE EXCEPTION
'BFL_DOCUMENT_IMMUTABILITY: cannot clear or change journal_entry_line_id on document % once set (BFL 5 kap 6 §).',
OLD.id;
END IF;
RETURN NEW;
END;
$$;
-- The trigger fired only on `UPDATE OF journal_entry_id`, so a line-id-only
-- UPDATE (SET journal_entry_line_id = NULL) never invoked the function at all,
-- which is why the durability guard above needs a wider column list to bite.
DROP TRIGGER IF EXISTS enforce_document_journal_entry_immutability
ON public.document_attachments;
CREATE TRIGGER enforce_document_journal_entry_immutability
BEFORE UPDATE OF journal_entry_id, journal_entry_line_id
ON public.document_attachments
FOR EACH ROW
EXECUTE FUNCTION public.enforce_document_journal_entry_immutability();
CREATE OR REPLACE FUNCTION public.relink_documents_to_correction(
p_user_id uuid,
p_from_entry_id uuid,
p_to_entry_id uuid
)
RETURNS integer
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
v_caller uuid := auth.uid();
v_jwt_role text := coalesce(
nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role',
''
);
v_from journal_entries%ROWTYPE;
v_to journal_entries%ROWTYPE;
v_is_member boolean;
v_moved integer;
BEGIN
-- Caller identity. Two legitimate caller shapes:
-- - authenticated user session (role anon/authenticated): auth.uid() is
-- present and MUST match p_user_id (the route layer passes the user's
-- own id; a mismatch is always malicious).
-- - service-role / direct (pending-operations executor / MCP approve flow
-- / migrations / pg-harness): no user JWT subject; p_user_id is trusted
-- and still membership-checked below. See undo_sie_import's auth.uid()
-- regression for why service-role callers must not be keyed on
-- auth.uid().
IF v_jwt_role IN ('anon', 'authenticated') THEN
IF v_caller IS NULL THEN
RAISE EXCEPTION 'Authentication required to relink documents';
END IF;
IF p_user_id IS DISTINCT FROM v_caller THEN
RAISE EXCEPTION 'p_user_id does not match authenticated user';
END IF;
ELSE
IF p_user_id IS NULL THEN
RAISE EXCEPTION 'p_user_id is required';
END IF;
END IF;
SELECT * INTO v_from FROM public.journal_entries WHERE id = p_from_entry_id;
IF v_from.id IS NULL THEN
RAISE EXCEPTION 'Source entry % not found', p_from_entry_id;
END IF;
SELECT * INTO v_to FROM public.journal_entries WHERE id = p_to_entry_id;
IF v_to.id IS NULL THEN
RAISE EXCEPTION 'Target entry % not found', p_to_entry_id;
END IF;
-- Tenant boundary: both entries in one company, and the acting user must
-- be a member. SECURITY DEFINER bypasses RLS, so enforce it here.
IF v_from.company_id IS DISTINCT FROM v_to.company_id THEN
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, description)
VALUES (p_user_id, v_from.company_id, 'SECURITY_EVENT', 'document_attachments', p_from_entry_id,
'Blocked cross-company document relink attempt to entry ' || p_to_entry_id);
RAISE EXCEPTION 'Entries belong to different companies';
END IF;
SELECT EXISTS (
SELECT 1 FROM public.company_members cm
WHERE cm.company_id = v_from.company_id AND cm.user_id = p_user_id
) INTO v_is_member;
IF NOT v_is_member THEN
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, description)
VALUES (p_user_id, v_from.company_id, 'SECURITY_EVENT', 'document_attachments', p_from_entry_id,
'Blocked document relink by non-member');
RAISE EXCEPTION 'User is not a member of the entries'' company';
END IF;
-- The move is only legal along a genuine correction chain: the target is
-- the posted correction of the reversed source. Anything else is an
-- arbitrary re-link, which BFL 5 kap 6 § forbids.
IF v_from.status <> 'reversed' THEN
RAISE EXCEPTION 'Source entry % is not reversed (status: %)', p_from_entry_id, v_from.status;
END IF;
IF v_to.status <> 'posted' THEN
RAISE EXCEPTION 'Target entry % is not posted (status: %)', p_to_entry_id, v_to.status;
END IF;
IF v_to.correction_of_id IS DISTINCT FROM p_from_entry_id THEN
RAISE EXCEPTION 'Target entry % is not the correction of source entry %', p_to_entry_id, p_from_entry_id;
END IF;
-- Transaction-local: resets automatically at COMMIT/ROLLBACK.
PERFORM set_config('gnubok.allow_correction_relink', 'true', true);
UPDATE public.document_attachments
SET journal_entry_id = p_to_entry_id,
journal_entry_line_id = NULL
WHERE company_id = v_from.company_id
AND journal_entry_id = p_from_entry_id;
GET DIAGNOSTICS v_moved = ROW_COUNT;
IF v_moved > 0 THEN
-- The row chain (correction_of_id) carries the legal traceability; this
-- audit row makes the underlag move visible without joining timelines.
INSERT INTO public.audit_log (user_id, company_id, action, table_name, record_id, actor_id, description)
VALUES (p_user_id, v_from.company_id, 'UPDATE', 'document_attachments', p_from_entry_id, p_user_id,
'Relinked ' || v_moved || ' document(s) from reversed entry ' || p_from_entry_id || ' to correction ' || p_to_entry_id);
END IF;
RETURN v_moved;
END;
$function$;
NOTIFY pgrst, 'reload schema';