-- Caterium v17.9.1 -- Public owners may register without a promo code. No-promo workspaces are -- permanently limited to the Basic plan. A valid promo keeps the existing -- server-enforced trial plan and duration. begin; create or replace function public.caterium_public_signup_policy() returns jsonb language sql stable security invoker set search_path = public as $function$ select jsonb_build_object( 'promo_optional', true, 'default_plan', 'basic' ); $function$; create or replace function public.sun_create_workspace(p_name text default 'Новая компания'::text) returns uuid language plpgsql security definer set search_path = public, auth, pg_temp as $function$ declare v_user uuid:=auth.uid(); v_workspace uuid; v_name text:='Новая компания'; v_email text; v_profile jsonb; v_storage jsonb; v_code text; v_has_promo boolean:=false; v_promo public.caterium_trial_promos%rowtype; v_trial_end timestamptz; begin if v_user is null then raise exception 'Authentication required'; end if; if not exists(select 1 from auth.users where id=v_user and email_confirmed_at is not null) then raise exception 'Подтвердите email'; end if; if exists(select 1 from public.sun_workspace_members where user_id=v_user and is_active=true) then raise exception 'Аккаунт уже относится к компании'; end if; select lower(email),public.caterium_normalize_trial_code(raw_user_meta_data->>'promo_code') into v_email,v_code from auth.users where id=v_user; v_has_promo:=coalesce(v_code,'')<>''; if v_has_promo then if exists(select 1 from public.caterium_trial_redemptions where user_id=v_user) then raise exception 'Пробный период для этого аккаунта уже использован'; end if; select * into v_promo from public.caterium_trial_promos where code=v_code for update; if not found then raise exception 'Промокод не найден'; end if; if not v_promo.is_active then raise exception 'Промокод отключён'; end if; if v_promo.valid_until is not null and v_promo.valid_until<=now() then raise exception 'Срок действия промокода истёк'; end if; if v_promo.use_count>=v_promo.max_uses then raise exception 'Промокод уже использован'; end if; if v_promo.client_email is not null and lower(v_promo.client_email)<>v_email then raise exception 'Промокод предназначен для другого email'; end if; v_trial_end:=now()+make_interval(days=>v_promo.trial_days); end if; insert into public.sun_workspaces(name,created_by) values(v_name,v_user) returning id into v_workspace; insert into public.sun_workspace_members(workspace_id,user_id,role,display_name,is_active,permissions) values( v_workspace, v_user, 'admin', coalesce((select raw_user_meta_data->>'name' from auth.users where id=v_user),split_part(coalesce(v_email,'Администратор'),'@',1)), true, public.sun_role_default_permissions('admin') ); v_profile:=jsonb_build_object( 'name','','shortName','','logo','','tagline','','city','','phone','','email',coalesce(v_email,''), 'website','','address','','legalName','','inn','','kpp','','ogrn','','legalAddress','', 'bank','','bik','','account','','corrAccount','','legacyLocked',false ); v_storage:=jsonb_build_object('sunCompanyProfileV1',v_profile::text); insert into public.sun_app_state(workspace_id,payload,client_id) values(v_workspace,jsonb_build_object('format','sun-cloud-v2','version',2,'storage',v_storage),'bootstrap') on conflict(workspace_id) do nothing; if v_has_promo then insert into public.sun_workspace_subscriptions( workspace_id,plan_id,status,trial_started_at,trial_ends_at,current_period_start,current_period_end,grace_until,source,note ) values( v_workspace,v_promo.plan_id,'trialing',now(),v_trial_end,null,null,v_trial_end+interval '7 days','promo_trial','Trial by promo '||v_promo.code ) on conflict(workspace_id) do update set plan_id=excluded.plan_id, status=excluded.status, trial_started_at=excluded.trial_started_at, trial_ends_at=excluded.trial_ends_at, current_period_start=null, current_period_end=null, grace_until=excluded.grace_until, source=excluded.source, note=excluded.note, updated_at=now(); insert into public.caterium_trial_redemptions(promo_id,workspace_id,user_id,email,trial_ends_at) values(v_promo.id,v_workspace,v_user,v_email,v_trial_end); update public.caterium_trial_promos set use_count=use_count+1,updated_at=now() where id=v_promo.id; insert into public.sun_platform_audit_events(actor_user_id,action,target_workspace_id,target_user_id,details) values( v_user,'trial_promo.redeem',v_workspace,v_user, jsonb_build_object('promo_id',v_promo.id,'code',v_promo.code,'trial_days',v_promo.trial_days,'plan',v_promo.plan_id) ); else insert into public.sun_workspace_subscriptions( workspace_id,plan_id,status,trial_started_at,trial_ends_at,current_period_start,current_period_end,grace_until,source,note ) values( v_workspace,'basic','active',null,null,now(),null,null,'public_signup_basic','Basic access without promo' ) on conflict(workspace_id) do update set plan_id='basic', status='active', trial_started_at=null, trial_ends_at=null, current_period_start=now(), current_period_end=null, grace_until=null, source='public_signup_basic', note='Basic access without promo', updated_at=now(); insert into public.sun_platform_audit_events(actor_user_id,action,target_workspace_id,target_user_id,details) values( v_user,'public_signup.basic',v_workspace,v_user, jsonb_build_object('plan','basic','promo',false) ); end if; update auth.users set raw_user_meta_data=coalesce(raw_user_meta_data,'{}'::jsonb)-'promo_code'-'company_name' where id=v_user; return v_workspace; end; $function$; revoke all on function public.caterium_public_signup_policy() from public,anon,authenticated; grant execute on function public.caterium_public_signup_policy() to anon,authenticated; revoke all on function public.sun_create_workspace(text) from public,anon; grant execute on function public.sun_create_workspace(text) to authenticated,service_role; commit;