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