Added apps

This commit is contained in:
nyan404 committed 2026-08-21 13:18:34 +03:00
1 parent 540c393258
commit cfeee5a814
11 files changed
+547 -11

No files matched your search

+1
View File
@@ -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: `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`. - 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. - 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 — несколько котят в прокачке # 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+8
View File
@@ -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 пока не подключён. Фотографии из сообщений 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. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака. Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака.
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено. Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
@@ -48,9 +54,11 @@ python3 -m app.belki.vk_bot
- `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей; - `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей;
- `app/belki/reports.py` — шаблоны сообщений; - `app/belki/reports.py` — шаблоны сообщений;
- `app/belki/api.py` — JSON API; - `app/belki/api.py` — JSON API;
- `app/belki/applications.py` — валидация и хранилище заявок;
- `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды; - `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды;
- `app/main.py` — веб-сервис и раздача сайта/userscript-файлов; - `app/main.py` — веб-сервис и раздача сайта/userscript-файлов;
- `web/calculator.html` — форма калькулятора; - `web/calculator.html` — форма калькулятора;
- `web/applications.html` — форма подачи заявок;
- `web/admin.html` — парольная история расчётов для администраторской проверки; - `web/admin.html` — парольная история расчётов для администраторской проверки;
- `tests/` — unit-тесты. - `tests/` — unit-тесты.
+199
View File
@@ -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,))
+144 -3
View File
@@ -4,6 +4,8 @@ import json
import os import os
import random import random
import re import re
import threading
import time
from datetime import datetime from datetime import datetime
from typing import Any, Iterator from typing import Any, Iterator
from urllib.parse import urlencode from urllib.parse import urlencode
@@ -13,6 +15,7 @@ from .api import ApiError, calculate_payload
from .history import CalculationStore from .history import CalculationStore
from .image_host import ImageHostClient from .image_host import ImageHostClient
from .identity import Identity, IdentityDirectory from .identity import Identity, IdentityDirectory
from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application
""" """
Обработка VK-бота: Обработка 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: class BelkiBot:
"""Основной класс бота, обрабатывающий события VK.""" """Основной класс бота, обрабатывающий события VK."""
def __init__(self, client: VkApiClient, group_id: int) -> None: def __init__(self, client: VkApiClient, group_id: int) -> None:
"""Инициализация бота с клиентом VK и ID группы.""" """Инициализация бота с клиентом VK и ID группы."""
self.client = client self.client = client
self.group_id = group_id self.group_id = group_id
identities = IdentityDirectory.from_environment(persistent=True)
self.dialog = BelkiDialog( self.dialog = BelkiDialog(
IdentityDirectory.from_environment(persistent=True), identities,
onboarding=True, onboarding=True,
calculation_store=CalculationStore.from_environment(), calculation_store=CalculationStore.from_environment(),
attachment_mirror=ImageHostClient().mirror, 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: def response_for_text(self, text: str) -> str:
"""Обработка текстового сообщения и возврат ответа.""" """Обработка текстового сообщения и возврат ответа."""
@@ -465,9 +583,26 @@ class BelkiBot:
photos = extract_photo_attachments(message) photos = extract_photo_attachments(message)
if photos: if photos:
self.dialog.queue_attachments(sender, photos) self.dialog.queue_attachments(sender, photos)
self.application_dialog.queue_attachments(sender, photos)
if text: if text:
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) response = self.dialog.handle(int(peer_id), text, user_id=sender)
self.client.send(int(peer_id), response, keyboard=self.dialog.keyboard_for(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 @staticmethod
def _button_text(message: dict[str, Any]) -> str | None: 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 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:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:inspection": "/осмотр", "menu:help": "/help", "menu:cancel": "/отмена", "menu:application": "/заявка",
"quick:today": "__today__", "quick:no_resources": "без ресурсов", "quick:today": "__today__", "quick:no_resources": "без ресурсов",
"place:hollow": "дупло", "place:crevice": "расщелина", "place:hollow": "дупло", "place:crevice": "расщелина",
"skill:lu": "ЛУ", "skill:zu": "ЗУ", "skill:lu": "ЛУ", "skill:zu": "ЗУ",
@@ -515,6 +650,11 @@ class BelkiBot:
def run_forever(self) -> None: 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(): for event in self.events():
self.handle_event(event) self.handle_event(event)
@@ -677,6 +817,7 @@ class BelkiDialog:
"buttons": [ "buttons": [
[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:application", "secondary")],
[self._button("Помощь", "menu:help", "secondary")], [self._button("Помощь", "menu:help", "secondary")],
], ],
} }
+44 -2
View File
@@ -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.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload
from .belki.history import CalculationStore from .belki.history import CalculationStore
from .belki.applications import ApplicationError, ApplicationStore, validate_application
from .belki.identity import IdentityDirectory from .belki.identity import IdentityDirectory
from .belki.image_host import ImageHostClient from .belki.image_host import ImageHostClient
@@ -19,6 +20,7 @@ ROOT = Path(__file__).resolve().parents[1]
WEB_ROOT = ROOT / "web" WEB_ROOT = ROOT / "web"
_HISTORY_STORE: CalculationStore | None = None _HISTORY_STORE: CalculationStore | None = None
_IDENTITY_DIR: IdentityDirectory | None = None _IDENTITY_DIR: IdentityDirectory | None = None
_APPLICATION_STORE: ApplicationStore | None = None
_WEB_SESSIONS: set[str] = set() _WEB_SESSIONS: set[str] = set()
@@ -36,6 +38,13 @@ def identity_dir() -> IdentityDirectory:
return _IDENTITY_DIR 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" _WEB_PROFILE_KEY = "web_user"
@@ -115,6 +124,9 @@ class Handler(BaseHTTPRequestHandler):
if path == "/admin": if path == "/admin":
self._file(WEB_ROOT / "admin.html") self._file(WEB_ROOT / "admin.html")
return return
if path in ("/applications", "/applications/"):
self._file(WEB_ROOT / "applications.html")
return
if path == "/api/admin/calculations": if path == "/api/admin/calculations":
if not self._admin_authorized(): if not self._admin_authorized():
return return
@@ -127,6 +139,13 @@ class Handler(BaseHTTPRequestHandler):
limit = 100 limit = 100
self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit)}) self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending, limit=limit)})
return 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": if path == "/api/web/session":
expected = os.getenv("BELKI_WEB_PASSWORD", "") expected = os.getenv("BELKI_WEB_PASSWORD", "")
cookies = self.headers.get("Cookie", "") cookies = self.headers.get("Cookie", "")
@@ -150,7 +169,7 @@ class Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None: # noqa: N802 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", 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": "Не найдено"}) self._json(404, {"error": "Не найдено"})
return return
try: try:
@@ -195,9 +214,13 @@ class Handler(BaseHTTPRequestHandler):
self._json(200, save_profile(payload)) self._json(200, save_profile(payload))
elif self.path == "/api/get-profile": elif self.path == "/api/get-profile":
self._json(200, 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: else:
self._json(200, calculate_and_store(payload, actor_id=None, source="web")) 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)}) self._json(400, {"error": str(exc)})
except (ValueError, json.JSONDecodeError) as exc: except (ValueError, json.JSONDecodeError) as exc:
self._json(400, {"error": str(exc)}) self._json(400, {"error": str(exc)})
@@ -224,6 +247,25 @@ class Handler(BaseHTTPRequestHandler):
return return
self._json(200, {"deleted": calculation_id}) 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: def log_message(self, format: str, *args: object) -> None:
if os.getenv("BELKI_ACCESS_LOG", "0") == "1": if os.getenv("BELKI_ACCESS_LOG", "0") == "1":
super().log_message(format, *args) super().log_message(format, *args)
+16
View File
@@ -68,6 +68,22 @@ http {
proxy_pass http://10.12.0.212/admin; 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/ { location ^~ /api/ {
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
+12 -3
View File
@@ -8,8 +8,8 @@
│ ├── Прокачка ЛУ (лазание) / ЗУ (зоркость) │ ├── Прокачка ЛУ (лазание) / ЗУ (зоркость)
│ ├── Тренировки │ ├── Тренировки
│ ├── Осмотры дупла/расщелины │ ├── Осмотры дупла/расщелины
│ ├── VK-бот для создания отчётов │ ├── VK-бот для создания отчётов и заявок
│ └── Админ-панель для истории расчётов │ └── Админ-панель для истории расчётов и заявок
│ │
│── 🏗️ Архитектура │── 🏗️ Архитектура
│ ├── Python 3.12 (backend) │ ├── Python 3.12 (backend)
@@ -28,12 +28,14 @@
│ │ ├── reports.py — шаблоны сообщений (render_*) │ │ ├── reports.py — шаблоны сообщений (render_*)
│ │ ├── vk_bot.py — VK Bots Long Poll API │ │ ├── vk_bot.py — VK Bots Long Poll API
│ │ ├── history.py — CalculationStore (PG/SQLite) │ │ ├── history.py — CalculationStore (PG/SQLite)
│ │ ├── applications.py — ApplicationStore и валидация заявок
│ │ ├── identity.py — IdentityDirectory (имя↔ID котёнка) │ │ ├── identity.py — IdentityDirectory (имя↔ID котёнка)
│ │ └── image_host.py — ImageHostClient (зеркалирование фото) │ │ └── image_host.py — ImageHostClient (зеркалирование фото)
│ │ │ │
│ ├── 📁 web/ — фронтенд + userscripts │ ├── 📁 web/ — фронтенд + userscripts
│ │ ├── index.html — редирект-страница │ │ ├── index.html — редирект-страница
│ │ ├── calculator.html — форма калькулятора (LU/ZU/training/inspection) │ │ ├── calculator.html — форма калькулятора (LU/ZU/training/inspection)
│ │ ├── applications.html — форма заявок (перья и роли)
│ │ ├── admin.html — админ-панель истории расчётов │ │ ├── admin.html — админ-панель истории расчётов
│ │ ├── cw.js — UserScript v1.54 (CatWar enhancements) │ │ ├── cw.js — UserScript v1.54 (CatWar enhancements)
│ │ ├── cw-lite.js — облегчённая версия │ │ ├── cw-lite.js — облегчённая версия
@@ -104,21 +106,26 @@
│ │ ├── /belki → calculator.html │ │ ├── /belki → calculator.html
│ │ ├── /calculator.html → форма калькулятора │ │ ├── /calculator.html → форма калькулятора
│ │ ├── /admin → admin.html │ │ ├── /admin → admin.html
│ │ ├── /applications → applications.html
│ │ ├── /api/admin/calculations │ │ ├── /api/admin/calculations
│ │ │ └→ X-Admin-Password → список расчётов (PG или SQLite) │ │ │ └→ X-Admin-Password → список расчётов (PG или SQLite)
│ │ ├── /api/admin/applications → очередь заявок
│ │ └── /web/* → статика (JS, CSS, шрифты) │ │ └── /web/* → статика (JS, CSS, шрифты)
│ │ │ │
│ ├── POST │ ├── POST
│ │ ├── /api/calculate → расчёт отчёта │ │ ├── /api/calculate → расчёт отчёта
│ │ ├── /api/inspect-bulk → bulk-инспекция JSON-payload │ │ ├── /api/inspect-bulk → bulk-инспекция JSON-payload
│ │ └── /api/resolve-identity → разрешение name↔ID │ │ └── /api/resolve-identity → разрешение name↔ID
│ │ └── /api/applications → создание веб-заявки
│ │ │ │
│ └── DELETE │ └── DELETE
│ └── /api/admin/calculations/{id} │ └── /api/admin/calculations/{id}
│ └→ X-Admin-Password → удаление записи │ └→ X-Admin-Password → удаление записи
│ │
│ └── PATCH /api/admin/applications/{id}/accept → принятие заявки
│
│── 🤖 VK-бот │── 🤖 VK-бот
│ ├── Команды: /лу, /зу, /урок, /осмотр, /help, /отмена │ ├── Команды: /лу, /зу, /урок, /осмотр, /заявка, /перо, /бельчонок, /летяга, /куратор, /help, /отмена
│ ├── VK Bots Long Poll API │ ├── VK Bots Long Poll API
│ ├── Контекстные сценарии (state machine) │ ├── Контекстные сценарии (state machine)
│ ├── Клавиатура (keyboard buttons) │ ├── Клавиатура (keyboard buttons)
@@ -150,10 +157,12 @@
│ ├── PostgreSQL (production) │ ├── PostgreSQL (production)
│ │ ├── BELKI_DATABASE_URL │ │ ├── BELKI_DATABASE_URL
│ │ ├── Таблица: calculations │ │ ├── Таблица: calculations
│ │ ├── Таблица: belki_applications
│ │ └── Таблица: identities │ │ └── Таблица: identities
│ ├── SQLite (development) │ ├── SQLite (development)
│ │ ├── data/belki.sqlite3 │ │ ├── data/belki.sqlite3
│ │ ├── Калькуляции │ │ ├── Калькуляции
│ │ ├── Заявки
│ │ ├── Связки персонажей │ │ ├── Связки персонажей
│ │ └── Профили пользователей │ │ └── Профили пользователей
│ └── ImageHost API │ └── ImageHost API
+3
View File
@@ -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. - 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. - 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. - `/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. - 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. - 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. - 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-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: 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-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: несколько котят # Обновление 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]`.
+47
View File
@@ -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()
+25 -3
View File
@@ -54,6 +54,10 @@
.delete { min-height: 34px; padding: 6px 10px; border-color: #d9b8b2; background: transparent; color: var(--danger); font-size: .82rem; } .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); } .delete:hover { border-color: var(--danger); background: #fff1ef; color: var(--danger); }
.empty { padding: 44px 20px; text-align: center; color: var(--muted); } .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 { 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; } dialog::backdrop { background: #211b1877; }
.gallery { display: grid; grid-template-columns: 52px 1fr 52px; align-items: center; gap: 12px; padding: 16px; } .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 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 { 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; } .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; } }
</style> </style>
</head> </head>
<body> <body>
@@ -77,6 +81,14 @@
</section> </section>
<section id="appView" class="hidden"> <section id="appView" class="hidden">
<header class="topbar">
<div><h1>Админская панель</h1><p class="intro">Расчёты и обращения из VK-бота и веб-формы.</p></div>
</header>
<nav class="tabs" aria-label="Раздел админской панели">
<button class="admin-tab tab" type="button" data-admin-view="reports" aria-selected="true">Отчёты</button>
<button class="admin-tab tab" type="button" data-admin-view="applications" aria-selected="false">Заявки</button>
</nav>
<section id="reportsView" class="admin-section">
<header class="topbar"> <header class="topbar">
<div><h1>История отчётов</h1><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div> <div><h1>История отчётов</h1><p class="intro">Подтверждённые расчёты из VK-бота и веб-калькулятора.</p></div>
<div class="record-count" id="recordCount">Записи не загружены</div> <div class="record-count" id="recordCount">Записи не загружены</div>
@@ -98,6 +110,8 @@
<p class="error" id="error" role="alert"></p> <p class="error" id="error" role="alert"></p>
<div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div> <div class="table-wrap"><table><thead><tr><th>Кот</th><th>Котята</th><th>Фото</th><th>Дата</th><th>Сообщение</th><th>Автор</th><th>ID</th><th></th></tr></thead><tbody id="rows"><tr><td class="empty" colspan="8">Загрузка истории…</td></tr></tbody></table></div>
</section> </section>
<section id="applicationsView" class="admin-section applications hidden" aria-labelledby="applicationsTitle"><header class="topbar"><div><h2 id="applicationsTitle">Заявки</h2><p class="intro">Новые обращения из VK-бота и веб-формы.</p></div><div class="record-count" id="applicationCount">Заявки не загружены</div></header><nav class="tabs" aria-label="Статус заявок"><button class="application-tab tab" type="button" data-status="pending" aria-selected="true">Новые</button><button class="application-tab tab" type="button" data-status="accepted" aria-selected="false">Принятые</button></nav><div class="application-layout"><div id="applicationList" class="application-list"><p class="empty">Загрузка заявок…</p></div><article id="applicationDetail" class="application-detail"><p class="empty">Выберите заявку слева.</p></article></div></section>
</section>
</main> </main>
<dialog id="galleryDialog"> <dialog id="galleryDialog">
@@ -123,6 +137,7 @@
const galleryImage = document.querySelector('#galleryImage'); const galleryImage = document.querySelector('#galleryImage');
const galleryCounter = document.querySelector('#galleryCounter'); const galleryCounter = document.querySelector('#galleryCounter');
let items = [], galleryPhotos = [], galleryIndex = 0, activeCategory = 'all'; let items = [], galleryPhotos = [], galleryIndex = 0, activeCategory = 'all';
let applications = [], activeApplicationStatus = 'pending', selectedApplicationId = null, activeAdminView = 'reports';
function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; } function personData(input) { return {name: input.escort_name || input.character_name || '', id: input.escort_id || input.character_id || ''}; }
function kittenEntries(input) { function kittenEntries(input) {
@@ -144,11 +159,18 @@
function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; } function fillFilters() { const cats = new Map(), kittens = new Map(); items.forEach(item => { const input = item.input || {}; const person = personData(input); if (person.id) cats.set(String(person.id), person.name); kittenEntries(input).forEach(entry => { if (entry.id) kittens.set(String(entry.id), entry.name); }); }); const catValue = catFilter.value, kittenValue = kittenFilter.value; catFilter.replaceChildren(new Option('Все коты', '')); [...cats.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => catFilter.add(new Option(`${name} [${id}]`, id))); kittenFilter.replaceChildren(new Option('Все котята', '')); [...kittens.entries()].sort((a,b) => a[1].localeCompare(b[1], 'ru')).forEach(([id,name]) => kittenFilter.add(new Option(`${name} [${id}]`, id))); if ([...catFilter.options].some(option => option.value === catValue)) catFilter.value = catValue; if ([...kittenFilter.options].some(option => option.value === kittenValue)) kittenFilter.value = kittenValue; }
function render() { rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} из ${items.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.created_at || '—'; return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE', headers: {'X-Admin-Password': password.value}}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); } function render() { rows.replaceChildren(); const visible = filteredItems(); recordCount.textContent = `${visible.length} из ${items.length} записей`; if (!visible.length) { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.className = 'empty'; cell.colSpan = 8; cell.textContent = 'По выбранным условиям записей нет.'; row.append(cell); rows.append(row); return; } visible.forEach(item => { const input = item.input || {}; const row = document.createElement('tr'); row.append(personCell(personData(input))); const kittenCell = document.createElement('td'); kittenCell.className = 'person'; kittenEntries(input).forEach(entry => { const strong = document.createElement('strong'); strong.textContent = entry.name; const small = document.createElement('span'); small.textContent = entry.id ? `[${entry.id}]` : 'ID не указан'; kittenCell.append(strong, small); }); if (!kittenCell.childElementCount) kittenCell.textContent = '—'; row.append(kittenCell, photoCell(input.attachments), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.created_at || '—'; return cell; })()); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.className = 'message'; pre.textContent = item.message; message.append(pre); row.append(message, (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.actor_id || '—'; return cell; })(), (() => { const cell = document.createElement('td'); cell.className = 'id-cell'; cell.textContent = item.id; return cell; })()); const actions = document.createElement('td'); const remove = document.createElement('button'); remove.className = 'delete'; remove.type = 'button'; remove.textContent = 'Удалить'; remove.addEventListener('click', async () => { if (!window.confirm(`Удалить запись №${item.id}?`)) return; remove.disabled = true; try { const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE', headers: {'X-Admin-Password': password.value}}); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись'); items = items.filter(entry => entry.id !== item.id); fillFilters(); render(); } catch (err) { error.textContent = err.message; remove.disabled = false; } }); actions.append(remove); row.append(actions); rows.append(row); }); }
async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = new URLSearchParams({sort: 'escort_name', direction: 'asc', limit: '500'}); const response = await fetch(`/api/admin/calculations?${query}`, {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } } async function load() { error.textContent = ''; loadButton.disabled = true; try { const query = new URLSearchParams({sort: 'escort_name', direction: 'asc', limit: '500'}); const response = await fetch(`/api/admin/calculations?${query}`, {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю'); items = data.items || []; fillFilters(); render(); } catch (err) { error.textContent = err.message; recordCount.textContent = 'История не загружена'; } finally { loadButton.disabled = false; } }
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/calculations?limit=1', {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); authView.classList.add('hidden'); appView.classList.remove('hidden'); items = data.items || []; await load(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); authView.append(message); } finally { authButton.disabled = false; } } const applicationLabels = {feather_donation: 'Пожертвование перьев', kitten: 'Стать бельчонком', flying_squirrel: 'Стать белкой-летягой', curator: 'Стать куратором'};
function applicationFields(item) { const a = item.application || {}; const fields = [['Тип', applicationLabels[a.type] || a.type], ['Персонаж', `${a.name || '—'}${a.character_id ? ` [${a.character_id}]` : ''}`], ['Источник', item.source === 'vk' ? 'VK-бот' : 'Веб-форма']]; if (a.vk_link) fields.push(['VK', a.vk_link]); if (a.type === 'flying_squirrel') { fields.push(['Практика ранее', a.practiced_before ? 'Да' : 'Нет']); if (a.practice_review_link) fields.push(['Комментарий практики', a.practice_review_link]); } if (a.type === 'feather_donation') fields.push(['Перья', (a.feathers || []).map(x => `${x.amount} ${x.color} — ${x.source}`).join('\n')]); if (a.type === 'curator') fields.push(['Подтверждение', 'Скриншот ЛУ с дробью']); return fields; }
function renderApplications() { const list = document.querySelector('#applicationList'), detail = document.querySelector('#applicationDetail'), visible = applications.filter(item => item.status === activeApplicationStatus); document.querySelector('#applicationCount').textContent = `${visible.length} ${activeApplicationStatus === 'pending' ? 'новых' : 'принятых'} заявок`; list.replaceChildren(); if (!visible.length) { const empty=document.createElement('p'); empty.className='empty'; empty.textContent='Заявок в этой категории нет.'; list.append(empty); detail.replaceChildren(); const prompt=document.createElement('p');prompt.className='empty';prompt.textContent='Выберите заявку слева.';detail.append(prompt); return; } if (!visible.some(item => item.id === selectedApplicationId)) selectedApplicationId = visible[0].id; visible.forEach(item => { const a=item.application||{}, button=document.createElement('button'), name=document.createElement('strong'), info=document.createElement('span'); button.type='button'; button.className='application-item'; button.setAttribute('aria-selected', String(item.id === selectedApplicationId)); name.textContent=`${a.name || 'Без имени'}${a.character_id ? ` [${a.character_id}]` : ''}`; info.textContent=`${applicationLabels[a.type] || a.type} · ${item.created_at || ''}`; button.append(name,info); button.onclick=()=>{selectedApplicationId=item.id;renderApplications()}; list.append(button); }); const item=visible.find(entry=>entry.id===selectedApplicationId); const fields=applicationFields(item); detail.replaceChildren(); const title=document.createElement('h2'); title.textContent=`Заявка №${item.id}`; const dl=document.createElement('dl'); fields.forEach(([term,value])=>{const dt=document.createElement('dt'),dd=document.createElement('dd');dt.textContent=term;dd.textContent=value;dl.append(dt,dd)}); detail.append(title,dl); const photos=(item.application||{}).attachments||[]; if(photos.length){const title=document.createElement('dt');title.textContent='Скриншоты';const gallery=photoCell(photos).querySelector('.photos');detail.append(title,gallery)} if(item.status==='pending'){const accept=document.createElement('button');accept.className='accept';accept.type='button';accept.textContent='Принять';accept.onclick=async()=>{accept.disabled=true;try{const r=await fetch(`/api/admin/applications/${item.id}/accept`,{method:'PATCH',headers:{'X-Admin-Password':password.value}});const data=await r.json();if(!r.ok)throw new Error(data.error||'Не удалось принять заявку');await loadApplications()}catch(err){error.textContent=err.message;accept.disabled=false}};detail.append(accept)} }
async function loadApplications() { try { const response=await fetch('/api/admin/applications',{headers:{'X-Admin-Password':password.value}}), data=await response.json(); if(!response.ok)throw new Error(data.error||'Не удалось загрузить заявки'); applications=data.items||[];renderApplications(); } catch(err) { error.textContent=err.message; } }
async function authenticate(event) { event.preventDefault(); error.textContent = ''; authButton.disabled = true; try { const response = await fetch('/api/admin/calculations?limit=1', {headers: {'X-Admin-Password': password.value}}); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Не удалось войти'); authView.classList.add('hidden'); appView.classList.remove('hidden'); items = data.items || []; await load(); await loadApplications(); } catch (err) { const message = document.createElement('p'); message.textContent = err.message; message.className = 'error'; const old = authView.querySelector('.error'); if (old) old.remove(); authView.append(message); } finally { authButton.disabled = false; } }
function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; } function updateGallery() { const photo = galleryPhotos[galleryIndex]; galleryImage.src = photo.mirror_url || photo.url; galleryCounter.textContent = `${galleryIndex + 1} из ${galleryPhotos.length}`; }
function openGallery(photos, index) { galleryPhotos = photos.filter(photo => photo.mirror_url || photo.url); galleryIndex = Math.min(index, galleryPhotos.length - 1); updateGallery(); if (galleryDialog.showModal) galleryDialog.showModal(); else galleryDialog.setAttribute('open', ''); } function openGallery(photos, index) { galleryPhotos = photos.filter(photo => photo.mirror_url || photo.url); galleryIndex = Math.min(index, galleryPhotos.length - 1); updateGallery(); if (galleryDialog.showModal) galleryDialog.showModal(); else galleryDialog.setAttribute('open', ''); }
function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); } function closeGallery() { if (galleryDialog.close) galleryDialog.close(); else galleryDialog.removeAttribute('open'); }
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', render); kittenFilter.addEventListener('change', render); document.querySelectorAll('.tab').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('.tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); render(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); }); function selectAdminView(view) { activeAdminView = view; document.querySelector('#reportsView').classList.toggle('hidden', view !== 'reports'); document.querySelector('#applicationsView').classList.toggle('hidden', view !== 'applications'); document.querySelectorAll('.admin-tab').forEach(tab => tab.setAttribute('aria-selected', String(tab.dataset.adminView === view))); }
authForm.addEventListener('submit', authenticate); loadButton.addEventListener('click', load); sort.addEventListener('change', render); direction.addEventListener('change', render); catFilter.addEventListener('change', render); kittenFilter.addEventListener('change', render); document.querySelectorAll('[data-category]').forEach(tab => tab.addEventListener('click', () => { activeCategory = tab.dataset.category; document.querySelectorAll('[data-category]').forEach(item => item.setAttribute('aria-selected', String(item === tab))); render(); })); document.querySelector('#closeGallery').addEventListener('click', closeGallery); document.querySelector('#prevPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex - 1 + galleryPhotos.length) % galleryPhotos.length; updateGallery(); }); document.querySelector('#nextPhoto').addEventListener('click', () => { galleryIndex = (galleryIndex + 1) % galleryPhotos.length; updateGallery(); }); document.addEventListener('keydown', event => { if (!galleryDialog.open) return; if (event.key === 'Escape') closeGallery(); if (event.key === 'ArrowLeft') document.querySelector('#prevPhoto').click(); if (event.key === 'ArrowRight') document.querySelector('#nextPhoto').click(); });
document.querySelectorAll('.application-tab').forEach(tab => tab.addEventListener('click', () => { activeApplicationStatus = tab.dataset.status; document.querySelectorAll('.application-tab').forEach(item => item.setAttribute('aria-selected', String(item === tab))); renderApplications(); }));
document.querySelectorAll('.admin-tab').forEach(tab => tab.addEventListener('click', () => selectAdminView(tab.dataset.adminView)));
</script> </script>
</body> </body>
</html> </html>
+48
View File
@@ -0,0 +1,48 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Беличья нора — новая заявка</title>
<style>
:root { font-family: Inter, ui-sans-serif, system-ui, sans-serif; color: #242522; background: #fff; }
* { box-sizing: border-box; } body { margin: 0; background: #fff; } main { width: min(920px, calc(100% - 32px)); margin: 0 auto; padding: 44px 0 76px; }
h1 { margin: 0; font: 650 clamp(2.1rem, 6vw, 3.7rem)/1.05 Georgia, serif; letter-spacing: -.04em; } h2 { margin: 0; font: 600 1.25rem/1.2 Georgia, serif; }
.intro, .hint, .status { color: #62675f; line-height: 1.55; } .intro { margin: 13px 0 31px; max-width: 640px; }
.topnav { display:flex; justify-content:space-between; gap:15px; align-items:center; margin-bottom:52px; padding-bottom:18px; border-bottom:1px solid #e6e7e2; } .brand { color:#1d622e; font-weight:800; text-decoration:none; font-size:1.05rem; } .topnav a:not(.brand) { color:#4f554d; text-decoration:none; font-size:.92rem; }
.auth { max-width:470px; margin: 14vh auto; border:1px solid #e1e4dc; border-radius:14px; padding:28px; box-shadow:0 12px 35px #3340130b; }
.auth label, label { display:grid; gap:7px; color:#40453f; font-size:.84rem; font-weight:700; } input, select, textarea, button { font:inherit; } input, select, textarea { width:100%; min-height:44px; padding:10px 12px; border:1px solid #cfd4cb; border-radius:8px; background:#fff; color:#20241f; } textarea { min-height:105px; resize:vertical; } input:focus, select:focus, textarea:focus { outline:3px solid #2f813529; border-color:#2f8135; }
.types { display:grid; grid-template-columns:repeat(2, minmax(0,1fr)); gap:10px; margin:25px 0 27px; } .type { display:flex; align-items:center; min-height:76px; padding:14px; text-align:left; color:#333a32; border:1px solid #dce1d8; border-radius:10px; background:#fff; cursor:pointer; font-weight:700; } .type::before { content:""; width:14px; height:14px; border:1px solid #aeb7ab; border-radius:50%; margin-right:11px; flex:0 0 auto; } .type.active { border-color:#237530; box-shadow:inset 0 0 0 1px #237530; } .type.active::before { border:4px solid #237530; }
.panel { border:1px solid #e0e4dc; border-radius:14px; padding:28px; box-shadow:0 14px 40px #3142190a; } .grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; } .wide { grid-column:1/-1; } .hidden { display:none!important; }
.upload { display:grid; justify-items:center; gap:8px; min-height:150px; padding:24px; text-align:center; border:1px dashed #b8c3b3; border-radius:10px; background:#fbfdf9; color:#596259; cursor:pointer; } .upload strong { color:#333a32; } .upload input { display:none; } .files { margin:10px 0 0; padding-left:18px; color:#5a6258; font-size:.86rem; }
.feather { display:grid; grid-template-columns:110px 1fr 1.3fr auto; gap:9px; align-items:end; margin-bottom:9px; } .remove { min-height:44px; padding:9px; background:#fff; border:1px solid #d9aaa5; color:#9b423a; border-radius:8px; cursor:pointer; } button.primary { min-height:48px; padding:10px 18px; border:1px solid #1e6a2b; border-radius:8px; background:#1e6a2b; color:#fff; cursor:pointer; font-weight:750; } button.primary:hover { background:#165521; } button.secondary { border:1px solid #bbc5b8; border-radius:8px; padding:9px 12px; background:#fff; color:#354234; cursor:pointer; }
.actions { display:flex; justify-content:space-between; align-items:center; gap:16px; margin-top:25px; } .error { min-height:22px; color:#a13d35; white-space:pre-wrap; } .success { margin-top:24px; padding:18px; border-left:4px solid #268038; background:#f4fbf3; color:#244b2c; border-radius:7px; }
@media (max-width:640px) { main{width:calc(100% - 26px);padding-top:26px}.topnav{margin-bottom:34px}.types,.grid{grid-template-columns:1fr}.panel{padding:20px}.wide{grid-column:auto}.feather{grid-template-columns:1fr}.actions{align-items:stretch;flex-direction:column-reverse}.actions button{width:100%} }
</style>
</head>
<body><main>
<nav class="topnav"><a class="brand" href="/belki">Беличья нора</a><a href="/belki">Калькулятор отчётов</a></nav>
<section id="auth" class="auth"><h2>Вход</h2><p class="hint">Введите пароль, чтобы подать заявку и приложить скриншоты.</p><form id="authForm"><label>Пароль<input id="password" type="password" autocomplete="current-password" required></label><p id="authError" class="error"></p><button class="primary" type="submit">Войти</button></form></section>
<section id="app" class="hidden"><h1>Новая заявка</h1><p class="intro">Заполните форму — администратор получит структурированную заявку для рассмотрения. Не нужно готовить форумную отпись.</p>
<div class="types" role="radiogroup" aria-label="Тип заявки">
<button class="type active" type="button" data-type="feather_donation">Пожертвовать перо отряду</button><button class="type" type="button" data-type="kitten">Хочу стать бельчонком</button><button class="type" type="button" data-type="flying_squirrel">Хочу стать белкой-летягой</button><button class="type" type="button" data-type="curator">Хочу стать куратором</button>
</div>
<form id="form" class="panel"><div class="grid">
<label>Имя персонажа<input name="name" required></label><label>ID персонажа<input name="character_id" type="number" min="1" required></label>
<label id="vkField" class="wide">Ссылка на страницу VK <span class="hint">(необязательно)</span><input name="vk_link" type="url" placeholder="https://vk.com/id…"></label>
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Перетащите изображение сюда или выберите файл</strong><span>PNG, JPG, JPEG до 15 МБ</span><input class="screenshots" type="file" accept="image/*" multiple></span></label><ul class="files"></ul></section>
<section id="curatorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>Нужен хотя бы один файл</span><input class="screenshots" type="file" accept="image/*" multiple></span></label><ul class="files"></ul></section>
<section id="flyingFields" class="wide hidden"><label>Сдавали практику ранее?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="practiceLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/... или https://vk.com/... "></label></section>
<section id="featherFields" class="wide"><h2>Перья для казны</h2><p class="hint">Укажите цвет, количество и откуда получены перья.</p><div id="feathers"></div><button id="addFeather" class="secondary" type="button">Добавить перо</button></section>
</div><p id="error" class="error" role="alert"></p><div class="actions"><span class="hint">После принятия VK-заявки бот напишет вам в личные сообщения.</span><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden"></div>
</section>
</main><script>
const auth=document.querySelector('#auth'), app=document.querySelector('#app'), form=document.querySelector('#form'), error=document.querySelector('#error'); let active='feather_donation';
function activate(){auth.classList.add('hidden');app.classList.remove('hidden')} async function session(){const r=await fetch('/api/web/session');const d=await r.json();if(d.authenticated)activate()}
document.querySelector('#authForm').addEventListener('submit',async e=>{e.preventDefault();const r=await fetch('/api/web/auth',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password:document.querySelector('#password').value})});const d=await r.json();if(!r.ok){document.querySelector('#authError').textContent=d.error||'Не удалось войти';return}activate()});session().catch(()=>{});
function addFeather(data={}){const row=document.createElement('div');row.className='feather';row.innerHTML='<label>Количество<input data-field="amount" type="number" min="1" required></label><label>Цвет<input data-field="color" placeholder="например, синие" required></label><label>Источник добычи<input data-field="source" placeholder="личные запасы, осмотр дупла…" required></label><button class="remove" type="button">Убрать</button>';Object.entries(data).forEach(([k,v])=>{const el=row.querySelector(`[data-field="${k}"]`);if(el)el.value=v});row.querySelector('.remove').onclick=()=>row.remove();document.querySelector('#feathers').append(row)} addFeather();document.querySelector('#addFeather').onclick=()=>addFeather();
function sync(){document.querySelector('#featherFields').classList.toggle('hidden',active!=='feather_donation');document.querySelector('#kittenFields').classList.toggle('hidden',active!=='kitten');document.querySelector('#curatorFields').classList.toggle('hidden',active!=='curator');document.querySelector('#flyingFields').classList.toggle('hidden',active!=='flying_squirrel');document.querySelector('#vkField').classList.toggle('hidden',active!=='flying_squirrel');document.querySelectorAll('.type').forEach(x=>x.classList.toggle('active',x.dataset.type===active))} document.querySelectorAll('.type').forEach(b=>b.onclick=()=>{active=b.dataset.type;sync()});sync();
document.querySelector('[name="practiced_before"]').onchange=e=>document.querySelector('#practiceLink').classList.toggle('hidden',e.target.value!=='yes');
document.querySelectorAll('.screenshots').forEach(input=>input.onchange=()=>{const list=input.closest('section').querySelector('.files');list.replaceChildren(...[...input.files].map(file=>{const li=document.createElement('li');li.textContent=file.name;return li}))});
async function uploads(){const items=[];for(const file of [...document.querySelectorAll('.screenshots')].flatMap(x=>[...x.files])){const data=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(file)});const r=await fetch('/api/web/upload',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:file.name,type:file.type,data})});const d=await r.json();if(!r.ok)throw new Error(d.error||`Не удалось загрузить ${file.name}`);items.push({type:'photo',url:d.url,name:file.name})}return items}
form.addEventListener('submit',async e=>{e.preventDefault();error.textContent='';try{const data=Object.fromEntries(new FormData(form).entries());data.type=active;data.character_id=Number(data.character_id);data.attachments=await uploads();if(active==='flying_squirrel'){data.practiced_before=data.practiced_before==='yes'}if(active==='feather_donation')data.feathers=[...document.querySelectorAll('.feather')].map(row=>({amount:Number(row.querySelector('[data-field="amount"]').value),color:row.querySelector('[data-field="color"]').value,source:row.querySelector('[data-field="source"]').value}));const r=await fetch('/api/applications',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Не удалось отправить заявку');const success=document.querySelector('#success');success.textContent=`Заявка №${d.id} отправлена на рассмотрение.`;success.classList.remove('hidden');form.reset();document.querySelector('#feathers').replaceChildren();addFeather()}catch(err){error.textContent=err.message}});
</script></body></html>