سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 20:45 UTC
Archive production Slice B organization RBAC migration
davoodmehraban89 committed
Sep 30, 2026 at 06:54 UTC
fdfdd86e26c28d875c050c484e781e20e581a1f0
1 file changed
+216
supabase/migrations/20260930031853_organization_membership_rbac_foundation.sql
new
+216
@@ -0,0 +1,216 @@
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();
\ No newline at end of file