-- Caterium v17.8.2 -- Public company creation belongs only to a new owner redeeming a trial promo. -- Employees are attached to an existing workspace through membership/invite flows. begin; 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_promo public.caterium_trial_promos%rowtype; v_trial_end timestamptz; begin if v_user is null then raise exception 'Authentication required'; 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; if coalesce(v_code,'')='' then raise exception 'Для создания новой компании нужен промокод пробной версии'; end if; 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); 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; insert into public.sun_workspace_subscriptions(workspace_id,plan_id,status,trial_started_at,trial_ends_at,grace_until,source,note) values(v_workspace,v_promo.plan_id,'trialing',now(),v_trial_end,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,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; update auth.users set raw_user_meta_data=coalesce(raw_user_meta_data,'{}'::jsonb)-'promo_code'-'company_name' where id=v_user; perform public.sun_platform_log_event('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)); return v_workspace; end; $function$; 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;