feat: add sent report history lookup

This commit is contained in:
nyan404 committed 2026-10-18 18:56:23 +03:00
1 parent 546fa37fce
commit 3ebab303a5
12 files changed
+393 -18

No files matched your search

+1
View File
@@ -22,6 +22,7 @@
- For k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab. - For k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab.
- Do not add unnecessary local build artifacts or temporary files to the repository. - Do not add unnecessary local build artifacts or temporary files to the repository.
- Admin report UI changes should cover both the persisted history flag and browser behavior: run the focused history/admin filter tests, Python compilation, `git diff --check`, and a JavaScript syntax check for `web/admin.html`. The report list defaults to the calendar current month; do not silently replace the existing sort order. - Admin report UI changes should cover both the persisted history flag and browser behavior: run the focused history/admin filter tests, Python compilation, `git diff --check`, and a JavaScript syntax check for `web/admin.html`. The report list defaults to the calendar current month; do not silently replace the existing sort order.
- Public report lookup is `GET /api/reports?character_id=<cat ID>`; it searches saved report participant IDs, returns at most 100 newest rows without `actor_id`, and is covered by `tests/test_report_lookup.py`. VK `/мои-отчёты` uses the callback sender ID and the same history store; validate with `python -m unittest tests.test_report_lookup tests.test_history tests.test_vk_bot -q`.
## Notes ## Notes
- VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule. - VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule.
+2
View File
@@ -1,5 +1,7 @@
# MEMORY # MEMORY
- 2026-10-18: sent-report history uses `CalculationStore.list_vk_reports(actor_id)` for VK's `Мои отчёты` menu and `list_character_reports(character_id)` for the public calculator tab/API; the latter searches escort, kitten, extra-kitten, and inspection IDs across sources, returns at most 100 newest rows, and omits VK `actor_id`.
- 2026-10-10: `/admin` report rows default to creation date descending (newest first); `CalculationStore` supports the `created_at` sort key and the UI requests it explicitly. - 2026-10-10: `/admin` report rows default to creation date descending (newest first); `CalculationStore` supports the `created_at` sort key and the UI requests it explicitly.
- 2026-10-10 live: rotated `BELKI_ADMIN_PASSWORD` from ignored `.secrets/BELKI_ADMIN_PASSWORD`, restarted web and bot, and verified `/api/admin/calculations` returns 200 with the current value and 401 with an invalid value. - 2026-10-10 live: rotated `BELKI_ADMIN_PASSWORD` from ignored `.secrets/BELKI_ADMIN_PASSWORD`, restarted web and bot, and verified `/api/admin/calculations` returns 200 with the current value and 401 with an invalid value.
+90 -14
View File
@@ -177,20 +177,7 @@ class CalculationStore:
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered """SELECT id, actor_id, source, mode, input_json, result_json, message, created_at, entered
FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,) FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,)
).fetchall() ).fetchall()
records = [] records = self._records_from_rows(rows)
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"}: if sort_by not in {"created_at", "escort_id", "escort_name", "kitten_id", "kitten_name"}:
sort_by = "escort_id" sort_by = "escort_id"
def sort_value(item: dict[str, Any]) -> tuple[bool, int, int | str]: 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) records.sort(key=sort_value, reverse=descending)
return records[:limit] 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: def set_entered(self, calculation_id: int, entered: bool) -> dict[str, Any] | None:
"""Set the administrative entered flag and return the updated row.""" """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: if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0:
+40 -2
View File
@@ -9,11 +9,12 @@ import re
import threading import threading
import time import time
import unicodedata import unicodedata
from datetime import datetime from datetime import datetime, timezone
from difflib import SequenceMatcher from difflib import SequenceMatcher
from typing import Any from typing import Any
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
from zoneinfo import ZoneInfo
from .api import ApiError, calculate_payload from .api import ApiError, calculate_payload
from .domain import MAX_COACHING_KITTENS from .domain import MAX_COACHING_KITTENS
@@ -954,7 +955,7 @@ class BelkiBot:
pass pass
value = payload.get("command") if isinstance(payload, dict) else payload value = payload.get("command") if isinstance(payload, dict) else payload
return { 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": "/изменить-имя", "menu:inspection": "/осмотр", "menu:goal": "/цель", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка", "menu:rename": "/изменить-имя",
"points:coaching": "прокачка", "points:training": "тренировка", "points:inspection": "осмотр", "points:coaching": "прокачка", "points:training": "тренировка", "points:inspection": "осмотр",
"application:feathers": "/перо", "application:kitten": "/бельчонок", "application:feathers": "/перо", "application:kitten": "/бельчонок",
@@ -1230,6 +1231,7 @@ class BelkiDialog:
[self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")], [self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")],
[self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")], [self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")],
[self._button("Калькулятор баллов", "menu:goal", "secondary")], [self._button("Калькулятор баллов", "menu:goal", "secondary")],
[self._button("Мои отчёты", "menu:my_reports", "secondary")],
[self._button("Подать заявку", "menu:application", "secondary")], [self._button("Подать заявку", "menu:application", "secondary")],
[self._button("Изменить имя кота", "menu:rename", "secondary")], [self._button("Изменить имя кота", "menu:rename", "secondary")],
[self._button("Помощь", "menu:help", "secondary")], [self._button("Помощь", "menu:help", "secondary")],
@@ -1728,6 +1730,8 @@ class BelkiDialog:
onboarding_response = self._ensure_profile(actor_id, text) onboarding_response = self._ensure_profile(actor_id, text)
if onboarding_response is not None: if onboarding_response is not None:
return onboarding_response return onboarding_response
if text.casefold() in {"/мои-отчёты", "/мои-отчеты", "мои отчёты", "мои отчеты"}:
return self._my_reports(actor_id)
if text.lower() in ("/отмена", "отмена", "нет") and actor_id in self._states: if text.lower() in ("/отмена", "отмена", "нет") and actor_id in self._states:
self._reset(actor_id) self._reset(actor_id)
return "Текущий ввод отменён. Для нового отчёта используйте /лу, /зу или /help." return "Текущий ввод отменён. Для нового отчёта используйте /лу, /зу или /help."
@@ -1792,6 +1796,40 @@ class BelkiDialog:
except (ApiError, ValueError) as exc: except (ApiError, ValueError) as exc:
return str(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: def main() -> None:
"""Запускает VK-бота, настроив API-клиент, хранилища и цикл событий.""" """Запускает VK-бота, настроив API-клиент, хранилища и цикл событий."""
+37
View File
@@ -389,6 +389,43 @@ class Handler(BaseHTTPRequestHandler):
if path in ("/sudoku", "/sudoku/"): if path in ("/sudoku", "/sudoku/"):
self._file(WEB_ROOT / "sudoku.html") self._file(WEB_ROOT / "sudoku.html")
return 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": if path == "/api/sudoku/games":
try: try:
nickname = parse_qs(urlparse(self.path).query).get("nickname", [""])[0] nickname = parse_qs(urlparse(self.path).query).get("nickname", [""])[0]
@@ -0,0 +1,7 @@
# План: просмотр отправленных отчётов
- [x] T1: Добавить личную историю VK и поиск веб-отчётов по ID кота; покрыть фильтры и UI проверками, обновить актуальную документацию и закоммитить.
goal: Пользователь видит свои отправленные записи в VK и находит отчёты по персонажу на сайте.
files: `app/belki/history.py`, `app/main.py`, `app/belki/vk_bot.py`, `web/calculator.html`, `tests/test_history.py`, `tests/test_vk_bot.py`, `tests/test_report_lookup.py`, `AGENTS.md`, `structure_and_data.md`, `MEMORY.md`, `project_mind_map.md`.
acceptance: Целевые unittest для хранилища, HTTP API и VK меню; Python compileall; `git diff --check`; осмотр вкладки в браузере на мобильной и настольной ширине. Remote test zone MCP в этой сессии не предоставлена, поэтому проверки выполнены локально.
spec: `docs/staging/specs/2026-10-18-sent-report-history.md`
@@ -0,0 +1,16 @@
# Просмотр отправленных отчётов
contract: VK-кнопка «Мои отчёты» показывает сохранённые записи `source='vk'` текущего VK `actor_id`; отдельная вкладка сайта принимает ID кота и показывает сохранённые отчёты, в которых этот ID указан среди участников.
invariant: VK-список содержит только записи текущего отправителя. Сайт ищет точный ID среди `escort_id`, `kitten_id`, ID элементов `extra_kittens` и `character_id`, не раскрывая VK `actor_id`; отчёты сортируются по `created_at DESC, id DESC` и выдаются ограниченной выборкой. Просмотр по произвольному введённому ID кота открыт без проверки владения ID, как следует из требуемого сценария.
test: Проверить VK-фильтр по отправителю; поиск сайта по каждому типу участника и отсутствие чужих совпадений; пустую историю, лимит/сортировку, VK-кнопку, валидацию ID и рендеринг новой вкладки; прогнать целевые тесты Belki и `git diff --check`.
convention: Использовать существующий `CalculationStore`, HTTP handler и систему вкладок `web/calculator.html`; выполнять ограниченный фильтр в БД, а динамический HTML строить через безопасные DOM API.
deferred: Нет.
## Working notes
- Трактовка ID на сайте исправлена по уточнению пользователя: числовой ID кота, не VK ID и не ID строки истории.
- В VK текущий пользователь определяется callback `actor_id`; список доступен только ему и берётся из общей таблицы истории.
- Веб поиск применяется к участникам в сохранённом JSON каждой записи; он не ограничивается только `source='vk'`, чтобы находить отчёты, отправленные через сайт и бот. Ответ не включает `actor_id`.
- Веб API должен выполнять ограниченный SQL-фильтр по точным ID участника (не фильтровать после глобального `list_calculations()`), отдавать только нужные поля и не выдавать административные операции или строки без совпадения.
- Представление: дата, тип записи, сохранённый текст отчёта и вложения осмотра через уже существующие публичные image proxy URL.
- Старые веб-отчёты с `actor_id = NULL` по ID не находятся; записи VK после подтверждения находятся.
+5 -1
View File
@@ -1,6 +1,6 @@
# Карта проекта «Беличья нора» # Карта проекта «Беличья нора»
Актуально на 2026-10-10. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур. Актуально на 2026-10-18. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур.
```mermaid ```mermaid
mindmap mindmap
@@ -21,6 +21,7 @@ mindmap
resolve identity resolve identity
rename existing identity rename existing identity
applications applications
character report lookup
Upload boundary Upload boundary
PNG JPEG WebP PNG JPEG WebP
JSON 20 MiB JSON 20 MiB
@@ -40,6 +41,7 @@ mindmap
Goal calculator Goal calculator
Applications Applications
Cat-name update tab Cat-name update tab
Report lookup by cat ID
web/admin.html web/admin.html
Review and accept Review and accept
Report entered checkbox Report entered checkbox
@@ -57,6 +59,7 @@ mindmap
durable vk_dialog_states checkpoint durable vk_dialog_states checkpoint
Natural one-line parser Natural one-line parser
Existing cat-name rename flow Existing cat-name rename flow
My reports by VK sender ID
Mentor and student labels Mentor and student labels
Per-ward self-sufficiency labels Per-ward self-sufficiency labels
Flexible punctuation and ID normalization Flexible punctuation and ID normalization
@@ -153,6 +156,7 @@ flowchart LR
- Диалоги, команды и естественный ввод проверяются в `tests/test_vk_conversation.py`. - Диалоги, команды и естественный ввод проверяются в `tests/test_vk_conversation.py`.
- Границы image-host и HTTP-предохранители проверяются в `tests/test_image_host.py`. - Границы image-host и HTTP-предохранители проверяются в `tests/test_image_host.py`.
- Заявки, экспортная очередь и уведомления проверяются в `tests/test_applications.py`; совместимость сортировки истории — в `tests/test_history.py`. - Заявки, экспортная очередь и уведомления проверяются в `tests/test_applications.py`; совместимость сортировки истории — в `tests/test_history.py`.
- Поиск публичной истории по ID участника, фильтр VK-истории и HTTP response shape проверяются в `tests/test_report_lookup.py` и `tests/test_vk_bot.py`.
- Периоды админки, защищённые XLSX-маршруты и целостность XLSX ZIP проверяются в `tests/test_admin_export.py`. - Периоды админки, защищённые XLSX-маршруты и целостность XLSX ZIP проверяются в `tests/test_admin_export.py`.
- Перед CI используйте Python 3.12 в Docker: `docker run --rm -v "$PWD:/work" -w /work python:3.12-slim sh -lc 'python -m compileall -q app tests && python -m unittest discover -s tests -q'`. - Перед CI используйте Python 3.12 в Docker: `docker run --rm -v "$PWD:/work" -w /work python:3.12-slim sh -lc 'python -m compileall -q app tests && python -m unittest discover -s tests -q'`.
+1
View File
@@ -136,6 +136,7 @@
- 2026-09-26: inspection scoring now has an explicit `EDIBLE_CATCHES` catalogue in `app/belki/domain.py`; `Ящерица` and `Летучая мышь` are documented as one-point catches and covered by regression tests. - 2026-09-26: inspection scoring now has an explicit `EDIBLE_CATCHES` catalogue in `app/belki/domain.py`; `Ящерица` and `Летучая мышь` are documented as one-point catches and covered by regression tests.
- 2026-10-10: VK input migrated from Long Poll to Callback API. `app/belki/vk_bot.py` now serves `/api/vk/callback` on port 8081, validates the callback secret and group ID, handles `message_new`/`message_event`, and keeps scheduler/notifier threads in the bot process. `vk_callback_events` deduplicates callback event IDs for seven days and releases failed claims for VK retry. `deploy/k8s/*` adds the `belki-bot` ClusterIP Service and callback probes; `nginx.conf` routes only the exact callback path to the bot while other `/api/` requests remain on `belki-web`. Public registration and live VK confirmation are still a deployment-stage action. - 2026-10-10: VK input migrated from Long Poll to Callback API. `app/belki/vk_bot.py` now serves `/api/vk/callback` on port 8081, validates the callback secret and group ID, handles `message_new`/`message_event`, and keeps scheduler/notifier threads in the bot process. `vk_callback_events` deduplicates callback event IDs for seven days and releases failed claims for VK retry. `deploy/k8s/*` adds the `belki-bot` ClusterIP Service and callback probes; `nginx.conf` routes only the exact callback path to the bot while other `/api/` requests remain on `belki-web`. Public registration and live VK confirmation are still a deployment-stage action.
- 2026-10-13: added persistent cat-name changes. `IdentityDirectory.rename_existing()` updates the existing `identities` row, all `profiles` rows for that character, and both in-memory indexes; unknown IDs are rejected. VK exposes the separate `Изменить имя кота` menu flow, while `/belki` adds the `Имя кота` tab backed by `/api/rename-identity` after a current-name lookup through `/api/resolve-identity`. - 2026-10-13: added persistent cat-name changes. `IdentityDirectory.rename_existing()` updates the existing `identities` row, all `profiles` rows for that character, and both in-memory indexes; unknown IDs are rejected. VK exposes the separate `Изменить имя кота` menu flow, while `/belki` adds the `Имя кота` tab backed by `/api/rename-identity` after a current-name lookup through `/api/resolve-identity`.
- 2026-10-18: sent-report history reuses the calculations table. VK `Мои отчёты` filters by callback `actor_id` and `source='vk'`; `/belki` adds `Отчёты по ID кота`, backed by `GET /api/reports?character_id=...`, which searches participant IDs across coaching, training, and inspection rows from all sources. The public response returns the latest 100 reports and excludes `actor_id`; it exposes only local `/api/images/<id>` proxy paths for stored screenshots.
# Обновление 2026-08-16: несколько котят # Обновление 2026-08-16: несколько котят
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
+98
View File
@@ -0,0 +1,98 @@
import http.client
import json
import tempfile
import threading
import unittest
from pathlib import Path
from urllib.parse import urlencode
from unittest.mock import patch
from app.belki.history import CalculationStore
from app.main import BelkiHTTPServer, Handler
class ReportLookupTests(unittest.TestCase):
def make_store(self, path: Path) -> CalculationStore:
store = CalculationStore(sqlite_path=path)
entries = [
(1, "vk", "coaching", {"escort_id": 123, "kitten_id": 201, "extra_kittens": [["Дополнительный", 301, "самостоятельно"]]}, "ЛУ [123] → [201]"),
(2, "web", "training", {"escort_id": 401, "kitten_id": 123}, "[123] — тренировка"),
(1, "vk", "inspection", {"character_id": 123}, "Осмотр [123]"),
(1, "vk", "goal", {"kitten_count": 1}, "Расчёт цели"),
(2, "vk", "coaching", {"escort_id": 402, "kitten_id": 403}, "Другой кот"),
]
for actor_id, source, mode, payload, message in entries:
store.save(actor_id=actor_id, source=source, payload={"mode": mode, **payload}, response={"mode": mode, "message": message, "result": {}})
return store
def test_vk_history_filters_sender_source_and_report_modes(self):
with tempfile.TemporaryDirectory() as directory:
store = self.make_store(Path(directory) / "history.sqlite3")
rows = store.list_vk_reports(1)
self.assertEqual({row["message"] for row in rows}, {"ЛУ [123] → [201]", "Осмотр [123]"})
self.assertTrue(all(row["actor_id"] == 1 and row["source"] == "vk" for row in rows))
def test_character_history_matches_every_participant_shape_and_source(self):
with tempfile.TemporaryDirectory() as directory:
store = self.make_store(Path(directory) / "history.sqlite3")
rows = store.list_character_reports(123)
self.assertEqual({row["message"] for row in rows}, {"ЛУ [123] → [201]", "[123] — тренировка", "Осмотр [123]"})
self.assertEqual([row["message"] for row in store.list_character_reports(301)], ["ЛУ [123] → [201]"])
self.assertEqual(store.list_character_reports(999), [])
def test_character_history_limit_is_applied_after_matching(self):
with tempfile.TemporaryDirectory() as directory:
store = self.make_store(Path(directory) / "history.sqlite3")
for index in range(15):
store.save(actor_id=None, source="web", payload={"mode": "inspection", "character_id": 123}, response={"mode": "inspection", "message": str(index), "result": {}})
rows = store.list_character_reports(123, limit=4)
self.assertEqual(len(rows), 4)
self.assertEqual([row["message"] for row in rows], ["14", "13", "12", "11"])
def test_public_character_lookup_returns_no_vk_sender_id(self):
with tempfile.TemporaryDirectory() as directory:
store = self.make_store(Path(directory) / "history.sqlite3")
server = BelkiHTTPServer(("127.0.0.1", 0), Handler)
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
with patch("app.main.history_store", return_value=store):
connection = http.client.HTTPConnection("127.0.0.1", server.server_port)
connection.request("GET", f"/api/reports?{urlencode({'character_id': '123'})}")
response = connection.getresponse()
payload = json.loads(response.read())
connection.close()
self.assertEqual(response.status, 200)
self.assertEqual(len(payload["items"]), 3)
self.assertTrue(all("actor_id" not in item for item in payload["items"]))
finally:
server.shutdown()
server.server_close()
worker.join(timeout=2)
def test_public_character_lookup_rejects_invalid_id(self):
server = BelkiHTTPServer(("127.0.0.1", 0), Handler)
worker = threading.Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
connection = http.client.HTTPConnection("127.0.0.1", server.server_port)
connection.request("GET", "/api/reports?character_id=0")
response = connection.getresponse()
payload = json.loads(response.read())
connection.close()
self.assertEqual(response.status, 400)
self.assertIn("ID кота", payload["error"])
finally:
server.shutdown()
server.server_close()
worker.join(timeout=2)
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -144,6 +144,7 @@ class VkBotTests(unittest.TestCase):
def test_button_payload_maps_to_command(self): def test_button_payload_maps_to_command(self):
self.assertEqual(BelkiBot._button_text({"payload": "menu:lu"}), "/лу") self.assertEqual(BelkiBot._button_text({"payload": "menu:lu"}), "/лу")
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"menu:my_reports"}'}), "/мои-отчёты")
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:coaching"}'}), "прокачка") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:coaching"}'}), "прокачка")
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:training"}'}), "тренировка") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:training"}'}), "тренировка")
self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:inspection"}'}), "осмотр") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:inspection"}'}), "осмотр")
@@ -176,6 +177,28 @@ class VkBotTests(unittest.TestCase):
self.assertIsInstance(payload, dict) self.assertIsInstance(payload, dict)
self.assertIn("command", payload) self.assertIn("command", payload)
def test_my_reports_menu_shows_only_current_vk_sender_history(self):
class Store:
def list_vk_reports(self, actor_id, *, limit=100):
self.actor_id = actor_id
return [{"id": 7, "mode": "training", "message": "Малыш [123] — тренировка.", "created_at": "2026-10-18T12:00:00+00:00"}]
store = Store()
dialog = BelkiDialog(calculation_store=store)
response = dialog.handle(900, "/мои-отчёты", user_id=501)
self.assertEqual(store.actor_id, 501)
self.assertIn("Малыш [123]", response)
self.assertIn("№7", response)
def test_my_reports_button_is_in_main_menu(self):
keyboard = BelkiDialog().keyboard_for(503)
commands = [
json.loads(button["action"]["payload"])["command"]
for row in keyboard["buttons"] for button in row
]
self.assertIn("menu:my_reports", commands)
def test_extract_photo_attachment_keeps_largest_size_and_vk_reference(self): def test_extract_photo_attachment_keeps_largest_size_and_vk_reference(self):
photos = extract_photo_attachments({"attachments": [{"type": "photo", "photo": { photos = extract_photo_attachments({"attachments": [{"type": "photo", "photo": {
"owner_id": -10, "id": 42, "access_key": "secret", "owner_id": -10, "id": 42, "access_key": "secret",
+73 -1
View File
@@ -69,6 +69,11 @@
.site-footer { margin-top: 48px; padding-top: 18px; border-top: 1px solid var(--line); color: var(--muted); font-size: .9rem; } .site-footer { margin-top: 48px; padding-top: 18px; border-top: 1px solid var(--line); color: var(--muted); font-size: .9rem; }
.site-footer a { color: inherit; text-underline-offset: 3px; } .site-footer a { color: inherit; text-underline-offset: 3px; }
.site-footer a:hover { color: var(--accent); } .site-footer a:hover { color: var(--accent); }
.report-results { display: grid; gap: 14px; margin-top: 18px; }
.saved-report { padding: 20px; border: 1px solid var(--line); border-left: 4px solid var(--accent); border-radius: 8px; background: var(--paper); }
.saved-report h3 { margin: 0 0 12px; font-size: 1rem; }
.saved-report pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; line-height: 1.55; }
.saved-report img { display: block; width: min(100%, 680px); max-height: 480px; object-fit: contain; object-position: left; margin-top: 14px; border: 1px solid var(--line); border-radius: 6px; background: #f4efe7; }
@media (prefers-reduced-motion: reduce) { *,*::before,*::after { transition-duration:.01ms!important; } } @media (prefers-reduced-motion: reduce) { *,*::before,*::after { transition-duration:.01ms!important; } }
@media (max-width: 700px) { @media (max-width: 700px) {
main { width: calc(100% - 24px); max-width: 1060px; margin: 24px auto 40px; } main { width: calc(100% - 24px); max-width: 1060px; margin: 24px auto 40px; }
@@ -102,6 +107,7 @@
<nav class="tabs section-tabs" role="tablist" aria-label="Раздел Беличьей норы"> <nav class="tabs section-tabs" role="tablist" aria-label="Раздел Беличьей норы">
<button class="active" id="reportsTab" type="button" role="tab" aria-selected="true" aria-controls="reportsSection" data-section="reports">Отчёты</button> <button class="active" id="reportsTab" type="button" role="tab" aria-selected="true" aria-controls="reportsSection" data-section="reports">Отчёты</button>
<button id="sentReportsTab" type="button" role="tab" aria-selected="false" aria-controls="sentReportsSection" data-section="sentReports">Отчёты по ID кота</button>
<button id="applicationsTab" type="button" role="tab" aria-selected="false" aria-controls="applicationsSection" data-section="applications">Заявки</button> <button id="applicationsTab" type="button" role="tab" aria-selected="false" aria-controls="applicationsSection" data-section="applications">Заявки</button>
<button id="identityTab" type="button" role="tab" aria-selected="false" aria-controls="identitySection" data-section="identity">Имя кота</button> <button id="identityTab" type="button" role="tab" aria-selected="false" aria-controls="identitySection" data-section="identity">Имя кота</button>
</nav> </nav>
@@ -222,6 +228,19 @@
<p class="error" id="error"></p> <p class="error" id="error"></p>
</section> </section>
</section> </section>
<section id="sentReportsSection" class="hidden" role="tabpanel" aria-labelledby="sentReportsTab">
<h2>Найти отчёты по ID кота</h2>
<p class="muted">Покажем последние 100 отправленных отчётов, где кот указан участником.</p>
<form id="sentReportsForm" class="panel">
<div class="grid">
<label>ID кота<input id="sentReportsCharacterId" name="character_id" type="text" inputmode="numeric" pattern="[0-9]+" required></label>
<div class="actions" style="align-items:end;margin-top:0"><button class="primary" id="sentReportsSubmit" type="submit">Найти отчёты</button></div>
</div>
<p id="sentReportsStatus" class="muted" role="status" aria-live="polite"></p>
<p id="sentReportsError" class="error" role="alert"></p>
</form>
<div id="sentReportsResults" class="report-results" aria-live="polite"></div>
</section>
<section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab"> <section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab">
<div id="applicationWorkspace"> <div id="applicationWorkspace">
@@ -547,9 +566,16 @@
goalCopy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); goalCopy.textContent = 'Скопировано'; setTimeout(() => goalCopy.textContent = 'Скопировать', 1500); }); goalCopy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); goalCopy.textContent = 'Скопировано'; setTimeout(() => goalCopy.textContent = 'Скопировать', 1500); });
const reportsSection = document.querySelector('#reportsSection'); const reportsSection = document.querySelector('#reportsSection');
const sentReportsSection = document.querySelector('#sentReportsSection');
const applicationsSection = document.querySelector('#applicationsSection'); const applicationsSection = document.querySelector('#applicationsSection');
const identitySection = document.querySelector('#identitySection'); const identitySection = document.querySelector('#identitySection');
const sectionTabs = [...document.querySelectorAll('[data-section]')]; const sectionTabs = [...document.querySelectorAll('[data-section]')];
const sentReportsForm = document.querySelector('#sentReportsForm');
const sentReportsCharacterId = document.querySelector('#sentReportsCharacterId');
const sentReportsSubmit = document.querySelector('#sentReportsSubmit');
const sentReportsStatus = document.querySelector('#sentReportsStatus');
const sentReportsError = document.querySelector('#sentReportsError');
const sentReportsResults = document.querySelector('#sentReportsResults');
const applicationForm = document.querySelector('#applicationForm'); const applicationForm = document.querySelector('#applicationForm');
const applicationError = document.querySelector('#applicationError'); const applicationError = document.querySelector('#applicationError');
const applicationSuccess = document.querySelector('#applicationSuccess'); const applicationSuccess = document.querySelector('#applicationSuccess');
@@ -568,8 +594,9 @@
// Changes between reports, applications, and identity management while optionally updating the URL. // Changes between reports, applications, and identity management while optionally updating the URL.
function setSection(nextSection, updateUrl = true) { function setSection(nextSection, updateUrl = true) {
const selectedSection = ['reports', 'applications', 'identity'].includes(nextSection) ? nextSection : 'reports'; const selectedSection = ['reports', 'sentReports', 'applications', 'identity'].includes(nextSection) ? nextSection : 'reports';
reportsSection.classList.toggle('hidden', selectedSection !== 'reports'); reportsSection.classList.toggle('hidden', selectedSection !== 'reports');
sentReportsSection.classList.toggle('hidden', selectedSection !== 'sentReports');
applicationsSection.classList.toggle('hidden', selectedSection !== 'applications'); applicationsSection.classList.toggle('hidden', selectedSection !== 'applications');
identitySection.classList.toggle('hidden', selectedSection !== 'identity'); identitySection.classList.toggle('hidden', selectedSection !== 'identity');
sectionTabs.forEach(tab => { sectionTabs.forEach(tab => {
@@ -587,6 +614,51 @@
sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section))); sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section)));
window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section'), false)); window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section'), false));
sentReportsForm.addEventListener('submit', async event => {
event.preventDefault();
sentReportsError.textContent = '';
sentReportsResults.replaceChildren();
const characterId = sentReportsCharacterId.value.trim();
if (!/^[0-9]+$/.test(characterId) || Number(characterId) <= 0) {
sentReportsError.textContent = 'Укажите положительный ID кота.';
return;
}
sentReportsSubmit.disabled = true;
sentReportsStatus.textContent = 'Ищем отчёты…';
try {
const response = await fetch(`/api/reports?character_id=${encodeURIComponent(characterId)}`);
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось загрузить отчёты.');
const items = data.items || [];
sentReportsStatus.textContent = items.length ? `Найдено отчётов: ${items.length}${items.length === data.limit ? ' (показаны последние 100)' : ''}.` : 'Для этого ID кота отчётов пока нет.';
items.forEach(item => {
const article = document.createElement('article');
article.className = 'saved-report';
const title = document.createElement('h3');
const date = item.created_at ? new Date(item.created_at) : null;
const dateLabel = date && !Number.isNaN(date.getTime()) ? new Intl.DateTimeFormat('ru-RU', {dateStyle: 'medium', timeStyle: 'short'}).format(date) : 'Дата неизвестна';
const labels = {coaching: 'Прокачка ЛУ/ЗУ', training: 'Тренировка', inspection: 'Осмотр'};
title.textContent = `${labels[item.mode] || 'Отчёт'} · ${dateLabel}`;
const message = document.createElement('pre');
message.textContent = item.message || '';
article.append(title, message);
(item.attachments || []).forEach(photo => {
const image = document.createElement('img');
image.src = photo.url;
image.alt = `Скриншот к отчёту кота ${characterId}`;
image.loading = 'lazy';
article.append(image);
});
sentReportsResults.append(article);
});
} catch (err) {
sentReportsStatus.textContent = '';
sentReportsError.textContent = err.message;
} finally {
sentReportsSubmit.disabled = false;
}
});
async function lookupRenameIdentity() { async function lookupRenameIdentity() {
renameIdentityError.textContent = ''; renameIdentityError.textContent = '';
renameIdentitySuccess.classList.add('hidden'); renameIdentitySuccess.classList.add('hidden');