chore: import MCTF services

- Added all seven issued service trees without omissions.
- Preserved the supplied runtime configuration, binaries, and assets.
This commit is contained in:
TakuyaYagam1 committed 2026-11-29 12:25:29 +03:00
commit 13f936bee9
1222 files changed
+21280

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
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;
$$;
+4
View File
@@ -0,0 +1,4 @@
create or replace function chat.greeting() returns jsonb
language sql immutable as $$
select jsonb_build_object('role', 'bot', 'text', 'Здравствуйте! Я умный помощник сервиса Dark Tariff. Чем могу помочь?', 'prompt', 'Введите ID показания.')
$$;
+204
View File
@@ -0,0 +1,204 @@
create or replace function chat.pack(p_bits bit varying) returns bytea
language sql immutable strict as $$
select substring(varbit_send(p_bits) from 5)
$$;
create or replace function chat.dot(p_h bit varying[], p_v bit varying) returns bit varying
language sql immutable strict as $$
select string_agg((bit_count(bits & p_v) % 2)::text, '' order by ord)::bit varying
from unnest(p_h) with ordinality as rows(bits, ord)
$$;
create or replace function chat.permute(p_v bit varying, p_order integer[]) returns bit varying
language sql immutable strict as $$
select string_agg(get_bit(p_v, pos)::text, '' order by ord)::bit varying
from unnest(p_order) with ordinality as positions(pos, ord)
$$;
create or replace function chat.hash(p_text text) returns text
language sql immutable strict as $$
select encode(digest(p_text, 'sha256'), 'hex')
$$;
create or replace function chat.challenge() returns integer
language plpgsql volatile as $$
declare
v integer;
begin
loop
v := get_byte(gen_random_bytes(1), 0);
exit when v < 200;
end loop;
v := v % 100;
return case when v < 70 then 0 when v < 95 then 1 else 2 end;
end;
$$;
create or replace function chat.make_parameters() returns jsonb
language plpgsql volatile as $$
declare
v_n integer := 1024;
v_m integer := 512;
v_w integer := 112;
v_s bit varying := repeat('0', v_n)::bit varying;
v_h bit varying[] := array[]::bit varying[];
v_y bit varying;
v_row bit varying;
v_bytes bytea := ''::bytea;
v_params text;
v_pos integer;
begin
for v_pos in select i from generate_series(0, v_n - 1) i order by gen_random_bytes(16) limit v_w loop
v_s := set_bit(v_s, v_pos, 1);
end loop;
for v_pos in 0..v_m - 1 loop
v_row := set_bit(repeat('0', v_m)::bit varying, v_pos, 1)
|| ('x' || encode(gen_random_bytes(v_m / 8), 'hex'))::bit varying;
v_h := array_append(v_h, v_row);
v_bytes := v_bytes || chat.pack(v_row);
end loop;
v_y := chat.dot(v_h, v_s);
v_params := replace(encode(convert_to(v_n::text || '|' || encode(v_bytes, 'hex') || '|'
|| v_y::text || '|' || v_w::text, 'UTF8'), 'base64'), E'\n', '');
return jsonb_build_object('n', v_n, 'h', to_jsonb(v_h), 'y', v_y::text, 'w', v_w,
'parameters', v_params,
'verification_id', replace(encode(chat.pack(v_s), 'base64'), E'\n', ''));
end;
$$;
create or replace function chat.valid_response(p_reading billing.reading, p_values text[], p_challenge integer, p_data jsonb)
returns boolean
language plpgsql immutable as $$
declare
v_text text := p_data ->> 'v';
v_v bit varying;
v_t bit varying;
v_p integer[];
v_a text;
v_b text;
v_c text;
begin
if jsonb_typeof(p_data) is distinct from 'object' or v_text is null
or length(v_text) <> p_reading.n or v_text !~ '^[01]+$' then
return false;
end if;
if (select count(*) from jsonb_object_keys(p_data)) <> 2 then
return false;
end if;
v_v := v_text::bit varying;
if p_challenge in (0, 1) then
if jsonb_typeof(p_data -> 'p') is distinct from 'array' then
return false;
end if;
if jsonb_array_length(p_data -> 'p') <> p_reading.n
or exists (select 1 from jsonb_array_elements(p_data -> 'p') x
where jsonb_typeof(x) <> 'number' or x::text !~ '^(0|[1-9][0-9]{0,4})$') then
return false;
end if;
select array_agg(x::text::integer order by ord) into v_p
from jsonb_array_elements(p_data -> 'p') with ordinality as positions(x, ord);
if (select count(distinct x) from unnest(v_p) x) <> p_reading.n
or (select min(x) from unnest(v_p) x) <> 0
or (select max(x) from unnest(v_p) x) <> p_reading.n - 1 then
return false;
end if;
v_a := chat.hash('a|' || array_to_string(v_p, ',') || '|'
|| (chat.dot(p_reading.h, v_v) # case when p_challenge = 1 then p_reading.y
else repeat('0', bit_length(p_reading.y))::bit varying end)::text);
if p_challenge = 0 then
v_b := chat.hash('b|' || chat.permute(v_v, v_p)::text);
return v_a = p_values[1] and v_b = p_values[2];
end if;
v_c := chat.hash('c|' || chat.permute(v_v, v_p)::text);
return v_a = p_values[1] and v_c = p_values[3];
elsif p_challenge = 2 then
v_text := p_data ->> 't';
if v_text is null or length(v_text) <> p_reading.n or v_text !~ '^[01]+$' then
return false;
end if;
v_t := v_text::bit varying;
return bit_count(v_t) = p_reading.w
and chat.hash('b|' || v_v::text) = p_values[2]
and chat.hash('c|' || (v_v # v_t)::text) = p_values[3];
end if;
return false;
end;
$$;
create or replace function chat.check_start(p_reading bigint) returns jsonb
language plpgsql as $$
declare
v_id uuid;
begin
perform 1 from billing.reading where id = p_reading and created_at > now() - interval '10 minutes' for key share;
if not found then
raise exception 'Reading not found.' using errcode = 'P0404';
end if;
insert into chat.check_session (reading_id) values (p_reading) returning id into v_id;
return jsonb_build_object('id', v_id, 'round', 1, 'stage', 'commit',
'message', 'Step 1 of 10. Submit three values.');
end;
$$;
create or replace function chat.check_commit(p_id uuid, p_round integer, p_values text[]) returns jsonb
language plpgsql as $$
declare
v_session chat.check_session;
v_challenge integer;
begin
select * into v_session from chat.check_session where id = p_id for update;
if not found then
raise exception 'Verification not found.' using errcode = 'P0404';
end if;
if v_session.complete or v_session.round <> p_round or v_session.challenge is not null then
raise exception 'This step is already complete or awaiting an answer.' using errcode = 'P0409';
end if;
if cardinality(p_values) is distinct from 3
or exists (select 1 from unnest(p_values) x where x is null or x !~ '^[0-9a-f]{64}$') then
raise exception 'Invalid data format.' using errcode = 'P0400';
end if;
v_challenge := chat.challenge();
update chat.check_session set data = p_values, challenge = v_challenge where id = p_id;
return jsonb_build_object('round', p_round, 'stage', 'answer', 'challenge', v_challenge,
'message', format('Step %s of 10. Challenge: %s. Submit an answer.', p_round, v_challenge));
end;
$$;
create or replace function chat.check_answer(p_id uuid, p_round integer, p_data jsonb) returns jsonb
language plpgsql as $$
declare
v_session chat.check_session;
v_reading billing.reading;
begin
select * into v_session from chat.check_session where id = p_id for update;
if not found then
raise exception 'Verification not found.' using errcode = 'P0404';
end if;
if v_session.complete or v_session.round <> p_round or v_session.challenge is null then
raise exception 'This step is already complete or awaiting data.' using errcode = 'P0409';
end if;
select * into v_reading from billing.reading
where id = v_session.reading_id and created_at > now() - interval '10 minutes';
if not found then
delete from chat.check_session where id = p_id;
return jsonb_build_object('stage', 'failed', 'message', 'The reading is no longer available.');
end if;
if not coalesce(chat.valid_response(v_reading, v_session.data, v_session.challenge, p_data), false) then
delete from chat.check_session where id = p_id;
return jsonb_build_object('stage', 'failed', 'message', 'Verification failed. Try again.');
end if;
if p_round = 10 then
update chat.check_session set complete = true, challenge = null, data = null where id = p_id;
return jsonb_build_object('stage', 'done', 'reading_id', v_reading.id,
'message', 'Verification complete.',
'reading', jsonb_build_object('id', v_reading.id, 'serial', v_reading.serial,
'kind', v_reading.kind, 'metrics', v_reading.metrics,
'created_at', v_reading.created_at));
end if;
update chat.check_session set round = p_round + 1, challenge = null, data = null where id = p_id;
return jsonb_build_object('round', p_round + 1, 'stage', 'commit',
'message', format('Step %s of 10. Submit three values.', p_round + 1));
end;
$$;
drop function if exists chat.check_file(uuid);
+47
View File
@@ -0,0 +1,47 @@
create or replace function billing.receipt_issue(p_reading billing.reading, p_key text) returns jsonb
language plpgsql as $$
declare
v_tariff jsonb;
v_quantity numeric;
v_rate numeric(12, 2);
v_total numeric(22, 2);
v_id bigint;
begin
select item -> 'tariff' into v_tariff
from jsonb_array_elements(billing.resource_types()) item where item ->> 'id' = p_reading.kind;
v_quantity := (p_reading.metrics ->> (v_tariff ->> 'metric'))::numeric;
v_rate := (v_tariff ->> 'rate')::numeric;
v_total := round(v_quantity * v_rate, 2);
insert into billing.receipt (reading_id, key_digest, data)
values (p_reading.id, digest(p_key, 'sha256'), jsonb_build_object(
'reading', jsonb_build_object('id', p_reading.id, 'serial', p_reading.serial, 'kind', p_reading.kind,
'metrics', p_reading.metrics, 'created_at', p_reading.created_at, 'parameters', p_reading.parameters),
'calculation', jsonb_build_object('metric', v_tariff ->> 'metric', 'quantity', v_quantity,
'unit', v_tariff ->> 'unit', 'unit_price', v_rate::text, 'amount', v_total::text,
'currency', 'EDD', 'formula', 'quantity * unit_price')
)) returning id into v_id;
return jsonb_build_object('receipt_id', v_id);
end;
$$;
create or replace function billing.receipt_list() returns jsonb
language sql stable as $$
select coalesce(jsonb_agg(jsonb_build_object('id', id, 'created_at', created_at)
order by created_at desc, id desc), '[]'::jsonb)
from billing.receipt
$$;
create or replace function billing.receipt_open(p_id bigint, p_key text) returns jsonb
language plpgsql stable as $$
declare
v_receipt billing.receipt;
begin
select c.* into v_receipt from billing.receipt c join billing.reading r on r.id = c.reading_id
where c.id = p_id and r.created_at > now() - interval '10 minutes';
if not found or p_key is null or digest(p_key, 'sha256') is distinct from v_receipt.key_digest then
raise exception 'Receipt unavailable. Check the receipt ID and calculation ID.' using errcode = 'P0403';
end if;
return jsonb_build_object('id', v_receipt.id, 'reading_id', v_receipt.reading_id,
'created_at', v_receipt.created_at) || v_receipt.data;
end;
$$;
+58
View File
@@ -0,0 +1,58 @@
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;
$$;