feat: add sent report history lookup
This commit is contained in:
1 parent
546fa37fce
commit
3ebab303a5
12 files changed
+393
-18
No files matched your search
+90
-14
@@ -177,20 +177,7 @@ class CalculationStore:
|
||||
"""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]),
|
||||
})
|
||||
records = self._records_from_rows(rows)
|
||||
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]:
|
||||
@@ -218,6 +205,95 @@ class CalculationStore:
|
||||
records.sort(key=sort_value, reverse=descending)
|
||||
return records[:limit]
|
||||
|
||||
@staticmethod
|
||||
def _validate_lookup_id(value: int, label: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
raise ValueError(f"{label} должен быть положительным целым числом")
|
||||
return value
|
||||
|
||||
def list_vk_reports(self, actor_id: int, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""Return the latest saved reports submitted by one VK user."""
|
||||
actor_id = self._validate_lookup_id(actor_id, "ID отправителя")
|
||||
limit = max(1, min(int(limit), 100))
|
||||
modes = ("coaching", "training", "inspection")
|
||||
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
|
||||
WHERE actor_id = %s AND source = 'vk' AND mode = ANY(%s)
|
||||
ORDER BY created_at DESC, id DESC LIMIT %s""",
|
||||
(actor_id, list(modes), limit),
|
||||
).fetchall()
|
||||
else:
|
||||
placeholders = ",".join("?" for _ in modes)
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
rows = connection.execute(
|
||||
f"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered
|
||||
FROM calculations
|
||||
WHERE actor_id = ? AND source = 'vk' AND mode IN ({placeholders})
|
||||
ORDER BY created_at DESC, id DESC LIMIT ?""",
|
||||
(actor_id, *modes, limit),
|
||||
).fetchall()
|
||||
return self._records_from_rows(rows)
|
||||
|
||||
def list_character_reports(self, character_id: int, *, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""Return recent reports containing a character in any participant role."""
|
||||
character_id = self._validate_lookup_id(character_id, "ID кота")
|
||||
limit = max(1, min(int(limit), 100))
|
||||
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
|
||||
WHERE mode = ANY(%s) AND (
|
||||
input_json->>'escort_id' = %s OR input_json->>'kitten_id' = %s
|
||||
OR input_json->>'character_id' = %s
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM jsonb_array_elements(
|
||||
CASE WHEN jsonb_typeof(input_json->'extra_kittens') = 'array'
|
||||
THEN input_json->'extra_kittens' ELSE '[]'::jsonb END
|
||||
) AS extra(value) WHERE extra.value->>1 = %s
|
||||
)
|
||||
) ORDER BY created_at DESC, id DESC LIMIT %s""",
|
||||
(["coaching", "training", "inspection"], str(character_id), str(character_id), str(character_id), str(character_id), 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
|
||||
WHERE mode IN ('coaching', 'training', 'inspection') AND (
|
||||
CAST(json_extract(input_json, '$.escort_id') AS TEXT) = ?
|
||||
OR CAST(json_extract(input_json, '$.kitten_id') AS TEXT) = ?
|
||||
OR CAST(json_extract(input_json, '$.character_id') AS TEXT) = ?
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM json_each(input_json, '$.extra_kittens') AS extra
|
||||
WHERE CAST(json_extract(extra.value, '$[1]') AS TEXT) = ?
|
||||
)
|
||||
) ORDER BY created_at DESC, id DESC LIMIT ?""",
|
||||
(str(character_id), str(character_id), str(character_id), str(character_id), limit),
|
||||
).fetchall()
|
||||
return self._records_from_rows(rows)
|
||||
|
||||
@staticmethod
|
||||
def _records_from_rows(rows: list[tuple[Any, ...]]) -> list[dict[str, Any]]:
|
||||
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]),
|
||||
})
|
||||
return records
|
||||
|
||||
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:
|
||||
|
||||
+40
-2
@@ -9,11 +9,12 @@ import re
|
||||
import threading
|
||||
import time
|
||||
import unicodedata
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from difflib import SequenceMatcher
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from .api import ApiError, calculate_payload
|
||||
from .domain import MAX_COACHING_KITTENS
|
||||
@@ -954,7 +955,7 @@ class BelkiBot:
|
||||
pass
|
||||
value = payload.get("command") if isinstance(payload, dict) else payload
|
||||
return {
|
||||
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок",
|
||||
"menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок", "menu:my_reports": "/мои-отчёты",
|
||||
"menu:inspection": "/осмотр", "menu:goal": "/цель", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка", "menu:rename": "/изменить-имя",
|
||||
"points:coaching": "прокачка", "points:training": "тренировка", "points:inspection": "осмотр",
|
||||
"application:feathers": "/перо", "application:kitten": "/бельчонок",
|
||||
@@ -1230,6 +1231,7 @@ class BelkiDialog:
|
||||
[self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")],
|
||||
[self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")],
|
||||
[self._button("Калькулятор баллов", "menu:goal", "secondary")],
|
||||
[self._button("Мои отчёты", "menu:my_reports", "secondary")],
|
||||
[self._button("Подать заявку", "menu:application", "secondary")],
|
||||
[self._button("Изменить имя кота", "menu:rename", "secondary")],
|
||||
[self._button("Помощь", "menu:help", "secondary")],
|
||||
@@ -1728,6 +1730,8 @@ class BelkiDialog:
|
||||
onboarding_response = self._ensure_profile(actor_id, text)
|
||||
if onboarding_response is not None:
|
||||
return onboarding_response
|
||||
if text.casefold() in {"/мои-отчёты", "/мои-отчеты", "мои отчёты", "мои отчеты"}:
|
||||
return self._my_reports(actor_id)
|
||||
if text.lower() in ("/отмена", "отмена", "нет") and actor_id in self._states:
|
||||
self._reset(actor_id)
|
||||
return "Текущий ввод отменён. Для нового отчёта используйте /лу, /зу или /help."
|
||||
@@ -1792,6 +1796,40 @@ class BelkiDialog:
|
||||
except (ApiError, ValueError) as exc:
|
||||
return str(exc)
|
||||
|
||||
def _my_reports(self, actor_id: int) -> str:
|
||||
"""Format the latest confirmed report submissions for one VK user."""
|
||||
if self.calculation_store is None:
|
||||
return "История отчётов сейчас недоступна. Попробуйте позже."
|
||||
try:
|
||||
reports = self.calculation_store.list_vk_reports(actor_id, limit=100)
|
||||
except Exception:
|
||||
logger.exception("Unable to load VK report history for actor %s", actor_id)
|
||||
return "Не удалось загрузить историю отчётов. Попробуйте позже."
|
||||
if not reports:
|
||||
return "Вы ещё не отправляли отчёты через VK-бота."
|
||||
|
||||
labels = {"coaching": "Прокачка", "training": "Тренировка", "inspection": "Осмотр"}
|
||||
lines = ["Ваши отправленные отчёты:"]
|
||||
truncated = False
|
||||
for report in reports:
|
||||
raw_timestamp = str(report.get("created_at", ""))
|
||||
try:
|
||||
parsed_timestamp = datetime.fromisoformat(raw_timestamp.replace("Z", "+00:00"))
|
||||
if parsed_timestamp.tzinfo is None:
|
||||
parsed_timestamp = parsed_timestamp.replace(tzinfo=timezone.utc)
|
||||
timestamp = parsed_timestamp.astimezone(ZoneInfo("Europe/Moscow")).strftime("%d.%m.%Y %H:%M")
|
||||
except ValueError:
|
||||
timestamp = raw_timestamp[:16].replace("T", " ") or "Дата неизвестна"
|
||||
label = labels.get(report.get("mode"), "Отчёт")
|
||||
entry = f"\n{timestamp} · {label} · №{report['id']}\n{report['message']}"
|
||||
if sum(map(len, lines)) + len(entry) > 3500:
|
||||
truncated = True
|
||||
break
|
||||
lines.append(entry)
|
||||
if truncated:
|
||||
lines.append("\nПоказана часть последних отчётов. Остальные можно найти на сайте по ID кота.")
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Запускает VK-бота, настроив API-клиент, хранилища и цикл событий."""
|
||||
|
||||
+37
@@ -389,6 +389,43 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if path in ("/sudoku", "/sudoku/"):
|
||||
self._file(WEB_ROOT / "sudoku.html")
|
||||
return
|
||||
if path == "/api/reports":
|
||||
query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
|
||||
raw_character_id = query.get("character_id", [""])[0].strip()
|
||||
if not re.fullmatch(r"\d{1,20}", raw_character_id) or int(raw_character_id) <= 0:
|
||||
self._json(400, {"error": "Укажите положительный ID кота"})
|
||||
return
|
||||
character_id = int(raw_character_id)
|
||||
if character_id > 9_223_372_036_854_775_807:
|
||||
self._json(400, {"error": "ID кота слишком большой"})
|
||||
return
|
||||
try:
|
||||
records = history_store().list_character_reports(character_id, limit=100)
|
||||
except ValueError as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
return
|
||||
except Exception:
|
||||
self._json(500, {"error": "Не удалось загрузить отчёты"})
|
||||
return
|
||||
items = []
|
||||
for item in records:
|
||||
attachments = []
|
||||
for photo in (item.get("input") or {}).get("attachments", []):
|
||||
if not isinstance(photo, dict):
|
||||
continue
|
||||
candidate = photo.get("mirror_url") or photo.get("url")
|
||||
if not isinstance(candidate, str):
|
||||
continue
|
||||
image_path = urlparse(candidate).path
|
||||
object_name = image_path.removeprefix("/api/images/")
|
||||
if image_path.startswith("/api/images/") and IMAGE_OBJECT_NAME.fullmatch(object_name):
|
||||
attachments.append({"url": image_path})
|
||||
items.append({
|
||||
"id": item["id"], "mode": item["mode"], "message": item["message"],
|
||||
"created_at": item["created_at"], "attachments": attachments,
|
||||
})
|
||||
self._json(200, {"items": items, "limit": 100})
|
||||
return
|
||||
if path == "/api/sudoku/games":
|
||||
try:
|
||||
nickname = parse_qs(urlparse(self.path).query).get("nickname", [""])[0]
|
||||
|
||||
Reference in new issue
Block a user