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

feat/document-lifecycle-temp-permanent-atef
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
sql 339 lines 15.3 KB
Raw
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') IN ('posted','reversed');
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 OR EXISTS (
114 SELECT 1 FROM public.records d
115 WHERE d.organization_id=r.organization_id
116 AND d.data->>'atefNumber'=v_atef::text
117 AND NOT (d.owner_id=r.owner_id AND d.collection=r.collection AND d.id=r.id)
118 ) THEN v_atef := public.finora_next_atef(r.organization_id); END IF;
119 v_temp := nullif(trim(coalesce(r.data->>'temporaryNumber',r.data->>'number','')),'');
120 IF v_temp IS NULL THEN v_temp := 'TMP-'||v_atef::text; END IF;
121 v_status := coalesce(r.data->>'status',r.data->>'documentStatus',r.data->>'accountingStatus','draft');
122
123 UPDATE public.records
124 SET data =
125 CASE
126 WHEN collection='journalVouchers' THEN
127 (data
128 || jsonb_build_object(
129 'atefNumber',v_atef,
130 'temporaryNumber',v_temp,
131 'lifecycleMigrationOriginalStatus',v_status,
132 'lifecycleMigrationOriginalNumber',coalesce(data->>'number',''),
133 'status','draft'
134 )
135 - 'number' - 'postedAt' - 'postedBy')
136 ELSE
137 (data
138 || jsonb_build_object(
139 'atefNumber',v_atef,
140 'temporaryNumber',v_temp,
141 'lifecycleMigrationOriginalStatus',v_status,
142 'lifecycleMigrationOriginalNumber',coalesce(data->>'number',''),
143 'documentStatus','draft',
144 'accountingStatus',CASE WHEN data ? 'accountingStatus' THEN 'draft' ELSE data->>'accountingStatus' END
145 )
146 - 'number' - 'postedAt' - 'postedBy' - 'accountingPostedAt' - 'documentPostedAt' - 'documentPostedBy')
147 END
148 WHERE organization_id=r.organization_id AND collection=r.collection AND id=r.id;
149
150 INSERT INTO public.finora_document_lifecycle_audit(
151 organization_id,atef_number,document_collection,document_id,event_type,
152 temporary_number,permanent_number,actor_id,original_status,metadata)
153 VALUES(
154 r.organization_id,v_atef,r.collection,r.id,'MIGRATED_TO_DRAFT',
155 v_temp,coalesce(r.data->>'number',''),auth.uid(),v_status,
156 jsonb_build_object('migration','20261118100000','source_record_version',r.version)
157 )
158 ON CONFLICT DO NOTHING;
159 END LOOP;
160 END $$;
161
162 -- Reconcile the sequence above any pre-existing ATEF values.
163 UPDATE public.finora_document_number_sequence s
164 SET next_atef = greatest(
165 s.next_atef,
166 coalesce((SELECT max((data->>'atefNumber')::bigint)+1
167 FROM public.records
168 WHERE organization_id=s.organization_id
169 AND data ? 'atefNumber'),1)
170 ),
171 updated_at=clock_timestamp();
172
173 -- Server-side creation of a temporary document number. ATEF is allocated once.
174 CREATE OR REPLACE FUNCTION public.finora_document_identity(
175 p_organization_id uuid,
176 p_collection text,
177 p_id text,
178 p_temporary_number text DEFAULT NULL
179 )
180 RETURNS jsonb
181 LANGUAGE plpgsql
182 SECURITY DEFINER
183 SET search_path=''
184 AS $$
185 DECLARE r public.records%rowtype; n bigint; t text;
186 BEGIN
187 SELECT * INTO r FROM public.records
188 WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id
189 FOR UPDATE;
190 IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_DOCUMENT_NOT_FOUND' USING ERRCODE='P0002'; END IF;
191 n:=NULLIF(r.data->>'atefNumber','')::bigint;
192 IF n IS NULL THEN n:=public.finora_next_atef(p_organization_id); END IF;
193 t:=nullif(trim(coalesce(p_temporary_number,r.data->>'temporaryNumber',r.data->>'number','')),'');
194 IF t IS NULL THEN t:='TMP-'||n::text; END IF;
195 UPDATE public.records
196 SET data=(r.data||jsonb_build_object('atefNumber',n,'temporaryNumber',t,'documentStatus','draft')-'number'-'postedAt'-'postedBy')
197 WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id;
198 INSERT INTO public.finora_document_lifecycle_audit(
199 organization_id,atef_number,document_collection,document_id,event_type,temporary_number,actor_id,metadata)
200 VALUES(p_organization_id,n,p_collection,p_id,'CREATED_DRAFT',t,auth.uid(),jsonb_build_object('temporary',true));
201 RETURN (SELECT data FROM public.records WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id);
202 END $$;
203
204 -- Posting assigns the permanent number. It never changes ATEF.
205 CREATE OR REPLACE FUNCTION public.finora_assign_permanent_document_number(
206 p_organization_id uuid,
207 p_collection text,
208 p_id text,
209 p_company_id text,
210 p_fiscal_year_id text,
211 p_document_type text
212 )
213 RETURNS jsonb
214 LANGUAGE plpgsql
215 SECURITY DEFINER
216 SET search_path=''
217 AS $$
218 DECLARE r public.records%rowtype; n bigint; status text;
219 BEGIN
220 SELECT * INTO r FROM public.records
221 WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id FOR UPDATE;
222 IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_DOCUMENT_NOT_FOUND' USING ERRCODE='P0002'; END IF;
223 status:=coalesce(r.data->>'status',r.data->>'documentStatus',r.data->>'accountingStatus','draft');
224 IF status<>'posted' THEN RAISE EXCEPTION 'FINORA_DOCUMENT_NOT_POSTED' USING ERRCODE='23514'; END IF;
225 n:=public.finora_next_permanent_number(p_organization_id,p_company_id,p_fiscal_year_id,p_document_type);
226 UPDATE public.records
227 SET data=(r.data||jsonb_build_object('number',n::text,'documentStatus','posted','accountingStatus',
228 CASE WHEN r.data ? 'accountingStatus' THEN 'posted' ELSE r.data->>'accountingStatus' END))
229 WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id;
230 INSERT INTO public.finora_document_lifecycle_audit(
231 organization_id,atef_number,document_collection,document_id,event_type,
232 temporary_number,permanent_number,actor_id,metadata)
233 VALUES(p_organization_id,(r.data->>'atefNumber')::bigint,p_collection,p_id,'POSTED',
234 r.data->>'temporaryNumber',n::text,auth.uid(),jsonb_build_object('document_type',p_document_type));
235 RETURN (SELECT data FROM public.records WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_id);
236 END $$;
237
238 REVOKE ALL ON FUNCTION public.finora_document_identity(uuid,text,text,text) FROM PUBLIC, anon, authenticated;
239 REVOKE ALL ON FUNCTION public.finora_assign_permanent_document_number(uuid,text,text,text,text,text) FROM PUBLIC, anon, authenticated;
240
241 -- Draft source deletion: source is the user-facing root. If it owns a draft
242 -- journal voucher, the voucher + lines + dimensions are deleted atomically too.
243 CREATE OR REPLACE FUNCTION public.finora_delete_draft_source(
244 p_organization_id uuid,
245 p_collection text,
246 p_source_id text
247 )
248 RETURNS jsonb
249 LANGUAGE plpgsql
250 SECURITY DEFINER
251 SET search_path=''
252 AS $$
253 DECLARE s public.records%rowtype; v public.records%rowtype; a bigint;
254 BEGIN
255 SELECT * INTO s FROM public.records
256 WHERE organization_id=p_organization_id AND collection=p_collection AND id=p_source_id
257 FOR UPDATE;
258 IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_SOURCE_NOT_FOUND' USING ERRCODE='P0002'; END IF;
259 IF coalesce(s.data->>'documentStatus',s.data->>'accountingStatus',s.data->>'status','draft')<>'draft'
260 THEN RAISE EXCEPTION 'FINORA_ONLY_DRAFT_CAN_BE_DELETED' USING ERRCODE='23514'; END IF;
261 a:=NULLIF(s.data->>'atefNumber','')::bigint;
262
263 IF coalesce(s.data->>'journalVoucherId','')<>'' THEN
264 SELECT * INTO v FROM public.records
265 WHERE organization_id=p_organization_id AND collection='journalVouchers'
266 AND id=s.data->>'journalVoucherId' FOR UPDATE;
267 IF FOUND AND coalesce(v.data->>'status','draft')<>'draft'
268 THEN RAISE EXCEPTION 'FINORA_LINKED_VOUCHER_NOT_DRAFT' USING ERRCODE='23514'; END IF;
269
270 IF FOUND THEN
271 INSERT INTO public.finora_document_lifecycle_audit(
272 organization_id,atef_number,document_collection,document_id,event_type,
273 temporary_number,permanent_number,related_collection,related_id,actor_id,original_status,metadata)
274 VALUES(p_organization_id,a,'journalVouchers',v.id,'DELETED_WITH_SOURCE',
275 v.data->>'temporaryNumber',v.data->>'number',p_collection,p_source_id,auth.uid(),'draft',
276 jsonb_build_object('source_atef',a));
277 DELETE FROM public.records WHERE organization_id=p_organization_id
278 AND collection IN ('journalLineDimensions','journalLines')
279 AND ((collection='journalLines' AND data->>'voucherId'=v.id)
280 OR (collection='journalLineDimensions' AND data->>'voucherId'=v.id));
281 DELETE FROM public.records WHERE organization_id=p_organization_id
282 AND collection='journalVouchers' AND id=v.id;
283 END IF;
284 END IF;
285
286 INSERT INTO public.finora_document_lifecycle_audit(
287 organization_id,atef_number,document_collection,document_id,event_type,
288 temporary_number,permanent_number,actor_id,original_status,metadata)
289 VALUES(p_organization_id,a,p_collection,p_source_id,'DELETED',
290 s.data->>'temporaryNumber',s.data->>'number',auth.uid(),'draft',
291 jsonb_build_object('cascade_voucher_id',s.data->>'journalVoucherId'));
292
293 DELETE FROM public.records WHERE organization_id=p_organization_id
294 AND collection=p_collection AND id=p_source_id;
295
296 RETURN jsonb_build_object('deleted',true,'atefNumber',a,'sourceId',p_source_id);
297 END $$;
298
299 REVOKE ALL ON FUNCTION public.finora_delete_draft_source(uuid,text,text) FROM PUBLIC, anon, authenticated;
300
301 -- Direct deletion of a linked voucher is deliberately forbidden. User must
302 -- delete the source document; the source operation then removes both.
303 CREATE OR REPLACE FUNCTION public.finora_delete_draft_voucher(
304 p_organization_id uuid,
305 p_voucher_id text
306 )
307 RETURNS jsonb
308 LANGUAGE plpgsql
309 SECURITY DEFINER
310 SET search_path=''
311 AS $$
312 DECLARE v public.records%rowtype; src public.records%rowtype;
313 BEGIN
314 SELECT * INTO v FROM public.records WHERE organization_id=p_organization_id
315 AND collection='journalVouchers' AND id=p_voucher_id FOR UPDATE;
316 IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_VOUCHER_NOT_FOUND' USING ERRCODE='P0002'; END IF;
317 IF coalesce(v.data->>'status','draft')<>'draft' THEN
318 RAISE EXCEPTION 'FINORA_ONLY_DRAFT_CAN_BE_DELETED' USING ERRCODE='23514';
319 END IF;
320 IF coalesce(v.data->>'sourceType','manual') IN ('sale','purchase') AND coalesce(v.data->>'sourceId','')<>'' THEN
321 RAISE EXCEPTION 'FINORA_DELETE_SOURCE_REQUIRED: ابتدا سند تجاری منبع را حذف کنید' USING ERRCODE='23514';
322 END IF;
323 DELETE FROM public.records WHERE organization_id=p_organization_id
324 AND collection IN ('journalLineDimensions','journalLines')
325 AND data->>'voucherId'=p_voucher_id;
326 DELETE FROM public.records WHERE organization_id=p_organization_id
327 AND collection='journalVouchers' AND id=p_voucher_id;
328 INSERT INTO public.finora_document_lifecycle_audit(
329 organization_id,atef_number,document_collection,document_id,event_type,
330 temporary_number,permanent_number,actor_id,original_status)
331 VALUES(p_organization_id,NULL,'journalVouchers',p_voucher_id,'DELETED_DRAFT_VOUCHER',
332 v.data->>'temporaryNumber',v.data->>'number',auth.uid(),'draft');
333 RETURN jsonb_build_object('deleted',true,'voucherId',p_voucher_id);
334 END $$;
335
336 REVOKE ALL ON FUNCTION public.finora_delete_draft_voucher(uuid,text) FROM PUBLIC, anon, authenticated;
337
338 -- Public read policy is intentionally absent; audit is accessed only through a
339 -- future privileged reporting RPC. The table is not exposed to clients.