""" Хранилище истории расчётов. Поддержка PostgreSQL (primary) и SQLite (fallback для локальной разработки). """ from __future__ import annotations import json import os import re import sqlite3 from dataclasses import asdict from pathlib import Path from typing import Any from .domain import InspectionReport, calculate_inspection def _restore_inspection_breakdown(input_data: dict[str, Any], result_data: Any) -> Any: """Backfill score details for inspection rows written before the breakdown existed.""" if input_data.get("mode") != "inspection" or not isinstance(result_data, dict): return result_data if "inspection_points" in result_data and "resource_points" in result_data: return result_data try: resources = tuple( (str(item[0]), int(item[1])) for item in input_data.get("resources", []) if isinstance(item, (list, tuple)) and len(item) == 2 ) report = InspectionReport( character_name=str(input_data.get("character_name", "Персонаж")), character_id=int(input_data.get("character_id", 1)), place=str(input_data.get("place", "дупло")), inspections=int(input_data.get("inspections", 0)), resources=resources, ) return asdict(calculate_inspection(report)) except (TypeError, ValueError): return result_data 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": """Создаёт хранилище, выбрав PostgreSQL или SQLite по окружению.""" 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 )""" ) columns = {row[1] for row in connection.execute("PRAGMA table_info(calculations)")} if "entered" not in columns: connection.execute("ALTER TABLE calculations ADD COLUMN entered INTEGER NOT NULL DEFAULT 0") 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() )""" ) connection.execute("ALTER TABLE belki_calculations ADD COLUMN IF NOT EXISTS entered BOOLEAN NOT NULL DEFAULT FALSE") 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-инъекция): - created_at — по дате создания - 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, entered 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, entered 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]) result_data = _restore_inspection_breakdown(input_data, result_data) message = row[6] if input_data.get("mode") == "inspection" and isinstance(result_data, dict) and "points" in result_data: message = re.sub(r"Баллы осмотра:\s*[-+]?\d+", f"Баллы осмотра: {result_data['points']}", message) records.append({ "id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3], "input": input_data, "result": result_data, "message": message, "created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7], "entered": bool(row[8]), }) if sort_by not in {"created_at", "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 == "created_at": value = item["created_at"] elif 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 set_entered(self, calculation_id: int, entered: bool) -> dict[str, Any] | None: """Set the administrative entered flag and return the updated row.""" 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("UPDATE belki_calculations SET entered=%s WHERE id=%s RETURNING id", (entered, calculation_id)).fetchone() if row is None: return None else: with sqlite3.connect(self.sqlite_path) as connection: cursor = connection.execute("UPDATE calculations SET entered=? WHERE id=?", (int(entered), calculation_id)) if cursor.rowcount == 0: return None return next((item for item in self.list_calculations(limit=500) if item["id"] == calculation_id), None) 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