سامانه صدور فاکتور و حسابداری
Prepare ELI-2 reusable organization roles
davoodmehraban89 committed
Sep 30, 2026 at 08:34 UTC
027b5082d769fd766f97096b12276052031d1193
5 files changed
+465
-1
.github/workflows/quality.yml
+2
@@ -44,6 +44,8 @@ jobs:
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: Reusable organization roles invariants
48
+ run: node scripts/enterprise-role-check.mjs
49
- name: Install browser smoke-test runtime
50
run: |
51
npm install --no-save @playwright/test@1.55.0 pdf-lib@1.17.1
PROJECT_STATE.md
+2
-1
@@ -13,6 +13,7 @@ Verify live GitHub+Supabase before acting; record material requests before imple
13
| Date | Request / decision | Status | Evidence / next action |
14
|---|---|---|---|
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 | Continue into ELI-2 reusable tenant roles without pausing after ELI-1; preserve direct member grants as overrides and keep commercial entitlement independent. | **ELI-2 SERVER CONTRACT PREPARED — PRODUCTION NOT YET APPLIED** | Plan: `docs/superpowers/plans/2026-09-30-enterprise-licensing-eli2-roles.md`. Repository migration adds tenant-scoped role catalog, role permissions, member assignments, starter roles, effective authorization union and audit. Production apply/adversarial verification remains pending. |
17
| 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 IMPLEMENTED / PRODUCTION + REAL-DOM VERIFIED** | 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 commit `e04e7b49` introduced the server contract; Task 2–3 product head `b410145a5e821b3f39453ba10008b80d52151c37` added platform-admin capacity UI, organization seat counters, delegated `core/configure`, suspend/reactivate UI and Chromium coverage. Production migration `20260930045827_enterprise_license_seats_delegated_admin` applied successfully. Transactional adversarial verification PASS using only existing legitimate principals and ROLLBACK test data: platform admin capacity mutation succeeds; non-admin commercial mutation rejects; limit-below-usage rejects; suspension frees a seat; reactivation at capacity rejects atomically; delegated core/configure manages non-owner member/unit; ordinary member denied; module configurator cannot cross-grant another module; company capacity counts legal-company records and ignores organization units; membership audit is emitted. No test residue remained and 0/4 licenses are below active-user or company usage. Product-head Quality `36671228468` PASS including accounting/Golden/ELI invariant and all Real-DOM specs; Security `36671228442` PASS; Pages `36671227923` PASS. Evidence: `docs/ELI_1_ENTERPRISE_LICENSE_VERIFICATION.md`. |
18
| 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. |
19
| 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`. |
@@ -43,7 +44,7 @@ Posted accounting history is immutable and balanced; tenant isolation is enforce
44
Authenticated two-real-user production browser E2E with a persistent legitimate non-owner member; 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.
45
46
## Exact next executable work
46
-1. Continue directly with ELI-2 reusable organization roles and effective-permission union; preserve direct grants as explicit overrides.
47
+1. ELI-2 reusable organization roles is now IN PROGRESS: server contract prepared for role catalog, role permissions, assignments and effective direct+role permission union; apply only after repository gates pass.
48
2. Then ELI-3 secure invitation lifecycle with atomic seat-safe acceptance and audit.
49
3. ELI-4 organization-tree UX/unit kinds and authenticated two-real-user browser verification when a legitimate persistent non-owner principal exists.
50
4. Then resume mature Office Slice C on the finalized enterprise identity/RBAC model.
docs/superpowers/plans/2026-09-30-enterprise-licensing-eli2-roles.md
new
+21
@@ -0,0 +1,21 @@
1
+# Enterprise Licensing ELI-2 — Reusable Roles Plan
2
+
3
+Date: 2026-09-30
4
+
5
+Goal: add reusable tenant-scoped role templates without replacing direct member grants.
6
+
7
+Deliverables:
8
+1. `organization_roles`, `organization_role_permissions`, `organization_member_roles`.
9
+2. Owner/`core.configure` role administration only.
10
+3. Effective authorization = direct member grants UNION active role grants, still intersected with commercial module entitlement, row scope and confidentiality.
11
+4. Starter roles seeded per organization but never auto-assigned.
12
+5. Role mutations audited.
13
+6. Runtime/UI role assignment and editing in a later ELI-2 product commit after the server contract is verified.
14
+7. Production migration + adversarial tests before completion.
15
+
16
+Security:
17
+- system roles cannot be deleted or have identity rewritten;
18
+- role permission cannot activate an unlicensed module;
19
+- module-only configurators do not become role administrators;
20
+- assignments are tenant-bound and cannot target owners;
21
+- stale permissions after commercial module reduction remain ineffective because entitlement is an independent gate.
scripts/enterprise-role-check.mjs
new
+16
@@ -0,0 +1,16 @@
1
+import fs from 'node:fs';
2
+const need=(text,rx,label)=>{if(!rx.test(text))throw new Error('ELI-2 invariant missing: '+label)};
3
+const m=fs.readFileSync('supabase/migrations/20260930052000_enterprise_reusable_roles.sql','utf8');
4
+need(m,/create table if not exists public\.organization_roles/i,'role catalog');
5
+need(m,/create table if not exists public\.organization_role_permissions/i,'role permissions');
6
+need(m,/create table if not exists public\.organization_member_roles/i,'member role assignments');
7
+need(m,/organization_upsert_role/i,'role upsert RPC');
8
+need(m,/organization_set_role_permission/i,'role permission RPC');
9
+need(m,/organization_assign_member_role/i,'role assignment RPC');
10
+need(m,/role_permission_allowed/i,'commercial entitlement validation');
11
+need(m,/organization_member_roles mr[\s\S]*organization_role_permissions rp/i,'role grants included in effective authorization');
12
+need(m,/system_admin[\s\S]*finance_manager[\s\S]*accountant[\s\S]*petty_cash[\s\S]*secretariat/i,'starter roles');
13
+need(m,/organization_role_audit_capture/i,'role audit');
14
+const q=fs.readFileSync('.github/workflows/quality.yml','utf8');
15
+need(q,/Reusable organization roles invariants[\s\S]*enterprise-role-check\.mjs/i,'quality workflow');
16
+console.log('ELI-2 reusable role database contract: PASS');
supabase/migrations/20260930052000_enterprise_reusable_roles.sql
new
+424
@@ -0,0 +1,424 @@
1
+-- ELI-2: reusable organization roles and effective-permission union.
2
+
3
+create table if not exists public.organization_roles (
4
+ id uuid primary key default gen_random_uuid(),
5
+ organization_id uuid not null references public.organizations(id) on delete cascade,
6
+ role_key text not null check (role_key ~ '^[a-z][a-z0-9_]{1,63}$'),
7
+ title text not null check (char_length(trim(title)) between 1 and 120),
8
+ description text,
9
+ is_system boolean not null default false,
10
+ active boolean not null default true,
11
+ created_by uuid references public.profiles(id) on delete set null,
12
+ created_at timestamptz not null default now(),
13
+ updated_at timestamptz not null default now(),
14
+ unique (organization_id,role_key)
15
+);
16
+
17
+create table if not exists public.organization_role_permissions (
18
+ id uuid primary key default gen_random_uuid(),
19
+ organization_id uuid not null references public.organizations(id) on delete cascade,
20
+ role_id uuid not null references public.organization_roles(id) on delete cascade,
21
+ module_key text not null check (module_key = any(array[
22
+ 'core','full_suite','accounting','commerce','treasury','contracting','inventory','assets',
23
+ 'hr_payroll','office_automation','requests_workflow','crm','transport','manufacturing',
24
+ 'maintenance','group_consolidation','analytics'
25
+ ]::text[])),
26
+ capabilities text[] not null default array['read']::text[],
27
+ scope_type text not null default 'own' check (scope_type in ('own','unit','branch','company','organization')),
28
+ scope_id text,
29
+ confidentiality_level smallint not null default 0 check (confidentiality_level between 0 and 3),
30
+ created_at timestamptz not null default now(),
31
+ updated_at timestamptz not null default now(),
32
+ check (capabilities <@ array['read','create','edit','delete','approve','register','refer','archive','configure']::text[]),
33
+ check (cardinality(capabilities)>0),
34
+ 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)),
35
+ unique nulls not distinct (organization_id,role_id,module_key,scope_type,scope_id)
36
+);
37
+
38
+create table if not exists public.organization_member_roles (
39
+ id uuid primary key default gen_random_uuid(),
40
+ organization_id uuid not null references public.organizations(id) on delete cascade,
41
+ member_id uuid not null references public.organization_members(id) on delete cascade,
42
+ role_id uuid not null references public.organization_roles(id) on delete cascade,
43
+ assigned_by uuid references public.profiles(id) on delete set null,
44
+ active boolean not null default true,
45
+ created_at timestamptz not null default now(),
46
+ updated_at timestamptz not null default now(),
47
+ unique (organization_id,member_id,role_id)
48
+);
49
+
50
+create index if not exists organization_roles_org_idx on public.organization_roles(organization_id,active,role_key);
51
+create index if not exists organization_role_permissions_role_idx on public.organization_role_permissions(role_id,module_key);
52
+create index if not exists organization_member_roles_member_idx on public.organization_member_roles(member_id,active);
53
+create index if not exists organization_member_roles_role_idx on public.organization_member_roles(role_id,active);
54
+
55
+alter table public.organization_roles enable row level security;
56
+alter table public.organization_role_permissions enable row level security;
57
+alter table public.organization_member_roles enable row level security;
58
+
59
+grant select,insert,update,delete on public.organization_roles to authenticated;
60
+grant select,insert,update,delete on public.organization_role_permissions to authenticated;
61
+grant select,insert,update,delete on public.organization_member_roles to authenticated;
62
+
63
+create policy organization_roles_select on public.organization_roles for select to authenticated
64
+using (organization_id in (select private.current_organization_ids()));
65
+create policy organization_roles_mutate_insert on public.organization_roles for insert to authenticated
66
+with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
67
+create policy organization_roles_mutate_update on public.organization_roles for update to authenticated
68
+using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'))
69
+with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
70
+create policy organization_roles_mutate_delete on public.organization_roles for delete to authenticated
71
+using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
72
+
73
+create policy organization_role_permissions_select on public.organization_role_permissions for select to authenticated
74
+using (organization_id in (select private.current_organization_ids()));
75
+create policy organization_role_permissions_mutate_insert on public.organization_role_permissions for insert to authenticated
76
+with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
77
+create policy organization_role_permissions_mutate_update on public.organization_role_permissions for update to authenticated
78
+using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'))
79
+with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
80
+create policy organization_role_permissions_mutate_delete on public.organization_role_permissions for delete to authenticated
81
+using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
82
+
83
+create policy organization_member_roles_select on public.organization_member_roles for select to authenticated
84
+using (organization_id in (select private.current_organization_ids()));
85
+create policy organization_member_roles_mutate_insert on public.organization_member_roles for insert to authenticated
86
+with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
87
+create policy organization_member_roles_mutate_update on public.organization_member_roles for update to authenticated
88
+using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'))
89
+with check (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
90
+create policy organization_member_roles_mutate_delete on public.organization_member_roles for delete to authenticated
91
+using (private.is_org_owner(organization_id) or private.has_org_capability(organization_id,'core','configure'));
92
+
93
+create or replace function private.protect_system_organization_role()
94
+returns trigger language plpgsql set search_path=''
95
+as $$
96
+begin
97
+ if tg_op='DELETE' and old.is_system then
98
+ raise exception 'system role cannot be deleted' using errcode='42501';
99
+ end if;
100
+ if tg_op='UPDATE' and old.is_system and (new.role_key<>old.role_key or not new.is_system) then
101
+ raise exception 'system role identity is immutable' using errcode='42501';
102
+ end if;
103
+ if tg_op='DELETE' then return old; else return new; end if;
104
+end $$;
105
+
106
+revoke all on function private.protect_system_organization_role() from public,anon,authenticated;
107
+drop trigger if exists trg_protect_system_organization_role on public.organization_roles;
108
+create trigger trg_protect_system_organization_role
109
+before update or delete on public.organization_roles
110
+for each row execute function private.protect_system_organization_role();
111
+
112
+create or replace function private.role_permission_allowed(
113
+ p_organization_id uuid,
114
+ p_module_key text
115
+)
116
+returns boolean
117
+language sql stable security definer set search_path=''
118
+as $$
119
+ select case
120
+ when p_module_key='core' then true
121
+ when p_module_key='full_suite' then private.organization_has_module_entitlement(p_organization_id,'full_suite',false)
122
+ else private.organization_has_module_entitlement(p_organization_id,p_module_key,false)
123
+ end
124
+$$;
125
+
126
+revoke all on function private.role_permission_allowed(uuid,text) from public,anon;
127
+grant execute on function private.role_permission_allowed(uuid,text) to authenticated;
128
+
129
+create or replace function public.organization_upsert_role(
130
+ p_organization_id uuid,
131
+ p_role_key text,
132
+ p_title text,
133
+ p_description text default null,
134
+ p_active boolean default true
135
+)
136
+returns uuid
137
+language plpgsql security invoker set search_path=''
138
+as $$
139
+declare v_id uuid;
140
+begin
141
+ if not (private.is_org_owner(p_organization_id) or private.has_org_capability(p_organization_id,'core','configure')) then
142
+ raise exception 'forbidden' using errcode='42501';
143
+ end if;
144
+ 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;
145
+ if nullif(trim(p_title),'') is null then raise exception 'role title required'; end if;
146
+
147
+ insert into public.organization_roles(organization_id,role_key,title,description,active,created_by)
148
+ values(p_organization_id,p_role_key,trim(p_title),nullif(trim(p_description),''),coalesce(p_active,true),(select auth.uid()))
149
+ on conflict(organization_id,role_key) do update
150
+ set title=excluded.title,
151
+ description=excluded.description,
152
+ active=excluded.active,
153
+ updated_at=now()
154
+ returning id into v_id;
155
+ return v_id;
156
+end $$;
157
+
158
+revoke all on function public.organization_upsert_role(uuid,text,text,text,boolean) from public,anon;
159
+grant execute on function public.organization_upsert_role(uuid,text,text,text,boolean) to authenticated;
160
+
161
+create or replace function public.organization_set_role_permission(
162
+ p_organization_id uuid,
163
+ p_role_id uuid,
164
+ p_module_key text,
165
+ p_capabilities text[],
166
+ p_scope_type text default 'organization',
167
+ p_scope_id text default null,
168
+ p_confidentiality_level smallint default 0
169
+)
170
+returns uuid
171
+language plpgsql security invoker set search_path=''
172
+as $$
173
+declare v_id uuid;
174
+begin
175
+ if not (private.is_org_owner(p_organization_id) or private.has_org_capability(p_organization_id,'core','configure')) then
176
+ raise exception 'forbidden' using errcode='42501';
177
+ end if;
178
+ 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
179
+ raise exception 'role not found';
180
+ end if;
181
+ if not private.role_permission_allowed(p_organization_id,p_module_key) then
182
+ raise exception 'module not licensed' using errcode='42501';
183
+ end if;
184
+
185
+ insert into public.organization_role_permissions(
186
+ organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level
187
+ )
188
+ values(
189
+ p_organization_id,p_role_id,p_module_key,p_capabilities,p_scope_type,p_scope_id,p_confidentiality_level
190
+ )
191
+ on conflict(organization_id,role_id,module_key,scope_type,scope_id) do update
192
+ set capabilities=excluded.capabilities,
193
+ confidentiality_level=excluded.confidentiality_level,
194
+ updated_at=now()
195
+ returning id into v_id;
196
+ return v_id;
197
+end $$;
198
+
199
+revoke all on function public.organization_set_role_permission(uuid,uuid,text,text[],text,text,smallint) from public,anon;
200
+grant execute on function public.organization_set_role_permission(uuid,uuid,text,text[],text,text,smallint) to authenticated;
201
+
202
+create or replace function public.organization_assign_member_role(
203
+ p_organization_id uuid,
204
+ p_member_id uuid,
205
+ p_role_id uuid,
206
+ p_active boolean default true
207
+)
208
+returns uuid
209
+language plpgsql security invoker set search_path=''
210
+as $$
211
+declare v_id uuid;
212
+begin
213
+ if not (private.is_org_owner(p_organization_id) or private.has_org_capability(p_organization_id,'core','configure')) then
214
+ raise exception 'forbidden' using errcode='42501';
215
+ end if;
216
+ 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
217
+ raise exception 'member not found or owner role is implicit';
218
+ end if;
219
+ 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
220
+ raise exception 'role not found';
221
+ end if;
222
+
223
+ insert into public.organization_member_roles(organization_id,member_id,role_id,assigned_by,active)
224
+ values(p_organization_id,p_member_id,p_role_id,(select auth.uid()),coalesce(p_active,true))
225
+ on conflict(organization_id,member_id,role_id) do update
226
+ set active=excluded.active,assigned_by=(select auth.uid()),updated_at=now()
227
+ returning id into v_id;
228
+ return v_id;
229
+end $$;
230
+
231
+revoke all on function public.organization_assign_member_role(uuid,uuid,uuid,boolean) from public,anon;
232
+grant execute on function public.organization_assign_member_role(uuid,uuid,uuid,boolean) to authenticated;
233
+
234
+-- Role grants augment direct member grants. Commercial entitlement remains a separate gate.
235
+create or replace function private.has_org_capability(p_organization_id uuid,p_module_key text,p_capability text)
236
+returns boolean
237
+language sql stable security definer set search_path=''
238
+as $$
239
+ select exists(
240
+ select 1
241
+ from public.organization_members m
242
+ where m.organization_id=p_organization_id
243
+ and m.user_id=(select auth.uid())
244
+ and m.status='active'
245
+ and (
246
+ (p_module_key='core' and p_capability='read')
247
+ or m.is_owner
248
+ or exists(
249
+ select 1 from public.member_module_permissions p
250
+ where p.organization_id=p_organization_id and p.member_id=m.id
251
+ and (p.module_key=p_module_key or p.module_key='full_suite')
252
+ and p_capability=any(p.capabilities)
253
+ )
254
+ or exists(
255
+ select 1
256
+ from public.organization_member_roles mr
257
+ join public.organization_roles r on r.id=mr.role_id and r.organization_id=mr.organization_id and r.active
258
+ join public.organization_role_permissions rp on rp.role_id=r.id and rp.organization_id=r.organization_id
259
+ where mr.organization_id=p_organization_id and mr.member_id=m.id and mr.active
260
+ and (rp.module_key=p_module_key or rp.module_key='full_suite')
261
+ and p_capability=any(rp.capabilities)
262
+ )
263
+ )
264
+ )
265
+$$;
266
+
267
+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)
268
+returns boolean
269
+language sql stable security definer set search_path=''
270
+as $$
271
+ select exists(
272
+ select 1 from public.organization_members m
273
+ where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active'
274
+ and (
275
+ (p_module_key='core' and p_capability='read')
276
+ or m.is_owner
277
+ or exists(
278
+ select 1 from (
279
+ select p.scope_type,p.scope_id,p.module_key,p.capabilities
280
+ from public.member_module_permissions p
281
+ where p.organization_id=p_organization_id and p.member_id=m.id
282
+ union all
283
+ select rp.scope_type,rp.scope_id,rp.module_key,rp.capabilities
284
+ from public.organization_member_roles mr
285
+ join public.organization_roles r on r.id=mr.role_id and r.organization_id=mr.organization_id and r.active
286
+ join public.organization_role_permissions rp on rp.role_id=r.id and rp.organization_id=r.organization_id
287
+ where mr.organization_id=p_organization_id and mr.member_id=m.id and mr.active
288
+ ) g
289
+ where (g.module_key=p_module_key or g.module_key='full_suite')
290
+ and p_capability=any(g.capabilities)
291
+ and (
292
+ g.scope_type='organization'
293
+ or (g.scope_type='own' and p_owner_id=(select auth.uid()))
294
+ or (g.scope_type='company' and g.scope_id=coalesce(p_data->>'companyId',p_data->>'company_id'))
295
+ or (g.scope_type='branch' and g.scope_id=coalesce(p_data->>'branchId',p_data->>'branch_id'))
296
+ or (g.scope_type='unit' and g.scope_id=coalesce(p_data->>'unitId',p_data->>'unit_id'))
297
+ )
298
+ )
299
+ )
300
+ )
301
+$$;
302
+
303
+create or replace function private.record_confidentiality_allowed(p_organization_id uuid,p_module_key text,p_data jsonb)
304
+returns boolean
305
+language sql stable security definer set search_path=''
306
+as $$
307
+ select case when p_module_key='core' then p_organization_id in (select private.current_organization_ids()) else exists(
308
+ select 1 from public.organization_members m
309
+ where m.organization_id=p_organization_id and m.user_id=(select auth.uid()) and m.status='active'
310
+ and (
311
+ m.is_owner
312
+ or coalesce((
313
+ select max(x.confidentiality_level)
314
+ from (
315
+ select p.confidentiality_level,p.module_key
316
+ from public.member_module_permissions p
317
+ where p.organization_id=p_organization_id and p.member_id=m.id
318
+ union all
319
+ select rp.confidentiality_level,rp.module_key
320
+ from public.organization_member_roles mr
321
+ join public.organization_roles r on r.id=mr.role_id and r.organization_id=mr.organization_id and r.active
322
+ join public.organization_role_permissions rp on rp.role_id=r.id and rp.organization_id=r.organization_id
323
+ where mr.organization_id=p_organization_id and mr.member_id=m.id and mr.active
324
+ ) x
325
+ where x.module_key=p_module_key or x.module_key='full_suite'
326
+ ),-1) >= (
327
+ case lower(coalesce(p_data->>'confidentiality','normal'))
328
+ when 'محرمانه' then 1 when 'confidential' then 1
329
+ when 'خیلی محرمانه' then 2 when 'very_confidential' then 2
330
+ when 'سری' then 3 when 'secret' then 3 else 0 end
331
+ )
332
+ )
333
+ ) end
334
+$$;
335
+
336
+-- Seed reusable starter roles. They grant nothing unless assigned.
337
+insert into public.organization_roles(organization_id,role_key,title,description,is_system,active)
338
+select o.id,x.role_key,x.title,x.description,true,true
339
+from public.organizations o
340
+cross join (values
341
+ ('system_admin','مدیر سیستم سازمان','مدیریت ساختار و کاربران سازمان'),
342
+ ('finance_manager','مدیر مالی','مدیریت و تأیید عملیات مالی'),
343
+ ('accountant','حسابدار','ثبت و ویرایش عملیات حسابداری'),
344
+ ('petty_cash','تنخواهگردان','عملیات پایه خزانه و تنخواه'),
345
+ ('secretariat','کاربر دبیرخانه','ثبت، ارجاع و بایگانی مکاتبات'),
346
+ ('viewer','مشاهدهگر','نقش پایه مشاهده')
347
+) as x(role_key,title,description)
348
+on conflict(organization_id,role_key) do nothing;
349
+
350
+insert into public.organization_role_permissions(organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level)
351
+select r.organization_id,r.id,'core',array['read','configure']::text[],'organization',null,3
352
+from public.organization_roles r where r.role_key='system_admin'
353
+on conflict(organization_id,role_id,module_key,scope_type,scope_id) do nothing;
354
+
355
+insert into public.organization_role_permissions(organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level)
356
+select r.organization_id,r.id,'accounting',array['read','create','edit','approve']::text[],'organization',null,1
357
+from public.organization_roles r
358
+join public.licenses l on l.organization_id=r.organization_id
359
+where r.role_key='finance_manager' and ('full_suite'=any(l.modules) or 'accounting'=any(l.modules))
360
+on conflict(organization_id,role_id,module_key,scope_type,scope_id) do nothing;
361
+
362
+insert into public.organization_role_permissions(organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level)
363
+select r.organization_id,r.id,'treasury',array['read','create','edit','approve']::text[],'organization',null,1
364
+from public.organization_roles r
365
+join public.licenses l on l.organization_id=r.organization_id
366
+where r.role_key='finance_manager' and ('full_suite'=any(l.modules) or 'treasury'=any(l.modules))
367
+on conflict(organization_id,role_id,module_key,scope_type,scope_id) do nothing;
368
+
369
+insert into public.organization_role_permissions(organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level)
370
+select r.organization_id,r.id,'accounting',array['read','create','edit']::text[],'organization',null,0
371
+from public.organization_roles r
372
+join public.licenses l on l.organization_id=r.organization_id
373
+where r.role_key='accountant' and ('full_suite'=any(l.modules) or 'accounting'=any(l.modules))
374
+on conflict(organization_id,role_id,module_key,scope_type,scope_id) do nothing;
375
+
376
+insert into public.organization_role_permissions(organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level)
377
+select r.organization_id,r.id,'treasury',array['read','create']::text[],'organization',null,0
378
+from public.organization_roles r
379
+join public.licenses l on l.organization_id=r.organization_id
380
+where r.role_key='petty_cash' and ('full_suite'=any(l.modules) or 'treasury'=any(l.modules))
381
+on conflict(organization_id,role_id,module_key,scope_type,scope_id) do nothing;
382
+
383
+insert into public.organization_role_permissions(organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level)
384
+select r.organization_id,r.id,'office_automation',array['read','create','register','refer','archive']::text[],'organization',null,1
385
+from public.organization_roles r
386
+join public.licenses l on l.organization_id=r.organization_id
387
+where r.role_key='secretariat' and ('full_suite'=any(l.modules) or 'office_automation'=any(l.modules))
388
+on conflict(organization_id,role_id,module_key,scope_type,scope_id) do nothing;
389
+
390
+insert into public.organization_role_permissions(organization_id,role_id,module_key,capabilities,scope_type,scope_id,confidentiality_level)
391
+select r.organization_id,r.id,'core',array['read']::text[],'organization',null,0
392
+from public.organization_roles r where r.role_key='viewer'
393
+on conflict(organization_id,role_id,module_key,scope_type,scope_id) do nothing;
394
+
395
+create or replace function private.organization_role_audit_capture()
396
+returns trigger
397
+language plpgsql security definer set search_path=''
398
+as $$
399
+declare v_org uuid; v_id text;
400
+begin
401
+ v_org:=case when tg_op='DELETE' then old.organization_id else new.organization_id end;
402
+ v_id:=case when tg_op='DELETE' then old.id::text else new.id::text end;
403
+ insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data)
404
+ values(
405
+ v_org,(select auth.uid()),lower(tg_table_name||'_'||tg_op),tg_table_name,v_id,
406
+ case when tg_op in ('UPDATE','DELETE') then to_jsonb(old) else null end,
407
+ case when tg_op in ('INSERT','UPDATE') then to_jsonb(new) else null end
408
+ );
409
+ if tg_op='DELETE' then return old; else return new; end if;
410
+end $$;
411
+
412
+revoke all on function private.organization_role_audit_capture() from public,anon,authenticated;
413
+
414
+drop trigger if exists organization_roles_audit on public.organization_roles;
415
+create trigger organization_roles_audit after insert or update or delete on public.organization_roles
416
+for each row execute function private.organization_role_audit_capture();
417
+
418
+drop trigger if exists organization_role_permissions_audit on public.organization_role_permissions;
419
+create trigger organization_role_permissions_audit after insert or update or delete on public.organization_role_permissions
420
+for each row execute function private.organization_role_audit_capture();
421
+
422
+drop trigger if exists organization_member_roles_audit on public.organization_member_roles;
423
+create trigger organization_member_roles_audit after insert or update or delete on public.organization_member_roles
424
+for each row execute function private.organization_role_audit_capture();