diff --git a/app/belki/domain.py b/app/belki/domain.py index 48d4c04..811b897 100644 --- a/app/belki/domain.py +++ b/app/belki/domain.py @@ -115,8 +115,6 @@ class CoachingSession: raise ValueError("ID участников одного захода не должны повторяться") statuses = (self.kitten_independence,) + tuple(independence for _, _, independence in self.extra_kittens) nonself_count = sum(status == "несамостоятельно" for status in statuses) - if self.skill == "ЗУ" and any(s != "самостоятельно" for s in statuses): - raise ValueError("Для ЗУ все котята должны быть самостоятельными") if self.skill == "ЛУ" and nonself_count > 1: raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок") @@ -174,9 +172,6 @@ def calculate_goal( 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("Для ЗУ котёнок должен быть самостоятельным") - ward_multiplier = 1.0 if kitten_count == 1 else 1.5 * (1.15 ** (kitten_count - 2)) nonself_bonus = minutes_per_session * 0.5 / 5 if kitten_independence == "несамостоятельно" else 0 points_per_session = _points(minutes_per_session * ward_multiplier / 5 + nonself_bonus) diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index 9e04297..9c31d75 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -170,6 +170,27 @@ def _labelled_kitten_statuses(text: str) -> dict[int, str]: return statuses +def _participant_statuses(text: str, participants: list[tuple[str, int]]) -> dict[int, str]: + """Read a status placed directly after an unlabelled participant's ID.""" + participant_ids = {participant_id for _, participant_id in participants} + statuses: dict[int, str] = {} + matches = list(_NATURAL_PERSON_RE.finditer(text)) + for index, match in enumerate(matches): + participant_id = int(match.group("id")) + if participant_id not in participant_ids: + continue + next_start = matches[index + 1].start() if index + 1 < len(matches) else len(text) + fragment = text[match.end():next_start] + status = re.search( + r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|несам|не\s+сам|сам)\b", + fragment, + ) + if status: + value = re.sub(r"\s+", "", status.group(1).casefold()) + statuses[participant_id] = "несамостоятельно" if value.startswith("несам") else "самостоятельно" + return statuses + + def _normalise_natural_text(text: str) -> str: """Make common free-form date/time/ID variations safe for the parser.""" text = unicodedata.normalize("NFKC", text).replace("\u00a0", " ") @@ -258,8 +279,6 @@ def _validate_independence(skill: str, primary: str, extras: tuple[tuple[str, in statuses = (primary,) + tuple(independence for _, _, independence in extras) if len(statuses) > MAX_COACHING_KITTENS: raise ValueError(f"В одном заходе может участвовать не более {MAX_COACHING_KITTENS} котят") - if skill == "ЗУ" and any(s != "самостоятельно" for s in statuses): - raise ValueError("Для ЗУ все котята должны быть самостоятельными") if skill == "ЛУ" and sum(status == "несамостоятельно" for status in statuses) > 1: raise ValueError("Для ЛУ допускается только один несамостоятельный котёнок") @@ -506,12 +525,13 @@ def parse_natural_bulk(text: str) -> tuple[dict[str, Any], list[str]] | None: else: questions.append("Не вижу котёнка в формате Имя и ID.") participants = kittens or fallback_kittens - labelled_statuses = _labelled_kitten_statuses(text) - independence_match = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|сам|несам)\b", text) + labelled_statuses = _participant_statuses(text, participants) + labelled_statuses.update(_labelled_kitten_statuses(text)) + independence_match = re.search(r"(?i)\b(самостоятельно|самостоятельный|несамостоятельно|несамостоятельный|несам|не\s+сам|сам)\b", text) primary_status = labelled_statuses.get(participants[0][1]) if participants else None if primary_status is None and independence_match: value = independence_match.group(1).lower() - primary_status = "несамостоятельно" if value.startswith("несам") else "самостоятельно" + primary_status = "несамостоятельно" if re.sub(r"\s+", "", value).startswith("несам") else "самостоятельно" if primary_status: fields["kitten_independence"] = primary_status else: @@ -1412,7 +1432,7 @@ class BelkiDialog: state[key] = True return self._ask_next(state) kitten_count = 1 + len(state.get("extra_kittens", ())) - if state.get("skill") == "ЛУ" and kitten_count > 1: + if kitten_count > 1: values = [part.strip() for part in text.split(",") if part.strip()] if len(values) != kitten_count: return f"Для ЛУ укажите статус каждого из {kitten_count} котят через запятую: сам, сам или несам, несам." @@ -1425,7 +1445,7 @@ class BelkiDialog: for (name, kitten_id, _), status in zip(state.get("extra_kittens", ()), extras_statuses) ] try: - _validate_independence("ЛУ", primary, extras) + _validate_independence(state.get("skill", "ЛУ"), primary, extras) except ValueError as exc: return str(exc) state["kitten_independence"] = primary diff --git a/docs/staging/bugs/2026-08-25-belki-bugs.md b/docs/staging/bugs/2026-08-25-belki-bugs.md index 2b7c53d..47c26e5 100644 --- a/docs/staging/bugs/2026-08-25-belki-bugs.md +++ b/docs/staging/bugs/2026-08-25-belki-bugs.md @@ -33,7 +33,7 @@ ## 18. Дополнительные котята: неудобный ID и неверная самостоятельность -**Статус:** ожидает исправления. +**Статус:** выполнено 25.08.2026. **Источник:** сообщения пользователя со скриншотом от 25.08.2026. @@ -63,6 +63,8 @@ - для каждого дополнительного котёнка можно выбрать оба значения самостоятельности; - приведённая строка формирует расчёт с правильным статусом каждого котёнка в веб-интерфейсе и VK-боте. +**Исправление:** ID участников переведены в текстовые поля с числовой валидацией; самостоятельность больше не блокируется для ЗУ и задаётся отдельно для каждого котёнка. Парсер естественного ввода связывает «сам»/«не сам» с ближайшим указанным котёнком. + ## 17. Название пользовательской страницы **Статус:** выполнено 25.08.2026. diff --git a/structure_and_data.md b/structure_and_data.md index 6235be6..b1643a4 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -104,6 +104,7 @@ - 2026-08-25: `/api/admin/auth` now permits five password attempts per source in a rolling 15-minute window and clears that local budget after a successful sign-in. Edge rate limiting and TLS remain required deployment controls. - 2026-08-25: server-memory admin sessions now expire after 12 hours and are capped at 100 active tokens; the browser cookie carries the same maximum age. - 2026-08-25: the deploy job waits for `deployment/belki-postgres` to become `Available`, rather than waiting for every Pod with the shared PostgreSQL label. Historical ReplicaSet Pods can remain during cleanup and must not fail a release after the current database replica is ready. +- 2026-08-25: coaching reports allow an independence status for every kitten in both ЛУ and ЗУ. Natural input attaches `сам`/`не сам` written after a participant ID to that participant, and web ID fields use numeric-text input instead of spinner controls. - 2026-08-25: removed unreferenced root-level legacy BBCode copies `belki.md`, `belki2.md`, and `belkifix.md`; the first two were byte-identical and the third differed only by a closing BBCode tag. They were neither served nor referenced by the calculator, bot, or documentation. # Обновление 2026-08-16: несколько котят diff --git a/tests/test_belki.py b/tests/test_belki.py index 186a9c6..4527603 100644 --- a/tests/test_belki.py +++ b/tests/test_belki.py @@ -67,22 +67,13 @@ class CalculationTests(unittest.TestCase): self.assertEqual(result.kitten_points, 12) def test_non_self_kitten_and_extra_companion(self): - with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"): - CoachingSession( - date="15.08", - skill="ЗУ", - start="11:00", - end="12:00", - escort_name="Белка", - escort_id=1, - kitten_name="Первый", - kitten_id=2, - kitten_independence="несамостоятельно", - extra_kittens=( - ("Второй", 3, "несамостоятельно"), - ("Третий", 4, "самостоятельно"), - ), - ) + session = CoachingSession( + date="15.08", skill="ЗУ", start="11:00", end="12:00", + escort_name="Белка", escort_id=1, kitten_name="Первый", kitten_id=2, + kitten_independence="несамостоятельно", + extra_kittens=(("Второй", 3, "несамостоятельно"), ("Третий", 4, "самостоятельно")), + ) + self.assertEqual(calculate_coaching(session).escort_points, 32.7) def test_domain_rejects_excessive_coaching_and_inspection_input(self): extras = tuple((f"Котёнок {index}", index + 2, "самостоятельно") for index in range(50)) @@ -111,19 +102,13 @@ class CalculationTests(unittest.TestCase): extra_kittens=((None, 3, "самостоятельно"),), # type: ignore[arg-type] ) - def test_zu_rejects_non_self_kitten(self): - with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"): - CoachingSession( - date="16.08", - skill="ЗУ", - start="13:00", - end="13:30", - escort_name="Дикая Вишня", - escort_id=1604614, - kitten_name="Муся", - kitten_id=134437, - kitten_independence="несамостоятельно", - ) + def test_zu_allows_a_non_self_kitten(self): + session = CoachingSession( + date="16.08", skill="ЗУ", start="13:00", end="13:30", + escort_name="Дикая Вишня", escort_id=1604614, + kitten_name="Муся", kitten_id=134437, kitten_independence="несамостоятельно", + ) + self.assertEqual(calculate_coaching(session).escort_points, 9) def test_non_self_60_minutes_gives_adult_18_and_kitten_12(self): result = calculate_coaching( @@ -179,10 +164,8 @@ class CalculationTests(unittest.TestCase): ).escort_points self.assertEqual(points("самостоятельно", "самостоятельно"), 18) - with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"): - points("самостоятельно", "несамостоятельно") - with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"): - points("несамостоятельно", "несамостоятельно") + self.assertEqual(points("самостоятельно", "несамостоятельно"), 24) + self.assertEqual(points("несамостоятельно", "несамостоятельно"), 30) def test_training_is_fixed(self): self.assertEqual(calculate_training(TrainingSession("Белка", 1, "Котёнок", 2)).points, 25) diff --git a/tests/test_vk_bot.py b/tests/test_vk_bot.py index 1cbe2be..1cc37f2 100644 --- a/tests/test_vk_bot.py +++ b/tests/test_vk_bot.py @@ -26,11 +26,12 @@ class VkBotTests(unittest.TestCase): ) self.assertEqual(command["extra_kittens"], (("Второй", 3, "самостоятельно"), ("Третий", 4, "самостоятельно"))) - def test_zu_command_rejects_non_self_kittens(self): - with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"): - parse_text_command( - "/зу 15.08 11:00 11:20 | Белка [1] | Первый [2], Второй [3] | несам" - ) + def test_zu_command_accepts_non_self_kittens(self): + command = parse_text_command( + "/зу 15.08 11:00 11:20 | Белка [1] | Первый [2], Второй [3] | несам" + ) + self.assertEqual(command["kitten_independence"], "несамостоятельно") + self.assertEqual(command["extra_kittens"], (("Второй", 3, "несамостоятельно"),)) def test_parse_help(self): self.assertEqual(parse_text_command("/help"), {"mode": "help"}) diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index dfa817e..884741f 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -192,11 +192,14 @@ class VkConversationTests(unittest.TestCase): ) self.assertEqual(inspected["fields"]["date"], expected) - def test_natural_zu_with_nonself_status_becomes_a_clarification_not_an_exception(self): - inspected = inspect_bulk_text("24.08 ЗУ 21:00 22:00 Белка [1] Ученик [2] несам") - self.assertEqual(inspected["status"], "needs_clarification") - self.assertNotIn("kitten_independence", inspected["fields"]) - self.assertIn("Для ЗУ", " ".join(inspected["questions"])) + def test_natural_zu_preserves_each_kitten_status(self): + inspected = inspect_bulk_text( + "25.08 ЗУ, Дикая Вишня 1604614, Микропипка 1708976 сам, " + "Мусипусик 1345975 не сам, 20:02-21:13" + ) + self.assertEqual(inspected["status"], "complete") + self.assertEqual(inspected["fields"]["kitten_independence"], "самостоятельно") + self.assertEqual(inspected["fields"]["extra_kittens"], [("Мусипусик", 1345975, "несамостоятельно")]) def test_training_supports_stepwise_and_natural_bulk(self): dialog = BelkiDialog() @@ -367,7 +370,7 @@ class VkConversationTests(unittest.TestCase): dialog.handle(502, answer) self.assertIn("скриншот", dialog.handle(502, "несам").lower()) - def test_compact_zu_command_rejects_non_self_variants(self): + def test_compact_zu_command_accepts_independence_variants(self): for value in ( ("сам", "самостоятельно"), ("самостоятельный", "самостоятельно"), @@ -383,10 +386,10 @@ class VkConversationTests(unittest.TestCase): ("несамостоятельный", "несамостоятельно"), ("несамостоятельно", "несамостоятельно"), ): - with self.assertRaisesRegex(ValueError, "Для ЗУ все котята должны быть самостоятельными"): - parse_text_command( - f"/зу 16.08 10:00 10:10 | Белка [1] | Малыш [2] | {value[0]}" - ) + parsed = parse_text_command( + f"/зу 16.08 10:00 10:10 | Белка [1] | Малыш [2] | {value[0]}" + ) + self.assertEqual(parsed["kitten_independence"], value[1]) def test_keyboard_changes_with_dialog_state(self): dialog = BelkiDialog() diff --git a/web/calculator.html b/web/calculator.html index 47c89da..ab2dfdf 100644 --- a/web/calculator.html +++ b/web/calculator.html @@ -96,9 +96,9 @@ - + - +