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:
commit
13f936bee9
1222 files changed
+21280
No files matched your search
Executable
+15
@@ -0,0 +1,15 @@
|
||||
FROM python:3.12.16-slim-bookworm
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY backend/requirements.txt ./
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY backend ./backend/
|
||||
COPY frontend ./frontend/
|
||||
|
||||
RUN useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin darktariff
|
||||
|
||||
USER darktariff
|
||||
|
||||
CMD ["sh", "-c", "python -m backend.app.db.initialize && exec uvicorn backend.app.main:create_app --factory --host 0.0.0.0 --port 8080 --workers 4 --limit-concurrency 32"]
|
||||
Executable
+24
@@ -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)
|
||||
Executable
+9
@@ -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
@@ -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
@@ -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
@@ -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"'})
|
||||
Executable
+43
@@ -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 = ""
|
||||
Executable
+18
@@ -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)
|
||||
Executable
+43
@@ -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
|
||||
Executable
+27
@@ -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())
|
||||
Executable
+75
@@ -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),
|
||||
)
|
||||
Executable
+63
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||
@@ -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
@@ -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;
|
||||
Executable
+21
@@ -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
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
FROM postgres:16.16-bookworm
|
||||
|
||||
COPY --chmod=755 cleaner.sh /cleaner.sh
|
||||
|
||||
CMD ["/cleaner.sh"]
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
set -eu
|
||||
|
||||
while true; do
|
||||
psql --no-psqlrc --set=ON_ERROR_STOP=1 <<'SQL'
|
||||
delete from billing.reading
|
||||
where created_at <= now() - interval '10 minutes';
|
||||
SQL
|
||||
sleep 60
|
||||
done
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
name: dark-tariff
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:16.16-bookworm
|
||||
command: ["postgres", "-c", "max_connections=64", "-c", "statement_timeout=5s", "-c", "lock_timeout=2s", "-c", "idle_in_transaction_session_timeout=5s"]
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-billing}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-billing}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-billing}
|
||||
volumes:
|
||||
- data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-billing} -d ${POSTGRES_DB:-billing}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 512M
|
||||
pids: 256
|
||||
stop_grace_period: 30s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
restart: unless-stopped
|
||||
|
||||
cleaner:
|
||||
build: ./cleaner
|
||||
environment:
|
||||
PGHOST: db
|
||||
PGPORT: "5432"
|
||||
PGUSER: ${POSTGRES_USER:-billing}
|
||||
PGPASSWORD: ${POSTGRES_PASSWORD:-billing}
|
||||
PGDATABASE: ${POSTGRES_DB:-billing}
|
||||
PGOPTIONS: "-c statement_timeout=30s -c lock_timeout=5s"
|
||||
depends_on:
|
||||
service:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
pids: 64
|
||||
init: true
|
||||
stop_grace_period: 10s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
restart: unless-stopped
|
||||
|
||||
service:
|
||||
build: .
|
||||
environment:
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-billing}:${POSTGRES_PASSWORD:-billing}@db:5432/${POSTGRES_DB:-billing}
|
||||
PYTHONDONTWRITEBYTECODE: "1"
|
||||
PYTHONUNBUFFERED: "1"
|
||||
ports:
|
||||
- "0.0.0.0:8080:8080"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=2).close()"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
start_period: 10s
|
||||
retries: 3
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 512M
|
||||
pids: 256
|
||||
init: true
|
||||
stop_grace_period: 10s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
data:
|
||||
driver: local
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
POSTGRES_USER=billing
|
||||
POSTGRES_PASSWORD=billing
|
||||
POSTGRES_DB=billing
|
||||
Executable
+150
@@ -0,0 +1,150 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="theme-color" content="#101015">
|
||||
<title>Передать показания — Dark Tariff</title>
|
||||
<link rel="stylesheet" href="/static/src/styles/main.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="shell topbar-inner">
|
||||
<a class="brand" href="#/submit" aria-label="Dark Tariff — главная">
|
||||
<svg id="brand-mark" class="brand-mark" viewBox="0 0 36 36" aria-hidden="true">
|
||||
<path class="meter-shell" d="M10 2h16l8 8v16l-8 8H10l-8-8V10z"/>
|
||||
<path class="meter-screen" d="M8 8h20v10H8z"/>
|
||||
<path class="meter-readout" d="M12 13h4m4 0h4"/>
|
||||
<path class="meter-dial" d="M9 28a9 9 0 0 1 18 0M18 27l6-6"/>
|
||||
<circle class="meter-core" cx="18" cy="27" r="2"/>
|
||||
</svg><span>Dark Tariff</span>
|
||||
</a>
|
||||
<nav class="main-nav" aria-label="Основные разделы">
|
||||
<a href="#/submit" data-route="submit">Передать показания</a>
|
||||
<a href="#/history" data-route="history">Показания</a>
|
||||
<a href="#/receipts" data-route="receipts">Квитанции</a>
|
||||
<a href="#/finance" data-route="finance">Финансы</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="shell">
|
||||
<section class="page" data-page="submit" aria-labelledby="submit-page-title">
|
||||
<p class="eyebrow">Учёт ресурсов</p>
|
||||
<h1 id="submit-page-title">Передавайте показания</h1>
|
||||
<p class="intro">Фиксируйте показания в новом сервисе Night City — Dark Tariff</p>
|
||||
<button id="reading-open" class="primary" type="button" disabled>Передать показания</button>
|
||||
<div id="page-note" class="note" role="status" aria-live="polite" hidden></div>
|
||||
</section>
|
||||
|
||||
<section class="page" data-page="history" aria-labelledby="history-page-title" hidden>
|
||||
<p class="eyebrow">Переданные показания</p>
|
||||
<h1 id="history-page-title">Показания</h1>
|
||||
<div id="history-note" class="note" role="status" aria-live="polite">Загрузка…</div>
|
||||
<div id="history" class="history-grid"></div>
|
||||
</section>
|
||||
<section class="page" data-page="receipts" aria-labelledby="receipts-page-title" hidden>
|
||||
<p class="eyebrow">Расчёт ресурсов</p>
|
||||
<h1 id="receipts-page-title">Квитанции</h1>
|
||||
<div id="receipts-note" class="note" role="status" aria-live="polite">Загрузка…</div>
|
||||
<div id="receipts" class="history-grid"></div>
|
||||
</section>
|
||||
<section class="page" data-page="finance" aria-labelledby="finance-page-title" hidden>
|
||||
<p class="eyebrow">Финансовый отчёт</p>
|
||||
<h1 id="finance-page-title">Финансы</h1>
|
||||
<div class="finance-controls">
|
||||
<label><span>Период</span><input id="finance-period" type="month" required></label>
|
||||
<label><span>Сортировка</span><select id="finance-sort"></select></label>
|
||||
<label><span>Группировка</span><select id="finance-group">
|
||||
<option value="period, resource, tariff">По ресурсу и тарифу</option>
|
||||
<option value="period, resource">По ресурсу</option>
|
||||
<option value="period">По месяцу</option>
|
||||
</select></label>
|
||||
<label><span>Ресурс содержит</span><input id="finance-filter" type="text" placeholder="Например, Вода"></label>
|
||||
<button id="finance-export" class="primary" type="button" disabled>Скачать CSV</button>
|
||||
</div>
|
||||
<fieldset class="finance-options">
|
||||
<legend>Колонки отчёта</legend>
|
||||
<div id="finance-fields"></div>
|
||||
</fieldset>
|
||||
<div id="finance-note" class="note" role="status" aria-live="polite">Загрузка…</div>
|
||||
<div class="finance-scroll"><table id="finance-table" hidden></table></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<dialog id="reading-dialog" aria-labelledby="reading-dialog-title">
|
||||
<div class="panel-head">
|
||||
<h2 id="reading-dialog-title">Передать показания</h2>
|
||||
<button id="reading-close" class="action" type="button" aria-label="Закрыть форму">×</button>
|
||||
</div>
|
||||
<form id="reading-form" autocomplete="off">
|
||||
<label><span>Серийный ID счётчика</span><input name="serial" maxlength="128" required></label>
|
||||
<label><span>Вид измеряемой величины</span><select name="kind" required><option value="">Выберите ресурс</option></select></label>
|
||||
<div id="metric-fields" class="metric-grid"></div>
|
||||
<div id="reading-note" class="note" role="status" aria-live="polite" hidden></div>
|
||||
<button class="primary" type="submit">Отправить показания</button>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<dialog id="verification-dialog" aria-labelledby="verification-title">
|
||||
<div class="panel-head">
|
||||
<h2 id="verification-title">Сохраните идентификаторы</h2>
|
||||
<button id="verification-close" class="action" type="button" aria-label="Закрыть идентификаторы">×</button>
|
||||
</div>
|
||||
<div class="verification-body">
|
||||
<p>Сохраните оба идентификатора. Они показываются только один раз: для проверки показания и открытия квитанции.</p>
|
||||
<p>ID показания: <strong id="verification-reading"></strong></p>
|
||||
<p>ID квитанции: <strong id="verification-receipt"></strong></p>
|
||||
<label><span>Идентификатор проверки</span><textarea id="verification-secret" rows="4" readonly spellcheck="false"></textarea></label>
|
||||
<label><span>Расчётный идентификатор</span><textarea id="calculation-secret" rows="2" readonly spellcheck="false"></textarea></label>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<dialog id="receipt-dialog" aria-labelledby="receipt-dialog-title">
|
||||
<div class="panel-head">
|
||||
<h2 id="receipt-dialog-title">Квитанция</h2>
|
||||
<button id="receipt-close" class="action" type="button" aria-label="Закрыть квитанцию">×</button>
|
||||
</div>
|
||||
<form id="receipt-form" autocomplete="off">
|
||||
<label><span>Расчётный идентификатор</span><input name="calculation_id" type="password" minlength="44" maxlength="44" required></label>
|
||||
<div id="receipt-note" class="note" role="status" aria-live="polite" hidden></div>
|
||||
<button class="primary" type="submit">Открыть квитанцию</button>
|
||||
</form>
|
||||
<div id="receipt-content" class="verification-body" hidden>
|
||||
<dl id="receipt-details" class="receipt-details"></dl>
|
||||
<label><span>Публичные параметры показания</span><textarea id="receipt-parameters" rows="4" readonly spellcheck="false"></textarea></label>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<dialog id="reading-result-dialog" aria-labelledby="reading-result-title">
|
||||
<div class="panel-head">
|
||||
<h2 id="reading-result-title">Показание</h2>
|
||||
<button id="reading-result-close" class="action" type="button" aria-label="Закрыть показание">×</button>
|
||||
</div>
|
||||
<div class="verification-body"><dl id="reading-result-details" class="receipt-details"></dl></div>
|
||||
</dialog>
|
||||
|
||||
<section id="help-chat" class="help-chat panel" role="dialog" aria-labelledby="help-chat-title" hidden>
|
||||
<div class="panel-head">
|
||||
<h2 id="help-chat-title">Помощник Dark Tariff</h2>
|
||||
<button id="help-close" type="button" class="action" aria-label="Закрыть чат">×</button>
|
||||
</div>
|
||||
<div class="help-messages" role="log" aria-live="polite">
|
||||
<p id="help-message">Загрузка…</p>
|
||||
</div>
|
||||
<div class="help-controls">
|
||||
<button id="help-question" class="action" type="button" disabled>Помогите мне проверить мои переданные показания</button>
|
||||
<form id="help-form" autocomplete="off" hidden>
|
||||
<label id="help-id-label"><span>ID показания</span><input id="help-id" name="reading_id" type="number" min="1" step="1" required></label>
|
||||
<label id="help-data-label" hidden><span>Данные проверки (JSON)</span><textarea id="help-data" rows="5" maxlength="24000" spellcheck="false" disabled required></textarea></label>
|
||||
<div id="help-note" class="note" role="status" aria-live="polite" hidden></div>
|
||||
<button class="primary" type="submit">Отправить</button>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
<button id="help-launcher" class="help-launcher" type="button" aria-controls="help-chat" aria-expanded="false">
|
||||
<span class="help-hint">Нужна помощь?</span>
|
||||
<svg class="brand-mark" viewBox="0 0 36 36" aria-hidden="true"><use href="#brand-mark"/></svg>
|
||||
</button>
|
||||
<script type="module" src="/static/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
function jsonPost(body) {
|
||||
return { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) };
|
||||
}
|
||||
|
||||
function responseError(result, fallback) {
|
||||
return new Error(typeof result.detail === "string" ? result.detail : fallback);
|
||||
}
|
||||
|
||||
export async function api(path, opts = {}) {
|
||||
const response = await fetch(path, opts);
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw responseError(result, "Проверьте поля запроса.");
|
||||
return result;
|
||||
}
|
||||
|
||||
export function post(path, body) {
|
||||
return api(path, jsonPost(body));
|
||||
}
|
||||
|
||||
export async function download(path, body, fallback) {
|
||||
const response = await fetch(path, jsonPost(body));
|
||||
if (!response.ok) {
|
||||
const result = await response.json();
|
||||
throw responseError(result, "Не удалось скачать отчёт.");
|
||||
}
|
||||
const url = URL.createObjectURL(await response.blob());
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = response.headers.get("content-disposition")?.match(/filename="?([^";]+)"?/i)?.[1] || fallback;
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
import { api, post } from "../api/client.js";
|
||||
import { $, cell, note } from "../shared/dom.js";
|
||||
|
||||
export async function initChat(resourcesPromise) {
|
||||
const launcher = $("#help-launcher");
|
||||
const chat = $("#help-chat");
|
||||
const close = $("#help-close");
|
||||
const question = $("#help-question");
|
||||
const form = $("#help-form");
|
||||
const input = $("#help-id");
|
||||
const data = $("#help-data");
|
||||
const messages = $(".help-messages");
|
||||
const dialog = $("#reading-result-dialog");
|
||||
const details = $("#reading-result-details");
|
||||
let greeting;
|
||||
let stage = "id";
|
||||
let check;
|
||||
let round;
|
||||
|
||||
function message(text, kind = "") {
|
||||
messages.append(cell("p", text, kind));
|
||||
messages.scrollTop = messages.scrollHeight;
|
||||
}
|
||||
function setOpen(open) {
|
||||
chat.hidden = !open;
|
||||
launcher.setAttribute("aria-expanded", String(open));
|
||||
(open ? close : launcher).focus();
|
||||
}
|
||||
function finish() {
|
||||
form.hidden = true;
|
||||
form.reset();
|
||||
question.hidden = false;
|
||||
check = null;
|
||||
}
|
||||
$("#reading-result-close").addEventListener("click", () => dialog.close());
|
||||
dialog.addEventListener("close", () => details.replaceChildren());
|
||||
launcher.addEventListener("click", () => setOpen(chat.hidden));
|
||||
close.addEventListener("click", () => setOpen(false));
|
||||
chat.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") setOpen(false);
|
||||
});
|
||||
question.addEventListener("click", () => {
|
||||
stage = "id";
|
||||
form.reset();
|
||||
question.hidden = true;
|
||||
form.hidden = false;
|
||||
$("#help-note").hidden = true;
|
||||
$("#help-id-label").hidden = false;
|
||||
$("#help-data-label").hidden = true;
|
||||
input.disabled = false;
|
||||
data.disabled = true;
|
||||
message(question.textContent, "help-user");
|
||||
message(greeting.prompt);
|
||||
input.focus();
|
||||
});
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const button = event.submitter;
|
||||
button.disabled = true;
|
||||
$("#help-note").hidden = true;
|
||||
try {
|
||||
let result;
|
||||
if (stage === "id") {
|
||||
result = await post("/api/chat/checks", { reading_id: Number(input.value) });
|
||||
check = result.id;
|
||||
input.disabled = true;
|
||||
data.disabled = false;
|
||||
$("#help-id-label").hidden = true;
|
||||
$("#help-data-label").hidden = false;
|
||||
} else {
|
||||
let value;
|
||||
try { value = JSON.parse(data.value); }
|
||||
catch { throw new Error("Проверьте формат JSON."); }
|
||||
result = await post(`/api/chat/checks/${check}/${stage === "commit" ? "commit" : "answer"}`,
|
||||
stage === "commit" ? { round, values: value } : { round, data: value });
|
||||
}
|
||||
stage = result.stage;
|
||||
round = result.round;
|
||||
data.value = "";
|
||||
message(result.message);
|
||||
if (stage === "done") {
|
||||
finish();
|
||||
const reading = result.reading;
|
||||
const resource = (await resourcesPromise).find((item) => item.id === reading.kind);
|
||||
const rows = [
|
||||
["ID показания", reading.id], ["Дата показания", new Date(reading.created_at).toLocaleString("ru-RU")],
|
||||
["Серийный ID", reading.serial], ["Вид ресурса", resource.title],
|
||||
...resource.metrics.map((metric) => [metric.label, `${reading.metrics[metric.key]} ${metric.unit}`]),
|
||||
];
|
||||
details.replaceChildren();
|
||||
for (const [label, value] of rows) details.append(cell("dt", label), cell("dd", value));
|
||||
dialog.showModal();
|
||||
} else if (stage === "failed") {
|
||||
finish();
|
||||
} else {
|
||||
data.focus();
|
||||
}
|
||||
} catch (error) {
|
||||
note($("#help-note"), error.message, "err");
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
try {
|
||||
greeting = await api("/api/chat/greeting");
|
||||
$("#help-message").textContent = greeting.text;
|
||||
question.disabled = false;
|
||||
} catch {
|
||||
$("#help-message").textContent = "Не удалось загрузить сообщение. Обновите страницу.";
|
||||
}
|
||||
return () => {
|
||||
setOpen(true);
|
||||
if (!question.hidden) question.click();
|
||||
};
|
||||
}
|
||||
Executable
+117
@@ -0,0 +1,117 @@
|
||||
import { api, download } from "../api/client.js";
|
||||
import { $, cell, note } from "../shared/dom.js";
|
||||
import { onRoute } from "../shared/router.js";
|
||||
|
||||
export function initFinance() {
|
||||
const period = $("#finance-period");
|
||||
const fields = $("#finance-fields");
|
||||
const sort = $("#finance-sort");
|
||||
const group = $("#finance-group");
|
||||
const filter = $("#finance-filter");
|
||||
const button = $("#finance-export");
|
||||
const table = $("#finance-table");
|
||||
const status = $("#finance-note");
|
||||
const money = new Intl.NumberFormat("ru-RU", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
const today = new Date();
|
||||
period.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}`;
|
||||
let loading = 0;
|
||||
|
||||
function selected() {
|
||||
return Array.from(fields.querySelectorAll("input:checked"), (input) => input.value);
|
||||
}
|
||||
|
||||
function query() {
|
||||
const text = filter.value.trim().replace(/[\\%_]/g, "\\$&").replaceAll("'", "''");
|
||||
return { report: "finance", period: period.value, fields: selected(), sort: sort.value,
|
||||
group_by: group.value, filter: text ? `resource ilike '%${text}%'` : "", having: "" };
|
||||
}
|
||||
|
||||
function selectSort() {
|
||||
const ids = selected();
|
||||
for (const option of sort.options) option.disabled = !ids.includes(option.value.split(" ")[0]);
|
||||
if (sort.selectedOptions[0]?.disabled) sort.value = Array.from(sort.options).find((option) => !option.disabled)?.value || "";
|
||||
sort.disabled = !ids.length;
|
||||
}
|
||||
|
||||
function selectGroup() {
|
||||
const dimensions = group.options[0].value.split(", ");
|
||||
for (const input of fields.querySelectorAll("input")) {
|
||||
if (dimensions.includes(input.value)) input.checked = group.value.split(", ").includes(input.value);
|
||||
}
|
||||
selectSort();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const request = ++loading;
|
||||
button.disabled = true;
|
||||
table.hidden = true;
|
||||
note(status, "Загрузка…");
|
||||
try {
|
||||
if (!fields.children.length) {
|
||||
const catalogue = await api("/api/reports/finance/fields");
|
||||
if (request !== loading) return;
|
||||
for (const field of catalogue) {
|
||||
const label = document.createElement("label");
|
||||
const input = document.createElement("input");
|
||||
input.type = "checkbox";
|
||||
input.value = field.id;
|
||||
input.checked = true;
|
||||
label.append(input, cell("span", field.title));
|
||||
fields.append(label);
|
||||
for (const direction of ["asc", "desc"]) {
|
||||
const option = cell("option", `${field.title} ${direction === "asc" ? "↑" : "↓"}`);
|
||||
option.value = `${field.id} ${direction}`;
|
||||
sort.append(option);
|
||||
}
|
||||
}
|
||||
sort.value = "resource asc";
|
||||
selectGroup();
|
||||
}
|
||||
const data = query();
|
||||
if (!data.fields.length) return note(status, "Выберите хотя бы одну колонку.");
|
||||
const params = new URLSearchParams({ period: data.period, sort: data.sort, group_by: data.group_by, filter: data.filter, having: data.having });
|
||||
for (const field of data.fields) params.append("fields", field);
|
||||
const report = await api(`/api/reports/finance/summary?${params}`);
|
||||
if (request !== loading) return;
|
||||
const head = document.createElement("thead");
|
||||
const row = document.createElement("tr");
|
||||
for (const column of report.columns) {
|
||||
const title = cell("th", column.title);
|
||||
title.scope = "col";
|
||||
row.append(title);
|
||||
}
|
||||
head.append(row);
|
||||
const body = document.createElement("tbody");
|
||||
for (const values of report.rows) {
|
||||
const row = document.createElement("tr");
|
||||
report.columns.forEach((column, index) => row.append(cell("td", ["tariff", "amount"].includes(column.id) ? money.format(values[index]) : values[index])));
|
||||
body.append(row);
|
||||
}
|
||||
table.replaceChildren(head, body);
|
||||
table.hidden = !report.rows.length;
|
||||
status.hidden = report.rows.length > 0;
|
||||
if (!report.rows.length) note(status, "За выбранный период показаний нет.");
|
||||
button.disabled = false;
|
||||
} catch (error) {
|
||||
if (request === loading) note(status, error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
period.addEventListener("change", load);
|
||||
sort.addEventListener("change", load);
|
||||
filter.addEventListener("input", load);
|
||||
fields.addEventListener("change", () => { selectSort(); load(); });
|
||||
group.addEventListener("change", () => { selectGroup(); load(); });
|
||||
button.addEventListener("click", async () => {
|
||||
const request = loading;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await download("/api/reports/export", query(), `finance-${period.value}.csv`);
|
||||
} catch (error) {
|
||||
note(status, error.message, "err");
|
||||
} finally {
|
||||
if (request === loading) button.disabled = !selected().length;
|
||||
}
|
||||
});
|
||||
onRoute("finance", load);
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import { api, post } from "../api/client.js";
|
||||
import { $, cell, note } from "../shared/dom.js";
|
||||
import { navigateTo, onRoute } from "../shared/router.js";
|
||||
|
||||
export async function initReadings(resourcesPromise, chatPromise) {
|
||||
const dialog = $("#reading-dialog");
|
||||
const form = $("#reading-form");
|
||||
const selector = form.elements.kind;
|
||||
let resources;
|
||||
try {
|
||||
resources = await resourcesPromise;
|
||||
} catch (error) {
|
||||
note($("#page-note"), error.message, "err");
|
||||
note($("#history-note"), error.message, "err");
|
||||
return;
|
||||
}
|
||||
for (const resource of resources) {
|
||||
const option = cell("option", resource.title);
|
||||
option.value = resource.id;
|
||||
selector.append(option);
|
||||
}
|
||||
|
||||
function renderFields() {
|
||||
const fields = $("#metric-fields");
|
||||
fields.replaceChildren();
|
||||
const resource = resources.find((item) => item.id === selector.value);
|
||||
if (!resource) return;
|
||||
for (const metric of resource.metrics) {
|
||||
const label = document.createElement("label");
|
||||
const input = document.createElement("input");
|
||||
input.type = "number";
|
||||
input.name = metric.key;
|
||||
input.step = "any";
|
||||
input.min = metric.min;
|
||||
input.max = metric.max;
|
||||
input.required = true;
|
||||
label.append(cell("span", `${metric.label}, ${metric.unit}`), input);
|
||||
fields.append(label);
|
||||
}
|
||||
}
|
||||
|
||||
let loading = 0;
|
||||
async function loadHistory() {
|
||||
const request = ++loading;
|
||||
const status = $("#history-note");
|
||||
note(status, "Загрузка…");
|
||||
try {
|
||||
const readings = await api("/api/readings");
|
||||
if (request !== loading) return;
|
||||
const cards = $("#history");
|
||||
cards.replaceChildren();
|
||||
for (const reading of readings) {
|
||||
const card = cell("article", "", "reading-card panel");
|
||||
const label = cell("label", "");
|
||||
const parameters = document.createElement("textarea");
|
||||
parameters.value = reading.parameters;
|
||||
parameters.readOnly = true;
|
||||
parameters.rows = 4;
|
||||
parameters.spellcheck = false;
|
||||
label.append(cell("span", "Параметры проверки"), parameters);
|
||||
const button = cell("button", "Проверка", "action reading-check");
|
||||
button.type = "button";
|
||||
button.setAttribute("aria-label", `Проверка показания #${reading.id}`);
|
||||
button.addEventListener("click", async () => {
|
||||
const openCheck = await chatPromise;
|
||||
openCheck();
|
||||
});
|
||||
card.append(cell("h2", `ID показания: ${reading.id}`), label, button);
|
||||
cards.append(card);
|
||||
}
|
||||
status.hidden = readings.length > 0;
|
||||
if (!readings.length) note(status, "Показаний пока нет.");
|
||||
} catch (error) {
|
||||
if (request === loading) note(status, error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
$("#verification-close").addEventListener("click", () => $("#verification-dialog").close());
|
||||
$("#verification-dialog").addEventListener("close", () => {
|
||||
$("#verification-secret").value = "";
|
||||
$("#verification-reading").textContent = "";
|
||||
$("#verification-receipt").textContent = "";
|
||||
$("#calculation-secret").value = "";
|
||||
});
|
||||
selector.addEventListener("change", renderFields);
|
||||
$("#reading-open").addEventListener("click", () => {
|
||||
$("#reading-note").hidden = true;
|
||||
dialog.showModal();
|
||||
});
|
||||
$("#reading-close").addEventListener("click", () => dialog.close());
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const button = event.submitter;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const data = new FormData(form);
|
||||
const resource = resources.find((item) => item.id === data.get("kind"));
|
||||
const metrics = Object.fromEntries(resource.metrics.map((metric) => [metric.key, data.get(metric.key)]));
|
||||
const result = await post("/api/readings", { serial: data.get("serial").trim(), kind: resource.id, metrics });
|
||||
form.reset();
|
||||
renderFields();
|
||||
dialog.close();
|
||||
navigateTo("history");
|
||||
$("#verification-reading").textContent = result.id;
|
||||
$("#verification-secret").value = result.verification_id;
|
||||
$("#verification-receipt").textContent = result.receipt_id;
|
||||
$("#calculation-secret").value = result.calculation_id;
|
||||
$("#verification-dialog").showModal();
|
||||
} catch (error) {
|
||||
note($("#reading-note"), error.message, "err");
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
$("#reading-open").disabled = false;
|
||||
onRoute("history", loadHistory);
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { api, post } from "../api/client.js";
|
||||
import { $, cell, note } from "../shared/dom.js";
|
||||
import { onRoute } from "../shared/router.js";
|
||||
|
||||
export async function initReceipts(resourcesPromise) {
|
||||
const dialog = $("#receipt-dialog");
|
||||
const form = $("#receipt-form");
|
||||
const details = $("#receipt-details");
|
||||
const amount = new Intl.NumberFormat("ru-RU", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
let selected;
|
||||
let opening = 0;
|
||||
let resources;
|
||||
let loading = 0;
|
||||
try {
|
||||
resources = await resourcesPromise;
|
||||
} catch (error) {
|
||||
note($("#receipts-note"), error.message, "err");
|
||||
return;
|
||||
}
|
||||
|
||||
async function loadReceipts() {
|
||||
const request = ++loading;
|
||||
note($("#receipts-note"), "Загрузка…");
|
||||
try {
|
||||
const receipts = await api("/api/receipts");
|
||||
if (request !== loading) return;
|
||||
const cards = $("#receipts");
|
||||
cards.replaceChildren();
|
||||
for (const receipt of receipts) {
|
||||
const card = cell("article", "", "reading-card panel");
|
||||
const time = cell("time", new Date(receipt.created_at).toLocaleString("ru-RU"));
|
||||
time.dateTime = receipt.created_at;
|
||||
const button = cell("button", "Открыть", "action");
|
||||
button.type = "button";
|
||||
button.setAttribute("aria-label", `Открыть квитанцию #${receipt.id}`);
|
||||
button.addEventListener("click", () => {
|
||||
opening++;
|
||||
selected = receipt.id;
|
||||
form.querySelector("button[type=submit]").disabled = false;
|
||||
form.reset();
|
||||
form.hidden = false;
|
||||
$("#receipt-note").hidden = true;
|
||||
$("#receipt-content").hidden = true;
|
||||
details.replaceChildren();
|
||||
$("#receipt-parameters").value = "";
|
||||
$("#receipt-dialog-title").textContent = `Квитанция #${receipt.id}`;
|
||||
dialog.showModal();
|
||||
});
|
||||
card.append(cell("h2", `ID квитанции: ${receipt.id}`), time, button);
|
||||
cards.append(card);
|
||||
}
|
||||
$("#receipts-note").hidden = receipts.length > 0;
|
||||
if (!receipts.length) note($("#receipts-note"), "Квитанций пока нет.");
|
||||
} catch (error) {
|
||||
if (request === loading) note($("#receipts-note"), error.message, "err");
|
||||
}
|
||||
}
|
||||
|
||||
$("#receipt-close").addEventListener("click", () => dialog.close());
|
||||
dialog.addEventListener("close", () => {
|
||||
opening++;
|
||||
form.reset();
|
||||
details.replaceChildren();
|
||||
$("#receipt-parameters").value = "";
|
||||
$("#receipt-content").hidden = true;
|
||||
});
|
||||
form.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const request = ++opening;
|
||||
const button = event.submitter;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const receipt = await post(`/api/receipts/${selected}/open`, { calculation_id: form.elements.calculation_id.value.trim() });
|
||||
if (request !== opening) return;
|
||||
const reading = receipt.reading;
|
||||
const calculation = receipt.calculation;
|
||||
const resource = resources.find((item) => item.id === reading.kind);
|
||||
const rows = [
|
||||
["ID квитанции", receipt.id], ["ID показания", receipt.reading_id],
|
||||
["Дата квитанции", new Date(receipt.created_at).toLocaleString("ru-RU")],
|
||||
["Дата показания", new Date(reading.created_at).toLocaleString("ru-RU")],
|
||||
["Серийный ID", reading.serial], ["Вид ресурса", resource.title],
|
||||
...resource.metrics.map((metric) => [metric.label, `${reading.metrics[metric.key]} ${metric.unit}`]),
|
||||
["Количество", `${calculation.quantity} ${calculation.unit}`],
|
||||
["Тариф", `${amount.format(calculation.unit_price)} €$ / ${calculation.unit}`],
|
||||
["Расчёт", `${calculation.quantity} × ${calculation.unit_price}`],
|
||||
["К оплате", `${amount.format(calculation.amount)} €$`],
|
||||
];
|
||||
details.replaceChildren();
|
||||
for (const [label, value] of rows) {
|
||||
details.append(cell("dt", label), cell("dd", value, label === "К оплате" ? "receipt-total" : ""));
|
||||
}
|
||||
$("#receipt-parameters").value = reading.parameters;
|
||||
form.reset();
|
||||
form.hidden = true;
|
||||
$("#receipt-content").hidden = false;
|
||||
} catch (error) {
|
||||
if (request === opening) note($("#receipt-note"), error.message, "err");
|
||||
} finally {
|
||||
if (request === opening) button.disabled = false;
|
||||
}
|
||||
});
|
||||
onRoute("receipts", loadReceipts);
|
||||
}
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
import { api } from "./api/client.js";
|
||||
import { initReadings } from "./features/readings.js";
|
||||
import { initReceipts } from "./features/receipts.js";
|
||||
import { initChat } from "./features/chat.js";
|
||||
import { initFinance } from "./features/finance.js";
|
||||
import { initRouter } from "./shared/router.js";
|
||||
|
||||
initRouter();
|
||||
const resources = api("/api/resources");
|
||||
const chat = initChat(resources);
|
||||
initReadings(resources, chat);
|
||||
initReceipts(resources);
|
||||
initFinance();
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
export const $ = (sel) => document.querySelector(sel);
|
||||
|
||||
export function cell(tag, text, cls) {
|
||||
const element = document.createElement(tag);
|
||||
element.textContent = text;
|
||||
if (cls) element.className = cls;
|
||||
return element;
|
||||
}
|
||||
|
||||
export function note(element, text, kind = "ok") {
|
||||
element.textContent = text;
|
||||
element.className = `note ${kind}`;
|
||||
element.hidden = false;
|
||||
}
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
const routes = {
|
||||
submit: "Передать показания",
|
||||
history: "Показания",
|
||||
receipts: "Квитанции",
|
||||
finance: "Финансы",
|
||||
};
|
||||
|
||||
function currentRoute() {
|
||||
const route = window.location.hash.replace(/^#\//, "");
|
||||
return routes[route] ? route : "submit";
|
||||
}
|
||||
|
||||
function renderRoute() {
|
||||
const route = currentRoute();
|
||||
for (const page of document.querySelectorAll("[data-page]")) {
|
||||
page.hidden = page.dataset.page !== route;
|
||||
}
|
||||
for (const link of document.querySelectorAll("[data-route]")) {
|
||||
if (link.dataset.route === route) link.setAttribute("aria-current", "page");
|
||||
else link.removeAttribute("aria-current");
|
||||
}
|
||||
document.title = routes[route] + " — Dark Tariff";
|
||||
}
|
||||
|
||||
export function onRoute(route, callback) {
|
||||
function load() {
|
||||
if (window.location.hash === "#/" + route) callback();
|
||||
}
|
||||
window.addEventListener("hashchange", load);
|
||||
load();
|
||||
}
|
||||
|
||||
export function navigateTo(route) {
|
||||
if (!routes[route]) return;
|
||||
if (currentRoute() === route) renderRoute();
|
||||
else window.location.hash = "#/" + route;
|
||||
}
|
||||
|
||||
export function initRouter() {
|
||||
if (!window.location.hash || !routes[window.location.hash.replace(/^#\//, "")]) {
|
||||
window.history.replaceState(null, "", "#/submit");
|
||||
}
|
||||
window.addEventListener("hashchange", renderRoute);
|
||||
renderRoute();
|
||||
}
|
||||
Executable
+207
@@ -0,0 +1,207 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #101015;
|
||||
--panel: #18181f;
|
||||
--field: #111117;
|
||||
--raised: #22222c;
|
||||
--line: #373744;
|
||||
--ink: #f3f2f5;
|
||||
--dim: #aaa8b6;
|
||||
--acid: #efff43;
|
||||
--cyan: #70ede1;
|
||||
--pink: #ff5090;
|
||||
--error: #ff9dbd;
|
||||
--sans: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
--mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
body { min-width: 1168px; min-height: 100vh; margin: 0; overflow-x: clip; isolation: isolate; background: var(--bg); color: var(--ink); font: 16px/1.5 var(--sans); }
|
||||
body::before, body::after { content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none; }
|
||||
body::before {
|
||||
background: repeating-linear-gradient(0deg, transparent 0 3px, #70ede104 3px 4px),
|
||||
linear-gradient(#70ede109 1px, transparent 1px), linear-gradient(90deg, #70ede109 1px, transparent 1px);
|
||||
background-size: auto, 80px 80px, 80px 80px;
|
||||
mask-image: linear-gradient(#0009, #0002);
|
||||
}
|
||||
body::after {
|
||||
inset: -12%;
|
||||
background: radial-gradient(ellipse at 80% 25%, #70ede11c, transparent 48%), radial-gradient(ellipse at 10% 85%, #efff4310, transparent 42%);
|
||||
animation: ambient-drift 20s ease-in-out infinite alternate;
|
||||
}
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { cursor: pointer; }
|
||||
button:disabled { opacity: .55; cursor: default; }
|
||||
:focus-visible { outline: 2px solid var(--cyan); outline-offset: 3px; }
|
||||
.shell { width: 1120px; margin-inline: auto; }
|
||||
.topbar { border-bottom: 1px solid var(--line); background: #0c0c11e8; box-shadow: 0 1px 0 #70ede10b; }
|
||||
.topbar-inner { min-height: 80px; display: flex; align-items: center; justify-content: space-between; gap: 24px; }
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
color: var(--ink);
|
||||
font-size: 24px;
|
||||
font-weight: 850;
|
||||
letter-spacing: -.05em;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
flex: 0 0 auto;
|
||||
filter: drop-shadow(0 0 7px #efff4366);
|
||||
}
|
||||
.meter-shell { fill: #17190c; stroke: var(--acid); stroke-width: 2; }
|
||||
.meter-screen { fill: #70ede122; stroke: var(--cyan); stroke-width: 1.5; }
|
||||
.meter-readout, .meter-dial { fill: none; stroke: var(--acid); stroke-linecap: square; stroke-width: 2; }
|
||||
.meter-core { fill: var(--pink); }
|
||||
|
||||
.main-nav { display: flex; gap: 24px; }
|
||||
.main-nav a { position: relative; padding-block: 8px; color: var(--dim); text-decoration: none; font-size: 13px; font-weight: 750; letter-spacing: .025em; text-transform: uppercase; transition: color .18s ease; }
|
||||
.main-nav a::after { content: ""; position: absolute; inset: auto 0 0; height: 2px; background: var(--acid); box-shadow: 0 0 12px #efff4340; transform: scaleX(0); transform-origin: left; transition: transform .2s ease; }
|
||||
.main-nav a:hover::after, .main-nav a[aria-current="page"]::after { transform: scaleX(1); }
|
||||
.main-nav a:hover, .main-nav a[aria-current="page"] { color: var(--acid); }
|
||||
.page { position: relative; padding: 60px 0 110px; }
|
||||
.page:not([hidden]) { animation: reveal .32s ease-out backwards; }
|
||||
.page::before { content: ""; position: absolute; top: 38px; right: 0; width: 88px; height: 4px; background: repeating-linear-gradient(135deg, var(--acid) 0 5px, transparent 5px 10px); opacity: .65; }
|
||||
h1 { margin: 14px 0 20px; font-size: 68px; font-weight: 900; letter-spacing: -.055em; line-height: 1.02; text-transform: uppercase; }
|
||||
#submit-page-title { max-width: 940px; margin-top: 24px; font-size: 96px; line-height: .98; }
|
||||
[data-page="submit"] { padding-top: clamp(60px, 9vh, 108px); }
|
||||
.eyebrow { display: flex; align-items: center; gap: 12px; margin: 0; color: var(--cyan); font: 700 12px/1.5 var(--mono); letter-spacing: .16em; text-transform: uppercase; }
|
||||
.eyebrow::before { content: ""; width: 8px; height: 8px; background: var(--acid); box-shadow: 0 0 14px #efff4340; }
|
||||
.intro { max-width: 620px; margin-bottom: 28px; color: var(--dim); }
|
||||
.primary, .action { min-height: 44px; padding: 11px 18px; border: 1px solid var(--line); font-weight: 750; clip-path: polygon(0 0, calc(100% - 8px) 0, 100% 8px, 100% 100%, 8px 100%, 0 calc(100% - 8px)); transition: transform .18s ease, background .18s ease, border-color .18s ease, color .18s ease; }
|
||||
.primary { border-color: var(--acid); background: var(--acid); color: var(--bg); }
|
||||
.primary:hover:not(:disabled) { background: #fbff9e; transform: translate(2px, -2px); }
|
||||
.primary:active:not(:disabled), .action:active:not(:disabled) { transform: translateY(1px); }
|
||||
.primary:focus-visible { box-shadow: inset 0 0 0 2px var(--bg); }
|
||||
.action:focus-visible { box-shadow: inset 0 0 0 2px var(--cyan); }
|
||||
.action { background: var(--field); color: var(--ink); }
|
||||
.action:hover:not(:disabled) { border-color: var(--cyan); background: #70ede10a; color: var(--cyan); transform: translateY(-2px); }
|
||||
.panel, dialog { background: linear-gradient(135deg, #70ede109, transparent 60%), var(--panel); border: 1px solid var(--line); border-radius: 0; clip-path: polygon(0 0, calc(100% - 16px) 0, 100% 16px, 100% 100%, 16px 100%, 0 calc(100% - 16px)); }
|
||||
.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 16px 24px; border-bottom: 1px solid var(--line); }
|
||||
.panel-head h2 { margin: 0; font: 750 18px/1.4 var(--mono); letter-spacing: -.025em; }
|
||||
dialog[open], .help-chat:not([hidden]) { animation: reveal .2s ease-out backwards; }
|
||||
dialog { width: 640px; max-height: calc(100vh - 32px); padding: 0; overflow: auto; color: var(--ink); }
|
||||
dialog::backdrop { background: #08080dcc; backdrop-filter: blur(6px); animation: backdrop-in .2s ease-out; }
|
||||
form { display: grid; gap: 20px; padding: 24px; }
|
||||
label { display: grid; gap: 7px; color: var(--dim); font-size: 14px; }
|
||||
input, select, textarea { width: 100%; min-width: 0; min-height: 44px; padding: 10px 12px; border: 1px solid var(--line); background: var(--field); color: var(--ink); }
|
||||
input:not([type="checkbox"]), select, textarea { transition: border-color .2s ease, box-shadow .2s ease; }
|
||||
input:not([type="checkbox"]):focus, select:focus, textarea:focus { border-color: var(--cyan); box-shadow: inset 3px 0 var(--cyan); }
|
||||
input, textarea, time, .receipt-details dd, #verification-reading, #verification-receipt { font-family: var(--mono); font-variant-numeric: tabular-nums; }
|
||||
.metric-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }
|
||||
.field-help { margin: 0; color: var(--dim); font-size: 13px; }
|
||||
.note { margin-top: 12px; padding: 10px 14px; border-left: 2px solid var(--cyan); background: var(--field); color: var(--cyan); overflow-wrap: anywhere; }
|
||||
.note.err { color: var(--error); border-color: var(--error); }
|
||||
.history-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
|
||||
.reading-card { position: relative; min-width: 0; padding: 24px; animation: reveal .34s ease-out backwards; transition: transform .2s ease, border-color .2s ease; }
|
||||
.reading-card::before { content: ""; position: absolute; top: 0; left: 0; width: 48px; height: 3px; background: var(--acid); }
|
||||
.reading-card::after { content: ""; position: absolute; right: 10px; bottom: 10px; width: 8px; height: 8px; border-right: 1px solid var(--cyan); border-bottom: 1px solid var(--cyan); opacity: .5; }
|
||||
.reading-card:hover { transform: translateY(-4px); border-color: var(--cyan); }
|
||||
.reading-card:nth-child(2) { animation-delay: 40ms; }
|
||||
.reading-card:nth-child(3) { animation-delay: 80ms; }
|
||||
.reading-card:nth-child(n+4) { animation-delay: 120ms; }
|
||||
.reading-card h2 { margin: 8px 0; overflow-wrap: anywhere; font: 750 20px/1.4 var(--mono); }
|
||||
.reading-check { min-height: 32px; margin-top: 16px; padding: 6px 12px; font-size: 12px; }
|
||||
|
||||
|
||||
.help-launcher {
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 10px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
}
|
||||
.help-hint {
|
||||
position: relative;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0;
|
||||
background: var(--raised);
|
||||
}
|
||||
.help-hint::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: -5px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-top: 1px solid var(--line);
|
||||
border-right: 1px solid var(--line);
|
||||
background: var(--raised);
|
||||
transform: translateY(-50%) rotate(45deg);
|
||||
}
|
||||
.help-chat {
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 100px;
|
||||
z-index: 20;
|
||||
width: 360px;
|
||||
max-height: calc(100vh - 124px);
|
||||
overflow: auto;
|
||||
}
|
||||
.help-chat .panel-head { min-height: 0; gap: 12px; padding: 16px; }
|
||||
.help-chat .panel-head h2 { font-size: 18px; }
|
||||
.help-messages p {
|
||||
margin: 0 0 10px;
|
||||
padding: 12px 14px;
|
||||
border-left: 2px solid var(--line);
|
||||
border-radius: 0;
|
||||
background: var(--raised);
|
||||
overflow-wrap: anywhere;
|
||||
animation: reveal .2s ease-out backwards;
|
||||
}
|
||||
|
||||
textarea { resize: vertical; font-size: 13px; line-height: 1.55; }
|
||||
.verification-body { display: grid; gap: 16px; padding: 24px; }
|
||||
.verification-body p { margin: 0; }
|
||||
.reading-card label { margin-top: 16px; }
|
||||
.help-controls { padding: 0 16px 16px; }
|
||||
.help-controls .action { width: 100%; text-align: left; font-size: 13px; }
|
||||
.help-controls form { gap: 12px; padding: 0; }
|
||||
.help-messages { min-height: 0; max-height: 240px; overflow-y: auto; padding: 16px; }
|
||||
.help-messages .help-user { color: var(--cyan); }
|
||||
|
||||
.reading-card time { display: block; margin: 8px 0 16px; color: var(--dim); font-size: 13px; }
|
||||
.receipt-details { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; margin: 0; }
|
||||
.receipt-details dt { color: var(--dim); }
|
||||
.receipt-details dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.receipt-details .receipt-total { color: var(--acid); font-weight: 750; }
|
||||
|
||||
.finance-controls { display: flex; flex-wrap: wrap; align-items: end; gap: 16px; margin-block: 24px; }
|
||||
.finance-controls label { display: grid; gap: 8px; }
|
||||
.finance-options { margin: 0 0 24px; padding: 16px; border: 1px solid var(--line); }
|
||||
#finance-fields { display: flex; flex-wrap: wrap; gap: 16px; }
|
||||
#finance-fields label { display: flex; align-items: center; gap: 8px; }
|
||||
#finance-fields input { width: auto; accent-color: var(--acid); }
|
||||
.finance-scroll { overflow-x: auto; }
|
||||
#finance-table { width: 100%; border-collapse: collapse; }
|
||||
#finance-table th, #finance-table td { padding: 12px; text-align: left; white-space: nowrap; border-bottom: 1px solid var(--line); }
|
||||
#finance-table th { color: var(--cyan); }
|
||||
#finance-table tbody tr { transition: background .18s ease; }
|
||||
#finance-table tbody tr:hover { background: #70ede107; }
|
||||
|
||||
@keyframes ambient-drift {
|
||||
from { transform: translate(-2%, -1%); }
|
||||
to { transform: translate(3%, 3%); }
|
||||
}
|
||||
|
||||
@keyframes reveal {
|
||||
from { opacity: 0; transform: translateY(12px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes backdrop-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
Reference in new issue
Block a user