Admin fixes

This commit is contained in:
nyan404 committed 2026-08-16 21:03:25 +03:00
1 parent 6db39f0d51
commit a7f6fc0fc8
18 files changed
+285 -59

No files matched your search

+3
View File
@@ -21,3 +21,6 @@
- The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas. - The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas.
- 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; the migrated cwshed Nginx gateway keeps MetalLB `10.12.0.204` and routes `/belki`, `/admin`, and `/api/*` to web `10.12.0.212`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. Runtime credentials remain only in the cluster Secret `belki-runtime`. - 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; the migrated cwshed Nginx gateway keeps MetalLB `10.12.0.204` and routes `/belki`, `/admin`, and `/api/*` to web `10.12.0.212`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. Runtime credentials remain only in the cluster Secret `belki-runtime`.
- GitLab CI/CD now builds SHA/latest tags and deploys `deploy/k8s/production.yaml` from `main`. The ignored `.gitlab.variables.env` is a local handoff for GitLab Variables; CI uses namespace-scoped ServiceAccount `belki/gitlab-deploy`, not cluster-admin credentials. - GitLab CI/CD now builds SHA/latest tags and deploys `deploy/k8s/production.yaml` from `main`. The ignored `.gitlab.variables.env` is a local handoff for GitLab Variables; CI uses namespace-scoped ServiceAccount `belki/gitlab-deploy`, not cluster-admin credentials.
# 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+1 -1
View File
@@ -41,7 +41,7 @@ python3 -m app.belki.vk_bot
Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака. Осмотр теперь считает баллы: 2 за каждый осмотр, паутина — 7, обычный мох — 3, водяной мох — 2, остальные ресурсы — 1, надпись и ядовитая дичь — 0. Луговая змея и гадюка относятся к обычным ресурсам и дают 1 балл, а обычная змея, щитомордник и полосатый аспид — 0. Названия нормализуются по регистру, пробелам и распространённым опечаткам. Количество ресурса умножается на его стоимость с учётом знака.
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля и показывает сохранённые расчёты с сортировкой по ID или имени котёнка. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено. Админская история доступна по адресу `/admin`. Она защищена заголовком пароля, показывает отдельные столбцы кота-сопровождающего и котёнка, по умолчанию сортирует по коту и позволяет удалять записи после подтверждения. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
## Структура ## Структура
+14 -4
View File
@@ -100,10 +100,20 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
mode = payload.get("mode") mode = payload.get("mode")
try: try:
if mode == "coaching": if mode == "coaching":
extras = tuple( raw_extras = payload.get("extra_kittens", [])
(str(item["name"]), int(item["id"]), str(item.get("independence", "самостоятельно"))) if not isinstance(raw_extras, (list, tuple)):
for item in payload.get("extra_kittens", []) raise ApiError("Поле extra_kittens должно быть списком")
) extras_list = []
for item in raw_extras:
if isinstance(item, dict):
name, kitten_id, independence = item.get("name"), item.get("id"), item.get("independence", "самостоятельно")
elif isinstance(item, (list, tuple)) and len(item) >= 2:
name, kitten_id = item[0], item[1]
independence = item[2] if len(item) > 2 else "самостоятельно"
else:
raise ApiError("Дополнительный котёнок должен содержать имя и ID")
extras_list.append((str(name), int(kitten_id), str(independence)))
extras = tuple(extras_list)
session = CoachingSession( session = CoachingSession(
date=str(_required(payload, "date")), date=str(_required(payload, "date")),
skill=str(_required(payload, "skill")), skill=str(_required(payload, "skill")),
+13 -6
View File
@@ -86,6 +86,8 @@ class CoachingResult:
minutes: int minutes: int
escort_points: float | int escort_points: float | int
kitten_points: float | int kitten_points: float | int
kitten_count: int = 1
escort_multiplier: float = 1.0
def calculate_coaching(session: CoachingSession) -> CoachingResult: def calculate_coaching(session: CoachingSession) -> CoachingResult:
@@ -93,15 +95,20 @@ def calculate_coaching(session: CoachingSession) -> CoachingResult:
if minutes <= 0: if minutes <= 0:
raise ValueError("Продолжительность захода должна быть больше нуля") raise ValueError("Продолжительность захода должна быть больше нуля")
escort_multiplier = 1.5 if session.kitten_independence == "несамостоятельно" else 1.0 independence_multiplier = 1.5 if session.kitten_independence == "несамостоятельно" else 1.0
for _, _, independence in session.extra_kittens: kitten_count = 1 + len(session.extra_kittens)
if independence == "несамостоятельно": # Several wards share one report: the second ward pays 1.5x, and each
escort_multiplier += 0.5 # following ward adds a further 1.15x multiplier instead of another full
# base payout.
ward_multiplier = 1.0 if kitten_count == 1 else 1.5 * (1.15 ** (kitten_count - 2))
escort_multiplier = independence_multiplier * ward_multiplier
return CoachingResult( return CoachingResult(
minutes=minutes, minutes=minutes,
escort_points=_points(minutes * escort_multiplier / 5), escort_points=_points(minutes * escort_multiplier / 5),
kitten_points=_points(minutes * 2 / 5), kitten_points=_points(minutes * 2 / 5),
kitten_count=kitten_count,
escort_multiplier=round(escort_multiplier, 4),
) )
@@ -145,8 +152,8 @@ class InspectionReport:
if isinstance(self.inspections, bool) or not isinstance(self.inspections, int) or self.inspections < 0: if isinstance(self.inspections, bool) or not isinstance(self.inspections, int) or self.inspections < 0:
raise ValueError("Количество осмотров должно быть неотрицательным целым") raise ValueError("Количество осмотров должно быть неотрицательным целым")
for name, amount in self.resources: for name, amount in self.resources:
if not name.strip() or not isinstance(amount, int): if not name.strip() or not isinstance(amount, int) or amount < 0:
raise ValueError("Ресурс должен иметь название и целое количество") raise ValueError("Ресурс должен иметь название и неотрицательное целое количество")
@dataclass(frozen=True) @dataclass(frozen=True)
+26 -5
View File
@@ -86,9 +86,9 @@ class CalculationStore:
) )
return int(cursor.lastrowid) return int(cursor.lastrowid)
def list_calculations(self, *, sort_by: str = "kitten_id", descending: bool = True, def list_calculations(self, *, sort_by: str = "escort_id", descending: bool = True,
limit: int = 100) -> list[dict[str, Any]]: limit: int = 100) -> list[dict[str, Any]]:
"""Return admin rows with safe, application-level sorting by kitten identity.""" """Return admin rows with safe, application-level sorting by participant or kitten."""
limit = max(1, min(int(limit), 500)) limit = max(1, min(int(limit), 500))
fetch_limit = 5000 fetch_limit = 5000
if self.database_url.startswith(("postgres://", "postgresql://")): if self.database_url.startswith(("postgres://", "postgresql://")):
@@ -112,8 +112,29 @@ class CalculationStore:
"input": input_data, "result": result_data, "message": row[6], "input": input_data, "result": result_data, "message": row[6],
"created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7], "created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7],
}) })
if sort_by not in {"kitten_id", "kitten_name"}: if sort_by not in {"escort_id", "escort_name", "kitten_id", "kitten_name"}:
sort_by = "kitten_id" sort_by = "escort_id"
records.sort(key=lambda item: (item["input"].get(sort_by) is None, item["input"].get(sort_by, "")), def sort_value(item: dict[str, Any]) -> Any:
data = item["input"]
if sort_by == "escort_id":
return data.get("escort_id", data.get("character_id"))
if sort_by == "escort_name":
return data.get("escort_name", data.get("character_name"))
return data.get(sort_by)
records.sort(key=lambda item: (sort_value(item) is None, sort_value(item) or ""),
reverse=descending) reverse=descending)
return records[:limit] return records[:limit]
def delete_calculation(self, calculation_id: int) -> bool:
"""Delete one history row and report whether it existed."""
if isinstance(calculation_id, bool) or not isinstance(calculation_id, int) or calculation_id <= 0:
raise ValueError("ID записи должно быть положительным целым числом")
if self.database_url.startswith(("postgres://", "postgresql://")):
with self._psycopg.connect(self.database_url) as connection:
row = connection.execute(
"DELETE FROM belki_calculations WHERE id = %s RETURNING id", (calculation_id,)
).fetchone()
return row is not None
with sqlite3.connect(self.sqlite_path) as connection:
cursor = connection.execute("DELETE FROM calculations WHERE id = ?", (calculation_id,))
return cursor.rowcount > 0
+6 -1
View File
@@ -19,15 +19,20 @@ def _number(value: float | int) -> str:
def render_coaching(session: CoachingSession, result: CoachingResult) -> str: def render_coaching(session: CoachingSession, result: CoachingResult) -> str:
hashtag = "#лазание" if session.skill == "ЛУ" else "#зоркость" hashtag = "#лазание" if session.skill == "ЛУ" else "#зоркость"
kitten_text = f"{session.kitten_name} [{session.kitten_id}]"
if session.extra_kittens:
kitten_text += ", " + ", ".join(f"{name} [{kitten_id}]" for name, kitten_id, _ in session.extra_kittens)
lines = [ lines = [
hashtag, hashtag,
f"{session.escort_name} [{session.escort_id}], помог(-ла) {session.kitten_name} [{session.kitten_id}] " f"{session.escort_name} [{session.escort_id}], помог(-ла) {kitten_text} "
f"прокачать {session.skill}.", f"прокачать {session.skill}.",
f"Время: {format_clock(parse_clock(session.start))} – " f"Время: {format_clock(parse_clock(session.start))} – "
f"{format_clock(parse_clock(session.end))} [{result.minutes} минут].", f"{format_clock(parse_clock(session.end))} [{result.minutes} минут].",
f"Баллы белки: {_number(result.escort_points)} баллы.", f"Баллы белки: {_number(result.escort_points)} баллы.",
f"Баллы бельчонка: {_number(result.kitten_points)} баллы.", f"Баллы бельчонка: {_number(result.kitten_points)} баллы.",
] ]
if result.kitten_count > 1:
lines.insert(-2, f"Подопечных: {result.kitten_count}; множитель белки: {_number(result.escort_multiplier)}x.")
return "\n".join(lines) return "\n".join(lines)
+73 -14
View File
@@ -20,14 +20,14 @@ HELP_TEXT = (
"Что можно оформить:\n" "Что можно оформить:\n"
"• ЛУ или ЗУ за один заход;\n" "• ЛУ или ЗУ за один заход;\n"
"• тренировку;\n" "• тренировку;\n"
"• осмотр дупла или расщелины.\n\n" "• осмотр дупла или расщелины. Количество ресурсов — только неотрицательное.\n\n"
"Как отправить данные:\n" "Как отправить данные:\n"
"1. Начните с /лу, /зу, /урок или /осмотр и отвечайте на вопросы бота.\n" "1. Начните с /лу, /зу, /урок или /осмотр и отвечайте на вопросы бота.\n"
"2. Или отправьте готовую команду:\n" "2. Или отправьте готовую команду:\n"
"/лу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | самостоятельно\n" "/лу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | самостоятельно | доп. котята: Имя [ID], Имя2 [ID]\n"
"/зу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | несамостоятельно\n" "/зу ДД.ММ HH:MM HH:MM | Имя [ID] | Котёнок [ID] | несамостоятельно\n"
"/урок Имя [ID] | Котёнок [ID]\n" "/урок Имя [ID] | Котёнок [ID]\n"
"/осмотр дупло 6 Имя [ID] | вьюнок=-2, паук=1\n\n" "/осмотр дупло 6 Имя [ID] | вьюнок=1, паук=1\n\n"
"Можно также прислать данные одной строкой без символов |, например:\n" "Можно также прислать данные одной строкой без символов |, например:\n"
"15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140\n" "15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140\n"
"Бот уточнит навык и статус котёнка. Для статуса подойдут «сам» и «несам».\n\n" "Бот уточнит навык и статус котёнка. Для статуса подойдут «сам» и «несам».\n\n"
@@ -53,6 +53,23 @@ def _person(value: str) -> tuple[str, int]:
return match.group("name").strip(), int(match.group("id")) return match.group("name").strip(), int(match.group("id"))
def _extra_kittens(value: str) -> tuple[tuple[str, int, str], ...]:
"""Parse comma-separated additional wards from a command segment."""
value = re.sub(r"(?i)^\s*(?:доп(?:олнительн(?:ые|ых|ый))?\.?\s*котят\w*\s*:\s*)", "", value).strip()
if not value or value.lower() in ("нет", "нету", "без"):
return ()
result = []
for item in re.split(r"\s*,\s*", value):
independence = "самостоятельно"
status = re.search(r"(?i)(?:;|\s+)\s*(самостоятельно|несамостоятельно|сам|несам)\s*$", item)
if status:
independence = "несамостоятельно" if status.group(1).lower().startswith("несам") else "самостоятельно"
item = item[:status.start()].strip()
name, kitten_id = _person(item)
result.append((name, kitten_id, independence))
return tuple(result)
def parse_text_command(text: str) -> dict[str, Any]: def parse_text_command(text: str) -> dict[str, Any]:
text = text.strip() text = text.strip()
if text.lower() in ("/help", "help", "/start", "start"): if text.lower() in ("/help", "help", "/start", "start"):
@@ -69,12 +86,21 @@ def parse_text_command(text: str) -> dict[str, Any]:
date, start, end = parts[0].split() date, start, end = parts[0].split()
escort_name, escort_id = _person(parts[1]) escort_name, escort_id = _person(parts[1])
kitten_name, kitten_id = _person(parts[2]) kitten_name, kitten_id = _person(parts[2])
extras = []
status_part = parts[3] if len(parts) > 3 else ""
status_value = status_part.lower()
status_is_valid = status_value in ("сам", "самостоятельно", "несам", "несамостоятельно")
extra_parts = parts[4:] if status_is_valid else parts[3:]
for extra_part in extra_parts:
if extra_part.strip().lower().startswith(("доп", "нет")) or "[" in extra_part:
extras.extend(_extra_kittens(extra_part))
return { return {
"mode": "coaching", "date": date, "skill": "ЛУ", "start": start, "end": end, "mode": "coaching", "date": date, "skill": "ЛУ", "start": start, "end": end,
"escort_name": escort_name, "escort_id": escort_id, "escort_name": escort_name, "escort_id": escort_id,
"kitten_name": kitten_name, "kitten_id": kitten_id, "kitten_name": kitten_name, "kitten_id": kitten_id,
"kitten_independence": parts[3] if len(parts) > 3 and parts[3] else "самостоятельно", "kitten_independence": ("несамостоятельно" if status_part.lower().startswith("несам") else "самостоятельно") if status_is_valid else "самостоятельно",
"_independence_provided": len(parts) > 3 and bool(parts[3]), "_independence_provided": status_is_valid,
"extra_kittens": tuple(extras),
} }
if command in ("/зу", "/зоркость"): if command in ("/зу", "/зоркость"):
parsed = parse_text_command("/лу " + body) parsed = parse_text_command("/лу " + body)
@@ -226,6 +252,8 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None:
fields["kitten_name"], fields["kitten_id"] = people[1] fields["kitten_name"], fields["kitten_id"] = people[1]
else: else:
questions.append("Не вижу котёнка в формате Имя и ID.") questions.append("Не вижу котёнка в формате Имя и ID.")
if len(people) > 2:
fields["extra_kittens"] = [(name, kitten_id, "самостоятельно") for name, kitten_id in people[2:]]
independence_match = re.search(r"(?i)\b(самостоятельно|несамостоятельно)\b", text) independence_match = re.search(r"(?i)\b(самостоятельно|несамостоятельно)\b", text)
if independence_match: if independence_match:
fields["kitten_independence"] = independence_match.group(1).lower() fields["kitten_independence"] = independence_match.group(1).lower()
@@ -400,7 +428,7 @@ class BelkiDialog:
("place", "Укажите место: дупло или расщелина."), ("place", "Укажите место: дупло или расщелина."),
("inspections", "Сколько было осмотров?"), ("inspections", "Сколько было осмотров?"),
("character", "Укажите персонажа в формате Имя [ID]."), ("character", "Укажите персонажа в формате Имя [ID]."),
("resources", "Перечислите ресурсы, например: -1 вьюнок, +3 паук — или напишите «без ресурсов»."), ("resources", "Перечислите ресурсы, например: +1 вьюнок, +3 паук — или напишите «без ресурсов»."),
), ),
} }
@@ -418,10 +446,20 @@ class BelkiDialog:
self._pending_attachments.pop(peer_id, None) self._pending_attachments.pop(peer_id, None)
def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None: def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
if attachments: if not attachments:
pending = self._pending_attachments.setdefault(actor_id, []) return
pending.extend(attachments) target = (
del pending[:-10] self._states[actor_id].setdefault("attachments", [])
if actor_id in self._states and self._states[actor_id].get("awaiting_attachments")
else self._pending_attachments.setdefault(actor_id, [])
)
known = {photo.get("attachment") or (photo.get("owner_id"), photo.get("id")) for photo in target}
for photo in attachments:
key = photo.get("attachment") or (photo.get("owner_id"), photo.get("id"))
if key not in known:
target.append(photo)
known.add(key)
del target[:-10]
def _attach_pending(self, actor_id: int) -> None: def _attach_pending(self, actor_id: int) -> None:
pending = self._pending_attachments.pop(actor_id, []) pending = self._pending_attachments.pop(actor_id, [])
@@ -547,7 +585,7 @@ class BelkiDialog:
state["awaiting_attachments"] = True state["awaiting_attachments"] = True
return ( return (
"Пришлите сюда скриншоты для этого отчёта. " "Пришлите сюда скриншоты для этого отчёта. "
"После загрузки всех фотографий нажмите «Готово»." "После загрузки фотографий нажмите на меню ещё раз и выберете \"Готово\"."
) )
@staticmethod @staticmethod
@@ -577,6 +615,10 @@ class BelkiDialog:
f"Ресурсы: {resources}\n" f"Ресурсы: {resources}\n"
"Подтвердить? Ответьте «да» или «нет»." "Подтвердить? Ответьте «да» или «нет»."
) )
extra_line = (
f"Дополнительные котята: {', '.join(f'{name} [{kitten_id}]' for name, kitten_id, _ in state.get('extra_kittens', []))}\n"
if state.get("extra_kittens") else ""
)
return ( return (
"Я распознал данные:\n" "Я распознал данные:\n"
f"Навык: {state['skill']}\n" f"Навык: {state['skill']}\n"
@@ -585,6 +627,7 @@ class BelkiDialog:
f"Сопровождающий: {state['escort_name']} [{state['escort_id']}]\n" f"Сопровождающий: {state['escort_name']} [{state['escort_id']}]\n"
f"Котёнок: {state['kitten_name']} [{state['kitten_id']}]\n" f"Котёнок: {state['kitten_name']} [{state['kitten_id']}]\n"
f"Статус: {state['kitten_independence']}\n" f"Статус: {state['kitten_independence']}\n"
f"{extra_line}"
"Подтвердить? Ответьте «да» или «нет»." "Подтвердить? Ответьте «да» или «нет»."
) )
@@ -621,7 +664,7 @@ class BelkiDialog:
self._states[peer_id] = parsed self._states[peer_id] = parsed
return "Данные распознаны, но не указан статус котёнка. Ответьте: самостоятельно или несамостоятельно." return "Данные распознаны, но не указан статус котёнка. Ответьте: самостоятельно или несамостоятельно."
self._states[peer_id] = {**parsed, "awaiting_attachments": True} self._states[peer_id] = {**parsed, "awaiting_attachments": True}
return "Пришлите сюда скриншоты для этого отчёта. После загрузки всех фотографий нажмите «Готово»." return "Пришлите сюда скриншоты для этого отчёта. После загрузки фотографий нажмите на меню ещё раз и выберете \"Готово\"."
if command.lower() in ("/урок", "/тренировка"): if command.lower() in ("/урок", "/тренировка"):
state = {"mode": "training"} state = {"mode": "training"}
self._apply_known_profile(peer_id, state) self._apply_known_profile(peer_id, state)
@@ -756,6 +799,8 @@ class BelkiDialog:
resources = [] resources = []
for item in text.split(","): for item in text.split(","):
item = item.strip() item = item.strip()
if re.match(r"^-\s*\d+\s+", item):
return "Количество ресурса не может быть отрицательным. Укажите, например: +1 вьюнок."
match = re.fullmatch(r"([+-])\s*(\d+)\s+(.+)", item) match = re.fullmatch(r"([+-])\s*(\d+)\s+(.+)", item)
if match: if match:
amount = int(match.group(2)) * (1 if match.group(1) == "+" else -1) amount = int(match.group(2)) * (1 if match.group(1) == "+" else -1)
@@ -765,11 +810,14 @@ class BelkiDialog:
if "=" in item: if "=" in item:
name, amount = item.split("=", 1) name, amount = item.split("=", 1)
try: try:
resources.append([name.strip(), int(amount.strip())]) parsed_amount = int(amount.strip())
except ValueError: except ValueError:
return "Количество ресурса должно быть целым числом." return "Количество ресурса должно быть целым числом."
if parsed_amount < 0:
return "Количество ресурса не может быть отрицательным. Укажите, например: +1 вьюнок."
resources.append([name.strip(), parsed_amount])
continue continue
return "Ресурсы укажите так: -1 вьюнок, +3 паук — или напишите «без ресурсов»." return "Ресурсы укажите так: +1 вьюнок, +3 паук — или напишите «без ресурсов». Отрицательные значения недопустимы."
state["resources"] = resources state["resources"] = resources
return self._ask_next(state) return self._ask_next(state)
@@ -786,6 +834,17 @@ class BelkiDialog:
if state: if state:
self._attach_pending(actor_id) self._attach_pending(actor_id)
if state and state.get("awaiting_attachments"): if state and state.get("awaiting_attachments"):
if text.lower().startswith(("/доп", "доп котята", "доп. котята")):
try:
additions = _extra_kittens(text.split(":", 1)[1] if ":" in text else text.split(" ", 1)[1])
except (ValueError, IndexError) as exc:
return f"Не удалось добавить котят: {exc}"
state["extra_kittens"] = list(state.get("extra_kittens", ()))
state["extra_kittens"].extend(additions)
return (
f"Добавлено дополнительных котят: {len(additions)}. "
"Теперь пришлите скриншоты и нажмите «Готово»."
)
if text.lower() in ("готово", "дальше", "продолжить"): if text.lower() in ("готово", "дальше", "продолжить"):
if not state.get("attachments"): if not state.get("attachments"):
return "Я пока не вижу скриншотов. Пришлите хотя бы одну фотографию, затем откройте меню ещё раз и нажмите «Готово»." return "Я пока не вижу скриншотов. Пришлите хотя бы одну фотографию, затем откройте меню ещё раз и нажмите «Готово»."
+32 -7
View File
@@ -34,6 +34,16 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers() self.end_headers()
self.wfile.write(encoded) self.wfile.write(encoded)
def _admin_authorized(self) -> bool:
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected:
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
return False
if self.headers.get("X-Admin-Password", "") != expected:
self._json(401, {"error": "Неверный пароль"})
return False
return True
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"):
@@ -46,15 +56,10 @@ class Handler(BaseHTTPRequestHandler):
self._file(WEB_ROOT / "admin.html") self._file(WEB_ROOT / "admin.html")
return return
if path == "/api/admin/calculations": if path == "/api/admin/calculations":
expected = os.getenv("BELKI_ADMIN_PASSWORD", "") if not self._admin_authorized():
if not expected:
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
return
if self.headers.get("X-Admin-Password", "") != expected:
self._json(401, {"error": "Неверный пароль"})
return return
query = parse_qs(urlparse(self.path).query) query = parse_qs(urlparse(self.path).query)
sort_by = query.get("sort", ["kitten_id"])[0] sort_by = query.get("sort", ["escort_id"])[0]
descending = query.get("direction", ["desc"])[0] != "asc" descending = query.get("direction", ["desc"])[0] != "asc"
self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending)}) self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending)})
return return
@@ -93,6 +98,26 @@ class Handler(BaseHTTPRequestHandler):
except Exception: except Exception:
self._json(500, {"error": "Внутренняя ошибка калькулятора"}) self._json(500, {"error": "Внутренняя ошибка калькулятора"})
def do_DELETE(self) -> None: # noqa: N802
parsed = urlparse(self.path)
prefix = "/api/admin/calculations/"
if not parsed.path.startswith(prefix):
self._json(404, {"error": "Не найдено"})
return
if not self._admin_authorized():
return
raw_id = parsed.path[len(prefix):]
try:
calculation_id = int(raw_id)
deleted = history_store().delete_calculation(calculation_id)
except ValueError as exc:
self._json(400, {"error": str(exc)})
return
if not deleted:
self._json(404, {"error": "Запись не найдена"})
return
self._json(200, {"deleted": calculation_id})
def log_message(self, format: str, *args: object) -> None: def log_message(self, format: str, *args: object) -> None:
if os.getenv("BELKI_ACCESS_LOG", "0") == "1": if os.getenv("BELKI_ACCESS_LOG", "0") == "1":
super().log_message(format, *args) super().log_message(format, *args)
@@ -28,8 +28,8 @@ milestone: M1 (see docs/ROADMAP.md)
- 5 минут дают 2 балла котёнку; - 5 минут дают 2 балла котёнку;
- самостоятельный основной котёнок: сопровождающий получает `minutes / 5`; - самостоятельный основной котёнок: сопровождающий получает `minutes / 5`;
- несамостоятельный основной котёнок: сопровождающий получает `minutes * 1.5 / 5`; - несамостоятельный основной котёнок: сопровождающий получает `minutes * 1.5 / 5`;
- каждый дополнительный несамостоятельный котёнок добавляет сопровождающему `minutes * 0.5 / 5`; - отчёт может содержать нескольких котят-подопечных без суммирования полной ставки за каждого: первый использует базовый коэффициент, второй — множитель `1.5`, каждый следующий — дополнительный множитель `1.15`;
- самостоятельный дополнительный котёнок не добавляет баллов сопровождающему; - множители дополнительных котят применяются к баллам сопровождающего; статус самостоятельности основного котёнка по-прежнему задаёт его базовый коэффициент `1.0` или `1.5`;
- котёнок получает `minutes / 5 * 2` согласно пользовательской разбалловке; - котёнок получает `minutes / 5 * 2` согласно пользовательской разбалловке;
- тренировка не смешивается с прокачкой и даёт фиксированные 25 баллов отдельной записью. - тренировка не смешивается с прокачкой и даёт фиксированные 25 баллов отдельной записью.
@@ -68,7 +68,7 @@ milestone: M1 (see docs/ROADMAP.md)
Скриншот истории и рта. Скриншот истории и рта.
``` ```
Для осмотра поддерживаются конкретные ресурсы с количеством добытого (`+`) и потерянного/отрицательного результата (`-`). Ничего или ядовитая дичь записывается как `0`. Съедобная дичь может быть объединена в одну категорию. Для осмотра поддерживаются конкретные ресурсы с неотрицательным количеством добытого (`+`). Ничего или ядовитая дичь записывается как `0`. Съедобная дичь может быть объединена в одну категорию.
## VK contract ## VK contract
+1
View File
@@ -22,3 +22,4 @@ flowchart TD
``` ```
The current phase is local implementation and validation. The k3s branch of the map is intentionally not live. The current phase is local implementation and validation. The k3s branch of the map is intentionally not live.
- multi-ward coaching: `extra_kittens` -> shared escort payout multiplier (1.5 for ward 2, 1.15 for each later ward)
+5 -2
View File
@@ -25,8 +25,8 @@
- Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git. - Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git.
- The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts. - The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts.
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp. - Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
- VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; `/admin` renders their thumbnails. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred. - VK photo attachments received during an active dialog are normalized into `input.attachments` and persisted with the calculation; active reports attach photos immediately and deduplicate repeated VK events. `/admin` renders all thumbnails in a wrapped gallery. With `BELKI_IMAGE_HOST_API_URL`, the bot mirrors each photo through image-hosting-web and stores `mirror_url`; Google Sheets export remains deferred.
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports sorting by kitten ID or name and does not persist the password in browser storage. - `/admin` and `/api/admin/calculations` expose the calculation history for review. The table shows both the reporting cat (escort) and kitten; default sorting is by the reporting cat, with optional kitten sorting. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports deleting individual records through authenticated `DELETE /api/admin/calculations/{id}`, with confirmation in the UI.
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported. - VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
- Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace. - Production k3s deployment (2026-08-16): namespace `belki` runs the Belki web calculator, VK bot, PostgreSQL 16, and the migrated cwshed Nginx gateway. The gateway keeps MetalLB IP `10.12.0.204`, serves the legacy CatWar site, and routes `/belki`, `/admin`, and `/api/*` to Belki web on `10.12.0.212`. Belki images are `reg.nyan404.ru/cwshed-clone/belki` and `reg.nyan404.ru/cwshed`; PostgreSQL is mirrored as `reg.nyan404.ru/library/postgres:16-alpine-amd64` because cluster nodes cannot pull Docker Hub directly. Registry pull credentials and runtime secrets are created out-of-band in the `belki` namespace.
- The previously inspected `stage-zone-runner` at `10.3.1.236` is not the runner used by the current pipeline. Runner `#2` (`Ryzen-builder`) at `10.3.1.168` is a privileged Docker executor and supports the DinD service used by `.gitlab-ci.yml`. - The previously inspected `stage-zone-runner` at `10.3.1.236` is not the runner used by the current pipeline. Runner `#2` (`Ryzen-builder`) at `10.3.1.168` is a privileged Docker executor and supports the DinD service used by `.gitlab-ci.yml`.
@@ -42,3 +42,6 @@
- 2026-08-16: added GitLab build/deploy stages, namespace-scoped `gitlab-deploy` RBAC, and the ignored local variables handoff `.gitlab.variables.env`. - 2026-08-16: added GitLab build/deploy stages, namespace-scoped `gitlab-deploy` RBAC, and the ignored local variables handoff `.gitlab.variables.env`.
- 2026-08-16: switched the image build back to explicit aliased DinD after confirming runner `#2` has no host socket but can start `docker:29.6.1-dind` successfully. - 2026-08-16: switched the image build back to explicit aliased DinD after confirming runner `#2` has no host socket but can start `docker:29.6.1-dind` successfully.
- 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: несколько котят
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
+2 -2
View File
@@ -37,11 +37,11 @@ class ApiTests(unittest.TestCase):
"character_id": 1604614, "character_id": 1604614,
"place": "дупло", "place": "дупло",
"inspections": 6, "inspections": 6,
"resources": [["вьюнок", -2], ["паук", 1]], "resources": [["вьюнок", 2], ["паук", 1]],
} }
) )
self.assertIn("осмотрел(-а) дупло 6 раз", response["message"]) self.assertIn("осмотрел(-а) дупло 6 раз", response["message"])
self.assertEqual(response["result"]["points"], 17) self.assertEqual(response["result"]["points"], 21)
def test_bulk_inspection_payload_explains_missing_fields(self): def test_bulk_inspection_payload_explains_missing_fields(self):
response = inspect_bulk_payload({"text": "/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]"}) response = inspect_bulk_payload({"text": "/лу 15.08 11:00 11:20 | Белка [1] | Котёнок [2]"})
+20 -4
View File
@@ -64,9 +64,21 @@ class CalculationTests(unittest.TestCase):
), ),
) )
) )
self.assertEqual(result.escort_points, 24) self.assertEqual(result.escort_points, 31.05)
self.assertEqual(result.kitten_points, 24) self.assertEqual(result.kitten_points, 24)
def test_additional_wards_use_multipliers_instead_of_full_sum(self):
base = CoachingSession("15.08", "ЛУ", "11:00", "12:00", "Белка", 1, "Первый", 2)
session = CoachingSession(
"15.08", "ЛУ", "11:00", "12:00", "Белка", 1, "Первый", 2,
extra_kittens=(("Второй", 3, "самостоятельно"), ("Третий", 4, "самостоятельно")),
)
self.assertEqual(calculate_coaching(base).escort_points, 12)
result = calculate_coaching(session)
self.assertEqual(result.kitten_count, 3)
self.assertEqual(result.escort_multiplier, 1.725)
self.assertEqual(result.escort_points, 20.7)
def test_training_is_fixed(self): def test_training_is_fixed(self):
self.assertEqual(calculate_training(TrainingSession("Белка", 1, "Котёнок", 2)).points, 25) self.assertEqual(calculate_training(TrainingSession("Белка", 1, "Котёнок", 2)).points, 25)
@@ -105,15 +117,15 @@ class ReportTests(unittest.TestCase):
character_id=1604614, character_id=1604614,
place="дупло", place="дупло",
inspections=6, inspections=6,
resources=(("вьюнок", -2), ("паук", 1)), resources=(("вьюнок", 2), ("паук", 1)),
) )
) )
self.assertIn("осмотрел(-а) дупло 6 раз", text) self.assertIn("осмотрел(-а) дупло 6 раз", text)
self.assertIn("#осмотр", text) self.assertIn("#осмотр", text)
self.assertIn("-2 вьюнок.", text) self.assertIn("+2 вьюнок.", text)
self.assertIn("+1 паук.", text) self.assertIn("+1 паук.", text)
self.assertNotIn("Скриншот", text) self.assertNotIn("Скриншот", text)
self.assertIn("Баллы осмотра: 17 баллы.", text) self.assertIn("Баллы осмотра: 21 баллы.", text)
def test_inspection_points_include_attempts_and_resource_values(self): def test_inspection_points_include_attempts_and_resource_values(self):
report = InspectionReport( report = InspectionReport(
@@ -124,6 +136,10 @@ class ReportTests(unittest.TestCase):
self.assertEqual(calculate_inspection(report).points, 11) self.assertEqual(calculate_inspection(report).points, 11)
self.assertIn("Баллы осмотра: 11 баллы.", render_inspection(report)) self.assertIn("Баллы осмотра: 11 баллы.", render_inspection(report))
def test_inspection_rejects_negative_resources(self):
with self.assertRaises(ValueError):
InspectionReport("Белка", 1, "дупло", 1, (("вьюнок", -1),))
def test_inspection_resource_aliases_and_typos(self): def test_inspection_resource_aliases_and_typos(self):
report = InspectionReport( report = InspectionReport(
character_name="Белка", character_id=1, place="дупло", inspections=0, character_name="Белка", character_id=1, place="дупло", inspections=0,
+16 -2
View File
@@ -9,11 +9,11 @@ class CalculationHistoryTests(unittest.TestCase):
def test_admin_rows_sort_by_kitten_id_and_name(self) -> None: def test_admin_rows_sort_by_kitten_id_and_name(self) -> None:
with tempfile.TemporaryDirectory() as directory: with tempfile.TemporaryDirectory() as directory:
store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3") store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3")
for kitten_id, kitten_name in ((30, "Тучка"), (10, "Янтарь"), (20, "Белка")): for escort_id, kitten_id, kitten_name in ((30, 30, "Тучка"), (10, 10, "Янтарь"), (20, 20, "Белка")):
store.save( store.save(
actor_id=99, actor_id=99,
source="vk", source="vk",
payload={"mode": "coaching", "kitten_id": kitten_id, "kitten_name": kitten_name}, payload={"mode": "coaching", "escort_id": escort_id, "escort_name": f"Кот {escort_id}", "kitten_id": kitten_id, "kitten_name": kitten_name},
response={"mode": "coaching", "message": f"расчёт {kitten_id}", "result": {"points": 1}}, response={"mode": "coaching", "message": f"расчёт {kitten_id}", "result": {"points": 1}},
) )
@@ -24,6 +24,20 @@ class CalculationHistoryTests(unittest.TestCase):
self.assertEqual(by_name[0]["actor_id"], 99) self.assertEqual(by_name[0]["actor_id"], 99)
self.assertEqual(by_name[0]["result"]["points"], 1) self.assertEqual(by_name[0]["result"]["points"], 1)
store.save(
actor_id=100,
source="web",
payload={"mode": "coaching", "escort_id": 5, "escort_name": "Альфа", "kitten_id": 99},
response={"mode": "coaching", "message": "расчёт 99", "result": {"points": 1}},
)
by_escort = store.list_calculations(sort_by="escort_id", descending=False)
self.assertEqual([row["input"].get("escort_id") for row in by_escort[:3]], [5, 10, 20])
record_id = by_name[0]["id"]
self.assertTrue(store.delete_calculation(record_id))
self.assertFalse(store.delete_calculation(record_id))
self.assertNotIn(record_id, [row["id"] for row in store.list_calculations()])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+6
View File
@@ -20,6 +20,12 @@ class VkBotTests(unittest.TestCase):
self.assertEqual(command["escort_id"], 1604614) self.assertEqual(command["escort_id"], 1604614)
self.assertEqual(command["kitten_id"], 1617140) self.assertEqual(command["kitten_id"], 1617140)
def test_parse_coaching_command_with_additional_wards(self):
command = parse_text_command(
"/лу 15.08 11:00 11:20 | Белка [1] | Первый [2] | сам | доп. котята: Второй [3], Третий [4]"
)
self.assertEqual(command["extra_kittens"], (("Второй", 3, "самостоятельно"), ("Третий", 4, "самостоятельно")))
def test_parse_help(self): def test_parse_help(self):
self.assertEqual(parse_text_command("/help"), {"mode": "help"}) self.assertEqual(parse_text_command("/help"), {"mode": "help"})
self.assertIn("/лу", HELP_TEXT) self.assertIn("/лу", HELP_TEXT)
+12 -2
View File
@@ -123,9 +123,9 @@ class VkConversationTests(unittest.TestCase):
dialog.handle(106, "дупло") dialog.handle(106, "дупло")
dialog.handle(106, "6") dialog.handle(106, "6")
dialog.handle(106, "Серолап [1617140]") dialog.handle(106, "Серолап [1617140]")
self.assertIn("скриншот", dialog.handle(106, "-1 вьюнок, + 3 паук").lower()) self.assertIn("скриншот", dialog.handle(106, "+1 вьюнок, + 3 паук").lower())
confirmation = self.add_screenshot(dialog, 106) confirmation = self.add_screenshot(dialog, 106)
self.assertIn("вьюнок=-1", confirmation) self.assertIn("вьюнок=1", confirmation)
self.assertIn("паук=3", confirmation) self.assertIn("паук=3", confirmation)
def test_queued_photo_is_saved_in_confirmed_state(self): def test_queued_photo_is_saved_in_confirmed_state(self):
@@ -138,6 +138,16 @@ class VkConversationTests(unittest.TestCase):
self.assertIn("подтверд", confirmation.lower()) self.assertIn("подтверд", confirmation.lower())
self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg") self.assertEqual(dialog._states[107]["attachments"][0]["url"], "https://example.test/photo.jpg")
def test_six_photos_are_kept_on_active_report(self):
dialog = BelkiDialog()
dialog.handle(109, "/урок")
dialog.handle(109, "Белка [1]")
dialog.handle(109, "Котёнок [2]")
dialog.queue_attachments(109, [{"type": "photo", "attachment": f"photo1_{index}", "url": f"https://example.test/{index}.jpg"} for index in range(6)])
confirmation = dialog.handle(109, "готово")
self.assertIn("подтверд", confirmation.lower())
self.assertEqual(len(dialog._states[109]["attachments"]), 6)
def test_photo_is_mirrored_before_history_save(self): def test_photo_is_mirrored_before_history_save(self):
mirrored = [] mirrored = []
+21 -5
View File
@@ -18,7 +18,8 @@
th, td { text-align: left; vertical-align: top; padding: 10px; border-bottom: 1px solid #4a383d; } th, td { text-align: left; vertical-align: top; padding: 10px; border-bottom: 1px solid #4a383d; }
th { color: #d59b62; } th { color: #d59b62; }
td pre { white-space: pre-wrap; margin: 0; max-width: 560px; } td pre { white-space: pre-wrap; margin: 0; max-width: 560px; }
td img { width: 96px; height: 72px; object-fit: cover; margin: 2px; border-radius: 5px; } td .photo-list { display: flex; flex-wrap: wrap; gap: 4px; max-width: 320px; }
td img { width: 96px; height: 72px; object-fit: cover; border-radius: 5px; }
.muted { color: #b9aaad; } .muted { color: #b9aaad; }
</style> </style>
</head> </head>
@@ -28,12 +29,12 @@
<p class="muted">История подтверждённых расчётов из VK-бота и веб-калькулятора.</p> <p class="muted">История подтверждённых расчётов из VK-бота и веб-калькулятора.</p>
<div class="toolbar"> <div class="toolbar">
<label>Пароль администратора<input id="password" type="password" autocomplete="current-password"></label> <label>Пароль администратора<input id="password" type="password" autocomplete="current-password"></label>
<label>Сортировать<select id="sort"><option value="kitten_id">ID котёнка</option><option value="kitten_name">Имя котёнка</option></select></label> <label>Сортировать<select id="sort"><option value="escort_id">ID кота</option><option value="escort_name">Имя кота</option><option value="kitten_id">ID котёнка</option><option value="kitten_name">Имя котёнка</option></select></label>
<label>Порядок<select id="direction"><option value="asc">А–Я / по возрастанию</option><option value="desc" selected>Я–А / по убыванию</option></select></label> <label>Порядок<select id="direction"><option value="asc">А–Я / по возрастанию</option><option value="desc" selected>Я–А / по убыванию</option></select></label>
<button id="load">Загрузить</button> <button id="load">Загрузить</button>
</div> </div>
<p class="error" id="error"></p> <p class="error" id="error"></p>
<div class="table-wrap"><table><thead><tr><th>ID записи</th><th>Автор</th><th>Режим</th><th>Котёнок</th><th>Фото</th><th>Дата</th><th>Сообщение</th></tr></thead><tbody id="rows"></tbody></table></div> <div class="table-wrap"><table><thead><tr><th>ID записи</th><th>Автор</th><th>Режим</th><th>Кот</th><th>Котёнок</th><th>Фото</th><th>Дата</th><th>Сообщение</th><th>Действие</th></tr></thead><tbody id="rows"></tbody></table></div>
</main> </main>
<script> <script>
const password = document.querySelector('#password'); const password = document.querySelector('#password');
@@ -52,19 +53,34 @@
data.items.forEach(item => { data.items.forEach(item => {
const row = document.createElement('tr'); const row = document.createElement('tr');
row.append(cell(item.id)); row.append(cell(item.actor_id || '—')); row.append(cell(item.mode)); row.append(cell(item.id)); row.append(cell(item.actor_id || '—')); row.append(cell(item.mode));
row.append(cell(`${item.input.escort_name || item.input.character_name || '—'} [${item.input.escort_id || item.input.character_id || '—'}]`));
row.append(cell(`${item.input.kitten_name || '—'} [${item.input.kitten_id || '—'}]`)); row.append(cell(`${item.input.kitten_name || '—'} [${item.input.kitten_id || '—'}]`));
const photos = document.createElement('td'); const photos = document.createElement('td');
const photoList = document.createElement('div'); photoList.className = 'photo-list';
(item.input.attachments || []).forEach(photo => { (item.input.attachments || []).forEach(photo => {
const photoUrl = photo.mirror_url || photo.url; const photoUrl = photo.mirror_url || photo.url;
if (!photoUrl) return; if (!photoUrl) return;
const link = document.createElement('a'); link.href = photoUrl; link.target = '_blank'; link.rel = 'noopener'; const link = document.createElement('a'); link.href = photoUrl; link.target = '_blank'; link.rel = 'noopener';
const image = document.createElement('img'); image.src = photoUrl; image.alt = 'Фото'; image.loading = 'lazy'; const image = document.createElement('img'); image.src = photoUrl; image.alt = 'Фото'; image.loading = 'lazy';
link.append(image); photos.append(link); link.append(image); photoList.append(link);
}); });
if (!photos.childNodes.length) photos.textContent = '—'; if (photoList.childNodes.length) photos.append(photoList); else photos.textContent = '—';
row.append(photos); row.append(photos);
row.append(cell(item.created_at)); row.append(cell(item.created_at));
const message = document.createElement('td'); const pre = document.createElement('pre'); pre.textContent = item.message; message.append(pre); row.append(message); const message = document.createElement('td'); const pre = document.createElement('pre'); pre.textContent = item.message; message.append(pre); row.append(message);
const actions = document.createElement('td');
const remove = document.createElement('button'); remove.textContent = 'Удалить';
remove.addEventListener('click', async () => {
if (!window.confirm(`Удалить запись №${item.id}?`)) return;
remove.disabled = true;
try {
const response = await fetch(`/api/admin/calculations/${encodeURIComponent(item.id)}`, {method: 'DELETE', headers: {'X-Admin-Password': password.value}});
const result = await response.json();
if (!response.ok) throw new Error(result.error || 'Не удалось удалить запись');
row.remove();
} catch (err) { error.textContent = err.message; remove.disabled = false; }
});
actions.append(remove); row.append(actions);
rows.append(row); rows.append(row);
}); });
} catch (err) { error.textContent = err.message; } } catch (err) { error.textContent = err.message; }
+31 -1
View File
@@ -25,6 +25,9 @@
.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-kitten { display: grid; grid-template-columns: 1fr 140px 180px auto; gap: 8px; align-items: end; }
@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; }
@@ -63,6 +66,11 @@
<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></label>
<div class="wide extra-kittens">
<label>Дополнительные котята <span class="muted">(общие баллы не суммируются; 2-й ×1,5, следующие ×1,15)</span></label>
<div id="extraKittens"></div>
<button type="button" id="addKitten">Добавить котёнка</button>
</div>
</div> </div>
<div id="training" class="grid mode hidden"> <div id="training" class="grid mode hidden">
@@ -78,7 +86,7 @@
<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><textarea name="resources" placeholder="вьюнок; 2&#10;паук; 1"></textarea></label>
</div> </div>
<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>
@@ -109,6 +117,20 @@
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';
const extraKittens = document.querySelector('#extraKittens');
function addExtraKitten(values = {}) {
const row = document.createElement('div'); row.className = 'extra-kitten';
row.innerHTML = `<input data-extra="name" placeholder="Имя котёнка" required>
<input data-extra="id" type="number" min="1" placeholder="ID" required>
<select data-extra="independence"><option value="самостоятельно">самостоятельно</option><option value="несамостоятельно">несамостоятельно</option></select>
<button type="button" data-remove>Удалить</button>`;
row.querySelector('[data-extra="name"]').value = values.name || '';
row.querySelector('[data-extra="id"]').value = values.id || '';
row.querySelector('[data-extra="independence"]').value = values.independence || 'самостоятельно';
row.querySelector('[data-remove]').addEventListener('click', () => row.remove());
extraKittens.append(row);
}
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
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));
@@ -134,6 +156,7 @@
setField(target, key, value); setField(target, key, value);
}); });
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]}));
bulkStatus.textContent = data.status === 'complete' bulkStatus.textContent = data.status === 'complete'
? 'Данные распознаны. Проверьте поля и нажмите «Подготовить сообщение».' ? 'Данные распознаны. Проверьте поля и нажмите «Подготовить сообщение».'
: `Нужно уточнить:\n${(data.questions || []).join('\n')}`; : `Нужно уточнить:\n${(data.questions || []).join('\n')}`;
@@ -186,6 +209,13 @@
return [name, Number(amount)]; return [name, Number(amount)];
}); });
} }
if (mode === 'coaching') {
data.extra_kittens = [...extraKittens.querySelectorAll('.extra-kitten')].map(row => ({
name: row.querySelector('[data-extra="name"]').value.trim(),
id: Number(row.querySelector('[data-extra="id"]').value),
independence: row.querySelector('[data-extra="independence"]').value,
}));
}
return data; return data;
} }
form.addEventListener('submit', async event => { form.addEventListener('submit', async event => {