Загрузка данных
do $fix_pds_groups_next$
declare
g record;
d record;
v_parent_id integer;
v_child_id integer;
v_count integer;
begin
for g in
select *
from (
values
(
'39035',
'РППО по выплатам выкупных сумм при расторжении договора ДС, переведенным в другой фонд'
),
(
'39036',
'РППО по выплатам выкупных сумм в особых жизненных ситуациях по договорам ДС'
),
(
'39037',
'РППО по выплатам правопреемникам по договорам ДС'
)
) as groups(account, name)
loop
select
count(distinct si.id),
min(si.id)
into v_count, v_parent_id
from ourpension.spr_indicator_bu si
join ourpension.spr_accounts_indicator_bu sa
on sa.spr_indicator_bu_id = si.id
where sa.account = g.account
and (
'NPO' = any(si.service_type)
or 'PDS' = any(si.service_type)
);
if v_count > 1 then
raise exception
'Для счета % найдено несколько показателей',
g.account;
end if;
if v_parent_id is null then
insert into ourpension.spr_indicator_bu (
name,
service_type,
is_aggregate
)
values (
g.name,
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,
g.account
);
end if;
for d in
select *
from (
values
(
g.account || '.1',
'обязательства к выплате'
),
(
g.account || '.2',
'обязательства, не исполненные в срок'
)
) as details(account, name)
loop
select
count(distinct si.id),
min(si.id)
into v_count, v_child_id
from ourpension.spr_indicator_bu si
join ourpension.spr_accounts_indicator_bu sa
on sa.spr_indicator_bu_id = si.id
where sa.account = d.account
and (
'NPO' = any(si.service_type)
or 'PDS' = any(si.service_type)
);
if v_count > 1 then
raise exception
'Для счета % найдено несколько показателей',
d.account;
end if;
if v_child_id is null then
insert into ourpension.spr_indicator_bu (
name,
service_type,
is_aggregate
)
values (
d.name,
array['NPO', 'PDS'],
v_parent_id
)
returning id into v_child_id;
insert into ourpension.spr_accounts_indicator_bu (
spr_indicator_bu_id,
account
)
values (
v_child_id,
d.account
);
else
update ourpension.spr_indicator_bu
set
name = d.name,
is_aggregate = v_parent_id
where id = v_child_id;
end if;
raise notice
'Общий показатель: ID %, счет %. Деталь: ID %, счет %',
v_parent_id, g.account,
v_child_id, d.account;
end loop;
end loop;
end;
$fix_pds_groups_next$;