Выберите заявку слева.
diff --git a/MEMORY.md b/MEMORY.md index e4ca0e3..00195c5 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -21,6 +21,7 @@ - 2026-08-16: `docs/staging/specs/2026-08-16-krylany-calculator-rules.md` supersedes the older Belki draft: Krylan equals Belka (the escort role); kittens always receive `minutes/5`, while the escort receives `minutes/5` or `minutes/5*1.5` for non-self-sufficient ЛУ; ZU always uses self-sufficient rules. - 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; the migrated cwshed Nginx gateway keeps MetalLB `10.12.0.204` and routes `/belki`, `/admin`, and `/api/*` to web `10.12.0.212`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. Runtime credentials remain only in the cluster Secret `belki-runtime`. - GitLab CI/CD now builds SHA/latest tags and deploys `deploy/k8s/production.yaml` from `main`. The ignored `.gitlab.variables.env` is a local handoff for GitLab Variables; CI uses namespace-scoped ServiceAccount `belki/gitlab-deploy`, not cluster-admin credentials. +- 2026-08-21: applications use a separate store/table from calculator history. `/applications` and VK `/заявка` collect typed data; `/admin` accepts it. The bot can automatically notify only VK submissions, because a web form has no known reply peer. # 2026-08-16 — несколько котят в прокачке `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. diff --git a/README.md b/README.md index 6bf79a1..7baa451 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,12 @@ python3 -m app.belki.vk_bot Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` защищён паролем `BELKI_WEB_PASSWORD` и позволяет выбрать несколько скриншотов; сервер загружает их на image host (в production — `https://img.nyan404.ru`) и сохраняет ссылки вместе с отчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же image host. Google Sheets пока не подключён. +## Заявки + +`/applications` — защищённая той же веб-сессией форма для пожертвования перьев, бельчонка, белки-летяги и куратора. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка` и выберите сценарий. + +В `/admin` есть верхняя вкладка «Заявки» рядом с «Отчётами»; внутри неё — вкладки новых и принятых заявок, полное содержимое и действие «Принять». После принятия VK-заявки бот пишет заявителю в личные сообщения. У веб-заявки нет автоматически известного VK-получателя: она получает номер, а VK-ссылку можно оставить для ручной связи. + Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака. Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено. @@ -48,9 +54,11 @@ python3 -m app.belki.vk_bot - `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей; - `app/belki/reports.py` — шаблоны сообщений; - `app/belki/api.py` — JSON API; +- `app/belki/applications.py` — валидация и хранилище заявок; - `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды; - `app/main.py` — веб-сервис и раздача сайта/userscript-файлов; - `web/calculator.html` — форма калькулятора; +- `web/applications.html` — форма подачи заявок; - `web/admin.html` — парольная история расчётов для администраторской проверки; - `tests/` — unit-тесты. diff --git a/app/belki/applications.py b/app/belki/applications.py new file mode 100644 index 0000000..b30e4be --- /dev/null +++ b/app/belki/applications.py @@ -0,0 +1,199 @@ +"""Заявки сообщества: валидация и отдельное хранилище очереди модерации.""" + +from __future__ import annotations + +import json +import os +import sqlite3 +import time +from pathlib import Path +from typing import Any + + +APPLICATION_TYPES = { + "feather_donation": "Пожертвовать перо отряду", + "kitten": "Стать бельчонком", + "flying_squirrel": "Стать белкой-летягой", + "curator": "Стать куратором", +} + + +class ApplicationError(ValueError): + """Понятная пользователю ошибка данных заявки.""" + + +def _positive_id(value: Any, label: str) -> int: + try: + result = int(value) + except (TypeError, ValueError) as exc: + raise ApplicationError(f"{label} должно быть числом") from exc + if result <= 0: + raise ApplicationError(f"{label} должно быть положительным") + return result + + +def validate_application(payload: dict[str, Any]) -> dict[str, Any]: + """Возвращает очищенную заявку и проверяет обязательные поля её типа.""" + if not isinstance(payload, dict): + raise ApplicationError("Ожидалась заявка в формате JSON") + application_type = str(payload.get("type", "")).strip() + if application_type not in APPLICATION_TYPES: + raise ApplicationError("Выберите тип заявки") + name = str(payload.get("name", "")).strip() + if not name: + raise ApplicationError("Укажите имя персонажа") + result: dict[str, Any] = { + "type": application_type, + "name": name, + "character_id": _positive_id(payload.get("character_id"), "ID персонажа"), + "attachments": [item for item in payload.get("attachments", []) if isinstance(item, dict)], + "vk_link": str(payload.get("vk_link", "")).strip(), + } + if application_type == "kitten": + if not result["attachments"]: + raise ApplicationError("Для заявки в бельчата приложите скриншот активности") + elif application_type == "flying_squirrel": + practiced_before = payload.get("practiced_before") + if not isinstance(practiced_before, bool): + raise ApplicationError("Укажите, сдавали ли вы практику ранее") + result["practiced_before"] = practiced_before + result["practice_review_link"] = str(payload.get("practice_review_link", "")).strip() + if practiced_before and not result["practice_review_link"]: + raise ApplicationError("Приложите ссылку на комментарий с прошлой практики") + elif application_type == "curator": + if not result["attachments"]: + raise ApplicationError("Для заявки куратором приложите скриншот ЛУ с дробью") + elif application_type == "feather_donation": + feathers = [] + for item in payload.get("feathers", []): + if not isinstance(item, dict): + continue + color = str(item.get("color", "")).strip() + source = str(item.get("source", "")).strip() + if not color or not source: + raise ApplicationError("Для каждого пера укажите цвет и источник добычи") + amount = _positive_id(item.get("amount"), "Количество перьев") + feathers.append({"color": color, "amount": amount, "source": source}) + if not feathers: + raise ApplicationError("Добавьте хотя бы одно перо") + result["feathers"] = feathers + return result + + +class ApplicationStore: + """Хранилище заявок в PostgreSQL production и SQLite для разработки.""" + + def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None: + 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) -> "ApplicationStore": + return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3")) + + def _ensure_sqlite_schema(self) -> None: + with sqlite3.connect(self.sqlite_path) as connection: + connection.execute("""CREATE TABLE IF NOT EXISTS applications ( + id INTEGER PRIMARY KEY AUTOINCREMENT, actor_id INTEGER, reply_peer_id INTEGER, + source TEXT NOT NULL, application_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, reviewed_at TEXT + )""") + try: + connection.execute("ALTER TABLE applications ADD COLUMN notified_at TEXT") + except sqlite3.OperationalError: + pass + + def _ensure_postgres_schema(self) -> None: + with self._psycopg.connect(self.database_url) as connection: + connection.execute("""CREATE TABLE IF NOT EXISTS belki_applications ( + id BIGSERIAL PRIMARY KEY, actor_id BIGINT, reply_peer_id BIGINT, source TEXT NOT NULL, + application_json JSONB NOT NULL, status TEXT NOT NULL DEFAULT 'pending', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), reviewed_at TIMESTAMPTZ + )""") + connection.execute("ALTER TABLE belki_applications ADD COLUMN IF NOT EXISTS notified_at TIMESTAMPTZ") + + def create(self, *, application: dict[str, Any], actor_id: int | None, reply_peer_id: int | None, source: str) -> int: + 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_applications + (actor_id, reply_peer_id, source, application_json) VALUES (%s, %s, %s, %s) RETURNING id""", + (actor_id, reply_peer_id, source, Jsonb(application))).fetchone() + return int(row[0]) + with sqlite3.connect(self.sqlite_path) as connection: + cursor = connection.execute("""INSERT INTO applications + (actor_id, reply_peer_id, source, application_json) VALUES (?, ?, ?, ?)""", + (actor_id, reply_peer_id, source, json.dumps(application, ensure_ascii=False))) + return int(cursor.lastrowid) + + def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]: + if status not in (None, "pending", "accepted"): + raise ApplicationError("Неизвестный статус заявки") + limit = max(1, min(int(limit), 500)) + if self.database_url.startswith(("postgres://", "postgresql://")): + query = "SELECT id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at FROM belki_applications" + params: tuple[Any, ...] = () + if status: + query += " WHERE status = %s"; params = (status,) + query += " ORDER BY created_at DESC LIMIT %s"; params += (limit,) + with self._psycopg.connect(self.database_url) as connection: + rows = connection.execute(query, params).fetchall() + else: + query = "SELECT id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at FROM applications" + params: tuple[Any, ...] = () + if status: + query += " WHERE status = ?"; params = (status,) + query += " ORDER BY created_at DESC LIMIT ?"; params += (limit,) + with sqlite3.connect(self.sqlite_path) as connection: + rows = connection.execute(query, params).fetchall() + return [{"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3], + "application": row[4] if isinstance(row[4], dict) else json.loads(row[4]), "status": row[5], + "created_at": row[6].isoformat() if hasattr(row[6], "isoformat") else row[6], + "reviewed_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7]} for row in rows] + + def accept(self, application_id: int) -> dict[str, Any] | None: + if application_id <= 0: + raise ApplicationError("ID заявки должно быть положительным") + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + row = connection.execute("""UPDATE belki_applications SET status = 'accepted', reviewed_at = NOW() + WHERE id = %s AND status = 'pending' + RETURNING id, actor_id, reply_peer_id, source, application_json, status, created_at, reviewed_at""", (application_id,)).fetchone() + else: + with sqlite3.connect(self.sqlite_path) as connection: + cursor = connection.execute("UPDATE applications SET status = 'accepted', reviewed_at = CURRENT_TIMESTAMP WHERE id = ? AND status = 'pending'", (application_id,)) + if not cursor.rowcount: + return None + return next((item for item in self.list(limit=500) if item["id"] == application_id), None) + if row is None: + return None + return {"id": row[0], "actor_id": row[1], "reply_peer_id": row[2], "source": row[3], + "application": row[4], "status": row[5], "created_at": row[6].isoformat(), "reviewed_at": row[7].isoformat()} + + def pending_notifications(self) -> list[dict[str, Any]]: + """Возвращает принятые VK-заявки, для которых ещё не отправлено уведомление.""" + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + rows = connection.execute("""SELECT id, reply_peer_id, application_json FROM belki_applications + WHERE status = 'accepted' AND notified_at IS NULL AND reply_peer_id IS NOT NULL""").fetchall() + else: + with sqlite3.connect(self.sqlite_path) as connection: + rows = connection.execute("""SELECT id, reply_peer_id, application_json FROM applications + WHERE status = 'accepted' AND notified_at IS NULL AND reply_peer_id IS NOT NULL""").fetchall() + return [{"id": row[0], "reply_peer_id": row[1], "application": row[2] if isinstance(row[2], dict) else json.loads(row[2])} for row in rows] + + def mark_notified(self, application_id: int) -> None: + if self.database_url.startswith(("postgres://", "postgresql://")): + with self._psycopg.connect(self.database_url) as connection: + connection.execute("UPDATE belki_applications SET notified_at = NOW() WHERE id = %s", (application_id,)) + else: + with sqlite3.connect(self.sqlite_path) as connection: + connection.execute("UPDATE applications SET notified_at = CURRENT_TIMESTAMP WHERE id = ?", (application_id,)) diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index 31c6ae1..3e31c22 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -4,6 +4,8 @@ import json import os import random import re +import threading +import time from datetime import datetime from typing import Any, Iterator from urllib.parse import urlencode @@ -13,6 +15,7 @@ from .api import ApiError, calculate_payload from .history import CalculationStore from .image_host import ImageHostClient from .identity import Identity, IdentityDirectory +from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application """ Обработка VK-бота: @@ -425,18 +428,133 @@ class VkApiClient: )) +class ApplicationDialog: + """Небольшой пошаговый опросник для заявок, не смешанный с расчётами.""" + + _commands = { + "/перо": "feather_donation", "/пожертвовать": "feather_donation", + "/бельчонок": "kitten", "/бельчата": "kitten", + "/летяга": "flying_squirrel", "/белка-летяга": "flying_squirrel", + "/куратор": "curator", + } + + def __init__(self, identities: IdentityDirectory, store: ApplicationStore) -> None: + self.identities, self.store = identities, store + self.states: dict[int, dict[str, Any]] = {} + + def active(self, actor_id: int) -> bool: + return actor_id in self.states + + def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None: + if actor_id in self.states: + target = self.states[actor_id].setdefault("attachments", []) + target.extend(attachments) + del target[:-10] + + @staticmethod + def _menu() -> str: + return ("Какую заявку хотите подать?\n" + "• /перо — пожертвовать перо отряду\n" + "• /бельчонок — стать бельчонком\n" + "• /летяга — стать белкой-летягой\n" + "• /куратор — стать куратором") + + def _start(self, actor_id: int, application_type: str) -> str: + profile = self.identities.profile(actor_id=actor_id) + state: dict[str, Any] = {"type": application_type, "attachments": []} + if profile: + state.update(name=profile.name, character_id=profile.character_id) + self.states[actor_id] = state + if not profile: + return "Укажите имя и ID персонажа: Имя [12345]." + return self._next(state) + + @staticmethod + def _next(state: dict[str, Any]) -> str: + kind = state["type"] + if kind == "feather_donation": + return "Перечислите перья через запятую: количество цвет — источник добычи.\nНапример: 2 синие — личные запасы, 1 чёрное — осмотр дупла." + if kind == "kitten": + return "Пришлите скриншот активности. Когда закончите, напишите «готово»." + if kind == "curator": + return "Пришлите скриншот ЛУ с дробью. Когда закончите, напишите «готово»." + if "vk_link" not in state: + return "Пришлите ссылку на страницу VK или напишите «нет»." + if "practiced_before" not in state: + return "Сдавали практику ранее? Ответьте «да» или «нет»." + if state["practiced_before"] and "practice_review_link" not in state: + return "Пришлите ссылку на комментарий ответственного/куратора с прошлой практики." + return "" + + @staticmethod + def _parse_feathers(text: str) -> list[dict[str, Any]]: + feathers = [] + for part in text.split(","): + match = re.fullmatch(r"\s*(\d+)\s+(.+?)\s*[—-]\s*(.+?)\s*", part) + if not match: + raise ApplicationError("Не смог разобрать перья. Используйте: 2 синие — личные запасы") + feathers.append({"amount": int(match.group(1)), "color": match.group(2), "source": match.group(3)}) + return feathers + + def _save(self, actor_id: int, peer_id: int, state: dict[str, Any]) -> str: + application = validate_application(state) + application_id = self.store.create(application=application, actor_id=actor_id, reply_peer_id=peer_id, source="vk") + self.states.pop(actor_id, None) + return f"Заявка №{application_id} отправлена на рассмотрение. Я напишу сюда, когда её примут." + + def handle(self, actor_id: int, peer_id: int, text: str) -> str | None: + command = text.strip().lower() + if command in ("/заявка", "/заявки"): + return self._menu() + if command in self._commands: + return self._start(actor_id, self._commands[command]) + state = self.states.get(actor_id) + if state is None: + return None + if command in ("/отмена", "отмена"): + self.states.pop(actor_id, None) + return "Заявка отменена." + try: + if "name" not in state: + state["name"], state["character_id"] = _person(text) + self.identities.remember_profile(actor_id=actor_id, name=state["name"], character_id=state["character_id"]) + return self._next(state) + if state["type"] == "feather_donation": + state["feathers"] = self._parse_feathers(text) + return self._save(actor_id, peer_id, state) + if state["type"] in ("kitten", "curator"): + if command != "готово": + return "Пришлите скриншот, затем напишите «готово»." + return self._save(actor_id, peer_id, state) + if "vk_link" not in state: + state["vk_link"] = "" if command in ("нет", "неа", "-") else text.strip() + return self._next(state) + if "practiced_before" not in state: + if command not in ("да", "нет"): + return "Ответьте «да» или «нет»." + state["practiced_before"] = command == "да" + return self._next(state) if state["practiced_before"] else self._save(actor_id, peer_id, state) + state["practice_review_link"] = text.strip() + return self._save(actor_id, peer_id, state) + except ApplicationError as exc: + return str(exc) + + class BelkiBot: """Основной класс бота, обрабатывающий события VK.""" def __init__(self, client: VkApiClient, group_id: int) -> None: """Инициализация бота с клиентом VK и ID группы.""" self.client = client self.group_id = group_id + identities = IdentityDirectory.from_environment(persistent=True) self.dialog = BelkiDialog( - IdentityDirectory.from_environment(persistent=True), + identities, onboarding=True, calculation_store=CalculationStore.from_environment(), attachment_mirror=ImageHostClient().mirror, ) + self.application_store = ApplicationStore.from_environment() + self.application_dialog = ApplicationDialog(identities, self.application_store) def response_for_text(self, text: str) -> str: """Обработка текстового сообщения и возврат ответа.""" @@ -465,9 +583,26 @@ class BelkiBot: photos = extract_photo_attachments(message) if photos: self.dialog.queue_attachments(sender, photos) + self.application_dialog.queue_attachments(sender, photos) if text: - response = self.dialog.handle(int(peer_id), text, user_id=sender) - self.client.send(int(peer_id), response, keyboard=self.dialog.keyboard_for(sender)) + response = self.application_dialog.handle(sender, int(peer_id), text) + if response is None: + response = self.dialog.handle(int(peer_id), text, user_id=sender) + keyboard = self.dialog.keyboard_for(sender) + else: + keyboard = None + self.client.send(int(peer_id), response, keyboard=keyboard) + + def notify_accepted_applications(self) -> None: + """Отправляет пользователям принятые админом заявки и отмечает доставку.""" + for item in self.application_store.pending_notifications(): + application = item["application"] + label = APPLICATION_TYPES.get(application.get("type"), "Заявка") + try: + self.client.send(int(item["reply_peer_id"]), f"Ваша заявка «{label}» принята. Спасибо!") + except (VkError, OSError): + continue + self.application_store.mark_notified(int(item["id"])) @staticmethod def _button_text(message: dict[str, Any]) -> str | None: @@ -483,7 +618,7 @@ class BelkiBot: value = payload.get("command") if isinstance(payload, dict) else payload return { "menu:lu": "/лу", "menu:zu": "/зу", "menu:training": "/урок", - "menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", + "menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка", "quick:today": "__today__", "quick:no_resources": "без ресурсов", "place:hollow": "дупло", "place:crevice": "расщелина", "skill:lu": "ЛУ", "skill:zu": "ЗУ", @@ -515,6 +650,11 @@ class BelkiBot: def run_forever(self) -> None: """Бесконечный цикл обработки событий.""" + def notification_loop() -> None: + while True: + self.notify_accepted_applications() + time.sleep(15) + threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start() for event in self.events(): self.handle_event(event) @@ -677,6 +817,7 @@ class BelkiDialog: "buttons": [ [self._button("Прокачка ЛУ", "menu:lu", "primary"), self._button("Прокачка ЗУ", "menu:zu", "primary")], [self._button("Тренировка", "menu:training", "secondary"), self._button("Осмотр", "menu:inspection", "secondary")], + [self._button("Подать заявку", "menu:application", "secondary")], [self._button("Помощь", "menu:help", "secondary")], ], } diff --git a/app/main.py b/app/main.py index 8925c95..9723c17 100644 --- a/app/main.py +++ b/app/main.py @@ -11,6 +11,7 @@ from urllib.parse import parse_qs, unquote, urlparse from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload from .belki.history import CalculationStore +from .belki.applications import ApplicationError, ApplicationStore, validate_application from .belki.identity import IdentityDirectory from .belki.image_host import ImageHostClient @@ -19,6 +20,7 @@ ROOT = Path(__file__).resolve().parents[1] WEB_ROOT = ROOT / "web" _HISTORY_STORE: CalculationStore | None = None _IDENTITY_DIR: IdentityDirectory | None = None +_APPLICATION_STORE: ApplicationStore | None = None _WEB_SESSIONS: set[str] = set() @@ -36,6 +38,13 @@ def identity_dir() -> IdentityDirectory: return _IDENTITY_DIR +def application_store() -> ApplicationStore: + global _APPLICATION_STORE + if _APPLICATION_STORE is None: + _APPLICATION_STORE = ApplicationStore.from_environment() + return _APPLICATION_STORE + + _WEB_PROFILE_KEY = "web_user" @@ -115,6 +124,9 @@ class Handler(BaseHTTPRequestHandler): if path == "/admin": self._file(WEB_ROOT / "admin.html") return + if path in ("/applications", "/applications/"): + self._file(WEB_ROOT / "applications.html") + return if path == "/api/admin/calculations": if not self._admin_authorized(): return @@ -127,6 +139,13 @@ class Handler(BaseHTTPRequestHandler): limit = 100 self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit)}) return + if path == "/api/admin/applications": + if not self._admin_authorized(): + return + query = parse_qs(urlparse(self.path).query) + status = query.get("status", [None])[0] or None + self._json(200, {"items": application_store().list(status=status)}) + return if path == "/api/web/session": expected = os.getenv("BELKI_WEB_PASSWORD", "") cookies = self.headers.get("Cookie", "") @@ -150,7 +169,7 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self) -> None: # noqa: N802 if self.path not in ("/api/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity", - "/api/save-profile", "/api/get-profile"): + "/api/save-profile", "/api/get-profile", "/api/applications"): self._json(404, {"error": "Не найдено"}) return try: @@ -195,9 +214,13 @@ class Handler(BaseHTTPRequestHandler): self._json(200, save_profile(payload)) elif self.path == "/api/get-profile": self._json(200, get_profile()) + elif self.path == "/api/applications": + application = validate_application(payload) + application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web") + self._json(201, {"id": application_id, "status": "pending", "message": "Заявка отправлена на рассмотрение."}) else: self._json(200, calculate_and_store(payload, actor_id=None, source="web")) - except ApiError as exc: + except (ApiError, ApplicationError) as exc: self._json(400, {"error": str(exc)}) except (ValueError, json.JSONDecodeError) as exc: self._json(400, {"error": str(exc)}) @@ -224,6 +247,25 @@ class Handler(BaseHTTPRequestHandler): return self._json(200, {"deleted": calculation_id}) + def do_PATCH(self) -> None: # noqa: N802 + parsed = urlparse(self.path) + prefix = "/api/admin/applications/" + if not parsed.path.startswith(prefix) or not parsed.path.endswith("/accept"): + self._json(404, {"error": "Не найдено"}) + return + if not self._admin_authorized(): + return + raw_id = parsed.path[len(prefix):-len("/accept")].strip("/") + try: + application = application_store().accept(int(raw_id)) + except (ValueError, ApplicationError) as exc: + self._json(400, {"error": str(exc)}) + return + if application is None: + self._json(404, {"error": "Заявка не найдена или уже принята"}) + return + self._json(200, {"item": application}) + def log_message(self, format: str, *args: object) -> None: if os.getenv("BELKI_ACCESS_LOG", "0") == "1": super().log_message(format, *args) diff --git a/nginx.conf b/nginx.conf index ade3d5d..6228734 100644 --- a/nginx.conf +++ b/nginx.conf @@ -68,6 +68,22 @@ http { proxy_pass http://10.12.0.212/admin; } + location = /applications { + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_pass http://10.12.0.212/applications; + } + + location = /applications/ { + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_pass http://10.12.0.212/applications/; + } + location ^~ /api/ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; diff --git a/project_mind_map.md b/project_mind_map.md index 2edbe20..c631e95 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -8,8 +8,8 @@ │ ├── Прокачка ЛУ (лазание) / ЗУ (зоркость) │ ├── Тренировки │ ├── Осмотры дупла/расщелины -│ ├── VK-бот для создания отчётов -│ └── Админ-панель для истории расчётов +│ ├── VK-бот для создания отчётов и заявок +│ └── Админ-панель для истории расчётов и заявок │ │── 🏗️ Архитектура │ ├── Python 3.12 (backend) @@ -28,12 +28,14 @@ │ │ ├── reports.py — шаблоны сообщений (render_*) │ │ ├── vk_bot.py — VK Bots Long Poll API │ │ ├── history.py — CalculationStore (PG/SQLite) +│ │ ├── applications.py — ApplicationStore и валидация заявок │ │ ├── identity.py — IdentityDirectory (имя↔ID котёнка) │ │ └── image_host.py — ImageHostClient (зеркалирование фото) │ │ │ ├── 📁 web/ — фронтенд + userscripts │ │ ├── index.html — редирект-страница │ │ ├── calculator.html — форма калькулятора (LU/ZU/training/inspection) +│ │ ├── applications.html — форма заявок (перья и роли) │ │ ├── admin.html — админ-панель истории расчётов │ │ ├── cw.js — UserScript v1.54 (CatWar enhancements) │ │ ├── cw-lite.js — облегчённая версия @@ -104,21 +106,26 @@ │ │ ├── /belki → calculator.html │ │ ├── /calculator.html → форма калькулятора │ │ ├── /admin → admin.html +│ │ ├── /applications → applications.html │ │ ├── /api/admin/calculations │ │ │ └→ X-Admin-Password → список расчётов (PG или SQLite) +│ │ ├── /api/admin/applications → очередь заявок │ │ └── /web/* → статика (JS, CSS, шрифты) │ │ │ ├── POST │ │ ├── /api/calculate → расчёт отчёта │ │ ├── /api/inspect-bulk → bulk-инспекция JSON-payload │ │ └── /api/resolve-identity → разрешение name↔ID +│ │ └── /api/applications → создание веб-заявки │ │ │ └── DELETE │ └── /api/admin/calculations/{id} │ └→ X-Admin-Password → удаление записи │ +│ └── PATCH /api/admin/applications/{id}/accept → принятие заявки +│ │── 🤖 VK-бот -│ ├── Команды: /лу, /зу, /урок, /осмотр, /help, /отмена +│ ├── Команды: /лу, /зу, /урок, /осмотр, /заявка, /перо, /бельчонок, /летяга, /куратор, /help, /отмена │ ├── VK Bots Long Poll API │ ├── Контекстные сценарии (state machine) │ ├── Клавиатура (keyboard buttons) @@ -150,10 +157,12 @@ │ ├── PostgreSQL (production) │ │ ├── BELKI_DATABASE_URL │ │ ├── Таблица: calculations +│ │ ├── Таблица: belki_applications │ │ └── Таблица: identities │ ├── SQLite (development) │ │ ├── data/belki.sqlite3 │ │ ├── Калькуляции +│ │ ├── Заявки │ │ ├── Связки персонажей │ │ └── Профили пользователей │ └── ImageHost API diff --git a/structure_and_data.md b/structure_and_data.md index a02870e..45afe27 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -27,6 +27,8 @@ - Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp. - VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred. - `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI. +- Applications are stored independently of calculation history by `app/belki/applications.py`: `belki_applications` in PostgreSQL and `applications` in SQLite. `/applications` reuses the existing password-gated web session and upload endpoint; `/api/applications` creates web applications, while `/api/admin/applications` lists them and `PATCH /api/admin/applications/{id}/accept` accepts one. +- Typed flows are: feather donation (amount/color/source rows), kitten (activity screenshot), flying squirrel (past practice and a review link when applicable), and curator (LU screenshot with fraction). VK uses `/заявка`, `/перо`, `/бельчонок`, `/летяга`, and `/куратор`. The bot polls accepted VK applications every 15 seconds and notifies the original peer; web applications have no inferred VK recipient. - The admin page uses a restrained light editorial table layout with a separate password gate, category tabs (all, осмотры, ЛУ, ЗУ, ПУ/уроки), responsive filters, client-side sorting across every visible column, cat/kitten selectors, sticky headings, and a keyboard-navigable photo gallery; behavior remains backed by the existing history API. - VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported. - Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace. @@ -47,6 +49,7 @@ - 2026-08-16: adopted `2026-08-16-krylany-calculator-rules.md`: Krylan is the Belka/escort role, kittens always receive 1 point per 5 minutes, non-self-sufficient ЛУ multiplies escort points by 1.5, and ZU forces self-sufficient calculation. - 2026-08-17: aligned `web/calculator.html` status controls with the VK bot and shared domain: LU allows at most one non-self-sufficient kitten, while ZU forces all kittens to self-sufficient; extra-kitten status controls are synchronized and validated before submission. - 2026-08-17: added password-gated web sessions via `BELKI_WEB_PASSWORD` and `/api/web/auth`; web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production `https://img.nyan404.ru`) and persisted as report attachments. +- 2026-08-21: added structured community applications for feathers, kitten, flying-squirrel, and curator roles across VK, `/applications`, and the top-level `/admin` "Заявки" tab; acceptance is a status transition, not a generated forum post. # Обновление 2026-08-16: несколько котят Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. diff --git a/tests/test_applications.py b/tests/test_applications.py new file mode 100644 index 0000000..a39491f --- /dev/null +++ b/tests/test_applications.py @@ -0,0 +1,47 @@ +import tempfile +import unittest +from pathlib import Path + +from app.belki.applications import ApplicationError, ApplicationStore, validate_application +from app.belki.identity import IdentityDirectory +from app.belki.vk_bot import ApplicationDialog + + +class ApplicationTests(unittest.TestCase): + def test_kitten_requires_activity_screenshot(self) -> None: + with self.assertRaisesRegex(ApplicationError, "скриншот активности"): + validate_application({"type": "kitten", "name": "Бельчоночек", "character_id": 1676767}) + + def test_flying_squirrel_requires_previous_practice_comment(self) -> None: + with self.assertRaisesRegex(ApplicationError, "прошлой практики"): + validate_application({"type": "flying_squirrel", "name": "Муся", "character_id": 1337, "practiced_before": True}) + + def test_feather_donation_is_saved_and_accepted(self) -> None: + with tempfile.TemporaryDirectory() as directory: + store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3") + application = validate_application({ + "type": "feather_donation", "name": "Белка", "character_id": 58775, + "feathers": [{"amount": 2, "color": "синие", "source": "личные запасы"}, {"amount": 1, "color": "чёрное", "source": "осмотр дупла"}], + }) + application_id = store.create(application=application, actor_id=10, reply_peer_id=10, source="vk") + self.assertEqual(store.list(status="pending")[0]["application"]["feathers"][0]["color"], "синие") + accepted = store.accept(application_id) + self.assertEqual(accepted["status"], "accepted") + self.assertEqual(store.pending_notifications()[0]["reply_peer_id"], 10) + store.mark_notified(application_id) + self.assertEqual(store.pending_notifications(), []) + + def test_vk_kitten_application_uses_profile_and_saves(self) -> None: + with tempfile.TemporaryDirectory() as directory: + store = ApplicationStore(sqlite_path=Path(directory) / "applications.sqlite3") + identities = IdentityDirectory(db_path=Path(directory) / "identities.sqlite3") + identities.remember_profile(actor_id=55, name="Бельчоночек", character_id=1676767) + dialog = ApplicationDialog(identities, store) + self.assertIn("скриншот активности", dialog.handle(55, 55, "/бельчонок").lower()) + dialog.queue_attachments(55, [{"type": "photo", "url": "https://example.test/activity.jpg"}]) + self.assertIn("отправлена", dialog.handle(55, 55, "готово").lower()) + self.assertEqual(store.list()[0]["application"]["type"], "kitten") + + +if __name__ == "__main__": + unittest.main() diff --git a/web/admin.html b/web/admin.html index 6b4b12f..f11cbbd 100644 --- a/web/admin.html +++ b/web/admin.html @@ -54,6 +54,10 @@ .delete { min-height: 34px; padding: 6px 10px; border-color: #d9b8b2; background: transparent; color: var(--danger); font-size: .82rem; } .delete:hover { border-color: var(--danger); background: #fff1ef; color: var(--danger); } .empty { padding: 44px 20px; text-align: center; color: var(--muted); } + .admin-section { padding-top: 28px; } + .applications { padding-top: 4px; } + .application-layout { display: grid; grid-template-columns: minmax(260px, .8fr) minmax(380px, 1.2fr); border: 1px solid var(--line); border-radius: 9px; overflow: hidden; background: var(--paper); } + .application-list { border-right: 1px solid var(--line); }.application-item { display: block; width: 100%; min-height: 76px; padding: 15px 16px; border: 0; border-bottom: 1px solid #ebe7e0; border-radius: 0; background: transparent; color: var(--ink); text-align: left; }.application-item:last-child { border-bottom: 0; }.application-item[aria-selected="true"] { background: #f0f7ee; }.application-item strong,.application-item span { display:block; }.application-item span { margin-top:4px; color:var(--muted); font-size:.82rem; }.application-detail { min-height: 360px; padding: 25px; }.application-detail dl { display:grid; grid-template-columns: 150px 1fr; gap:12px 16px; margin:22px 0; }.application-detail dt { color:var(--muted); font-size:.8rem; font-weight:750; text-transform:uppercase; letter-spacing:.05em; }.application-detail dd { margin:0; white-space:pre-wrap; }.application-detail .photos { max-width:none; }.application-detail .photos button { width:120px; height:90px; }.accept { border-color:#247036; background:#247036; }.accept:hover { background:#185627; } dialog { width: min(900px, calc(100% - 32px)); padding: 0; border: 1px solid #5a524b; border-radius: 10px; background: #24211f; color: #fffdfa; box-shadow: 0 24px 80px #211b18aa; } dialog::backdrop { background: #211b1877; } .gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; } @@ -62,7 +66,7 @@ .gallery button:hover { background: #514840; } .gallery-footer { display: flex; justify-content: space-between; align-items: center; padding: 0 18px 16px; color: #c8bfb8; font-size: .85rem; } .gallery-footer button { min-height: 34px; padding: 5px 10px; } - @media (max-width: 720px) { main { width: calc(100% - 28px); padding-top: 28px; } .topbar { display: block; } .record-count { display: block; margin-top: 18px; } .controls { display: grid; grid-template-columns: 1fr 1fr; } .control-group:first-child, .controls > button { grid-column: 1 / -1; } input { min-width: 0; width: 100%; } .auth-form { display: grid; } } + @media (max-width: 720px) { main { width: calc(100% - 28px); padding-top: 28px; } .topbar { display: block; } .record-count { display: block; margin-top: 18px; } .controls { display: grid; grid-template-columns: 1fr 1fr; } .control-group:first-child, .controls > button { grid-column: 1 / -1; } input { min-width: 0; width: 100%; } .auth-form { display: grid; } .application-layout { grid-template-columns: 1fr; }.application-list { border-right:0; border-bottom:1px solid var(--line); }.application-detail dl { grid-template-columns:1fr; gap:4px; }.application-detail dd { margin-bottom:14px; } }
@@ -77,6 +81,14 @@Расчёты и обращения из VK-бота и веб-формы.
Подтверждённые расчёты из VK-бота и веб-калькулятора.
| Кот | Котята | Фото | Дата | Сообщение | Автор | ID | |
|---|---|---|---|---|---|---|---|
| Загрузка истории… | |||||||