-- OWNER: run in your existing Supabase SQL Editor after 001, 002 and 003. -- Rerunnable and additive. No administrator is granted automatically. begin; do $$ begin if to_regclass('public.creator_accounts') is null or to_regclass('public.creator_credit_ledger') is null or to_regclass('public.creator_uploads') is null or not exists(select 1 from information_schema.columns where table_schema='public' and table_name='creator_projects' and column_name='source_image_paths') or not exists(select 1 from information_schema.columns where table_schema='public' and table_name='creator_projects' and column_name='video_settings') or not exists(select 1 from information_schema.columns where table_schema='public' and table_name='creator_projects' and column_name='source_video_path') or to_regprocedure('public.creator_reserve_video(uuid,uuid,text,text,text,jsonb)') is null or to_regprocedure('public.creator_reserve_photo_video(uuid,uuid,text,text,text[],jsonb)') is null then raise exception 'Prerequisites missing: apply 001_creator.sql, 002_video_models.sql and 003_photo_videos.sql first.'; end if; end $$; create table if not exists public.creator_admin_roles ( user_id uuid primary key references auth.users(id) on delete restrict, created_at timestamptz not null default now() ); alter table public.creator_accounts add column if not exists blocked boolean not null default false; alter table public.creator_projects add column if not exists provider_credits numeric, add column if not exists provider_usage_final boolean; create table if not exists public.creator_plans ( id uuid primary key default gen_random_uuid(), name text not null check(length(name) between 1 and 80), monthly_inr numeric(12,2) not null check(monthly_inr>=0), yearly_inr numeric(12,2) not null check(yearly_inr>=0), included_credits integer not null check(included_credits>=0), enabled boolean not null default true, archived boolean not null default false ); create table if not exists public.creator_subscriptions ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.users(id), plan_id uuid not null references public.creator_plans(id) on delete restrict, status text not null check(status in ('active','expired','canceled')), provider_reference text unique not null, current_period_end timestamptz not null, created_at timestamptz not null default now() ); create table if not exists public.creator_payments ( id uuid primary key default gen_random_uuid(), user_id uuid not null references auth.users(id), plan_id uuid references public.creator_plans(id) on delete restrict, subscription_id uuid references public.creator_subscriptions(id), provider_reference text unique not null, kind text not null check(kind in ('payment','subscription','refund')), status text not null check(status in ('pending','captured','failed','refunded')), amount_inr numeric(12,2) not null check(amount_inr>=0), created_at timestamptz not null default now() ); create table if not exists public.creator_model_policy ( id text primary key check(id in ('flux-schnell','upscale','ltx-2.5','veo3.1-lite','gemini-omni-1.2')), name text not null check(length(name) between 1 and 80), visible boolean not null default true, enabled boolean not null default true, credit_price integer not null check(credit_price between 1 and 100000), resolutions text[] not null default '{}', durations integer[] not null default '{}' ); insert into public.creator_model_policy(id,name,credit_price) values ('flux-schnell','Flux Schnell',5),('upscale','Image upscale',5), ('ltx-2.5','LTX 2.5',25),('veo3.1-lite','Google Veo 3.1 Lite',25),('gemini-omni-1.2','Google Omni Flash 1.2',25) on conflict do nothing; -- Empty subsets mean all verified provider options until explicitly narrowed. create table if not exists public.creator_site_settings ( id boolean primary key default true check(id), value jsonb not null default '{"site_name":"AI Creator","logo_url":"","announcement":"","banner_text":"","banner_url":"","support_email":"","support_url":"","maintenance":false}', updated_at timestamptz not null default now() ); insert into public.creator_site_settings(id) values(true) on conflict do nothing; create table if not exists public.creator_admin_audit ( id uuid primary key default gen_random_uuid(), request_id uuid unique not null, actor_id uuid not null references auth.users(id) on delete restrict, action text not null, target text, details jsonb not null, created_at timestamptz not null default now() ); create table if not exists public.creator_api_operations ( id uuid primary key default gen_random_uuid(), operation text not null, project_id uuid references public.creator_projects(id), outcome text not null check(outcome in ('success','unavailable','rejected')), http_status integer, duration_ms integer not null, -- Unknown costs MUST stay null. Provider credits are not currency. provider_credits numeric, expenditure_inr numeric, provider_balance numeric, provider_tier text, created_at timestamptz not null default now() ); create index if not exists creator_api_operations_created on public.creator_api_operations(created_at desc); create index if not exists creator_admin_audit_created on public.creator_admin_audit(created_at desc); do $$ declare t text; begin foreach t in array array['creator_admin_roles','creator_plans','creator_subscriptions','creator_payments','creator_model_policy','creator_site_settings','creator_admin_audit','creator_api_operations'] loop execute format('alter table public.%I enable row level security',t); execute format('revoke all on public.%I from public, anon, authenticated',t); execute format('grant all on public.%I to service_role',t); end loop; end $$; -- Serialize owner role edits with admin mutations and prevent the last unblocked admin -- from being removed. SQL Editor owner may bootstrap by INSERT only, using an existing UUID. create or replace function public.creator_protect_admin_role() returns trigger language plpgsql set search_path=public as $$ begin perform pg_advisory_xact_lock(9182741); if tg_op in ('DELETE','UPDATE') and not exists( select 1 from creator_admin_roles r left join creator_accounts a on a.id=r.user_id where r.user_id<>old.user_id and not coalesce(a.blocked,false) ) then raise exception 'Cannot remove the last administrator'; end if; if tg_op='DELETE' then return old; end if; if exists(select 1 from creator_accounts where id=new.user_id and blocked) then raise exception 'Unblock this account before granting administrator'; end if; return new; end $$; drop trigger if exists creator_protect_admin_role on public.creator_admin_roles; create trigger creator_protect_admin_role before insert or update or delete on public.creator_admin_roles for each row execute function public.creator_protect_admin_role(); create or replace function public.creator_admin_mutate(p_actor uuid,p_request uuid,p_action text,p_target text,p_reason text,p_value jsonb) returns jsonb language plpgsql set search_path=public as $$ declare prior creator_admin_audit; a creator_accounts; p creator_projects; amount integer; plan uuid; begin perform pg_advisory_xact_lock(9182741); if not exists(select 1 from creator_admin_roles r left join creator_accounts acct on acct.id=r.user_id where r.user_id=p_actor and not coalesce(acct.blocked,false)) then raise exception 'Administrator authorization required'; end if; if p_reason is null or length(trim(p_reason)) not between 5 and 250 then raise exception 'A reason is required'; end if; select * into prior from creator_admin_audit where request_id=p_request; if found then if prior.actor_id<>p_actor or prior.action<>p_action or prior.details is distinct from jsonb_build_object('reason',p_reason,'value',p_value,'input_target',p_target) then raise exception 'Request ID already used'; end if; return jsonb_build_object('ok',true,'duplicate',true); end if; if p_action='credits' then -- Match automatic refund lock order: project then account. if p_value->>'kind'='refund' then select * into p from creator_projects where id=(p_value->>'project_id')::uuid for update; if not found or p.user_id<>p_target::uuid then raise exception 'Project not found for user'; end if; if p.refunded or p.status<>'failed' then raise exception 'Only an unrefunded failed generation may be refunded'; end if; amount:=p.cost; else amount:=(p_value->>'amount')::integer; if amount is null or amount not between 1 and 1000000 or p_value->>'kind' not in ('add','deduct') then raise exception 'Invalid credit adjustment'; end if; if p_value->>'kind'='deduct' then amount:=-amount; end if; end if; perform creator_ensure_account(p_target::uuid); select * into a from creator_accounts where id=p_target::uuid for update; if a.credits+amount<0 then raise exception 'Not enough credits'; end if; if p_value->>'kind'='refund' then insert into creator_credit_ledger(user_id,project_id,amount,reason) values(a.id,p.id,amount,'refund'); update creator_projects set refunded=true where id=p.id; else insert into creator_credit_ledger(user_id,amount,reason) values(a.id,amount,'admin:'||p_request::text); end if; update creator_accounts set credits=credits+amount where id=a.id; elsif p_action='block' then if (p_value->>'blocked')::boolean and exists(select 1 from creator_admin_roles where user_id=p_target::uuid) and not exists(select 1 from creator_admin_roles r left join creator_accounts acct on acct.id=r.user_id where r.user_id<>p_target::uuid and not coalesce(acct.blocked,false)) then raise exception 'Cannot block the last administrator'; end if; perform creator_ensure_account(p_target::uuid); update creator_accounts set blocked=(p_value->>'blocked')::boolean where id=p_target::uuid; elsif p_action='plan' then plan:=coalesce(p_target::uuid,gen_random_uuid()); insert into creator_plans(id,name,monthly_inr,yearly_inr,included_credits,enabled,archived) values(plan,p_value->>'name',(p_value->>'monthly_inr')::numeric,(p_value->>'yearly_inr')::numeric,(p_value->>'included_credits')::integer,(p_value->>'enabled')::boolean,(p_value->>'archived')::boolean) on conflict(id) do update set name=excluded.name,monthly_inr=excluded.monthly_inr,yearly_inr=excluded.yearly_inr,included_credits=excluded.included_credits,enabled=excluded.enabled,archived=excluded.archived; elsif p_action='delete-plan' then if exists(select 1 from creator_subscriptions where plan_id=p_target::uuid) or exists(select 1 from creator_payments where plan_id=p_target::uuid) then raise exception 'Referenced plans must be archived'; end if; delete from creator_plans where id=p_target::uuid; if not found then raise exception 'Plan not found'; end if; elsif p_action='model' then update creator_model_policy set name=p_value->>'name',visible=(p_value->>'visible')::boolean,enabled=(p_value->>'enabled')::boolean, credit_price=(p_value->>'credit_price')::integer, resolutions=array(select jsonb_array_elements_text(p_value->'resolutions')), durations=array(select jsonb_array_elements_text(p_value->'durations')::integer) where id=p_target; if not found then raise exception 'Model not found'; end if; elsif p_action='settings' then update creator_site_settings set value=p_value,updated_at=now() where id=true; elsif p_action<>'check-connection' then raise exception 'Unknown action'; end if; insert into creator_admin_audit(request_id,actor_id,action,target,details) values(p_request,p_actor,p_action,coalesce(p_target,plan::text,case p_action when 'settings' then 'website' when 'check-connection' then 'magic-hour' end), jsonb_build_object('reason',p_reason,'value',p_value,'input_target',p_target)); return jsonb_build_object('ok',true); end $$; -- Atomic managed reservation. Existing requests return their stored price and settings. -- This wrapper leaves the original reservation and refund ledger semantics intact. create or replace function public.creator_reserve( p_user uuid,p_id uuid,p_prompt text,p_mode text,p_ratio text,p_image_path text default null ) returns public.creator_projects language plpgsql set search_path=public as $$ declare a creator_accounts; p creator_projects; price integer; model text; begin perform creator_ensure_account(p_user); select * into a from creator_accounts where id=p_user for update; select * into p from creator_projects where id=p_id; if found then if p.user_id<>p_user or p.prompt<>p_prompt or p.mode<>p_mode or p.aspect_ratio<>p_ratio or p.image_path is distinct from p_image_path then raise exception 'Request ID was already used with different inputs'; end if; return p; end if; if a.blocked then raise exception 'Account blocked'; end if; if exists(select 1 from creator_site_settings where id=true and (value->>'maintenance')::boolean) then raise exception 'Maintenance mode'; end if; if p_mode not in ('image','video','upscale') or p_ratio not in ('16:9','9:16','1:1') then raise exception 'Invalid generation options'; end if; if (select count(*) from creator_projects where user_id=p_user and status not in ('completed','failed'))>=3 then raise exception 'Wait for an active generation to finish (maximum 3)'; end if; if (select count(*) from creator_projects where user_id=p_user and created_at>now()-interval '1 day')>=20 then raise exception 'Daily limit reached'; end if; model:=case p_mode when 'image' then 'flux-schnell' when 'upscale' then 'upscale' else coalesce(nullif(current_setting('creator.model',true),''),'ltx-2.5') end; select credit_price into price from creator_model_policy where id=model and enabled and visible for share; if price is null then raise exception 'Model unavailable'; end if; if a.credits>'requestId')::uuid; if found then if p.user_id<>p_user or p.prompt<>trim(p_input->>'prompt') or p.mode<>p_input->>'mode' or p.aspect_ratio<>p_input->>'aspectRatio' or p.image_path is distinct from p_input->>'imagePath' or coalesce(p.video_settings,'{"modelId":"ltx-2.5","duration":5,"resolution":"480p","audio":false}'::jsonb) is distinct from coalesce(p_input->'videoSettings','{"modelId":"ltx-2.5","duration":5,"resolution":"480p","audio":false}'::jsonb) or p.source_image_paths is distinct from array(select jsonb_array_elements_text(coalesce(p_input->'imagePaths','[]'::jsonb))) then raise exception 'Request ID was already used with different inputs'; end if; return p; end if; perform 1 from creator_site_settings where id=true for share; if exists(select 1 from creator_site_settings where id=true and (value->>'maintenance')::boolean) then raise exception 'Maintenance mode'; end if; settings:=coalesce(p_input->'videoSettings','{"modelId":"ltx-2.5","duration":5,"resolution":"480p","audio":false}'::jsonb); model:=case p_input->>'mode' when 'video' then settings->>'modelId' when 'image' then 'flux-schnell' else 'upscale' end; select * into policy from creator_model_policy where id=model for share; if not found or not policy.enabled or not policy.visible then raise exception 'Model unavailable'; end if; if p_input ? 'quotedCost' and (p_input->>'quotedCost')::integer is distinct from policy.credit_price then raise exception 'Quote changed'; end if; if p_input->>'mode'='video' and ( (cardinality(policy.resolutions)>0 and not (settings->>'resolution'=any(policy.resolutions))) or (cardinality(policy.durations)>0 and not ((settings->>'duration')::integer=any(policy.durations))) ) then raise exception 'Model settings unavailable'; end if; perform set_config('creator.model',model,true); photos:=array(select jsonb_array_elements_text(coalesce(p_input->'imagePaths','[]'::jsonb))); if cardinality(photos)>0 then select * into p from creator_reserve_photo_video(p_user,(p_input->>'requestId')::uuid,trim(p_input->>'prompt'),p_input->>'aspectRatio',photos,settings); elsif p_input->>'mode'='video' then select * into p from creator_reserve_video(p_user,(p_input->>'requestId')::uuid,trim(p_input->>'prompt'),p_input->>'aspectRatio',p_input->>'imagePath',settings); else select * into p from creator_reserve(p_user,(p_input->>'requestId')::uuid,trim(p_input->>'prompt'),p_input->>'mode',p_input->>'aspectRatio',p_input->>'imagePath'); end if; delta:=policy.credit_price-p.cost; if (select credits from creator_accounts where id=p_user)=p_from and last_sign_in_at<=p_to), 'paid_subscribers',(select count(distinct s.user_id) from creator_subscriptions s where s.status='active' and s.current_period_end>p_to and exists(select 1 from creator_payments p where p.subscription_id=s.id and p.status='captured')), 'image_generations',(select count(*) from creator_projects where mode='image' and created_at between p_from and p_to), 'video_generations',(select count(*) from creator_projects where mode='video' and created_at between p_from and p_to), 'upscale_generations',(select count(*) from creator_projects where mode='upscale' and created_at between p_from and p_to), 'failed_generations',(select count(*) from creator_projects where status='failed' and created_at between p_from and p_to), 'api_usage',(select count(*) from creator_api_operations where created_at between p_from and p_to), 'revenue_inr',(select sum(case when kind='refund' then -amount_inr else amount_inr end) from creator_payments where status in ('captured','refunded') and created_at between p_from and p_to), 'api_expenditure_inr',(select sum(expenditure_inr) from creator_api_operations where created_at between p_from and p_to), 'estimated_profit_inr',null); $$; create or replace function public.creator_admin_generations(p_search text,p_page integer,p_status text default null,p_mode text default null) returns jsonb language sql set search_path=public as $$ with jobs as ( select p.id,p.user_id,u.email,p.title,p.mode,p.status,p.cost,p.refunded,p.provider_id,p.error,p.created_at,p.updated_at, case when p.provider_credits is null then null else jsonb_build_object('credits',p.provider_credits,'final',p.provider_usage_final) end provider_usage from creator_projects p join auth.users u on u.id=p.user_id where (p_status is null or p.status=p_status) and (p_mode is null or p.mode=p_mode) and (p_search='' or p.title ilike '%'||p_search||'%' or p.provider_id ilike '%'||p_search||'%' or u.email ilike '%'||p_search||'%' or p.id::text=p_search or p.user_id::text=p_search) ) select jsonb_build_object('rows',coalesce((select jsonb_agg(x) from (select * from jobs order by created_at desc,id limit 25 offset (greatest(p_page,1)-1)*25) x),'[]'::jsonb), 'page',p_page,'pageSize',25,'total',(select count(*) from jobs)); $$; -- All RPCs are server-only. Invoker rights intentionally avoid security-definer escalation. revoke all on function public.creator_admin_users(text,integer,uuid), public.creator_admin_overview(timestamptz,timestamptz), public.creator_admin_generations(text,integer,text,text), public.creator_admin_mutate(uuid,uuid,text,text,text,jsonb), public.creator_reserve_managed(uuid,jsonb), public.creator_protect_admin_role() from public,anon,authenticated; grant execute on function public.creator_admin_users(text,integer,uuid), public.creator_admin_overview(timestamptz,timestamptz), public.creator_admin_generations(text,integer,text,text), public.creator_admin_mutate(uuid,uuid,text,text,text,jsonb), public.creator_reserve_managed(uuid,jsonb) to service_role; commit; -- FIRST ADMINISTRATOR: owner only, replace with an EXISTING confirmed auth.users UUID: -- insert into public.creator_admin_roles(user_id) values ('YOUR-EXISTING-USER-UUID') on conflict do nothing; -- Never use user_metadata, email matching, signup order, or browser flags for admin access.