create or replace function billing.resource_types() returns jsonb language sql immutable as $$ select '[ {"id": "water", "title": "Вода", "tariff": {"metric": "volume_m3", "rate": "42.10", "unit": "м³"}, "metrics": [ {"key": "volume_m3", "label": "Объём", "unit": "м³", "min": 0, "max": 999999999}, {"key": "temperature_c", "label": "Температура", "unit": "°C", "min": -273.15, "max": 1000}, {"key": "pressure_bar", "label": "Давление", "unit": "бар", "min": 0, "max": 999999999}, {"key": "flow_m3h", "label": "Расход", "unit": "м³/ч", "min": 0, "max": 999999999} ]}, {"id": "air", "title": "Воздух", "tariff": {"metric": "volume_m3", "rate": "25.50", "unit": "м³"}, "metrics": [ {"key": "volume_m3", "label": "Объём", "unit": "м³", "min": 0, "max": 999999999}, {"key": "temperature_c", "label": "Температура", "unit": "°C", "min": -273.15, "max": 1000}, {"key": "pressure_kpa", "label": "Давление", "unit": "кПа", "min": 0, "max": 999999999}, {"key": "humidity_pct", "label": "Влажность", "unit": "%", "min": 0, "max": 100} ]}, {"id": "power", "title": "Электроэнергия", "tariff": {"metric": "energy_kwh", "rate": "7.35", "unit": "кВт⋅ч"}, "metrics": [ {"key": "energy_kwh", "label": "Энергия", "unit": "кВт⋅ч", "min": 0, "max": 999999999}, {"key": "voltage_v", "label": "Напряжение", "unit": "В", "min": 0, "max": 999999999}, {"key": "current_a", "label": "Сила тока", "unit": "А", "min": 0, "max": 999999999}, {"key": "frequency_hz", "label": "Частота", "unit": "Гц", "min": 0, "max": 999999999} ]}, {"id": "heat", "title": "Тепло", "tariff": {"metric": "energy_gcal", "rate": "2300.00", "unit": "Гкал"}, "metrics": [ {"key": "energy_gcal", "label": "Тепловая энергия", "unit": "Гкал", "min": 0, "max": 999999999}, {"key": "volume_m3", "label": "Объём теплоносителя", "unit": "м³", "min": 0, "max": 999999999}, {"key": "supply_temperature_c", "label": "Температура подачи", "unit": "°C", "min": -273.15, "max": 1000}, {"key": "return_temperature_c", "label": "Температура обратки", "unit": "°C", "min": -273.15, "max": 1000} ]}, {"id": "waste", "title": "Отходы", "tariff": {"metric": "mass_kg", "rate": "12.00", "unit": "кг"}, "metrics": [ {"key": "mass_kg", "label": "Масса", "unit": "кг", "min": 0, "max": 999999999}, {"key": "volume_m3", "label": "Объём", "unit": "м³", "min": 0, "max": 999999999}, {"key": "density_kg_m3", "label": "Плотность", "unit": "кг/м³", "min": 0, "max": 999999999}, {"key": "humidity_pct", "label": "Влажность", "unit": "%", "min": 0, "max": 100} ]} ]'::jsonb $$; create or replace function billing.reading_list() returns jsonb language sql stable as $$ select coalesce(jsonb_agg(jsonb_build_object('id', r.id, 'parameters', r.parameters) order by r.created_at desc, r.id desc), '[]'::jsonb) from billing.reading r $$; create or replace function billing.reading_public(p_id bigint) returns jsonb language plpgsql stable as $$ declare v_reading jsonb; begin select jsonb_build_object('id', r.id, 'parameters', r.parameters) into v_reading from billing.reading r where r.id = p_id; if not found then raise exception 'Reading not found.' using errcode = 'P0404'; end if; return v_reading; end; $$; create or replace function billing.reading_add(p_serial text, p_kind text, p_metrics jsonb) returns jsonb language plpgsql as $$ declare v_resource jsonb; v_metric jsonb; v_text text; v_value numeric; v_metrics jsonb := '{}'::jsonb; v_reading billing.reading; v_parameters jsonb; begin if p_serial is null or btrim(p_serial) = '' or length(p_serial) > 128 then raise exception 'Enter a meter serial ID between 1 and 128 characters.' using errcode = 'P0400'; end if; select item into v_resource from jsonb_array_elements(billing.resource_types()) item where item ->> 'id' = p_kind; if v_resource is null then raise exception 'Select a valid resource type.' using errcode = 'P0400'; end if; if jsonb_typeof(p_metrics) is distinct from 'object' then raise exception 'Provide all four metrics for the selected resource type.' using errcode = 'P0400'; end if; if (select count(*) from jsonb_object_keys(p_metrics)) <> 4 or not p_metrics ?& array(select item ->> 'key' from jsonb_array_elements(v_resource -> 'metrics') item) then raise exception 'Provide all four metrics for the selected resource type.' using errcode = 'P0400'; end if; for v_metric in select * from jsonb_array_elements(v_resource -> 'metrics') loop v_text := p_metrics ->> (v_metric ->> 'key'); if v_text is null or length(v_text) > 32 then raise exception 'All metrics are required and must be numeric.' using errcode = 'P0400'; end if; begin v_value := v_text::numeric; exception when invalid_text_representation or numeric_value_out_of_range then raise exception 'All metrics are required and must be numeric.' using errcode = 'P0400'; end; if v_value not between (v_metric ->> 'min')::numeric and (v_metric ->> 'max')::numeric then raise exception 'Metric "%" is out of range.', v_metric ->> 'key' using errcode = 'P0400'; end if; v_metrics := v_metrics || jsonb_build_object(v_metric ->> 'key', v_value); end loop; v_parameters := chat.make_parameters(); insert into billing.reading (serial, kind, metrics, n, h, y, w, parameters) values (btrim(p_serial), p_kind, v_metrics, (v_parameters ->> 'n')::integer, array(select x::bit varying from jsonb_array_elements_text(v_parameters -> 'h') x), (v_parameters ->> 'y')::bit varying, (v_parameters ->> 'w')::integer, v_parameters ->> 'parameters') returning * into v_reading; return jsonb_build_object('id', v_reading.id, 'parameters', v_reading.parameters, 'verification_id', v_parameters ->> 'verification_id'); end; $$;