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

hardening/wp1-ledger-integrity-20261102
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
json 429 lines 91.4 KB
Raw
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 }