fix(goal): bound public calculator inputs

This commit is contained in:
nyan404 committed 2026-08-25 03:34:58 +03:00
1 parent 041d717439
commit 5d6e5987d1
8 files changed
+58 -8

No files matched your search

+1
View File
@@ -32,6 +32,7 @@
- 2026-08-21: Belki Python base image `reg.nyan404.ru/cwshed-clone/belki-base:py312-d6c42c4497ce` pins `pip==26.2.1`; CI upgrades to the same version before installing requirements.
- 2026-08-25: Belki fixes: natural bulk parsing now extracts `Имя ID` and `Имя [ID]` before a `HH:MM-HH:MM` range; web quick input is coaching-only; inspection resources use `+N название`; reports decline `раз/раза`; VK image mirroring defaults to `https://nyan.nyan404.ru`; `/belki` has a standalone goal calculator backed by `mode=goal`.
- 2026-08-25: VK now exposes the goal calculator in the main keyboard and through `/цель`/`/калькулятор`; its interactive state collects points, session duration, skill, independence, and kitten count, then confirms the calculated result without screenshots.
- 2026-08-25: public goal calculations reject non-finite scores and bound session length to 1–1440 minutes and kitten count to 1–50, consistently across domain, API, and VK input.
# 2026-08-16 — несколько котят в прокачке
`CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде.
+7 -1
View File
@@ -6,6 +6,7 @@ API-слой: парсинг JSON-пейлоадов и диспетчериза
from __future__ import annotations
from dataclasses import asdict
from math import isfinite
from typing import Any
from .domain import (
@@ -190,10 +191,15 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
if mode == "goal":
def _number_value(key: str) -> float:
value = _required(payload, key)
if isinstance(value, bool):
raise ApiError(f"Поле {key} должно быть числом")
try:
return float(value)
number = float(value)
except (TypeError, ValueError) as exc:
raise ApiError(f"Поле {key} должно быть числом") from exc
if not isfinite(number):
raise ApiError(f"Поле {key} должно быть конечным числом")
return number
minutes = _int(payload, "minutes_per_session")
result = calculate_goal(
+13 -5
View File
@@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from difflib import SequenceMatcher
from math import ceil
from math import ceil, isfinite
import re
from typing import Literal
@@ -19,6 +19,11 @@ Place = Literal["дупло", "расщелина"]
_CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
# The goal calculator is public. These limits keep accidental and hostile
# values from turning a simple estimate into an unbounded exponentiation.
MAX_GOAL_MINUTES_PER_SESSION = 24 * 60
MAX_GOAL_KITTENS = 50
def parse_clock(value: str) -> int:
"""Преобразует строку 'HH:MM' в количество минут от начала суток."""
@@ -134,16 +139,19 @@ def calculate_goal(
kitten_count: int = 1,
) -> GoalResult:
"""Рассчитывает, сколько времени нужно до целевого числа баллов."""
for value, label in ((current_points, "Текущие баллы"), (target_points, "Целевые баллы")):
if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value):
raise ValueError(f"{label} должны быть конечным числом")
if skill not in ("ЛУ", "ЗУ"):
raise ValueError("Навык должен быть ЛУ или ЗУ")
if kitten_independence not in ("самостоятельно", "несамостоятельно"):
raise ValueError("Некорректный статус самостоятельности")
if current_points < 0 or target_points < 0:
raise ValueError("Баллы не могут быть отрицательными")
if minutes_per_session <= 0:
raise ValueError("Продолжительность захода должна быть больше нуля")
if kitten_count <= 0:
raise ValueError("Количество котят должно быть положительным")
if isinstance(minutes_per_session, bool) or not isinstance(minutes_per_session, int) or not 0 < minutes_per_session <= MAX_GOAL_MINUTES_PER_SESSION:
raise ValueError(f"Продолжительность захода должна быть целым числом от 1 до {MAX_GOAL_MINUTES_PER_SESSION} минут")
if isinstance(kitten_count, bool) or not isinstance(kitten_count, int) or not 0 < kitten_count <= MAX_GOAL_KITTENS:
raise ValueError(f"Количество котят должно быть целым числом от 1 до {MAX_GOAL_KITTENS}")
if skill == "ЗУ" and kitten_independence != "самостоятельно":
raise ValueError("Для ЗУ котёнок должен быть самостоятельным")
+8 -2
View File
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
from math import isfinite
import os
import random
import re
@@ -1283,12 +1284,17 @@ class BelkiDialog:
value = float(text.replace(",", "."))
except ValueError:
return "Баллы укажите числом, например 12 или 12,5."
if not isfinite(value):
return "Баллы укажите конечным числом, например 12 или 12,5."
if value < 0:
return "Баллы не могут быть отрицательными."
state[key] = int(value) if value.is_integer() else value
elif key in ("minutes_per_session", "kitten_count"):
if not re.fullmatch(r"\d+", text) or int(text) <= 0:
return "Укажите положительное целое число."
from .domain import MAX_GOAL_KITTENS, MAX_GOAL_MINUTES_PER_SESSION
maximum = MAX_GOAL_MINUTES_PER_SESSION if key == "minutes_per_session" else MAX_GOAL_KITTENS
if not re.fullmatch(r"\d+", text) or not 0 < int(text) <= maximum:
label = "длительность захода" if key == "minutes_per_session" else "количество котят"
return f"Укажите {label}: целое число от 1 до {maximum}."
state[key] = int(text)
elif key == "kitten_independence":
value = self._independence(text)
+1
View File
@@ -59,6 +59,7 @@
- 2026-08-21: added a disabled durable Google Sheets export outbox for application-created and application-accepted events; no external request is attempted until an approved Apps Script URL and `BELKI_GOOGLE_EXPORT_ENABLED=1` are configured.
- 2026-08-25: fixed separator-free bulk parsing around time ranges, scoped web quick input to coaching, changed web inspection resources to `+N name`, corrected Russian inspection-count grammar, enabled VK image mirroring fallback, and added the standalone goal calculator mode/API.
- 2026-08-25: added the goal calculator to the VK menu as `/цель` and `/калькулятор`; the bot now runs the same goal calculation interactively with step prompts, choice buttons, and confirmation without report attachments.
- 2026-08-25: hardened the public goal calculator: point values must be finite, one session is limited to 1–1440 minutes, and one calculation to 1–50 kittens. The same validation is applied by the domain, JSON API, and VK dialogue, with regression tests for `NaN`, infinity, and excessive values.
# Обновление 2026-08-16: несколько котят
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
+7
View File
@@ -44,6 +44,13 @@ class ApiTests(unittest.TestCase):
self.assertEqual(response["result"]["total_hours"], 2)
self.assertIn("Осталось добрать: 24", response["message"])
def test_goal_calculator_rejects_non_finite_json_number(self):
with self.assertRaisesRegex(ApiError, "конечным числом"):
calculate_payload({
"mode": "goal", "current_points": "NaN", "target_points": 34,
"minutes_per_session": 20, "kitten_count": 1,
})
def test_calculate_and_store_uses_calculation_store(self):
with TemporaryDirectory() as directory:
with patch.dict("os.environ", {"BELKI_DATABASE_URL": "", "BELKI_HISTORY_DB": f"{directory}/history.sqlite3"}, clear=False):
+13
View File
@@ -1,4 +1,5 @@
import unittest
from math import inf, nan
from app.belki.domain import (
CoachingSession,
@@ -6,6 +7,7 @@ from app.belki.domain import (
TrainingSession,
calculate_coaching,
calculate_inspection,
calculate_goal,
calculate_training,
format_clock,
parse_clock,
@@ -28,6 +30,17 @@ class ClockTests(unittest.TestCase):
class CalculationTests(unittest.TestCase):
def test_goal_rejects_non_finite_and_unbounded_input(self):
for current_points, target_points in ((nan, 1), (1, inf)):
with self.assertRaisesRegex(ValueError, "конечным числом"):
calculate_goal(
current_points=current_points, target_points=target_points,
minutes_per_session=20, kitten_count=1,
)
with self.assertRaisesRegex(ValueError, "от 1 до 1440"):
calculate_goal(current_points=0, target_points=1, minutes_per_session=1441)
with self.assertRaisesRegex(ValueError, "от 1 до 50"):
calculate_goal(current_points=0, target_points=1, minutes_per_session=20, kitten_count=51)
def test_self_sufficient_kitten(self):
result = calculate_coaching(
CoachingSession(
+8
View File
@@ -18,6 +18,14 @@ class VkConversationTests(unittest.TestCase):
self.assertIn("/отмена", HELP_TEXT)
self.assertNotIn("Для детей", HELP_TEXT)
def test_goal_dialog_rejects_non_finite_and_unbounded_values(self):
dialog = BelkiDialog()
self.assertIn("баллов", dialog.handle(110, "/цель").lower())
self.assertIn("конечным", dialog.handle(110, "NaN").lower())
dialog.handle(110, "0")
dialog.handle(110, "10")
self.assertIn("от 1 до 1440", dialog.handle(110, "1441"))
def test_step_by_step_coaching_dialog(self):
dialog = BelkiDialog()
self.assertIn("дат", dialog.handle(77, "/лу").lower())