feat: delete last voucher, notes field, schema cache fix (#230)

* feat: delete last voucher, notes field, schema cache fix

Address three customer feedback items from William (wigu.se):

1. Delete last voucher per series (Fortnox model):
   - New `delete_last_voucher` RPC with full safety checks (last-in-series,
     open period, no references, owner/admin only)
   - Session variable bypass for immutability/retention/line triggers
   - Full JSONB audit trail (BFNAR 2013:2 behandlingshistorik)
   - DELETE endpoint + UI with confirmation dialogs
   - Storno restoration when deleting a reversal entry

2. Notes/comment field on vouchers:
   - `notes` column on journal_entries (always-editable internal metadata)
   - Immutability trigger updated to allow notes-only updates on posted entries
   - PATCH endpoint, inline-edit UI on detail page, form textarea

3. Schema cache fix:
   - NOTIFY pgrst applied to production (immediate fix)
   - Retroactive migration + CLAUDE.md migration rule added

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

* fix: address Greptile review — tighten trigger, lock voucher sequence

P1: The notes-only exception in enforce_journal_entry_immutability was
too broad — it only checked 7 verifikation fields, allowing silent
mutation of correction_of_id, reverses_id, reversed_by_id, committed_at,
and user_id on posted entries. Now guards all metadata fields; only
notes and updated_at may differ.

P2: Lock voucher_sequences row FOR UPDATE before the MAX(voucher_number)
check in delete_last_voucher to serialise against concurrent
commit_journal_entry calls, preventing voucher number gaps.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-04-13 16:12:03 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent ade4ad5971
commit 7bf7565852
21 changed files with 713 additions and 28 deletions
@@ -0,0 +1,4 @@
-- Retroactive schema cache reload after recent ALTER TABLE migrations
-- (trade_name, delivery_date, pays_salaries, etc.) that did not include
-- NOTIFY pgrst. Ensures PostgREST picks up all new columns immediately.
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,73 @@
-- Add optional notes/comment field to journal entries.
-- Notes are internal metadata (not part of BFL verifikation content)
-- and remain editable even after posting, following the Fortnox model.
ALTER TABLE public.journal_entries ADD COLUMN notes text;
-- Update the immutability trigger to allow notes-only updates on posted entries.
-- BFL 5 kap 7§ defines verifikation content (date, description, amount, counterparty,
-- number, underlag refs). Notes are NOT in that list — they are internal metadata.
CREATE OR REPLACE FUNCTION public.enforce_journal_entry_immutability()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
-- Session variable bypass for controlled operations (e.g. delete_last_voucher RPC)
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN
-- No exemption for drafts: varaktighet applies from insertion.
-- Application code uses status='cancelled' instead of DELETE.
RAISE EXCEPTION 'Cannot delete journal entries (id: %, status: %). Use cancelled status instead.',
OLD.id, OLD.status;
END IF;
-- Draft can transition to draft (update fields), posted, or cancelled
IF OLD.status = 'draft' AND NEW.status IN ('draft', 'posted', 'cancelled') THEN
RETURN NEW;
END IF;
-- Posted entries: allow notes-only updates (internal metadata, not verifikation content)
-- BFL 5 kap 7§ mandates immutability for verifikation fields (description, date, amounts,
-- voucher number, etc.). Notes/comments are outside this scope per Fortnox precedent.
IF OLD.status = 'posted' AND NEW.status = 'posted' THEN
IF NEW.description = OLD.description
AND NEW.entry_date = OLD.entry_date
AND NEW.fiscal_period_id = OLD.fiscal_period_id
AND NEW.voucher_number = OLD.voucher_number
AND NEW.voucher_series = OLD.voucher_series
AND NEW.source_type = OLD.source_type
AND COALESCE(NEW.source_id::text, '') = COALESCE(OLD.source_id::text, '')
AND NEW.user_id = OLD.user_id
AND COALESCE(NEW.reversed_by_id::text, '') = COALESCE(OLD.reversed_by_id::text, '')
AND COALESCE(NEW.reverses_id::text, '') = COALESCE(OLD.reverses_id::text, '')
AND COALESCE(NEW.correction_of_id::text, '') = COALESCE(OLD.correction_of_id::text, '')
AND NEW.committed_at IS NOT DISTINCT FROM OLD.committed_at
THEN
RETURN NEW; -- Only notes and updated_at may differ
END IF;
END IF;
-- Posted can transition to reversed (storno) or cancelled (orphaned cleanup)
IF OLD.status = 'posted' AND NEW.status IN ('reversed', 'cancelled') THEN
IF NEW.status = 'reversed' THEN
IF NEW.description != OLD.description OR NEW.entry_date != OLD.entry_date
OR NEW.fiscal_period_id != OLD.fiscal_period_id
OR NEW.voucher_number != OLD.voucher_number THEN
RAISE EXCEPTION 'Cannot modify fields of a posted entry during reversal (id: %)', OLD.id;
END IF;
END IF;
RETURN NEW;
END IF;
-- Reversed entries can transition back to posted (when their storno is deleted)
IF OLD.status = 'reversed' AND NEW.status = 'posted'
AND current_setting('gnubok.allow_delete', true) = 'true' THEN
RETURN NEW;
END IF;
RAISE EXCEPTION 'Cannot modify a % journal entry (id: %). Committed entries are immutable per Bokforingslagen.',
OLD.status, OLD.id;
END; $$;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,223 @@
-- Delete last voucher per series (Fortnox model).
-- Allows deleting the highest-numbered posted voucher in a series,
-- maintaining an unbroken voucher number sequence per BFL 5 kap 7§.
--
-- Safeguards:
-- 1. Only the LAST voucher in its (company, fiscal_period, series) can be deleted
-- 2. Fiscal period must not be closed or locked
-- 3. No other entries may reference it (reverses_id, correction_of_id)
-- 4. Calling user must be company owner or admin
-- 5. Full audit trail via write_audit_log() trigger (BFNAR 2013:2 behandlingshistorik)
-- 1. Update line immutability trigger to respect session variable bypass
CREATE OR REPLACE FUNCTION public.enforce_journal_entry_line_immutability()
RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE v_status text;
BEGIN
-- Session variable bypass for controlled operations (delete_last_voucher RPC)
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END IF;
SELECT status INTO v_status FROM public.journal_entries
WHERE id = COALESCE(OLD.journal_entry_id, NEW.journal_entry_id);
-- Draft entries: all operations allowed
IF v_status = 'draft' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END IF;
-- Cancelled entries: only DELETE for cleanup
IF v_status = 'cancelled' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RAISE EXCEPTION 'Cannot % lines of a cancelled journal entry.', TG_OP;
END IF;
RAISE EXCEPTION 'Cannot % lines of a % journal entry.', TG_OP, v_status;
END; $$;
-- 2. Update retention trigger to respect session variable bypass
CREATE OR REPLACE FUNCTION public.enforce_retention_journal_entries()
RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER AS $$
DECLARE
v_retention_expires date;
BEGIN
-- Session variable bypass for controlled operations (delete_last_voucher RPC)
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
RETURN OLD;
END IF;
SELECT fp.retention_expires_at INTO v_retention_expires
FROM public.fiscal_periods fp
WHERE fp.id = OLD.fiscal_period_id;
IF v_retention_expires IS NOT NULL AND v_retention_expires > CURRENT_DATE THEN
INSERT INTO public.audit_log (user_id, action, table_name, record_id, description)
VALUES (OLD.user_id, 'RETENTION_BLOCK', 'journal_entries', OLD.id,
'Attempted deletion within retention period (expires ' || v_retention_expires || ')');
RAISE EXCEPTION 'Cannot delete journal entry within 7-year retention period (expires %)',
v_retention_expires;
END IF;
RETURN OLD;
END; $$;
-- 3. Create the delete_last_voucher RPC
CREATE OR REPLACE FUNCTION public.delete_last_voucher(
p_company_id uuid,
p_entry_id uuid
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_entry record;
v_period record;
v_max_voucher integer;
v_ref_count integer;
v_caller_role text;
v_snapshot jsonb;
v_lines_snapshot jsonb;
BEGIN
-- 1. Verify calling user is company owner or admin
SELECT cm.role INTO v_caller_role
FROM company_members cm
WHERE cm.company_id = p_company_id
AND cm.user_id = auth.uid();
IF v_caller_role IS NULL OR v_caller_role NOT IN ('owner', 'admin') THEN
RAISE EXCEPTION 'Only company owners and admins can delete vouchers';
END IF;
-- 2. Lock and fetch the target entry
SELECT * INTO v_entry
FROM journal_entries
WHERE id = p_entry_id
AND company_id = p_company_id
FOR UPDATE;
IF v_entry IS NULL THEN
RAISE EXCEPTION 'Journal entry not found';
END IF;
IF v_entry.status != 'posted' THEN
RAISE EXCEPTION 'Only posted entries can be deleted (current status: %)', v_entry.status;
END IF;
-- 3. Verify fiscal period is open
SELECT * INTO v_period
FROM fiscal_periods
WHERE id = v_entry.fiscal_period_id
FOR UPDATE;
IF v_period.is_closed THEN
RAISE EXCEPTION 'Cannot delete voucher in a closed fiscal period';
END IF;
IF v_period.locked_at IS NOT NULL THEN
RAISE EXCEPTION 'Cannot delete voucher in a locked fiscal period';
END IF;
-- 4. Lock voucher_sequences row to serialise against concurrent commit_journal_entry.
-- Without this, a concurrent commit could assign a new voucher number between
-- our MAX check and the DELETE, producing a gap (violating BFL 5 kap 7§).
PERFORM 1 FROM voucher_sequences
WHERE company_id = p_company_id
AND fiscal_period_id = v_entry.fiscal_period_id
AND voucher_series = v_entry.voucher_series
FOR UPDATE;
-- Verify it is the LAST voucher in its series
SELECT MAX(voucher_number) INTO v_max_voucher
FROM journal_entries
WHERE company_id = p_company_id
AND fiscal_period_id = v_entry.fiscal_period_id
AND voucher_series = v_entry.voucher_series
AND status NOT IN ('cancelled', 'draft');
IF v_entry.voucher_number != v_max_voucher THEN
RAISE EXCEPTION 'Kan bara radera det sista verifikatet i serien. % har nummer % men senaste är %',
v_entry.voucher_series, v_entry.voucher_number, v_max_voucher;
END IF;
-- 5. Verify no other entries reference this one
SELECT COUNT(*) INTO v_ref_count
FROM journal_entries
WHERE company_id = p_company_id
AND status != 'cancelled'
AND (reverses_id = p_entry_id OR correction_of_id = p_entry_id);
IF v_ref_count > 0 THEN
RAISE EXCEPTION 'Cannot delete: other entries reference this voucher (% references)',
v_ref_count;
END IF;
-- 6. Capture snapshot for audit trail (BFNAR 2013:2 behandlingshistorik)
-- The write_audit_log() AFTER trigger also captures old_state, but we
-- include lines here for complete traceability.
SELECT jsonb_agg(to_jsonb(l)) INTO v_lines_snapshot
FROM journal_entry_lines l
WHERE l.journal_entry_id = p_entry_id;
v_snapshot := to_jsonb(v_entry) || jsonb_build_object('lines', COALESCE(v_lines_snapshot, '[]'::jsonb));
-- 7. If this entry is a storno (reverses another entry), restore the original
IF v_entry.reverses_id IS NOT NULL THEN
-- Use session variable to allow reversed → posted transition
PERFORM set_config('gnubok.allow_delete', 'true', true);
UPDATE journal_entries
SET status = 'posted', reversed_by_id = NULL
WHERE id = v_entry.reverses_id
AND company_id = p_company_id;
END IF;
-- 8. Enable session variable bypass for deletion triggers
PERFORM set_config('gnubok.allow_delete', 'true', true);
-- 9. Unlink document attachments (FK is RESTRICT, must clear before delete)
UPDATE document_attachments
SET journal_entry_id = NULL
WHERE journal_entry_id = p_entry_id;
-- 10. Delete the journal entry
-- journal_entry_lines: ON DELETE CASCADE (auto-deleted)
-- transactions: ON DELETE SET NULL (auto-nullified)
-- supplier_invoices: ON DELETE SET NULL (auto-nullified)
-- supplier_invoice_payments: ON DELETE SET NULL (auto-nullified)
-- invoice_payments: ON DELETE SET NULL (auto-nullified)
DELETE FROM journal_entries WHERE id = p_entry_id;
-- 11. Decrement voucher sequence
UPDATE voucher_sequences
SET last_number = GREATEST(last_number - 1, 0)
WHERE company_id = p_company_id
AND fiscal_period_id = v_entry.fiscal_period_id
AND voucher_series = v_entry.voucher_series;
-- 12. Insert explicit audit entry with full snapshot including lines
INSERT INTO audit_log (user_id, action, table_name, record_id, actor_id, old_state, description)
VALUES (
v_entry.user_id,
'DELETE',
'journal_entries',
p_entry_id,
auth.uid(),
v_snapshot,
'Deleted voucher ' || v_entry.voucher_series || v_entry.voucher_number ||
' (delete_last_voucher RPC, caller: ' || auth.uid() || ')'
);
RETURN jsonb_build_object(
'deleted', true,
'voucher_series', v_entry.voucher_series,
'voucher_number', v_entry.voucher_number
);
END;
$$;
NOTIFY pgrst, 'reload schema';