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

fix/office-c7-source-ref-binding
audit-remediation-wave3-4-20261002 audit-remediation-wave3-verify-20261002 audit-remediation-wave4-20261002 audit-remediation-wave4b-20261002 audit-remediation-wave5a-identity-20261002 audit-remediation-wave5b-offboarding-20261002 audit-remediation-wave5c-authorization-20261002 audit-security-intent-review-20261002 audit/finora-financial-core-20261115 audit/finora-master-prompt-phase0-20261016 audit/finora-stage3-legacy-source-readonly-20261023 audit/full-controls-20261030 audit/owner-live-state-reconcile-20261012 audit/owner-review-20261007 audit/phase1-live-permissions-readonly-20261013 audit/reconcile-live-state-20261006 audit/reconcile-state-20261002 audit/wp0-hardening-baseline-20261102 branding-login-favicon-20261002 c8-workflow-task1 c8-workflow-task2 c8-workflow-task3 chore/wave0-pages-gate-closeout claude-code-plugins-setup design/finora-c01-authoritative-source-draft-20261124 docs-wave4b-verified-20261002 docs/active-company-invoice-release-evidence-20261014 docs/agent-operating-model-20261114 docs/chart-taxpayer-release-evidence-20261004 docs/cloud-only-agent-orchestration-20261115 docs/confirm-finora-product-charter-20261115 docs/continuation-20261030 docs/d4a-verified docs/external-work-review-20261121 docs/finora-audit-continuity-20261014 docs/finora-backup-merge-evidence-20261014 docs/finora-ci-reconciliation-20261122 docs/finora-codex-master-prompt docs/finora-eight-phase-plan-20261011 docs/finora-f002-live-buyer-filter-verified-20261015 docs/finora-license-race-release-evidence-20261014 docs/finora-license-rollout-acceptance-20261015 docs/finora-phase0-repeat-and-pages-nav-verified-20261015 docs/finora-phase0-repeat-evidence-20261015 docs/finora-selectors-release-and-fixture-qa-20261015 docs/finora-stagea-pr240-ci-triage-20261123 docs/finora-test-license-live-pass-20261015 docs/finora-v2-m01-coverage-20261124 docs/handoff-charter-v2-20261124 docs/invoice-product-search-release-20261011 docs/invoice-workspace-release-20261007 docs/phase-status-20261031 docs/phase0-acceptance-release-evidence-20261012 docs/phase0-admin-provision-release-evidence-20261012 docs/phase0-core-bundle-owner-login-open-20261013 docs/phase0-duplicate-js-release-20261016 docs/phase0-f001-auth-rest-shared-timeout-20261013 docs/phase0-f001-owner-login-observed-20261013 docs/phase0-f001-second-device-fail-40s-20261013 docs/phase0-f003-release-verification-20261011 docs/phase0-f004-print-release-evidence-20261012 docs/phase0-f004-watermark-release-evidence-20261012 docs/phase0-f005-large-selector-release-20261012 docs/phase0-f005-release-evidence-20261012 docs/phase0-f006-dark-release-evidence-20261012 docs/phase0-f008-final-pr-closure-evidence-20261012 docs/phase0-f008-reconcile-stale-prs-20261012 docs/phase0-f107-production-evidence-20261012 docs/phase0-kavenegar-otp-preflight-release-20261012 docs/phase0-login-release-evidence-20261012 docs/phase0-login-rest-bootstrap-stage-release-20261012 docs/phase0-owner-app-assets-bundle-release-20261013 docs/phase0-owner-login-csp-release-20261012 docs/phase0-reconcile-postmerge-evidence-20261012 docs/phase0-site-probe-release-evidence-20261012 docs/phase0-startup-release-evidence-20261012 docs/phase3-treasury-release-evidence-20261014 docs/pilot-posted-correction-release-evidence-20261014 docs/pilot-purchase-correction-release-evidence-20261014 docs/print-persian-release-verification-20261011 docs/qa-ci-triage-218-20261122 docs/real-account-qa-20261030 docs/release-state-20261007 docs/seamless-amendment-release-20261014 docs/seamless-document-correction-release-20261014 docs/settings-login-release-20261025 docs/stripe-qa-deployment-evidence-20261011 docs/ux-f2-release-evidence-20261011 docs/ux-f2-release-verification-20261011 docs/wave0-closeout docs/wave2-closeout exec-phase1-architecture exec-phase1-implementation exec-phase1-qa exec-phase1-security-release exec-phase1-ux feat/accounting-document-draft-approval-20261011 feat/accounting-document-release-candidate-20261011 feat/active-company-strict-isolation-20261014 feat/admin-provisioning-reconciled-20261011 feat/admin-secure-user-provisioning-20261011 feat/admin-user-provisioning-merged-20261011 feat/d4a-request-work-queue feat/document-lifecycle-atf-20261118 feat/document-lifecycle-temp-permanent-atef feat/draft-first-attachment-lifecycle-216 feat/finora-offline-encrypted-backup-20261014 feat/finora-phase-a-navigation-20261023 feat/finora-stripe-sandbox-edge-gate feat/immutable-attachment-temporary-vouchers feat/iran-accounting-design-audit feat/journal-document-lifecycle-20261118 feat/journal-rpc-repository-adapter-20261117 feat/office-c7-fulltext-ocr-provenance feat/password-recovery-admin-reset-20261025 feat/pilot-expense-income-inplace-amendment-20261014 feat/pilot-journal-invoice-correction-20261014 feat/pilot-purchase-correction-20261014 feat/pilot-treasury-unallocated-correction-20261014 feat/retain-document-editor-after-save-20261014 feat/seamless-financial-document-correction-20261014 feat/slice-b-tenant-rbac feat/stripe-sandbox-invoice-probe feature/accounting-core-p0 feature/accounting-product-guidance feature/admin-identity-phone-auth feature/commercial-rnd feature/finora-phase1a-supabase-cli-20261016 feature/finora-stage2-manual-canary-20261017 feature/finora-stage3-commercial-payload-20261023 feature/finora-stage3-enforce-invoice-rpc-20261023 feature/finora-stage3-enforce-purchase-red-20261023 feature/invoice-workspace-cleanup feature/phase0-kavenegar-otp-preflight-20261012 feature/ux-commerce-settings-r2 fix-shell-scroll-live-cache-20261002 fix-shell-scrollbar-explicit-ownership-20261002 fix-shell-scrollbar-ownership-20261002 fix-shell-scrollbar-right-edge-20261002 fix/about-bug-report-20261114 fix/active-company-invoice-scope-20261014 fix/active-company-isolation-reconcile-20261014 fix/admin-central-password-reset-20261028 fix/auth-network-diagnostics fix/chart-taxpayer-reference-20261003 fix/combobox-enter-reliability fix/combobox-live-search fix/combobox-production-cache fix/combobox-release-asset-v2 fix/company-edit-action-20261028 fix/company-edit-pilot-delete-20261014 fix/company-form-action-state-20261014 fix/company-form-action-state-rebased-20261014 fix/contact-operational-balance-20261111 fix/dark-theme-contrast fix/financial-lifecycle-recovery-20261124 fix/finora-accounting-test-organization-readiness-20261015 fix/finora-b01-safe-org-switch-20261124 fix/finora-b02-sync-recovery-20261124 fix/finora-b03-conflict-review-20261124 fix/finora-org-license-bootstrap-race-20261014 fix/finora-stage3-posted-source-immutable-20261023 fix/finora-v2-b03-r2-qa-20261124 fix/finora-v2-b03-r3-readonly-20261124 fix/g01-asof-financial-position-20261128 fix/invoice-product-search-rehydrate-20261011 fix/invoice-search-cache-bust fix/issue229-linked-draft-status-20261122 fix/login-assets-retry-20261014 fix/login-inert-startup-20261110 fix/login-member-access-20261101 fix/login-resilience-20261017 fix/login-short-viewport-20261028 fix/login-startup-readiness-20261024 fix/navigation-utilities-placement-20261105 fix/office-c7-source-ref-binding fix/office-c7-source-ref-binding-v2 fix/owner-login-network-20261026 fix/password-recovery-invalid-cancel-20261026 fix/payment-amount-format-20261111 fix/phase0-admin-provision-seat-bootstrap-20261012 fix/phase0-auth-bundled-assets-for-unstable-isp-20261013 fix/phase0-auth-handler-binding-stalled-session-20261012 fix/phase0-login-context-stage-visibility-20261012 fix/phase0-login-single-local-bundle-20261013 fix/phase0-login-site-probe-clarity-20261012 fix/phase0-login-ui-ready-20261012 fix/phase0-modal-dashboard-drill-20261011 fix/phase0-pages-blocking-core-bundles-20261013 fix/phase0-print-no-draft-watermark-20261012 fix/phase0-startup-parallel-asset-load-20261012 fix/phase3-behavioral-verification fix/preserve-pending-edits-20261121 fix/print-persian-digit-consistency-20261011 fix/recovery-login-startup-20261027 fix/report-opening-balance-release-20261130 fix/settings-checkbox-persistence-20261024 fix/taxpayer-arithmetic-20261004 fix/ux-keyboard-search-f2-20261011 fix/wave2-request-input-integrity hardening/c01-source-draft-20261129 hardening/global-draft-conversion-20261113 hardening/wp1-ledger-integrity-20261102 integration/finora-execution-20261124 integration/issue229-ui-qa-20261122 integration/wp1-ledger-core-20261115 integration/wp2-manual-journal-rpc-20261116 main ops-heartbeat-v2-20261002 ops-progress-heartbeat-rule-20261002 ops/wave4-production-20261003 plan/financial-core-phase1-approval-20261016 qa/attachment-allocator-two-session-20261122 qa/draft-first-save-red-evidence-20261122 qa/finora-autopost-retry-identity-red-20261122 qa/finora-identity-rpc-security-tripwire-20261122 qa/finora-issue223-manual-kardex-browser-red-20261123 qa/finora-issue223-stock-real-jwt-20261123 qa/finora-issue238-inventory-count-browser-red-20261123 qa/finora-issue238-save-browser-red-20261122 qa/finora-login-cors-header-preflight-20261025 qa/finora-phase0-saved-session-repeat-20261015 qa/finora-phase5-posted-insert-jwt-red-20261123 qa/finora-stage3-ui-jwt-autopost-20261023 qa/finora-v2-g01-report-reconciliation-20261125 qa/free-supabase-local-wp2-20261116 qa/issue229-approval-boundary-jwt-20261122 qa/issue229-sale-save-linked-draft-red-20261122 qa/phase0-acceptance-start-20261012 qa/phase0-f005-account-project-contract-stress-20261012 qa/phase0-f005-selector-stress-20261012 qa/phase0-f006-dark-contrast-20261012 qa/post-wave4-verification-20261003 qa/posted-source-immutable-jwt-20261122 qa/pr219-wp1-disposable-dburl-proof-20261123 qa/purchase-source-jwt-20261122 qa/real-settings-acceptance-20261025 qa/recovery-mail-acceptance-20261026 qa/source-autopost-jwt-atomicity-20261122 qa/wave0-negative-gate-proof qa/wp2-auth-tenant-e2e-20261117 qa/wp2-authorized-journal-write-20261122 qa/wp2-financial-paths-reconciliation-20261122 qa/wp3-financial-tenant-isolation-20261117 remediation/wave0-liveqa-wave1 remediation/wave2-request-integrity staging/finora-stage22-free-20261022 state-scroll-verified-20261002 state-wave4b-production-20261002 state-wave5a-production-20261002 test/finora-accounting-boot-readiness-20261015 test/finora-f0-02-production-selectors-20261015 test/finora-pages-commerce-event-wiring-20261015 test/finora-pages-invoice-selectors-readonly-20261015 test/finora-stage3-jwt-source-post-20261023 test/phase0-invoice-fixture-bootstrap-20261016 test/phase0-invoice-persistence-20261011 test/phase0-pages-delayed-dispatcher-20261016 ux-scroll-ownership-20261002 work/finora-stage3-enforce-purchase-green-20261023 work/finora-stage3-enforce-sale-green-20261023 work/finora-stage3-payload-green-20261023
sql 216 lines 22 KB
Raw
1 create table public.organizations (
2 id uuid primary key default gen_random_uuid(),
3 owner_user_id uuid not null references public.profiles(id) on delete restrict,
4 name text not null check (char_length(trim(name)) between 1 and 160),
5 status text not null default 'active' check (status in ('active','suspended')),
6 created_at timestamptz not null default now(),
7 updated_at timestamptz not null default now()
8 );
9 create table public.organization_units (
10 id uuid primary key default gen_random_uuid(),
11 organization_id uuid not null references public.organizations(id) on delete cascade,
12 parent_id uuid references public.organization_units(id) on delete set null,
13 code text not null check (char_length(trim(code)) between 1 and 64),
14 title text not null check (char_length(trim(title)) between 1 and 160),
15 active boolean not null default true,
16 created_at timestamptz not null default now(),
17 unique (organization_id,code)
18 );
19 create table public.organization_members (
20 id uuid primary key default gen_random_uuid(),
21 organization_id uuid not null references public.organizations(id) on delete cascade,
22 user_id uuid not null references public.profiles(id) on delete cascade,
23 unit_id uuid references public.organization_units(id) on delete set null,
24 position_title text,
25 status text not null default 'active' check (status in ('active','suspended','left')),
26 is_owner boolean not null default false,
27 created_at timestamptz not null default now(),
28 updated_at timestamptz not null default now(),
29 unique (organization_id,user_id)
30 );
31 create table public.member_module_permissions (
32 id uuid primary key default gen_random_uuid(),
33 organization_id uuid not null references public.organizations(id) on delete cascade,
34 member_id uuid not null references public.organization_members(id) on delete cascade,
35 module_key text not null check (module_key in ('full_suite','accounting','commerce','treasury','contracting','inventory','assets','hr_payroll','office_automation','requests_workflow','crm','transport','manufacturing','maintenance','group_consolidation','analytics')),
36 capabilities text[] not null default array['read']::text[],
37 scope_type text not null default 'own' check (scope_type in ('own','unit','branch','company','organization')),
38 scope_id text,
39 confidentiality_level smallint not null default 0 check (confidentiality_level between 0 and 3),
40 created_at timestamptz not null default now(),
41 updated_at timestamptz not null default now(),
42 check (capabilities <@ array['read','create','edit','delete','approve','register','refer','archive','configure']::text[]),
43 check (cardinality(capabilities)>0),
44 check ((scope_type in ('own','organization') and scope_id is null) or (scope_type in ('unit','branch','company') and nullif(trim(scope_id),'') is not null)),
45 unique nulls not distinct (organization_id,member_id,module_key,scope_type,scope_id)
46 );
47 create table public.organization_audit (
48 id uuid primary key default gen_random_uuid(),
49 organization_id uuid not null references public.organizations(id) on delete restrict,
50 actor_user_id uuid references public.profiles(id) on delete set null,
51 action text not null,
52 entity_type text not null,
53 entity_id text,
54 before_data jsonb,
55 after_data jsonb,
56 created_at timestamptz not null default now()
57 );
58 alter table public.licenses add column if not exists organization_id uuid references public.organizations(id) on delete restrict;
59 alter table public.records add column if not exists organization_id uuid references public.organizations(id) on delete restrict;
60 insert into public.organizations(owner_user_id,name)
61 select l.user_id,coalesce(nullif(trim(p.full_name),''),nullif(trim(p.username),''),'Finora Organization')
62 from public.licenses l join public.profiles p on p.id=l.user_id where l.organization_id is null;
63 update public.licenses l set organization_id=(select o.id from public.organizations o where o.owner_user_id=l.user_id order by o.created_at,o.id limit 1) where l.organization_id is null;
64 insert into public.organization_members(organization_id,user_id,status,is_owner,position_title)
65 select l.organization_id,l.user_id,'active',true,'مالک سازمان' from public.licenses l where l.organization_id is not null
66 on conflict (organization_id,user_id) do update set is_owner=true,status='active',updated_at=now();
67 update public.records r set organization_id=l.organization_id from public.licenses l where r.organization_id is null and l.user_id=r.owner_id;
68 do $$ begin
69 if exists(select 1 from public.licenses where organization_id is null) then raise exception 'license organization backfill incomplete'; end if;
70 if exists(select 1 from public.records where organization_id is null) then raise exception 'record organization backfill incomplete'; end if;
71 end $$;
72 alter table public.licenses alter column organization_id set not null;
73 alter table public.records alter column organization_id set not null;
74 create unique index licenses_organization_uq on public.licenses(organization_id);
75 create index organization_members_user_idx on public.organization_members(user_id,organization_id) where status='active';
76 create index organization_members_org_idx on public.organization_members(organization_id,user_id);
77 create index member_module_permissions_member_idx on public.member_module_permissions(member_id,module_key);
78 create index records_organization_collection_idx on public.records(organization_id,collection);
79 create index organization_audit_org_created_idx on public.organization_audit(organization_id,created_at desc);
80 alter table public.records drop constraint if exists records_pkey;
81 alter table public.records add constraint records_pkey primary key (organization_id,collection,id);
82 create or replace function private.current_organization_ids() returns setof uuid
83 language sql stable security definer set search_path='' as $$
84 select m.organization_id from public.organization_members m where m.user_id=(select auth.uid()) and m.status='active'
85 $$;
86 create or replace function private.default_organization_id() returns uuid
87 language sql stable security definer set search_path='' as $$
88 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
89 $$;
90 create or replace function private.is_org_owner(p_organization_id uuid) returns boolean
91 language sql stable security definer set search_path='' as $$
92 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)
93 $$;
94 create or replace function private.organization_has_module_entitlement(p_organization_id uuid,p_module_key text,p_require_active boolean default false) returns boolean
95 language sql stable security definer set search_path='' as $$
96 select case when p_module_key='core' and not p_require_active then true else exists(
97 select 1 from public.licenses l where l.organization_id=p_organization_id
98 and (p_module_key='core' or 'full_suite'=any(l.modules) or p_module_key=any(l.modules))
99 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)))
100 ) end
101 $$;
102 create or replace function private.has_org_capability(p_organization_id uuid,p_module_key text,p_capability text) returns boolean
103 language sql stable security definer set search_path='' as $$
104 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 or exists(select 1 from public.member_module_permissions p where p.organization_id=p_organization_id and p.member_id=m.id and (p.module_key=p_module_key or p.module_key='full_suite') and p_capability=any(p.capabilities))))
105 $$;
106 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) returns boolean
107 language sql stable security definer set search_path='' as $$
108 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 or exists(select 1 from public.member_module_permissions p where p.organization_id=p_organization_id and p.member_id=m.id and (p.module_key=p_module_key or p.module_key='full_suite') and p_capability=any(p.capabilities) and (p.scope_type='organization' or (p.scope_type='own' and p_owner_id=(select auth.uid())) or (p.scope_type='company' and p.scope_id=coalesce(p_data->>'companyId',p_data->>'company_id')) or (p.scope_type='branch' and p.scope_id=coalesce(p_data->>'branchId',p_data->>'branch_id')) or (p.scope_type='unit' and p.scope_id=coalesce(p_data->>'unitId',p_data->>'unit_id'))))))
109 $$;
110 create or replace function private.record_confidentiality_allowed(p_organization_id uuid,p_module_key text,p_data jsonb) returns boolean
111 language sql stable security definer set search_path='' as $$
112 with required as (select case lower(coalesce(p_data->>'confidentiality','normal')) when 'محرمانه' then 1 when 'confidential' then 1 when 'خیلی محرمانه' then 2 when 'very_confidential' then 2 when 'سری' then 3 when 'secret' then 3 else 0 end as lvl)
113 select exists(select 1 from public.organization_members m,required r where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active' and (m.is_owner or coalesce((select max(p.confidentiality_level) from public.member_module_permissions p where p.organization_id=p_organization_id and p.member_id=m.id and (p.module_key=p_module_key or p.module_key='full_suite')),-1)>=r.lvl))
114 $$;
115 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) returns boolean
116 language sql stable security definer set search_path='' as $$
117 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)
118 $$;
119 create or replace function private.has_any_configure(p_organization_id uuid) returns boolean
120 language sql stable security definer set search_path='' as $$
121 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))
122 $$;
123 revoke all on function private.current_organization_ids() from public,anon;
124 revoke all on function private.default_organization_id() from public,anon;
125 revoke all on function private.is_org_owner(uuid) from public,anon;
126 revoke all on function private.organization_has_module_entitlement(uuid,text,boolean) from public,anon;
127 revoke all on function private.has_org_capability(uuid,text,text) from public,anon;
128 revoke all on function private.record_in_member_scope(uuid,text,uuid,jsonb,text) from public,anon;
129 revoke all on function private.record_confidentiality_allowed(uuid,text,jsonb) from public,anon;
130 revoke all on function private.can_access_record(uuid,text,uuid,jsonb,text) from public,anon;
131 revoke all on function private.has_any_configure(uuid) from public,anon;
132 grant execute on function private.current_organization_ids() to authenticated;
133 grant execute on function private.default_organization_id() to authenticated;
134 grant execute on function private.is_org_owner(uuid) to authenticated;
135 grant execute on function private.organization_has_module_entitlement(uuid,text,boolean) to authenticated;
136 grant execute on function private.has_org_capability(uuid,text,text) to authenticated;
137 grant execute on function private.record_in_member_scope(uuid,text,uuid,jsonb,text) to authenticated;
138 grant execute on function private.record_confidentiality_allowed(uuid,text,jsonb) to authenticated;
139 grant execute on function private.can_access_record(uuid,text,uuid,jsonb,text) to authenticated;
140 grant execute on function private.has_any_configure(uuid) to authenticated;
141 create or replace function private.has_module_entitlement(module_key text) returns boolean
142 language sql stable security definer set search_path='' as $$
143 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
144 $$;
145 create or replace function public.has_active_license() returns boolean
146 language sql stable security definer set search_path='' as $$
147 select exists(select 1 from private.current_organization_ids() org_id where private.organization_has_module_entitlement(org_id,'core',true))
148 $$;
149 alter table public.organizations enable row level security;
150 alter table public.organization_units enable row level security;
151 alter table public.organization_members enable row level security;
152 alter table public.member_module_permissions enable row level security;
153 alter table public.organization_audit enable row level security;
154 grant select on public.organizations to authenticated;
155 grant select on public.organization_units to authenticated;
156 grant insert,update,delete on public.organization_units to authenticated;
157 grant select on public.organization_members to authenticated;
158 grant insert,update on public.organization_members to authenticated;
159 grant select on public.member_module_permissions to authenticated;
160 grant insert,update,delete on public.member_module_permissions to authenticated;
161 grant select on public.organization_audit to authenticated;
162 create policy organizations_select on public.organizations for select to authenticated using (id in (select private.current_organization_ids()));
163 create policy organization_units_select on public.organization_units for select to authenticated using (organization_id in (select private.current_organization_ids()));
164 create policy organization_units_insert on public.organization_units for insert to authenticated with check (private.is_org_owner(organization_id));
165 create policy organization_units_update on public.organization_units for update to authenticated using (private.is_org_owner(organization_id)) with check (private.is_org_owner(organization_id));
166 create policy organization_units_delete on public.organization_units for delete to authenticated using (private.is_org_owner(organization_id));
167 create policy organization_members_select on public.organization_members for select to authenticated using (organization_id in (select private.current_organization_ids()));
168 create policy organization_members_insert on public.organization_members for insert to authenticated with check (private.is_org_owner(organization_id));
169 create policy organization_members_update on public.organization_members for update to authenticated using (private.is_org_owner(organization_id)) with check (private.is_org_owner(organization_id));
170 create policy member_module_permissions_select on public.member_module_permissions for select to authenticated using (organization_id in (select private.current_organization_ids()));
171 create policy member_module_permissions_insert on public.member_module_permissions for insert to authenticated with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,module_key,'configure'));
172 create policy member_module_permissions_update on public.member_module_permissions for update to authenticated using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,module_key,'configure')) with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,module_key,'configure'));
173 create policy member_module_permissions_delete on public.member_module_permissions for delete to authenticated using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,module_key,'configure'));
174 create policy organization_audit_select on public.organization_audit for select to authenticated using (private.is_org_owner(organization_id) or private.has_any_configure(organization_id));
175 drop policy if exists profiles_select on public.profiles;
176 create policy profiles_select on public.profiles for select to authenticated using (id=(select auth.uid()) or public.is_admin() or exists(select 1 from public.organization_members target where target.user_id=public.profiles.id and target.organization_id in (select private.current_organization_ids())));
177 drop policy if exists licenses_select on public.licenses;
178 create policy licenses_select on public.licenses for select to authenticated using (user_id=(select auth.uid()) or organization_id in (select private.current_organization_ids()) or public.is_admin());
179 drop policy if exists records_select on public.records;
180 drop policy if exists records_insert on public.records;
181 drop policy if exists records_update on public.records;
182 drop policy if exists records_delete on public.records;
183 create policy records_select on public.records for select to authenticated using (private.can_access_record(organization_id,collection,owner_id,data,'read'));
184 create policy records_insert on public.records for insert to authenticated with check (private.organization_has_module_entitlement(organization_id,private.collection_module(collection),true) and (private.can_access_record(organization_id,collection,owner_id,data,'create') or (collection='correspondence' and private.can_access_record(organization_id,collection,owner_id,data,'register')) or (collection='correspondenceReferrals' and private.can_access_record(organization_id,collection,owner_id,data,'refer'))));
185 create policy records_update on public.records for update to authenticated using (private.organization_has_module_entitlement(organization_id,private.collection_module(collection),true) and (private.can_access_record(organization_id,collection,owner_id,data,'edit') or (collection='officeRegistries' and private.can_access_record(organization_id,collection,owner_id,data,'register')))) with check (private.organization_has_module_entitlement(organization_id,private.collection_module(collection),true) and (private.can_access_record(organization_id,collection,owner_id,data,'edit') or (collection='officeRegistries' and private.can_access_record(organization_id,collection,owner_id,data,'register'))));
186 create policy records_delete on public.records for delete to authenticated using (private.organization_has_module_entitlement(organization_id,private.collection_module(collection),true) and private.can_access_record(organization_id,collection,owner_id,data,'delete'));
187 create or replace function public.finora_sync_records(p_upserts jsonb default '[]'::jsonb,p_deletes jsonb default '[]'::jsonb,p_organization_id uuid default null) returns void
188 language plpgsql security invoker set search_path='' as $$
189 declare v_org uuid:=coalesce(p_organization_id,private.default_organization_id());
190 begin
191 if (select auth.uid()) is null then raise exception 'authentication required'; end if;
192 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;
193 if not private.organization_has_module_entitlement(v_org,'core',true) then raise exception 'active license required' using errcode='42501'; end if;
194 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;
195 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;
196 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;
197 end $$;
198 revoke all on function public.finora_sync_records(jsonb,jsonb,uuid) from public,anon;
199 grant execute on function public.finora_sync_records(jsonb,jsonb,uuid) to authenticated;
200 create or replace function private.organization_audit_capture() returns trigger
201 language plpgsql security definer set search_path='' as $$
202 declare v_org uuid; v_action text; v_entity text; v_entity_id text;
203 begin
204 v_org:=coalesce(new.organization_id,old.organization_id);
205 v_action:='permission_'||lower(tg_op);
206 v_entity:='member_module_permission';
207 v_entity_id:=coalesce(new.id,old.id)::text;
208 insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data)
209 values(v_org,(select auth.uid()),v_action,v_entity,v_entity_id,case when tg_op in ('UPDATE','DELETE') then to_jsonb(old) else null end,case when tg_op in ('INSERT','UPDATE') then to_jsonb(new) else null end);
210 if tg_op='DELETE' then return old; else return new; end if;
211 end $$;
212 revoke all on function private.organization_audit_capture() from public,anon,authenticated;
213 create trigger member_module_permissions_audit after insert or update or delete on public.member_module_permissions for each row execute function private.organization_audit_capture();
214 create or replace function private.organization_audit_immutable() returns trigger language plpgsql set search_path='' as $$ begin raise exception 'organization audit is immutable' using errcode='42501'; end $$;
215 revoke all on function private.organization_audit_immutable() from public,anon,authenticated;
216 create trigger organization_audit_immutable before update or delete on public.organization_audit for each row execute function private.organization_audit_immutable();