Files
accounted/supabase/migrations/20260506090000_transactions_document_immutability.sql
T
admin e7f0070e84
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s
fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
2026-11-10 09:37:22 +01:00

51 lines
1.8 KiB
PL/PgSQL

-- BFL 5 kap 6 § / 7 kap 1 §: once a document has propagated to a journal
-- entry (i.e. become räkenskapsinformation underlag), the link from the
-- transaction to that document must not be silently broken. The application-
-- layer guard in /api/transactions/[id]/attach-document gives the user a
-- friendly Swedish error; this trigger is the DB-level safety net that also
-- catches direct SQL writes, races, and the FK SET NULL path.
CREATE OR REPLACE FUNCTION public.enforce_transactions_document_immutability()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
old_doc_je_id uuid;
BEGIN
-- Only act when document_id changes.
IF NEW.document_id IS NOT DISTINCT FROM OLD.document_id THEN
RETURN NEW;
END IF;
-- No previously-attached document, nothing to protect.
IF OLD.document_id IS NULL THEN
RETURN NEW;
END IF;
-- If the previously-attached document is already räkenskapsinformation
-- (linked to a journal entry), block the change. Storno the journal entry
-- first if you genuinely need to swap or detach.
SELECT journal_entry_id
INTO old_doc_je_id
FROM public.document_attachments
WHERE id = OLD.document_id;
IF old_doc_je_id IS NOT NULL THEN
RAISE EXCEPTION
'Cannot detach or swap document % from transaction %: document is linked to journal entry % and is räkenskapsinformation per BFL 5 kap 6 §. Reverse the journal entry first.',
OLD.document_id, OLD.id, old_doc_je_id
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS enforce_transactions_document_immutability ON public.transactions;
CREATE TRIGGER enforce_transactions_document_immutability
BEFORE UPDATE OF document_id ON public.transactions
FOR EACH ROW
EXECUTE FUNCTION public.enforce_transactions_document_immutability();
NOTIFY pgrst, 'reload schema';