diff --git a/AGENTS.md b/AGENTS.md index e8935d6..d019856 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,6 +22,7 @@ - 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. - 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=`; 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 - 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. diff --git a/MEMORY.md b/MEMORY.md index 36fae46..d0aef1a 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -1,5 +1,7 @@ # 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 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. diff --git a/app/belki/history.py b/app/belki/history.py index 02dce91..66d5274 100644 --- a/app/belki/history.py +++ b/app/belki/history.py @@ -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: diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index f48a10f..7826c62 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -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-клиент, хранилища и цикл событий.""" diff --git a/app/main.py b/app/main.py index 9cbc7ad..fdc6426 100644 --- a/app/main.py +++ b/app/main.py @@ -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] diff --git a/docs/staging/plans/2026-10-18-sent-report-history.md b/docs/staging/plans/2026-10-18-sent-report-history.md new file mode 100644 index 0000000..3219d03 --- /dev/null +++ b/docs/staging/plans/2026-10-18-sent-report-history.md @@ -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` diff --git a/docs/staging/specs/2026-10-18-sent-report-history.md b/docs/staging/specs/2026-10-18-sent-report-history.md new file mode 100644 index 0000000..30546ec --- /dev/null +++ b/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 после подтверждения находятся. diff --git a/project_mind_map.md b/project_mind_map.md index 531a2ff..e62f8e7 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -1,6 +1,6 @@ # Карта проекта «Беличья нора» -Актуально на 2026-10-10. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур. +Актуально на 2026-10-18. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур. ```mermaid mindmap @@ -21,6 +21,7 @@ mindmap resolve identity rename existing identity applications + character report lookup Upload boundary PNG JPEG WebP JSON 20 MiB @@ -40,6 +41,7 @@ mindmap Goal calculator Applications Cat-name update tab + Report lookup by cat ID web/admin.html Review and accept Report entered checkbox @@ -57,6 +59,7 @@ mindmap durable vk_dialog_states checkpoint Natural one-line parser Existing cat-name rename flow + My reports by VK sender ID Mentor and student labels Per-ward self-sufficiency labels Flexible punctuation and ID normalization @@ -153,6 +156,7 @@ flowchart LR - Диалоги, команды и естественный ввод проверяются в `tests/test_vk_conversation.py`. - Границы image-host и HTTP-предохранители проверяются в `tests/test_image_host.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`. - Перед 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'`. diff --git a/structure_and_data.md b/structure_and_data.md index fa23360..29afdce 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -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-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-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/` proxy paths for stored screenshots. # Обновление 2026-08-16: несколько котят Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. diff --git a/tests/test_report_lookup.py b/tests/test_report_lookup.py new file mode 100644 index 0000000..60b94f8 --- /dev/null +++ b/tests/test_report_lookup.py @@ -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() diff --git a/tests/test_vk_bot.py b/tests/test_vk_bot.py index d6418b2..dcdfdde 100644 --- a/tests/test_vk_bot.py +++ b/tests/test_vk_bot.py @@ -144,6 +144,7 @@ class VkBotTests(unittest.TestCase): def test_button_payload_maps_to_command(self): 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:training"}'}), "тренировка") self.assertEqual(BelkiBot._button_text({"payload": '{"command":"points:inspection"}'}), "осмотр") @@ -176,6 +177,28 @@ class VkBotTests(unittest.TestCase): self.assertIsInstance(payload, dict) 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): photos = extract_photo_attachments({"attachments": [{"type": "photo", "photo": { "owner_id": -10, "id": 42, "access_key": "secret", diff --git a/web/calculator.html b/web/calculator.html index 65ff744..8116d4d 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -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 a { color: inherit; text-underline-offset: 3px; } .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 (max-width: 700px) { main { width: calc(100% - 24px); max-width: 1060px; margin: 24px auto 40px; } @@ -102,6 +107,7 @@ @@ -222,6 +228,19 @@

+