diff --git a/.env.example b/.env.example index c75611d..f0f96fe 100644 --- a/.env.example +++ b/.env.example @@ -7,3 +7,5 @@ VK_API_VERSION=5.199 BELKI_DATABASE_URL=postgresql://belki:change-me@postgres:5432/belki # SQLite fallback/runtime identity database when BELKI_DATABASE_URL is empty. BELKI_IDENTITIES_DB=data/belki.sqlite3 +# Required to access /admin and /api/admin/calculations. +BELKI_ADMIN_PASSWORD=change-me diff --git a/MEMORY.md b/MEMORY.md index 28e1d8d..01936c2 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -17,4 +17,5 @@ - VK onboarding asks first-time authors for `Имя [ID]`, stores the profile by `from_id` in SQLite, greets by name on later conversations, and accepts `сам`/`несам` as independence shortcuts. - VK `/help` is a neutral FAQ: it explains step-by-step entry, complete commands, separator-free one-line input, confirmation, screenshots, and `/отмена` without audience-specific wording. - Confirmed calculations are persisted through `BELKI_DATABASE_URL` by `app/belki/history.py`; PostgreSQL is the intended production store and SQLite is only a local fallback. +- The admin history is served at `/admin`; `/api/admin/calculations` requires `BELKI_ADMIN_PASSWORD` via `X-Admin-Password` and supports sorting by kitten ID/name. The password is configured out-of-band and is not stored in browser localStorage. - The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas. diff --git a/README.md b/README.md index 01daa58..a801680 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,8 @@ python3 -m app.belki.vk_bot Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL. +Админская история доступна по адресу `/admin`. Она защищена заголовком пароля и показывает сохранённые расчёты с сортировкой по ID или имени котёнка. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено. + ## Структура - `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей; @@ -45,6 +47,7 @@ python3 -m app.belki.vk_bot - `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды; - `app/main.py` — веб-сервис и раздача сайта/userscript-файлов; - `web/calculator.html` — форма калькулятора; +- `web/admin.html` — парольная история расчётов для администраторской проверки; - `tests/` — unit-тесты. Спецификация и план находятся в `docs/staging/`. diff --git a/app/belki/history.py b/app/belki/history.py index 9f8b958..7a678d3 100644 --- a/app/belki/history.py +++ b/app/belki/history.py @@ -15,6 +15,7 @@ class CalculationStore: def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None: self.database_url = database_url or "" self.sqlite_path = Path(sqlite_path) if sqlite_path else None + fetch_limit = 5000 if self.database_url.startswith(("postgres://", "postgresql://")): import psycopg self._psycopg = psycopg @@ -85,3 +86,34 @@ class CalculationStore: ) return int(cursor.lastrowid) + def list_calculations(self, *, sort_by: str = "kitten_id", descending: bool = True, + limit: int = 100) -> list[dict[str, Any]]: + """Return admin rows with safe, application-level sorting by kitten identity.""" + limit = max(1, min(int(limit), 500)) + fetch_limit = 5000 + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + rows = connection.execute( + """SELECT id, actor_id, source, mode, input_json, result_json, message, created_at + FROM belki_calculations ORDER BY created_at DESC LIMIT %s""", (fetch_limit,) + ).fetchall() + else: + with sqlite3.connect(self.sqlite_path) as connection: + rows = connection.execute( + """SELECT id, actor_id, source, mode, input_json, result_json, message, created_at + FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,) + ).fetchall() + records = [] + for row in rows: + input_data = row[4] if isinstance(row[4], dict) else json.loads(row[4]) + result_data = row[5] if isinstance(row[5], dict) or row[5] is None else json.loads(row[5]) + records.append({ + "id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3], + "input": input_data, "result": result_data, "message": row[6], + "created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7], + }) + if sort_by not in {"kitten_id", "kitten_name"}: + sort_by = "kitten_id" + records.sort(key=lambda item: (item["input"].get(sort_by) is None, item["input"].get(sort_by, "")), + reverse=descending) + return records[:limit] diff --git a/app/main.py b/app/main.py index 47990f8..b9b7f41 100644 --- a/app/main.py +++ b/app/main.py @@ -5,13 +5,22 @@ import mimetypes import os from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from urllib.parse import unquote, urlparse +from urllib.parse import parse_qs, unquote, urlparse from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload +from .belki.history import CalculationStore ROOT = Path(__file__).resolve().parents[1] WEB_ROOT = ROOT / "web" +_HISTORY_STORE: CalculationStore | None = None + + +def history_store() -> CalculationStore: + global _HISTORY_STORE + if _HISTORY_STORE is None: + _HISTORY_STORE = CalculationStore.from_environment() + return _HISTORY_STORE class Handler(BaseHTTPRequestHandler): @@ -26,13 +35,30 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write(encoded) def do_GET(self) -> None: # noqa: N802 - if self.path in ("/health", "/api/health"): + path = urlparse(self.path).path + if path in ("/health", "/api/health"): self._json(200, {"status": "ok"}) return - if self.path in ("/", "/calculator.html"): + if path in ("/", "/calculator.html"): self._file(WEB_ROOT / "calculator.html") return - requested = unquote(urlparse(self.path).path).lstrip("/") + if path == "/admin": + self._file(WEB_ROOT / "admin.html") + return + if path == "/api/admin/calculations": + expected = os.getenv("BELKI_ADMIN_PASSWORD", "") + if not expected: + self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"}) + return + if self.headers.get("X-Admin-Password", "") != expected: + self._json(401, {"error": "Неверный пароль"}) + return + query = parse_qs(urlparse(self.path).query) + sort_by = query.get("sort", ["kitten_id"])[0] + descending = query.get("direction", ["desc"])[0] != "asc" + self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending)}) + return + requested = unquote(path).lstrip("/") candidate = (WEB_ROOT / requested).resolve() if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents: self._file(candidate) diff --git a/deploy/k8s/app.yaml b/deploy/k8s/app.yaml index c2cb8d7..22e4763 100644 --- a/deploy/k8s/app.yaml +++ b/deploy/k8s/app.yaml @@ -33,6 +33,11 @@ spec: secretKeyRef: name: belki-vk key: BELKI_DATABASE_URL + - name: BELKI_ADMIN_PASSWORD + valueFrom: + secretKeyRef: + name: belki-vk + key: BELKI_ADMIN_PASSWORD readinessProbe: httpGet: path: /health diff --git a/deploy/k8s/secret.example.yaml b/deploy/k8s/secret.example.yaml index cf08cea..de84559 100644 --- a/deploy/k8s/secret.example.yaml +++ b/deploy/k8s/secret.example.yaml @@ -9,3 +9,4 @@ stringData: VK_GROUP_ID: replace-out-of-band VK_API_VERSION: "5.199" BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki + BELKI_ADMIN_PASSWORD: replace-out-of-band diff --git a/structure_and_data.md b/structure_and_data.md index 52364cf..a5be622 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -25,6 +25,7 @@ - Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git. - The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts. - Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp. +- `/admin` and `/api/admin/calculations` expose the calculation history for review. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports sorting by kitten ID or name and does not persist the password in browser storage. - VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported. - No k3s deployment or cluster state change has been made. The SSH tunnel used for read-only service inventory was stopped. - Remote runner host: `root@10.3.1.236` (`docker-03.homelab.local`), GitLab Runner `stage-zone-runner`, Docker executor, privileged, with `docker:29.6.1-dind` as the service image. diff --git a/tests/test_history.py b/tests/test_history.py new file mode 100644 index 0000000..350407f --- /dev/null +++ b/tests/test_history.py @@ -0,0 +1,29 @@ +import tempfile +import unittest +from pathlib import Path + +from app.belki.history import CalculationStore + + +class CalculationHistoryTests(unittest.TestCase): + def test_admin_rows_sort_by_kitten_id_and_name(self) -> None: + with tempfile.TemporaryDirectory() as directory: + store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3") + for kitten_id, kitten_name in ((30, "Тучка"), (10, "Янтарь"), (20, "Белка")): + store.save( + actor_id=99, + source="vk", + payload={"mode": "coaching", "kitten_id": kitten_id, "kitten_name": kitten_name}, + response={"mode": "coaching", "message": f"расчёт {kitten_id}", "result": {"points": 1}}, + ) + + by_id = store.list_calculations(sort_by="kitten_id", descending=False) + self.assertEqual([row["input"]["kitten_id"] for row in by_id], [10, 20, 30]) + by_name = store.list_calculations(sort_by="kitten_name", descending=False) + self.assertEqual([row["input"]["kitten_name"] for row in by_name], ["Белка", "Тучка", "Янтарь"]) + self.assertEqual(by_name[0]["actor_id"], 99) + self.assertEqual(by_name[0]["result"]["points"], 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/admin.html b/web/admin.html new file mode 100644 index 0000000..2225049 --- /dev/null +++ b/web/admin.html @@ -0,0 +1,65 @@ + + + + + + Беличья нора — админка + + + +
+

Беличья нора — админская

+

История подтверждённых расчётов из VK-бота и веб-калькулятора.

+
+ + + + +
+

+
ID записиАвторРежимКотёнокДатаСообщение
+
+ + +