سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 14:15 UTC
qa/pr219-wp1-disposable-dburl-proof-20261123
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
| 1 | -- Phase 4: universal temporary journal-document lifecycle. |
| 2 | -- Every accounting voucher receives an immutable, never-reused ATF (عطف) number |
| 3 | -- and a temporary document number. Posting changes lifecycle state only; it does |
| 4 | -- not allocate a second identity. |
| 5 | CREATE SEQUENCE IF NOT EXISTS public.finora_journal_atf_seq AS bigint START WITH 1 INCREMENT BY 1 NO CYCLE; |
| 6 | CREATE SEQUENCE IF NOT EXISTS public.finora_journal_temp_seq AS bigint START WITH 1 INCREMENT BY 1 NO CYCLE; |
| 7 | |
| 8 | CREATE TABLE IF NOT EXISTS public.finora_journal_document_registry ( |
| 9 | atf_number bigint PRIMARY KEY, |
| 10 | organization_id uuid NOT NULL, |
| 11 | company_id text NOT NULL, |
| 12 | fiscal_year_id text, |
| 13 | voucher_id text NOT NULL, |
| 14 | temporary_number bigint NOT NULL, |
| 15 | state text NOT NULL CHECK (state IN ('draft','posted','reversed','deleted')), |
| 16 | created_at timestamptz NOT NULL DEFAULT clock_timestamp(), |
| 17 | created_by uuid, |
| 18 | posted_at timestamptz, |
| 19 | posted_by uuid, |
| 20 | deleted_at timestamptz, |
| 21 | deleted_by uuid, |
| 22 | delete_reason text |
| 23 | ); |
| 24 | |
| 25 | CREATE UNIQUE INDEX IF NOT EXISTS finora_jdr_voucher_uq |
| 26 | ON public.finora_journal_document_registry(organization_id, voucher_id); |
| 27 | CREATE UNIQUE INDEX IF NOT EXISTS finora_jdr_temp_uq |
| 28 | ON public.finora_journal_document_registry(organization_id, company_id, fiscal_year_id, temporary_number); |
| 29 | |
| 30 | CREATE TABLE IF NOT EXISTS public.finora_journal_document_audit ( |
| 31 | id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, |
| 32 | atf_number bigint NOT NULL, |
| 33 | organization_id uuid NOT NULL, |
| 34 | voucher_id text NOT NULL, |
| 35 | action text NOT NULL CHECK (action IN ('created','posted','reversed','deleted','migrated_to_draft')), |
| 36 | old_state text, |
| 37 | new_state text, |
| 38 | actor_id uuid, |
| 39 | occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(), |
| 40 | reason text, |
| 41 | snapshot jsonb |
| 42 | ); |
| 43 | |
| 44 | CREATE INDEX IF NOT EXISTS finora_jda_atf_idx |
| 45 | ON public.finora_journal_document_audit(atf_number, occurred_at); |
| 46 | |
| 47 | ALTER TABLE public.finora_journal_document_registry ENABLE ROW LEVEL SECURITY; |
| 48 | ALTER TABLE public.finora_journal_document_audit ENABLE ROW LEVEL SECURITY; |
| 49 | -- Direct table reads remain disabled; access is exposed only through SECURITY DEFINER RPCs. |
| 50 | REVOKE ALL ON public.finora_journal_document_registry FROM PUBLIC, anon, authenticated; |
| 51 | REVOKE ALL ON public.finora_journal_document_audit FROM PUBLIC, anon, authenticated; |
| 52 | |
| 53 | CREATE OR REPLACE FUNCTION public.finora_journal_allocate_identity( |
| 54 | p_organization_id uuid, |
| 55 | p_company_id text, |
| 56 | p_fiscal_year_id text, |
| 57 | p_voucher_id text, |
| 58 | p_actor uuid DEFAULT auth.uid() |
| 59 | ) RETURNS jsonb |
| 60 | LANGUAGE plpgsql SECURITY DEFINER SET search_path='' |
| 61 | AS $$ |
| 62 | DECLARE |
| 63 | v_existing public.finora_journal_document_registry%rowtype; |
| 64 | v_atf bigint; |
| 65 | v_temp bigint; |
| 66 | BEGIN |
| 67 | PERFORM private.finora_phase1a_authorize(p_organization_id,'create',NULL); |
| 68 | |
| 69 | SELECT * INTO v_existing |
| 70 | FROM public.finora_journal_document_registry |
| 71 | WHERE organization_id=p_organization_id AND voucher_id=p_voucher_id |
| 72 | FOR UPDATE; |
| 73 | |
| 74 | IF FOUND THEN |
| 75 | RETURN jsonb_build_object( |
| 76 | 'atfNumber',v_existing.atf_number, |
| 77 | 'temporaryNumber',v_existing.temporary_number, |
| 78 | 'state',v_existing.state |
| 79 | ); |
| 80 | END IF; |
| 81 | |
| 82 | v_atf:=nextval('public.finora_journal_atf_seq'); |
| 83 | v_temp:=nextval('public.finora_journal_temp_seq'); |
| 84 | |
| 85 | INSERT INTO public.finora_journal_document_registry( |
| 86 | atf_number,organization_id,company_id,fiscal_year_id,voucher_id, |
| 87 | temporary_number,state,created_by |
| 88 | ) VALUES ( |
| 89 | v_atf,p_organization_id,p_company_id,p_fiscal_year_id,p_voucher_id, |
| 90 | v_temp,'draft',p_actor |
| 91 | ); |
| 92 | |
| 93 | INSERT INTO public.finora_journal_document_audit( |
| 94 | atf_number,organization_id,voucher_id,action,old_state,new_state,actor_id,snapshot |
| 95 | ) VALUES ( |
| 96 | v_atf,p_organization_id,p_voucher_id,'created',NULL,'draft',p_actor, |
| 97 | jsonb_build_object('companyId',p_company_id,'fiscalYearId',p_fiscal_year_id, |
| 98 | 'temporaryNumber',v_temp) |
| 99 | ); |
| 100 | |
| 101 | RETURN jsonb_build_object( |
| 102 | 'atfNumber',v_atf,'temporaryNumber',v_temp,'state','draft' |
| 103 | ); |
| 104 | END $$; |
| 105 | |
| 106 | CREATE OR REPLACE FUNCTION public.finora_journal_post_identity( |
| 107 | p_organization_id uuid, |
| 108 | p_voucher_id text, |
| 109 | p_actor uuid DEFAULT auth.uid() |
| 110 | ) RETURNS jsonb |
| 111 | LANGUAGE plpgsql SECURITY DEFINER SET search_path='' |
| 112 | AS $$ |
| 113 | DECLARE v public.finora_journal_document_registry%rowtype; |
| 114 | BEGIN |
| 115 | PERFORM private.finora_phase1a_authorize(p_organization_id,'approve',NULL); |
| 116 | SELECT * INTO v FROM public.finora_journal_document_registry |
| 117 | WHERE organization_id=p_organization_id AND voucher_id=p_voucher_id |
| 118 | FOR UPDATE; |
| 119 | IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_ATF_NOT_FOUND' USING ERRCODE='23503'; END IF; |
| 120 | IF v.state='deleted' THEN RAISE EXCEPTION 'FINORA_ATF_DELETED' USING ERRCODE='23514'; END IF; |
| 121 | IF v.state='posted' THEN |
| 122 | RETURN jsonb_build_object('atfNumber',v.atf_number,'temporaryNumber',v.temporary_number,'state','posted'); |
| 123 | END IF; |
| 124 | UPDATE public.finora_journal_document_registry |
| 125 | SET state='posted',posted_at=clock_timestamp(),posted_by=p_actor |
| 126 | WHERE atf_number=v.atf_number; |
| 127 | INSERT INTO public.finora_journal_document_audit( |
| 128 | atf_number,organization_id,voucher_id,action,old_state,new_state,actor_id |
| 129 | ) VALUES (v.atf_number,p_organization_id,p_voucher_id,'posted','draft','posted',p_actor); |
| 130 | RETURN jsonb_build_object('atfNumber',v.atf_number,'temporaryNumber',v.temporary_number,'state','posted'); |
| 131 | END $$; |
| 132 | |
| 133 | CREATE OR REPLACE FUNCTION public.finora_journal_delete_identity( |
| 134 | p_organization_id uuid, |
| 135 | p_voucher_id text, |
| 136 | p_reason text, |
| 137 | p_actor uuid DEFAULT auth.uid() |
| 138 | ) RETURNS jsonb |
| 139 | LANGUAGE plpgsql SECURITY DEFINER SET search_path='' |
| 140 | AS $$ |
| 141 | DECLARE v public.finora_journal_document_registry%rowtype; |
| 142 | BEGIN |
| 143 | PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',NULL); |
| 144 | IF coalesce(trim(p_reason),'')='' THEN |
| 145 | RAISE EXCEPTION 'FINORA_DELETE_REASON_REQUIRED' USING ERRCODE='23514'; |
| 146 | END IF; |
| 147 | |
| 148 | SELECT * INTO v FROM public.finora_journal_document_registry |
| 149 | WHERE organization_id=p_organization_id AND voucher_id=p_voucher_id |
| 150 | FOR UPDATE; |
| 151 | IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_ATF_NOT_FOUND' USING ERRCODE='23503'; END IF; |
| 152 | IF v.state IN ('posted','reversed') THEN |
| 153 | RAISE EXCEPTION 'FINORA_POSTED_DOCUMENT_NOT_DELETABLE' |
| 154 | USING ERRCODE='23514', |
| 155 | DETAIL='اسناد قطعی/برگشتی حذف فیزیکی نمیشوند؛ از ابطال/برگشت استفاده کنید.'; |
| 156 | END IF; |
| 157 | IF v.state='deleted' THEN |
| 158 | RETURN jsonb_build_object('atfNumber',v.atf_number,'temporaryNumber',v.temporary_number,'state','deleted'); |
| 159 | END IF; |
| 160 | |
| 161 | UPDATE public.finora_journal_document_registry |
| 162 | SET state='deleted',deleted_at=clock_timestamp(),deleted_by=p_actor,delete_reason=trim(p_reason) |
| 163 | WHERE atf_number=v.atf_number; |
| 164 | |
| 165 | INSERT INTO public.finora_journal_document_audit( |
| 166 | atf_number,organization_id,voucher_id,action,old_state,new_state,actor_id,reason |
| 167 | ) VALUES (v.atf_number,p_organization_id,p_voucher_id,'deleted','draft','deleted',p_actor,trim(p_reason)); |
| 168 | |
| 169 | RETURN jsonb_build_object( |
| 170 | 'atfNumber',v.atf_number,'temporaryNumber',v.temporary_number,'state','deleted' |
| 171 | ); |
| 172 | END $$; |
| 173 | |
| 174 | -- Existing vouchers are deliberately migrated to draft. Their old lifecycle is |
| 175 | -- preserved in the audit table so no historical identity disappears. |
| 176 | DO $$ |
| 177 | DECLARE r record; atf bigint; tmp bigint; |
| 178 | BEGIN |
| 179 | FOR r IN |
| 180 | SELECT organization_id,id,data |
| 181 | FROM public.records |
| 182 | WHERE collection='journalVouchers' |
| 183 | LOOP |
| 184 | IF NOT EXISTS ( |
| 185 | SELECT 1 FROM public.finora_journal_document_registry x |
| 186 | WHERE x.organization_id=r.organization_id AND x.voucher_id=r.id |
| 187 | ) THEN |
| 188 | atf:=nextval('public.finora_journal_atf_seq'); |
| 189 | tmp:=nextval('public.finora_journal_temp_seq'); |
| 190 | INSERT INTO public.finora_journal_document_registry( |
| 191 | atf_number,organization_id,company_id,fiscal_year_id,voucher_id, |
| 192 | temporary_number,state,created_at,created_by |
| 193 | ) VALUES ( |
| 194 | atf,r.organization_id,coalesce(r.data->>'companyId',''),r.data->>'fiscalYearId', |
| 195 | r.id,tmp,'draft',coalesce((r.data->>'createdAt')::timestamptz,clock_timestamp()), |
| 196 | nullif(r.data->>'createdBy','')::uuid |
| 197 | ); |
| 198 | INSERT INTO public.finora_journal_document_audit( |
| 199 | atf_number,organization_id,voucher_id,action,old_state,new_state,actor_id,reason,snapshot |
| 200 | ) VALUES ( |
| 201 | atf,r.organization_id,r.id,'migrated_to_draft',r.data->>'status','draft', |
| 202 | auth.uid(),'مهاجرت چرخه اسناد به حالت موقت',r.data |
| 203 | ); |
| 204 | UPDATE public.records |
| 205 | SET data=(data-'postedAt'-'postedBy'-'reversalVoucherId'-'reversedAt') |
| 206 | ||jsonb_build_object( |
| 207 | 'status','draft', |
| 208 | 'documentStatus','draft', |
| 209 | 'accountingStatus','draft', |
| 210 | 'atfNumber',atf, |
| 211 | 'temporaryNumber',tmp, |
| 212 | 'numberStatus','temporary' |
| 213 | ), |
| 214 | version=version+1 |
| 215 | WHERE organization_id=r.organization_id AND collection='journalVouchers' AND id=r.id; |
| 216 | END IF; |
| 217 | END LOOP; |
| 218 | |
| 219 | -- Any commercial source previously linked to a posted journal becomes a |
| 220 | -- draft source as well; the voucher identity remains linked and traceable. |
| 221 | UPDATE public.records s |
| 222 | SET data=(s.data-'accountingPostedAt'-'documentPostedAt'-'documentPostedBy') |
| 223 | ||jsonb_build_object('documentStatus','draft','accountingStatus','draft'), |
| 224 | version=s.version+1 |
| 225 | WHERE s.collection IN ('invoices','purchases') |
| 226 | AND (s.data->>'journalVoucherId') IS NOT NULL |
| 227 | AND coalesce(s.data->>'accountingStatus','')='posted'; |
| 228 | |
| 229 | -- All other source modules linked to a journal voucher are moved to the |
| 230 | -- same temporary accounting lifecycle. Operational status fields are left |
| 231 | -- untouched; only the accounting/document projection is reset. |
| 232 | UPDATE public.records s |
| 233 | SET data=(s.data-'accountingPostedAt'-'documentPostedAt'-'documentPostedBy') |
| 234 | ||jsonb_build_object('documentStatus','draft','accountingStatus','draft'), |
| 235 | version=s.version+1 |
| 236 | FROM public.records v |
| 237 | WHERE s.collection<>'journalVouchers' |
| 238 | AND s.data->>'journalVoucherId'=v.id |
| 239 | AND v.collection='journalVouchers' |
| 240 | AND v.organization_id=s.organization_id |
| 241 | AND v.data->>'status'='draft' |
| 242 | AND coalesce(s.data->>'accountingStatus','')='posted'; |
| 243 | END $$; |
| 244 | |
| 245 | REVOKE ALL ON FUNCTION public.finora_journal_allocate_identity(uuid,text,text,text,uuid) |
| 246 | FROM PUBLIC, anon, authenticated; |
| 247 | GRANT EXECUTE ON FUNCTION public.finora_journal_allocate_identity(uuid,text,text,text,uuid) TO authenticated; |
| 248 | REVOKE ALL ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) |
| 249 | FROM PUBLIC, anon, authenticated; |
| 250 | GRANT EXECUTE ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) TO authenticated; |
| 251 | REVOKE ALL ON FUNCTION public.finora_journal_delete_identity(uuid,text,text,uuid) |
| 252 | FROM PUBLIC, anon, authenticated; |
| 253 | GRANT EXECUTE ON FUNCTION public.finora_journal_delete_identity(uuid,text,text,uuid) TO authenticated; |
| 254 | |
| 255 | |
| 256 | -- Posting keeps the immutable temporary number; it changes its lifecycle |
| 257 | -- classification to final instead of allocating a second document number. |
| 258 | CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core( |
| 259 | p_org uuid,p_id text,p_expected_version bigint,p_auto boolean DEFAULT false) |
| 260 | RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' |
| 261 | AS $fn$ |
| 262 | DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text; |
| 263 | v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp(); |
| 264 | v_registry public.finora_journal_document_registry%rowtype; |
| 265 | BEGIN |
| 266 | IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members |
| 267 | WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN |
| 268 | RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501'; |
| 269 | END IF; |
| 270 | SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE; |
| 271 | IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF; |
| 272 | v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual'); |
| 273 | IF p_auto THEN |
| 274 | IF v_src='reversal' THEN |
| 275 | SELECT data->>'sourceType' INTO v_original_src FROM public.records |
| 276 | WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId'; |
| 277 | IF coalesce(v_original_src,'manual')='manual' THEN |
| 278 | PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL); |
| 279 | ELSE |
| 280 | PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src); |
| 281 | END IF; |
| 282 | ELSIF v_src IN ('manual','') THEN |
| 283 | RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501'; |
| 284 | ELSE |
| 285 | PERFORM private.finora_phase1a_authorize(p_org,'create',v_src); |
| 286 | END IF; |
| 287 | ELSE |
| 288 | PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL); |
| 289 | END IF; |
| 290 | IF v.data->>'status'='posted' THEN |
| 291 | RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true); |
| 292 | END IF; |
| 293 | IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF; |
| 294 | IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF; |
| 295 | IF v_src IN ('sale','purchase') THEN PERFORM private.finora_phase1a_revalidate_autopost(p_org,v); END IF; |
| 296 | IF NOT EXISTS(SELECT 1 FROM public.records fy WHERE fy.organization_id=p_org AND fy.collection='fiscalYears' |
| 297 | AND fy.id=v_fy AND fy.data->>'companyId'=v_company AND coalesce(fy.data->>'status','open')<>'locked') THEN |
| 298 | RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED_OR_MISSING' USING ERRCODE='23514'; |
| 299 | END IF; |
| 300 | PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company); |
| 301 | |
| 302 | SELECT * INTO v_registry FROM public.finora_journal_document_registry |
| 303 | WHERE organization_id=p_org AND voucher_id=p_id FOR UPDATE; |
| 304 | IF NOT FOUND THEN |
| 305 | PERFORM public.finora_journal_allocate_identity(p_org,v_company,v_fy,p_id,v_actor); |
| 306 | SELECT * INTO v_registry FROM public.finora_journal_document_registry |
| 307 | WHERE organization_id=p_org AND voucher_id=p_id FOR UPDATE; |
| 308 | END IF; |
| 309 | v_no:=v_registry.temporary_number; |
| 310 | |
| 311 | UPDATE public.records SET data=v.data||jsonb_build_object( |
| 312 | 'status','posted','number',v_no::text,'temporaryNumber',v_no, |
| 313 | 'numberStatus','posted','documentStatus','posted','accountingStatus','posted', |
| 314 | 'postedAt',v_at,'postedBy',v_actor) |
| 315 | WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id |
| 316 | RETURNING * INTO v; |
| 317 | |
| 318 | UPDATE public.finora_journal_document_registry |
| 319 | SET state='posted',posted_at=v_at,posted_by=v_actor |
| 320 | WHERE organization_id=p_org AND voucher_id=p_id; |
| 321 | |
| 322 | PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','', |
| 323 | jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId')); |
| 324 | |
| 325 | RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version), |
| 326 | 'replayed',false,'atfNumber',v_registry.atf_number,'temporaryNumber',v_no); |
| 327 | END $fn$; |
| 328 | |
| 329 | -- Create a source-linked draft without posting it. This is the new default |
| 330 | -- lifecycle for sales/purchases: source + accounting voucher are both temporary |
| 331 | -- until an authorized approver posts the voucher. |
| 332 | CREATE OR REPLACE FUNCTION public.finora_journal_create_source_draft( |
| 333 | p_organization_id uuid,p_voucher_id text,p_source_collection text, |
| 334 | p_source_id text,p_header jsonb,p_lines jsonb) |
| 335 | RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' |
| 336 | AS $fn$ |
| 337 | DECLARE typ text:=p_header->>'sourceType'; |
| 338 | coll text:=CASE WHEN typ='sale' THEN 'invoices' WHEN typ='purchase' THEN 'purchases' ELSE NULL END; |
| 339 | source public.records%rowtype; cfg_version bigint; lines jsonb; draft jsonb; voucher public.records%rowtype; |
| 340 | prior public.records%rowtype; |
| 341 | BEGIN |
| 342 | IF coll IS NULL OR p_source_collection IS DISTINCT FROM coll |
| 343 | OR coalesce(p_source_id,'')='' OR p_header->>'sourceId' IS DISTINCT FROM p_source_id THEN |
| 344 | RAISE EXCEPTION 'FINORA_SOURCE_IDENTITY_INVALID' USING ERRCODE='23514'; |
| 345 | END IF; |
| 346 | PERFORM private.finora_phase1a_authorize(p_organization_id,'create',typ); |
| 347 | |
| 348 | SELECT * INTO source FROM public.records |
| 349 | WHERE organization_id=p_organization_id AND collection=coll AND id=p_source_id |
| 350 | AND data->>'companyId'=p_header->>'companyId' |
| 351 | AND private.can_access_record(p_organization_id,coll,owner_id,data,'create') |
| 352 | FOR UPDATE; |
| 353 | IF NOT FOUND THEN |
| 354 | RAISE EXCEPTION 'FINORA_SOURCE_NOT_COMMITTED_IN_ORG' USING ERRCODE='23503'; |
| 355 | END IF; |
| 356 | |
| 357 | IF coalesce(source.data->>'journalVoucherId','')<>'' THEN |
| 358 | SELECT * INTO prior FROM public.records |
| 359 | WHERE organization_id=p_organization_id AND collection='journalVouchers' |
| 360 | AND id=source.data->>'journalVoucherId' FOR SHARE; |
| 361 | IF FOUND AND prior.data->>'sourceType'=typ |
| 362 | AND prior.data->>'sourceId'=p_source_id |
| 363 | AND prior.data->>'status'='draft' THEN |
| 364 | RETURN jsonb_build_object('voucher',prior.data||jsonb_build_object('id',prior.id,'version',prior.version),'replayed',true); |
| 365 | END IF; |
| 366 | RAISE EXCEPTION 'FINORA_SOURCE_ALREADY_LINKED' USING ERRCODE='23514'; |
| 367 | END IF; |
| 368 | |
| 369 | SELECT max(version) INTO cfg_version |
| 370 | FROM private.finora_phase1a_account_role_snapshots |
| 371 | WHERE organization_id=p_organization_id |
| 372 | AND company_id=p_header->>'companyId' AND approved; |
| 373 | IF cfg_version IS NULL THEN |
| 374 | RAISE EXCEPTION 'FINORA_POSTING_ACCOUNT_ROLE_MISSING: حساب نقش ثبت خودکار تعریف نشده است' |
| 375 | USING ERRCODE='23514'; |
| 376 | END IF; |
| 377 | |
| 378 | lines:=private.finora_phase1a_expected_lines( |
| 379 | p_organization_id,p_header->>'companyId',typ,source.data,cfg_version); |
| 380 | |
| 381 | IF p_lines IS NOT NULL AND p_lines<>'[]'::jsonb |
| 382 | AND private.finora_phase1a_line_set(p_lines) |
| 383 | IS DISTINCT FROM private.finora_phase1a_line_set(lines) THEN |
| 384 | RAISE EXCEPTION 'FINORA_POSTING_LINES_MISMATCH' USING ERRCODE='23514'; |
| 385 | END IF; |
| 386 | |
| 387 | draft:=private.finora_phase1a_create_core( |
| 388 | p_organization_id,p_voucher_id, |
| 389 | p_header||jsonb_build_object( |
| 390 | 'sourceType',typ,'sourceId',p_source_id, |
| 391 | 'sourceVersion',coalesce(p_header->>'sourceVersion','1')), |
| 392 | lines); |
| 393 | |
| 394 | UPDATE public.records |
| 395 | SET data=data||jsonb_build_object( |
| 396 | 'postingContractRule',typ||'-v1', |
| 397 | 'postingContractVersion',cfg_version, |
| 398 | 'documentStatus','draft', |
| 399 | 'accountingStatus','draft') |
| 400 | WHERE organization_id=p_organization_id |
| 401 | AND collection='journalVouchers' AND id=p_voucher_id |
| 402 | RETURNING * INTO voucher; |
| 403 | |
| 404 | UPDATE public.records |
| 405 | SET data=(data-'accountingPostingPending'-'accountingPostingPendingAt')|| |
| 406 | jsonb_build_object( |
| 407 | 'journalVoucherId',p_voucher_id, |
| 408 | 'accountingStatus','draft', |
| 409 | 'documentStatus','draft', |
| 410 | 'updatedAt',clock_timestamp()) |
| 411 | WHERE organization_id=p_organization_id |
| 412 | AND collection=coll AND id=p_source_id; |
| 413 | |
| 414 | RETURN jsonb_build_object( |
| 415 | 'voucher',voucher.data||jsonb_build_object('id',voucher.id,'version',voucher.version), |
| 416 | 'replayed',coalesce((draft->>'replayed')::boolean,false), |
| 417 | 'computedLines',lines,'contractVersion',cfg_version); |
| 418 | END $fn$; |
| 419 | |
| 420 | REVOKE ALL ON FUNCTION public.finora_journal_create_source_draft(uuid,text,text,text,jsonb,jsonb) |
| 421 | FROM PUBLIC,anon,authenticated; |
| 422 | GRANT EXECUTE ON FUNCTION public.finora_journal_create_source_draft(uuid,text,text,text,jsonb,jsonb) |
| 423 | TO authenticated; |
| 424 | |
| 425 | CREATE OR REPLACE FUNCTION public.finora_journal_refresh_source_draft( |
| 426 | p_organization_id uuid,p_source_collection text,p_source_id text, |
| 427 | p_expected_voucher_version bigint) |
| 428 | RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' |
| 429 | AS $fn$ |
| 430 | DECLARE source public.records%rowtype; voucher public.records%rowtype; |
| 431 | typ text; cfg_version bigint; lines jsonb; |
| 432 | BEGIN |
| 433 | typ:=CASE p_source_collection WHEN 'invoices' THEN 'sale' WHEN 'purchases' THEN 'purchase' ELSE NULL END; |
| 434 | IF typ IS NULL THEN RAISE EXCEPTION 'FINORA_SOURCE_COLLECTION_UNSUPPORTED' USING ERRCODE='23514'; END IF; |
| 435 | PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',typ); |
| 436 | |
| 437 | SELECT * INTO source FROM public.records |
| 438 | WHERE organization_id=p_organization_id AND collection=p_source_collection AND id=p_source_id |
| 439 | FOR UPDATE; |
| 440 | IF NOT FOUND OR coalesce(source.data->>'documentStatus','draft')<>'draft' |
| 441 | THEN RAISE EXCEPTION 'FINORA_SOURCE_DRAFT_REQUIRED' USING ERRCODE='23514'; END IF; |
| 442 | IF coalesce(source.data->>'journalVoucherId','')='' THEN |
| 443 | RAISE EXCEPTION 'FINORA_SOURCE_DRAFT_VOUCHER_MISSING' USING ERRCODE='23503'; |
| 444 | END IF; |
| 445 | |
| 446 | SELECT * INTO voucher FROM public.records |
| 447 | WHERE organization_id=p_organization_id AND collection='journalVouchers' |
| 448 | AND id=source.data->>'journalVoucherId' FOR UPDATE; |
| 449 | IF NOT FOUND OR voucher.data->>'status'<>'draft' |
| 450 | THEN RAISE EXCEPTION 'FINORA_SOURCE_DRAFT_VOUCHER_REQUIRED' USING ERRCODE='23514'; END IF; |
| 451 | IF voucher.version<>p_expected_voucher_version THEN |
| 452 | RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001'; |
| 453 | END IF; |
| 454 | |
| 455 | SELECT max(version) INTO cfg_version |
| 456 | FROM private.finora_phase1a_account_role_snapshots |
| 457 | WHERE organization_id=p_organization_id |
| 458 | AND company_id=source.data->>'companyId' AND approved; |
| 459 | IF cfg_version IS NULL THEN |
| 460 | RAISE EXCEPTION 'FINORA_POSTING_ACCOUNT_ROLE_MISSING' USING ERRCODE='23514'; |
| 461 | END IF; |
| 462 | |
| 463 | lines:=private.finora_phase1a_expected_lines( |
| 464 | p_organization_id,source.data->>'companyId',typ,source.data,cfg_version); |
| 465 | |
| 466 | DELETE FROM public.records |
| 467 | WHERE organization_id=p_organization_id AND collection='journalLineDimensions' |
| 468 | AND data->>'voucherId'=voucher.id; |
| 469 | DELETE FROM public.records |
| 470 | WHERE organization_id=p_organization_id AND collection='journalLines' |
| 471 | AND data->>'voucherId'=voucher.id; |
| 472 | |
| 473 | PERFORM private.finora_phase1a_write_lines( |
| 474 | p_organization_id,auth.uid(),voucher.id,source.data->>'companyId',lines); |
| 475 | PERFORM private.finora_phase1a_validate_saved( |
| 476 | p_organization_id,voucher.id,source.data->>'companyId'); |
| 477 | |
| 478 | UPDATE public.records |
| 479 | SET data=data||jsonb_build_object( |
| 480 | 'date',coalesce(source.data->>'date',data->>'date'), |
| 481 | 'description',coalesce(source.data->>'description',data->>'description'), |
| 482 | 'reference',coalesce(source.data->>'number',data->>'reference'), |
| 483 | 'sourceVersion',coalesce(source.data->>'accountingVersion','1'), |
| 484 | 'postingContractRule',typ||'-v1', |
| 485 | 'postingContractVersion',cfg_version, |
| 486 | 'status','draft','documentStatus','draft','accountingStatus','draft', |
| 487 | 'editedAt',clock_timestamp(),'editedBy',auth.uid()) |
| 488 | WHERE organization_id=p_organization_id AND collection='journalVouchers' AND id=voucher.id |
| 489 | RETURNING * INTO voucher; |
| 490 | |
| 491 | RETURN jsonb_build_object( |
| 492 | 'voucher',voucher.data||jsonb_build_object('id',voucher.id,'version',voucher.version), |
| 493 | 'computedLines',lines,'contractVersion',cfg_version); |
| 494 | END $fn$; |
| 495 | |
| 496 | REVOKE ALL ON FUNCTION public.finora_journal_refresh_source_draft(uuid,text,text,bigint) |
| 497 | FROM PUBLIC,anon,authenticated; |
| 498 | GRANT EXECUTE ON FUNCTION public.finora_journal_refresh_source_draft(uuid,text,text,bigint) |
| 499 | TO authenticated; |
| 500 | |
| 501 | CREATE OR REPLACE FUNCTION public.finora_journal_delete_source_draft( |
| 502 | p_organization_id uuid,p_source_collection text,p_source_id text,p_reason text) |
| 503 | RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' |
| 504 | AS $fn$ |
| 505 | DECLARE source public.records%rowtype; voucher public.records%rowtype; typ text; |
| 506 | BEGIN |
| 507 | typ:=CASE p_source_collection WHEN 'invoices' THEN 'sale' WHEN 'purchases' THEN 'purchase' ELSE NULL END; |
| 508 | IF typ IS NULL THEN RAISE EXCEPTION 'FINORA_SOURCE_COLLECTION_UNSUPPORTED' USING ERRCODE='23514'; END IF; |
| 509 | PERFORM private.finora_phase1a_authorize(p_organization_id,'edit',typ); |
| 510 | IF coalesce(trim(p_reason),'')='' THEN RAISE EXCEPTION 'FINORA_DELETE_REASON_REQUIRED' USING ERRCODE='23514'; END IF; |
| 511 | |
| 512 | SELECT * INTO source FROM public.records |
| 513 | WHERE organization_id=p_organization_id AND collection=p_source_collection AND id=p_source_id |
| 514 | FOR UPDATE; |
| 515 | IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_SOURCE_NOT_FOUND' USING ERRCODE='23503'; END IF; |
| 516 | IF coalesce(source.data->>'documentStatus','draft')<>'draft' |
| 517 | AND coalesce(source.data->>'accountingStatus','draft')<>'draft' THEN |
| 518 | RAISE EXCEPTION 'FINORA_POSTED_SOURCE_NOT_DELETABLE' USING ERRCODE='23514'; |
| 519 | END IF; |
| 520 | |
| 521 | IF coalesce(source.data->>'journalVoucherId','')<>'' THEN |
| 522 | SELECT * INTO voucher FROM public.records |
| 523 | WHERE organization_id=p_organization_id AND collection='journalVouchers' |
| 524 | AND id=source.data->>'journalVoucherId' FOR UPDATE; |
| 525 | IF FOUND AND voucher.data->>'status'<>'draft' THEN |
| 526 | RAISE EXCEPTION 'FINORA_POSTED_DOCUMENT_NOT_DELETABLE' USING ERRCODE='23514'; |
| 527 | END IF; |
| 528 | END IF; |
| 529 | |
| 530 | -- The records trigger performs the second-side delete in this same transaction, |
| 531 | -- while finora_journal_delete_identity writes the immutable ATF tombstone. |
| 532 | DELETE FROM public.records |
| 533 | WHERE organization_id=p_organization_id AND collection=p_source_collection AND id=p_source_id; |
| 534 | |
| 535 | RETURN jsonb_build_object( |
| 536 | 'deleted',true,'sourceId',p_source_id, |
| 537 | 'voucherId',coalesce(source.data->>'journalVoucherId',''), |
| 538 | 'atfNumber',coalesce(voucher.data->>'atfNumber',NULL), |
| 539 | 'temporaryNumber',coalesce(voucher.data->>'temporaryNumber',NULL)); |
| 540 | END $fn$; |
| 541 | |
| 542 | REVOKE ALL ON FUNCTION public.finora_journal_delete_source_draft(uuid,text,text,text) |
| 543 | FROM PUBLIC,anon,authenticated; |
| 544 | GRANT EXECUTE ON FUNCTION public.finora_journal_delete_source_draft(uuid,text,text,text) |
| 545 | TO authenticated; |
| 546 | |
| 547 | -- Enforce identity/state transitions at the records boundary so every writer |
| 548 | -- (UI, sync, RPC or migration) receives the same lifecycle semantics. |
| 549 | CREATE OR REPLACE FUNCTION public.finora_journal_document_lifecycle_trigger() |
| 550 | RETURNS trigger |
| 551 | LANGUAGE plpgsql |
| 552 | SECURITY DEFINER |
| 553 | SET search_path='' |
| 554 | AS $$ |
| 555 | DECLARE |
| 556 | v_identity jsonb; |
| 557 | v_org uuid; |
| 558 | v_company text; |
| 559 | v_fy text; |
| 560 | v_source_collection text; |
| 561 | v_source_id text; |
| 562 | BEGIN |
| 563 | IF TG_OP='INSERT' AND NEW.collection='journalVouchers' THEN |
| 564 | v_org:=NEW.organization_id; |
| 565 | v_company:=coalesce(NEW.data->>'companyId',''); |
| 566 | v_fy:=NEW.data->>'fiscalYearId'; |
| 567 | |
| 568 | IF coalesce(NEW.data->>'status','draft') <> 'draft' THEN |
| 569 | NEW.data:=jsonb_set(NEW.data,'{status}','"draft"',true); |
| 570 | END IF; |
| 571 | NEW.data:=jsonb_set(NEW.data,'{documentStatus}','"draft"',true); |
| 572 | NEW.data:=jsonb_set(NEW.data,'{accountingStatus}','"draft"',true); |
| 573 | NEW.data:=jsonb_set(NEW.data,'{numberStatus}','"temporary"',true); |
| 574 | |
| 575 | v_identity:=public.finora_journal_allocate_identity( |
| 576 | v_org,v_company,v_fy,NEW.id,auth.uid() |
| 577 | ); |
| 578 | NEW.data:=NEW.data |
| 579 | ||jsonb_build_object( |
| 580 | 'atfNumber',(v_identity->>'atfNumber')::bigint, |
| 581 | 'temporaryNumber',(v_identity->>'temporaryNumber')::bigint |
| 582 | ); |
| 583 | RETURN NEW; |
| 584 | END IF; |
| 585 | |
| 586 | IF TG_OP='UPDATE' AND OLD.collection='journalVouchers' THEN |
| 587 | -- ATF and temporary number are immutable identities. |
| 588 | IF OLD.data->>'atfNumber' IS NOT NULL |
| 589 | AND NEW.data->>'atfNumber' IS DISTINCT FROM OLD.data->>'atfNumber' THEN |
| 590 | RAISE EXCEPTION 'FINORA_ATF_IMMUTABLE' USING ERRCODE='23514'; |
| 591 | END IF; |
| 592 | IF OLD.data->>'temporaryNumber' IS NOT NULL |
| 593 | AND NEW.data->>'temporaryNumber' IS DISTINCT FROM OLD.data->>'temporaryNumber' THEN |
| 594 | RAISE EXCEPTION 'FINORA_TEMP_NUMBER_IMMUTABLE' USING ERRCODE='23514'; |
| 595 | END IF; |
| 596 | |
| 597 | IF coalesce(OLD.data->>'status','draft')='draft' |
| 598 | AND coalesce(NEW.data->>'status','draft')='posted' THEN |
| 599 | PERFORM public.finora_journal_post_identity(NEW.organization_id,NEW.id,auth.uid()); |
| 600 | NEW.data:=NEW.data |
| 601 | ||jsonb_build_object('documentStatus','posted','accountingStatus','posted', |
| 602 | 'numberStatus','posted'); |
| 603 | END IF; |
| 604 | |
| 605 | IF coalesce(OLD.data->>'status','draft') IN ('posted','reversed') THEN |
| 606 | IF (OLD.data - ARRAY[ |
| 607 | 'status','documentStatus','accountingStatus','numberStatus', |
| 608 | 'postedAt','postedBy','reversalVoucherId','reversedAt' |
| 609 | ]::text[]) IS DISTINCT FROM |
| 610 | (NEW.data - ARRAY[ |
| 611 | 'status','documentStatus','accountingStatus','numberStatus', |
| 612 | 'postedAt','postedBy','reversalVoucherId','reversedAt' |
| 613 | ]::text[]) THEN |
| 614 | RAISE EXCEPTION 'FINORA_POSTED_VOUCHER_IMMUTABLE' USING ERRCODE='23514'; |
| 615 | END IF; |
| 616 | END IF; |
| 617 | RETURN NEW; |
| 618 | END IF; |
| 619 | |
| 620 | IF TG_OP='DELETE' AND OLD.collection='journalVouchers' THEN |
| 621 | PERFORM public.finora_journal_delete_identity( |
| 622 | OLD.organization_id,OLD.id,'حذف سند موقت توسط کاربر',auth.uid() |
| 623 | ); |
| 624 | |
| 625 | -- Delete the source in the same transaction. Recursive trigger depth is |
| 626 | -- intentionally ignored so the second side does not delete twice. |
| 627 | IF pg_trigger_depth()=1 |
| 628 | AND coalesce(OLD.data->>'status','draft')='draft' THEN |
| 629 | v_source_collection:=CASE OLD.data->>'sourceType' |
| 630 | WHEN 'sale' THEN 'invoices' |
| 631 | WHEN 'purchase' THEN 'purchases' |
| 632 | ELSE NULL END; |
| 633 | v_source_id:=OLD.data->>'sourceId'; |
| 634 | IF v_source_collection IS NOT NULL AND coalesce(v_source_id,'')<>'' THEN |
| 635 | DELETE FROM public.records |
| 636 | WHERE organization_id=OLD.organization_id |
| 637 | AND collection=v_source_collection |
| 638 | AND id=v_source_id; |
| 639 | END IF; |
| 640 | END IF; |
| 641 | RETURN OLD; |
| 642 | END IF; |
| 643 | |
| 644 | IF TG_OP='DELETE' AND OLD.collection IN ('invoices','purchases') THEN |
| 645 | IF pg_trigger_depth()=1 |
| 646 | AND coalesce(OLD.data->>'documentStatus','draft')='draft' |
| 647 | AND coalesce(OLD.data->>'journalVoucherId','')<>'' THEN |
| 648 | DELETE FROM public.records |
| 649 | WHERE organization_id=OLD.organization_id |
| 650 | AND collection='journalVouchers' |
| 651 | AND id=OLD.data->>'journalVoucherId'; |
| 652 | END IF; |
| 653 | RETURN OLD; |
| 654 | END IF; |
| 655 | |
| 656 | RETURN CASE WHEN TG_OP='DELETE' THEN OLD ELSE NEW END; |
| 657 | END $$; |
| 658 | |
| 659 | DROP TRIGGER IF EXISTS finora_journal_document_lifecycle_trg ON public.records; |
| 660 | CREATE TRIGGER finora_journal_document_lifecycle_trg |
| 661 | BEFORE INSERT OR UPDATE OR DELETE ON public.records |
| 662 | FOR EACH ROW EXECUTE FUNCTION public.finora_journal_document_lifecycle_trigger(); |
| 663 | |
| 664 | REVOKE ALL ON FUNCTION public.finora_journal_document_lifecycle_trigger() FROM PUBLIC, anon, authenticated; |