create or replace function billing.report_fields(p_report text) returns jsonb language sql stable as $$ select coalesce(jsonb_agg(jsonb_build_object('id', id, 'title', title) order by position, id), '[]'::jsonb) from billing.report_field where report_types @> array[p_report] $$; create or replace function billing.finance_report( p_period text, p_fields text[], p_sort text, p_group_by text, p_filter text, p_having text ) returns jsonb language plpgsql stable as $$ declare v_period text := coalesce(p_period, to_char(current_date, 'YYYY-MM')); v_fields text[] := p_fields; v_columns jsonb; v_context text; v_select text; v_group text; v_values text; v_rows jsonb; begin if v_period !~ '^[0-9]{4}-(0[1-9]|1[0-2])$' or left(v_period, 4) = '0000' then raise exception 'Invalid period. Use YYYY-MM.' using errcode = 'P0400'; end if; if coalesce(cardinality(v_fields), 0) = 0 then select array_agg(id order by position, id) into v_fields from billing.report_field where report_types @> array['finance']; end if; if exists (select 1 from unnest(v_fields) field where not exists ( select 1 from billing.report_field where id = field and report_types @> array['finance'] )) then raise exception 'Unknown financial report column.' using errcode = 'P0400'; end if; select string_agg(format('%s as %I', expression, id), ', ' order by position, id) into v_context from billing.report_field where report_types @> array['finance'] and not aggregate; select jsonb_agg(jsonb_build_object('id', id, 'title', title) order by position, id), string_agg(format('%s as %I', case when aggregate then expression else format('dimensions.%I', id) end, id), ', ' order by position, id), string_agg(format('dimensions.%I', id), ', ' order by position, id) filter (where not aggregate), string_agg(format('report.%I', id), ', ' order by position, id) into v_columns, v_select, v_group, v_values from billing.report_field where id = any(v_fields) and report_types @> array['finance']; execute format( 'select coalesce(jsonb_agg(jsonb_build_array(%s)), ''[]''::jsonb) from ( select %s from billing.receipt c join billing.reading r on r.id = c.reading_id cross join lateral (select %s) dimensions where to_char(r.created_at, ''YYYY-MM'') = $1 and (%s) group by %s having (%s) order by %s ) report', v_values, v_select, v_context, coalesce(nullif(btrim(p_filter), ''), 'true'), concat_ws(', ', coalesce(nullif(btrim(p_group_by), ''), 'period, resource, tariff'), v_group), coalesce(nullif(btrim(p_having), ''), 'true'), coalesce(nullif(btrim(p_sort), ''), 'resource') ) into v_rows using v_period; return jsonb_build_object('columns', v_columns, 'rows', v_rows); exception when syntax_error_or_access_rule_violation or data_exception then raise exception 'Invalid report expression.' using errcode = 'P0400'; end; $$;