-- ACOM Church Office. Run once in Supabase SQL Editor as project owner. -- No donor records or passwords are included. New accounts start Pending. begin; create table if not exists public.acom_profiles ( user_id uuid primary key references auth.users(id) on delete cascade, email text not null, display_name text not null default '', role text not null default 'Pending' check (role in ('Pending','Admin','Secretary','Finance','Pastor','Worship','Media','Church Member')), household_name text not null default '' ); create table if not exists public.acom_sections ( name text primary key check(name in ('gifts','expenses','people','ministries','events','songs','services')), data jsonb not null default '[]'::jsonb check(jsonb_typeof(data)='array'), version bigint not null default 0, updated_at timestamptz not null default now() ); create table if not exists public.acom_audit ( id bigint generated always as identity primary key, actor uuid not null, action text not null, target text not null, created_at timestamptz not null default now() ); alter table public.acom_profiles enable row level security; alter table public.acom_sections enable row level security; alter table public.acom_audit enable row level security; -- Access is through the bounded, authenticated functions below only. revoke all on public.acom_profiles,public.acom_sections,public.acom_audit from anon,authenticated; insert into public.acom_sections(name) values ('gifts'),('expenses'),('people'),('ministries'),('events'),('songs'),('services') on conflict do nothing; create or replace function public.acom_new_user() returns trigger language plpgsql security definer set search_path='' as $$ begin insert into public.acom_profiles(user_id,email,display_name) values(new.id,coalesce(new.email,''),left(coalesce(new.raw_user_meta_data->>'full_name',''),160)) on conflict do nothing; return new; end $$; revoke all on function public.acom_new_user() from public,anon,authenticated; drop trigger if exists acom_create_profile on auth.users; create trigger acom_create_profile after insert on auth.users for each row execute function public.acom_new_user(); insert into public.acom_profiles(user_id,email,display_name) select id,coalesce(email,''),left(coalesce(raw_user_meta_data->>'full_name',''),160) from auth.users on conflict do nothing; create or replace function public.acom_get_state() returns jsonb language plpgsql security definer set search_path='' as $$ declare p public.acom_profiles; result jsonb; versions jsonb; totals jsonb; allowed text[]; begin if auth.uid() is null then raise exception 'Sign in required'; end if; select * into p from public.acom_profiles where user_id=auth.uid(); if p.user_id is null then raise exception 'Profile is missing'; end if; result=jsonb_build_object('profile',to_jsonb(p)); if p.role='Pending' then return result; end if; allowed=case p.role when 'Admin' then array['gifts','expenses','people','ministries','events','songs','services'] when 'Finance' then array['gifts','expenses','people'] when 'Secretary' then array['people','ministries','events','songs','services'] when 'Pastor' then array['people','ministries','events','songs','services'] when 'Worship' then array['ministries','events','songs','services'] when 'Media' then array['ministries','events','songs','services'] else array[]::text[] end; select coalesce(jsonb_object_agg(name,data),'{}'),coalesce(jsonb_object_agg(name,version),'{}') into result,versions from public.acom_sections where name=any(allowed); -- Ministry budgets never leave the server for Worship, Media, or Secretary. if p.role in ('Worship','Media','Secretary') then result=jsonb_set(result,'{ministries}',coalesce((select jsonb_agg(x-'budget') from jsonb_array_elements(coalesce(result->'ministries','[]')) x),'[]')); end if; if p.role='Church Member' then result=jsonb_build_object('gifts',coalesce((select jsonb_agg(x) from public.acom_sections s cross join lateral jsonb_array_elements(s.data) x where s.name='gifts' and x->>'member_user_id'=auth.uid()::text),'[]')); end if; if p.role in ('Pastor','Church Member') then select coalesce(jsonb_agg(to_jsonb(t)),'[]') into totals from ( select x->>'fund' fund,left(x->>'date',4) as "year",sum(case when s.name='gifts' then (x->>'amount')::numeric else 0 end) giving,sum(case when s.name='expenses' then (x->>'amount')::numeric else 0 end) expenses from public.acom_sections s cross join lateral jsonb_array_elements(s.data) x where s.name in ('gifts','expenses') and (p.role='Pastor' or x->>'fund'='General') group by x->>'fund',left(x->>'date',4) ) t; end if; return jsonb_build_object('profile',to_jsonb(p),'sections',result,'versions',versions,'totals',coalesce(totals,'[]')); end $$; create or replace function public.acom_save_sections(changes jsonb) returns jsonb language plpgsql security definer set search_path='' as $$ declare r text; c jsonb; n text; v bigint; updated jsonb='{}'; allowed text[]; begin if auth.uid() is null then raise exception 'Sign in required'; end if; select role into r from public.acom_profiles where user_id=auth.uid(); allowed=case r when 'Admin' then array['gifts','expenses','people','ministries','events','songs','services'] when 'Finance' then array['gifts','expenses'] when 'Secretary' then array['people','events','songs','services'] when 'Worship' then array['songs'] when 'Media' then array['songs'] else array[]::text[] end; if jsonb_typeof(changes)<>'array' or jsonb_array_length(changes)>7 or octet_length(changes::text)>4000000 then raise exception 'Invalid update'; end if; -- Sorted locks prevent cross-client deadlocks. All sections commit atomically. for c in select value from jsonb_array_elements(changes) order by value->>'name' loop n=c->>'name'; if not coalesce(n=any(allowed),false) then raise exception 'Permission denied for %',n; end if; if jsonb_typeof(c->'data') is distinct from 'array' then raise exception 'Invalid records'; end if; if n in ('gifts','expenses') and exists(select 1 from jsonb_array_elements(c->'data') x where jsonb_typeof(x->'amount') is distinct from 'number' or coalesce(x->>'date','')!~'^\d{4}-\d{2}-\d{2}$') then raise exception 'Amount and date are required'; end if; if exists(select 1 from jsonb_array_elements(c->'data') x where jsonb_typeof(x) is distinct from 'object') then raise exception 'Records must be objects'; end if; if n in ('songs','services') and exists(select 1 from jsonb_array_elements(c->'data') x where jsonb_typeof(x->'id') is distinct from 'number') then raise exception 'Planning IDs must be numbers'; end if; if n='services' then if exists(select 1 from jsonb_array_elements(c->'data') x where jsonb_typeof(x->'items') is distinct from 'array' or jsonb_typeof(x->'team') is distinct from 'array' or coalesce(x->>'time','')!~'^([01][0-9]|2[0-3]):[0-5][0-9]$' or coalesce(x->>'date','')!~'^\d{4}-\d{2}-\d{2}$') then raise exception 'Invalid service structure, date, or time'; end if; if exists(select 1 from jsonb_array_elements(c->'data') x cross join lateral jsonb_array_elements(x->'items') item where jsonb_typeof(item->'minutes') is distinct from 'number') then raise exception 'Item duration must be a number'; end if; end if; select version into v from public.acom_sections where name=n for update; if v is distinct from (c->>'version')::bigint then raise exception 'Records changed on another device. Refresh before editing.'; end if; update public.acom_sections set data=c->'data',version=version+1,updated_at=now() where name=n returning version into v; updated=updated||jsonb_build_object(n,v); insert into public.acom_audit(actor,action,target) values(auth.uid(),'save',n); end loop; return updated; end $$; create or replace function public.acom_manage_accounts(target uuid default null,new_role text default null,new_household text default null) returns jsonb language plpgsql security definer set search_path='' as $$ begin if auth.uid() is null or not exists(select 1 from public.acom_profiles where user_id=auth.uid() and role='Admin') then raise exception 'Admin required'; end if; if target is not null then if target=auth.uid() then raise exception 'You cannot change your own assignment'; end if; update public.acom_profiles set role=coalesce(new_role,role),household_name=coalesce(new_household,household_name) where user_id=target; insert into public.acom_audit(actor,action,target) values(auth.uid(),'assign role',target::text); end if; return coalesce((select jsonb_agg(to_jsonb(p) order by p.email) from public.acom_profiles p),'[]'); end $$; revoke all on function public.acom_get_state(),public.acom_save_sections(jsonb),public.acom_manage_accounts(uuid,text,text) from public,anon; grant execute on function public.acom_get_state(),public.acom_save_sections(jsonb),public.acom_manage_accounts(uuid,text,text) to authenticated; commit; -- After registering your Church Office account, promote ONLY your verified email: -- update public.acom_profiles set role='Admin' where email='YOUR_CHURCH_OFFICE_EMAIL';