New web ui

This commit is contained in:
nyan404 committed 2026-08-17 02:31:18 +03:00
1 parent a360fd9c63
commit caee27c3ea
11 files changed
+247 -15

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
{
"worktrees": {},
"sessions": {},
"tabOrder": {
"local": [
"pending:1"
]
}
}
+3
View File
@@ -19,3 +19,6 @@
## Notes ## Notes
- The build job waits for the DinD daemon and runs `docker info` before building. - The build job waits for the DinD daemon and runs `docker info` before building.
- Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig. - Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig.
## Agent Rules
- Zod `.describe()` on optional fields: always append `.optional()` — e.g. `zod.string().describe("…").optional()` — to avoid validation failures when the field is absent.
+1 -1
View File
@@ -37,7 +37,7 @@ python3 -m app.belki.vk_bot
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL. Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот скачивает фото, загружает его через API `image-hosting-web` и сохраняет постоянный `mirror_url`; админская панель показывает зеркальную ссылку. Без настройки API сохраняется исходная ссылка VK. Google Sheets пока не подключён. Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` защищён паролем `BELKI_WEB_PASSWORD` и позволяет выбрать несколько скриншотов; сервер загружает их на image host (в production — `https://img.nyan404.ru`) и сохраняет ссылки вместе с отчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же image host. Google Sheets пока не подключён.
Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака. Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака.
+2 -2
View File
@@ -87,8 +87,8 @@ class CoachingSession:
raise ValueError("Некорректный статус самостоятельности") raise ValueError("Некорректный статус самостоятельности")
statuses = (self.kitten_independence,) + tuple(independence for _, _, independence in self.extra_kittens) statuses = (self.kitten_independence,) + tuple(independence for _, _, independence in self.extra_kittens)
nonself_count = sum(status == "несамостоятельно" for status in statuses) nonself_count = sum(status == "несамостоятельно" for status in statuses)
if self.skill == "ЗУ" and len(set(statuses)) > 1: if self.skill == "ЗУ" and any(s != "самостоятельно" for s in statuses):
raise ValueError("Для ЗУ все котята в одном отчёте должны иметь одинаковый статус") raise ValueError("Для ЗУ все котята должны быть самостоятельными")
if self.skill == "ЛУ" and nonself_count > 1: if self.skill == "ЛУ" and nonself_count > 1:
raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок") raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок")
+6
View File
@@ -55,6 +55,12 @@ class ImageHostClient:
body = response.read() body = response.read()
content_type = response.headers.get_content_type() or "image/jpeg" content_type = response.headers.get_content_type() or "image/jpeg"
file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg" file_name = f"vk-{photo.get('owner_id', 'photo')}-{photo.get('id', 'upload')}.jpg"
return self.upload_bytes(body, file_name, content_type)
def upload_bytes(self, body: bytes, file_name: str, content_type: str = "image/jpeg") -> str | None:
"""Загружает произвольный файл на image-host и возвращает прямую ссылку."""
if not self.api_url or not body:
return None
initiate = self._request_json( initiate = self._request_json(
"/api/uploads/initiate", "/api/uploads/initiate",
{ {
+2 -2
View File
@@ -96,8 +96,8 @@ def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
def _validate_independence(skill: str, primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None: def _validate_independence(skill: str, primary: str, extras: tuple[tuple[str, int, str], ...] | list[tuple[str, int, str]]) -> None:
statuses = (primary,) + tuple(independence for _, _, independence in extras) statuses = (primary,) + tuple(independence for _, _, independence in extras)
if skill == "ЗУ" and len(set(statuses)) > 1: if skill == "ЗУ" and any(s != "самостоятельно" for s in statuses):
raise ValueError("Для ЗУ все котята в одном отчёте должны иметь одинаковый статус") raise ValueError("Для ЗУ все котята должны быть самостоятельными")
if skill == "ЛУ" and sum(status == "несамостоятельно" for status in statuses) > 1: if skill == "ЛУ" and sum(status == "несамостоятельно" for status in statuses) > 1:
raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок") raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок")
+105 -3
View File
@@ -1,19 +1,25 @@
from __future__ import annotations from __future__ import annotations
import json import json
import base64
import mimetypes import mimetypes
import os import os
import secrets
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse 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.identity import IdentityDirectory
from .belki.image_host import ImageHostClient
ROOT = Path(__file__).resolve().parents[1] 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
_WEB_SESSIONS: set[str] = set()
def history_store() -> CalculationStore: def history_store() -> CalculationStore:
@@ -23,6 +29,39 @@ def history_store() -> CalculationStore:
return _HISTORY_STORE return _HISTORY_STORE
def identity_dir() -> IdentityDirectory:
global _IDENTITY_DIR
if _IDENTITY_DIR is None:
_IDENTITY_DIR = IdentityDirectory.from_environment(persistent=True)
return _IDENTITY_DIR
_WEB_PROFILE_KEY = "web_user"
def save_profile(payload):
name = str(payload.get("name", "")).strip()
raw_id = payload.get("character_id")
try:
character_id = int(raw_id) if raw_id not in (None, "") else None
except (TypeError, ValueError):
raise ApiError("ID персонажа должно быть числом")
if not name or character_id is None:
raise ApiError("Нужно указать и имя, и ID персонажа")
identity = identity_dir().remember(name=name, character_id=character_id)
actor_id = int(_WEB_PROFILE_KEY.encode().hex(), 16) if isinstance(_WEB_PROFILE_KEY, str) else 0
identity_dir().remember_profile(actor_id=actor_id, name=name, character_id=character_id)
return {"status": "saved", "name": identity.name, "character_id": identity.character_id}
def get_profile():
actor_id = int(_WEB_PROFILE_KEY.encode().hex(), 16) if isinstance(_WEB_PROFILE_KEY, str) else 0
profile = identity_dir().profile(actor_id=actor_id)
if profile:
return {"status": "found", "name": profile.name, "character_id": profile.character_id}
return {"status": "not_found"}
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
server_version = "BelkiCalculator/0.1" server_version = "BelkiCalculator/0.1"
@@ -44,6 +83,27 @@ class Handler(BaseHTTPRequestHandler):
return False return False
return True return True
def _web_authorized(self) -> bool:
expected = os.getenv("BELKI_WEB_PASSWORD", "")
if not expected:
self._json(503, {"error": "Веб-доступ не настроен: задайте BELKI_WEB_PASSWORD"})
return False
cookies = self.headers.get("Cookie", "")
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
if token not in _WEB_SESSIONS:
self._json(401, {"error": "Требуется авторизация"})
return False
return True
def _json_with_cookie(self, status: int, body: dict, cookie: str) -> 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("Set-Cookie", cookie)
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
self.wfile.write(encoded)
def do_GET(self) -> None: # noqa: N802 def do_GET(self) -> None: # noqa: N802
path = urlparse(self.path).path path = urlparse(self.path).path
if path in ("/health", "/api/health"): if path in ("/health", "/api/health"):
@@ -67,6 +127,12 @@ 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/web/session":
expected = os.getenv("BELKI_WEB_PASSWORD", "")
cookies = self.headers.get("Cookie", "")
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
self._json(200, {"authenticated": bool(expected and token in _WEB_SESSIONS)})
return
requested = unquote(path).lstrip("/") requested = unquote(path).lstrip("/")
candidate = (WEB_ROOT / requested).resolve() candidate = (WEB_ROOT / requested).resolve()
if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents: if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents:
@@ -83,16 +149,52 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(content) self.wfile.write(content)
def do_POST(self) -> None: # noqa: N802 def do_POST(self) -> None: # noqa: N802
if self.path not in ("/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"):
self._json(404, {"error": "Не найдено"}) self._json(404, {"error": "Не найдено"})
return return
try: try:
length = int(self.headers.get("Content-Length", "0")) length = int(self.headers.get("Content-Length", "0"))
payload = json.loads(self.rfile.read(length)) payload = json.loads(self.rfile.read(length)) if length else {}
if self.path == "/api/inspect-bulk": if self.path == "/api/web/auth":
expected = os.getenv("BELKI_WEB_PASSWORD", "")
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
self._json(401, {"error": "Неверный пароль"})
return
token = secrets.token_urlsafe(32)
_WEB_SESSIONS.add(token)
self._json_with_cookie(200, {"authenticated": True}, f"belki_session={token}; Path=/; HttpOnly; SameSite=Lax")
elif self.path == "/api/web/logout":
cookies = self.headers.get("Cookie", "")
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
_WEB_SESSIONS.discard(token)
self._json_with_cookie(200, {"authenticated": False}, "belki_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
elif not self._web_authorized():
return
elif self.path == "/api/web/upload":
raw = str(payload.get("data", ""))
if "," in raw:
raw = raw.split(",", 1)[1]
try:
body = base64.b64decode(raw, validate=True)
except (ValueError, TypeError) as exc:
raise ApiError("Не удалось прочитать изображение") from exc
if len(body) > 15 * 1024 * 1024:
raise ApiError("Файл слишком большой (максимум 15 МБ)")
url = ImageHostClient(api_url=os.getenv("BELKI_IMAGE_HOST_API_URL", "https://img.nyan404.ru")).upload_bytes(
body, str(payload.get("name", "screenshot.jpg")), str(payload.get("type", "image/jpeg"))
)
if not url:
raise ApiError("Хранилище изображений не настроено")
self._json(200, {"url": url, "name": payload.get("name", "screenshot.jpg")})
elif self.path == "/api/inspect-bulk":
self._json(200, inspect_bulk_payload(payload)) self._json(200, inspect_bulk_payload(payload))
elif self.path == "/api/resolve-identity": elif self.path == "/api/resolve-identity":
self._json(200, resolve_identity_payload(payload)) self._json(200, resolve_identity_payload(payload))
elif self.path == "/api/save-profile":
self._json(200, save_profile(payload))
elif self.path == "/api/get-profile":
self._json(200, get_profile())
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 as exc:
+7 -2
View File
@@ -119,8 +119,13 @@ spec:
secretKeyRef: secretKeyRef:
name: belki-runtime name: belki-runtime
key: BELKI_ADMIN_PASSWORD key: BELKI_ADMIN_PASSWORD
- name: BELKI_WEB_PASSWORD
valueFrom:
secretKeyRef:
name: belki-runtime
key: BELKI_WEB_PASSWORD
- name: BELKI_IMAGE_HOST_API_URL - name: BELKI_IMAGE_HOST_API_URL
value: https://nyan.nyan404.ru value: https://img.nyan404.ru
readinessProbe: readinessProbe:
httpGet: httpGet:
path: /health path: /health
@@ -199,4 +204,4 @@ spec:
name: belki-runtime name: belki-runtime
key: BELKI_DATABASE_URL key: BELKI_DATABASE_URL
- name: BELKI_IMAGE_HOST_API_URL - name: BELKI_IMAGE_HOST_API_URL
value: https://nyan.nyan404.ru value: https://img.nyan404.ru
+1
View File
@@ -11,3 +11,4 @@ stringData:
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
POSTGRES_PASSWORD: replace-out-of-band POSTGRES_PASSWORD: replace-out-of-band
BELKI_ADMIN_PASSWORD: replace-out-of-band BELKI_ADMIN_PASSWORD: replace-out-of-band
BELKI_WEB_PASSWORD: replace-out-of-band
+2
View File
@@ -45,6 +45,8 @@
- 2026-08-16: replaced the unavailable `bitnami/kubectl:1.34` CI image with `alpine/k8s:1.36.2`, which matches the cluster minor version and includes the shell required by GitLab Runner. - 2026-08-16: replaced the unavailable `bitnami/kubectl:1.34` CI image with `alpine/k8s:1.36.2`, which matches the cluster minor version and includes the shell required by GitLab Runner.
- 2026-08-16: corrected coaching payout direction for non-self-sufficient kittens. The escort receives the 1-per-5-minutes base rate or 1.5x for non-self-sufficient ЛУ; kitten points are not reported. Added a 30-minute regression case. - 2026-08-16: corrected coaching payout direction for non-self-sufficient kittens. The escort receives the 1-per-5-minutes base rate or 1.5x for non-self-sufficient ЛУ; kitten points are not reported. Added a 30-minute regression case.
- 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: 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-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]`.
+109 -5
View File
@@ -21,23 +21,35 @@
textarea { min-height: 210px; resize: vertical; } textarea { min-height: 210px; resize: vertical; }
.wide { grid-column: 1 / -1; } .wide { grid-column: 1 / -1; }
.actions { display: flex; gap: 10px; margin-top: 18px; } .actions { display: flex; gap: 10px; margin-top: 18px; }
.quick-actions { display: flex; gap: 6px; margin-top: 4px; flex-wrap: wrap; }
.quick-actions button { padding: 4px 10px; font-size: 0.85em; border-width: 1px; }
.bulk { margin-bottom: 20px; padding-bottom: 18px; border-bottom: 1px solid #4a383d; } .bulk { margin-bottom: 20px; padding-bottom: 18px; border-bottom: 1px solid #4a383d; }
.bulk textarea { min-height: 100px; margin: 8px 0; } .bulk textarea { min-height: 100px; margin: 8px 0; }
.bulk-status { white-space: pre-wrap; } .bulk-status { white-space: pre-wrap; }
.identity-tools { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } .identity-tools { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.extra-kittens { display: grid; gap: 8px; } .extra-kittens { display: grid; gap: 8px; }
.extra-kitten { display: grid; grid-template-columns: 1fr 140px 180px auto; gap: 8px; align-items: end; } .extra-kitten { display: grid; grid-template-columns: 1fr 140px 180px auto; gap: 8px; align-items: end; }
.status-help { margin: -4px 0 0; font-size: .85rem; }
@media (max-width: 700px) { .extra-kitten { grid-template-columns: 1fr; } } @media (max-width: 700px) { .extra-kitten { grid-template-columns: 1fr; } }
dialog { max-width: min(440px, calc(100% - 32px)); background: #251e20; color: inherit; border: 1px solid #80656c; border-radius: 10px; padding: 20px; } 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; } dialog::backdrop { background: #0009; }
.result { margin-top: 20px; } .result { margin-top: 20px; }
.hidden { display: none; } .hidden { display: none; }
.error { color: #ff9f9f; white-space: pre-wrap; } .error { color: #ff9f9f; white-space: pre-wrap; }
.auth-panel { max-width: 460px; margin: 12vh auto; }
.auth-panel form { display: grid; gap: 12px; }
@media (max-width: 700px) { .grid { grid-template-columns: 1fr; } .wide { grid-column: auto; } } @media (max-width: 700px) { .grid { grid-template-columns: 1fr; } .wide { grid-column: auto; } }
</style> </style>
</head> </head>
<body> <body>
<main> <main>
<section class="panel auth-panel" id="webAuth">
<h2>Вход в калькулятор</h2>
<p class="muted">Введите пароль, чтобы создавать отчёты и загружать скриншоты.</p>
<form id="webAuthForm"><label>Пароль<input id="webPassword" type="password" autocomplete="current-password" required></label><button class="primary" type="submit">Войти</button></form>
<p class="error" id="webAuthError"></p>
</section>
<div id="webApp" class="hidden">
<h1>Беличья нора — калькулятор отчётов</h1> <h1>Беличья нора — калькулятор отчётов</h1>
<p class="muted">Один заход — один отчёт. Скриншоты к готовому отчёту нужно приложить вручную.</p> <p class="muted">Один заход — один отчёт. Скриншоты к готовому отчёту нужно приложить вручную.</p>
@@ -57,7 +69,9 @@
</div> </div>
<form id="form"> <form id="form">
<div id="coaching" class="grid mode"> <div id="coaching" class="grid mode">
<label>Дата<input name="date" value="15.08" required></label> <label>Дата<input name="date" value="15.08" required>
<div class="quick-actions"><button type="button" id="todayBtn" class="quick-btn">Сегодня</button></div>
</label>
<label>Навык<select name="skill"><option>ЛУ</option><option>ЗУ</option></select></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="start" type="time" value="11:00" required></label>
<label>Конец<input name="end" type="time" value="11:20" required></label> <label>Конец<input name="end" type="time" value="11:20" required></label>
@@ -65,7 +79,7 @@
<label>ID сопровождающего<input name="escort_id" type="number" min="1" required></label> <label>ID сопровождающего<input name="escort_id" type="number" min="1" required></label>
<label>Имя котёнка<input name="kitten_name" required></label> <label>Имя котёнка<input name="kitten_name" required></label>
<label>ID котёнка<input name="kitten_id" type="number" min="1" 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> <label>Котёнок<select name="kitten_independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select><span class="muted status-help" id="statusHelp">Для ЛУ можно указать не более одного несамостоятельного котёнка.</span></label>
<div class="wide extra-kittens"> <div class="wide extra-kittens">
<label>Дополнительные котята <span class="muted">(общие баллы не суммируются; 2-й ×1,5, следующие ×1,15)</span></label> <label>Дополнительные котята <span class="muted">(общие баллы не суммируются; 2-й ×1,5, следующие ×1,15)</span></label>
<div id="extraKittens"></div> <div id="extraKittens"></div>
@@ -86,14 +100,40 @@
<div class="wide identity-tools"><button type="button" id="resolveIdentity">Найти связку имени и ID</button><span class="muted" id="identityStatus"></span></div> <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>Место<select name="place"><option>дупло</option><option>расщелина</option></select></label>
<label>Количество осмотров<input name="inspections" type="number" min="0" value="0"></label> <label>Количество осмотров<input name="inspections" type="number" min="0" value="0"></label>
<label class="wide">Ресурсы, по одному на строку: название; количество<br><textarea name="resources" placeholder="вьюнок; 2&#10;паук; 1"></textarea></label> <label class="wide">Ресурсы, по одному на строку: название; количество<br>
<div class="quick-actions"><button type="button" id="noResourcesBtn" class="quick-btn">Без ресурсов</button></div>
<textarea name="resources" placeholder="вьюнок; 2&#10;паук; 1"></textarea></label>
</div> </div>
<label class="wide">Скриншоты отчёта<input id="screenshots" type="file" accept="image/*" multiple><span class="muted">Можно выбрать несколько фотографий. Они будут загружены на img.nyan404.ru.</span></label>
<div class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div> <div class="actions"><button class="primary" type="submit">Подготовить сообщение</button><button type="button" id="copy" disabled>Скопировать</button></div>
</form> </form>
<div id="profileSection" class="panel hidden" style="margin-top: 16px;">
<strong>Ваш профиль</strong>
<div class="grid">
<label>Имя персонажа<input id="profileName"></label>
<label>ID персонажа<input id="profileId" type="number" min="1"></label>
</div>
<div class="actions">
<button type="button" id="saveProfileBtn">Сохранить профиль</button>
<button type="button" id="clearProfileBtn" class="muted" style="background:transparent;border-color:#665159;">Очистить</button>
</div>
<p class="muted">Профиль будет автоматически подставляться в поля при создании отчётов.</p>
</div>
<dialog id="confirmDialog">
<h3 style="margin-top:0">Подтверждение</h3>
<div id="confirmPreview" style="white-space:pre-wrap;background:#171516;padding:12px;border-radius:8px;border:1px solid #4a383d;max-height:40vh;overflow-y:auto;margin-bottom:12px;"></div>
<div style="display:flex;gap:10px;">
<button type="button" id="confirmYes" class="primary">Да, сформировать</button>
<button type="button" id="confirmNo">Отмена</button>
</div>
</dialog>
<div class="result hidden" id="result"><h2>Сообщение</h2><textarea id="message" readonly></textarea><p class="muted" id="summary"></p></div> <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> <p class="error" id="error"></p>
</section> </section>
</div>
</main> </main>
<dialog id="identityDialog"> <dialog id="identityDialog">
<p id="identityDialogText"></p> <p id="identityDialogText"></p>
@@ -103,12 +143,18 @@
<button type="button" id="closeIdentityDialog">Понятно</button> <button type="button" id="closeIdentityDialog">Понятно</button>
</dialog> </dialog>
<script> <script>
const webAuth = document.querySelector('#webAuth');
const webApp = document.querySelector('#webApp');
const webAuthForm = document.querySelector('#webAuthForm');
const webPassword = document.querySelector('#webPassword');
const webAuthError = document.querySelector('#webAuthError');
const form = document.querySelector('#form'); const form = document.querySelector('#form');
const error = document.querySelector('#error'); const error = document.querySelector('#error');
const result = document.querySelector('#result'); const result = document.querySelector('#result');
const message = document.querySelector('#message'); const message = document.querySelector('#message');
const summary = document.querySelector('#summary'); const summary = document.querySelector('#summary');
const copy = document.querySelector('#copy'); const copy = document.querySelector('#copy');
const screenshots = document.querySelector('#screenshots');
const bulkText = document.querySelector('#bulkText'); const bulkText = document.querySelector('#bulkText');
const bulkStatus = document.querySelector('#bulkStatus'); const bulkStatus = document.querySelector('#bulkStatus');
const identityStatus = document.querySelector('#identityStatus'); const identityStatus = document.querySelector('#identityStatus');
@@ -117,20 +163,57 @@
const identityMissingLabel = document.querySelector('#identityMissingLabel'); const identityMissingLabel = document.querySelector('#identityMissingLabel');
const identityMissingValue = document.querySelector('#identityMissingValue'); const identityMissingValue = document.querySelector('#identityMissingValue');
let mode = 'coaching'; let mode = 'coaching';
function showWebApp() { webAuth.classList.add('hidden'); webApp.classList.remove('hidden'); }
async function checkWebSession() {
const response = await fetch('/api/web/session');
const data = await response.json();
if (data.authenticated) showWebApp();
}
webAuthForm.addEventListener('submit', async event => {
event.preventDefault(); webAuthError.textContent = '';
try {
const response = await fetch('/api/web/auth', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({password: webPassword.value})});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось войти');
showWebApp();
} catch (err) { webAuthError.textContent = err.message; }
});
checkWebSession().catch(err => { webAuthError.textContent = err.message; });
const extraKittens = document.querySelector('#extraKittens'); const extraKittens = document.querySelector('#extraKittens');
const statusHelp = document.querySelector('#statusHelp');
function addExtraKitten(values = {}) { function addExtraKitten(values = {}) {
const row = document.createElement('div'); row.className = 'extra-kitten'; const row = document.createElement('div'); row.className = 'extra-kitten';
row.innerHTML = `<input data-extra="name" placeholder="Имя котёнка" required> row.innerHTML = `<input data-extra="name" placeholder="Имя котёнка" required>
<input data-extra="id" type="number" min="1" placeholder="ID" required> <input data-extra="id" type="number" min="1" placeholder="ID" required>
<select data-extra="independence"><option value="самостоятельно">самостоятельно</option><option value="несамостоятельно">несамостоятельно</option></select> <select data-extra="independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select>
<button type="button" data-remove>Удалить</button>`; <button type="button" data-remove>Удалить</button>`;
row.querySelector('[data-extra="name"]').value = values.name || ''; row.querySelector('[data-extra="name"]').value = values.name || '';
row.querySelector('[data-extra="id"]').value = values.id || ''; row.querySelector('[data-extra="id"]').value = values.id || '';
row.querySelector('[data-extra="independence"]').value = values.independence || 'самостоятельно'; row.querySelector('[data-extra="independence"]').value = values.independence || 'самостоятельно';
row.querySelector('[data-extra="independence"]').addEventListener('change', updateStatusRules);
row.querySelector('[data-remove]').addEventListener('click', () => row.remove()); row.querySelector('[data-remove]').addEventListener('click', () => row.remove());
extraKittens.append(row); extraKittens.append(row);
} }
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten()); document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
function statusFields() { return [document.querySelector('#coaching [name="kitten_independence"]'), ...extraKittens.querySelectorAll('[data-extra="independence"]')]; }
function updateStatusRules(event) {
const fields = statusFields();
const isZu = document.querySelector('#coaching [name="skill"]').value === 'ЗУ';
if (isZu) {
fields.forEach(field => { field.value = 'самостоятельно'; field.disabled = true; });
statusHelp.textContent = 'Для ЗУ все котята должны быть самостоятельными.';
} else {
fields.forEach(field => { field.disabled = false; });
statusHelp.textContent = 'Для ЛУ можно указать не более одного несамостоятельного котёнка.';
}
}
function validateStatusRules() {
const fields = statusFields();
const skill = document.querySelector('#coaching [name="skill"]').value;
if (skill === 'ЗУ' && new Set(fields.map(field => field.value)).size > 1) return 'Для ЗУ статус всех котят должен совпадать.';
if (skill === 'ЛУ' && fields.filter(field => field.value === 'несамостоятельно').length > 1) return 'Для ЛУ допускается только один несамостоятельный котёнок.';
return '';
}
function selectMode(nextMode) { function selectMode(nextMode) {
mode = nextMode; mode = nextMode;
document.querySelectorAll('[data-mode]').forEach(item => item.classList.toggle('active', item.dataset.mode === mode)); document.querySelectorAll('[data-mode]').forEach(item => item.classList.toggle('active', item.dataset.mode === mode));
@@ -138,6 +221,8 @@
error.textContent = ''; error.textContent = '';
} }
document.querySelectorAll('[data-mode]').forEach(button => button.addEventListener('click', () => selectMode(button.dataset.mode))); document.querySelectorAll('[data-mode]').forEach(button => button.addEventListener('click', () => selectMode(button.dataset.mode)));
document.querySelector('#coaching [name="skill"]').addEventListener('change', updateStatusRules);
document.querySelector('#coaching [name="kitten_independence"]').addEventListener('change', updateStatusRules);
function setField(panel, name, value) { function setField(panel, name, value) {
const field = document.querySelector(`#${panel} [name="${name}"]`); const field = document.querySelector(`#${panel} [name="${name}"]`);
if (field && value !== undefined && value !== null) field.value = value; if (field && value !== undefined && value !== null) field.value = value;
@@ -157,6 +242,7 @@
}); });
if (fields.resources) setField(target, 'resources', fields.resources.map(item => `${item[0]}; ${item[1]}`).join('\n')); if (fields.resources) setField(target, 'resources', fields.resources.map(item => `${item[0]}; ${item[1]}`).join('\n'));
(fields.extra_kittens || []).forEach(item => addExtraKitten({name: item[0], id: item[1], independence: item[2]})); (fields.extra_kittens || []).forEach(item => addExtraKitten({name: item[0], id: item[1], independence: item[2]}));
updateStatusRules();
bulkStatus.textContent = data.status === 'complete' bulkStatus.textContent = data.status === 'complete'
? 'Данные распознаны. Проверьте поля и нажмите «Подготовить сообщение».' ? 'Данные распознаны. Проверьте поля и нажмите «Подготовить сообщение».'
: `Нужно уточнить:\n${(data.questions || []).join('\n')}`; : `Нужно уточнить:\n${(data.questions || []).join('\n')}`;
@@ -218,10 +304,28 @@
} }
return data; return data;
} }
async function uploadScreenshots() {
const files = [...(screenshots.files || [])];
const uploaded = [];
for (const file of files) {
const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(file); });
const response = await fetch('/api/web/upload', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name: file.name, type: file.type, data})});
const result = await response.json();
if (!response.ok) throw new Error(result.error || `Не удалось загрузить ${file.name}`);
uploaded.push({type: 'photo', url: result.url, name: file.name});
}
return uploaded;
}
form.addEventListener('submit', async event => { form.addEventListener('submit', async event => {
event.preventDefault(); error.textContent = ''; event.preventDefault(); error.textContent = '';
try { try {
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload()) }); if (mode === 'coaching') {
const statusError = validateStatusRules();
if (statusError) throw new Error(statusError);
}
const reportPayload = payload();
reportPayload.attachments = await uploadScreenshots();
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) });
const data = await response.json(); const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора'); if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
message.value = data.message; summary.textContent = data.result ? `Результат: ${JSON.stringify(data.result)}` : ''; message.value = data.message; summary.textContent = data.result ? `Результат: ${JSON.stringify(data.result)}` : '';