سامانه صدور فاکتور و حسابداری
test: prove conservative rollback for all ledger prerequisites
JVK committed
Nov 3, 2026 at 11:16 UTC
799cff4fcb1b9a98f763baf9e79a030c099deb58
19 files changed
+1037
-2
.github/workflows/wp1-ledger.yml
+5
-1
@@ -27,10 +27,14 @@ jobs:
27
run: node scripts/wp1-ledger-test.mjs green
28
- name: Verify correction migration UP DOWN UP and retained history
29
run: WP1_EVIDENCE_DIR=/tmp/finora-wp1-evidence/correction-cycle node scripts/wp1-correction-cycle.mjs
30
+ - name: Verify all prerequisite conservative DOWN and UP
31
+ run: node scripts/wp1-prerequisite-rollback.mjs
32
- name: Upload synthetic evidence
33
if: always()
34
uses: actions/upload-artifact@v4
35
with:
36
name: wp1-disposable-ledger-evidence
35
- path: /tmp/finora-wp1-evidence/
37
+ path: |
38
+ /tmp/finora-wp1-evidence/
39
+ docs/wp1/evidence/prerequisite-rollback/
40
retention-days: 14
PROJECT_STATE.md
+2
@@ -251,3 +251,5 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
251
- Owner explicitly approves continuation and asks to complete the phases. This supersedes the earlier WP0+WP1-only session scope; continue sequential package acceptance and maintain factual goal/in-progress/remaining docs. G1–G5 concrete owner gates remain; this is not approval to install an unreviewed Production migration. PR195head4b00e5b is still draft: Security/3DB success, full Quality and WP1proof running at this checkpoint. Proceed with remaining WP1 before declaring any later package complete.
252
- PR195 initialhead4b00e5b allrequiredCI SUCCESS: Quality41586514247,Security41586514251,WP1proof41586514303. WP1job05:53:25–06:07:08UTC completedbaselineRED,fullSQLsuite(includingseeded1000 andactualconcurrency)andcorrectionUP/DOWN/UP. Artifactdownload unavailable fromprovider; job/stepcompletion verifiedviaGitHubAPI; do notinventrawCIlogcounts. This supersedes interruptedlocal1000status for exact4b00e5b only.
253
- NewpurchaseguardRED→GREEN: enforce/network/malformedmode/accountswitchreject beforelocalreversal/save/sync; onlyconfirmedmissingRPC oroff/auditretainlegacycorrection. Browser28/28PASS incl3newnegativecases; generatedPages3/3PASS. Guard is safe refusal, NOT completedserverpurchasecorrection. Firstbrowserattemptfailedbecausefixtureorgwasaddedbeforeorganizationbootstrap; correctedfixturesetsorgafterready, noappAuthchange/assertionrelaxation. Newsourcechange notyetremoteCIverified.
254
+
255
+- Elevenprerequisite conservativeDOWNscripts generatedfromdisposable pre/postcatalogs andproved inreverseorder aftercorrectionDOWN. Restored71baselinefunctions/ACLs andpriortriggers; newAPIgrantsrevoked;4postedvouchers,10lines,10auditrows,counterhistory retainedbit-identically byhash. ReUPall12 thenD1/D2PASS. Source-derivedscope only; compatibleindexes/columns/inerthelpers retained intentionally. Proof scripts/wp1-prerequisite-rollback.mjs; evidence docs/wp1/evidence/prerequisite-rollback. CIstep added; finalheadCIpending.
docs/wp1/ROLLOUT_HOLD.md
+1
-1
@@ -8,7 +8,7 @@ Required before G1:
8
9
- Reconcile24/24historical migration-version drift by SQL content, and verify new columns/indexes/function contracts against the live catalog.
10
- Red/green tests for all corrective findings; actual concurrent posting;1000event trial balance; all suite and CI results at exact SHA.
11
-- Data-preserving rollback for EVERY staged migration plus the corrective migration; UP/DOWN/UP with posted rows/audit/counters retained. Reject rollback rather than merge independent company sequences incorrectly.
11
+- Conservative DOWN/UP for all11prerequisites pluscorrection is now locally proved:71baselinefunctiondefinitions/ACLs andbaseline triggers restored;4postedvouchers/10lines/10auditrows retained byhash; candidate APIs revoked, compatibleindexes/counters retained. Fresh exactheadCI andproductionparity remain gates. This is notpristineschema rollback.
12
- Capability-safe client integration; correct purchase correction/cancel transaction; no successful toast without server acknowledgement. Until proven, no enforcement cutover.
13
- Per-source shadow report including fieldscope/currency/period checks, not only aggregate balance. Existing11posted vouchers had zero anomalies in the limited aggregate audit; that is not full cutover approval.
14
- Read-only encrypted backup and disposable restore proof (G3secret viaenvironment), ordered verification queries, owner-reviewable G1 checklist.
docs/wp1/STATUS_FA.md
+2
@@ -24,3 +24,5 @@
24
روی کامیت `4b00e5b`، [Quality41586514247](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41586514247)،[Security41586514251](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41586514251) و [WP1 proof41586514303](https://github.com/davoodmehraban89/Factor-easy/actions/runs/41586514303) موفق شدند. فرمان کامل SQL شامل آزمون۱۰۰۰رویداد و همزمانی پایان یافت؛ این شاهد جایگزین اجرای محلی قطعشده است. دریافت artifact از provider ممکن نشد؛ نتیجه job/step در GitHub API تأیید شد، نه شمارش ساختگی لاگ.
25
26
محافظ جدید خرید قبل از تغییر محلی، حالت سرور را بررسی میکند: ENFORCE یا خطای شبکه/حالت نامعتبر/تعویض حساب، اصلاح و ابطال را بدون تغییر رد میکند. نبود صریح RPC یا off/audit مسیر قبلی را حفظ میکند.۲۸تست مرورگر و۳تست محافظ در Pages موفق؛ اجرای نهایی CI این تغییر جداست. این حفاظت معادل تکمیل عملیات اصلاح خرید روی سرور نیست.
27
+
28
+بازگشت محافظهکارانه هر۱۱پیشنیاز نیز اکنون در محیط مستقل موفق است:۷۱تعریف تابع/مجوز و تریگرهای قبلی بازگردانده شدند؛۴سند قطعی،۱۰ردیف و۱۰رویداد ممیزی و تاریخچه شمارنده بدون تغییر ماندند. پس از UP مجدد،D1/D2 موفقاند. ایندکسها و ساختارهای سازگار عمداً حفظ میشوند؛ همسانی با Production هنوز گیت جداست. [شاهد](evidence/prerequisite-rollback/result.json).
docs/wp1/evidence/prerequisite-rollback/catalog-baseline.json
new
+429
@@ -0,0 +1,429 @@
1
+{
2
+ "functions": {
3
+ "public.touch_updated_at()": {
4
+ "definition": "CREATE OR REPLACE FUNCTION public.touch_updated_at()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO 'public'\nAS $function$\nbegin new.updated_at := now(); return new; end $function$\n",
5
+ "grants": [
6
+ "PUBLIC"
7
+ ]
8
+ },
9
+ "public.is_admin()": {
10
+ "definition": "CREATE OR REPLACE FUNCTION public.is_admin()\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select exists (select 1 from public.profiles where id = auth.uid() and role = 'admin');\n$function$\n",
11
+ "grants": [
12
+ "authenticated",
13
+ "service_role"
14
+ ]
15
+ },
16
+ "private.invitation_token_hash(p_token text)": {
17
+ "definition": "CREATE OR REPLACE FUNCTION private.invitation_token_hash(p_token text)\n RETURNS text\n LANGUAGE sql\n IMMUTABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select encode(extensions.digest(convert_to(p_token,'UTF8'),'sha256'),'hex')\n$function$\n",
18
+ "grants": []
19
+ },
20
+ "public.admin_cancel_license(target uuid)": {
21
+ "definition": "CREATE OR REPLACE FUNCTION public.admin_cancel_license(target uuid)\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\nbegin\n if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;\n update public.licenses set status = 'cancelled', updated_at = now() where user_id = target;\n if not found then raise exception 'user not found'; end if;\nend $function$\n",
22
+ "grants": [
23
+ "authenticated",
24
+ "service_role"
25
+ ]
26
+ },
27
+ "public.finora_guard_phase5_posted_records()": {
28
+ "definition": "CREATE OR REPLACE FUNCTION public.finora_guard_phase5_posted_records()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO 'public'\nAS $function$\nbegin\n if old.collection not in ('stockMovements','inventoryCounts','assetDepreciations') or coalesce(old.data->>'status','') <> 'posted' then\n return case when tg_op='DELETE' then old else new end;\n end if;\n if tg_op='UPDATE' and new.data=old.data then return new; end if;\n raise exception 'posted Phase 5 operational record is immutable';\nend $function$\n",
29
+ "grants": [
30
+ "PUBLIC"
31
+ ]
32
+ },
33
+ "public.has_active_license()": {
34
+ "definition": "CREATE OR REPLACE FUNCTION public.has_active_license()\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select exists(select 1 from private.current_organization_ids() org_id where private.organization_has_module_entitlement(org_id,'core',true))\n$function$\n",
35
+ "grants": [
36
+ "authenticated",
37
+ "service_role"
38
+ ]
39
+ },
40
+ "public.admin_extend_license(target uuid, days integer)": {
41
+ "definition": "CREATE OR REPLACE FUNCTION public.admin_extend_license(target uuid, days integer)\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\nbegin\n if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;\n if days is null or days < 1 or days > 3650 then raise exception 'invalid days'; end if;\n update public.licenses\n set ends_at = greatest(ends_at, current_date) + days,\n plan = case when plan = 'trial' then 'monthly' else plan end,\n status = 'active',\n updated_at = now()\n where user_id = target and plan <> 'lifetime';\n if not found then raise exception 'user not found or lifetime'; end if;\nend $function$\n",
42
+ "grants": [
43
+ "authenticated",
44
+ "service_role"
45
+ ]
46
+ },
47
+ "public.admin_set_license(target uuid, new_plan text, days integer, new_status text)": {
48
+ "definition": "CREATE OR REPLACE FUNCTION public.admin_set_license(target uuid, new_plan text, days integer DEFAULT NULL::integer, new_status text DEFAULT 'active'::text)\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare d int;\nbegin\n if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;\n if new_plan not in ('trial','monthly','three_months','annual','lifetime') then raise exception 'invalid plan'; end if;\n d := coalesce(days, case new_plan when 'trial' then 15 when 'monthly' then 30 when 'three_months' then 90 when 'annual' then 365 else 0 end);\n update public.licenses\n set plan = new_plan,\n status = new_status,\n starts_at = current_date,\n ends_at = case when new_plan = 'lifetime' then date '2099-01-01' else current_date + d end,\n updated_at = now()\n where user_id = target;\n if not found then raise exception 'user not found'; end if;\nend $function$\n",
49
+ "grants": [
50
+ "authenticated",
51
+ "service_role"
52
+ ]
53
+ },
54
+ "public.finora_guard_posted_journal()": {
55
+ "definition": "CREATE OR REPLACE FUNCTION public.finora_guard_posted_journal()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO 'public'\nAS $function$\ndeclare\n old_status text := old.data->>'status';\n new_status text;\nbegin\n if old.collection <> 'journalVouchers' or old_status not in ('posted','reversed') then\n return case when tg_op='DELETE' then old else new end;\n end if;\n if tg_op='DELETE' then raise exception 'posted/reversed journal voucher is immutable'; end if;\n new_status := new.data->>'status';\n if old_status='posted' and new_status='reversed'\n and (old.data - array['status','reversalVoucherId','reversedAt']) =\n (new.data - array['status','reversalVoucherId','reversedAt'])\n and coalesce(new.data->>'reversalVoucherId','') <> '' then\n return new;\n end if;\n if new.data = old.data then return new; end if;\n raise exception 'posted/reversed journal voucher is immutable';\nend $function$\n",
56
+ "grants": [
57
+ "PUBLIC"
58
+ ]
59
+ },
60
+ "public.finora_guard_posted_journal_children()": {
61
+ "definition": "CREATE OR REPLACE FUNCTION public.finora_guard_posted_journal_children()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO 'public'\nAS $function$\ndeclare vid text; parent_status text;\nbegin\n if old.collection not in ('journalLines','journalLineDimensions') then return case when tg_op='DELETE' then old else new end; end if;\n vid := old.data->>'voucherId';\n select r.data->>'status' into parent_status\n from public.records r\n where r.owner_id=old.owner_id and r.collection='journalVouchers' and r.id=vid;\n if parent_status in ('posted','reversed') then raise exception 'posted/reversed journal lines are immutable'; end if;\n return case when tg_op='DELETE' then old else new end;\nend $function$\n",
62
+ "grants": [
63
+ "PUBLIC"
64
+ ]
65
+ },
66
+ "public.finora_enforce_company_license_limit()": {
67
+ "definition": "CREATE OR REPLACE FUNCTION public.finora_enforce_company_license_limit()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare allowed_count integer; actual_count integer;\nbegin\n if new.collection<>'companies' then return new; end if;\n\n select l.max_companies into allowed_count\n from public.licenses l\n where l.organization_id=new.organization_id\n for update;\n\n if allowed_count is null then raise exception 'organization license not found' using errcode='23503'; end if;\n\n select count(*)::integer into actual_count\n from public.records r\n where r.organization_id=new.organization_id and r.collection='companies';\n\n if actual_count>allowed_count then\n raise exception 'company license limit exceeded' using errcode='23514';\n end if;\n return new;\nend $function$\n",
68
+ "grants": []
69
+ },
70
+ "public.admin_set_license_modules(target uuid, new_modules text[])": {
71
+ "definition": "CREATE OR REPLACE FUNCTION public.admin_set_license_modules(target uuid, new_modules text[])\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare normalized text[];\nbegin\n if not public.is_admin() then raise exception 'forbidden' using errcode = '42501'; end if;\n if new_modules is null or cardinality(new_modules)=0 then raise exception 'at least one module is required'; end if;\n if exists (select 1 from unnest(new_modules) m where not private.is_valid_finora_module(m)) then\n raise exception 'invalid module entitlement';\n end if;\n if 'full_suite' = any(new_modules) then normalized := array['full_suite']::text[];\n else select array_agg(distinct m order by m) into normalized from unnest(new_modules) m;\n end if;\n update public.licenses set modules=normalized, updated_at=now() where user_id=target;\n if not found then raise exception 'user not found'; end if;\nend\n$function$\n",
72
+ "grants": [
73
+ "authenticated",
74
+ "service_role"
75
+ ]
76
+ },
77
+ "public.finora_guard_posted_source_records()": {
78
+ "definition": "CREATE OR REPLACE FUNCTION public.finora_guard_posted_source_records()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO 'public'\nAS $function$\ndeclare vid text:=coalesce(old.data->>'journalVoucherId',''); voucher_status text:=''; source_locked boolean:=false;\nbegin\n if old.collection not in ('invoices','purchases','payments','expenses','cheques','contractStatements','payrollRuns','employeeBenefitAccruals','pettyCashTransactions') then return case when tg_op='DELETE' then old else new end; end if;\n if vid<>'' then select coalesce(r.data->>'status','') into voucher_status from public.records r where r.owner_id=old.owner_id and r.collection='journalVouchers' and r.id=vid; end if;\n source_locked:=coalesce(old.data->>'accountingStatus','')='posted' or (old.collection='cheques' and coalesce(old.data->>'status','') in ('cleared','bounced','cancelled')) or (old.collection='contractStatements' and coalesce(old.data->>'status','') in ('posted','reversed')) or (old.collection in ('payrollRuns','employeeBenefitAccruals','pettyCashTransactions') and coalesce(old.data->>'status','') in ('posted','reversed')) or voucher_status in ('posted','reversed');\n if not source_locked then return case when tg_op='DELETE' then old else new end; end if;\n if tg_op='UPDATE' and new.data=old.data then return new; end if;\n raise exception 'source record linked to posted/reversed accounting history is immutable';\nend $function$\n",
79
+ "grants": [
80
+ "PUBLIC"
81
+ ]
82
+ },
83
+ "private.is_valid_finora_module(module_key text)": {
84
+ "definition": "CREATE OR REPLACE FUNCTION private.is_valid_finora_module(module_key text)\n RETURNS boolean\n LANGUAGE sql\n IMMUTABLE\n SET search_path TO ''\nAS $function$\n select module_key = any(array[\n 'full_suite','core','accounting','commerce','treasury','contracting','inventory','assets',\n 'hr_payroll','office_automation','requests_workflow','crm','transport','manufacturing',\n 'maintenance','group_consolidation','analytics'\n ]::text[])\n$function$\n",
85
+ "grants": [
86
+ "authenticated"
87
+ ]
88
+ },
89
+ "private.collection_module(collection_key text)": {
90
+ "definition": "CREATE OR REPLACE FUNCTION private.collection_module(collection_key text)\n RETURNS text\n LANGUAGE sql\n IMMUTABLE\n SET search_path TO ''\nAS $function$\n select case\n when collection_key = any(array['companies','settings','importBatches','integrationConnections','integrationOutbox','phase5Audit','enterpriseAudit']::text[]) then 'core'\n when collection_key = any(array['fiscalYears','accounts','dimensionTypes','dimensionValues','accountDimensionRules','branches','postingProfiles','journalVouchers','journalLines','journalLineDimensions','currencies','exchangeRates','costCenters','expenses','complianceRules','budgets','costDrivers','costAllocations']::text[]) then 'accounting'\n when collection_key = any(array['contacts','products','invoices','purchases']::text[]) then 'commerce'\n when collection_key = any(array['cheques','payments','cashboxes','pettyCashFunds','pettyCashTransactions']::text[]) then 'treasury'\n when collection_key = any(array['projects','projectLinks','contracts','contractAmendments','contractParties','contractDeductions','guarantees','guaranteeEvents','contractStatements','phase4Audit']::text[]) then 'contracting'\n when collection_key = any(array['warehouses','stockMovements','inventoryCounts']::text[]) then 'inventory'\n when collection_key = any(array['fixedAssets','assetDepreciations']::text[]) then 'assets'\n when collection_key = any(array['employees','employmentContracts','employeeLeave','payrollRuns','payrollLines','employeeBenefitAccruals']::text[]) then 'hr_payroll'\n when collection_key = 'intercompanyTransactions' then 'group_consolidation'\n when collection_key = any(array['officeRegistries','correspondence','correspondenceAttachments','correspondenceReferrals','correspondenceAudit']::text[]) then 'office_automation'\n when collection_key = any(array['requestTypes','requests','requestActions']::text[]) then 'requests_workflow'\n else null\n end\n$function$\n",
91
+ "grants": [
92
+ "authenticated"
93
+ ]
94
+ },
95
+ "private.has_collection_entitlement(collection_key text)": {
96
+ "definition": "CREATE OR REPLACE FUNCTION private.has_collection_entitlement(collection_key text)\n RETURNS boolean\n LANGUAGE sql\n STABLE\n SET search_path TO ''\nAS $function$\n select coalesce(private.has_module_entitlement(private.collection_module(collection_key)), false)\n$function$\n",
97
+ "grants": [
98
+ "authenticated"
99
+ ]
100
+ },
101
+ "private.has_org_capability(p_organization_id uuid, p_module_key text, p_capability text)": {
102
+ "definition": "CREATE OR REPLACE FUNCTION private.has_org_capability(p_organization_id uuid, p_module_key text, p_capability text)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select exists(\n select 1\n from public.organization_members m\n where m.organization_id=p_organization_id\n and m.user_id=(select auth.uid())\n and m.status='active'\n and (\n (p_module_key='core' and p_capability='read')\n or m.is_owner\n or exists(\n select 1 from public.member_module_permissions p\n where p.organization_id=p_organization_id and p.member_id=m.id\n and (p.module_key=p_module_key or p.module_key='full_suite')\n and p_capability=any(p.capabilities)\n )\n or exists(\n select 1\n from public.organization_member_roles mr\n join public.organization_roles r on r.id=mr.role_id and r.organization_id=mr.organization_id and r.active\n join public.organization_role_permissions rp on rp.role_id=r.id and rp.organization_id=r.organization_id\n where mr.organization_id=p_organization_id and mr.member_id=m.id and mr.active\n and (rp.module_key=p_module_key or rp.module_key='full_suite')\n and p_capability=any(rp.capabilities)\n )\n )\n )\n$function$\n",
103
+ "grants": [
104
+ "authenticated"
105
+ ]
106
+ },
107
+ "private.has_module_entitlement(module_key text)": {
108
+ "definition": "CREATE OR REPLACE FUNCTION private.has_module_entitlement(module_key text)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select case when module_key='core' then true else exists(select 1 from private.current_organization_ids() org_id where private.organization_has_module_entitlement(org_id,module_key,false)) end\n$function$\n",
109
+ "grants": [
110
+ "authenticated"
111
+ ]
112
+ },
113
+ "private.current_organization_ids()": {
114
+ "definition": "CREATE OR REPLACE FUNCTION private.current_organization_ids()\n RETURNS SETOF uuid\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select m.organization_id from public.organization_members m where m.user_id=(select auth.uid()) and m.status='active'\n$function$\n",
115
+ "grants": [
116
+ "authenticated"
117
+ ]
118
+ },
119
+ "private.default_organization_id()": {
120
+ "definition": "CREATE OR REPLACE FUNCTION private.default_organization_id()\n RETURNS uuid\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select m.organization_id from public.organization_members m where m.user_id=(select auth.uid()) and m.status='active' order by m.is_owner desc,m.created_at,m.organization_id limit 1\n$function$\n",
121
+ "grants": [
122
+ "authenticated"
123
+ ]
124
+ },
125
+ "public.office_register_correspondence(p_id text, p_registry_id text, p_payload jsonb)": {
126
+ "definition": "CREATE OR REPLACE FUNCTION public.office_register_correspondence(p_id text, p_registry_id text, p_payload jsonb)\n RETURNS text\n LANGUAGE plpgsql\n SET search_path TO 'public'\nAS $function$\ndeclare\n registry_row public.records%rowtype;\n next_no integer;\n prefix text;\n assigned text;\nbegin\n if auth.uid() is null then raise exception 'authentication required'; end if;\n if not public.has_active_license() or not private.has_module_entitlement('office_automation') then\n raise exception 'office automation entitlement required' using errcode='42501';\n end if;\n if p_id is null or p_id !~ '^[A-Za-z0-9_-]{1,64}$' then raise exception 'invalid correspondence id'; end if;\n if p_registry_id is null or p_registry_id !~ '^[A-Za-z0-9_-]{1,64}$' then raise exception 'invalid registry id'; end if;\n if p_payload is null or jsonb_typeof(p_payload) <> 'object' then raise exception 'invalid payload'; end if;\n\n select * into registry_row\n from public.records\n where owner_id=auth.uid() and collection='officeRegistries' and id=p_registry_id\n for update;\n if not found then raise exception 'registry not found'; end if;\n\n next_no := greatest(1,coalesce(nullif(registry_row.data->>'nextNumber','')::integer,1));\n prefix := trim(coalesce(registry_row.data->>'prefix',''));\n assigned := case when prefix='' then next_no::text else prefix||'-'||next_no::text end;\n\n update public.records\n set data=jsonb_set(registry_row.data,'{nextNumber}',to_jsonb(next_no+1),true)\n where owner_id=auth.uid() and collection='officeRegistries' and id=p_registry_id;\n\n insert into public.records(owner_id,collection,id,data)\n values(auth.uid(),'correspondence',p_id,\n p_payload || jsonb_build_object(\n 'registryId',p_registry_id,\n 'registerNumber',assigned,\n 'status','registered',\n 'registeredAt',now()\n ))\n on conflict(owner_id,collection,id) do update\n set data = case\n when public.records.data->>'status'='registered' then public.records.data\n else excluded.data\n end;\n\n return assigned;\nend\n$function$\n",
127
+ "grants": [
128
+ "authenticated"
129
+ ]
130
+ },
131
+ "public.finora_sync_records(p_upserts jsonb, p_deletes jsonb)": {
132
+ "definition": "CREATE OR REPLACE FUNCTION public.finora_sync_records(p_upserts jsonb DEFAULT '[]'::jsonb, p_deletes jsonb DEFAULT '[]'::jsonb)\n RETURNS void\n LANGUAGE plpgsql\n SET search_path TO 'public'\nAS $function$\nbegin\n if auth.uid() is null then raise exception 'authentication required'; end if;\n if not public.has_active_license() then raise exception 'active license required'; end if;\n if exists (\n select 1 from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb)\n where not private.has_collection_entitlement(x.collection)\n ) or exists (\n select 1 from jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text)\n where not private.has_collection_entitlement(d.collection)\n ) then raise exception 'module entitlement required' using errcode='42501'; end if;\n\n insert into public.records(owner_id, collection, id, data)\n select auth.uid(), x.collection, x.id, x.data\n from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb)\n on conflict (owner_id,collection,id) do update set data=excluded.data;\n\n delete from public.records r\n using jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text)\n where r.owner_id=auth.uid() and r.collection=d.collection and r.id=d.id;\nend $function$\n",
133
+ "grants": [
134
+ "authenticated"
135
+ ]
136
+ },
137
+ "private.enforce_organization_member_seat()": {
138
+ "definition": "CREATE OR REPLACE FUNCTION private.enforce_organization_member_seat()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_limit integer; v_active integer;\nbegin\n if new.status<>'active' then return new; end if;\n if tg_op='UPDATE' and old.status='active' and old.organization_id=new.organization_id then return new; end if;\n\n select l.max_users into v_limit\n from public.licenses l\n where l.organization_id=new.organization_id\n for update;\n\n if v_limit is null then\n raise exception 'organization license not found' using errcode='23503';\n end if;\n\n select count(*)::integer into v_active\n from public.organization_members m\n where m.organization_id=new.organization_id\n and m.status='active'\n and (tg_op='INSERT' or m.id<>new.id);\n\n if v_active >= v_limit then\n raise exception 'named-user seat limit exceeded' using errcode='23514';\n end if;\n return new;\nend $function$\n",
139
+ "grants": []
140
+ },
141
+ "private.organization_active_member_count(p_organization_id uuid)": {
142
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_active_member_count(p_organization_id uuid)\n RETURNS integer\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select count(*)::integer\n from public.organization_members m\n where m.organization_id=p_organization_id and m.status='active'\n$function$\n",
143
+ "grants": [
144
+ "authenticated"
145
+ ]
146
+ },
147
+ "private.is_org_owner(p_organization_id uuid)": {
148
+ "definition": "CREATE OR REPLACE FUNCTION private.is_org_owner(p_organization_id uuid)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select exists(select 1 from public.organization_members m where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active' and m.is_owner)\n$function$\n",
149
+ "grants": [
150
+ "authenticated"
151
+ ]
152
+ },
153
+ "private.organization_has_module_entitlement(p_organization_id uuid, p_module_key text, p_require_active boolean)": {
154
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_has_module_entitlement(p_organization_id uuid, p_module_key text, p_require_active boolean DEFAULT false)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select case when p_module_key='core' and not p_require_active then true else exists(\n select 1 from public.licenses l where l.organization_id=p_organization_id\n and (p_module_key='core' or 'full_suite'=any(l.modules) or p_module_key=any(l.modules))\n and (not p_require_active or (l.status in ('trial','active') and (l.plan='lifetime' or l.ends_at >= (now() at time zone 'Asia/Tehran')::date)))\n ) end\n$function$\n",
155
+ "grants": [
156
+ "authenticated"
157
+ ]
158
+ },
159
+ "private.can_access_record(p_organization_id uuid, p_collection text, p_owner_id uuid, p_data jsonb, p_capability text)": {
160
+ "definition": "CREATE OR REPLACE FUNCTION private.can_access_record(p_organization_id uuid, p_collection text, p_owner_id uuid, p_data jsonb, p_capability text)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select p_organization_id in (select private.current_organization_ids()) and private.organization_has_module_entitlement(p_organization_id,private.collection_module(p_collection),false) and private.has_org_capability(p_organization_id,private.collection_module(p_collection),p_capability) and private.record_in_member_scope(p_organization_id,private.collection_module(p_collection),p_owner_id,p_data,p_capability) and private.record_confidentiality_allowed(p_organization_id,private.collection_module(p_collection),p_data)\n$function$\n",
161
+ "grants": [
162
+ "authenticated"
163
+ ]
164
+ },
165
+ "private.has_any_configure(p_organization_id uuid)": {
166
+ "definition": "CREATE OR REPLACE FUNCTION private.has_any_configure(p_organization_id uuid)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select private.is_org_owner(p_organization_id) or exists(select 1 from public.organization_members m join public.member_module_permissions p on p.member_id=m.id and p.organization_id=m.organization_id where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active' and 'configure'=any(p.capabilities))\n$function$\n",
167
+ "grants": [
168
+ "authenticated"
169
+ ]
170
+ },
171
+ "private.organization_has_seat(p_organization_id uuid, p_excluding_member uuid)": {
172
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_has_seat(p_organization_id uuid, p_excluding_member uuid DEFAULT NULL::uuid)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select coalesce((\n select (\n select count(*)\n from public.organization_members m\n where m.organization_id=p_organization_id\n and m.status='active'\n and (p_excluding_member is null or m.id<>p_excluding_member)\n ) < l.max_users\n from public.licenses l\n where l.organization_id=p_organization_id\n ), false)\n$function$\n",
173
+ "grants": [
174
+ "authenticated"
175
+ ]
176
+ },
177
+ "public.admin_set_user_limit(target uuid, new_max_users integer)": {
178
+ "definition": "CREATE OR REPLACE FUNCTION public.admin_set_user_limit(target uuid, new_max_users integer)\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid; v_active integer;\nbegin\n if not public.is_admin() then raise exception 'forbidden' using errcode='42501'; end if;\n if new_max_users is null or new_max_users<1 or new_max_users>100000 then raise exception 'invalid user limit'; end if;\n\n select l.organization_id into v_org\n from public.licenses l where l.user_id=target\n for update;\n if v_org is null then raise exception 'user/license not found'; end if;\n\n select count(*)::integer into v_active\n from public.organization_members m\n where m.organization_id=v_org and m.status='active';\n\n if new_max_users<v_active then raise exception 'user limit below active member count'; end if;\n\n update public.licenses\n set max_users=new_max_users,updated_at=now()\n where user_id=target;\nend $function$\n",
179
+ "grants": [
180
+ "authenticated",
181
+ "service_role"
182
+ ]
183
+ },
184
+ "private.organization_audit_immutable()": {
185
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_audit_immutable()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$ begin raise exception 'organization audit is immutable' using errcode='42501'; end $function$\n",
186
+ "grants": []
187
+ },
188
+ "public.finora_sync_records(p_upserts jsonb, p_deletes jsonb, p_organization_id uuid)": {
189
+ "definition": "CREATE OR REPLACE FUNCTION public.finora_sync_records(p_upserts jsonb DEFAULT '[]'::jsonb, p_deletes jsonb DEFAULT '[]'::jsonb, p_organization_id uuid DEFAULT NULL::uuid)\n RETURNS void\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid:=coalesce(p_organization_id,private.default_organization_id());\nbegin\n if (select auth.uid()) is null then raise exception 'authentication required'; end if;\n if v_org is null or v_org not in (select private.current_organization_ids()) then raise exception 'organization membership required' using errcode='42501'; end if;\n if not private.organization_has_module_entitlement(v_org,'core',true) then raise exception 'active license required' using errcode='42501'; end if;\n if exists(select 1 from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb) where not private.organization_has_module_entitlement(v_org,private.collection_module(x.collection),true)) or exists(select 1 from jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text) where not private.organization_has_module_entitlement(v_org,private.collection_module(d.collection),true)) then raise exception 'module entitlement required' using errcode='42501'; end if;\n insert into public.records(organization_id,owner_id,collection,id,data) select v_org,(select auth.uid()),x.collection,x.id,x.data from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb) on conflict (organization_id,collection,id) do update set data=excluded.data;\n delete from public.records r using jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text) where r.organization_id=v_org and r.collection=d.collection and r.id=d.id;\nend $function$\n",
190
+ "grants": [
191
+ "authenticated"
192
+ ]
193
+ },
194
+ "private.organization_audit_capture()": {
195
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_audit_capture()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid; v_action text; v_entity text; v_entity_id text;\nbegin\n if tg_table_name='member_module_permissions' then\n v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;\n v_action:='permission_'||lower(tg_op);\n v_entity:='member_module_permission';\n v_entity_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;\n elsif tg_table_name='organization_members' then\n v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;\n v_action:='membership_'||lower(tg_op);\n v_entity:='organization_member';\n v_entity_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;\n elsif tg_table_name='records' then\n v_org:=new.organization_id;\n v_action:='referral_insert';\n v_entity:='correspondence_referral';\n v_entity_id:=new.id;\n else\n if tg_op='DELETE' then return old; else return new; end if;\n end if;\n\n insert into public.organization_audit(\n organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data\n )\n values(\n v_org,(select auth.uid()),v_action,v_entity,v_entity_id,\n case when tg_op in ('UPDATE','DELETE') then to_jsonb(old) else null end,\n case when tg_op in ('INSERT','UPDATE') then to_jsonb(new) else null end\n );\n\n if tg_op='DELETE' then return old; else return new; end if;\nend $function$\n",
196
+ "grants": []
197
+ },
198
+ "private.enforce_invitation_role_tenant_integrity()": {
199
+ "definition": "CREATE OR REPLACE FUNCTION private.enforce_invitation_role_tenant_integrity()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\nbegin\n if not exists(\n select 1 from public.organization_invitations i\n where i.id=new.invitation_id and i.organization_id=new.organization_id\n ) then raise exception 'invitation/organization mismatch' using errcode='23514'; end if;\n if not exists(\n select 1 from public.organization_roles r\n where r.id=new.role_id and r.organization_id=new.organization_id and r.active\n ) then raise exception 'role/organization mismatch' using errcode='23514'; end if;\n return new;\nend $function$\n",
200
+ "grants": []
201
+ },
202
+ "public.organization_create_invitation(p_organization_id uuid, p_email text, p_unit_id uuid, p_position_title text, p_role_ids uuid[], p_expires_hours integer)": {
203
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_create_invitation(p_organization_id uuid, p_email text, p_unit_id uuid DEFAULT NULL::uuid, p_position_title text DEFAULT NULL::text, p_role_ids uuid[] DEFAULT '{}'::uuid[], p_expires_hours integer DEFAULT 168)\n RETURNS jsonb\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare\n v_email text:=lower(trim(coalesce(p_email,'')));\n v_token text;\n v_hash text;\n v_id uuid;\n v_role uuid;\nbegin\n if (select auth.uid()) is null then raise exception 'authentication required' using errcode='42501'; end if;\n if not (\n private.is_org_owner(p_organization_id)\n or private.has_org_capability(p_organization_id,'core','configure')\n ) then raise exception 'forbidden' using errcode='42501'; end if;\n if not private.organization_has_module_entitlement(p_organization_id,'core',true) then\n raise exception 'organization license inactive' using errcode='42501';\n end if;\n if v_email='' or v_email not like '%@%' then raise exception 'invalid email'; end if;\n if p_expires_hours is null or p_expires_hours<1 or p_expires_hours>720 then raise exception 'invalid expiry'; end if;\n if p_unit_id is not null and not exists(\n select 1 from public.organization_units u\n where u.id=p_unit_id and u.organization_id=p_organization_id and u.active\n ) then raise exception 'invalid organization unit'; end if;\n\n if exists(\n select 1 from public.organization_members m\n join public.profiles p on p.id=m.user_id\n where m.organization_id=p_organization_id and lower(p.email)=v_email and m.status='active'\n ) then raise exception 'user is already an active member'; end if;\n\n update public.organization_invitations\n set status='revoked',revoked_at=now(),updated_at=now()\n where organization_id=p_organization_id and email_normalized=v_email and status='pending';\n\n v_token:=encode(extensions.gen_random_bytes(32),'hex');\n v_hash:=private.invitation_token_hash(v_token);\n\n insert into public.organization_invitations(\n organization_id,email_normalized,unit_id,position_title,token_hash,status,expires_at,invited_by\n )\n values(\n p_organization_id,v_email,p_unit_id,nullif(trim(p_position_title),''),\n v_hash,'pending',now()+make_interval(hours=>p_expires_hours),(select auth.uid())\n )\n returning id into v_id;\n\n foreach v_role in array coalesce(p_role_ids,'{}'::uuid[]) loop\n if not exists(\n select 1 from public.organization_roles r\n where r.id=v_role and r.organization_id=p_organization_id and r.active\n ) then raise exception 'invalid invitation role'; end if;\n insert into public.organization_invitation_roles(organization_id,invitation_id,role_id)\n values(p_organization_id,v_id,v_role);\n end loop;\n\n return jsonb_build_object('invitation_id',v_id,'token',v_token,'expires_at',now()+make_interval(hours=>p_expires_hours));\nend $function$\n",
204
+ "grants": [
205
+ "authenticated"
206
+ ]
207
+ },
208
+ "public.office_register_correspondence(p_id text, p_registry_id text, p_payload jsonb, p_organization_id uuid)": {
209
+ "definition": "CREATE OR REPLACE FUNCTION public.office_register_correspondence(p_id text, p_registry_id text, p_payload jsonb, p_organization_id uuid DEFAULT NULL::uuid)\n RETURNS text\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid:=coalesce(p_organization_id,private.default_organization_id()); registry_row public.records%rowtype; next_no integer; prefix text; assigned text;\nbegin\n if (select auth.uid()) is null then raise exception 'authentication required'; end if;\n if v_org is null or not private.organization_has_module_entitlement(v_org,'office_automation',true) or not private.has_org_capability(v_org,'office_automation','register') then raise exception 'forbidden' using errcode='42501'; end if;\n if p_id is null or p_id !~ '^[A-Za-z0-9_-]{1,64}$' then raise exception 'invalid correspondence id'; end if;\n if p_registry_id is null or p_registry_id !~ '^[A-Za-z0-9_-]{1,64}$' then raise exception 'invalid registry id'; end if;\n if p_payload is null or jsonb_typeof(p_payload)<>'object' then raise exception 'invalid payload'; end if;\n select * into registry_row from public.records where organization_id=v_org and collection='officeRegistries' and id=p_registry_id for update;\n if not found then raise exception 'registry not found'; end if;\n next_no:=greatest(1,coalesce(nullif(registry_row.data->>'nextNumber','')::integer,1));\n prefix:=trim(coalesce(registry_row.data->>'prefix',''));\n assigned:=case when prefix='' then next_no::text else prefix||'-'||next_no::text end;\n update public.records set data=jsonb_set(registry_row.data,'{nextNumber}',to_jsonb(next_no+1),true) where organization_id=v_org and collection='officeRegistries' and id=p_registry_id;\n insert into public.records(organization_id,owner_id,collection,id,data) values(v_org,(select auth.uid()),'correspondence',p_id,p_payload||jsonb_build_object('registryId',p_registry_id,'registerNumber',assigned,'status','registered','registeredAt',now()))\n on conflict(organization_id,collection,id) do update set data=case when public.records.data->>'status'='registered' then public.records.data else excluded.data end;\n return assigned;\nend $function$\n",
210
+ "grants": [
211
+ "authenticated"
212
+ ]
213
+ },
214
+ "public.admin_set_company_limit(target uuid, new_max_companies integer)": {
215
+ "definition": "CREATE OR REPLACE FUNCTION public.admin_set_company_limit(target uuid, new_max_companies integer)\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid; existing_count integer;\nbegin\n if not public.is_admin() then raise exception 'forbidden' using errcode='42501'; end if;\n if new_max_companies is null or new_max_companies<1 or new_max_companies>1000 then raise exception 'invalid company limit'; end if;\n\n select l.organization_id into v_org\n from public.licenses l where l.user_id=target\n for update;\n if v_org is null then raise exception 'user/license not found'; end if;\n\n select count(*)::integer into existing_count\n from public.records r\n where r.organization_id=v_org and r.collection='companies';\n\n if existing_count>new_max_companies then raise exception 'company limit below existing company count'; end if;\n\n update public.licenses\n set max_companies=new_max_companies,updated_at=now()\n where user_id=target;\nend $function$\n",
216
+ "grants": [
217
+ "authenticated",
218
+ "service_role"
219
+ ]
220
+ },
221
+ "private.profile_id_by_email(p_email text)": {
222
+ "definition": "CREATE OR REPLACE FUNCTION private.profile_id_by_email(p_email text)\n RETURNS uuid\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$ select p.id from public.profiles p where lower(p.email)=lower(trim(p_email)) limit 1 $function$\n",
223
+ "grants": [
224
+ "authenticated"
225
+ ]
226
+ },
227
+ "public.organization_add_member(p_organization_id uuid, p_email text, p_unit_id uuid, p_position_title text)": {
228
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_add_member(p_organization_id uuid, p_email text, p_unit_id uuid DEFAULT NULL::uuid, p_position_title text DEFAULT NULL::text)\n RETURNS uuid\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare v_user uuid; v_member uuid;\nbegin\n if not (\n private.is_org_owner(p_organization_id)\n or private.has_org_capability(p_organization_id,'core','configure')\n ) then raise exception 'forbidden' using errcode='42501'; end if;\n\n v_user:=private.profile_id_by_email(p_email);\n if v_user is null then raise exception 'Finora user not found for email'; end if;\n\n if p_unit_id is not null and not exists(\n select 1 from public.organization_units u\n where u.id=p_unit_id and u.organization_id=p_organization_id and u.active\n ) then raise exception 'invalid organization unit'; end if;\n\n insert into public.organization_members(organization_id,user_id,unit_id,position_title,status,is_owner)\n values(p_organization_id,v_user,p_unit_id,nullif(trim(p_position_title),''),'active',false)\n on conflict(organization_id,user_id) do update\n set unit_id=excluded.unit_id,\n position_title=excluded.position_title,\n status='active',\n updated_at=now()\n where not public.organization_members.is_owner\n returning id into v_member;\n\n if v_member is null then raise exception 'owner membership cannot be replaced'; end if;\n return v_member;\nend $function$\n",
229
+ "grants": [
230
+ "authenticated"
231
+ ]
232
+ },
233
+ "private.protect_office_evidence_insert()": {
234
+ "definition": "CREATE OR REPLACE FUNCTION private.protect_office_evidence_insert()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\nbegin\n if new.collection in ('correspondenceReferrals','correspondenceAudit')\n and current_user not in ('postgres','service_role')\n then\n raise exception 'office evidence must be created by an authorized server operation' using errcode='42501';\n end if;\n return new;\nend $function$\n",
235
+ "grants": []
236
+ },
237
+ "public.organization_set_member_status(p_organization_id uuid, p_member_id uuid, p_status text)": {
238
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_set_member_status(p_organization_id uuid, p_member_id uuid, p_status text)\n RETURNS void\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\nbegin\n if p_status not in ('active','suspended','left') then raise exception 'invalid member status'; end if;\n if not (\n private.is_org_owner(p_organization_id)\n or private.has_org_capability(p_organization_id,'core','configure')\n ) then raise exception 'forbidden' using errcode='42501'; end if;\n\n update public.organization_members m\n set status=p_status,updated_at=now()\n where m.id=p_member_id and m.organization_id=p_organization_id and not m.is_owner;\n\n if not found then raise exception 'member not found or owner status is protected'; end if;\nend $function$\n",
239
+ "grants": [
240
+ "authenticated"
241
+ ]
242
+ },
243
+ "private.protect_system_organization_role()": {
244
+ "definition": "CREATE OR REPLACE FUNCTION private.protect_system_organization_role()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\nbegin\n if tg_op='DELETE' and old.is_system then\n raise exception 'system role cannot be deleted' using errcode='42501';\n end if;\n if tg_op='UPDATE' and old.is_system and (new.role_key<>old.role_key or not new.is_system) then\n raise exception 'system role identity is immutable' using errcode='42501';\n end if;\n if tg_op='DELETE' then return old; else return new; end if;\nend $function$\n",
245
+ "grants": []
246
+ },
247
+ "public.organization_upsert_role(p_organization_id uuid, p_role_key text, p_title text, p_description text, p_active boolean)": {
248
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_upsert_role(p_organization_id uuid, p_role_key text, p_title text, p_description text DEFAULT NULL::text, p_active boolean DEFAULT true)\n RETURNS uuid\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare v_id uuid;\nbegin\n if not (private.is_org_owner(p_organization_id) or private.has_org_capability(p_organization_id,'core','configure')) then\n raise exception 'forbidden' using errcode='42501';\n end if;\n if p_role_key is null or p_role_key !~ '^[a-z][a-z0-9_]{1,63}$' then raise exception 'invalid role key'; end if;\n if nullif(trim(p_title),'') is null then raise exception 'role title required'; end if;\n\n insert into public.organization_roles(organization_id,role_key,title,description,active,created_by)\n values(p_organization_id,p_role_key,trim(p_title),nullif(trim(p_description),''),coalesce(p_active,true),(select auth.uid()))\n on conflict(organization_id,role_key) do update\n set title=excluded.title,\n description=excluded.description,\n active=excluded.active,\n updated_at=now()\n returning id into v_id;\n return v_id;\nend $function$\n",
249
+ "grants": [
250
+ "authenticated"
251
+ ]
252
+ },
253
+ "private.role_permission_allowed(p_organization_id uuid, p_module_key text)": {
254
+ "definition": "CREATE OR REPLACE FUNCTION private.role_permission_allowed(p_organization_id uuid, p_module_key text)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select case\n when p_module_key='core' then true\n when p_module_key='full_suite' then private.organization_has_module_entitlement(p_organization_id,'full_suite',false)\n else private.organization_has_module_entitlement(p_organization_id,p_module_key,false)\n end\n$function$\n",
255
+ "grants": [
256
+ "authenticated"
257
+ ]
258
+ },
259
+ "public.organization_set_role_permission(p_organization_id uuid, p_role_id uuid, p_module_key text, p_capabilities text[], p_scope_type text, p_scope_id text, p_confidentiality_level smallint)": {
260
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_set_role_permission(p_organization_id uuid, p_role_id uuid, p_module_key text, p_capabilities text[], p_scope_type text DEFAULT 'organization'::text, p_scope_id text DEFAULT NULL::text, p_confidentiality_level smallint DEFAULT 0)\n RETURNS uuid\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare v_id uuid;\nbegin\n if not (private.is_org_owner(p_organization_id) or private.has_org_capability(p_organization_id,'core','configure')) then\n raise exception 'forbidden' using errcode='42501';\n end if;\n if not exists(select 1 from public.organization_roles r where r.id=p_role_id and r.organization_id=p_organization_id and r.active) then\n raise exception 'role not found';\n end if;\n if not private.role_permission_allowed(p_organization_id,p_module_key) then\n raise exception 'module not licensed' using errcode='42501';\n end if;\n\n insert into public.organization_role_permissions(\n organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level\n )\n values(\n p_organization_id,p_role_id,p_module_key,p_capabilities,p_scope_type,p_scope_id,p_confidentiality_level\n )\n on conflict(organization_id,role_id,module_key,scope_type,scope_id) do update\n set capabilities=excluded.capabilities,\n confidentiality_level=excluded.confidentiality_level,\n updated_at=now()\n returning id into v_id;\n return v_id;\nend $function$\n",
261
+ "grants": [
262
+ "authenticated"
263
+ ]
264
+ },
265
+ "public.organization_assign_member_role(p_organization_id uuid, p_member_id uuid, p_role_id uuid, p_active boolean)": {
266
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_assign_member_role(p_organization_id uuid, p_member_id uuid, p_role_id uuid, p_active boolean DEFAULT true)\n RETURNS uuid\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare v_id uuid;\nbegin\n if not (private.is_org_owner(p_organization_id) or private.has_org_capability(p_organization_id,'core','configure')) then\n raise exception 'forbidden' using errcode='42501';\n end if;\n if not exists(select 1 from public.organization_members m where m.id=p_member_id and m.organization_id=p_organization_id and not m.is_owner) then\n raise exception 'member not found or owner role is implicit';\n end if;\n if not exists(select 1 from public.organization_roles r where r.id=p_role_id and r.organization_id=p_organization_id and r.active) then\n raise exception 'role not found';\n end if;\n\n insert into public.organization_member_roles(organization_id,member_id,role_id,assigned_by,active)\n values(p_organization_id,p_member_id,p_role_id,(select auth.uid()),coalesce(p_active,true))\n on conflict(organization_id,member_id,role_id) do update\n set active=excluded.active,assigned_by=(select auth.uid()),updated_at=now()\n returning id into v_id;\n return v_id;\nend $function$\n",
267
+ "grants": [
268
+ "authenticated"
269
+ ]
270
+ },
271
+ "private.referral_immutable()": {
272
+ "definition": "CREATE OR REPLACE FUNCTION private.referral_immutable()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$ begin raise exception 'correspondence referral is immutable' using errcode='42501'; end $function$\n",
273
+ "grants": []
274
+ },
275
+ "private.can_access_office_storage(p_name text, p_capability text)": {
276
+ "definition": "CREATE OR REPLACE FUNCTION private.can_access_office_storage(p_name text, p_capability text)\n RETURNS boolean\n LANGUAGE plpgsql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare parts text[]:=string_to_array(p_name,'/'); v_org uuid; v_cor text; v_row public.records%rowtype;\nbegin\n if array_length(parts,1) is null then return false; end if;\n if parts[1]=(select auth.uid())::text then\n if p_capability='read' then return private.has_module_entitlement('office_automation'); end if;\n return exists(select 1 from private.current_organization_ids() org_id where private.is_org_owner(org_id) and private.organization_has_module_entitlement(org_id,'office_automation',true));\n end if;\n if parts[1] !~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' then return false; end if;\n v_org:=parts[1]::uuid;\n if p_capability='create' then return parts[2]=(select auth.uid())::text and private.organization_has_module_entitlement(v_org,'office_automation',true) and private.has_org_capability(v_org,'office_automation','create'); end if;\n v_cor:=parts[3];\n select * into v_row from public.records where organization_id=v_org and collection='correspondence' and id=v_cor;\n if not found then return false; end if;\n return private.can_access_record(v_org,'correspondence',v_row.owner_id,v_row.data,p_capability);\nend $function$\n",
277
+ "grants": [
278
+ "authenticated"
279
+ ]
280
+ },
281
+ "public.office_refer_correspondence(p_organization_id uuid, p_correspondence_id text, p_to_member_id uuid, p_note text)": {
282
+ "definition": "CREATE OR REPLACE FUNCTION public.office_refer_correspondence(p_organization_id uuid, p_correspondence_id text, p_to_member_id uuid, p_note text DEFAULT NULL::text)\n RETURNS text\n LANGUAGE sql\n SET search_path TO ''\nAS $function$\n select public.office_refer_correspondence_v2(\n p_organization_id,p_correspondence_id,p_to_member_id,p_note,null::timestamptz\n )\n$function$\n",
283
+ "grants": [
284
+ "authenticated"
285
+ ]
286
+ },
287
+ "public.organization_set_member_permission(p_organization_id uuid, p_member_id uuid, p_module_key text, p_capabilities text[], p_scope_type text, p_scope_id text, p_confidentiality_level smallint)": {
288
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_set_member_permission(p_organization_id uuid, p_member_id uuid, p_module_key text, p_capabilities text[], p_scope_type text DEFAULT 'own'::text, p_scope_id text DEFAULT NULL::text, p_confidentiality_level smallint DEFAULT 0)\n RETURNS uuid\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare v_id uuid; v_allowed boolean:=false;\nbegin\n if p_module_key='core' then\n v_allowed:=private.is_org_owner(p_organization_id)\n or private.has_org_capability(p_organization_id,'core','configure');\n elsif p_module_key='full_suite' then\n v_allowed:=private.is_org_owner(p_organization_id)\n and private.organization_has_module_entitlement(p_organization_id,'full_suite',false);\n else\n v_allowed:=(private.is_org_owner(p_organization_id)\n or private.has_org_capability(p_organization_id,p_module_key,'configure'))\n and private.organization_has_module_entitlement(p_organization_id,p_module_key,false);\n end if;\n\n if not v_allowed then raise exception 'forbidden' using errcode='42501'; end if;\n\n if not exists(\n select 1 from public.organization_members m\n where m.id=p_member_id and m.organization_id=p_organization_id and not m.is_owner\n ) then raise exception 'member not found or owner permission is implicit'; end if;\n\n insert into public.member_module_permissions(\n organization_id,member_id,module_key,capabilities,scope_type,scope_id,confidentiality_level\n )\n values(\n p_organization_id,p_member_id,p_module_key,p_capabilities,p_scope_type,p_scope_id,p_confidentiality_level\n )\n on conflict(organization_id,member_id,module_key,scope_type,scope_id) do update\n set capabilities=excluded.capabilities,\n confidentiality_level=excluded.confidentiality_level,\n updated_at=now()\n returning id into v_id;\n\n return v_id;\nend $function$\n",
289
+ "grants": [
290
+ "authenticated"
291
+ ]
292
+ },
293
+ "private.record_in_member_scope(p_organization_id uuid, p_module_key text, p_owner_id uuid, p_data jsonb, p_capability text)": {
294
+ "definition": "CREATE OR REPLACE FUNCTION private.record_in_member_scope(p_organization_id uuid, p_module_key text, p_owner_id uuid, p_data jsonb, p_capability text)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select exists(\n select 1 from public.organization_members m\n where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active'\n and (\n (p_module_key='core' and p_capability='read')\n or m.is_owner\n or exists(\n select 1 from (\n select p.scope_type,p.scope_id,p.module_key,p.capabilities\n from public.member_module_permissions p\n where p.organization_id=p_organization_id and p.member_id=m.id\n union all\n select rp.scope_type,rp.scope_id,rp.module_key,rp.capabilities\n from public.organization_member_roles mr\n join public.organization_roles r on r.id=mr.role_id and r.organization_id=mr.organization_id and r.active\n join public.organization_role_permissions rp on rp.role_id=r.id and rp.organization_id=r.organization_id\n where mr.organization_id=p_organization_id and mr.member_id=m.id and mr.active\n ) g\n where (g.module_key=p_module_key or g.module_key='full_suite')\n and p_capability=any(g.capabilities)\n and (\n g.scope_type='organization'\n or (g.scope_type='own' and p_owner_id=(select auth.uid()))\n or (g.scope_type='company' and g.scope_id=coalesce(p_data->>'companyId',p_data->>'company_id'))\n or (g.scope_type='branch' and g.scope_id=coalesce(p_data->>'branchId',p_data->>'branch_id'))\n or (g.scope_type='unit' and g.scope_id=coalesce(p_data->>'unitId',p_data->>'unit_id'))\n )\n )\n )\n )\n$function$\n",
295
+ "grants": [
296
+ "authenticated"
297
+ ]
298
+ },
299
+ "private.record_confidentiality_allowed(p_organization_id uuid, p_module_key text, p_data jsonb)": {
300
+ "definition": "CREATE OR REPLACE FUNCTION private.record_confidentiality_allowed(p_organization_id uuid, p_module_key text, p_data jsonb)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n select case when p_module_key='core' then p_organization_id in (select private.current_organization_ids()) else exists(\n select 1 from public.organization_members m\n where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active'\n and (\n m.is_owner\n or coalesce((\n select max(x.confidentiality_level)\n from (\n select p.confidentiality_level,p.module_key\n from public.member_module_permissions p\n where p.organization_id=p_organization_id and p.member_id=m.id\n union all\n select rp.confidentiality_level,rp.module_key\n from public.organization_member_roles mr\n join public.organization_roles r on r.id=mr.role_id and r.organization_id=mr.organization_id and r.active\n join public.organization_role_permissions rp on rp.role_id=r.id and rp.organization_id=r.organization_id\n where mr.organization_id=p_organization_id and mr.member_id=m.id and mr.active\n ) x\n where x.module_key=p_module_key or x.module_key='full_suite'\n ),-1) >= (\n case lower(coalesce(p_data->>'confidentiality','normal'))\n when 'محرمانه' then 1 when 'confidential' then 1\n when 'خیلی محرمانه' then 2 when 'very_confidential' then 2\n when 'سری' then 3 when 'secret' then 3 else 0 end\n )\n )\n ) end\n$function$\n",
301
+ "grants": [
302
+ "authenticated"
303
+ ]
304
+ },
305
+ "private.organization_role_audit_capture()": {
306
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_role_audit_capture()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid; v_id text;\nbegin\n v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;\n v_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;\n insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data)\n values(\n v_org,(select auth.uid()),lower(tg_table_name||'_'||tg_op),tg_table_name,v_id,\n case when tg_op in ('UPDATE','DELETE') then to_jsonb(old) else null end,\n case when tg_op in ('INSERT','UPDATE') then to_jsonb(new) else null end\n );\n if tg_op='DELETE' then return old; else return new; end if;\nend $function$\n",
307
+ "grants": []
308
+ },
309
+ "private.enforce_organization_role_tenant_integrity()": {
310
+ "definition": "CREATE OR REPLACE FUNCTION private.enforce_organization_role_tenant_integrity()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\nbegin\n if tg_table_name='organization_role_permissions' then\n if not exists(\n select 1 from public.organization_roles r\n where r.id=new.role_id and r.organization_id=new.organization_id\n ) then raise exception 'role/organization mismatch' using errcode='23514'; end if;\n if not private.role_permission_allowed(new.organization_id,new.module_key) then\n raise exception 'module not licensed' using errcode='42501';\n end if;\n elsif tg_table_name='organization_member_roles' then\n if not exists(\n select 1 from public.organization_members m\n where m.id=new.member_id and m.organization_id=new.organization_id and not m.is_owner\n ) then raise exception 'member/organization mismatch' using errcode='23514'; end if;\n if not exists(\n select 1 from public.organization_roles r\n where r.id=new.role_id and r.organization_id=new.organization_id and r.active\n ) then raise exception 'role/organization mismatch' using errcode='23514'; end if;\n end if;\n return new;\nend $function$\n",
311
+ "grants": []
312
+ },
313
+ "private.enforce_organization_unit_tree()": {
314
+ "definition": "CREATE OR REPLACE FUNCTION private.enforce_organization_unit_tree()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\nbegin\n if new.parent_id is null then return new; end if;\n if new.parent_id=new.id then raise exception 'organization unit cannot parent itself' using errcode='23514'; end if;\n if not exists(select 1 from public.organization_units p where p.id=new.parent_id and p.organization_id=new.organization_id) then\n raise exception 'parent unit belongs to another organization' using errcode='23514';\n end if;\n if tg_op='UPDATE' and exists(\n with recursive descendants as (\n select u.id from public.organization_units u where u.parent_id=new.id\n union all\n select u.id from public.organization_units u join descendants d on u.parent_id=d.id\n ) select 1 from descendants where id=new.parent_id\n ) then raise exception 'organization unit cycle detected' using errcode='23514'; end if;\n return new;\nend $function$\n",
315
+ "grants": []
316
+ },
317
+ "public.organization_accept_invitation(p_token text)": {
318
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_accept_invitation(p_token text)\n RETURNS uuid\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare\n v_uid uuid:=(select auth.uid());\n v_email text:=lower(coalesce((select auth.jwt()->>'email'),''));\n v_hash text;\n v_inv public.organization_invitations%rowtype;\n v_member uuid;\nbegin\n if v_uid is null then raise exception 'authentication required' using errcode='42501'; end if;\n if nullif(trim(p_token),'') is null then raise exception 'invalid invitation token'; end if;\n\n v_hash:=private.invitation_token_hash(trim(p_token));\n select * into v_inv\n from public.organization_invitations\n where token_hash=v_hash\n for update;\n\n if not found then raise exception 'invitation not found' using errcode='22023'; end if;\n\n if v_inv.status='accepted' and v_inv.accepted_by=v_uid then\n select id into v_member from public.organization_members\n where organization_id=v_inv.organization_id and user_id=v_uid;\n return v_member;\n end if;\n\n if v_inv.status<>'pending' then raise exception 'invitation is not pending' using errcode='22023'; end if;\n\n if v_inv.expires_at<=now() then\n update public.organization_invitations set status='expired',updated_at=now() where id=v_inv.id;\n raise exception 'invitation expired' using errcode='22023';\n end if;\n\n if v_email='' then\n select lower(coalesce(p.email,'')) into v_email from public.profiles p where p.id=v_uid;\n end if;\n if v_email<>v_inv.email_normalized then raise exception 'invitation email mismatch' using errcode='42501'; end if;\n\n if not private.organization_has_module_entitlement(v_inv.organization_id,'core',true) then\n raise exception 'organization license inactive' using errcode='42501';\n end if;\n\n insert into public.organization_members(organization_id,user_id,unit_id,position_title,status,is_owner)\n values(v_inv.organization_id,v_uid,v_inv.unit_id,v_inv.position_title,'active',false)\n on conflict(organization_id,user_id) do update\n set unit_id=excluded.unit_id,\n position_title=excluded.position_title,\n status='active',\n updated_at=now()\n where not public.organization_members.is_owner\n returning id into v_member;\n\n if v_member is null then raise exception 'owner membership cannot accept invitation'; end if;\n\n insert into public.organization_member_roles(organization_id,member_id,role_id,assigned_by,active)\n select v_inv.organization_id,v_member,ir.role_id,v_inv.invited_by,true\n from public.organization_invitation_roles ir\n join public.organization_roles r on r.id=ir.role_id and r.organization_id=ir.organization_id and r.active\n where ir.invitation_id=v_inv.id and ir.organization_id=v_inv.organization_id\n on conflict(organization_id,member_id,role_id) do update\n set active=true,assigned_by=excluded.assigned_by,updated_at=now();\n\n update public.organization_invitations\n set status='accepted',accepted_by=v_uid,accepted_at=now(),updated_at=now()\n where id=v_inv.id;\n\n return v_member;\nend $function$\n",
319
+ "grants": [
320
+ "authenticated"
321
+ ]
322
+ },
323
+ "public.organization_expire_invitations(p_organization_id uuid)": {
324
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_expire_invitations(p_organization_id uuid)\n RETURNS integer\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_count integer;\nbegin\n if not (\n private.is_org_owner(p_organization_id)\n or private.has_org_capability(p_organization_id,'core','configure')\n ) then raise exception 'forbidden' using errcode='42501'; end if;\n update public.organization_invitations\n set status='expired',updated_at=now()\n where organization_id=p_organization_id and status='pending' and expires_at<=now();\n get diagnostics v_count=row_count;\n return v_count;\nend $function$\n",
325
+ "grants": [
326
+ "authenticated"
327
+ ]
328
+ },
329
+ "public.organization_revoke_invitation(p_organization_id uuid, p_invitation_id uuid)": {
330
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_revoke_invitation(p_organization_id uuid, p_invitation_id uuid)\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\nbegin\n if not (\n private.is_org_owner(p_organization_id)\n or private.has_org_capability(p_organization_id,'core','configure')\n ) then raise exception 'forbidden' using errcode='42501'; end if;\n\n update public.organization_invitations\n set status='revoked',revoked_at=now(),updated_at=now()\n where id=p_invitation_id and organization_id=p_organization_id and status='pending';\n\n if not found then raise exception 'pending invitation not found'; end if;\nend $function$\n",
331
+ "grants": [
332
+ "authenticated"
333
+ ]
334
+ },
335
+ "private.organization_invitation_audit_capture()": {
336
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_invitation_audit_capture()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid; v_id text;\nbegin\n v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;\n v_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;\n insert into public.organization_audit(\n organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data\n )\n values(\n v_org,(select auth.uid()),lower(tg_table_name||'_'||tg_op),tg_table_name,v_id,\n case when tg_op in ('UPDATE','DELETE') then to_jsonb(old)-'token_hash' else null end,\n case when tg_op in ('INSERT','UPDATE') then to_jsonb(new)-'token_hash' else null end\n );\n if tg_op='DELETE' then return old; else return new; end if;\nend $function$\n",
337
+ "grants": []
338
+ },
339
+ "public.organization_capacity_summary(p_organization_id uuid)": {
340
+ "definition": "CREATE OR REPLACE FUNCTION public.organization_capacity_summary(p_organization_id uuid)\n RETURNS jsonb\n LANGUAGE plpgsql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v jsonb;\nbegin\n if not (private.is_org_owner(p_organization_id) or private.has_org_capability(p_organization_id,'core','configure')) then\n raise exception 'forbidden' using errcode='42501';\n end if;\n select jsonb_build_object(\n 'plan',l.plan,'status',l.status,'ends_at',l.ends_at,'modules',l.modules,\n 'max_users',l.max_users,\n 'active_users',(select count(*) from public.organization_members m where m.organization_id=p_organization_id and m.status='active'),\n 'max_companies',l.max_companies,\n 'company_count',(select count(*) from public.records r where r.organization_id=p_organization_id and r.collection='companies')\n ) into v from public.licenses l where l.organization_id=p_organization_id;\n if v is null then raise exception 'organization license not found'; end if;\n return v;\nend $function$\n",
341
+ "grants": [
342
+ "authenticated"
343
+ ]
344
+ },
345
+ "private.organization_unit_audit_capture()": {
346
+ "definition": "CREATE OR REPLACE FUNCTION private.organization_unit_audit_capture()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_org uuid; v_id text;\nbegin\n v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;\n v_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;\n insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data)\n values(v_org,(select auth.uid()),'organization_unit_'||lower(tg_op),'organization_unit',v_id,\n case when tg_op in ('UPDATE','DELETE') then to_jsonb(old) else null end,\n case when tg_op in ('INSERT','UPDATE') then to_jsonb(new) else null end);\n if tg_op='DELETE' then return old; else return new; end if;\nend $function$\n",
347
+ "grants": []
348
+ },
349
+ "private.protect_registered_correspondence_history()": {
350
+ "definition": "CREATE OR REPLACE FUNCTION private.protect_registered_correspondence_history()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$\ndeclare old_rank int; new_rank int;\nbegin\n if old.collection<>'correspondence' or coalesce(old.data->>'status','draft')='draft' then\n if tg_op='DELETE' then return old; else return new; end if;\n end if;\n if tg_op='DELETE' then raise exception 'registered correspondence cannot be deleted' using errcode='42501'; end if;\n if new.organization_id is distinct from old.organization_id\n or new.owner_id is distinct from old.owner_id\n or new.collection is distinct from old.collection\n or new.id is distinct from old.id\n or new.data->>'registryId' is distinct from old.data->>'registryId'\n or new.data->>'registerNumber' is distinct from old.data->>'registerNumber'\n or new.data->>'registeredAt' is distinct from old.data->>'registeredAt' then\n raise exception 'registered correspondence identity is immutable' using errcode='42501';\n end if;\n old_rank:=case old.data->>'status' when 'registered' then 1 when 'submitted' then 2 when 'closed' then 3 else 1 end;\n new_rank:=case new.data->>'status' when 'registered' then 1 when 'submitted' then 2 when 'closed' then 3 else 0 end;\n if new_rank<old_rank then raise exception 'registered correspondence status cannot move backward' using errcode='42501'; end if;\n return new;\nend $function$\n",
351
+ "grants": []
352
+ },
353
+ "private.office_correspondence_audit_capture()": {
354
+ "definition": "CREATE OR REPLACE FUNCTION private.office_correspondence_audit_capture()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\nbegin\n insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data)\n values(new.organization_id,(select auth.uid()),case when tg_op='INSERT' then 'correspondence_registered' else 'correspondence_update' end,'correspondence',new.id,\n case when tg_op='UPDATE' then to_jsonb(old) else null end,to_jsonb(new));\n return new;\nend $function$\n",
355
+ "grants": []
356
+ },
357
+ "private.office_audit_immutable()": {
358
+ "definition": "CREATE OR REPLACE FUNCTION private.office_audit_immutable()\n RETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $function$ begin raise exception 'office audit evidence is immutable' using errcode='42501'; end $function$\n",
359
+ "grants": []
360
+ },
361
+ "public.office_mark_correspondence_read(p_organization_id uuid, p_correspondence_id text)": {
362
+ "definition": "CREATE OR REPLACE FUNCTION public.office_mark_correspondence_read(p_organization_id uuid, p_correspondence_id text)\n RETURNS text\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_source public.records%rowtype; v_id text; v_uid uuid:=(select auth.uid());\nbegin\n if v_uid is null then raise exception 'authentication required' using errcode='42501'; end if;\n if not private.organization_has_module_entitlement(p_organization_id,'office_automation',true) then raise exception 'office automation entitlement required' using errcode='42501'; end if;\n select * into v_source from public.records r where r.organization_id=p_organization_id and r.collection='correspondence' and r.id=p_correspondence_id;\n if not found or not private.can_access_record(p_organization_id,'correspondence',v_source.owner_id,v_source.data,'read') then raise exception 'correspondence not found or not readable' using errcode='42501'; end if;\n v_id:='READ_'||replace(gen_random_uuid()::text,'-','');\n insert into public.records(organization_id,owner_id,collection,id,data)\n values(p_organization_id,v_uid,'correspondenceAudit',v_id,jsonb_build_object('event','read','correspondenceId',p_correspondence_id,'readerUserId',v_uid,'readAt',now()));\n return v_id;\nend $function$\n",
363
+ "grants": [
364
+ "authenticated"
365
+ ]
366
+ },
367
+ "private.member_can_access_record(p_member_id uuid, p_module_key text, p_owner_id uuid, p_data jsonb, p_capability text)": {
368
+ "definition": "CREATE OR REPLACE FUNCTION private.member_can_access_record(p_member_id uuid, p_module_key text, p_owner_id uuid, p_data jsonb, p_capability text)\n RETURNS boolean\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n with member_row as (\n select m.id,m.organization_id,m.user_id,m.is_owner\n from public.organization_members m\n where m.id=p_member_id and m.status='active'\n ), grants as (\n select p.organization_id,p.member_id,p.module_key,p.capabilities,p.scope_type,p.scope_id,p.confidentiality_level\n from public.member_module_permissions p\n join member_row m on m.id=p.member_id and m.organization_id=p.organization_id\n union all\n select rp.organization_id,mr.member_id,rp.module_key,rp.capabilities,rp.scope_type,rp.scope_id,rp.confidentiality_level\n from public.organization_member_roles mr\n join member_row m on m.id=mr.member_id and m.organization_id=mr.organization_id\n join public.organization_roles r on r.id=mr.role_id and r.organization_id=mr.organization_id and r.active\n join public.organization_role_permissions rp on rp.role_id=r.id and rp.organization_id=r.organization_id\n where mr.active\n ), access_grants as (\n select g.*,m.user_id\n from grants g join member_row m on m.id=g.member_id\n where (g.module_key=p_module_key or g.module_key='full_suite')\n and p_capability=any(g.capabilities)\n and (\n g.scope_type='organization'\n or (g.scope_type='own' and p_owner_id=m.user_id)\n or (g.scope_type='company' and g.scope_id=coalesce(p_data->>'companyId',p_data->>'company_id'))\n or (g.scope_type='branch' and g.scope_id=coalesce(p_data->>'branchId',p_data->>'branch_id'))\n or (g.scope_type='unit' and g.scope_id=coalesce(p_data->>'unitId',p_data->>'unit_id'))\n )\n )\n select exists(\n select 1 from member_row m\n where m.is_owner\n or (\n exists(select 1 from access_grants)\n and coalesce((\n select max(g.confidentiality_level)\n from grants g\n where g.module_key=p_module_key or g.module_key='full_suite'\n ),-1) >= case lower(coalesce(p_data->>'confidentiality','normal'))\n when 'محرمانه' then 1 when 'confidential' then 1\n when 'خیلی محرمانه' then 2 when 'very_confidential' then 2\n when 'سری' then 3 when 'secret' then 3 else 0 end\n )\n )\n$function$\n",
369
+ "grants": []
370
+ },
371
+ "public.office_refer_correspondence_v2(p_organization_id uuid, p_correspondence_id text, p_to_member_id uuid, p_note text, p_due_at timestamp with time zone)": {
372
+ "definition": "CREATE OR REPLACE FUNCTION public.office_refer_correspondence_v2(p_organization_id uuid, p_correspondence_id text, p_to_member_id uuid, p_note text, p_due_at timestamp with time zone)\n RETURNS text\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare\n v_uid uuid:=(select auth.uid());\n v_source public.records%rowtype;\n v_target public.organization_members%rowtype;\n v_id text;\nbegin\n if v_uid is null then raise exception 'authentication required' using errcode='42501'; end if;\n if not private.organization_has_module_entitlement(p_organization_id,'office_automation',true)\n or not private.has_org_capability(p_organization_id,'office_automation','refer')\n then raise exception 'forbidden' using errcode='42501'; end if;\n select * into v_source from public.records r\n where r.organization_id=p_organization_id and r.collection='correspondence' and r.id=p_correspondence_id;\n if not found or not private.can_access_record(p_organization_id,'correspondence',v_source.owner_id,v_source.data,'read')\n then raise exception 'correspondence not found or not readable' using errcode='42501'; end if;\n select * into v_target from public.organization_members m\n where m.id=p_to_member_id and m.organization_id=p_organization_id and m.status='active';\n if not found then raise exception 'target member not found' using errcode='42501'; end if;\n if v_target.user_id=v_uid then raise exception 'self referral is not allowed' using errcode='22023'; end if;\n if not private.member_can_access_record(v_target.id,'office_automation',v_source.owner_id,v_source.data,'read')\n then raise exception 'target member cannot read correspondence' using errcode='42501'; end if;\n v_id:='REF_'||replace(gen_random_uuid()::text,'-','');\n insert into public.records(organization_id,owner_id,collection,id,data)\n values(p_organization_id,v_target.user_id,'correspondenceReferrals',v_id,\n jsonb_build_object(\n 'correspondenceId',p_correspondence_id,'fromUserId',v_uid,'toMemberId',v_target.id,'toUserId',v_target.user_id,\n 'note',coalesce(p_note,''),'status','sent','createdAt',now(),'dueAt',p_due_at,\n 'companyId',coalesce(v_source.data->>'companyId',v_source.data->>'company_id',''),\n 'unitId',coalesce(v_source.data->>'unitId',v_source.data->>'unit_id',''),\n 'branchId',coalesce(v_source.data->>'branchId',v_source.data->>'branch_id',''),\n 'confidentiality',coalesce(v_source.data->>'confidentiality','normal')\n ));\n return v_id;\nend $function$\n",
373
+ "grants": [
374
+ "authenticated"
375
+ ]
376
+ },
377
+ "public.office_act_on_referral(p_organization_id uuid, p_referral_id text, p_action text, p_note text)": {
378
+ "definition": "CREATE OR REPLACE FUNCTION public.office_act_on_referral(p_organization_id uuid, p_referral_id text, p_action text, p_note text DEFAULT NULL::text)\n RETURNS text\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare\n v_uid uuid:=(select auth.uid());\n v_ref public.records%rowtype;\n v_source public.records%rowtype;\n v_member_id uuid;\n v_event text;\n v_id text;\n v_ack boolean;\n v_done boolean;\nbegin\n if v_uid is null then raise exception 'authentication required' using errcode='42501'; end if;\n if p_action not in ('acknowledged','completed') then raise exception 'invalid referral action' using errcode='22023'; end if;\n if not private.organization_has_module_entitlement(p_organization_id,'office_automation',true)\n then raise exception 'office automation entitlement required' using errcode='42501'; end if;\n select * into v_ref from public.records r\n where r.organization_id=p_organization_id and r.collection='correspondenceReferrals' and r.id=p_referral_id;\n if not found then raise exception 'referral not found' using errcode='42501'; end if;\n if v_ref.data->>'toUserId' is distinct from v_uid::text\n then raise exception 'only referral target may act' using errcode='42501'; end if;\n begin v_member_id:=(v_ref.data->>'toMemberId')::uuid;\n exception when others then raise exception 'invalid referral target' using errcode='42501'; end;\n if not exists(select 1 from public.organization_members m\n where m.id=v_member_id and m.organization_id=p_organization_id and m.user_id=v_uid and m.status='active')\n then raise exception 'referral target membership is inactive' using errcode='42501'; end if;\n select * into v_source from public.records r\n where r.organization_id=p_organization_id and r.collection='correspondence' and r.id=v_ref.data->>'correspondenceId';\n if not found or not private.member_can_access_record(v_member_id,'office_automation',v_source.owner_id,v_source.data,'read')\n then raise exception 'correspondence no longer readable by referral target' using errcode='42501'; end if;\n select exists(select 1 from public.records a\n where a.organization_id=p_organization_id and a.collection='correspondenceAudit'\n and a.data->>'referralId'=p_referral_id and a.data->>'event'='referral_acknowledged') into v_ack;\n select exists(select 1 from public.records a\n where a.organization_id=p_organization_id and a.collection='correspondenceAudit'\n and a.data->>'referralId'=p_referral_id and a.data->>'event'='referral_completed') into v_done;\n if p_action='acknowledged' and v_ack then raise exception 'referral already acknowledged' using errcode='22023'; end if;\n if p_action='completed' and not v_ack then raise exception 'completion requires acknowledgement' using errcode='22023'; end if;\n if p_action='completed' and v_done then raise exception 'referral already completed' using errcode='22023'; end if;\n v_event:='referral_'||p_action;\n v_id:='RA_'||replace(gen_random_uuid()::text,'-','');\n insert into public.records(organization_id,owner_id,collection,id,data)\n values(p_organization_id,v_uid,'correspondenceAudit',v_id,\n jsonb_build_object('event',v_event,'referralId',p_referral_id,'correspondenceId',v_ref.data->>'correspondenceId',\n 'actorUserId',v_uid,'note',coalesce(p_note,''),'at',now()));\n return v_id;\nend $function$\n",
379
+ "grants": [
380
+ "authenticated"
381
+ ]
382
+ },
383
+ "public.office_referral_work_queue(p_organization_id uuid)": {
384
+ "definition": "CREATE OR REPLACE FUNCTION public.office_referral_work_queue(p_organization_id uuid)\n RETURNS TABLE(referral_id text, correspondence_id text, register_number text, subject text, from_user_id uuid, to_user_id uuid, note text, created_at timestamp with time zone, due_at timestamp with time zone, state text, overdue boolean)\n LANGUAGE sql\n STABLE SECURITY DEFINER\n SET search_path TO ''\nAS $function$\n with caller as (\n select m.id,m.user_id,m.is_owner from public.organization_members m\n where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active'\n ), refs as (\n select r.*,c.data as correspondence_data,c.owner_id as correspondence_owner\n from public.records r\n join public.records c on c.organization_id=r.organization_id and c.collection='correspondence' and c.id=r.data->>'correspondenceId'\n where r.organization_id=p_organization_id and r.collection='correspondenceReferrals'\n )\n select r.id,r.data->>'correspondenceId',r.correspondence_data->>'registerNumber',r.correspondence_data->>'subject',\n nullif(r.data->>'fromUserId','')::uuid,nullif(r.data->>'toUserId','')::uuid,coalesce(r.data->>'note',''),\n nullif(r.data->>'createdAt','')::timestamptz,nullif(r.data->>'dueAt','')::timestamptz,\n case\n when exists(select 1 from public.records a where a.organization_id=p_organization_id and a.collection='correspondenceAudit' and a.data->>'referralId'=r.id and a.data->>'event'='referral_completed') then 'completed'\n when exists(select 1 from public.records a where a.organization_id=p_organization_id and a.collection='correspondenceAudit' and a.data->>'referralId'=r.id and a.data->>'event'='referral_acknowledged') then 'acknowledged'\n else 'sent'\n end,\n (nullif(r.data->>'dueAt','')::timestamptz < now()\n and not exists(select 1 from public.records a where a.organization_id=p_organization_id and a.collection='correspondenceAudit' and a.data->>'referralId'=r.id and a.data->>'event'='referral_completed'))\n from refs r\n where exists(select 1 from caller)\n and private.organization_has_module_entitlement(p_organization_id,'office_automation',false)\n and ((select is_owner from caller limit 1)\n or r.data->>'fromUserId'=(select auth.uid())::text\n or r.data->>'toUserId'=(select auth.uid())::text)\n and private.can_access_record(p_organization_id,'correspondence',r.correspondence_owner,r.correspondence_data,'read')\n order by (nullif(r.data->>'dueAt','')::timestamptz < now()) desc,\n nullif(r.data->>'createdAt','')::timestamptz desc\n$function$\n",
385
+ "grants": [
386
+ "authenticated"
387
+ ]
388
+ },
389
+ "public.handle_new_user()": {
390
+ "definition": "CREATE OR REPLACE FUNCTION public.handle_new_user()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_username text; v_org_name text; v_org_id uuid; v_identity text;\nbegin\n v_identity:=coalesce(nullif(lower(new.email),''),nullif(new.phone,''));\n if v_identity is null then\n raise exception 'Finora requires an email or phone identity for signup';\n end if;\n v_username:=lower(coalesce(\n nullif(new.raw_user_meta_data->>'username',''),\n case when new.email is not null then split_part(new.email,'@',1)\n else regexp_replace(new.phone,'[^0-9+]','','g') end\n ));\n v_org_name:=left(\n coalesce(\n nullif(trim(new.raw_user_meta_data->>'full_name'),''),\n nullif(trim(new.raw_user_meta_data->>'name'),''),\n nullif(v_username,''),\n 'Finora'\n )||' - شخصی',\n 160\n );\n insert into public.profiles(id,email,phone,username,role,full_name)\n values(\n new.id,\n case when new.email is null then null else lower(new.email) end,\n new.phone,\n v_username,\n 'user',\n nullif(trim(coalesce(new.raw_user_meta_data->>'full_name',new.raw_user_meta_data->>'name','')),'')\n );\n insert into public.organizations(owner_user_id,name,status)\n values(new.id,v_org_name,'active') returning id into v_org_id;\n\n -- The BEFORE INSERT seat guard on organization_members checks this row.\n -- Seed the trial license FIRST, without weakening or disabling that guard.\n insert into public.licenses(user_id,organization_id,plan,status,starts_at,ends_at,max_companies,max_users,modules,limits)\n values(new.id,v_org_id,'trial','trial',current_date,current_date+15,1,1,array['full_suite']::text[],'{}'::jsonb);\n\n insert into public.organization_members(organization_id,user_id,status,is_owner)\n values(v_org_id,new.id,'active',true);\n return new;\nend $function$\n",
391
+ "grants": []
392
+ },
393
+ "public.update_my_identity_profile(new_username text, new_full_name text)": {
394
+ "definition": "CREATE OR REPLACE FUNCTION public.update_my_identity_profile(new_username text, new_full_name text DEFAULT NULL::text)\n RETURNS void\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $function$\ndeclare v_uid uuid:=auth.uid();v_username text:=lower(trim(coalesce(new_username,'')));\nbegin\n if v_uid is null then raise exception 'Authentication required';end if;\n if v_username !~ '^[a-z0-9_.-]{3,40}$' then raise exception 'Username must be 3-40 latin letters, digits, dot, underscore or dash';end if;\n if exists(select 1 from public.profiles where lower(username)=v_username and id<>v_uid) then raise exception 'Username already in use';end if;\n update public.profiles set username=v_username,full_name=coalesce(nullif(trim(new_full_name),''),full_name) where id=v_uid;\nend $function$\n",
395
+ "grants": [
396
+ "authenticated"
397
+ ]
398
+ }
399
+ },
400
+ "triggers": {
401
+ "public.organization_units|organization_units_audit": "CREATE TRIGGER organization_units_audit AFTER INSERT OR DELETE OR UPDATE ON public.organization_units FOR EACH ROW EXECUTE FUNCTION private.organization_unit_audit_capture()",
402
+ "public.organization_units|trg_organization_unit_tree": "CREATE TRIGGER trg_organization_unit_tree BEFORE INSERT OR UPDATE OF organization_id, parent_id ON public.organization_units FOR EACH ROW EXECUTE FUNCTION private.enforce_organization_unit_tree()",
403
+ "public.organization_members|organization_members_audit": "CREATE TRIGGER organization_members_audit AFTER INSERT OR UPDATE ON public.organization_members FOR EACH ROW EXECUTE FUNCTION private.organization_audit_capture()",
404
+ "public.organization_members|trg_organization_member_seat": "CREATE TRIGGER trg_organization_member_seat BEFORE INSERT OR UPDATE OF status, organization_id ON public.organization_members FOR EACH ROW EXECUTE FUNCTION private.enforce_organization_member_seat()",
405
+ "public.organization_audit|organization_audit_immutable": "CREATE TRIGGER organization_audit_immutable BEFORE DELETE OR UPDATE ON public.organization_audit FOR EACH ROW EXECUTE FUNCTION private.organization_audit_immutable()",
406
+ "public.member_module_permissions|member_module_permissions_audit": "CREATE TRIGGER member_module_permissions_audit AFTER INSERT OR DELETE OR UPDATE ON public.member_module_permissions FOR EACH ROW EXECUTE FUNCTION private.organization_audit_capture()",
407
+ "public.organization_roles|organization_roles_audit": "CREATE TRIGGER organization_roles_audit AFTER INSERT OR DELETE OR UPDATE ON public.organization_roles FOR EACH ROW EXECUTE FUNCTION private.organization_role_audit_capture()",
408
+ "public.organization_roles|trg_protect_system_organization_role": "CREATE TRIGGER trg_protect_system_organization_role BEFORE DELETE OR UPDATE ON public.organization_roles FOR EACH ROW EXECUTE FUNCTION private.protect_system_organization_role()",
409
+ "public.records|office_evidence_insert_guard": "CREATE TRIGGER office_evidence_insert_guard BEFORE INSERT ON public.records FOR EACH ROW WHEN ((new.collection = ANY (ARRAY['correspondenceReferrals'::text, 'correspondenceAudit'::text]))) EXECUTE FUNCTION private.protect_office_evidence_insert()",
410
+ "public.records|correspondence_audit_immutable": "CREATE TRIGGER correspondence_audit_immutable BEFORE DELETE OR UPDATE ON public.records FOR EACH ROW WHEN ((old.collection = 'correspondenceAudit'::text)) EXECUTE FUNCTION private.office_audit_immutable()",
411
+ "public.records|correspondence_registered_audit": "CREATE TRIGGER correspondence_registered_audit AFTER INSERT OR UPDATE ON public.records FOR EACH ROW WHEN (((new.collection = 'correspondence'::text) AND (COALESCE((new.data ->> 'status'::text), 'draft'::text) <> 'draft'::text))) EXECUTE FUNCTION private.office_correspondence_audit_capture()",
412
+ "public.records|trg_protect_registered_correspondence_history": "CREATE TRIGGER trg_protect_registered_correspondence_history BEFORE DELETE OR UPDATE ON public.records FOR EACH ROW WHEN ((old.collection = 'correspondence'::text)) EXECUTE FUNCTION private.protect_registered_correspondence_history()",
413
+ "public.records|correspondence_referrals_immutable": "CREATE TRIGGER correspondence_referrals_immutable BEFORE DELETE OR UPDATE ON public.records FOR EACH ROW WHEN ((old.collection = 'correspondenceReferrals'::text)) EXECUTE FUNCTION private.referral_immutable()",
414
+ "public.records|correspondence_referrals_audit": "CREATE TRIGGER correspondence_referrals_audit AFTER INSERT ON public.records FOR EACH ROW WHEN ((new.collection = 'correspondenceReferrals'::text)) EXECUTE FUNCTION private.organization_audit_capture()",
415
+ "public.records|trg_finora_company_license_limit": "CREATE TRIGGER trg_finora_company_license_limit AFTER INSERT ON public.records FOR EACH ROW WHEN ((new.collection = 'companies'::text)) EXECUTE FUNCTION finora_enforce_company_license_limit()",
416
+ "public.records|trg_finora_guard_posted_source_records": "CREATE TRIGGER trg_finora_guard_posted_source_records BEFORE DELETE OR UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION finora_guard_posted_source_records()",
417
+ "public.records|trg_finora_guard_phase5_posted_records": "CREATE TRIGGER trg_finora_guard_phase5_posted_records BEFORE DELETE OR UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION finora_guard_phase5_posted_records()",
418
+ "public.records|trg_finora_guard_posted_journal_children": "CREATE TRIGGER trg_finora_guard_posted_journal_children BEFORE DELETE OR UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION finora_guard_posted_journal_children()",
419
+ "public.records|trg_finora_guard_posted_journal": "CREATE TRIGGER trg_finora_guard_posted_journal BEFORE DELETE OR UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION finora_guard_posted_journal()",
420
+ "public.records|records_touch": "CREATE TRIGGER records_touch BEFORE UPDATE ON public.records FOR EACH ROW EXECUTE FUNCTION touch_updated_at()",
421
+ "public.organization_invitation_roles|organization_invitation_roles_audit": "CREATE TRIGGER organization_invitation_roles_audit AFTER INSERT OR DELETE OR UPDATE ON public.organization_invitation_roles FOR EACH ROW EXECUTE FUNCTION private.organization_invitation_audit_capture()",
422
+ "public.organization_invitation_roles|trg_invitation_role_tenant_integrity": "CREATE TRIGGER trg_invitation_role_tenant_integrity BEFORE INSERT OR UPDATE ON public.organization_invitation_roles FOR EACH ROW EXECUTE FUNCTION private.enforce_invitation_role_tenant_integrity()",
423
+ "public.organization_role_permissions|trg_role_permission_tenant_integrity": "CREATE TRIGGER trg_role_permission_tenant_integrity BEFORE INSERT OR UPDATE ON public.organization_role_permissions FOR EACH ROW EXECUTE FUNCTION private.enforce_organization_role_tenant_integrity()",
424
+ "public.organization_role_permissions|organization_role_permissions_audit": "CREATE TRIGGER organization_role_permissions_audit AFTER INSERT OR DELETE OR UPDATE ON public.organization_role_permissions FOR EACH ROW EXECUTE FUNCTION private.organization_role_audit_capture()",
425
+ "public.organization_member_roles|trg_member_role_tenant_integrity": "CREATE TRIGGER trg_member_role_tenant_integrity BEFORE INSERT OR UPDATE ON public.organization_member_roles FOR EACH ROW EXECUTE FUNCTION private.enforce_organization_role_tenant_integrity()",
426
+ "public.organization_member_roles|organization_member_roles_audit": "CREATE TRIGGER organization_member_roles_audit AFTER INSERT OR DELETE OR UPDATE ON public.organization_member_roles FOR EACH ROW EXECUTE FUNCTION private.organization_role_audit_capture()",
427
+ "public.organization_invitations|organization_invitations_audit": "CREATE TRIGGER organization_invitations_audit AFTER INSERT OR DELETE OR UPDATE ON public.organization_invitations FOR EACH ROW EXECUTE FUNCTION private.organization_invitation_audit_capture()"
428
+ }
429
+}
docs/wp1/evidence/prerequisite-rollback/posted-reversal-seed.log
new
+11
@@ -0,0 +1,11 @@
1
+{"name":"fixture","pass":true,"diagnostic":""}
2
+{"name":"drafts","pass":true,"diagnostic":""}
3
+{"name":"simultaneous_duplicate_create","pass":true,"diagnostic":" "}
4
+{"name":"concurrent_double_click_one_voucher_two_lines","pass":true,"diagnostic":"1,2\n"}
5
+{"name":"two_posts","pass":true,"diagnostic":" "}
6
+{"name":"gapless_numbers","pass":true,"diagnostic":"1,2\n"}
7
+{"name":"original","pass":true,"diagnostic":""}
8
+{"name":"two_reversals_one_winner","pass":true,"diagnostic":" ERROR: FINORA_REVERSAL_OVER_ALLOCATION\nCONTEXT: PL/pgSQL function public.finora_journal_reverse(uuid,text,text,text,text,bigint,jsonb) line 73 at RAISE\n"}
9
+{"name":"no_duplicate_reversals","pass":true,"diagnostic":"1\n"}
10
+{"name":"partial_status_from_view","pass":true,"diagnostic":"partially_reversed\n"}
11
+FINORA_STAGE1_TWO_CONNECTIONS_PASS
docs/wp1/evidence/prerequisite-rollback/result.json
new
+14
@@ -0,0 +1,14 @@
1
+{
2
+ "result": "PASS",
3
+ "prerequisites": 11,
4
+ "baselineFunctionCount": 71,
5
+ "retained": {
6
+ "posted_count": 4,
7
+ "line_count": 10,
8
+ "audit_count": 10,
9
+ "records": "00de9380350064f3e642af5161f28d7a",
10
+ "audit": "6a0d80b89dc60983b4d80dd1ffda51a0",
11
+ "counters": "be61da114b20499ea00a1ee4b4146e83"
12
+ },
13
+ "scope": "conservative rollback preserves inert structures/indexes; NOT pristine schema or production parity"
14
+}
scripts/wp1-prerequisite-rollback.mjs
new
+62
@@ -0,0 +1,62 @@
1
+// Generate conservative, data-preserving DOWN definitions on a disposable DB only.
2
+// This is not a production migration executor and accepts no connection string.
3
+import {withDisposableLedger} from './wp0-ledger-harness.mjs';
4
+import {readFileSync,readdirSync,writeFileSync,mkdirSync} from 'node:fs';
5
+import assert from 'node:assert/strict';
6
+import {spawnSync} from 'node:child_process';
7
+const generate=process.argv.includes('--generate');
8
+const dir='docs/wp1/evidence/prerequisite-rollback';mkdirSync(dir,{recursive:true});
9
+await withDisposableLedger(async c=>{
10
+ const query=s=>{
11
+ const r=c.sql('\\pset format unaligned\n\\pset tuples_only on\n'+s);
12
+ c.requireSuccess(r,'catalog');return JSON.parse(r.stdout.split('\n').find(x=>x.startsWith('{')));
13
+ };
14
+ const catalog=()=>query(`select json_build_object('functions',coalesce((select json_object_agg(sig,json_build_object('definition',def,'grants',grants)) from (
15
+ select p.oid,n.nspname||'.'||p.proname||'('||pg_get_function_identity_arguments(p.oid)||')' sig,pg_get_functiondef(p.oid) def,
16
+ (select coalesce(json_agg(case when a.grantee=0 then 'PUBLIC' else quote_ident(pg_get_userbyid(a.grantee)) end),'[]') from aclexplode(coalesce(p.proacl,acldefault('f',p.proowner))) a where a.privilege_type='EXECUTE' and a.grantee<>p.proowner) grants
17
+ from pg_proc p join pg_namespace n on n.oid=p.pronamespace where n.nspname in ('public','private') and p.prokind='f') f),'{}'),
18
+ 'triggers',coalesce((select json_object_agg(quote_ident(n.nspname)||'.'||quote_ident(t.relname)||'|'||quote_ident(g.tgname),pg_get_triggerdef(g.oid)) from pg_trigger g join pg_class t on t.oid=g.tgrelid join pg_namespace n on n.oid=t.relnamespace where n.nspname in ('public','private') and not g.tgisinternal),'{}'));`);
19
+ const migrations=readdirSync('supabase/migrations').filter(x=>x.startsWith('2026101610')&&x.endsWith('.sql')).sort();
20
+ assert.equal(migrations.length,11);
21
+ const baseline=catalog();
22
+ for(const name of migrations){
23
+ const before=catalog();c.requireSuccess(c.sql(readFileSync('supabase/migrations/'+name,'utf8')),name);const after=catalog();
24
+ if(generate){
25
+ const lines=['-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.','-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.'];
26
+ for(const [key,def] of Object.entries(after.triggers))if(before.triggers[key]!==def){const [table,trigger]=key.split('|');lines.push('DROP TRIGGER IF EXISTS '+trigger+' ON '+table+';');if(before.triggers[key])lines.push(before.triggers[key]+';');}
27
+ for(const [sig,fn] of Object.entries(after.functions))if(JSON.stringify(before.functions[sig])!==JSON.stringify(fn)){
28
+ if(before.functions[sig])lines.push(before.functions[sig].definition+';');
29
+ lines.push('REVOKE ALL ON FUNCTION '+sig+' FROM PUBLIC,anon,authenticated,service_role;');
30
+ for(const role of before.functions[sig]?.grants||[])lines.push('GRANT EXECUTE ON FUNCTION '+sig+' TO '+role+';');
31
+ }
32
+ // The newly exposed reversal view stays inert for data-preserving DOWN.
33
+ if(name.includes('journal_rpc_surface'))lines.push('REVOKE ALL ON public.finora_journal_reversal_status FROM PUBLIC,anon,authenticated,service_role;');
34
+ writeFileSync('supabase/rollback/'+name,lines.join('\n\n')+'\n');
35
+ }
36
+ }
37
+ const correction=readdirSync('supabase/migrations').find(x=>x.includes('_wp1_'));
38
+ c.requireSuccess(c.sql(readFileSync('supabase/migrations/'+correction,'utf8')),'correction UP');
39
+ // Existing correction-cycle fixture posts a real voucher and snapshots retained rows.
40
+ const seeded=spawnSync(process.execPath,['scripts/wp1-concurrency.mjs'],{env:{...process.env,WP1_CONTAINER:`finora-wp0-ledger-${process.pid}`},encoding:'utf8'});
41
+ writeFileSync(dir+'/posted-reversal-seed.log',(seeded.stdout||'')+(seeded.stderr||''));
42
+ c.requireSuccess(seeded,'seed actual posted vouchers and partial reversal');
43
+ writeFileSync(dir+'/catalog-baseline.json',JSON.stringify(baseline,null,2)+'\n');
44
+ // Seed separately from application Auth; only synthetic valid rows, no production values.
45
+ c.requireSuccess(c.sql(`insert into auth.users(id,email,raw_user_meta_data) values('a1234567-0000-4000-8000-000000000001','rollback-all@example.invalid','{}');
46
+ insert into private.finora_wp1_company_counters(organization_id,company_id,fiscal_year_id,last_no) select id,'RB_COMPANY','RB_YEAR',17 from public.organizations where owner_user_id='a1234567-0000-4000-8000-000000000001';`),'seed retained counter');
47
+ const fingerprint=()=>query(`select json_build_object('posted_count',(select count(*) from public.records where collection='journalVouchers' and data->>'status'='posted'),'line_count',(select count(*) from public.records where collection='journalLines'),'audit_count',(select count(*) from private.finora_phase1a_journal_audit),'records',md5(coalesce((select string_agg(row_to_json(r)::text,'' order by organization_id,collection,id) from public.records r),'')), 'audit',md5(coalesce((select string_agg(row_to_json(r)::text,'' order by id) from private.finora_phase1a_journal_audit r),'')), 'counters',md5(coalesce((select string_agg(row_to_json(r)::text,'' order by organization_id,company_id,fiscal_year_id) from private.finora_wp1_company_counters r),'')));`);
48
+ const before=fingerprint();assert.ok(before.posted_count>=4&&before.line_count>=8&&before.audit_count>0,'Financial history fixture is empty');
49
+ c.requireSuccess(c.sql(readFileSync('supabase/rollback/'+correction,'utf8')),'correction DOWN');
50
+ for(const name of [...migrations].reverse())c.requireSuccess(c.sql(readFileSync('supabase/rollback/'+name,'utf8')),name+' DOWN');
51
+ assert.deepEqual(fingerprint(),before,'DOWN changed retained rows');
52
+ const down=catalog();for(const [sig,fn] of Object.entries(baseline.functions))assert.deepEqual(down.functions[sig],fn,'Prior function/ACL not restored: '+sig);
53
+ for(const [key,def] of Object.entries(baseline.triggers))assert.equal(down.triggers[key],def,'Prior trigger not restored: '+key);
54
+ // New privileged functions may remain only inaccessible to application roles.
55
+ for(const [sig,fn] of Object.entries(down.functions))if(!baseline.functions[sig])assert.equal(fn.grants.filter(x=>['PUBLIC','anon','authenticated','service_role'].includes(x)).length,0,'Unrevoked candidate API '+sig);
56
+ for(const name of migrations)c.requireSuccess(c.sql(readFileSync('supabase/migrations/'+name,'utf8')),name+' UP again');
57
+ c.requireSuccess(c.sql(readFileSync('supabase/migrations/'+correction,'utf8')),'correction UP again');
58
+ assert.deepEqual(fingerprint(),before,'UP changed retained rows');
59
+ c.requireSuccess(c.sql(readFileSync('supabase/tests/wp1_direct_write_regressions.sql','utf8')),'D1/D2 after full cycle');
60
+ writeFileSync(dir+'/result.json',JSON.stringify({result:'PASS',prerequisites:migrations.length,baselineFunctionCount:Object.keys(baseline.functions).length,retained:before,scope:'conservative rollback preserves inert structures/indexes; NOT pristine schema or production parity'},null,2)+'\n');
61
+ console.log('PASS eleven prerequisite DOWN/UP: baseline function ACLs/triggers restored, retained rows unchanged, D1/D2 enforced again.');
62
+});
supabase/rollback/20261016100000_phase1a_server_journal_invariants.sql
new
+15
@@ -0,0 +1,15 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+DROP TRIGGER IF EXISTS trg_finora_phase1a_posted_balance ON public.records;
6
+
7
+DROP TRIGGER IF EXISTS trg_finora_phase1a_guard_children ON public.records;
8
+
9
+DROP TRIGGER IF EXISTS trg_finora_phase1a_journal_server_only ON public.records;
10
+
11
+REVOKE ALL ON FUNCTION private.finora_phase1a_guard_journal_children() FROM PUBLIC,anon,authenticated,service_role;
12
+
13
+REVOKE ALL ON FUNCTION private.finora_phase1a_assert_posted_balance() FROM PUBLIC,anon,authenticated,service_role;
14
+
15
+REVOKE ALL ON FUNCTION private.finora_phase1a_guard_server_journal_fields() FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016100500_phase1a_optimistic_version_sync.sql
new
+62
@@ -0,0 +1,62 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+DROP TRIGGER IF EXISTS trg_finora_phase1a_stamp_version ON public.records;
6
+
7
+CREATE OR REPLACE FUNCTION public.finora_sync_records(p_upserts jsonb DEFAULT '[]'::jsonb, p_deletes jsonb DEFAULT '[]'::jsonb)
8
+ RETURNS void
9
+ LANGUAGE plpgsql
10
+ SET search_path TO 'public'
11
+AS $function$
12
+begin
13
+ if auth.uid() is null then raise exception 'authentication required'; end if;
14
+ if not public.has_active_license() then raise exception 'active license required'; end if;
15
+ if exists (
16
+ select 1 from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb)
17
+ where not private.has_collection_entitlement(x.collection)
18
+ ) or exists (
19
+ select 1 from jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text)
20
+ where not private.has_collection_entitlement(d.collection)
21
+ ) then raise exception 'module entitlement required' using errcode='42501'; end if;
22
+
23
+ insert into public.records(owner_id, collection, id, data)
24
+ select auth.uid(), x.collection, x.id, x.data
25
+ from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb)
26
+ on conflict (owner_id,collection,id) do update set data=excluded.data;
27
+
28
+ delete from public.records r
29
+ using jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text)
30
+ where r.owner_id=auth.uid() and r.collection=d.collection and r.id=d.id;
31
+end $function$
32
+;
33
+
34
+REVOKE ALL ON FUNCTION public.finora_sync_records(p_upserts jsonb, p_deletes jsonb) FROM PUBLIC,anon,authenticated,service_role;
35
+
36
+GRANT EXECUTE ON FUNCTION public.finora_sync_records(p_upserts jsonb, p_deletes jsonb) TO authenticated;
37
+
38
+CREATE OR REPLACE FUNCTION public.finora_sync_records(p_upserts jsonb DEFAULT '[]'::jsonb, p_deletes jsonb DEFAULT '[]'::jsonb, p_organization_id uuid DEFAULT NULL::uuid)
39
+ RETURNS void
40
+ LANGUAGE plpgsql
41
+ SET search_path TO ''
42
+AS $function$
43
+declare v_org uuid:=coalesce(p_organization_id,private.default_organization_id());
44
+begin
45
+ if (select auth.uid()) is null then raise exception 'authentication required'; end if;
46
+ if v_org is null or v_org not in (select private.current_organization_ids()) then raise exception 'organization membership required' using errcode='42501'; end if;
47
+ if not private.organization_has_module_entitlement(v_org,'core',true) then raise exception 'active license required' using errcode='42501'; end if;
48
+ if exists(select 1 from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb) where not private.organization_has_module_entitlement(v_org,private.collection_module(x.collection),true)) or exists(select 1 from jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text) where not private.organization_has_module_entitlement(v_org,private.collection_module(d.collection),true)) then raise exception 'module entitlement required' using errcode='42501'; end if;
49
+ insert into public.records(organization_id,owner_id,collection,id,data) select v_org,(select auth.uid()),x.collection,x.id,x.data from jsonb_to_recordset(coalesce(p_upserts,'[]'::jsonb)) as x(collection text,id text,data jsonb) on conflict (organization_id,collection,id) do update set data=excluded.data;
50
+ delete from public.records r using jsonb_to_recordset(coalesce(p_deletes,'[]'::jsonb)) as d(collection text,id text) where r.organization_id=v_org and r.collection=d.collection and r.id=d.id;
51
+end $function$
52
+;
53
+
54
+REVOKE ALL ON FUNCTION public.finora_sync_records(p_upserts jsonb, p_deletes jsonb, p_organization_id uuid) FROM PUBLIC,anon,authenticated,service_role;
55
+
56
+GRANT EXECUTE ON FUNCTION public.finora_sync_records(p_upserts jsonb, p_deletes jsonb, p_organization_id uuid) TO authenticated;
57
+
58
+REVOKE ALL ON FUNCTION private.finora_phase1a_stamp_version() FROM PUBLIC,anon,authenticated,service_role;
59
+
60
+REVOKE ALL ON FUNCTION private.finora_phase1a_log_legacy_sync(p_signature text) FROM PUBLIC,anon,authenticated,service_role;
61
+
62
+REVOKE ALL ON FUNCTION public.finora_sync_records_v2(p_upserts jsonb, p_deletes jsonb, p_organization_id uuid) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016101000_phase1a_guard_modes_audit.sql
new
+162
@@ -0,0 +1,162 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+DROP TRIGGER IF EXISTS trg_finora_phase1a_audit_immutable ON private.finora_phase1a_journal_audit;
6
+
7
+REVOKE ALL ON FUNCTION private.finora_phase1a_audit_immutable() FROM PUBLIC,anon,authenticated,service_role;
8
+
9
+REVOKE ALL ON FUNCTION private.finora_phase1a_mode(p_org uuid) FROM PUBLIC,anon,authenticated,service_role;
10
+
11
+CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_server_journal_fields()
12
+ RETURNS trigger
13
+ LANGUAGE plpgsql
14
+ SET search_path TO ''
15
+AS $function$
16
+DECLARE
17
+ v_is_server boolean := current_user IN ('postgres','supabase_admin','service_role');
18
+ v_new_status text;
19
+BEGIN
20
+ IF TG_OP NOT IN ('INSERT','UPDATE') OR new.collection<>'journalVouchers' THEN RETURN new; END IF;
21
+ v_new_status:=new.data->>'status';
22
+ IF NOT v_is_server THEN
23
+ IF TG_OP='INSERT' THEN
24
+ IF new.data ?| ARRAY['status','number','postedAt','postedBy','reversedAt','reversalVoucherId'] THEN
25
+ RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
26
+ END IF;
27
+ ELSIF (new.data->'status') IS DISTINCT FROM (old.data->'status')
28
+ OR (new.data->'number') IS DISTINCT FROM (old.data->'number')
29
+ OR (new.data->'postedAt') IS DISTINCT FROM (old.data->'postedAt')
30
+ OR (new.data->'postedBy') IS DISTINCT FROM (old.data->'postedBy')
31
+ OR (new.data->'reversedAt') IS DISTINCT FROM (old.data->'reversedAt')
32
+ OR (new.data->'reversalVoucherId') IS DISTINCT FROM (old.data->'reversalVoucherId') THEN
33
+ RAISE EXCEPTION 'FINORA_SERVER_ONLY_JOURNAL_FIELDS' USING ERRCODE='P0001';
34
+ END IF;
35
+ END IF;
36
+ -- Even privileged administrative DML may not fabricate an invalid status.
37
+ IF v_new_status IS NOT NULL AND v_new_status NOT IN ('draft','posted','reversed') THEN
38
+ RAISE EXCEPTION 'FINORA_INVALID_JOURNAL_STATUS' USING ERRCODE='23514';
39
+ END IF;
40
+ RETURN new;
41
+END
42
+$function$
43
+;
44
+
45
+REVOKE ALL ON FUNCTION private.finora_phase1a_guard_server_journal_fields() FROM PUBLIC,anon,authenticated,service_role;
46
+
47
+CREATE OR REPLACE FUNCTION private.finora_phase1a_assert_posted_balance()
48
+ RETURNS trigger
49
+ LANGUAGE plpgsql
50
+ SECURITY DEFINER
51
+ SET search_path TO ''
52
+AS $function$
53
+DECLARE
54
+ v_org uuid;
55
+ v_id text;
56
+ v_status text;
57
+ v_count integer;
58
+ v_invalid integer;
59
+ v_debit numeric;
60
+ v_credit numeric;
61
+BEGIN
62
+ IF TG_OP='DELETE' THEN RETURN NULL; END IF;
63
+ IF new.collection<>'journalVouchers' THEN RETURN NULL; END IF;
64
+ v_org:=new.organization_id;v_id:=new.id;
65
+ SELECT v.data->>'status' INTO v_status FROM public.records v
66
+ WHERE v.organization_id=v_org AND v.collection='journalVouchers' AND v.id=v_id;
67
+ IF NOT FOUND OR v_status NOT IN ('posted','reversed') THEN RETURN NULL; END IF;
68
+ SELECT count(*)::integer,
69
+ count(*) FILTER(WHERE jsonb_typeof(l.data->'debit') IS DISTINCT FROM 'number'
70
+ OR jsonb_typeof(l.data->'credit') IS DISTINCT FROM 'number'
71
+ OR coalesce(l.data->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
72
+ OR coalesce(l.data->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$')::integer,
73
+ coalesce(sum(CASE WHEN coalesce(l.data->>'debit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'debit')::numeric ELSE 0 END),0),
74
+ coalesce(sum(CASE WHEN coalesce(l.data->>'credit','') ~ '^(0|[1-9][0-9]{0,27})$' THEN (l.data->>'credit')::numeric ELSE 0 END),0)
75
+ INTO v_count,v_invalid,v_debit,v_credit
76
+ FROM public.records l WHERE l.organization_id=v_org AND l.collection='journalLines' AND l.data->>'voucherId'=v_id;
77
+ IF v_invalid<>0 THEN RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514'; END IF;
78
+ IF v_count<2 OR v_debit<>v_credit THEN
79
+ RAISE EXCEPTION 'FINORA_UNBALANCED_POSTED_JOURNAL' USING ERRCODE='23514';
80
+ END IF;
81
+ RETURN NULL;
82
+END
83
+$function$
84
+;
85
+
86
+REVOKE ALL ON FUNCTION private.finora_phase1a_assert_posted_balance() FROM PUBLIC,anon,authenticated,service_role;
87
+
88
+CREATE OR REPLACE FUNCTION private.finora_phase1a_guard_journal_children()
89
+ RETURNS trigger
90
+ LANGUAGE plpgsql
91
+ SECURITY DEFINER
92
+ SET search_path TO ''
93
+AS $function$
94
+DECLARE
95
+ x record;
96
+ v_voucher_id text;
97
+ v_parent_status text;
98
+ v_org uuid;
99
+ v_line_id text;
100
+ v_debit numeric;
101
+ v_credit numeric;
102
+BEGIN
103
+ IF TG_OP='DELETE' THEN
104
+ IF old.collection NOT IN ('journalLines','journalLineDimensions') THEN RETURN old; END IF;
105
+ ELSE
106
+ IF new.collection NOT IN ('journalLines','journalLineDimensions')
107
+ AND (TG_OP='INSERT' OR old.collection NOT IN ('journalLines','journalLineDimensions')) THEN
108
+ RETURN new;
109
+ END IF;
110
+ END IF;
111
+ -- Check both old and new voucher, so a malicious UPDATE cannot move a
112
+ -- line/dimension away from a posted document.
113
+ FOR x IN
114
+ SELECT old.organization_id AS org,old.collection AS coll,old.data AS doc WHERE TG_OP<>'INSERT'
115
+ UNION ALL
116
+ SELECT new.organization_id AS org,new.collection AS coll,new.data AS doc WHERE TG_OP<>'DELETE'
117
+ LOOP
118
+ IF x.coll NOT IN ('journalLines','journalLineDimensions') THEN CONTINUE; END IF;
119
+ v_org:=x.org; v_voucher_id:=nullif(x.doc->>'voucherId','');
120
+ IF v_voucher_id IS NULL THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_REQUIRED' USING ERRCODE='23514'; END IF;
121
+ IF x.coll='journalLines' AND TG_OP<>'DELETE' AND x.doc=new.data THEN
122
+ IF jsonb_typeof(x.doc->'debit') IS DISTINCT FROM 'number'
123
+ OR jsonb_typeof(x.doc->'credit') IS DISTINCT FROM 'number'
124
+ OR coalesce(x.doc->>'debit','') !~ '^(0|[1-9][0-9]{0,27})$'
125
+ OR coalesce(x.doc->>'credit','') !~ '^(0|[1-9][0-9]{0,27})$' THEN
126
+ RAISE EXCEPTION 'FINORA_INVALID_RIAL_AMOUNT' USING ERRCODE='23514';
127
+ END IF;
128
+ v_debit:=(x.doc->>'debit')::numeric;
129
+ v_credit:=(x.doc->>'credit')::numeric;
130
+ IF (v_debit=0 AND v_credit=0) OR (v_debit>0 AND v_credit>0) THEN
131
+ RAISE EXCEPTION 'FINORA_INVALID_RIAL_LINE' USING ERRCODE='23514';
132
+ END IF;
133
+ END IF;
134
+ -- Row lock serializes this child's insertion and concurrent posting.
135
+ SELECT v.data->>'status' INTO v_parent_status
136
+ FROM public.records v WHERE v.organization_id=v_org
137
+ AND v.collection='journalVouchers' AND v.id=v_voucher_id FOR UPDATE;
138
+ IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_CHILD_PARENT_NOT_FOUND' USING ERRCODE='23503'; END IF;
139
+ IF v_parent_status IN ('posted','reversed') THEN
140
+ RAISE EXCEPTION 'FINORA_POSTED_JOURNAL_CHILD_IMMUTABLE' USING ERRCODE='P0001';
141
+ END IF;
142
+ IF x.coll='journalLineDimensions' THEN
143
+ v_line_id:=nullif(x.doc->>'journalLineId','');
144
+ IF v_line_id IS NULL OR NOT EXISTS (
145
+ SELECT 1 FROM public.records l WHERE l.organization_id=v_org
146
+ AND l.collection='journalLines' AND l.id=v_line_id
147
+ AND l.data->>'voucherId'=v_voucher_id
148
+ ) THEN
149
+ RAISE EXCEPTION 'FINORA_DIMENSION_LINE_PARENT_MISMATCH' USING ERRCODE='23503';
150
+ END IF;
151
+ END IF;
152
+ END LOOP;
153
+ RETURN CASE WHEN TG_OP='DELETE' THEN old ELSE new END;
154
+END
155
+$function$
156
+;
157
+
158
+REVOKE ALL ON FUNCTION private.finora_phase1a_guard_journal_children() FROM PUBLIC,anon,authenticated,service_role;
159
+
160
+REVOKE ALL ON FUNCTION private.finora_phase1a_audit_event(p_org uuid, p_voucher text, p_actor uuid, p_action text, p_reason text, p_details jsonb) FROM PUBLIC,anon,authenticated,service_role;
161
+
162
+REVOKE ALL ON FUNCTION private.finora_phase1a_log_guard(p_org uuid, p_voucher text, p_message text, p_state text) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016101500_phase1a_journal_core.sql
new
+15
@@ -0,0 +1,15 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+REVOKE ALL ON FUNCTION private.finora_phase1a_post_core(p_org uuid, p_id text, p_expected_version bigint, p_auto boolean) FROM PUBLIC,anon,authenticated,service_role;
6
+
7
+REVOKE ALL ON FUNCTION private.finora_phase1a_validate_line(p_org uuid, p_company text, p_line jsonb) FROM PUBLIC,anon,authenticated,service_role;
8
+
9
+REVOKE ALL ON FUNCTION private.finora_phase1a_validate_saved(p_org uuid, p_voucher text, p_company text) FROM PUBLIC,anon,authenticated,service_role;
10
+
11
+REVOKE ALL ON FUNCTION private.finora_phase1a_write_lines(p_org uuid, p_actor uuid, p_voucher text, p_company text, p_lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
12
+
13
+REVOKE ALL ON FUNCTION private.finora_phase1a_authorize(p_org uuid, p_cap text, p_source_type text) FROM PUBLIC,anon,authenticated,service_role;
14
+
15
+REVOKE ALL ON FUNCTION private.finora_phase1a_create_core(p_org uuid, p_id text, p_header jsonb, p_lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016102000_phase1a_journal_rpc_surface.sql
new
+17
@@ -0,0 +1,17 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+REVOKE ALL ON FUNCTION public.finora_journal_create_draft(p_organization_id uuid, p_voucher_id text, p_header jsonb, p_lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
6
+
7
+REVOKE ALL ON FUNCTION public.finora_journal_post(p_organization_id uuid, p_voucher_id text, p_expected_version bigint) FROM PUBLIC,anon,authenticated,service_role;
8
+
9
+REVOKE ALL ON FUNCTION public.finora_journal_delete_draft(p_organization_id uuid, p_voucher_id text, p_expected_version bigint) FROM PUBLIC,anon,authenticated,service_role;
10
+
11
+REVOKE ALL ON FUNCTION public.finora_journal_update_draft(p_organization_id uuid, p_voucher_id text, p_expected_version bigint, p_header jsonb, p_lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
12
+
13
+REVOKE ALL ON FUNCTION public.finora_journal_autopost(p_organization_id uuid, p_voucher_id text, p_source_collection text, p_source_id text, p_header jsonb, p_lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
14
+
15
+REVOKE ALL ON FUNCTION public.finora_journal_reverse(p_organization_id uuid, p_original_id text, p_reversal_id text, p_date text, p_reason text, p_expected_version bigint, p_allocations jsonb) FROM PUBLIC,anon,authenticated,service_role;
16
+
17
+REVOKE ALL ON public.finora_journal_reversal_status FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016102500_phase1a_account_role_protection.sql
new
+19
@@ -0,0 +1,19 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+DROP TRIGGER IF EXISTS trg_finora_phase1a_account_mapping_sync ON public.records;
6
+
7
+DROP TRIGGER IF EXISTS trg_finora_phase1a_role_snapshots_immutable ON private.finora_phase1a_account_role_snapshots;
8
+
9
+DROP TRIGGER IF EXISTS trg_finora_phase1a_role_audit_immutable ON private.finora_phase1a_account_role_audit;
10
+
11
+REVOKE ALL ON FUNCTION private.finora_phase1a_role_immutable() FROM PUBLIC,anon,authenticated,service_role;
12
+
13
+REVOKE ALL ON FUNCTION private.finora_phase1a_account_fields(p jsonb) FROM PUBLIC,anon,authenticated,service_role;
14
+
15
+REVOKE ALL ON FUNCTION private.finora_phase1a_guard_account_mapping_sync() FROM PUBLIC,anon,authenticated,service_role;
16
+
17
+REVOKE ALL ON FUNCTION public.finora_phase1a_publish_role_assignments(p_organization_id uuid, p_company_id text, p_assignments jsonb, p_expected_version bigint, p_reason text) FROM PUBLIC,anon,authenticated,service_role;
18
+
19
+REVOKE ALL ON FUNCTION private.finora_phase1a_check_role_account(p_org uuid, p_company text, p_role text, p_account text) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016103000_phase1a_sale_monetary_contract.sql
new
+13
@@ -0,0 +1,13 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+REVOKE ALL ON FUNCTION private.finora_phase1a_resolve_role(p_org uuid, p_company text, p_role text, p_version bigint) FROM PUBLIC,anon,authenticated,service_role;
6
+
7
+REVOKE ALL ON FUNCTION private.finora_phase1a_expected_lines(org uuid, company text, typ text, source jsonb, ver bigint) FROM PUBLIC,anon,authenticated,service_role;
8
+
9
+REVOKE ALL ON FUNCTION private.finora_phase1a_sale_lines(org uuid, company text, source jsonb, ver bigint) FROM PUBLIC,anon,authenticated,service_role;
10
+
11
+REVOKE ALL ON FUNCTION private.finora_phase1a_document_amounts(s jsonb, k text) FROM PUBLIC,anon,authenticated,service_role;
12
+
13
+REVOKE ALL ON FUNCTION private.finora_phase1a_rial(p jsonb, k text) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016103100_phase1a_autopost_server_authority.sql
new
+157
@@ -0,0 +1,157 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+CREATE OR REPLACE FUNCTION private.finora_phase1a_post_core(p_org uuid, p_id text, p_expected_version bigint, p_auto boolean DEFAULT false)
6
+ RETURNS jsonb
7
+ LANGUAGE plpgsql
8
+ SECURITY DEFINER
9
+ SET search_path TO ''
10
+AS $function$
11
+DECLARE v public.records%rowtype;v_fy text;v_company text;v_src text;v_original_src text;
12
+ v_no bigint;v_actor uuid:=auth.uid();v_at timestamptz:=clock_timestamp();
13
+BEGIN
14
+ IF v_actor IS NULL OR NOT EXISTS(SELECT 1 FROM public.organization_members
15
+ WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
16
+ RAISE EXCEPTION 'FINORA_ORG_FORBIDDEN' USING ERRCODE='42501';
17
+ END IF;
18
+ SELECT * INTO v FROM public.records WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id FOR UPDATE;
19
+ IF NOT FOUND THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_FOUND' USING ERRCODE='23503';END IF;
20
+ v_fy:=v.data->>'fiscalYearId';v_company:=v.data->>'companyId';v_src:=coalesce(v.data->>'sourceType','manual');
21
+ IF p_auto THEN
22
+ IF v_src='reversal' THEN
23
+ SELECT data->>'sourceType' INTO v_original_src FROM public.records
24
+ WHERE organization_id=p_org AND collection='journalVouchers' AND id=v.data->>'sourceId';
25
+ IF coalesce(v_original_src,'manual')='manual' THEN
26
+ PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
27
+ ELSE
28
+ PERFORM private.finora_phase1a_authorize(p_org,'create',v_original_src);
29
+ END IF;
30
+ ELSIF v_src IN ('manual','') THEN
31
+ RAISE EXCEPTION 'FINORA_INVALID_AUTOMATIC_SOURCE' USING ERRCODE='42501';
32
+ ELSE
33
+ PERFORM private.finora_phase1a_authorize(p_org,'create',v_src);
34
+ END IF;
35
+ ELSE
36
+ PERFORM private.finora_phase1a_authorize(p_org,'approve',NULL);
37
+ END IF;
38
+ IF v.data->>'status'='posted' THEN
39
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',true);
40
+ END IF;
41
+ IF v.data->>'status'<>'draft' THEN RAISE EXCEPTION 'FINORA_JOURNAL_NOT_DRAFT' USING ERRCODE='23514';END IF;
42
+ IF v.version<>p_expected_version THEN RAISE EXCEPTION 'FINORA_VERSION_CONFLICT' USING ERRCODE='40001';END IF;
43
+ IF NOT EXISTS(SELECT 1 FROM public.records fy
44
+ WHERE fy.organization_id=p_org AND fy.collection='fiscalYears'
45
+ AND fy.id=v_fy AND fy.data->>'companyId'=v_company
46
+ AND coalesce(fy.data->>'status','open')<>'locked') THEN
47
+ RAISE EXCEPTION 'FINORA_FISCAL_YEAR_LOCKED_OR_MISSING' USING ERRCODE='23514';
48
+ END IF;
49
+ PERFORM private.finora_phase1a_validate_saved(p_org,p_id,v_company);
50
+ -- First lock the persisted fiscal-year counter; only the first posting
51
+ -- initializes it from the maximum historic number. This avoids O(N^2)
52
+ -- scanning during a 1000-document batch and retains transactional rollback.
53
+ SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
54
+ WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
55
+ IF NOT FOUND THEN
56
+ INSERT INTO private.finora_phase1a_journal_counters(organization_id,fiscal_year_id,last_no)
57
+ SELECT p_org,v_fy,coalesce(max((d.data->>'number')::bigint),0)
58
+ FROM public.records d WHERE d.organization_id=p_org
59
+ AND d.collection='journalVouchers' AND d.data->>'fiscalYearId'=v_fy
60
+ AND d.data->>'status' IN ('posted','reversed')
61
+ AND d.data->>'number' ~ '^[0-9]{1,17}$'
62
+ ON CONFLICT (organization_id,fiscal_year_id) DO NOTHING;
63
+ SELECT last_no INTO v_no FROM private.finora_phase1a_journal_counters
64
+ WHERE organization_id=p_org AND fiscal_year_id=v_fy FOR UPDATE;
65
+ END IF;
66
+ v_no:=v_no+1;
67
+ UPDATE private.finora_phase1a_journal_counters SET last_no=v_no
68
+ WHERE organization_id=p_org AND fiscal_year_id=v_fy;
69
+ UPDATE public.records SET data=v.data||jsonb_build_object(
70
+ 'status','posted','number',v_no::text,'postedAt',v_at,
71
+ 'postedBy',v_actor)
72
+ WHERE organization_id=p_org AND collection='journalVouchers' AND id=p_id
73
+ RETURNING * INTO v;
74
+ PERFORM private.finora_phase1a_audit_event(p_org,p_id,v_actor,'posted','',
75
+ jsonb_build_object('number',v_no,'sourceType',v_src,'sourceId',v.data->>'sourceId'));
76
+ RETURN jsonb_build_object('voucher',v.data||jsonb_build_object('id',v.id,'version',v.version),'replayed',false);
77
+END $function$
78
+;
79
+
80
+REVOKE ALL ON FUNCTION private.finora_phase1a_post_core(p_org uuid, p_id text, p_expected_version bigint, p_auto boolean) FROM PUBLIC,anon,authenticated,service_role;
81
+
82
+CREATE OR REPLACE FUNCTION public.finora_journal_autopost(p_organization_id uuid, p_voucher_id text, p_source_collection text, p_source_id text, p_header jsonb, p_lines jsonb)
83
+ RETURNS jsonb
84
+ LANGUAGE plpgsql
85
+ SECURITY DEFINER
86
+ SET search_path TO ''
87
+AS $function$
88
+DECLARE v_type text:=p_header->>'sourceType';v_collection text;
89
+ v_draft jsonb;v_result jsonb;v_source public.records%rowtype;
90
+ v_source_amount numeric;v_debit numeric;v_credit numeric;
91
+BEGIN
92
+ v_collection:=CASE v_type
93
+ WHEN 'sale' THEN 'invoices' WHEN 'purchase' THEN 'purchases'
94
+ WHEN 'receipt' THEN 'payments' WHEN 'payment' THEN 'payments'
95
+ WHEN 'expense' THEN 'expenses' WHEN 'income' THEN 'expenses'
96
+ WHEN 'contract_statement' THEN 'contractStatements'
97
+ WHEN 'inventory_adjustment' THEN 'stockMovements'
98
+ WHEN 'asset_depreciation' THEN 'assetDepreciations'
99
+ WHEN 'payroll_run' THEN 'payrollRuns'
100
+ WHEN 'employee_benefit_accrual' THEN 'employeeBenefitAccruals'
101
+ WHEN 'petty_cash' THEN 'pettyCashTransactions' ELSE NULL END;
102
+ IF v_collection IS NULL OR p_source_collection<>v_collection OR coalesce(p_source_id,'')=''
103
+ OR p_header->>'sourceId' IS DISTINCT FROM p_source_id THEN
104
+ RAISE EXCEPTION 'FINORA_SOURCE_IDENTITY_INVALID' USING ERRCODE='23514';END IF;
105
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'create',v_type);
106
+ -- Take a share lock on the persisted business record within this transaction.
107
+ SELECT src.* INTO v_source FROM public.records src
108
+ WHERE src.organization_id=p_organization_id AND src.collection=p_source_collection
109
+ AND src.id=p_source_id AND src.data->>'companyId'=p_header->>'companyId'
110
+ AND private.can_access_record(p_organization_id,p_source_collection,
111
+ src.owner_id,src.data,'create')
112
+ FOR SHARE;
113
+ IF NOT FOUND THEN
114
+ RAISE EXCEPTION 'FINORA_SOURCE_NOT_COMMITTED_IN_ORG' USING ERRCODE='23503';
115
+ END IF;
116
+ IF (v_type='sale' AND coalesce(v_source.data->>'kind','') NOT IN ('formal','non_formal'))
117
+ OR (v_type IN ('receipt','payment') AND v_source.data->>'direction'
118
+ IS DISTINCT FROM CASE WHEN v_type='receipt' THEN 'inbound' ELSE 'outbound' END)
119
+ OR (v_type IN ('expense','income') AND v_source.data->>'kind' IS DISTINCT FROM v_type)
120
+ OR (v_source.data ? 'accountingVersion' AND
121
+ v_source.data->>'accountingVersion' IS DISTINCT FROM
122
+ coalesce(p_header->>'sourceVersion','1'))
123
+ THEN RAISE EXCEPTION 'FINORA_SOURCE_TYPE_OR_VERSION_MISMATCH' USING ERRCODE='23514';END IF;
124
+ IF v_type IN ('sale','purchase') THEN
125
+ IF jsonb_typeof(v_source.data->'grandTotal')<>'number'
126
+ OR (v_source.data->>'grandTotal') !~ '^[1-9][0-9]{0,27}$' THEN
127
+ RAISE EXCEPTION 'FINORA_SOURCE_AMOUNT_INVALID' USING ERRCODE='23514';END IF;
128
+ v_source_amount:=(v_source.data->>'grandTotal')::numeric;
129
+ ELSE
130
+ IF jsonb_typeof(v_source.data->'amount')<>'number'
131
+ OR (v_source.data->>'amount') !~ '^[1-9][0-9]{0,27}$' THEN
132
+ RAISE EXCEPTION 'FINORA_SOURCE_AMOUNT_INVALID' USING ERRCODE='23514';END IF;
133
+ v_source_amount:=(v_source.data->>'amount')::numeric;
134
+ END IF;
135
+ IF jsonb_typeof(p_lines)<>'array' OR jsonb_array_length(p_lines)<2 THEN
136
+ RAISE EXCEPTION 'FINORA_INVALID_LINE_COUNT' USING ERRCODE='23514';END IF;
137
+ SELECT coalesce(sum((l.value->>'debit')::numeric),0),
138
+ coalesce(sum((l.value->>'credit')::numeric),0)
139
+ INTO v_debit,v_credit FROM jsonb_array_elements(p_lines) AS l(value);
140
+ IF v_debit<>v_source_amount OR v_credit<>v_source_amount THEN
141
+ RAISE EXCEPTION 'FINORA_SOURCE_LEDGER_AMOUNT_MISMATCH' USING ERRCODE='23514';
142
+ END IF;
143
+ -- Specific account-profile contract is a separately gated Stage 3 issue.
144
+ v_draft:=private.finora_phase1a_create_core(p_organization_id,p_voucher_id,p_header,p_lines);
145
+ v_result:=private.finora_phase1a_post_core(p_organization_id,p_voucher_id,
146
+ (v_draft#>>'{voucher,version}')::bigint,true);
147
+ RETURN v_result||jsonb_build_object('draftReplayed',coalesce((v_draft->>'replayed')::boolean,false));
148
+END $function$
149
+;
150
+
151
+REVOKE ALL ON FUNCTION public.finora_journal_autopost(p_organization_id uuid, p_voucher_id text, p_source_collection text, p_source_id text, p_header jsonb, p_lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
152
+
153
+GRANT EXECUTE ON FUNCTION public.finora_journal_autopost(p_organization_id uuid, p_voucher_id text, p_source_collection text, p_source_id text, p_header jsonb, p_lines jsonb) TO authenticated;
154
+
155
+REVOKE ALL ON FUNCTION private.finora_phase1a_line_set(lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
156
+
157
+REVOKE ALL ON FUNCTION private.finora_phase1a_revalidate_autopost(org uuid, v records) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016103500_phase1a_purchase_fixed_contract.sql
new
+18
@@ -0,0 +1,18 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+CREATE OR REPLACE FUNCTION private.finora_phase1a_expected_lines(org uuid, company text, typ text, source jsonb, ver bigint)
6
+ RETURNS jsonb
7
+ LANGUAGE plpgsql
8
+ SECURITY DEFINER
9
+ SET search_path TO ''
10
+AS $function$ BEGIN
11
+ IF typ='sale' THEN RETURN private.finora_phase1a_sale_lines(org,company,source,ver);END IF;
12
+ RAISE EXCEPTION 'FINORA_AUTOPOST_CONTRACT_UNSUPPORTED' USING ERRCODE='23514';
13
+END $function$
14
+;
15
+
16
+REVOKE ALL ON FUNCTION private.finora_phase1a_expected_lines(org uuid, company text, typ text, source jsonb, ver bigint) FROM PUBLIC,anon,authenticated,service_role;
17
+
18
+REVOKE ALL ON FUNCTION private.finora_phase1a_purchase_lines(org uuid, company text, source jsonb, ver bigint) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016104000_stage22_manual_guard_owner_mode.sql
new
+26
@@ -0,0 +1,26 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+CREATE OR REPLACE FUNCTION public.finora_journal_create_draft(p_organization_id uuid, p_voucher_id text, p_header jsonb, p_lines jsonb)
6
+ RETURNS jsonb
7
+ LANGUAGE plpgsql
8
+ SECURITY DEFINER
9
+ SET search_path TO ''
10
+AS $function$
11
+BEGIN
12
+ PERFORM private.finora_phase1a_authorize(p_organization_id,'create',NULL);
13
+ IF coalesce(p_header->>'sourceType','manual')<>'manual' OR coalesce(p_header->>'sourceId','')<>'' THEN
14
+ RAISE EXCEPTION 'FINORA_MANUAL_DRAFT_ONLY' USING ERRCODE='42501';
15
+ END IF;
16
+ RETURN private.finora_phase1a_create_core(p_organization_id,p_voucher_id,p_header,p_lines);
17
+END $function$
18
+;
19
+
20
+REVOKE ALL ON FUNCTION public.finora_journal_create_draft(p_organization_id uuid, p_voucher_id text, p_header jsonb, p_lines jsonb) FROM PUBLIC,anon,authenticated,service_role;
21
+
22
+GRANT EXECUTE ON FUNCTION public.finora_journal_create_draft(p_organization_id uuid, p_voucher_id text, p_header jsonb, p_lines jsonb) TO authenticated;
23
+
24
+REVOKE ALL ON FUNCTION public.finora_journal_get_guard_mode(p_organization_id uuid) FROM PUBLIC,anon,authenticated,service_role;
25
+
26
+REVOKE ALL ON FUNCTION public.finora_journal_set_guard_mode(p_organization_id uuid, p_expected_mode text, p_mode text, p_reason text) FROM PUBLIC,anon,authenticated,service_role;
supabase/rollback/20261016104500_stage3_posted_source_immutable.sql
new
+7
@@ -0,0 +1,7 @@
1
+-- Conservative WP1 DOWN: restore prior definitions/ACLs; retain records, audit, counters, version columns and compatible indexes.
2
+
3
+-- Generated from the source-derived disposable baseline. Production schema parity remains a separate gate.
4
+
5
+DROP TRIGGER IF EXISTS trg_finora_stage3_posted_source_immutable ON public.records;
6
+
7
+REVOKE ALL ON FUNCTION private.finora_stage3_guard_posted_source() FROM PUBLIC,anon,authenticated,service_role;