@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / c524150
Fork 0

سامانه صدور فاکتور و حسابداری

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 3, 22:00 UTC

Prepare server guard for posted source immutability

davoodmehraban89 committed Sep 29, 2026 at 22:22 UTC c5241502ad2710251ea3f3f8ef6aa77ba6442866
1 file changed +43
supabase/migrations/20260929190000_posted_source_immutability_guard.sql new
+43
@@ -0,0 +1,43 @@
1 +-- PREPARED, NOT YET APPLIED: requires explicit schema-change approval.
2 +-- High-assurance guard for operational source records already tied to posted/reversed accounting history.
3 +
4 +create or replace function public.finora_guard_posted_source_records()
5 +returns trigger
6 +language plpgsql
7 +security invoker
8 +set search_path = public
9 +as $$
10 +declare
11 + vid text := coalesce(old.data->>'journalVoucherId','');
12 + voucher_status text := '';
13 + source_locked boolean := false;
14 +begin
15 + if old.collection not in ('invoices','purchases','payments','expenses','contractStatements') then
16 + return case when tg_op='DELETE' then old else new end;
17 + end if;
18 +
19 + if vid <> '' then
20 + select coalesce(r.data->>'status','') into voucher_status
21 + from public.records r
22 + where r.owner_id=old.owner_id
23 + and r.collection='journalVouchers'
24 + and r.id=vid;
25 + end if;
26 +
27 + source_locked :=
28 + coalesce(old.data->>'accountingStatus','')='posted'
29 + or (old.collection='contractStatements' and coalesce(old.data->>'status','') in ('posted','reversed'))
30 + or voucher_status in ('posted','reversed');
31 +
32 + if not source_locked then
33 + return case when tg_op='DELETE' then old else new end;
34 + end if;
35 +
36 + if tg_op='UPDATE' and new.data=old.data then return new; end if;
37 + raise exception 'source record linked to posted/reversed accounting history is immutable';
38 +end $$;
39 +
40 +drop trigger if exists trg_finora_guard_posted_source_records on public.records;
41 +create trigger trg_finora_guard_posted_source_records
42 +before update or delete on public.records
43 +for each row execute function public.finora_guard_posted_source_records();