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

feat(lifecycle): establish draft-first temp-permanent numbering and immutable ATEF audit

davoodmehraban89 committed Nov 18, 2026 at 09:01 UTC a9c2d746acbbb22365e1a2b711eaaa9a55de0d67
1 file changed +334
supabase/migrations/20261118100000_document_lifecycle_temp_permanent_atef.sql new
+334
@@ -0,0 +1,334 @@
1 +-- Document lifecycle v1
2 +-- Contract:
3 +-- 1) Every financial document starts as draft/temporary.
4 +-- 2) ATEF is immutable and never reused, including after deletion.
5 +-- 3) Temporary number may become the permanent number at posting; permanent numbers
6 +-- are allocated server-side and never assigned twice.
7 +-- 4) Draft source + draft accounting voucher are deleted atomically through the
8 +-- source document. Direct deletion of a linked voucher is blocked.
9 +-- 5) Posted documents are not physically deleted; they are reversed/cancelled.
10 +-- 6) Existing financial documents are migrated to draft while preserving their
11 +-- previous state/number in audit metadata.
12 +
13 +CREATE TABLE IF NOT EXISTS public.finora_document_number_sequence (
14 + organization_id uuid PRIMARY KEY,
15 + next_atef bigint NOT NULL DEFAULT 1,
16 + updated_at timestamptz NOT NULL DEFAULT clock_timestamp()
17 +);
18 +
19 +CREATE TABLE IF NOT EXISTS public.finora_document_lifecycle_audit (
20 + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
21 + organization_id uuid NOT NULL,
22 + atef_number bigint NOT NULL,
23 + document_collection text NOT NULL,
24 + document_id text NOT NULL,
25 + event_type text NOT NULL,
26 + temporary_number text,
27 + permanent_number text,
28 + related_collection text,
29 + related_id text,
30 + actor_id uuid,
31 + original_status text,
32 + metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
33 + created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
34 + UNIQUE (organization_id, atef_number, event_type, document_collection, document_id)
35 +);
36 +
37 +CREATE INDEX IF NOT EXISTS finora_document_lifecycle_audit_doc_idx
38 + ON public.finora_document_lifecycle_audit(organization_id, document_collection, document_id, created_at DESC);
39 +
40 +CREATE INDEX IF NOT EXISTS finora_document_lifecycle_audit_atef_idx
41 + ON public.finora_document_lifecycle_audit(organization_id, atef_number);
42 +
43 +CREATE OR REPLACE FUNCTION public.finora_next_atef(p_organization_id uuid)
44 +RETURNS bigint
45 +LANGUAGE plpgsql
46 +SECURITY DEFINER
47 +SET search_path=''
48 +AS $$
49 +DECLARE n bigint;
50 +BEGIN
51 + IF p_organization_id IS NULL THEN
52 + RAISE EXCEPTION 'FINORA_ORGANIZATION_REQUIRED' USING ERRCODE='23514';
53 + END IF;
54 + PERFORM pg_advisory_xact_lock(hashtextextended('finora-atef:'||p_organization_id::text, 0));
55 + INSERT INTO public.finora_document_number_sequence(organization_id,next_atef)
56 + VALUES(p_organization_id,2)
57 + ON CONFLICT(organization_id) DO UPDATE
58 + SET next_atef=public.finora_document_number_sequence.next_atef+1,
59 + updated_at=clock_timestamp()
60 + RETURNING next_atef-1 INTO n;
61 + RETURN n;
62 +END $$;
63 +
64 +CREATE OR REPLACE FUNCTION public.finora_next_permanent_number(
65 + p_organization_id uuid,
66 + p_company_id text,
67 + p_fiscal_year_id text,
68 + p_document_type text
69 +)
70 +RETURNS bigint
71 +LANGUAGE plpgsql
72 +SECURITY DEFINER
73 +SET search_path=''
74 +AS $$
75 +DECLARE n bigint;
76 +BEGIN
77 + IF p_organization_id IS NULL OR coalesce(p_company_id,'')='' OR coalesce(p_fiscal_year_id,'')='' THEN
78 + RAISE EXCEPTION 'FINORA_NUMBERING_CONTEXT_REQUIRED' USING ERRCODE='23514';
79 + END IF;
80 + PERFORM pg_advisory_xact_lock(hashtextextended(
81 + 'finora-permanent-number:'||p_organization_id::text||':'||
82 + p_company_id||':'||p_fiscal_year_id||':'||coalesce(p_document_type,'journal'),0));
83 + SELECT coalesce(max(NULLIF(data->>'number','')::bigint),0)+1
84 + INTO n
85 + FROM public.records
86 + WHERE organization_id=p_organization_id
87 + AND collection IN ('journalVouchers','invoices','purchases','payments','expenses','cheques','contractStatements',
88 + 'payrollRuns','employeeBenefitAccruals','pettyCashTransactions')
89 + AND coalesce(data->>'companyId','')=p_company_id
90 + AND coalesce(data->>'fiscalYearId','')=p_fiscal_year_id
91 + AND coalesce(data->>'documentType',data->>'sourceType',collection)=coalesce(p_document_type,collection)
92 + AND coalesce(data->>'status',data->>'documentStatus',data->>'accountingStatus','draft')='posted';
93 + RETURN n;
94 +END $$;
95 +
96 +REVOKE ALL ON FUNCTION public.finora_next_atef(uuid) FROM PUBLIC, anon, authenticated;
97 +REVOKE ALL ON FUNCTION public.finora_next_permanent_number(uuid,text,text,text) FROM PUBLIC, anon, authenticated;
98 +
99 +-- Add immutable lifecycle metadata to all existing transactional records.
100 +DO $$
101 +DECLARE r record; v_atef bigint; v_temp text; v_status text;
102 +DECLARE transactional text[] := ARRAY[
103 + 'journalVouchers','invoices','purchases','payments','expenses','cheques',
104 + 'contractStatements','payrollRuns','employeeBenefitAccruals','pettyCashTransactions'
105 +];
106 +BEGIN
107 + FOR r IN
108 + SELECT * FROM public.records
109 + WHERE collection = ANY(transactional)
110 + ORDER BY organization_id, collection, id
111 + LOOP
112 + v_atef := NULLIF(r.data->>'atefNumber','')::bigint;
113 + IF v_atef IS NULL THEN v_atef := public.finora_next_atef(r.organization_id); END IF;
114 + v_temp := nullif(trim(coalesce(r.data->>'temporaryNumber',r.data->>'number','')),'');
115 + IF v_temp IS NULL THEN v_temp := 'TMP-'||v_atef::text; END IF;
116 + v_status := coalesce(r.data->>'status',r.data->>'documentStatus',r.data->>'accountingStatus','draft');
117 +
118 + UPDATE public.records
119 + SET data =
120 + CASE
121 + WHEN collection='journalVouchers' THEN
122 + (data
123 + || jsonb_build_object(
124 + 'atefNumber',v_atef,
125 + 'temporaryNumber',v_temp,
126 + 'lifecycleMigrationOriginalStatus',v_status,
127 + 'lifecycleMigrationOriginalNumber',coalesce(data->>'number',''),
128 + 'status','draft'
129 + )
130 + - 'number' - 'postedAt' - 'postedBy')
131 + ELSE
132 + (data
133 + || jsonb_build_object(
134 + 'atefNumber',v_atef,
135 + 'temporaryNumber',v_temp,
136 + 'lifecycleMigrationOriginalStatus',v_status,
137 + 'lifecycleMigrationOriginalNumber',coalesce(data->>'number',''),
138 + 'documentStatus','draft',
139 + 'accountingStatus',CASE WHEN data ? 'accountingStatus' THEN 'draft' ELSE data->>'accountingStatus' END
140 + )
141 + - 'number' - 'postedAt' - 'postedBy' - 'accountingPostedAt' - 'documentPostedAt' - 'documentPostedBy')
142 + END
143 + WHERE organization_id=r.organization_id AND collection=r.collection AND id=r.id;
144 +
145 + INSERT INTO public.finora_document_lifecycle_audit(
146 + organization_id,atef_number,document_collection,document_id,event_type,
147 + temporary_number,permanent_number,actor_id,original_status,metadata)
148 + VALUES(
149 + r.organization_id,v_atef,r.collection,r.id,'MIGRATED_TO_DRAFT',
150 + v_temp,coalesce(r.data->>'number',''),auth.uid(),v_status,
151 + jsonb_build_object('migration','20261118100000','source_record_version',r.version)
152 + )
153 + ON CONFLICT DO NOTHING;
154 + END LOOP;
155 +END $$;
156 +
157 +-- Reconcile the sequence above any pre-existing ATEF values.
158 +UPDATE public.finora_document_number_sequence s
159 +SET next_atef = greatest(
160 + s.next_atef,
161 + coalesce((SELECT max((data->>'atefNumber')::bigint)+1
162 + FROM public.records
163 + WHERE organization_id=s.organization_id
164 + AND data ? 'atefNumber'),1)
165 +),
166 +updated_at=clock_timestamp();
167 +
168 +-- Server-side creation of a temporary document number. ATEF is allocated once.
169 +CREATE OR REPLACE FUNCTION public.finora_document_identity(
170 + p_organization_id uuid,
171 + p_collection text,
172 + p_id text,
173 + p_temporary_number text DEFAULT NULL
174 +)
175 +RETURNS jsonb
176 +LANGUAGE plpgsql
177 +SECURITY DEFINER
178 +SET search_path=''
179 +AS $$
180 +DECLARE r public.records%rowtype; n bigint; t text;
181 +BEGIN
182 + SELECT * INTO r FROM public.records
183 + WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id
184 + FOR UPDATE;
185 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_DOCUMENT_NOT_FOUND' USING ERRCODE='P0002'; END IF;
186 + n:=NULLIF(r.data->>'atefNumber','')::bigint;
187 + IF n IS NULL THEN n:=public.finora_next_atef(p_organization_id); END IF;
188 + t:=nullif(trim(coalesce(p_temporary_number,r.data->>'temporaryNumber',r.data->>'number','')),'');
189 + IF t IS NULL THEN t:='TMP-'||n::text; END IF;
190 + UPDATE public.records
191 + SET data=(r.data||jsonb_build_object('atefNumber',n,'temporaryNumber',t,'documentStatus','draft')-'number'-'postedAt'-'postedBy')
192 + WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id;
193 + INSERT INTO public.finora_document_lifecycle_audit(
194 + organization_id,atef_number,document_collection,document_id,event_type,temporary_number,actor_id,metadata)
195 + VALUES(p_organization_id,n,p_collection,p_id,'CREATED_DRAFT',t,auth.uid(),jsonb_build_object('temporary',true));
196 + RETURN (SELECT data FROM public.records WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id);
197 +END $$;
198 +
199 +-- Posting assigns the permanent number. It never changes ATEF.
200 +CREATE OR REPLACE FUNCTION public.finora_assign_permanent_document_number(
201 + p_organization_id uuid,
202 + p_collection text,
203 + p_id text,
204 + p_company_id text,
205 + p_fiscal_year_id text,
206 + p_document_type text
207 +)
208 +RETURNS jsonb
209 +LANGUAGE plpgsql
210 +SECURITY DEFINER
211 +SET search_path=''
212 +AS $$
213 +DECLARE r public.records%rowtype; n bigint; status text;
214 +BEGIN
215 + SELECT * INTO r FROM public.records
216 + WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id FOR UPDATE;
217 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_DOCUMENT_NOT_FOUND' USING ERRCODE='P0002'; END IF;
218 + status:=coalesce(r.data->>'status',r.data->>'documentStatus',r.data->>'accountingStatus','draft');
219 + IF status<>'posted' THEN RAISE EXCEPTION 'FINORA_DOCUMENT_NOT_POSTED' USING ERRCODE='23514'; END IF;
220 + n:=public.finora_next_permanent_number(p_organization_id,p_company_id,p_fiscal_year_id,p_document_type);
221 + UPDATE public.records
222 + SET data=(r.data||jsonb_build_object('number',n::text,'documentStatus','posted','accountingStatus',
223 + CASE WHEN r.data ? 'accountingStatus' THEN 'posted' ELSE r.data->>'accountingStatus' END))
224 + WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id;
225 + INSERT INTO public.finora_document_lifecycle_audit(
226 + organization_id,atef_number,document_collection,document_id,event_type,
227 + temporary_number,permanent_number,actor_id,metadata)
228 + VALUES(p_organization_id,(r.data->>'atefNumber')::bigint,p_collection,p_id,'POSTED',
229 + r.data->>'temporaryNumber',n::text,auth.uid(),jsonb_build_object('document_type',p_document_type));
230 + RETURN (SELECT data FROM public.records WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id);
231 +END $$;
232 +
233 +REVOKE ALL ON FUNCTION public.finora_document_identity(uuid,text,text,text) FROM PUBLIC, anon, authenticated;
234 +REVOKE ALL ON FUNCTION public.finora_assign_permanent_document_number(uuid,text,text,text,text,text) FROM PUBLIC, anon, authenticated;
235 +
236 +-- Draft source deletion: source is the user-facing root. If it owns a draft
237 +-- journal voucher, the voucher + lines + dimensions are deleted atomically too.
238 +CREATE OR REPLACE FUNCTION public.finora_delete_draft_source(
239 + p_organization_id uuid,
240 + p_collection text,
241 + p_source_id text
242 +)
243 +RETURNS jsonb
244 +LANGUAGE plpgsql
245 +SECURITY DEFINER
246 +SET search_path=''
247 +AS $$
248 +DECLARE s public.records%rowtype; v public.records%rowtype; a bigint;
249 +BEGIN
250 + SELECT * INTO s FROM public.records
251 + WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_source_id
252 + FOR UPDATE;
253 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_SOURCE_NOT_FOUND' USING ERRCODE='P0002'; END IF;
254 + IF coalesce(s.data->>'documentStatus',s.data->>'accountingStatus',s.data->>'status','draft')<>'draft'
255 + THEN RAISE EXCEPTION 'FINORA_ONLY_DRAFT_CAN_BE_DELETED' USING ERRCODE='23514'; END IF;
256 + a:=NULLIF(s.data->>'atefNumber','')::bigint;
257 +
258 + IF coalesce(s.data->>'journalVoucherId','')<>'' THEN
259 + SELECT * INTO v FROM public.records
260 + WHERE organization_id=p_organization_id AND collection='journalVouchers'
261 + AND id=s.data->>'journalVoucherId' FOR UPDATE;
262 + IF FOUND AND coalesce(v.data->>'status','draft')<>'draft'
263 + THEN RAISE EXCEPTION 'FINORA_LINKED_VOUCHER_NOT_DRAFT' USING ERRCODE='23514'; END IF;
264 +
265 + IF FOUND THEN
266 + INSERT INTO public.finora_document_lifecycle_audit(
267 + organization_id,atef_number,document_collection,document_id,event_type,
268 + temporary_number,permanent_number,related_collection,related_id,actor_id,original_status,metadata)
269 + VALUES(p_organization_id,a,'journalVouchers',v.id,'DELETED_WITH_SOURCE',
270 + v.data->>'temporaryNumber',v.data->>'number',p_collection,p_source_id,auth.uid(),'draft',
271 + jsonb_build_object('source_atef',a));
272 + DELETE FROM public.records WHERE organization_id=p_organization_id
273 + AND collection IN ('journalLineDimensions','journalLines')
274 + AND ((collection='journalLines' AND data->>'voucherId'=v.id)
275 + OR (collection='journalLineDimensions' AND data->>'voucherId'=v.id));
276 + DELETE FROM public.records WHERE organization_id=p_organization_id
277 + AND collection='journalVouchers' AND id=v.id;
278 + END IF;
279 + END IF;
280 +
281 + INSERT INTO public.finora_document_lifecycle_audit(
282 + organization_id,atef_number,document_collection,document_id,event_type,
283 + temporary_number,permanent_number,actor_id,original_status,metadata)
284 + VALUES(p_organization_id,a,p_collection,p_source_id,'DELETED',
285 + s.data->>'temporaryNumber',s.data->>'number',auth.uid(),'draft',
286 + jsonb_build_object('cascade_voucher_id',s.data->>'journalVoucherId'));
287 +
288 + DELETE FROM public.records WHERE organization_id=p_organization_id
289 + AND collection=p_collection AND id=p_source_id;
290 +
291 + RETURN jsonb_build_object('deleted',true,'atefNumber',a,'sourceId',p_source_id);
292 +END $$;
293 +
294 +REVOKE ALL ON FUNCTION public.finora_delete_draft_source(uuid,text,text) FROM PUBLIC, anon, authenticated;
295 +
296 +-- Direct deletion of a linked voucher is deliberately forbidden. User must
297 +-- delete the source document; the source operation then removes both.
298 +CREATE OR REPLACE FUNCTION public.finora_delete_draft_voucher(
299 + p_organization_id uuid,
300 + p_voucher_id text
301 +)
302 +RETURNS jsonb
303 +LANGUAGE plpgsql
304 +SECURITY DEFINER
305 +SET search_path=''
306 +AS $$
307 +DECLARE v public.records%rowtype; src public.records%rowtype;
308 +BEGIN
309 + SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
310 + AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
311 + IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_VOUCHER_NOT_FOUND' USING ERRCODE='P0002'; END IF;
312 + IF coalesce(v.data->>'status','draft')<>'draft' THEN
313 + RAISE EXCEPTION 'FINORA_ONLY_DRAFT_CAN_BE_DELETED' USING ERRCODE='23514';
314 + END IF;
315 + IF coalesce(v.data->>'sourceType','manual') IN ('sale','purchase') AND coalesce(v.data->>'sourceId','')<>'' THEN
316 + RAISE EXCEPTION 'FINORA_DELETE_SOURCE_REQUIRED: ابتدا سند تجاری منبع را حذف کنید' USING ERRCODE='23514';
317 + END IF;
318 + DELETE FROM public.records WHERE organization_id=p_organization_id
319 + AND collection IN ('journalLineDimensions','journalLines')
320 + AND data->>'voucherId'=p_voucher_id;
321 + DELETE FROM public.records WHERE organization_id=p_organization_id
322 + AND collection='journalVouchers' AND id=p_voucher_id;
323 + INSERT INTO public.finora_document_lifecycle_audit(
324 + organization_id,atef_number,document_collection,document_id,event_type,
325 + temporary_number,permanent_number,actor_id,original_status)
326 + VALUES(p_organization_id,NULL,'journalVouchers',p_voucher_id,'DELETED_DRAFT_VOUCHER',
327 + v.data->>'temporaryNumber',v.data->>'number',auth.uid(),'draft');
328 + RETURN jsonb_build_object('deleted',true,'voucherId',p_voucher_id);
329 +END $$;
330 +
331 +REVOKE ALL ON FUNCTION public.finora_delete_draft_voucher(uuid,text) FROM PUBLIC, anon, authenticated;
332 +
333 +-- Public read policy is intentionally absent; audit is accessed only through a
334 +-- future privileged reporting RPC. The table is not exposed to clients.