create table if not exists billing.report_field ( id text primary key, title text not null, expression text not null, aggregate boolean not null default false, report_types text[] not null default '{}', position integer not null, created_at timestamptz not null default now() ); insert into billing.report_field (id, title, expression, aggregate, report_types, position) values ('period', 'Период', $field$to_char(r.created_at, 'YYYY-MM')$field$, false, '{finance}', 10), ('resource', 'Ресурс', $field$coalesce((select item->>'title' from jsonb_array_elements(billing.resource_types()) item where item->>'id' = r.kind), r.kind)$field$, false, '{finance}', 20), ('tariff', 'Тариф', $field$(c.data->'calculation'->>'unit_price')::numeric$field$, false, '{finance}', 30), ('quantity', 'Количество', $field$sum((c.data->'calculation'->>'quantity')::numeric)$field$, true, '{finance}', 40), ('amount', 'Сумма', $field$sum((c.data->'calculation'->>'amount')::numeric)$field$, true, '{finance}', 50), ('readings', 'Показаний', 'count(*)', true, '{finance}', 60) on conflict (id) do update set title = excluded.title, expression = excluded.expression, aggregate = excluded.aggregate, report_types = excluded.report_types, position = excluded.position;