سامانه صدور فاکتور و حسابداری
feat(lifecycle): enforce draft-first identity for new transactional records
davoodmehraban89 committed
Nov 18, 2026 at 09:02 UTC
3fa36314e1605c8a8edb6d72911ae9c6777962c4
1 file changed
+48
supabase/migrations/20261118101000_document_identity_trigger.sql
new
+48
@@ -0,0 +1,48 @@
1
+-- Allocate immutable ATEF and a temporary number for every new transactional document.
2
+-- This keeps identity server-owned even when the UI uses generic datastore sync.
3
+CREATE OR REPLACE FUNCTION public.finora_document_identity_trigger()
4
+RETURNS trigger
5
+LANGUAGE plpgsql
6
+SECURITY DEFINER
7
+SET search_path=''
8
+AS $$
9
+DECLARE n bigint; t text; transactional boolean;
10
+BEGIN
11
+ transactional := NEW.collection IN (
12
+ 'journalVouchers','invoices','purchases','payments','expenses','cheques',
13
+ 'contractStatements','payrollRuns','employeeBenefitAccruals','pettyCashTransactions'
14
+ );
15
+ IF NOT transactional THEN RETURN NEW; END IF;
16
+
17
+ n := NULLIF(NEW.data->>'atefNumber','')::bigint;
18
+ IF n IS NULL THEN n:=public.finora_next_atef(NEW.organization_id); END IF;
19
+
20
+ t := nullif(trim(coalesce(NEW.data->>'temporaryNumber',NEW.data->>'number','')),'');
21
+ IF t IS NULL THEN t:='TMP-'||n::text; END IF;
22
+
23
+ NEW.data := NEW.data || jsonb_build_object('atefNumber',n,'temporaryNumber',t);
24
+
25
+ -- A newly created transaction is always draft. Existing posted rows remain
26
+ -- posted when unrelated metadata is updated; only an explicit posting RPC
27
+ -- may move draft -> posted.
28
+ IF TG_OP='INSERT' AND NEW.collection<>'journalLines' AND NEW.collection<>'journalLineDimensions' THEN
29
+ IF NEW.collection='journalVouchers' THEN
30
+ NEW.data := NEW.data - 'number' - 'postedAt' - 'postedBy' || jsonb_build_object('status','draft');
31
+ ELSE
32
+ NEW.data := NEW.data - 'number' - 'postedAt' - 'postedBy' - 'accountingPostedAt' - 'documentPostedAt' - 'documentPostedBy'
33
+ || jsonb_build_object('documentStatus','draft');
34
+ IF NEW.data ? 'accountingStatus' THEN
35
+ NEW.data := NEW.data || jsonb_build_object('accountingStatus','draft');
36
+ END IF;
37
+ END IF;
38
+ END IF;
39
+ RETURN NEW;
40
+END $$;
41
+
42
+DROP TRIGGER IF EXISTS finora_document_identity_trigger ON public.records;
43
+CREATE TRIGGER finora_document_identity_trigger
44
+BEFORE INSERT ON public.records
45
+FOR EACH ROW
46
+EXECUTE FUNCTION public.finora_document_identity_trigger();
47
+
48
+REVOKE ALL ON FUNCTION public.finora_document_identity_trigger() FROM PUBLIC, anon, authenticated;