192 lines
9.0 KiB
Python
192 lines
9.0 KiB
Python
"""
|
|
Хранилище истории расчётов.
|
|
|
|
Поддержка PostgreSQL (primary) и SQLite (fallback для локальной разработки).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
|
|
class CalculationStore:
|
|
"""
|
|
Сохраняет успешные расчёты без привязки домена к конкретной БД.
|
|
|
|
Поддерживает два режима:
|
|
- PostgreSQL через psycopg (production)
|
|
- SQLite через sqlite3 (локальная разработка)
|
|
"""
|
|
|
|
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
|
|
"""
|
|
Инициализация хранилища с автоматическим созданием схемы.
|
|
|
|
Args:
|
|
database_url: URL PostgreSQL-БД (например postgresql://...)
|
|
sqlite_path: Путь к локальному SQLite-файлу
|
|
"""
|
|
self.database_url = database_url or ""
|
|
self.sqlite_path = Path(sqlite_path) if sqlite_path else None
|
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
|
import psycopg
|
|
self._psycopg = psycopg
|
|
self._ensure_postgres_schema()
|
|
else:
|
|
self.sqlite_path = self.sqlite_path or Path("data/belki.sqlite3")
|
|
self.sqlite_path.parent.mkdir(parents=True, exist_ok=True)
|
|
self._ensure_sqlite_schema()
|
|
|
|
@classmethod
|
|
def from_environment(cls) -> "CalculationStore":
|
|
return cls(
|
|
database_url=os.getenv("BELKI_DATABASE_URL"),
|
|
sqlite_path=os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"),
|
|
)
|
|
|
|
def _ensure_sqlite_schema(self) -> None:
|
|
"""Создаёт таблицу calculations в SQLite, если её нет."""
|
|
with sqlite3.connect(self.sqlite_path) as connection:
|
|
connection.execute(
|
|
"""CREATE TABLE IF NOT EXISTS calculations (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
actor_id INTEGER,
|
|
source TEXT NOT NULL,
|
|
mode TEXT NOT NULL,
|
|
input_json TEXT NOT NULL,
|
|
result_json TEXT,
|
|
message TEXT NOT NULL,
|
|
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
)"""
|
|
)
|
|
|
|
def _ensure_postgres_schema(self) -> None:
|
|
"""Создаёт таблицу belki_calculations в PostgreSQL, если её нет."""
|
|
with self._psycopg.connect(self.database_url) as connection:
|
|
connection.execute(
|
|
"""CREATE TABLE IF NOT EXISTS belki_calculations (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
actor_id BIGINT,
|
|
source TEXT NOT NULL,
|
|
mode TEXT NOT NULL,
|
|
input_json JSONB NOT NULL,
|
|
result_json JSONB,
|
|
message TEXT NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
)"""
|
|
)
|
|
|
|
def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int:
|
|
"""
|
|
Сохраняет результат расчёта в БД.
|
|
|
|
Args:
|
|
actor_id: ID пользователя (None для автоматических расчётов)
|
|
source: Источник ("vk", "web", "hook")
|
|
payload: Исходные данные расчёта
|
|
response: Результат расчёта
|
|
|
|
Returns:
|
|
ID сохранённой записи
|
|
"""
|
|
mode = str(payload.get("mode", response.get("mode", "unknown")))
|
|
message = str(response["message"])
|
|
result = response.get("result")
|
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
|
from psycopg.types.json import Jsonb
|
|
with self._psycopg.connect(self.database_url) as connection:
|
|
row = connection.execute(
|
|
"""INSERT INTO belki_calculations
|
|
(actor_id, source, mode, input_json, result_json, message)
|
|
VALUES (%s, %s, %s, %s, %s, %s) RETURNING id""",
|
|
(actor_id, source, mode, Jsonb(payload), Jsonb(result) if result is not None else None, message),
|
|
).fetchone()
|
|
return int(row[0])
|
|
with sqlite3.connect(self.sqlite_path) as connection:
|
|
cursor = connection.execute(
|
|
"""INSERT INTO calculations
|
|
(actor_id, source, mode, input_json, result_json, message)
|
|
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
(actor_id, source, mode, json.dumps(payload, ensure_ascii=False),
|
|
json.dumps(result, ensure_ascii=False) if result is not None else None, message),
|
|
)
|
|
return int(cursor.lastrowid)
|
|
|
|
def list_calculations(self, *, sort_by: str = "escort_id", descending: bool = True,
|
|
limit: int = 100) -> list[dict[str, Any]]:
|
|
"""
|
|
Возвращает записи истории для админ-панели.
|
|
|
|
Безопасная сортировка на уровне приложения (не SQL-инъекция):
|
|
- escort_id, escort_name — по сопровождающему
|
|
- kitten_id, kitten_name — по котянку
|
|
|
|
Ограничения:
|
|
- fetch_limit: 5000 записей для выборки из БД
|
|
- limit: 1-500 записей для возврата
|
|
"""
|
|
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 {"escort_id", "escort_name", "kitten_id", "kitten_name"}:
|
|
sort_by = "escort_id"
|
|
def sort_value(item: dict[str, Any]) -> tuple[bool, int, int | str]:
|
|
data = item["input"]
|
|
if sort_by == "escort_id":
|
|
value = data.get("escort_id", data.get("character_id"))
|
|
elif sort_by == "escort_name":
|
|
value = data.get("escort_name", data.get("character_name"))
|
|
else:
|
|
value = data.get(sort_by)
|
|
if value is None:
|
|
return True, 0, ""
|
|
if sort_by.endswith("_id"):
|
|
try:
|
|
return False, 0, int(value)
|
|
except (TypeError, ValueError):
|
|
# Existing records can predate API type normalization. Keep
|
|
# malformed legacy values visible rather than failing the
|
|
# entire privileged history view.
|
|
return False, 1, str(value)
|
|
return False, 0, str(value).casefold()
|
|
records.sort(key=sort_value, reverse=descending)
|
|
return records[:limit]
|
|
|
|
def delete_calculation(self, calculation_id: int) -> bool:
|
|
"""Delete one history row and report whether it existed."""
|
|
if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0:
|
|
raise ValueError("ID записи должен быть положительным целым числом")
|
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
|
with self._psycopg.connect(self.database_url) as connection:
|
|
row = connection.execute(
|
|
"DELETE FROM belki_calculations WHERE id = %s RETURNING id", (calculation_id,)
|
|
).fetchone()
|
|
return row is not None
|
|
with sqlite3.connect(self.sqlite_path) as connection:
|
|
cursor = connection.execute("DELETE FROM calculations WHERE id = ?", (calculation_id,))
|
|
return cursor.rowcount > 0
|