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

+24
View File
@@ -0,0 +1,24 @@
from uuid import UUID
from fastapi import APIRouter
from backend.app.db import operations
from backend.app.api.schemas import CheckStart, CheckCommit, CheckAnswer
router = APIRouter(prefix="/api/chat", tags=["chat"])
@router.get("/greeting")
async def greeting():
return await operations.chat_greeting()
@router.post("/checks", status_code=201)
async def check_start(body: CheckStart):
return await operations.check_start(body.reading_id)
@router.post("/checks/{check_id}/commit")
async def check_commit(check_id: UUID, body: CheckCommit):
return await operations.check_commit(check_id, body.round, body.values)
@router.post("/checks/{check_id}/answer")
async def check_answer(check_id: UUID, body: CheckAnswer):
return await operations.check_answer(check_id, body.round, body.data)
+9
View File
@@ -0,0 +1,9 @@
from fastapi import APIRouter
from backend.app.db import operations
router = APIRouter(prefix="/api", tags=["system"])
@router.get("/health")
async def health():
return {"ok": await operations.ping() == 1}
+22
View File
@@ -0,0 +1,22 @@
from fastapi import APIRouter
from backend.app.db import operations
from backend.app.api.schemas import ReadingIn
router = APIRouter(prefix="/api", tags=["readings"])
@router.get("/resources")
async def resources():
return await operations.resources()
@router.get("/readings")
async def readings():
return await operations.readings()
@router.get("/readings/{reading_id}")
async def reading_public(reading_id: int):
return await operations.reading_public(reading_id)
@router.post("/readings", status_code=201)
async def reading_add(body: ReadingIn):
return await operations.add_reading(body.serial, body.kind, body.model_dump(mode="json")["metrics"])
+14
View File
@@ -0,0 +1,14 @@
from fastapi import APIRouter
from backend.app.db import operations
from backend.app.api.schemas import ReceiptOpen
router = APIRouter(prefix="/api/receipts", tags=["receipts"])
@router.get("")
async def receipts():
return await operations.receipts()
@router.post("/{receipt_id}/open")
async def receipt_open(receipt_id: int, body: ReceiptOpen):
return await operations.open_receipt(receipt_id, body.calculation_id)
+36
View File
@@ -0,0 +1,36 @@
import csv
import io
from fastapi import APIRouter, Query
from fastapi.responses import Response
from backend.app.api.schemas import ReportQueryIn
from backend.app.db import operations
from backend.app.db.connection import QueryError
router = APIRouter(prefix="/api/reports", tags=["reports"])
@router.get("/finance/fields")
async def finance_fields():
return await operations.report_fields("finance")
@router.get("/finance/summary")
async def finance_summary(period: str | None = None, fields: list[str] = Query(default=[]),
sort: str = "", group_by: str = "", filter: str = "", having: str = ""):
selected = [field.strip() for item in fields for field in item.split(",") if field.strip()]
return await operations.finance_report(period, selected, sort, group_by, filter, having)
@router.post("/export")
async def export_report(body: ReportQueryIn):
fields = body.fields
if not fields:
fields = [field["id"] for field in await operations.report_fields(body.report)]
if not fields:
raise QueryError("P0400", "Unknown report type.")
report = await operations.finance_report(body.period, fields, body.sort, body.group_by, body.filter, body.having)
output = io.StringIO(newline="")
writer = csv.writer(output)
writer.writerow([column["title"] for column in report["columns"]])
writer.writerows(report["rows"])
return Response(output.getvalue(), media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f'attachment; filename="finance-{report["period"]}.csv"'})
+43
View File
@@ -0,0 +1,43 @@
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, Field
class ReadingIn(BaseModel):
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
serial: str = Field(min_length=1, max_length=128)
kind: str = Field(min_length=1, max_length=16)
metrics: dict[str, Decimal] = Field(min_length=4, max_length=4)
class CheckStart(BaseModel):
model_config = ConfigDict(extra="forbid")
reading_id: int = Field(gt=0)
class CheckCommit(BaseModel):
model_config = ConfigDict(extra="forbid")
round: int = Field(ge=1, le=10)
values: list[str] = Field(min_length=3, max_length=3)
class CheckAnswer(BaseModel):
model_config = ConfigDict(extra="forbid")
round: int = Field(ge=1, le=10)
data: dict = Field(min_length=2, max_length=2)
class ReceiptOpen(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
calculation_id: str = Field(min_length=44, max_length=44, pattern=r"^[A-Za-z0-9+/]{43}=$")
class ReportQueryIn(BaseModel):
model_config = ConfigDict(extra="forbid")
report: str
period: str
fields: list[str] = []
sort: str = ""
group_by: str = ""
filter: str = ""
having: str = ""
+18
View File
@@ -0,0 +1,18 @@
from pathlib import Path
SQL = Path(__file__).resolve().parents[2] / "database" / "sql"
FILES = (
"schema/billing.sql",
"schema/receipts.sql",
"schema/checks.sql",
"schema/reports.sql",
"functions/checks.sql",
"functions/billing.sql",
"functions/receipts.sql",
"functions/chat.sql",
"functions/reports.sql",
)
def sql():
return "\n".join((SQL / name).read_text(encoding="utf-8") for name in FILES)
+43
View File
@@ -0,0 +1,43 @@
import os
from typing import Any
import psycopg
from psycopg_pool import AsyncConnectionPool
DSN = os.environ.get(
"DATABASE_URL", "postgresql://billing:billing@127.0.0.1:5432/billing"
)
pool: AsyncConnectionPool
class QueryError(Exception):
def __init__(self, sqlstate: str, message: str):
super().__init__(message)
self.sqlstate = sqlstate
self.message = message
def query_error(exc: psycopg.Error) -> QueryError:
message = getattr(exc.diag, "message_primary", None) or str(exc).splitlines()[0]
return QueryError(exc.sqlstate or "", message)
async def open_pool():
global pool
pool = AsyncConnectionPool(
DSN, min_size=1, max_size=8, open=False, kwargs={"autocommit": True},
check=AsyncConnectionPool.check_connection,
)
await pool.open(wait=True)
async def close_pool():
await pool.close()
async def call(sql: str, params: tuple = ()) -> Any:
try:
async with pool.connection() as connection:
cursor = await connection.execute(sql, params)
row = await cursor.fetchone()
except psycopg.Error as exc:
raise query_error(exc) from None
return row[0] if row else None
+27
View File
@@ -0,0 +1,27 @@
import asyncio
import psycopg
from backend.app.db import bootstrap
from backend.app.db.connection import DSN
STARTUP_ATTEMPTS = 10
STARTUP_DELAY = 1.0
async def initialize():
for attempt in range(1, STARTUP_ATTEMPTS + 1):
try:
async with await psycopg.AsyncConnection.connect(DSN, autocommit=True, connect_timeout=5) as db:
async with db.transaction():
await db.execute("select pg_advisory_xact_lock(hashtextextended('dark-tariff:bootstrap', 0))")
await db.execute(bootstrap.sql())
return
except psycopg.OperationalError as error:
if error.sqlstate and not (error.sqlstate.startswith("08") or error.sqlstate in {"40001", "40P01", "55P03"}):
raise
if attempt == STARTUP_ATTEMPTS:
raise
await asyncio.sleep(STARTUP_DELAY)
if __name__ == "__main__":
asyncio.run(initialize())
+75
View File
@@ -0,0 +1,75 @@
import asyncio
import base64
import secrets
import psycopg
from argon2.low_level import Type, hash_secret_raw
from psycopg.types.json import Jsonb
from backend.app.db import connection
from backend.app.db.connection import call
async def resources():
return await call("select billing.resource_types()")
async def readings():
return await call("select billing.reading_list()")
async def reading_public(reading_id):
return await call("select billing.reading_public(%s::bigint)", (reading_id,))
def calculation_key(reading_id):
value = f"{reading_id}|{secrets.randbelow(10000):04d}".encode("ascii")
key = hash_secret_raw(value, bytes(16), time_cost=1, memory_cost=8192,
parallelism=1, hash_len=32, type=Type.ID, version=19)
return base64.b64encode(key).decode("ascii")
async def add_reading(serial, kind, metrics):
try:
async with connection.pool.connection() as db:
async with db.transaction():
cursor = await db.execute(
"select billing.reading_add(%s::text, %s::text, %s::jsonb)",
(serial, kind, Jsonb(metrics)),
)
reading = (await cursor.fetchone())[0]
key = await asyncio.to_thread(calculation_key, reading["id"])
cursor = await db.execute(
"select billing.receipt_issue(r, %s::text)"
" from billing.reading r where r.id = %s::bigint",
(key, reading["id"]),
)
return reading | (await cursor.fetchone())[0] | {"calculation_id": key}
except psycopg.Error as exc:
raise connection.query_error(exc) from None
async def ping():
return await call("select 1")
async def chat_greeting():
return await call("select chat.greeting()")
async def check_start(reading_id):
return await call("select chat.check_start(%s::bigint)", (reading_id,))
async def check_commit(check_id, round, values):
return await call("select chat.check_commit(%s::uuid, %s::int, %s::text[])", (check_id, round, values))
async def check_answer(check_id, round, data):
return await call("select chat.check_answer(%s::uuid, %s::int, %s::jsonb)", (check_id, round, Jsonb(data)))
async def receipts():
return await call("select billing.receipt_list()")
async def open_receipt(receipt_id, calculation_id):
return await call("select billing.receipt_open(%s::bigint, %s::text)", (receipt_id, calculation_id))
async def report_fields(report):
return await call("select billing.report_fields(%s::text)", (report,))
async def finance_report(period=None, fields=None, sort="", group_by="", filter="", having=""):
return await call(
"select jsonb_build_object('period', coalesce(%s::text, to_char(current_date, 'YYYY-MM')))"
" || billing.finance_report(%s::text, %s::text[], %s::text, %s::text, %s::text, %s::text)",
(period, period, fields or [], sort, group_by, filter, having),
)
+63
View File
@@ -0,0 +1,63 @@
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from backend.app.db.connection import QueryError, close_pool, open_pool
from backend.app.api.routes import readings, receipts, health, chat, reports
FRONTEND = Path(__file__).resolve().parents[2] / "frontend"
STATUS = {
"P0400": 400,
"P0403": 403,
"P0404": 404,
"P0409": 409,
}
@asynccontextmanager
async def lifespan(_: FastAPI):
await open_pool()
yield
await close_pool()
def create_app() -> FastAPI:
app = FastAPI(
title="dark-tariff",
lifespan=lifespan,
docs_url=None,
redoc_url=None,
openapi_url=None,
max_body_size=65536,
)
for router in (readings.router, receipts.router, health.router, chat.router, reports.router):
app.include_router(router)
@app.exception_handler(QueryError)
async def query_error(_, exc: QueryError):
status = STATUS.get(exc.sqlstate, 500)
return JSONResponse(
{"detail": exc.message if status != 500 else "The service could not process the request."},
status_code=status,
)
app.mount("/static", StaticFiles(directory=FRONTEND), name="static")
@app.middleware("http")
async def revalidate_static(request, call_next):
response = await call_next(request)
if request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache"
if request.url.path.startswith("/api/") and request.method == "POST":
response.headers["Cache-Control"] = "no-store"
return response
@app.get("/", include_in_schema=False)
async def index():
return FileResponse(FRONTEND / "public" / "index.html")
return app
+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;
$$;
+22
View File
@@ -0,0 +1,22 @@
create extension if not exists pgcrypto;
create schema if not exists billing;
create table if not exists billing.reading (
id bigserial primary key,
serial text not null check (btrim(serial) <> '' and length(serial) <= 128),
kind text not null,
metrics jsonb not null check (jsonb_typeof(metrics) = 'object'),
created_at timestamptz not null default now(),
n integer not null,
h bit varying[] not null,
y bit varying not null,
w integer not null,
parameters text not null
);
create index if not exists reading_created_at_idx
on billing.reading (created_at);
create unique index if not exists reading_parameters_uniq
on billing.reading (digest(parameters, 'sha256'));
+12
View File
@@ -0,0 +1,12 @@
create schema if not exists chat;
create table if not exists chat.check_session (
id uuid primary key default gen_random_uuid(),
reading_id bigint not null references billing.reading (id) on delete cascade,
round integer not null default 1 check (round between 1 and 10),
challenge integer check (challenge between 0 and 2),
data text[],
complete boolean not null default false
);
create index if not exists check_session_reading_idx on chat.check_session (reading_id);
+7
View File
@@ -0,0 +1,7 @@
create table if not exists billing.receipt (
id bigserial primary key,
reading_id bigint not null unique references billing.reading (id) on delete cascade,
created_at timestamptz not null default now(),
key_digest bytea not null check (octet_length(key_digest) = 32),
data jsonb not null
);
+19
View File
@@ -0,0 +1,19 @@
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;
+21
View File
@@ -0,0 +1,21 @@
annotated-types==0.8.0
anyio==4.16.0
argon2-cffi==25.1.0
argon2-cffi-bindings==25.1.0
cffi==2.0.0
click==8.5.1
fastapi==0.165.0
h11==0.16.0
httptools==0.9.0
idna==3.20
psycopg==3.2.13
psycopg-binary==3.2.13
psycopg-pool==3.2.8
pycparser==2.23
pydantic==2.14.4
pydantic_core==2.50.5
starlette==1.10.0
typing-inspection==0.4.5
typing_extensions==4.16.0
uvicorn==0.34.3
uvloop==0.23.0