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

Prepare ELI-1 seat and delegated admin contract

davoodmehraban89 committed Sep 30, 2026 at 08:24 UTC e04e7b4929772d1d2d589dadd80e42ce08e76004
4 files changed +444 -40
.github/workflows/quality.yml
+2
@@ -42,6 +42,8 @@ jobs:
42 run: node scripts/platform-office-check.mjs
43 - name: Slice B tenant and RBAC invariants
44 run: node scripts/slice-b-rbac-check.mjs
45 + - name: Enterprise license seats and delegated admin invariants
46 + run: node scripts/enterprise-license-check.mjs
47 - name: Install browser smoke-test runtime
48 run: |
49 npm install --no-save @playwright/test@1.55.0 pdf-lib@1.17.1
PROJECT_STATE.md
+23 -40
@@ -7,60 +7,43 @@
7 Read `AGENTS.md` first, then this file. Latest user chat is the only source of new instructions; repo files are continuity/context. Detailed older history remains at `9d9caade2c3e34d7608e540e40b09ab23f0d19e9`.
8
9 ## Protocol / authority
10 -Verify live GitHub+Supabase before acting; record material requests before implementation; implement/test/fix/retest/commit/verify in vertical slices; update this file with every durable implementation commit; archive exact production SQL; never call unrun work verified. Owner granted standing authority on 2026-09-30 for in-scope GitHub/Supabase engineering, excluding platform-required confirmations, paid/public/external actions and unsafe destructive financial-history changes.
10 +Verify live GitHub+Supabase before acting; record material requests before implementation; implement/test/fix/retest/commit/verify in vertical slices; update this file with every durable implementation commit; archive exact production SQL; never call unrun work verified. Owner granted standing authority on 2026-09-30 for in-scope GitHub/Supabase engineering, excluding platform-required confirmations, paid/public/external actions and unsafe destructive financial-history changes. Owner further directed on 2026-09-30 that implementation must continue autonomously without waiting for routine confirmations; questions or progress messages must not stop executable work unless the owner explicitly says stop or a real safety/tool blocker requires input.
11
12 ## Current change ledger
13 | Date | Request / decision | Status | Evidence / next action |
14 |---|---|---|---|
15 -| 2026-09-30 | Implement the approved enterprise licensing/organization model so a sold license can carry named-user seat capacity, company capacity and module entitlements; customer can delegate organization/system administration, model regions/units/positions, invite/manage users, and assign reusable roles/permissions. Keep the design evolvable for future commercial packaging changes. | **DISCOVERY APPROVED / ARCHITECTURAL SPEC WRITTEN — IMPLEMENTATION NOT STARTED** | Live production schema confirms organization tenant, organization units, memberships, per-member module permissions, `max_companies`, module entitlements and organization-linked licenses already exist; no `max_users`/seat limit exists, `core` is not yet delegable through member permissions, member onboarding still requires a pre-existing Finora account, and reusable role templates are absent. Design: `docs/superpowers/specs/2026-09-30-enterprise-licensing-organization-identity-design.md`. Per mandatory design gate, implementation begins only after owner reviews this written spec; then create the implementation plan and execute it in vertical slices. |
16 -| 2026-09-30 | Continue closing the current-stage gap register autonomously, prioritizing production safety and real evidence. | **IN PROGRESS — SECURITY HARDENING APPLIED / CUTOVER RECONCILED / REAL-USER E2E BLOCKED BY TEST PRINCIPALS** | Live Supabase rechecked `ACTIVE_HEALTHY`. Migration `20260930041735_harden_public_security_definer_rpc_grants_search_path` applied and archived: all 7 public SECURITY DEFINER helpers now use empty `search_path`; `PUBLIC`/`anon` execute revoked; `authenticated`/`service_role` explicit. Transactional impersonation of a real non-admin principal proved all 5 admin mutators reject with SQLSTATE `42501`; advisor still reports 7 exposure warnings by design because authenticated RPC access remains intentional. Evidence: `docs/SECURITY_DEFINER_HARDENING_2026-09-30.md`. Production accounting source population re-read without mutation: 7 invoices = 4 formal + 1 non-formal eligible total `3,371,160,000`, plus 2 `pre_invoice` total `3,570,000,000`; both invoice-holding orgs have fiscal-year records but zero account masters and unset company sector, so automatic historical posting remains prohibited until owner mapping/chart approval. Evidence: `docs/PRODUCTION_ACCOUNTING_CUTOVER_READINESS_2026-09-30.md`; Phase-6 manifest wording corrected. Two-real-user E2E cannot yet be truthfully executed because all 4 organizations currently have only their owner member and zero active non-owner members; do not fabricate a second production user or grant cross-org access silently. |
17 -| 2026-09-30 | Audit Gmail GitHub `Run failed` notifications, verify/fix any still-live CI defects, and produce a severity-ranked list of remaining gaps needed to make the current Finora stage complete. | **AUDITED / HISTORICAL FAILURES TRIAGED / CI MAINTENANCE VERIFIED / GAP REGISTERED** | Gmail failures mapped to intermediate commits: old Real-DOM/request-builder failures were fixed by later browser hardening; Slice-B migration-count invariant was fixed by later archived migrations; Security failures were Dependency Review failing because GitHub Dependency graph is disabled while CodeQL passed. During this audit a CodeQL v4 modernization attempt exposed a repository invariant still pinned to v3 and generated transient main failure emails (`31ef607`, `42d2476`, `7e8e43e`); rather than weaken the gate, CodeQL was restored to supported v3. Final audit-closeout commit `5182b786dc7488146eaaa68d87dcc2f1d2c9a725` passed Quality run `36666677736`, Security run `36666677677`, and Pages run `36666676797`. Quality uses `checkout@v7` + `setup-node@v7`; security uses `checkout@v7` and CodeQL v3 until invariant+action migrate together. Prioritized register: `docs/CURRENT_STAGE_GAP_REGISTER_2026-09-30.md`. |
18 -| 2026-09-30 | Continue from verified Slice A into Slice B: organization tenant, multi-user memberships, module roles/capabilities, row scopes, confidentiality, shared office access/referral foundation and immutable permission/referral audit. | **IMPLEMENTED / MERGED / VERIFIED** | PR #7 merged as `d212c6aeef5b49f33351166771a0899f307a9067`. PR Quality `36664844247` PASS and Security `36664844234` CodeQL PASS. Final main checkpoint `99a23edcaddf542f9080bbe70bb0b450af14913f` also passed Quality `36664994360`, Security/CodeQL `36664994384`, and Pages `36664994039`. Production migrations `20260930031853`, `20260930031942`, `20260930032615`, `20260930032654`, `20260930033010` applied+archived. Production transactional tests PASS for own/org scope, confidentiality, read-only capability, member core read-only context, expired-license read-only, referral/audit immutability and member Storage-path isolation. GitHub Dependency graph remains disabled, so dependency review is not claimed. Evidence: `docs/SLICE_B_TENANT_RBAC_VERIFICATION.md`. |
19 -| 2026-09-30 | Modular organization-wide ERP: office automation/scanned correspondence/secretariat, configurable requests, module managers/permissions, module-select entry, module-by-module/full-suite licensing, future transport/operations; research Barid/ParGar, Chargoon/Didgah, Faragostar. | **SLICE A IMPLEMENTED / VERIFIED** | Request `0b622439`; implementation `d3934690`; read-only expiry hardening `906d78d7`; browser integration hardening `df82067ecb1fda9007eb11a30d0a9d7cc1b113cd`. Production migrations `20260930025546`, `20260930025647`, `20260930030314` applied+archived. Final product-head Quality `36662911587` PASS including syntax, accounting/Phase2–6/Golden, modular-office invariants and Chromium Real-DOM tests; Security `36662911572` PASS; Pages `36662911432` PASS. |
15 +| 2026-09-30 | Continue autonomously: do not pause for routine confirmations; keep implementation moving unless explicitly stopped or a real blocker requires owner action. | **ACTIVE OPERATING DIRECTIVE** | Applies to all in-scope reversible engineering work. No claim of background execution; each chat turn continues as far as available tools permit. |
16 +| 2026-09-30 | Implement approved enterprise licensing/organization identity model: named-user seat capacity, company capacity, module entitlements, delegated organization/system admin, regions/units/positions, later invitations and reusable roles; keep packaging evolvable. | **ELI-1 IMPLEMENTATION STARTED — DB CONTRACT PREPARED, PRODUCTION NOT YET APPLIED** | Approved spec: `docs/superpowers/specs/2026-09-30-enterprise-licensing-organization-identity-design.md`. Plan: `docs/superpowers/plans/2026-09-30-enterprise-licensing-eli1.md`. Live pre-change head `665c2d6e2a71026ad171e234786a4495e2211d0a`; Supabase ACTIVE_HEALTHY, 30 migrations through `20260930041735`, 4 organizations each currently one active owner. Task 1 repository contract introduces `max_users`, future-safe `limits`, atomic seat enforcement, organization-scoped company capacity, delegated `core/configure`, member suspend/reactivate, and membership audit. This commit is repository-prepared only; Production apply/transactional verification remains next. |
17 +| 2026-09-30 | Continue closing current-stage gap register autonomously, prioritizing production safety and real evidence. | **IN PROGRESS** | Security hardening migration `20260930041735` applied/archived; 7 intentional authenticated SECURITY DEFINER warnings remain plus leaked-password protection disabled. Controlled accounting cutover remains blocked by missing approved chart/company classification. |
18 +| 2026-09-30 | Audit Gmail GitHub Run failed notifications and rank remaining gaps. | **AUDITED / GAP REGISTERED** | Final audit checkpoint `5182b786dc7488146eaaa68d87dcc2f1d2c9a725` passed Quality `36666677736`, Security `36666677677`, Pages `36666676797`. Gap register: `docs/CURRENT_STAGE_GAP_REGISTER_2026-09-30.md`. |
19 +| 2026-09-30 | Slice B organization tenant/RBAC/shared office foundation. | **IMPLEMENTED / VERIFIED** | Merge `d212c6aeef5b49f33351166771a0899f307a9067`; production migrations through `20260930033010`; final verified checkpoint `99a23edcaddf542f9080bbe70bb0b450af14913f`. |
20 +| 2026-09-30 | Modular organization-wide ERP + office automation/request foundation. | **SLICE A IMPLEMENTED / VERIFIED** | Product head `df82067ecb1fda9007eb11a30d0a9d7cc1b113cd` passed Quality/Security/Pages. |
21 | 2026-09-30 | Iran-first high-assurance ERP expansion. | IN PROGRESS — broader roadmap | `docs/IRAN_COMPLIANCE_MATRIX_V1.md`; do not claim statutory consolidation/full tax submission/full HR/CRM until complete lifecycle/accounting/permissions/tests exist. |
22
23 ## Current production state — 2026-09-30
23 -- Current main head before enterprise-licensing design commit: `ab1104ff185295928f366dfad78de61032994be8`; its Pages run `36668318530` passed. The prior fully green checkpoint across Quality/Security/Pages remains `5182b786dc7488146eaaa68d87dcc2f1d2c9a725` until all applicable gates for a newer implementation head are explicitly observed.
24 +- Pre-ELI-1 live main head: `665c2d6e2a71026ad171e234786a4495e2211d0a`.
25 - Supabase `hcsixhqbyuhpshfwqpjx`: `ACTIVE_HEALTHY`, PostgreSQL `17.6.1.166`, 30 migrations through `20260930041735`.
25 -- 4 existing licenses remain `full_suite`; each license belongs to a backfilled organization whose original account is owner. Current membership check: each of the 4 organizations has exactly 1 active owner and 0 active non-owner members.
26 -- Live schema verification for the enterprise-licensing discovery: `licenses` currently has `max_companies`, `modules`, and `organization_id` but no user-seat limit; `organization_members` has unit, position, status and owner flag; `member_module_permissions` has capability/scope/confidentiality but its module-key constraint does not include `core`; `organization_units` is hierarchical.
27 -- `records` primary identity is `(organization_id, collection, id)`; RLS enforces membership/entitlement/capability/scope/confidentiality. Writes require active organization license; expired/cancelled organizations retain authorized historical reads.
28 -- Active non-owner members receive read-only `core` context for workspace initialization; core writes remain owner-only in Slice B.
29 -- Organization security metadata: `organizations`, `organization_units`, `organization_members`, `member_module_permissions`, immutable `organization_audit`.
30 -- Office registration is organization-aware; referral is server-validated and immutable; new Storage path is organization/uploader/correspondence/file and resolves access through correspondence authorization. Legacy attachment writes are owner-only.
31 -- Security hardening migration `20260930041735`: all 7 reviewed public SECURITY DEFINER helpers have empty `search_path`, no `anon` execute, and explicit authenticated/service-role execute. Non-admin mutation negative tests pass. Supabase advisor still reports the 7 authenticated-callable warnings because the RPC exposure is intentional; zero-warning architecture would require moving privileged mutation behind a non-exposed/server boundary. Leaked-password protection remains disabled.
32 -- Live performance advisor reports 5 newly-created unused-index informational notices; no unindexed-FK finding is present. Do not remove new indexes before representative workload evidence.
33 -- Production invoice history is 7 records: 4 formal + 1 non-formal eligible for controlled accounting cutover (`3,371,160,000` total), plus 2 `pre_invoice` (`3,570,000,000`) excluded from posting. Invoice-holding organizations have fiscal-year records but no account masters; company sector is unset. Controlled accounting cutover remains P0 and must not be auto-posted.
26 +- `licenses`: 4 rows, each organization-linked; before ELI-1 has `max_companies`/modules but no `max_users`.
27 +- `organization_members`: 4 rows, one active owner per organization; zero non-owner members.
28 +- RLS enabled on all listed public tables. Security advisor: 7 intentional authenticated SECURITY DEFINER warnings + leaked-password protection disabled. Performance advisor: 5 new unused-index informational findings.
29 +- Production invoice history remains 7 records; controlled accounting cutover is unchanged and not part of ELI-1.
30
35 -## Implemented Slice A
36 -- Architecture/research: `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md`.
37 -- Server-enforced commercial module entitlements; full suite or explicit module subset independent of duration/company capacity.
38 -- Module-filtered rail/commands, explicit workspace launcher and admin license module picker. Roadmap-only CRM/transport/manufacturing/maintenance disabled for sale.
39 -- Office: secretariat registries, incoming/outgoing/internal metadata, drafts, server-atomic registration number, private scan attachments, archive metadata search, OCR-ready fields.
40 -- Requests: admin-defined request type/field schema + request submission foundation.
41 -
42 -## Implemented Slice B
43 -- Organization tenant and membership model with conservative legacy backfill.
44 -- Per-member module capabilities: `read/create/edit/delete/approve/register/refer/archive/configure`.
45 -- Row scopes: own/unit/branch/company/organization; missing scope key does not broaden access.
46 -- Confidentiality clearance independent of generic module read.
47 -- Organization-aware license selection, explicit organization switcher, workspace/module visibility and sync.
48 -- Owner/member access-management surface; module configurators can assign permissions for their module. Adding a member currently requires an already-registered Finora account.
49 -- Shared office records through server RLS, capability-gated draft/register/configure/refer actions, immutable referrals and permission/referral audit.
31 +## Implemented foundations
32 +- Slice A: server-enforced commercial module entitlements, module launcher, office registries/correspondence/private scans, configurable request-type foundation.
33 +- Slice B: organizations, hierarchical units, memberships, direct per-member module capabilities, row scopes, confidentiality, organization-aware sync/license context, shared office records/referrals/audit.
34 +- Existing accounting Phases 1–6 and Iran enterprise foundation remain accepted; ELI work must not rewrite posted accounting history.
35
36 ## Invariants
52 -Posted accounting history is immutable and balanced; tenant isolation is data-boundary enforced; commercial module entitlement and member authorization are independent; UI hiding is never security; expired licenses are read-only; office numbers are server-atomic; binary scans stay in private Storage; roadmap-only modules are not presented as operational.
37 +Posted accounting history is immutable and balanced; tenant isolation is enforced at the data boundary; commercial entitlement and member authorization are independent; UI hiding is never security; expired licenses are read-only; office numbering is server-atomic; private scans remain private; seat/company limits are server-enforced; no delegated customer admin can mutate commercial license entitlements.
38
39 ## Required evidence
55 -`docs/PHASE_1_REDESIGN_VERIFICATION.md` · `docs/PHASE_2_REDESIGN_VERIFICATION.md` · `docs/PHASE_3_REDESIGN_VERIFICATION.md` · `docs/PHASE_4_REDESIGN_VERIFICATION.md` · `docs/PHASE_5_VERIFICATION.md` · `docs/PHASE_6_VERIFICATION.md` · `docs/PHASE_6_CUTOVER_MANIFEST.md` · `docs/PRODUCTION_ACCOUNTING_CUTOVER_READINESS_2026-09-30.md` · `docs/IRAN_COMPLIANCE_MATRIX_V1.md` · `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md` · `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md` · `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md` · `docs/SLICE_B_TENANT_RBAC_VERIFICATION.md` · `docs/SECURITY_DEFINER_HARDENING_2026-09-30.md` · `docs/CURRENT_STAGE_GAP_REGISTER_2026-09-30.md` · `docs/superpowers/specs/2026-09-30-enterprise-licensing-organization-identity-design.md` · `docs/PRODUCTION_RUNBOOK.md` · `supabase/migrations/`.
40 +`docs/PHASE_1_REDESIGN_VERIFICATION.md` · `docs/PHASE_2_REDESIGN_VERIFICATION.md` · `docs/PHASE_3_REDESIGN_VERIFICATION.md` · `docs/PHASE_4_REDESIGN_VERIFICATION.md` · `docs/PHASE_5_VERIFICATION.md` · `docs/PHASE_6_VERIFICATION.md` · `docs/PHASE_6_CUTOVER_MANIFEST.md` · `docs/PRODUCTION_ACCOUNTING_CUTOVER_READINESS_2026-09-30.md` · `docs/IRAN_COMPLIANCE_MATRIX_V1.md` · `docs/FINORA_ERP_EXPANSION_ROADMAP_V4.md` · `docs/FINORA_UX_ACCOUNTING_BENCHMARK_V3.md` · `docs/FINORA_MODULAR_ERP_OFFICE_AUTOMATION_V1.md` · `docs/SLICE_B_TENANT_RBAC_VERIFICATION.md` · `docs/SECURITY_DEFINER_HARDENING_2026-09-30.md` · `docs/CURRENT_STAGE_GAP_REGISTER_2026-09-30.md` · `docs/superpowers/specs/2026-09-30-enterprise-licensing-organization-identity-design.md` · `docs/superpowers/plans/2026-09-30-enterprise-licensing-eli1.md` · `docs/PRODUCTION_RUNBOOK.md` · `supabase/migrations/`.
41
42 ## NOT VERIFIED / external boundary
58 -Authenticated two-real-user production browser E2E (no active non-owner member exists yet); member invitation without a pre-existing account; named-user seat enforcement and delegated organization administration (design only, not implemented yet); owner-approved chart/mapping and controlled posting/reconciliation of existing production invoices; real Persian OCR accuracy; qualified digital signature; physical printer; third-party webhook/ECE/email gateways; GitHub Dependency graph/dependency-review availability; Supabase leaked-password protection; zero-warning architectural replacement for public authenticated SECURITY DEFINER RPC exposure; PostgreSQL 17.11 platform upgrade; CodeQL v4 migration.
43 +Authenticated two-real-user production browser E2E; ELI-2 reusable roles; ELI-3 invitations for users without an account; owner-approved accounting cutover; real Persian OCR; qualified digital signature; physical printer; live external adapters; GitHub Dependency graph; leaked-password protection; PostgreSQL 17.11 upgrade; CodeQL v4 migration.
44
45 ## Exact next executable work
61 -1. Review/approve `docs/superpowers/specs/2026-09-30-enterprise-licensing-organization-identity-design.md`; then write the implementation plan and execute the enterprise licensing/organization identity slice before Slice C so office automation inherits the final user/admin/seat model.
62 -2. Do not fabricate P0 closure: two-real-user browser E2E needs a legitimate second test/member principal; accounting cutover needs owner chart/company-type approval because sector is unset and account masters are absent.
63 -3. Continue independent P1/P2 hardening that does not require those decisions: leaked-password platform configuration when the platform exposes a controllable setting, dependency graph when repository administration is available, and CodeQL v4 invariant+action migration as one tested PR.
64 -4. Slice C: mature office lifecycle — templates/editor, signatures/approval, referral chains/read receipts, SLA/reminders, reply/related-letter graph, archive classification, OCR/full-text and integration adapters.
65 -5. Slice D: versioned workflow engine for configurable requests — steps, conditions, parallel/sequential approval, delegation/substitution, SLA/escalation and immutable action history.
66 -6. Slice E: transport/procurement/service/CRM/manufacturing/maintenance only as complete tested vertical modules with accounting/permissions/reporting integration.
46 +1. Apply/reconcile ELI-1 Task 1 migration after repository static/CI checks; run transactional adversarial SQL verification.
47 +2. Implement ELI-1 Task 2 runtime/admin UI and Task 3 Real-DOM coverage; keep state in same durable commits.
48 +3. Close ELI-1 only after Production seat/RLS verification + Real-DOM + accounting invariants + Quality/Security/Pages.
49 +4. Then continue ELI-2 roles, ELI-3 invitations, ELI-4 enterprise organization UX/real-user verification before mature Office Slice C.
scripts/enterprise-license-check.mjs new
+21
@@ -0,0 +1,21 @@
1 +import fs from 'node:fs';
2 +
3 +const need=(text,rx,label)=>{if(!rx.test(text))throw new Error('ELI-1 invariant missing: '+label)};
4 +const migration=fs.readFileSync('supabase/migrations/20260930050000_enterprise_license_seats_delegated_admin.sql','utf8');
5 +need(migration,/add column if not exists max_users/i,'max_users');
6 +need(migration,/add column if not exists limits jsonb/i,'future-safe limits metadata');
7 +need(migration,/organization_active_member_count/i,'active seat count helper');
8 +need(migration,/organization_has_seat/i,'seat availability helper');
9 +need(migration,/for update;[\s\S]*named-user seat limit exceeded/i,'atomic license-row seat locking');
10 +need(migration,/admin_set_user_limit/i,'platform user-capacity RPC');
11 +need(migration,/new_max_users<v_active/i,'cannot reduce user limit below usage');
12 +need(migration,/module_key = any\(array\[[\s\S]*'core'/i,'core permission domain');
13 +need(migration,/organization_id=v_org and r\.collection='companies'/i,'organization-scoped company capacity');
14 +need(migration,/has_org_capability\(p_organization_id,'core','configure'\)/i,'delegated core configure');
15 +need(migration,/organization_set_member_status/i,'suspend-reactivate RPC');
16 +need(migration,/organization_members_audit/i,'membership audit');
17 +
18 +const q=fs.readFileSync('.github/workflows/quality.yml','utf8');
19 +need(q,/Enterprise license seats and delegated admin invariants[\s\S]*enterprise-license-check\.mjs/i,'quality workflow entry');
20 +
21 +console.log('ELI-1 database contract invariants: PASS');
supabase/migrations/20260930050000_enterprise_license_seats_delegated_admin.sql new
+398
@@ -0,0 +1,398 @@
1 +-- ELI-1: enterprise named-user seats + delegated organization administration.
2 +-- Additive migration. Does not rewrite accounting history or tenant identities.
3 +
4 +alter table public.licenses
5 + add column if not exists max_users integer not null default 1,
6 + add column if not exists limits jsonb not null default '{}'::jsonb;
7 +
8 +alter table public.licenses drop constraint if exists licenses_max_users_check;
9 +alter table public.licenses add constraint licenses_max_users_check check (max_users between 1 and 100000);
10 +
11 +alter table public.licenses drop constraint if exists licenses_limits_object_check;
12 +alter table public.licenses add constraint licenses_limits_object_check check (jsonb_typeof(limits)='object');
13 +
14 +update public.licenses l
15 +set max_users = greatest(
16 + l.max_users,
17 + coalesce((
18 + select count(*)::integer
19 + from public.organization_members m
20 + where m.organization_id=l.organization_id and m.status='active'
21 + ),0),
22 + 1
23 +);
24 +
25 +alter table public.member_module_permissions
26 + drop constraint if exists member_module_permissions_module_key_check;
27 +alter table public.member_module_permissions
28 + add constraint member_module_permissions_module_key_check
29 + check (module_key = any(array[
30 + 'core','full_suite','accounting','commerce','treasury','contracting','inventory','assets',
31 + 'hr_payroll','office_automation','requests_workflow','crm','transport','manufacturing',
32 + 'maintenance','group_consolidation','analytics'
33 + ]::text[]));
34 +
35 +create or replace function private.organization_active_member_count(p_organization_id uuid)
36 +returns integer
37 +language sql stable security definer set search_path=''
38 +as $$
39 + select count(*)::integer
40 + from public.organization_members m
41 + where m.organization_id=p_organization_id and m.status='active'
42 +$$;
43 +
44 +create or replace function private.organization_has_seat(
45 + p_organization_id uuid,
46 + p_excluding_member uuid default null
47 +)
48 +returns boolean
49 +language sql stable security definer set search_path=''
50 +as $$
51 + select coalesce((
52 + select (
53 + select count(*)
54 + from public.organization_members m
55 + where m.organization_id=p_organization_id
56 + and m.status='active'
57 + and (p_excluding_member is null or m.id<>p_excluding_member)
58 + ) < l.max_users
59 + from public.licenses l
60 + where l.organization_id=p_organization_id
61 + ), false)
62 +$$;
63 +
64 +revoke all on function private.organization_active_member_count(uuid) from public,anon;
65 +revoke all on function private.organization_has_seat(uuid,uuid) from public,anon;
66 +grant execute on function private.organization_active_member_count(uuid) to authenticated;
67 +grant execute on function private.organization_has_seat(uuid,uuid) to authenticated;
68 +
69 +create or replace function private.enforce_organization_member_seat()
70 +returns trigger
71 +language plpgsql security definer set search_path=''
72 +as $$
73 +declare v_limit integer; v_active integer;
74 +begin
75 + if new.status<>'active' then return new; end if;
76 + if tg_op='UPDATE' and old.status='active' and old.organization_id=new.organization_id then return new; end if;
77 +
78 + select l.max_users into v_limit
79 + from public.licenses l
80 + where l.organization_id=new.organization_id
81 + for update;
82 +
83 + if v_limit is null then
84 + raise exception 'organization license not found' using errcode='23503';
85 + end if;
86 +
87 + select count(*)::integer into v_active
88 + from public.organization_members m
89 + where m.organization_id=new.organization_id
90 + and m.status='active'
91 + and (tg_op='INSERT' or m.id<>new.id);
92 +
93 + if v_active >= v_limit then
94 + raise exception 'named-user seat limit exceeded' using errcode='23514';
95 + end if;
96 + return new;
97 +end $$;
98 +
99 +revoke all on function private.enforce_organization_member_seat() from public,anon,authenticated;
100 +
101 +drop trigger if exists trg_organization_member_seat on public.organization_members;
102 +create trigger trg_organization_member_seat
103 +before insert or update of status,organization_id on public.organization_members
104 +for each row execute function private.enforce_organization_member_seat();
105 +
106 +create or replace function public.admin_set_user_limit(target uuid,new_max_users integer)
107 +returns void
108 +language plpgsql security definer set search_path=''
109 +as $$
110 +declare v_org uuid; v_active integer;
111 +begin
112 + if not public.is_admin() then raise exception 'forbidden' using errcode='42501'; end if;
113 + if new_max_users is null or new_max_users<1 or new_max_users>100000 then raise exception 'invalid user limit'; end if;
114 +
115 + select l.organization_id into v_org
116 + from public.licenses l where l.user_id=target
117 + for update;
118 + if v_org is null then raise exception 'user/license not found'; end if;
119 +
120 + select count(*)::integer into v_active
121 + from public.organization_members m
122 + where m.organization_id=v_org and m.status='active';
123 +
124 + if new_max_users<v_active then raise exception 'user limit below active member count'; end if;
125 +
126 + update public.licenses
127 + set max_users=new_max_users,updated_at=now()
128 + where user_id=target;
129 +end $$;
130 +
131 +revoke all on function public.admin_set_user_limit(uuid,integer) from public,anon;
132 +grant execute on function public.admin_set_user_limit(uuid,integer) to authenticated,service_role;
133 +
134 +create or replace function public.admin_set_company_limit(target uuid,new_max_companies integer)
135 +returns void
136 +language plpgsql security definer set search_path=''
137 +as $$
138 +declare v_org uuid; existing_count integer;
139 +begin
140 + if not public.is_admin() then raise exception 'forbidden' using errcode='42501'; end if;
141 + if new_max_companies is null or new_max_companies<1 or new_max_companies>1000 then raise exception 'invalid company limit'; end if;
142 +
143 + select l.organization_id into v_org
144 + from public.licenses l where l.user_id=target
145 + for update;
146 + if v_org is null then raise exception 'user/license not found'; end if;
147 +
148 + select count(*)::integer into existing_count
149 + from public.records r
150 + where r.organization_id=v_org and r.collection='companies';
151 +
152 + if existing_count>new_max_companies then raise exception 'company limit below existing company count'; end if;
153 +
154 + update public.licenses
155 + set max_companies=new_max_companies,updated_at=now()
156 + where user_id=target;
157 +end $$;
158 +
159 +alter function public.admin_set_company_limit(uuid,integer) set search_path='';
160 +revoke all on function public.admin_set_company_limit(uuid,integer) from public,anon;
161 +grant execute on function public.admin_set_company_limit(uuid,integer) to authenticated,service_role;
162 +
163 +create or replace function public.finora_enforce_company_license_limit()
164 +returns trigger
165 +language plpgsql security definer set search_path=''
166 +as $$
167 +declare allowed_count integer; actual_count integer;
168 +begin
169 + if new.collection<>'companies' then return new; end if;
170 +
171 + select l.max_companies into allowed_count
172 + from public.licenses l
173 + where l.organization_id=new.organization_id
174 + for update;
175 +
176 + if allowed_count is null then raise exception 'organization license not found' using errcode='23503'; end if;
177 +
178 + select count(*)::integer into actual_count
179 + from public.records r
180 + where r.organization_id=new.organization_id and r.collection='companies';
181 +
182 + if actual_count>allowed_count then
183 + raise exception 'company license limit exceeded' using errcode='23514';
184 + end if;
185 + return new;
186 +end $$;
187 +
188 +revoke all on function public.finora_enforce_company_license_limit() from public,anon,authenticated;
189 +
190 +create or replace function public.organization_add_member(
191 + p_organization_id uuid,
192 + p_email text,
193 + p_unit_id uuid default null,
194 + p_position_title text default null
195 +)
196 +returns uuid
197 +language plpgsql security invoker set search_path=''
198 +as $$
199 +declare v_user uuid; v_member uuid;
200 +begin
201 + if not (
202 + private.is_org_owner(p_organization_id)
203 + or private.has_org_capability(p_organization_id,'core','configure')
204 + ) then raise exception 'forbidden' using errcode='42501'; end if;
205 +
206 + v_user:=private.profile_id_by_email(p_email);
207 + if v_user is null then raise exception 'Finora user not found for email'; end if;
208 +
209 + if p_unit_id is not null and not exists(
210 + select 1 from public.organization_units u
211 + where u.id=p_unit_id and u.organization_id=p_organization_id and u.active
212 + ) then raise exception 'invalid organization unit'; end if;
213 +
214 + insert into public.organization_members(organization_id,user_id,unit_id,position_title,status,is_owner)
215 + values(p_organization_id,v_user,p_unit_id,nullif(trim(p_position_title),''),'active',false)
216 + on conflict(organization_id,user_id) do update
217 + set unit_id=excluded.unit_id,
218 + position_title=excluded.position_title,
219 + status='active',
220 + updated_at=now()
221 + where not public.organization_members.is_owner
222 + returning id into v_member;
223 +
224 + if v_member is null then raise exception 'owner membership cannot be replaced'; end if;
225 + return v_member;
226 +end $$;
227 +
228 +revoke all on function public.organization_add_member(uuid,text,uuid,text) from public,anon;
229 +grant execute on function public.organization_add_member(uuid,text,uuid,text) to authenticated;
230 +
231 +create or replace function public.organization_set_member_status(
232 + p_organization_id uuid,
233 + p_member_id uuid,
234 + p_status text
235 +)
236 +returns void
237 +language plpgsql security invoker set search_path=''
238 +as $$
239 +begin
240 + if p_status not in ('active','suspended','left') then raise exception 'invalid member status'; end if;
241 + if not (
242 + private.is_org_owner(p_organization_id)
243 + or private.has_org_capability(p_organization_id,'core','configure')
244 + ) then raise exception 'forbidden' using errcode='42501'; end if;
245 +
246 + update public.organization_members m
247 + set status=p_status,updated_at=now()
248 + where m.id=p_member_id and m.organization_id=p_organization_id and not m.is_owner;
249 +
250 + if not found then raise exception 'member not found or owner status is protected'; end if;
251 +end $$;
252 +
253 +revoke all on function public.organization_set_member_status(uuid,uuid,text) from public,anon;
254 +grant execute on function public.organization_set_member_status(uuid,uuid,text) to authenticated;
255 +
256 +create or replace function public.organization_set_member_permission(
257 + p_organization_id uuid,
258 + p_member_id uuid,
259 + p_module_key text,
260 + p_capabilities text[],
261 + p_scope_type text default 'own',
262 + p_scope_id text default null,
263 + p_confidentiality_level smallint default 0
264 +)
265 +returns uuid
266 +language plpgsql security invoker set search_path=''
267 +as $$
268 +declare v_id uuid; v_allowed boolean:=false;
269 +begin
270 + if p_module_key='core' then
271 + v_allowed:=private.is_org_owner(p_organization_id)
272 + or private.has_org_capability(p_organization_id,'core','configure');
273 + elsif p_module_key='full_suite' then
274 + v_allowed:=private.is_org_owner(p_organization_id)
275 + and private.organization_has_module_entitlement(p_organization_id,'full_suite',false);
276 + else
277 + v_allowed:=(private.is_org_owner(p_organization_id)
278 + or private.has_org_capability(p_organization_id,p_module_key,'configure'))
279 + and private.organization_has_module_entitlement(p_organization_id,p_module_key,false);
280 + end if;
281 +
282 + if not v_allowed then raise exception 'forbidden' using errcode='42501'; end if;
283 +
284 + if not exists(
285 + select 1 from public.organization_members m
286 + where m.id=p_member_id and m.organization_id=p_organization_id and not m.is_owner
287 + ) then raise exception 'member not found or owner permission is implicit'; end if;
288 +
289 + insert into public.member_module_permissions(
290 + organization_id,member_id,module_key,capabilities,scope_type,scope_id,confidentiality_level
291 + )
292 + values(
293 + p_organization_id,p_member_id,p_module_key,p_capabilities,p_scope_type,p_scope_id,p_confidentiality_level
294 + )
295 + on conflict(organization_id,member_id,module_key,scope_type,scope_id) do update
296 + set capabilities=excluded.capabilities,
297 + confidentiality_level=excluded.confidentiality_level,
298 + updated_at=now()
299 + returning id into v_id;
300 +
301 + return v_id;
302 +end $$;
303 +
304 +revoke all on function public.organization_set_member_permission(uuid,uuid,text,text[],text,text,smallint) from public,anon;
305 +grant execute on function public.organization_set_member_permission(uuid,uuid,text,text[],text,text,smallint) to authenticated;
306 +
307 +drop policy if exists organization_units_insert on public.organization_units;
308 +drop policy if exists organization_units_update on public.organization_units;
309 +drop policy if exists organization_units_delete on public.organization_units;
310 +create policy organization_units_insert on public.organization_units for insert to authenticated
311 +with check (
312 + private.is_org_owner(organization_id)
313 + or private.has_org_capability(organization_id,'core','configure')
314 +);
315 +create policy organization_units_update on public.organization_units for update to authenticated
316 +using (
317 + private.is_org_owner(organization_id)
318 + or private.has_org_capability(organization_id,'core','configure')
319 +)
320 +with check (
321 + private.is_org_owner(organization_id)
322 + or private.has_org_capability(organization_id,'core','configure')
323 +);
324 +create policy organization_units_delete on public.organization_units for delete to authenticated
325 +using (
326 + private.is_org_owner(organization_id)
327 + or private.has_org_capability(organization_id,'core','configure')
328 +);
329 +
330 +drop policy if exists organization_members_insert on public.organization_members;
331 +drop policy if exists organization_members_update on public.organization_members;
332 +create policy organization_members_insert on public.organization_members for insert to authenticated
333 +with check (
334 + not is_owner
335 + and (
336 + private.is_org_owner(organization_id)
337 + or private.has_org_capability(organization_id,'core','configure')
338 + )
339 +);
340 +create policy organization_members_update on public.organization_members for update to authenticated
341 +using (
342 + not is_owner
343 + and (
344 + private.is_org_owner(organization_id)
345 + or private.has_org_capability(organization_id,'core','configure')
346 + )
347 +)
348 +with check (
349 + not is_owner
350 + and (
351 + private.is_org_owner(organization_id)
352 + or private.has_org_capability(organization_id,'core','configure')
353 + )
354 +);
355 +
356 +create or replace function private.organization_audit_capture()
357 +returns trigger
358 +language plpgsql security definer set search_path=''
359 +as $$
360 +declare v_org uuid; v_action text; v_entity text; v_entity_id text;
361 +begin
362 + if tg_table_name='member_module_permissions' then
363 + v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;
364 + v_action:='permission_'||lower(tg_op);
365 + v_entity:='member_module_permission';
366 + v_entity_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;
367 + elsif tg_table_name='organization_members' then
368 + v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;
369 + v_action:='membership_'||lower(tg_op);
370 + v_entity:='organization_member';
371 + v_entity_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;
372 + elsif tg_table_name='records' then
373 + v_org:=new.organization_id;
374 + v_action:='referral_insert';
375 + v_entity:='correspondence_referral';
376 + v_entity_id:=new.id;
377 + else
378 + if tg_op='DELETE' then return old; else return new; end if;
379 + end if;
380 +
381 + insert into public.organization_audit(
382 + organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data
383 + )
384 + values(
385 + v_org,(select auth.uid()),v_action,v_entity,v_entity_id,
386 + case when tg_op in ('UPDATE','DELETE') then to_jsonb(old) else null end,
387 + case when tg_op in ('INSERT','UPDATE') then to_jsonb(new) else null end
388 + );
389 +
390 + if tg_op='DELETE' then return old; else return new; end if;
391 +end $$;
392 +
393 +drop trigger if exists organization_members_audit on public.organization_members;
394 +create trigger organization_members_audit
395 +after insert or update on public.organization_members
396 +for each row execute function private.organization_audit_capture();
397 +
398 +-- Existing member-module and referral audit triggers continue to use the replaced capture function.