do $fix_indicators$
declare
v_group record;
v_parent_id integer;
v_parent_count integer;
begin
for v_group in
select *
from (
values
('38911', array[31, 32]),
('39011', array[36, 37])
) as groups(account, child_ids)
loop
select min(si.id), count(distinct si.id)
into v_parent_id, v_parent_count
from ourpension.spr_indicator_bu si
join ourpension.spr_accounts_indicator_bu sa
on sa.spr_indicator_bu_id = si.id
where sa.account = v_group.account
and (
'NPO' = any(si.service_type)
or 'PDS' = any(si.service_type)
);
if v_parent_count > 1 then
raise exception
'Для счёта % найдено несколько показателей',
v_group.account;
end if;
if v_parent_count = 0 then
insert into ourpension.spr_indicator_bu (
name,
service_type,
is_aggregate
)
values (
'РППО по договорам НПО (ОВТ)',
array['NPO', 'PDS'],
0
)
returning id into v_parent_id;
insert into ourpension.spr_accounts_indicator_bu (
spr_indicator_bu_id,
account
)
values (
v_parent_id,
v_group.account
);
end if;
update ourpension.spr_indicator_bu
set
is_aggregate = v_parent_id,
name = case
when id in (31, 36)
then 'обязательства к выплате'
when id in (32, 37)
then 'обязательства, не исполненные в срок'
end
where id = any(v_group.child_ids);
raise notice
'Счёт %: общий показатель ID %, связанные детали %',
v_group.account,
v_parent_id,
v_group.child_ids;
end loop;
end;
$fix_indicators$;