feat: add Belichya Nora calculator and VK bot
This commit is contained in:
1 parent
cd6a594ed4
commit
c86d077f9f
20 files changed
+2002
-18
No files matched your search
@@ -0,0 +1,8 @@
|
||||
.git
|
||||
.gitlab
|
||||
.secrets
|
||||
__pycache__
|
||||
*.pyc
|
||||
tests
|
||||
docs/staging
|
||||
*.xlsx
|
||||
@@ -0,0 +1,11 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Переписаны подсказки VK-бота и веб-формы: единый нейтральный FAQ объясняет пошаговый ввод, готовые команды, ввод одной строкой, подтверждение и отмену.
|
||||
- Добавлено расчётное ядро для прокачки ЛУ/ЗУ, тренировки и осмотров.
|
||||
- Добавлены новые текстовые шаблоны отчётов и веб-форма.
|
||||
- Добавлен VK Bots Long Poll adapter без хранения токенов в коде.
|
||||
- Добавлено постоянное SQLite-хранилище автоматически изученных связок имени и ID персонажа; runtime-файлы базы игнорируются Git.
|
||||
- Добавлен onboarding автора VK с приветствием по имени, сохранением профиля и нормализацией ответов `сам`/`несам` и склонений самостоятельности.
|
||||
- Добавлено сохранение каждого подтверждённого расчёта в PostgreSQL с SQLite fallback для локальной разработки.
|
||||
+12
-18
@@ -1,21 +1,15 @@
|
||||
# Используем официальный образ nginx
|
||||
FROM nginx:alpine
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Устанавливаем локаль UTF-8 (решает проблемы внутри контейнера)
|
||||
ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
LANG=C.UTF-8 \
|
||||
LC_ALL=C.UTF-8
|
||||
|
||||
# Копируем файлы сайта
|
||||
COPY ./web /usr/share/nginx/html
|
||||
WORKDIR /app
|
||||
COPY requirements.txt ./requirements.txt
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY app ./app
|
||||
COPY web ./web
|
||||
|
||||
# Копируем кастомный конфиг nginx
|
||||
COPY nginx.conf /etc/nginx/nginx.conf
|
||||
|
||||
# Выставляем правильные разрешения (важно для контейнера!)
|
||||
RUN chmod -R 755 /usr/share/nginx/html && chown -R nginx:nginx /usr/share/nginx/html
|
||||
|
||||
# Открываем порты
|
||||
EXPOSE 80
|
||||
EXPOSE 443
|
||||
|
||||
# Запускаем nginx
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
EXPOSE 8080
|
||||
CMD ["python", "-m", "app.main"]
|
||||
@@ -0,0 +1,10 @@
|
||||
.PHONY: test run build
|
||||
|
||||
test:
|
||||
python3 -m unittest discover -s tests -v
|
||||
|
||||
run:
|
||||
python3 -m app.main
|
||||
|
||||
build:
|
||||
docker build -t belki-calculator:test .
|
||||
@@ -0,0 +1,50 @@
|
||||
# «Беличья нора» — калькулятор отчётов
|
||||
|
||||
Отдельный калькулятор для отчётов по прокачке ЛУ/ЗУ, тренировкам и осмотрам. Старые CatWar userscript-файлы остаются в `web/` и продолжают раздаваться по своим URL.
|
||||
|
||||
## Локальный запуск
|
||||
|
||||
```bash
|
||||
make test
|
||||
make run
|
||||
```
|
||||
|
||||
После запуска сайт доступен на `http://127.0.0.1:8080/`, health endpoint — `/health`.
|
||||
|
||||
VK-бот запускается отдельным процессом из того же образа:
|
||||
|
||||
```bash
|
||||
VK_GROUP_TOKEN='...' VK_GROUP_ID='123' python3 -m app.belki.vk_bot
|
||||
```
|
||||
|
||||
Для локального теста можно скопировать `.env.example` в `.env`, заполнить токен и ID группы, а затем загрузить переменные в текущий shell:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
set -a; source .env; set +a
|
||||
python3 -m app.belki.vk_bot
|
||||
```
|
||||
|
||||
Файл `.env` игнорируется Git и не должен добавляться в коммиты.
|
||||
|
||||
Секреты не записываются в репозиторий. VK-команды перечислены в `/help`.
|
||||
|
||||
Бот поддерживает два способа ввода. Отправьте `/лу`, `/зу`, `/урок` или `/осмотр`, чтобы отвечать на вопросы по одному. Либо пришлите данные одной строкой без `|`, например `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140` или `урок Дикая Вишня 1604614 Серолап 1617140`: бот распознает заполненные поля и спросит недостающие. Полный формат команд с разделителями также поддерживается. Перед созданием отчёта бот показывает распознанные данные и ждёт подтверждения. Для персонажа в осмотре можно ввести только имя или только ID: сохранённая связка подставит вторую часть, а при её отсутствии бот попросит добавить недостающее значение. Незавершённый сценарий хранится отдельно для каждого VK `peer_id`; `/отмена` его сбрасывает.
|
||||
|
||||
При первом сообщении бот попросит представиться (`Имя [ID]`), запомнит профиль по автору VK и дальше будет приветствовать по имени. Профиль хранится в SQLite вместе со связками персонажей. Для самостоятельности принимаются полные формы и короткие ответы `сам`/`несам`.
|
||||
|
||||
Связки персонажей автоматически сохраняются в SQLite-файл `BELKI_IDENTITIES_DB` (по умолчанию `data/belki.sqlite3`). Когда пользователь вводит недостающую пару имя/ID, она запоминается и доступна в следующих диалогах. Без найденной связки бот не угадывает имя, а явно просит вторую часть.
|
||||
|
||||
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
||||
|
||||
## Структура
|
||||
|
||||
- `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей;
|
||||
- `app/belki/reports.py` — шаблоны сообщений;
|
||||
- `app/belki/api.py` — JSON API;
|
||||
- `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды;
|
||||
- `app/main.py` — веб-сервис и раздача сайта/userscript-файлов;
|
||||
- `web/calculator.html` — форма калькулятора;
|
||||
- `tests/` — unit-тесты.
|
||||
|
||||
Спецификация и план находятся в `docs/staging/`.
|
||||
@@ -0,0 +1 @@
|
||||
"""Belki calculator application package."""
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Domain and adapters for the Belki calculator."""
|
||||
|
||||
from .domain import (
|
||||
CoachingResult,
|
||||
CoachingSession,
|
||||
InspectionReport,
|
||||
TrainingResult,
|
||||
TrainingSession,
|
||||
calculate_coaching,
|
||||
calculate_training,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CoachingResult",
|
||||
"CoachingSession",
|
||||
"InspectionReport",
|
||||
"TrainingResult",
|
||||
"TrainingSession",
|
||||
"calculate_coaching",
|
||||
"calculate_training",
|
||||
]
|
||||
@@ -0,0 +1,147 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict
|
||||
from typing import Any
|
||||
|
||||
from .domain import (
|
||||
CoachingSession,
|
||||
InspectionReport,
|
||||
TrainingSession,
|
||||
calculate_coaching,
|
||||
calculate_training,
|
||||
)
|
||||
from .reports import render_coaching, render_inspection, render_training
|
||||
from .identity import IdentityDirectory
|
||||
from .history import CalculationStore
|
||||
|
||||
|
||||
class ApiError(ValueError):
|
||||
"""A user-facing validation error suitable for a JSON response."""
|
||||
|
||||
|
||||
_IDENTITY_DIRECTORY: IdentityDirectory | None = None
|
||||
_CALCULATION_STORE: CalculationStore | None = None
|
||||
|
||||
|
||||
def _identity_directory() -> IdentityDirectory:
|
||||
global _IDENTITY_DIRECTORY
|
||||
if _IDENTITY_DIRECTORY is None:
|
||||
_IDENTITY_DIRECTORY = IdentityDirectory.from_environment(persistent=True)
|
||||
return _IDENTITY_DIRECTORY
|
||||
|
||||
|
||||
def _calculation_store() -> CalculationStore:
|
||||
global _CALCULATION_STORE
|
||||
if _CALCULATION_STORE is None:
|
||||
_CALCULATION_STORE = CalculationStore.from_environment()
|
||||
return _CALCULATION_STORE
|
||||
|
||||
|
||||
def calculate_and_store(payload: dict[str, Any], *, actor_id: int | None, source: str) -> dict[str, Any]:
|
||||
response = calculate_payload(payload)
|
||||
_calculation_store().save(actor_id=actor_id, source=source, payload=payload, response=response)
|
||||
return response
|
||||
|
||||
|
||||
def inspect_bulk_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not isinstance(payload, dict) or not isinstance(payload.get("text"), str):
|
||||
raise ApiError("Ожидалось текстовое поле text")
|
||||
from .vk_bot import inspect_bulk_text
|
||||
return inspect_bulk_text(payload["text"])
|
||||
|
||||
|
||||
def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Resolve either character name or ID from the optional configured directory."""
|
||||
if not isinstance(payload, dict):
|
||||
raise ApiError("Ожидался JSON-объект")
|
||||
name = str(payload.get("name", "")).strip() or None
|
||||
raw_id = payload.get("character_id")
|
||||
if not name and raw_id in (None, ""):
|
||||
raise ApiError("Укажите имя или ID персонажа")
|
||||
try:
|
||||
character_id = int(raw_id) if raw_id not in (None, "") else None
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApiError("ID персонажа должно быть числом") from exc
|
||||
directory = _identity_directory()
|
||||
identity = directory.resolve(name=name, character_id=character_id)
|
||||
if identity:
|
||||
return {"status": "found", "name": identity.name, "character_id": identity.character_id}
|
||||
if payload.get("remember") and name and character_id is not None:
|
||||
identity = directory.remember(name=name, character_id=character_id)
|
||||
return {"status": "saved", "name": identity.name, "character_id": identity.character_id}
|
||||
return {
|
||||
"status": "needs_input",
|
||||
"name": name or "",
|
||||
"character_id": character_id,
|
||||
"message": directory.suggest(name=name, character_id=character_id),
|
||||
}
|
||||
|
||||
|
||||
def _required(payload: dict[str, Any], key: str) -> Any:
|
||||
if key not in payload:
|
||||
raise ApiError(f"Не заполнено поле: {key}")
|
||||
return payload[key]
|
||||
|
||||
|
||||
def _int(payload: dict[str, Any], key: str) -> int:
|
||||
value = _required(payload, key)
|
||||
if isinstance(value, bool):
|
||||
raise ApiError(f"Поле {key} должно быть числом")
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApiError(f"Поле {key} должно быть числом") from exc
|
||||
|
||||
|
||||
def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not isinstance(payload, dict):
|
||||
raise ApiError("Ожидался JSON-объект")
|
||||
mode = payload.get("mode")
|
||||
try:
|
||||
if mode == "coaching":
|
||||
extras = tuple(
|
||||
(str(item["name"]), int(item["id"]), str(item.get("independence", "самостоятельно")))
|
||||
for item in payload.get("extra_kittens", [])
|
||||
)
|
||||
session = CoachingSession(
|
||||
date=str(_required(payload, "date")),
|
||||
skill=str(_required(payload, "skill")),
|
||||
start=str(_required(payload, "start")),
|
||||
end=str(_required(payload, "end")),
|
||||
escort_name=str(_required(payload, "escort_name")),
|
||||
escort_id=_int(payload, "escort_id"),
|
||||
kitten_name=str(_required(payload, "kitten_name")),
|
||||
kitten_id=_int(payload, "kitten_id"),
|
||||
kitten_independence=str(payload.get("kitten_independence", "самостоятельно")),
|
||||
extra_kittens=extras,
|
||||
)
|
||||
result = calculate_coaching(session)
|
||||
return {
|
||||
"mode": mode,
|
||||
"result": asdict(result),
|
||||
"message": render_coaching(session, result),
|
||||
}
|
||||
if mode == "training":
|
||||
session = TrainingSession(
|
||||
escort_name=str(_required(payload, "escort_name")),
|
||||
escort_id=_int(payload, "escort_id"),
|
||||
kitten_name=str(_required(payload, "kitten_name")),
|
||||
kitten_id=_int(payload, "kitten_id"),
|
||||
)
|
||||
result = calculate_training(session)
|
||||
return {"mode": mode, "result": asdict(result), "message": render_training(session, result)}
|
||||
if mode == "inspection":
|
||||
resources = tuple((str(name), int(amount)) for name, amount in payload.get("resources", []))
|
||||
report = InspectionReport(
|
||||
character_name=str(_required(payload, "character_name")),
|
||||
character_id=_int(payload, "character_id"),
|
||||
place=str(_required(payload, "place")),
|
||||
inspections=_int(payload, "inspections"),
|
||||
resources=resources,
|
||||
)
|
||||
return {"mode": mode, "message": render_inspection(report)}
|
||||
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
||||
if isinstance(exc, ApiError):
|
||||
raise
|
||||
raise ApiError(str(exc)) from exc
|
||||
raise ApiError("Неизвестный режим калькулятора")
|
||||
@@ -0,0 +1,148 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
|
||||
Independence = Literal["самостоятельно", "несамостоятельно"]
|
||||
Skill = Literal["ЛУ", "ЗУ"]
|
||||
Place = Literal["дупло", "расщелина"]
|
||||
|
||||
_CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
|
||||
|
||||
|
||||
def parse_clock(value: str) -> int:
|
||||
if not isinstance(value, str) or not _CLOCK_RE.fullmatch(value):
|
||||
raise ValueError("Время должно быть в формате HH:MM, например 05:07")
|
||||
hours, minutes = value.split(":")
|
||||
return int(hours) * 60 + int(minutes)
|
||||
|
||||
|
||||
def format_clock(minutes: int) -> str:
|
||||
if not isinstance(minutes, int) or not 0 <= minutes < 24 * 60:
|
||||
raise ValueError("Время должно быть минутами внутри суток")
|
||||
return f"{minutes // 60:02d}:{minutes % 60:02d}"
|
||||
|
||||
|
||||
def _positive_id(value: int, label: str) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
raise ValueError(f"{label} должен быть положительным целым числом")
|
||||
return value
|
||||
|
||||
|
||||
def _points(value: float) -> float | int:
|
||||
if value.is_integer():
|
||||
return int(value)
|
||||
return round(value, 2)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CoachingSession:
|
||||
date: str
|
||||
skill: Skill
|
||||
start: str
|
||||
end: str
|
||||
escort_name: str
|
||||
escort_id: int
|
||||
kitten_name: str
|
||||
kitten_id: int
|
||||
kitten_independence: Independence = "самостоятельно"
|
||||
extra_kittens: tuple[tuple[str, int, Independence], ...] = field(default_factory=tuple)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.skill not in ("ЛУ", "ЗУ"):
|
||||
raise ValueError("Навык должен быть ЛУ или ЗУ")
|
||||
parse_clock(self.start)
|
||||
parse_clock(self.end)
|
||||
for value, label in (
|
||||
(self.escort_name, "Имя сопровождающего"),
|
||||
(self.kitten_name, "Имя котёнка"),
|
||||
(self.date, "Дата"),
|
||||
):
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValueError(f"{label} не может быть пустым")
|
||||
_positive_id(self.escort_id, "ID сопровождающего")
|
||||
_positive_id(self.kitten_id, "ID котёнка")
|
||||
if self.kitten_independence not in ("самостоятельно", "несамостоятельно"):
|
||||
raise ValueError("Некорректный статус самостоятельности")
|
||||
for name, kitten_id, independence in self.extra_kittens:
|
||||
if not name.strip():
|
||||
raise ValueError("Имя дополнительного котёнка не может быть пустым")
|
||||
_positive_id(kitten_id, "ID дополнительного котёнка")
|
||||
if independence not in ("самостоятельно", "несамостоятельно"):
|
||||
raise ValueError("Некорректный статус самостоятельности")
|
||||
|
||||
@staticmethod
|
||||
def duration_minutes(start: str, end: str) -> int:
|
||||
start_minutes = parse_clock(start)
|
||||
end_minutes = parse_clock(end)
|
||||
return (end_minutes - start_minutes) % (24 * 60)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CoachingResult:
|
||||
minutes: int
|
||||
escort_points: float | int
|
||||
kitten_points: float | int
|
||||
|
||||
|
||||
def calculate_coaching(session: CoachingSession) -> CoachingResult:
|
||||
minutes = session.duration_minutes(session.start, session.end)
|
||||
if minutes <= 0:
|
||||
raise ValueError("Продолжительность захода должна быть больше нуля")
|
||||
|
||||
escort_multiplier = 1.5 if session.kitten_independence == "несамостоятельно" else 1.0
|
||||
for _, _, independence in session.extra_kittens:
|
||||
if independence == "несамостоятельно":
|
||||
escort_multiplier += 0.5
|
||||
|
||||
return CoachingResult(
|
||||
minutes=minutes,
|
||||
escort_points=_points(minutes * escort_multiplier / 5),
|
||||
kitten_points=_points(minutes * 2 / 5),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TrainingSession:
|
||||
escort_name: str
|
||||
escort_id: int
|
||||
kitten_name: str
|
||||
kitten_id: int
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.escort_name.strip() or not self.kitten_name.strip():
|
||||
raise ValueError("Имена участников не могут быть пустыми")
|
||||
_positive_id(self.escort_id, "ID сопровождающего")
|
||||
_positive_id(self.kitten_id, "ID котёнка")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TrainingResult:
|
||||
points: int = 25
|
||||
|
||||
|
||||
def calculate_training(session: TrainingSession) -> TrainingResult:
|
||||
return TrainingResult()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InspectionReport:
|
||||
character_name: str
|
||||
character_id: int
|
||||
place: Place
|
||||
inspections: int
|
||||
resources: tuple[tuple[str, int], ...] = field(default_factory=tuple)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.character_name.strip():
|
||||
raise ValueError("Имя персонажа не может быть пустым")
|
||||
_positive_id(self.character_id, "ID персонажа")
|
||||
if self.place not in ("дупло", "расщелина"):
|
||||
raise ValueError("Место должно быть дуплом или расщелиной")
|
||||
if isinstance(self.inspections, bool) or not isinstance(self.inspections, int) or self.inspections < 0:
|
||||
raise ValueError("Количество осмотров должно быть неотрицательным целым")
|
||||
for name, amount in self.resources:
|
||||
if not name.strip() or not isinstance(amount, int):
|
||||
raise ValueError("Ресурс должен иметь название и целое количество")
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Durable calculation history for PostgreSQL, with a local SQLite fallback."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
class CalculationStore:
|
||||
"""Persist successful calculations without coupling the domain to a database."""
|
||||
|
||||
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) -> "CalculationStore":
|
||||
return cls(
|
||||
database_url=os.getenv("BELKI_DATABASE_URL"),
|
||||
sqlite_path=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 calculations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
actor_id INTEGER,
|
||||
source TEXT NOT NULL,
|
||||
mode TEXT NOT NULL,
|
||||
input_json TEXT NOT NULL,
|
||||
result_json TEXT,
|
||||
message TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)"""
|
||||
)
|
||||
|
||||
def _ensure_postgres_schema(self) -> None:
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS belki_calculations (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
actor_id BIGINT,
|
||||
source TEXT NOT NULL,
|
||||
mode TEXT NOT NULL,
|
||||
input_json JSONB NOT NULL,
|
||||
result_json JSONB,
|
||||
message TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
)"""
|
||||
)
|
||||
|
||||
def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int:
|
||||
mode = str(payload.get("mode", response.get("mode", "unknown")))
|
||||
message = str(response["message"])
|
||||
result = response.get("result")
|
||||
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_calculations
|
||||
(actor_id, source, mode, input_json, result_json, message)
|
||||
VALUES (%s, %s, %s, %s, %s, %s) RETURNING id""",
|
||||
(actor_id, source, mode, Jsonb(payload), Jsonb(result) if result is not None else None, message),
|
||||
).fetchone()
|
||||
return int(row[0])
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
cursor = connection.execute(
|
||||
"""INSERT INTO calculations
|
||||
(actor_id, source, mode, input_json, result_json, message)
|
||||
VALUES (?, ?, ?, ?, ?, ?)""",
|
||||
(actor_id, source, mode, json.dumps(payload, ensure_ascii=False),
|
||||
json.dumps(result, ensure_ascii=False) if result is not None else None, message),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Small configurable identity directory used by interactive character entry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Identity:
|
||||
name: str
|
||||
character_id: int
|
||||
|
||||
|
||||
class IdentityDirectory:
|
||||
"""Resolve and persist character name/ID pairs in PostgreSQL or local SQLite."""
|
||||
|
||||
def __init__(self, identities: list[Identity] | None = None, db_path: str | Path | None = None,
|
||||
database_url: str | None = None) -> None:
|
||||
self.db_path = Path(db_path) if db_path else None
|
||||
self.database_url = database_url or ""
|
||||
self._by_id: dict[int, Identity] = {}
|
||||
self._by_name: dict[str, Identity] = {}
|
||||
self._profiles: dict[int, Identity] = {}
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
import psycopg
|
||||
self._psycopg = psycopg
|
||||
with psycopg.connect(self.database_url) as connection:
|
||||
connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS identities (character_id BIGINT PRIMARY KEY, name TEXT NOT NULL)"
|
||||
)
|
||||
connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS profiles (actor_id BIGINT PRIMARY KEY, name TEXT NOT NULL, character_id BIGINT NOT NULL)"
|
||||
)
|
||||
identities = [Identity(name, character_id) for character_id, name in connection.execute(
|
||||
"SELECT character_id, name FROM identities"
|
||||
)]
|
||||
elif self.db_path:
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with sqlite3.connect(self.db_path) as connection:
|
||||
connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS identities (character_id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
|
||||
)
|
||||
connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS profiles (actor_id INTEGER PRIMARY KEY, name TEXT NOT NULL, character_id INTEGER NOT NULL)"
|
||||
)
|
||||
identities = [Identity(name, character_id) for character_id, name in connection.execute(
|
||||
"SELECT character_id, name FROM identities"
|
||||
)]
|
||||
for item in identities or []:
|
||||
self._index(item)
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls, *, persistent: bool = True) -> "IdentityDirectory":
|
||||
raw = os.getenv("BELKI_IDENTITIES_JSON", "")
|
||||
identities: list[Identity] = []
|
||||
try:
|
||||
if raw:
|
||||
data: Any = json.loads(raw)
|
||||
rows = data.get("characters", data) if isinstance(data, dict) else data
|
||||
identities = [Identity(name=str(row["name"]), character_id=int(row["id"])) for row in rows]
|
||||
except (TypeError, ValueError, KeyError, json.JSONDecodeError) as exc:
|
||||
raise ValueError("BELKI_IDENTITIES_JSON должен содержать список {name,id}") from exc
|
||||
database_url = os.getenv("BELKI_DATABASE_URL", "") if persistent else ""
|
||||
db_path = os.getenv("BELKI_IDENTITIES_DB", "data/belki.sqlite3") if persistent and not database_url else None
|
||||
directory = cls(identities, db_path=db_path, database_url=database_url)
|
||||
for item in identities:
|
||||
directory.remember(name=item.name, character_id=item.character_id)
|
||||
return directory
|
||||
|
||||
def _index(self, identity: Identity) -> None:
|
||||
self._by_id[identity.character_id] = identity
|
||||
self._by_name[identity.name.casefold()] = identity
|
||||
|
||||
def resolve(self, *, name: str | None = None, character_id: int | None = None) -> Identity | None:
|
||||
if character_id is not None and character_id in self._by_id:
|
||||
return self._by_id[character_id]
|
||||
if name and name.casefold() in self._by_name:
|
||||
return self._by_name[name.casefold()]
|
||||
return None
|
||||
|
||||
def remember(self, *, name: str, character_id: int) -> Identity:
|
||||
identity = Identity(name=name.strip(), character_id=character_id)
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO identities(character_id, name) VALUES (%s, %s) "
|
||||
"ON CONFLICT(character_id) DO UPDATE SET name=excluded.name",
|
||||
(identity.character_id, identity.name),
|
||||
)
|
||||
elif self.db_path:
|
||||
with sqlite3.connect(self.db_path) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO identities(character_id, name) VALUES (?, ?) "
|
||||
"ON CONFLICT(character_id) DO UPDATE SET name=excluded.name",
|
||||
(identity.character_id, identity.name),
|
||||
)
|
||||
self._index(identity)
|
||||
return identity
|
||||
|
||||
def remember_profile(self, *, actor_id: int, name: str, character_id: int) -> Identity:
|
||||
identity = self.remember(name=name, character_id=character_id)
|
||||
self._profiles[actor_id] = identity
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO profiles(actor_id, name, character_id) VALUES (%s, %s, %s) "
|
||||
"ON CONFLICT(actor_id) DO UPDATE SET name=excluded.name, character_id=excluded.character_id",
|
||||
(actor_id, identity.name, identity.character_id),
|
||||
)
|
||||
elif self.db_path:
|
||||
with sqlite3.connect(self.db_path) as connection:
|
||||
connection.execute(
|
||||
"INSERT INTO profiles(actor_id, name, character_id) VALUES (?, ?, ?) "
|
||||
"ON CONFLICT(actor_id) DO UPDATE SET name=excluded.name, character_id=excluded.character_id",
|
||||
(actor_id, identity.name, identity.character_id),
|
||||
)
|
||||
return identity
|
||||
|
||||
def profile(self, *, actor_id: int) -> Identity | None:
|
||||
if actor_id in self._profiles:
|
||||
return self._profiles[actor_id]
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
row = connection.execute(
|
||||
"SELECT name, character_id FROM profiles WHERE actor_id = %s", (actor_id,)
|
||||
).fetchone()
|
||||
elif self.db_path:
|
||||
with sqlite3.connect(self.db_path) as connection:
|
||||
row = connection.execute(
|
||||
"SELECT name, character_id FROM profiles WHERE actor_id = ?", (actor_id,)
|
||||
).fetchone()
|
||||
else:
|
||||
return None
|
||||
identity = Identity(row[0], row[1]) if row else None
|
||||
if identity:
|
||||
self._profiles[actor_id] = identity
|
||||
return identity
|
||||
|
||||
def suggest(self, *, name: str | None = None, character_id: int | None = None) -> str:
|
||||
if name and character_id is None:
|
||||
return f"Для «{name}» не найдена связка. Введите ID или добавьте её в справочник."
|
||||
if character_id is not None and not name:
|
||||
return f"Для ID {character_id} не найдена связка. Введите имя или добавьте её в справочник."
|
||||
return "Связка имени и ID не найдена. Добавьте недостающее значение или настройте справочник."
|
||||
@@ -0,0 +1,66 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from .domain import (
|
||||
CoachingResult,
|
||||
CoachingSession,
|
||||
InspectionReport,
|
||||
TrainingSession,
|
||||
TrainingResult,
|
||||
format_clock,
|
||||
parse_clock,
|
||||
)
|
||||
|
||||
|
||||
def _number(value: float | int) -> str:
|
||||
return str(value).rstrip("0").rstrip(".") if isinstance(value, float) else str(value)
|
||||
|
||||
|
||||
def render_coaching(session: CoachingSession, result: CoachingResult) -> str:
|
||||
reminder = (
|
||||
"Не забудьте приложить скриншот истории с подтверждением махинации."
|
||||
if session.kitten_independence == "несамостоятельно"
|
||||
else ""
|
||||
)
|
||||
lines = [
|
||||
f"{session.date} [{session.skill}]",
|
||||
f"Время: {format_clock(parse_clock(session.start))}–"
|
||||
f"{format_clock(parse_clock(session.end))} [{result.minutes} минут]",
|
||||
f"Сопровождающий: {session.escort_name} [{session.escort_id}]",
|
||||
f"Котёнок: {session.kitten_name} [{session.kitten_id}]",
|
||||
f"Баллы белки: {_number(result.escort_points)}",
|
||||
f"Баллы бельчонка: {_number(result.kitten_points)}",
|
||||
"Не забудьте приложить скриншот Игровой с временем и датой начала и конца.",
|
||||
]
|
||||
if reminder:
|
||||
lines.append(reminder)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_training(session: TrainingSession, result: TrainingResult | None = None) -> str:
|
||||
result = result or TrainingResult()
|
||||
return (
|
||||
"#урок\n"
|
||||
f"{session.escort_name} [{session.escort_id}] провёл(а) тренировку "
|
||||
f"{session.kitten_name} [{session.kitten_id}].\n"
|
||||
f"Баллы: {result.points}"
|
||||
)
|
||||
|
||||
|
||||
def render_inspection(report: InspectionReport) -> str:
|
||||
if report.inspections == 1:
|
||||
word = "раз"
|
||||
else:
|
||||
word = "раз"
|
||||
lines = [
|
||||
f"{report.character_name} [{report.character_id}] осмотрел(а) {report.place} {report.inspections} {word}."
|
||||
]
|
||||
if report.resources:
|
||||
lines.extend(
|
||||
f"{('+' + str(abs(amount))) if amount > 0 else ('- ' + str(abs(amount)))} {name}"
|
||||
for name, amount in report.resources
|
||||
if amount
|
||||
)
|
||||
else:
|
||||
lines.append("0")
|
||||
lines.append("Не забудьте приложить скриншот истории и рта.")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,637 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from typing import Any, Iterator
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from .api import ApiError, calculate_payload
|
||||
from .history import CalculationStore
|
||||
from .identity import Identity, IdentityDirectory
|
||||
|
||||
|
||||
HELP_TEXT = (
|
||||
"Беличья нора — помощь\n\n"
|
||||
"Что можно оформить:\n"
|
||||
"• ЛУ или ЗУ за один заход;\n"
|
||||
"• тренировку;\n"
|
||||
"• осмотр дупла или расщелины.\n\n"
|
||||
"Как отправить данные:\n"
|
||||
"1. Начните с /лу, /зу, /урок или /осмотр и отвечайте на вопросы бота.\n"
|
||||
"2. Или отправьте готовую команду:\n"
|
||||
"/лу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | самостоятельно\n"
|
||||
"/зу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | несамостоятельно\n"
|
||||
"/урок Имя [ID] | Котёнок [ID]\n"
|
||||
"/осмотр дупло 6 Имя [ID] | вьюнок=-2, паук=1\n\n"
|
||||
"Можно также прислать данные одной строкой без символов |, например:\n"
|
||||
"15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140\n"
|
||||
"Бот уточнит навык и статус котёнка. Для статуса подойдут «сам» и «несам».\n\n"
|
||||
"Перед созданием отчёта бот покажет распознанные данные и попросит подтвердить их. "
|
||||
"Для каждого захода отправляйте отдельное сообщение. Скриншоты прикладываются вручную.\n\n"
|
||||
"Чтобы начать заново, отправьте /отмена."
|
||||
)
|
||||
|
||||
_PERSON_RE = re.compile(r"^\s*(?P<name>.+?)\s*\[(?P<id>\d+)\]\s*$")
|
||||
_DATE_RE = re.compile(r"\b(?P<date>\d{1,2}\.\d{1,2})\b")
|
||||
_TIME_RE = re.compile(r"\b(?:[01]?\d|2[0-3]):[0-5]\d\b")
|
||||
_NATURAL_PERSON_RE = re.compile(r"(?P<name>[А-Яа-яЁёA-Za-z][^\d|,\n]*?)\s*\[?(?P<id>\d{3,})\]?")
|
||||
|
||||
|
||||
class VkError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _person(value: str) -> tuple[str, int]:
|
||||
match = _PERSON_RE.fullmatch(value)
|
||||
if not match:
|
||||
raise ValueError("Укажите имя и ID в формате Имя [12345]")
|
||||
return match.group("name").strip(), int(match.group("id"))
|
||||
|
||||
|
||||
def parse_text_command(text: str) -> dict[str, Any]:
|
||||
text = text.strip()
|
||||
if text.lower() in ("/help", "help", "/start", "start"):
|
||||
return {"mode": "help"}
|
||||
if not text.startswith("/"):
|
||||
raise ValueError("Команда должна начинаться с /")
|
||||
|
||||
head, _, body = text.partition(" ")
|
||||
command = head.lower()
|
||||
if command in ("/лу", "/лазание"):
|
||||
parts = [part.strip() for part in body.split("|")]
|
||||
if len(parts) < 3:
|
||||
raise ValueError("Формат: /лу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | статус")
|
||||
date, start, end = parts[0].split()
|
||||
escort_name, escort_id = _person(parts[1])
|
||||
kitten_name, kitten_id = _person(parts[2])
|
||||
return {
|
||||
"mode": "coaching", "date": date, "skill": "ЛУ", "start": start, "end": end,
|
||||
"escort_name": escort_name, "escort_id": escort_id,
|
||||
"kitten_name": kitten_name, "kitten_id": kitten_id,
|
||||
"kitten_independence": parts[3] if len(parts) > 3 and parts[3] else "самостоятельно",
|
||||
"_independence_provided": len(parts) > 3 and bool(parts[3]),
|
||||
}
|
||||
if command in ("/зу", "/зоркость"):
|
||||
parsed = parse_text_command("/лу " + body)
|
||||
parsed["skill"] = "ЗУ"
|
||||
return parsed
|
||||
if command in ("/урок", "/тренировка"):
|
||||
parts = [part.strip() for part in body.split("|")]
|
||||
if len(parts) != 2:
|
||||
raise ValueError("Формат: /урок Имя [ID] | Котёнок [ID]")
|
||||
escort_name, escort_id = _person(parts[0])
|
||||
kitten_name, kitten_id = _person(parts[1])
|
||||
return {"mode": "training", "escort_name": escort_name, "escort_id": escort_id,
|
||||
"kitten_name": kitten_name, "kitten_id": kitten_id}
|
||||
if command in ("/осмотр", "/осмотры"):
|
||||
head_parts, _, resources_text = body.partition("|")
|
||||
parts = head_parts.split()
|
||||
if len(parts) < 3:
|
||||
raise ValueError("Формат: /осмотр дупло N Имя [ID] | ресурс=количество")
|
||||
place, inspections = parts[0], int(parts[1])
|
||||
identity_text = " ".join(parts[2:]).strip()
|
||||
try:
|
||||
character_name, character_id = _person(identity_text)
|
||||
identity_fields = {"character_name": character_name, "character_id": character_id}
|
||||
except ValueError:
|
||||
if identity_text.isdigit():
|
||||
identity_fields = {"character_id": int(identity_text)}
|
||||
elif identity_text:
|
||||
identity_fields = {"character_name": identity_text}
|
||||
else:
|
||||
raise ValueError("Укажите имя или ID персонажа")
|
||||
resources = []
|
||||
for item in resources_text.split(",") if resources_text.strip() else []:
|
||||
name, amount = item.split("=", 1)
|
||||
resources.append([name.strip(), int(amount.strip())])
|
||||
return {"mode": "inspection", **identity_fields, "place": place,
|
||||
"inspections": inspections, "resources": resources}
|
||||
raise ValueError("Неизвестная команда. Используйте /help")
|
||||
|
||||
|
||||
def inspect_bulk_text(text: str) -> dict[str, Any]:
|
||||
"""Classify bulk input without calculating or mutating dialog state."""
|
||||
raw = text.strip()
|
||||
if not raw:
|
||||
return {"status": "needs_clarification", "fields": {}, "questions": ["Пришлите данные для расчёта."]}
|
||||
if not raw.startswith("/"):
|
||||
natural = parse_natural_bulk(raw)
|
||||
if natural is not None:
|
||||
fields, questions = natural
|
||||
return {"status": "needs_clarification" if questions else "complete", "fields": fields, "questions": questions}
|
||||
return {"status": "not_bulk", "fields": {}, "questions": []}
|
||||
try:
|
||||
parsed = parse_text_command(raw)
|
||||
except (ValueError, IndexError) as exc:
|
||||
return {"status": "needs_clarification", "fields": {}, "questions": [str(exc)]}
|
||||
provided = parsed.pop("_independence_provided", True)
|
||||
questions = []
|
||||
if parsed.get("mode") == "coaching" and not provided:
|
||||
questions.append("Котёнок самостоятельный или несамостоятельный?")
|
||||
return {
|
||||
"status": "needs_clarification" if questions else "complete",
|
||||
"fields": parsed,
|
||||
"questions": questions,
|
||||
}
|
||||
|
||||
|
||||
def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
|
||||
"""Parse a forgiving one-line entry without separators."""
|
||||
lowered = text.lower()
|
||||
if re.search(r"\b(урок|тренировк)\w*\b", lowered):
|
||||
people_text = re.sub(r"(?i)^\s*(?:урок|тренировк\w*)\s*", "", text)
|
||||
people = [(match.group("name").strip(" |,–-"), int(match.group("id")))
|
||||
for match in _NATURAL_PERSON_RE.finditer(people_text)]
|
||||
fields: dict[str, Any] = {"mode": "training"}
|
||||
questions: list[str] = []
|
||||
if people:
|
||||
fields["escort_name"], fields["escort_id"] = people[0]
|
||||
else:
|
||||
questions.append("Не вижу сопровождающего в формате Имя и ID.")
|
||||
if len(people) > 1:
|
||||
fields["kitten_name"], fields["kitten_id"] = people[1]
|
||||
else:
|
||||
questions.append("Не вижу котёнка в формате Имя и ID.")
|
||||
return fields, questions
|
||||
if re.search(r"\b(осмотр|дупло|расщелин)\w*\b", lowered):
|
||||
fields = {"mode": "inspection"}
|
||||
questions = []
|
||||
place_match = re.search(r"\b(дупло|расщелин\w*)\b", lowered)
|
||||
if place_match:
|
||||
fields["place"] = "дупло" if place_match.group(1) == "дупло" else "расщелина"
|
||||
else:
|
||||
questions.append("Укажите место: дупло или расщелина.")
|
||||
count_match = re.search(r"\b(\d+)\s*(?:раз(?:а|ов)?|осмотр(?:а|ов)?)?\b", lowered)
|
||||
if count_match:
|
||||
fields["inspections"] = int(count_match.group(1))
|
||||
else:
|
||||
questions.append("Сколько было осмотров?")
|
||||
people_text = text[count_match.end():] if count_match else text
|
||||
people = [(match.group("name").strip(" |,–-"), int(match.group("id")))
|
||||
for match in _NATURAL_PERSON_RE.finditer(people_text)]
|
||||
if people:
|
||||
fields["character_name"], fields["character_id"] = people[0]
|
||||
else:
|
||||
id_match = re.search(r"\b\d{3,}\b", people_text)
|
||||
if id_match:
|
||||
fields["character_id"] = int(id_match.group(0))
|
||||
questions.append("Для этого ID не хватает имени персонажа (или его связки в справочнике).")
|
||||
else:
|
||||
candidate = re.split(r"(?i)\b(?:без ресурсов|ресурс(?:ы|ов)?)\b", people_text, maxsplit=1)[0].strip(" |,–-")
|
||||
if candidate:
|
||||
fields["character_name"] = candidate
|
||||
questions.append("Для этого имени не хватает ID персонажа (или его связки в справочнике).")
|
||||
else:
|
||||
questions.append("Укажите имя или ID персонажа.")
|
||||
resources = []
|
||||
for match in re.finditer(r"([А-Яа-яЁёA-Za-z][А-Яа-яЁёA-Za-z _-]*)\s*[=;:]\s*(-?\d+)", text):
|
||||
resources.append([match.group(1).strip(), int(match.group(2))])
|
||||
fields["resources"] = resources
|
||||
return fields, questions
|
||||
date_match = _DATE_RE.search(text)
|
||||
times = _TIME_RE.findall(text)
|
||||
person_tail = text[max((match.end() for match in _TIME_RE.finditer(text)), default=0):]
|
||||
people = [(match.group("name").strip(" |,–-"), int(match.group("id")))
|
||||
for match in _NATURAL_PERSON_RE.finditer(person_tail)]
|
||||
if not date_match and len(times) < 2 and len(people) < 1:
|
||||
return None
|
||||
skill_match = re.search(r"(?i)\b(лу|лазание|зу|зоркость)\b", text)
|
||||
skill = None
|
||||
if skill_match:
|
||||
skill = "ЗУ" if skill_match.group(1).lower() in ("зу", "зоркость") else "ЛУ"
|
||||
fields: dict[str, Any] = {"mode": "coaching"}
|
||||
questions: list[str] = []
|
||||
if skill:
|
||||
fields["skill"] = skill
|
||||
else:
|
||||
questions.append("Какой навык считать: ЛУ или ЗУ?")
|
||||
if date_match:
|
||||
fields["date"] = date_match.group("date")
|
||||
else:
|
||||
questions.append("Не вижу дату. Напишите её, например 15.08.")
|
||||
if len(times) >= 2:
|
||||
fields["start"], fields["end"] = times[:2]
|
||||
else:
|
||||
questions.append("Нужны время начала и время конца, например 11:00 11:20.")
|
||||
if len(people) >= 1:
|
||||
fields["escort_name"], fields["escort_id"] = people[0]
|
||||
else:
|
||||
questions.append("Не вижу сопровождающего в формате Имя и ID.")
|
||||
if len(people) >= 2:
|
||||
fields["kitten_name"], fields["kitten_id"] = people[1]
|
||||
else:
|
||||
questions.append("Не вижу котёнка в формате Имя и ID.")
|
||||
independence_match = re.search(r"(?i)\b(самостоятельно|несамостоятельно)\b", text)
|
||||
if independence_match:
|
||||
fields["kitten_independence"] = independence_match.group(1).lower()
|
||||
else:
|
||||
questions.append("Котёнок самостоятельный или несамостоятельный?")
|
||||
return fields, questions
|
||||
|
||||
|
||||
def build_message_request(peer_id: int, message: str, access_token: str, api_version: str,
|
||||
random_id: int | None = None) -> dict[str, Any]:
|
||||
return {
|
||||
"peer_id": peer_id,
|
||||
"message": message,
|
||||
"random_id": random_id if random_id is not None else random.randint(1, 2**31 - 1),
|
||||
"access_token": access_token,
|
||||
"v": api_version,
|
||||
}
|
||||
|
||||
|
||||
class VkApiClient:
|
||||
def __init__(self, access_token: str, api_version: str = "5.199") -> None:
|
||||
self.access_token = access_token
|
||||
self.api_version = api_version
|
||||
|
||||
def call(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
values = {**(params or {}), "access_token": self.access_token, "v": self.api_version}
|
||||
request = Request(
|
||||
f"https://api.vk.com/method/{method}",
|
||||
data=urlencode(values).encode(),
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||
)
|
||||
with urlopen(request, timeout=35) as response:
|
||||
payload = json.load(response)
|
||||
if "error" in payload:
|
||||
raise VkError(payload["error"].get("error_msg", "VK API error"))
|
||||
return payload.get("response", {})
|
||||
|
||||
def send(self, peer_id: int, message: str) -> dict[str, Any]:
|
||||
return self.call("messages.send", {"peer_id": peer_id, "message": message,
|
||||
"random_id": random.randint(1, 2**31 - 1)})
|
||||
|
||||
|
||||
class BelkiBot:
|
||||
def __init__(self, client: VkApiClient, group_id: int) -> None:
|
||||
self.client = client
|
||||
self.group_id = group_id
|
||||
self.dialog = BelkiDialog(
|
||||
IdentityDirectory.from_environment(persistent=True),
|
||||
onboarding=True,
|
||||
calculation_store=CalculationStore.from_environment(),
|
||||
)
|
||||
|
||||
def response_for_text(self, text: str) -> str:
|
||||
try:
|
||||
command = parse_text_command(text)
|
||||
if command["mode"] == "help":
|
||||
return HELP_TEXT
|
||||
return calculate_payload(command)["message"]
|
||||
except (ApiError, ValueError) as exc:
|
||||
return f"Не удалось подготовить отчёт: {exc}\n\n{HELP_TEXT}"
|
||||
|
||||
def handle_event(self, event: dict[str, Any]) -> None:
|
||||
if event.get("type") != "message_new":
|
||||
return
|
||||
message = event.get("object", {}).get("message", event.get("object", {}))
|
||||
peer_id = message.get("peer_id")
|
||||
sender_id = message.get("from_id", message.get("sender_id", peer_id))
|
||||
text = message.get("text", "")
|
||||
if peer_id is not None and text:
|
||||
self.client.send(int(peer_id), self.dialog.handle(int(peer_id), text, user_id=int(sender_id)))
|
||||
|
||||
def events(self) -> Iterator[dict[str, Any]]:
|
||||
poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id})
|
||||
server, key, ts = poll["server"], poll["key"], poll["ts"]
|
||||
while True:
|
||||
query = urlencode({"act": "a_check", "key": key, "wait": 25, "ts": ts})
|
||||
with urlopen(f"{server}?{query}", timeout=35) as response:
|
||||
payload = json.load(response)
|
||||
if payload.get("ts"):
|
||||
ts = payload["ts"]
|
||||
if payload.get("failed"):
|
||||
poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id})
|
||||
server, key, ts = poll["server"], poll["key"], poll["ts"]
|
||||
continue
|
||||
for event in payload.get("updates", []):
|
||||
yield event
|
||||
|
||||
def run_forever(self) -> None:
|
||||
for event in self.events():
|
||||
self.handle_event(event)
|
||||
|
||||
|
||||
class BelkiDialog:
|
||||
"""Conversation state for one VK peer; safe to use without a VK token."""
|
||||
|
||||
_ORDERS = {
|
||||
"coaching": (
|
||||
("skill", "Какой навык считать: ЛУ или ЗУ?"),
|
||||
("date", "Укажите дату в формате ДД.ММ."),
|
||||
("start", "Укажите время начала в формате HH:MM."),
|
||||
("end", "Укажите время конца (конец захода) в формате HH:MM."),
|
||||
("escort", "Укажите сопровождающего в формате Имя [ID]."),
|
||||
("kitten", "Укажите котёнка в формате Имя [ID]."),
|
||||
("independence", "Котёнок самостоятельный или несамостоятельный?"),
|
||||
),
|
||||
"training": (
|
||||
("escort", "Укажите сопровождающего в формате Имя [ID]."),
|
||||
("kitten", "Укажите котёнка в формате Имя [ID]."),
|
||||
),
|
||||
"inspection": (
|
||||
("place", "Укажите место: дупло или расщелина."),
|
||||
("inspections", "Сколько было осмотров?"),
|
||||
("character", "Укажите персонажа в формате Имя [ID]."),
|
||||
("resources", "Перечислите ресурсы (например, вьюнок=-2, паук=1) или напишите «без ресурсов»."),
|
||||
),
|
||||
}
|
||||
|
||||
def __init__(self, identity_directory: IdentityDirectory | None = None, *, onboarding: bool = False,
|
||||
calculation_store: CalculationStore | None = None) -> None:
|
||||
self._states: dict[int, dict[str, Any]] = {}
|
||||
self.identity_directory = identity_directory or IdentityDirectory()
|
||||
self.onboarding = onboarding
|
||||
self.calculation_store = calculation_store
|
||||
|
||||
def _reset(self, peer_id: int) -> None:
|
||||
self._states.pop(peer_id, None)
|
||||
|
||||
@staticmethod
|
||||
def _independence(value: str) -> str | None:
|
||||
normalized = re.sub(r"[^а-яё]", "", value.lower().replace("ё", "е"))
|
||||
if normalized in ("несам", "нсам") or normalized.startswith("несамостоятель"):
|
||||
return "несамостоятельно"
|
||||
if normalized == "сам" or normalized.startswith("самостоятель"):
|
||||
return "самостоятельно"
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _welcome(profile: Identity) -> str:
|
||||
return (
|
||||
f"Привет, {profile.name}!\n"
|
||||
"Выберите, что хотите оформить: /лу, /зу, /урок или /осмотр. "
|
||||
"Подсказки по всем форматам — в /help."
|
||||
)
|
||||
|
||||
def _ensure_profile(self, actor_id: int, text: str) -> str | None:
|
||||
if not self.onboarding:
|
||||
return None
|
||||
profile = self.identity_directory.profile(actor_id=actor_id)
|
||||
state = self._states.get(actor_id)
|
||||
if profile and not (state and state.get("onboarding")):
|
||||
return None
|
||||
if not state or not state.get("onboarding"):
|
||||
self._states[actor_id] = {"onboarding": True}
|
||||
return "Привет! Представься :)\nНапиши имя и ID, например: Дикая Вишня [1604614]"
|
||||
try:
|
||||
name, character_id = _person(text)
|
||||
except ValueError:
|
||||
return "Не смог разобрать. Напиши имя и ID так: Дикая Вишня [1604614]"
|
||||
identity = self.identity_directory.remember_profile(
|
||||
actor_id=actor_id, name=name, character_id=character_id
|
||||
)
|
||||
self._reset(actor_id)
|
||||
return self._welcome(identity)
|
||||
|
||||
def _ask_next(self, state: dict[str, Any]) -> str:
|
||||
for key, prompt in self._ORDERS[state["mode"]]:
|
||||
if not self._has_field(state, key):
|
||||
if key == "character" and state.get("character_id"):
|
||||
return "Связка не найдена. Введите имя персонажа, чтобы добавить его к ID."
|
||||
if key == "character" and state.get("character_name"):
|
||||
return "Связка не найдена. Введите ID персонажа, чтобы добавить его к имени."
|
||||
return prompt
|
||||
state["confirm"] = True
|
||||
return self._confirmation(state)
|
||||
|
||||
@staticmethod
|
||||
def _has_field(state: dict[str, Any], key: str) -> bool:
|
||||
return {
|
||||
"escort": "escort_name" in state and "escort_id" in state,
|
||||
"kitten": "kitten_name" in state and "kitten_id" in state,
|
||||
"independence": "kitten_independence" in state,
|
||||
"character": "character_name" in state and "character_id" in state,
|
||||
}.get(key, key in state)
|
||||
|
||||
@staticmethod
|
||||
def _confirmation(state: dict[str, Any]) -> str:
|
||||
if state["mode"] == "training":
|
||||
return (
|
||||
"Я распознал данные:\n"
|
||||
f"Сопровождающий: {state['escort_name']} [{state['escort_id']}]\n"
|
||||
f"Котёнок: {state['kitten_name']} [{state['kitten_id']}]\n"
|
||||
"Это тренировка на 25 баллов. Подтвердить? Ответьте «да» или «нет»."
|
||||
)
|
||||
if state["mode"] == "inspection":
|
||||
resources = ", ".join(f"{name}={amount}" for name, amount in state.get("resources", [])) or "без ресурсов"
|
||||
return (
|
||||
"Я распознал данные:\n"
|
||||
f"Место: {state['place']}; осмотров: {state['inspections']}\n"
|
||||
f"Персонаж: {state['character_name']} [{state['character_id']}]\n"
|
||||
f"Ресурсы: {resources}\n"
|
||||
"Подтвердить? Ответьте «да» или «нет»."
|
||||
)
|
||||
return (
|
||||
"Я распознал данные:\n"
|
||||
f"Навык: {state['skill']}\n"
|
||||
f"Дата: {state['date']}\n"
|
||||
f"Время: {state['start']}–{state['end']}\n"
|
||||
f"Сопровождающий: {state['escort_name']} [{state['escort_id']}]\n"
|
||||
f"Котёнок: {state['kitten_name']} [{state['kitten_id']}]\n"
|
||||
f"Статус: {state['kitten_independence']}\n"
|
||||
"Подтвердить? Ответьте «да» или «нет»."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _bulk_hint(text: str) -> bool:
|
||||
return bool(re.search(r"\b\d{1,2}:\d{2}\b", text) and "|" in text and "[" in text)
|
||||
|
||||
def _start_bulk(self, peer_id: int, text: str) -> str | None:
|
||||
command = text.strip()
|
||||
if not command.startswith("/"):
|
||||
natural = parse_natural_bulk(command)
|
||||
if natural is not None:
|
||||
fields, _ = natural
|
||||
self._states[peer_id] = fields
|
||||
return "Я нашёл часть данных. " + self._ask_next(self._states[peer_id])
|
||||
if self._bulk_hint(command):
|
||||
return "Похоже, здесь данные для ЛУ или ЗУ. Укажите навык: ЛУ или ЗУ."
|
||||
return None
|
||||
if command.lower() in ("/лу", "/зу"):
|
||||
self._states[peer_id] = {"mode": "coaching", "skill": "ЛУ" if command.lower() == "/лу" else "ЗУ"}
|
||||
return self._ask_next(self._states[peer_id])
|
||||
if command.lower().startswith(("/лу ", "/лазание ", "/зу ", "/зоркость ")):
|
||||
try:
|
||||
parsed = parse_text_command(command)
|
||||
except (ValueError, IndexError) as exc:
|
||||
return f"Не удалось распознать данные: {exc}. Проверьте формат или начните с команды и отвечайте на вопросы по одному."
|
||||
independence_provided = parsed.pop("_independence_provided", False)
|
||||
if not parsed.get("kitten_independence") or not independence_provided:
|
||||
parsed.pop("kitten_independence", None)
|
||||
parsed["mode"] = "coaching"
|
||||
self._states[peer_id] = parsed
|
||||
return "Данные распознаны, но не указан статус котёнка. Ответьте: самостоятельно или несамостоятельно."
|
||||
self._states[peer_id] = {**parsed, "confirm": True}
|
||||
return self._confirmation(self._states[peer_id])
|
||||
if command.lower() in ("/урок", "/тренировка"):
|
||||
self._states[peer_id] = {"mode": "training"}
|
||||
return self._ask_next(self._states[peer_id])
|
||||
if command.lower() in ("/осмотр", "/осмотры"):
|
||||
self._states[peer_id] = {"mode": "inspection"}
|
||||
return self._ask_next(self._states[peer_id])
|
||||
if command.lower().startswith(("/урок ", "/тренировка ", "/осмотр ", "/осмотры ")):
|
||||
try:
|
||||
parsed = parse_text_command(command)
|
||||
except (ValueError, IndexError) as exc:
|
||||
return f"Не удалось распознать данные скопом: {exc}. Проверьте запись или начните ввод по одному вопросу."
|
||||
self._states[peer_id] = parsed
|
||||
return self._ask_next(self._states[peer_id])
|
||||
return None
|
||||
|
||||
def _consume_field(self, state: dict[str, Any], text: str) -> str:
|
||||
key = next((key for key, _ in self._ORDERS[state["mode"]] if not self._has_field(state, key)), None)
|
||||
if key == "date":
|
||||
if not re.fullmatch(r"\d{2}\.\d{2}", text):
|
||||
return "Дата должна быть в формате ДД.ММ, например 15.08."
|
||||
state[key] = text
|
||||
elif key == "skill":
|
||||
value = text.lower()
|
||||
if value in ("лу", "лазание"):
|
||||
state[key] = "ЛУ"
|
||||
elif value in ("зу", "зоркость"):
|
||||
state[key] = "ЗУ"
|
||||
else:
|
||||
return "Ответьте «ЛУ» для лазания или «ЗУ» для зоркости."
|
||||
elif key in ("start", "end"):
|
||||
from .domain import parse_clock
|
||||
try:
|
||||
parse_clock(text)
|
||||
except ValueError as exc:
|
||||
return str(exc)
|
||||
state[key] = text
|
||||
elif key == "escort":
|
||||
try:
|
||||
state["escort_name"], state["escort_id"] = _person(text)
|
||||
except ValueError as exc:
|
||||
return str(exc)
|
||||
state[key] = True
|
||||
elif key == "kitten":
|
||||
try:
|
||||
state["kitten_name"], state["kitten_id"] = _person(text)
|
||||
except ValueError as exc:
|
||||
return str(exc)
|
||||
state[key] = True
|
||||
elif key == "independence":
|
||||
value = self._independence(text)
|
||||
if value is None:
|
||||
return "Ответьте «самостоятельный» или «несамостоятельный» (подойдут и другие формы слова)."
|
||||
state["kitten_independence"] = value
|
||||
state[key] = True
|
||||
elif key == "place":
|
||||
value = text.lower()
|
||||
if value not in ("дупло", "расщелина"):
|
||||
return "Напишите «дупло» или «расщелина»."
|
||||
state["place"] = value
|
||||
elif key == "inspections":
|
||||
if not text.isdigit() or int(text) < 0:
|
||||
return "Количество осмотров должно быть целым числом."
|
||||
state["inspections"] = int(text)
|
||||
elif key == "character":
|
||||
try:
|
||||
name, character_id = _person(text)
|
||||
except ValueError:
|
||||
name = None
|
||||
character_id = None
|
||||
pending_name = state.get("_character_name", state.get("character_name"))
|
||||
pending_id = state.get("_character_id", state.get("character_id"))
|
||||
if name is not None and character_id is not None:
|
||||
self.identity_directory.remember(name=name, character_id=character_id)
|
||||
state["character_name"], state["character_id"] = name, character_id
|
||||
state.pop("_character_name", None)
|
||||
state.pop("_character_id", None)
|
||||
elif pending_name or pending_id:
|
||||
state.pop("character_name", None)
|
||||
state.pop("character_id", None)
|
||||
state.pop("_character_name", None)
|
||||
state.pop("_character_id", None)
|
||||
if pending_name and text.isdigit():
|
||||
name, character_id = pending_name, int(text)
|
||||
elif pending_id and text:
|
||||
name, character_id = text, pending_id
|
||||
else:
|
||||
return "Введите недостающий ID или имя персонажа."
|
||||
self.identity_directory.remember(name=name, character_id=character_id)
|
||||
state["character_name"], state["character_id"] = name, character_id
|
||||
elif re.fullmatch(r"\d+", text):
|
||||
character_id = int(text)
|
||||
identity = self.identity_directory.resolve(character_id=character_id)
|
||||
if identity:
|
||||
state["character_name"], state["character_id"] = identity.name, identity.character_id
|
||||
else:
|
||||
state["_character_id"] = character_id
|
||||
return self.identity_directory.suggest(character_id=character_id) + " Введите имя, чтобы сохранить связку."
|
||||
elif text:
|
||||
identity = self.identity_directory.resolve(name=text)
|
||||
if identity:
|
||||
state["character_name"], state["character_id"] = identity.name, identity.character_id
|
||||
else:
|
||||
state["_character_name"] = text
|
||||
return self.identity_directory.suggest(name=text) + " Введите ID, чтобы сохранить связку."
|
||||
else:
|
||||
return "Введите имя или ID персонажа."
|
||||
elif key == "resources":
|
||||
if text.lower() in ("без ресурсов", "пропустить", "нет ресурсов"):
|
||||
state["resources"] = []
|
||||
else:
|
||||
resources = []
|
||||
for item in text.split(","):
|
||||
if "=" not in item:
|
||||
return "Ресурсы укажите так: вьюнок=-2, паук=1 — или напишите «без ресурсов»."
|
||||
name, amount = item.split("=", 1)
|
||||
try:
|
||||
resources.append([name.strip(), int(amount.strip())])
|
||||
except ValueError:
|
||||
return "Количество ресурса должно быть целым числом."
|
||||
state["resources"] = resources
|
||||
return self._ask_next(state)
|
||||
|
||||
def handle(self, peer_id: int, text: str, user_id: int | None = None) -> str:
|
||||
text = text.strip()
|
||||
actor_id = user_id or peer_id
|
||||
onboarding_response = self._ensure_profile(actor_id, text)
|
||||
if onboarding_response is not None:
|
||||
return onboarding_response
|
||||
if text.lower() in ("/отмена", "отмена", "нет") and actor_id in self._states:
|
||||
self._reset(actor_id)
|
||||
return "Текущий ввод отменён. Для нового отчёта используйте /лу, /зу или /help."
|
||||
state = self._states.get(actor_id)
|
||||
if state and state.get("confirm"):
|
||||
if text.lower() in ("да", "подтвердить", "подтверждаю"):
|
||||
payload = {key: value for key, value in state.items() if key not in {"confirm", "escort", "kitten", "character", "independence", "_independence_provided"}}
|
||||
response = calculate_payload(payload)
|
||||
if self.calculation_store:
|
||||
self.calculation_store.save(
|
||||
actor_id=actor_id, source="vk", payload=payload,
|
||||
response=response,
|
||||
)
|
||||
self._reset(actor_id)
|
||||
return response["message"]
|
||||
return "Не подтверждено. Ответьте «да» для формирования сообщения или «нет» для отмены."
|
||||
if text.lower() in ("/help", "help", "/start", "start"):
|
||||
return HELP_TEXT
|
||||
if not state:
|
||||
response = self._start_bulk(actor_id, text)
|
||||
if response is not None:
|
||||
return response
|
||||
return "Начните с /лу или /зу. Для списка команд отправьте /help."
|
||||
try:
|
||||
return self._consume_field(state, text)
|
||||
except (ApiError, ValueError) as exc:
|
||||
return str(exc)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
token = os.environ["VK_GROUP_TOKEN"]
|
||||
group_id = int(os.environ["VK_GROUP_ID"])
|
||||
version = os.getenv("VK_API_VERSION", "5.199")
|
||||
bot = BelkiBot(VkApiClient(token, version), group_id)
|
||||
bot.run_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB_ROOT = ROOT / "web"
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
server_version = "BelkiCalculator/0.1"
|
||||
|
||||
def _json(self, status: int, body: dict) -> None:
|
||||
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(encoded)))
|
||||
self.end_headers()
|
||||
self.wfile.write(encoded)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
if self.path in ("/health", "/api/health"):
|
||||
self._json(200, {"status": "ok"})
|
||||
return
|
||||
if self.path in ("/", "/calculator.html"):
|
||||
self._file(WEB_ROOT / "calculator.html")
|
||||
return
|
||||
requested = unquote(urlparse(self.path).path).lstrip("/")
|
||||
candidate = (WEB_ROOT / requested).resolve()
|
||||
if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents:
|
||||
self._file(candidate)
|
||||
return
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
|
||||
def _file(self, path: Path) -> None:
|
||||
content = path.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", mimetypes.guess_type(path.name)[0] or "application/octet-stream")
|
||||
self.send_header("Content-Length", str(len(content)))
|
||||
self.end_headers()
|
||||
self.wfile.write(content)
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
if self.path not in ("/api/calculate", "/api/inspect-bulk", "/api/resolve-identity"):
|
||||
self._json(404, {"error": "Не найдено"})
|
||||
return
|
||||
try:
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
payload = json.loads(self.rfile.read(length))
|
||||
if self.path == "/api/inspect-bulk":
|
||||
self._json(200, inspect_bulk_payload(payload))
|
||||
elif self.path == "/api/resolve-identity":
|
||||
self._json(200, resolve_identity_payload(payload))
|
||||
else:
|
||||
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
|
||||
except ApiError as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
except (ValueError, json.JSONDecodeError) as exc:
|
||||
self._json(400, {"error": str(exc)})
|
||||
except Exception:
|
||||
self._json(500, {"error": "Внутренняя ошибка калькулятора"})
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
if os.getenv("BELKI_ACCESS_LOG", "0") == "1":
|
||||
super().log_message(format, *args)
|
||||
|
||||
|
||||
def serve() -> None:
|
||||
host = os.getenv("BELKI_HOST", "0.0.0.0")
|
||||
port = int(os.getenv("BELKI_PORT", "8080"))
|
||||
ThreadingHTTPServer((host, port), Handler).serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve()
|
||||
@@ -0,0 +1 @@
|
||||
psycopg[binary]==3.3.4
|
||||
@@ -0,0 +1,72 @@
|
||||
import unittest
|
||||
import sqlite3
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from app.belki.api import ApiError, calculate_payload, inspect_bulk_payload, resolve_identity_payload
|
||||
from app.belki.history import CalculationStore
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
def test_calculate_coaching_payload(self):
|
||||
response = calculate_payload(
|
||||
{
|
||||
"mode": "coaching",
|
||||
"date": "15.08",
|
||||
"skill": "ЛУ",
|
||||
"start": "00:52",
|
||||
"end": "01:52",
|
||||
"escort_name": "Дикая Вишня",
|
||||
"escort_id": 1604614,
|
||||
"kitten_name": "Котёнок",
|
||||
"kitten_id": 1676767,
|
||||
"kitten_independence": "самостоятельно",
|
||||
}
|
||||
)
|
||||
self.assertEqual(response["result"]["minutes"], 60)
|
||||
self.assertIn("Баллы белки: 12", response["message"])
|
||||
|
||||
def test_calculate_rejects_unknown_mode(self):
|
||||
with self.assertRaises(ApiError):
|
||||
calculate_payload({"mode": "unknown"})
|
||||
|
||||
def test_calculate_inspection_payload(self):
|
||||
response = calculate_payload(
|
||||
{
|
||||
"mode": "inspection",
|
||||
"character_name": "Дикая Вишня",
|
||||
"character_id": 1604614,
|
||||
"place": "дупло",
|
||||
"inspections": 6,
|
||||
"resources": [["вьюнок", -2], ["паук", 1]],
|
||||
}
|
||||
)
|
||||
self.assertIn("осмотрел(а) дупло 6 раз", response["message"])
|
||||
|
||||
def test_bulk_inspection_payload_explains_missing_fields(self):
|
||||
response = inspect_bulk_payload({"text": "/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]"})
|
||||
self.assertEqual(response["status"], "needs_clarification")
|
||||
self.assertTrue(response["questions"])
|
||||
|
||||
def test_identity_resolution_without_directory_requests_missing_half(self):
|
||||
response = resolve_identity_payload({"character_id": 1617140})
|
||||
self.assertEqual(response["status"], "needs_input")
|
||||
self.assertIn("имя", response["message"].lower())
|
||||
|
||||
def test_calculation_store_persists_full_record(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = f"{directory}/history.sqlite3"
|
||||
store = CalculationStore(sqlite_path=path)
|
||||
response = calculate_payload({
|
||||
"mode": "training", "escort_name": "Дикая Вишня", "escort_id": 1604614,
|
||||
"kitten_name": "Серолап", "kitten_id": 1617140,
|
||||
})
|
||||
record_id = store.save(actor_id=700, source="vk", payload={"mode": "training"}, response=response)
|
||||
self.assertGreater(record_id, 0)
|
||||
with sqlite3.connect(path) as connection:
|
||||
row = connection.execute("SELECT actor_id, mode, source, message FROM calculations").fetchone()
|
||||
self.assertEqual(row[:3], (700, "training", "vk"))
|
||||
self.assertIn("25", row[3])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,115 @@
|
||||
import unittest
|
||||
|
||||
from app.belki.domain import (
|
||||
CoachingSession,
|
||||
InspectionReport,
|
||||
TrainingSession,
|
||||
calculate_coaching,
|
||||
calculate_training,
|
||||
format_clock,
|
||||
parse_clock,
|
||||
)
|
||||
from app.belki.reports import render_coaching, render_inspection, render_training
|
||||
|
||||
|
||||
class ClockTests(unittest.TestCase):
|
||||
def test_duration_supports_midnight(self):
|
||||
self.assertEqual(parse_clock("23:55"), 23 * 60 + 55)
|
||||
self.assertEqual(format_clock(parse_clock("23:05")), "23:05")
|
||||
self.assertEqual(
|
||||
CoachingSession.duration_minutes("23:55", "00:10"),
|
||||
15,
|
||||
)
|
||||
|
||||
def test_invalid_clock_is_rejected(self):
|
||||
with self.assertRaises(ValueError):
|
||||
parse_clock("5:5")
|
||||
|
||||
|
||||
class CalculationTests(unittest.TestCase):
|
||||
def test_self_sufficient_kitten(self):
|
||||
result = calculate_coaching(
|
||||
CoachingSession(
|
||||
date="15.08",
|
||||
skill="ЛУ",
|
||||
start="00:52",
|
||||
end="01:52",
|
||||
escort_name="Дикая Вишня",
|
||||
escort_id=1604614,
|
||||
kitten_name="Котёнок",
|
||||
kitten_id=1676767,
|
||||
kitten_independence="самостоятельно",
|
||||
)
|
||||
)
|
||||
self.assertEqual(result.minutes, 60)
|
||||
self.assertEqual(result.escort_points, 12)
|
||||
self.assertEqual(result.kitten_points, 24)
|
||||
|
||||
def test_non_self_kitten_and_extra_companion(self):
|
||||
result = calculate_coaching(
|
||||
CoachingSession(
|
||||
date="15.08",
|
||||
skill="ЗУ",
|
||||
start="11:00",
|
||||
end="12:00",
|
||||
escort_name="Белка",
|
||||
escort_id=1,
|
||||
kitten_name="Первый",
|
||||
kitten_id=2,
|
||||
kitten_independence="несамостоятельно",
|
||||
extra_kittens=(
|
||||
("Второй", 3, "несамостоятельно"),
|
||||
("Третий", 4, "самостоятельно"),
|
||||
),
|
||||
)
|
||||
)
|
||||
self.assertEqual(result.escort_points, 24)
|
||||
self.assertEqual(result.kitten_points, 24)
|
||||
|
||||
def test_training_is_fixed(self):
|
||||
self.assertEqual(calculate_training(TrainingSession("Белка", 1, "Котёнок", 2)).points, 25)
|
||||
|
||||
|
||||
class ReportTests(unittest.TestCase):
|
||||
def test_coaching_report_contains_new_fields_and_reminder(self):
|
||||
session = CoachingSession(
|
||||
date="15.08",
|
||||
skill="ЛУ",
|
||||
start="11:00",
|
||||
end="11:20",
|
||||
escort_name="Дикая Вишня",
|
||||
escort_id=1604614,
|
||||
kitten_name="Серолап",
|
||||
kitten_id=1617140,
|
||||
kitten_independence="несамостоятельно",
|
||||
)
|
||||
text = render_coaching(session, calculate_coaching(session))
|
||||
self.assertIn("15.08 [ЛУ]", text)
|
||||
self.assertIn("Время: 11:00–11:20 [20 минут]", text)
|
||||
self.assertIn("Сопровождающий: Дикая Вишня [1604614]", text)
|
||||
self.assertIn("Баллы белки: 6", text)
|
||||
self.assertIn("Баллы бельчонка: 8", text)
|
||||
self.assertIn("истории", text)
|
||||
|
||||
def test_training_report_is_separate(self):
|
||||
text = render_training(TrainingSession("Белка", 1, "Котёнок", 2))
|
||||
self.assertIn("#урок", text)
|
||||
self.assertIn("25", text)
|
||||
|
||||
def test_inspection_report_lists_zero_and_resources(self):
|
||||
text = render_inspection(
|
||||
InspectionReport(
|
||||
character_name="Дикая Вишня",
|
||||
character_id=1604614,
|
||||
place="дупло",
|
||||
inspections=6,
|
||||
resources=(("вьюнок", -2), ("паук", 1)),
|
||||
)
|
||||
)
|
||||
self.assertIn("осмотрел(а) дупло 6 раз", text)
|
||||
self.assertIn("- 2 вьюнок", text)
|
||||
self.assertIn("+1 паук", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,33 @@
|
||||
import unittest
|
||||
|
||||
from app.belki.vk_bot import (
|
||||
HELP_TEXT,
|
||||
build_message_request,
|
||||
parse_text_command,
|
||||
)
|
||||
|
||||
|
||||
class VkBotTests(unittest.TestCase):
|
||||
def test_parse_coaching_command(self):
|
||||
command = parse_text_command(
|
||||
"/лу 15.08 11:00 11:20 | Дикая Вишня [1604614] | Серолап [1617140] | самостоятельно"
|
||||
)
|
||||
self.assertEqual(command["mode"], "coaching")
|
||||
self.assertEqual(command["escort_id"], 1604614)
|
||||
self.assertEqual(command["kitten_id"], 1617140)
|
||||
|
||||
def test_parse_help(self):
|
||||
self.assertEqual(parse_text_command("/help"), {"mode": "help"})
|
||||
self.assertIn("/лу", HELP_TEXT)
|
||||
self.assertIn("Беличья нора", HELP_TEXT)
|
||||
|
||||
def test_message_request_never_omits_random_id(self):
|
||||
request = build_message_request(123, "Готово", "secret", "5.199", random_id=77)
|
||||
self.assertEqual(request["peer_id"], 123)
|
||||
self.assertEqual(request["random_id"], 77)
|
||||
self.assertEqual(request["access_token"], "secret")
|
||||
self.assertEqual(request["v"], "5.199")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,148 @@
|
||||
import unittest
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from app.belki.identity import Identity, IdentityDirectory
|
||||
from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text
|
||||
|
||||
|
||||
class VkConversationTests(unittest.TestCase):
|
||||
def test_help_is_a_neutral_faq(self):
|
||||
self.assertIn("Беличья нора — помощь", HELP_TEXT)
|
||||
self.assertIn("Как отправить данные", HELP_TEXT)
|
||||
self.assertIn("/отмена", HELP_TEXT)
|
||||
self.assertNotIn("Для детей", HELP_TEXT)
|
||||
|
||||
def test_step_by_step_coaching_dialog(self):
|
||||
dialog = BelkiDialog()
|
||||
self.assertIn("дат", dialog.handle(77, "/лу").lower())
|
||||
self.assertIn("начал", dialog.handle(77, "15.08").lower())
|
||||
self.assertIn("конец", dialog.handle(77, "11:00").lower())
|
||||
self.assertIn("сопровождающ", dialog.handle(77, "11:20").lower())
|
||||
self.assertIn("котён", dialog.handle(77, "Дикая Вишня [1604614]").lower())
|
||||
self.assertIn("самостоятель", dialog.handle(77, "Серолап [1617140]").lower())
|
||||
confirmation = dialog.handle(77, "самостоятельно")
|
||||
self.assertIn("подтверд", confirmation.lower())
|
||||
report = dialog.handle(77, "да")
|
||||
self.assertIn("Баллы белки: 4", report)
|
||||
|
||||
def test_bulk_input_is_detected_and_confirmed(self):
|
||||
dialog = BelkiDialog()
|
||||
confirmation = dialog.handle(
|
||||
88,
|
||||
"/лу 15.08 11:00 11:20 | Дикая Вишня [1604614] | Серолап [1617140] | самостоятельно",
|
||||
)
|
||||
self.assertIn("распознал", confirmation.lower())
|
||||
self.assertIn("11:00", confirmation)
|
||||
self.assertIn("подтверд", confirmation.lower())
|
||||
report = dialog.handle(88, "да")
|
||||
self.assertIn("15.08 [ЛУ]", report)
|
||||
|
||||
def test_bulk_without_skill_requests_clarification(self):
|
||||
dialog = BelkiDialog()
|
||||
response = dialog.handle(99, "15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
|
||||
self.assertIn("ЛУ", response)
|
||||
self.assertIn("ЗУ", response)
|
||||
|
||||
def test_cancel_clears_dialog(self):
|
||||
dialog = BelkiDialog()
|
||||
dialog.handle(1, "/лу")
|
||||
self.assertIn("отмен", dialog.handle(1, "/отмена").lower())
|
||||
|
||||
def test_bulk_inspector_returns_fields_and_missing_questions(self):
|
||||
inspected = inspect_bulk_text("/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
|
||||
self.assertEqual(inspected["status"], "needs_clarification")
|
||||
self.assertIn("skill", inspected["fields"])
|
||||
self.assertIn("самостоятель", " ".join(inspected["questions"]).lower())
|
||||
|
||||
def test_bulk_inspector_detects_plain_text_without_skill(self):
|
||||
inspected = inspect_bulk_text("15.08 11:00 11:20 | Белка [1] | Котёнок [2]")
|
||||
self.assertEqual(inspected["status"], "needs_clarification")
|
||||
self.assertIn("ЛУ", " ".join(inspected["questions"]))
|
||||
|
||||
def test_natural_bulk_input_needs_no_pipes(self):
|
||||
dialog = BelkiDialog()
|
||||
response = dialog.handle(101, "15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140")
|
||||
self.assertIn("ЛУ", response)
|
||||
self.assertIn("ЗУ", response)
|
||||
response = dialog.handle(101, "ЛУ")
|
||||
self.assertIn("самостоятель", response.lower())
|
||||
response = dialog.handle(101, "самостоятельно")
|
||||
self.assertIn("подтверд", response.lower())
|
||||
|
||||
def test_training_supports_stepwise_and_natural_bulk(self):
|
||||
dialog = BelkiDialog()
|
||||
self.assertIn("сопровождающ", dialog.handle(102, "/урок").lower())
|
||||
self.assertIn("котён", dialog.handle(102, "Дикая Вишня [1604614]").lower())
|
||||
confirmation = dialog.handle(102, "Серолап [1617140]")
|
||||
self.assertIn("25", confirmation)
|
||||
self.assertIn("балл", dialog.handle(102, "да").lower())
|
||||
|
||||
natural = dialog.handle(103, "урок Дикая Вишня 1604614 Серолап 1617140")
|
||||
self.assertIn("25", natural)
|
||||
self.assertIn("подтверд", natural.lower())
|
||||
|
||||
def test_inspection_supports_stepwise_and_id_only_character(self):
|
||||
directory = IdentityDirectory([Identity("Серолап", 1617140)])
|
||||
dialog = BelkiDialog(directory)
|
||||
self.assertIn("место", dialog.handle(104, "/осмотр").lower())
|
||||
self.assertIn("сколько", dialog.handle(104, "дупло").lower())
|
||||
self.assertIn("персонаж", dialog.handle(104, "6").lower())
|
||||
self.assertIn("ресурс", dialog.handle(104, "1617140").lower())
|
||||
confirmation = dialog.handle(104, "без ресурсов")
|
||||
self.assertIn("Серолап", confirmation)
|
||||
self.assertIn("подтверд", confirmation.lower())
|
||||
|
||||
def test_inspection_character_without_directory_offers_pairing(self):
|
||||
dialog = BelkiDialog(IdentityDirectory())
|
||||
dialog.handle(105, "/осмотр")
|
||||
dialog.handle(105, "дупло")
|
||||
dialog.handle(105, "1")
|
||||
response = dialog.handle(105, "1617140")
|
||||
self.assertIn("связк", response.lower())
|
||||
dialog.handle(105, "Серолап")
|
||||
confirmation = dialog.handle(105, "без ресурсов")
|
||||
self.assertIn("Серолап", confirmation)
|
||||
|
||||
def test_natural_inspection_accepts_character_id_without_name(self):
|
||||
inspected = inspect_bulk_text("осмотр дупло 6 1617140 без ресурсов")
|
||||
self.assertEqual(inspected["fields"]["character_id"], 1617140)
|
||||
self.assertIn("имени", " ".join(inspected["questions"]).lower())
|
||||
|
||||
def test_identity_directory_persists_pairs_in_sqlite(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
path = f"{directory}/identities.sqlite3"
|
||||
first = IdentityDirectory(db_path=path)
|
||||
first.remember(name="Серолап", character_id=1617140)
|
||||
second = IdentityDirectory(db_path=path)
|
||||
self.assertEqual(second.resolve(character_id=1617140).name, "Серолап")
|
||||
self.assertEqual(second.resolve(name="Серолап").character_id, 1617140)
|
||||
|
||||
def test_onboarding_remembers_author_and_greets_by_name(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
identities = IdentityDirectory(db_path=f"{directory}/identities.sqlite3")
|
||||
dialog = BelkiDialog(identities, onboarding=True)
|
||||
self.assertIn("представься", dialog.handle(500, "/лу", user_id=700).lower())
|
||||
welcome = dialog.handle(500, "Дикая Вишня [1604614]", user_id=700)
|
||||
self.assertIn("Привет, Дикая Вишня", welcome)
|
||||
self.assertIn("/осмотр", welcome)
|
||||
self.assertIn("дат", dialog.handle(500, "/лу", user_id=700).lower())
|
||||
|
||||
restarted = BelkiDialog(IdentityDirectory(db_path=f"{directory}/identities.sqlite3"), onboarding=True)
|
||||
self.assertIn("дат", restarted.handle(500, "/лу", user_id=700).lower())
|
||||
|
||||
def test_independence_accepts_adjectival_forms(self):
|
||||
dialog = BelkiDialog()
|
||||
dialog.handle(501, "/лу")
|
||||
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
|
||||
dialog.handle(501, answer)
|
||||
confirmation = dialog.handle(501, "Самостоятельный")
|
||||
self.assertIn("самостоятельно", confirmation.lower())
|
||||
|
||||
dialog.handle(502, "/лу")
|
||||
for answer in ("15.08", "11:00", "11:20", "Дикая Вишня [1604614]", "Серолап [1617140]"):
|
||||
dialog.handle(502, answer)
|
||||
self.assertIn("несамостоятельно", dialog.handle(502, "несам").lower())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,204 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Беличья нора — калькулятор отчётов</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; font-family: system-ui, sans-serif; }
|
||||
body { margin: 0; background: #171516; color: #f4eeee; }
|
||||
main { width: min(980px, calc(100% - 32px)); margin: 32px auto; }
|
||||
h1 { margin-bottom: 4px; }
|
||||
.muted { color: #b9aaad; }
|
||||
.tabs { display: flex; gap: 8px; flex-wrap: wrap; margin: 24px 0 16px; }
|
||||
button, select, input, textarea { font: inherit; }
|
||||
button { cursor: pointer; border: 1px solid #80656c; border-radius: 8px; padding: 9px 14px; background: #33262a; color: inherit; }
|
||||
button.active, button.primary { background: #d59b62; color: #211818; border-color: #d59b62; }
|
||||
.panel { background: #251e20; border: 1px solid #4a383d; border-radius: 12px; padding: 20px; }
|
||||
.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; }
|
||||
label { display: grid; gap: 6px; color: #d8cace; }
|
||||
input, select, textarea { width: 100%; box-sizing: border-box; border: 1px solid #665159; border-radius: 7px; padding: 9px; background: #171516; color: inherit; }
|
||||
textarea { min-height: 210px; resize: vertical; }
|
||||
.wide { grid-column: 1 / -1; }
|
||||
.actions { display: flex; gap: 10px; margin-top: 18px; }
|
||||
.bulk { margin-bottom: 20px; padding-bottom: 18px; border-bottom: 1px solid #4a383d; }
|
||||
.bulk textarea { min-height: 100px; margin: 8px 0; }
|
||||
.bulk-status { white-space: pre-wrap; }
|
||||
.identity-tools { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
dialog { max-width: min(440px, calc(100% - 32px)); background: #251e20; color: inherit; border: 1px solid #80656c; border-radius: 10px; padding: 20px; }
|
||||
dialog::backdrop { background: #0009; }
|
||||
.result { margin-top: 20px; }
|
||||
.hidden { display: none; }
|
||||
.error { color: #ff9f9f; white-space: pre-wrap; }
|
||||
@media (max-width: 700px) { .grid { grid-template-columns: 1fr; } .wide { grid-column: auto; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Беличья нора — калькулятор отчётов</h1>
|
||||
<p class="muted">Один заход — один отчёт. Скриншоты к готовому отчёту нужно приложить вручную.</p>
|
||||
|
||||
<div class="tabs" role="tablist">
|
||||
<button class="active" data-mode="coaching">Прокачка ЛУ/ЗУ</button>
|
||||
<button data-mode="training">Тренировка</button>
|
||||
<button data-mode="inspection">Осмотры</button>
|
||||
</div>
|
||||
|
||||
<section class="panel">
|
||||
<div class="bulk">
|
||||
<strong>Быстрый ввод</strong>
|
||||
<p class="muted">Вставьте данные одной строкой — символы <code>|</code> не нужны. Мы распознаем заполненные поля и подскажем, что ещё указать.</p>
|
||||
<textarea id="bulkText" placeholder="15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140"></textarea>
|
||||
<button type="button" id="inspectBulk">Распознать данные</button>
|
||||
<p class="muted bulk-status" id="bulkStatus"></p>
|
||||
</div>
|
||||
<form id="form">
|
||||
<div id="coaching" class="grid mode">
|
||||
<label>Дата<input name="date" value="15.08" required></label>
|
||||
<label>Навык<select name="skill"><option>ЛУ</option><option>ЗУ</option></select></label>
|
||||
<label>Начало<input name="start" type="time" value="11:00" required></label>
|
||||
<label>Конец<input name="end" type="time" value="11:20" required></label>
|
||||
<label>Имя сопровождающего<input name="escort_name" required></label>
|
||||
<label>ID сопровождающего<input name="escort_id" type="number" min="1" required></label>
|
||||
<label>Имя котёнка<input name="kitten_name" required></label>
|
||||
<label>ID котёнка<input name="kitten_id" type="number" min="1" required></label>
|
||||
<label>Котёнок<select name="kitten_independence"><option value="самостоятельно">самостоятельно</option><option value="несамостоятельно">несамостоятельно</option></select></label>
|
||||
</div>
|
||||
|
||||
<div id="training" class="grid mode hidden">
|
||||
<label>Имя сопровождающего<input name="escort_name"></label>
|
||||
<label>ID сопровождающего<input name="escort_id" type="number" min="1"></label>
|
||||
<label>Имя котёнка<input name="kitten_name"></label>
|
||||
<label>ID котёнка<input name="kitten_id" type="number" min="1"></label>
|
||||
</div>
|
||||
|
||||
<div id="inspection" class="grid mode hidden">
|
||||
<label>Имя персонажа<input name="character_name"></label>
|
||||
<label>ID персонажа<input name="character_id" type="number" min="1"></label>
|
||||
<div class="wide identity-tools"><button type="button" id="resolveIdentity">Найти связку имени и ID</button><span class="muted" id="identityStatus"></span></div>
|
||||
<label>Место<select name="place"><option>дупло</option><option>расщелина</option></select></label>
|
||||
<label>Количество осмотров<input name="inspections" type="number" min="0" value="0"></label>
|
||||
<label class="wide">Ресурсы, по одному на строку: название; количество<br><textarea name="resources" placeholder="вьюнок; -2 паук; 1"></textarea></label>
|
||||
</div>
|
||||
|
||||
<div class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div>
|
||||
</form>
|
||||
<div class="result hidden" id="result"><h2>Сообщение</h2><textarea id="message" readonly></textarea><p class="muted" id="summary"></p></div>
|
||||
<p class="error" id="error"></p>
|
||||
</section>
|
||||
</main>
|
||||
<dialog id="identityDialog">
|
||||
<p id="identityDialogText"></p>
|
||||
<label id="identityMissingLabel">Недостающее значение<input id="identityMissingValue"></label>
|
||||
<p class="muted">Связка сохранится в локальную базу и будет доступна в следующих расчётах.</p>
|
||||
<button type="button" id="saveIdentity">Добавить связку</button>
|
||||
<button type="button" id="closeIdentityDialog">Понятно</button>
|
||||
</dialog>
|
||||
<script>
|
||||
const form = document.querySelector('#form');
|
||||
const error = document.querySelector('#error');
|
||||
const result = document.querySelector('#result');
|
||||
const message = document.querySelector('#message');
|
||||
const summary = document.querySelector('#summary');
|
||||
const copy = document.querySelector('#copy');
|
||||
const bulkText = document.querySelector('#bulkText');
|
||||
const bulkStatus = document.querySelector('#bulkStatus');
|
||||
const identityStatus = document.querySelector('#identityStatus');
|
||||
const identityDialog = document.querySelector('#identityDialog');
|
||||
const identityDialogText = document.querySelector('#identityDialogText');
|
||||
const identityMissingLabel = document.querySelector('#identityMissingLabel');
|
||||
const identityMissingValue = document.querySelector('#identityMissingValue');
|
||||
let mode = 'coaching';
|
||||
function selectMode(nextMode) {
|
||||
mode = nextMode;
|
||||
document.querySelectorAll('[data-mode]').forEach(item => item.classList.toggle('active', item.dataset.mode === mode));
|
||||
document.querySelectorAll('.mode').forEach(panel => panel.classList.toggle('hidden', panel.id !== mode));
|
||||
error.textContent = '';
|
||||
}
|
||||
document.querySelectorAll('[data-mode]').forEach(button => button.addEventListener('click', () => selectMode(button.dataset.mode)));
|
||||
function setField(panel, name, value) {
|
||||
const field = document.querySelector(`#${panel} [name="${name}"]`);
|
||||
if (field && value !== undefined && value !== null) field.value = value;
|
||||
}
|
||||
document.querySelector('#inspectBulk').addEventListener('click', async () => {
|
||||
bulkStatus.textContent = '';
|
||||
try {
|
||||
const response = await fetch('/api/inspect-bulk', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({text: bulkText.value}) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось распознать данные');
|
||||
const fields = data.fields || {};
|
||||
if (fields.mode) selectMode(fields.mode);
|
||||
const target = fields.mode || mode;
|
||||
Object.entries(fields).forEach(([key, value]) => {
|
||||
if (['mode', 'raw', 'resources'].includes(key)) return;
|
||||
setField(target, key, value);
|
||||
});
|
||||
if (fields.resources) setField(target, 'resources', fields.resources.map(item => `${item[0]}; ${item[1]}`).join('\n'));
|
||||
bulkStatus.textContent = data.status === 'complete'
|
||||
? 'Данные распознаны. Проверьте поля и нажмите «Подготовить сообщение».'
|
||||
: `Нужно уточнить:\n${(data.questions || []).join('\n')}`;
|
||||
} catch (err) { bulkStatus.textContent = err.message; }
|
||||
});
|
||||
document.querySelector('#resolveIdentity').addEventListener('click', async () => {
|
||||
identityStatus.textContent = '';
|
||||
try {
|
||||
const name = document.querySelector('#inspection [name="character_name"]').value.trim();
|
||||
const characterId = document.querySelector('#inspection [name="character_id"]').value.trim();
|
||||
const response = await fetch('/api/resolve-identity', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, character_id: characterId}) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось проверить связку');
|
||||
if (data.status === 'found') {
|
||||
setField('inspection', 'character_name', data.name);
|
||||
setField('inspection', 'character_id', data.character_id);
|
||||
identityStatus.textContent = 'Связка найдена и подставлена.';
|
||||
} else {
|
||||
identityDialogText.textContent = data.message;
|
||||
const missing = name ? 'ID персонажа' : 'Имя персонажа';
|
||||
identityMissingLabel.firstChild.textContent = `Введите ${missing}`;
|
||||
identityMissingValue.value = '';
|
||||
identityMissingValue.type = name ? 'number' : 'text';
|
||||
if (identityDialog.showModal) identityDialog.showModal();
|
||||
else window.alert(data.message);
|
||||
}
|
||||
} catch (err) { identityStatus.textContent = err.message; }
|
||||
});
|
||||
document.querySelector('#saveIdentity').addEventListener('click', async () => {
|
||||
const nameField = document.querySelector('#inspection [name="character_name"]');
|
||||
const idField = document.querySelector('#inspection [name="character_id"]');
|
||||
const name = nameField.value.trim() || (identityMissingValue.type === 'text' ? identityMissingValue.value.trim() : '');
|
||||
const characterId = idField.value.trim() || (identityMissingValue.type === 'number' ? identityMissingValue.value.trim() : '');
|
||||
if (!name || !characterId) { identityDialogText.textContent = 'Нужно указать и имя, и ID персонажа.'; return; }
|
||||
const response = await fetch('/api/resolve-identity', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, character_id: characterId, remember: true}) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) { identityDialogText.textContent = data.error || 'Не удалось сохранить связку'; return; }
|
||||
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
|
||||
identityDialog.close(); identityStatus.textContent = 'Связка добавлена в текущий процесс.';
|
||||
});
|
||||
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
|
||||
function payload() {
|
||||
const data = {};
|
||||
document.querySelectorAll(`#${mode} [name]`).forEach(field => { data[field.name] = field.value; });
|
||||
data.mode = mode;
|
||||
['escort_id', 'kitten_id', 'character_id', 'inspections'].forEach(key => { if (data[key] !== undefined && data[key] !== '') data[key] = Number(data[key]); });
|
||||
if (mode === 'inspection') {
|
||||
data.resources = (data.resources || '').split('\n').map(line => line.trim()).filter(Boolean).map(line => {
|
||||
const [name, amount] = line.split(';').map(item => item.trim());
|
||||
return [name, Number(amount)];
|
||||
});
|
||||
}
|
||||
return data;
|
||||
}
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault(); error.textContent = '';
|
||||
try {
|
||||
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload()) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
|
||||
message.value = data.message; summary.textContent = data.result ? `Результат: ${JSON.stringify(data.result)}` : '';
|
||||
result.classList.remove('hidden'); copy.disabled = false;
|
||||
} catch (err) { error.textContent = err.message; }
|
||||
});
|
||||
copy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); copy.textContent = 'Скопировано'; setTimeout(() => copy.textContent = 'Скопировать', 1500); });
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user