-- Generated by ops/demo/build-trial-demo.mjs. Fictional training catalog only. begin; create or replace function public.caterium_trial_demo_seed_v1() returns jsonb language sql immutable security definer set search_path=public,pg_temp as $fn$ select $demo$__DEMO_JSON__$demo$::jsonb $fn$; revoke all on function public.caterium_trial_demo_seed_v1() from public,anon,authenticated; create or replace function public.caterium_trial_demo_status(p_workspace uuid) returns jsonb language plpgsql stable security definer set search_path=public,pg_temp as $fn$ declare v_storage jsonb; v_empty boolean:=true; v_key text; v_value jsonb; v_allowed boolean; v_installed boolean; begin if auth.uid() is null or public.sun_member_role(p_workspace) is null then raise exception 'Access denied'; end if; select coalesce(payload->'storage','{}'::jsonb) into v_storage from public.sun_app_state where workspace_id=p_workspace; v_installed:=coalesce(v_storage#>>'{sunTrialDemoV1,v,version}','')='1'; foreach v_key in array array['sunBoxes','sunStock','sunSuppliers','sunStockMoves'] loop v_value:=v_storage#>array[v_key,'v']; if v_value is not null and v_value<>'[]'::jsonb then v_empty:=false; end if; if v_storage ? v_key and (jsonb_typeof(v_storage->v_key)<>'object' or v_value is null) then v_empty:=false; end if; end loop; v_allowed:=public.sun_member_role(p_workspace)='admin' and public.sun_subscription_access_mode(p_workspace)='full' and (exists(select 1 from public.sun_workspace_subscriptions where workspace_id=p_workspace and status='trialing') or public.sun_is_platform_admin()) and public.sun_workspace_has_feature(p_workspace,'catalog_edit') and public.sun_workspace_has_feature(p_workspace,'stock') and public.sun_workspace_has_feature(p_workspace,'suppliers') and not exists(select 1 from public.sun_workspace_members m join public.caterium_sidebar_brand_assignment a on a.user_id=m.user_id where m.workspace_id=p_workspace); return jsonb_build_object('eligible',coalesce(v_allowed,false),'installed',v_installed,'empty',v_empty,'canInstall',coalesce(v_allowed,false) and v_empty and not v_installed); end $fn$; revoke all on function public.caterium_trial_demo_status(uuid) from public,anon; grant execute on function public.caterium_trial_demo_status(uuid) to authenticated; create or replace function public.caterium_install_trial_demo(p_workspace uuid) returns jsonb language plpgsql security definer set search_path=public,pg_temp as $fn$ declare v_state public.sun_app_state%rowtype; v_status jsonb; v_seed jsonb; v_storage jsonb; v_moves jsonb; v_marker jsonb; begin if auth.uid() is null or public.sun_member_role(p_workspace) is distinct from 'admin' then raise exception 'Administrator membership required'; end if; perform 1 from public.sun_workspaces where id=p_workspace for update; v_status:=public.caterium_trial_demo_status(p_workspace); if not (v_status->>'eligible')::boolean then raise exception 'Демонстрационная база доступна в пробной или собственной тестовой компании разработчика'; end if; if (v_status->>'installed')::boolean then return v_status; end if; if not (v_status->>'empty')::boolean then raise exception 'Каталог, склад или поставщики уже заполнены. Данные сохранены без изменений'; end if; select * into v_state from public.sun_app_state where workspace_id=p_workspace for update; if not found then raise exception 'Рабочая база не найдена'; end if; v_seed:=public.caterium_trial_demo_seed_v1(); select coalesce(jsonb_agg(jsonb_build_object('id','demo-v1-opening-'||(p->>'id'),'productId',p->>'id','productName',p->>'name','unit',p->>'unit', 'type','set','qty',p->'qty','setTo',p->'qty','cost',p->'cost','date',current_date::text,'createdAt',now(), 'supplierId',p->>'supplierId','note','Учебный начальный остаток')),'[]'::jsonb) into v_moves from jsonb_array_elements(v_seed->'stock') p where (p->>'qty')::numeric>0; v_marker:=jsonb_build_object('version',1,'batch','trial-demo-v1','installedAt',now(),'scenario',v_seed->'scenario'); v_storage:=coalesce(v_state.payload->'storage','{}'::jsonb)||jsonb_build_object( 'sunBoxes',jsonb_build_object('t','j','v',v_seed->'boxes'), 'sunStock',jsonb_build_object('t','j','v',v_seed->'stock'), 'sunSuppliers',jsonb_build_object('t','j','v',v_seed->'suppliers'), 'sunStockMoves',jsonb_build_object('t','j','v',v_moves), 'sunTrialDemoV1',jsonb_build_object('t','j','v',v_marker)); perform public.sun_save_app_state_v17(p_workspace,jsonb_set(v_state.payload,'{storage}',v_storage),'trial-demo-v1',v_state.revision); insert into public.sun_platform_audit_events(actor_user_id,action,target_workspace_id,details) values(auth.uid(),'trial_demo.install',p_workspace,jsonb_build_object('version',1,'boxes',10)); return public.caterium_trial_demo_status(p_workspace); end $fn$; revoke all on function public.caterium_install_trial_demo(uuid) from public,anon; grant execute on function public.caterium_install_trial_demo(uuid) to authenticated; create or replace function public.caterium_seed_new_trial() returns trigger language plpgsql security definer set search_path=public,pg_temp as $fn$ begin if coalesce((public.caterium_trial_demo_status(new.workspace_id)->>'canInstall')::boolean,false) then perform public.caterium_install_trial_demo(new.workspace_id); end if; return new; end $fn$; revoke all on function public.caterium_seed_new_trial() from public,anon,authenticated; drop trigger if exists caterium_seed_new_trial on public.caterium_trial_redemptions; create trigger caterium_seed_new_trial after insert on public.caterium_trial_redemptions for each row execute function public.caterium_seed_new_trial(); notify pgrst,'reload schema'; commit;