fix: preserve independence for each kitten

This commit is contained in:
nyan404 committed 2026-08-25 21:36:03 +03:00
1 parent 7018bc0398
commit fa61d11912
8 files changed
+66 -66

No files matched your search

-5
View File
@@ -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)
+27 -7
View File
@@ -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
+3 -1
View File
@@ -33,7 +33,7 @@
## 18. Дополнительные котята: неудобный ID и неверная самостоятельность
**Статус:** ожидает исправления.
**Статус:** выполнено 25.08.2026.
**Источник:** сообщения пользователя со скриншотом от 25.08.2026.
@@ -63,6 +63,8 @@
- для каждого дополнительного котёнка можно выбрать оба значения самостоятельности;
- приведённая строка формирует расчёт с правильным статусом каждого котёнка в веб-интерфейсе и VK-боте.
**Исправление:** ID участников переведены в текстовые поля с числовой валидацией; самостоятельность больше не блокируется для ЗУ и задаётся отдельно для каждого котёнка. Парсер естественного ввода связывает «сам»/«не сам» с ближайшим указанным котёнком.
## 17. Название пользовательской страницы
**Статус:** выполнено 25.08.2026.
+1
View File
@@ -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: несколько котят
+13 -30
View File
@@ -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,
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, "самостоятельно"),
),
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)
+4 -3
View File
@@ -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(
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"})
+11 -8
View File
@@ -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(
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()
+7 -12
View File
@@ -96,9 +96,9 @@
<label>Начало<input name="start" type="time" value="11:00" required></label>
<label>Конец<input name="end" type="time" value="11:20" required></label>
<label>Имя сопровождающего<input name="escort_name" required></label>
<label>ID сопровождающего<input name="escort_id" type="number" min="1" required></label>
<label>ID сопровождающего<input name="escort_id" type="text" inputmode="numeric" pattern="[0-9]+" 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="text" inputmode="numeric" pattern="[0-9]+" required></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">
<label>Дополнительные котята <span class="muted">(общие баллы не суммируются; 2-й ×1,5, следующие ×1,15)</span></label>
@@ -248,7 +248,7 @@
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>
<input data-extra="id" type="text" inputmode="numeric" pattern="[0-9]+" 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 || '';
@@ -261,23 +261,18 @@
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
// Returns all independence controls participating in the current coaching form.
function statusFields() { return [document.querySelector('#coaching [name="kitten_independence"]'), ...extraKittens.querySelectorAll('[data-extra="independence"]')]; }
// Enables or locks independence controls according to the selected skill.
// Keeps every kitten's independence selection available for the chosen skill.
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 = 'Для ЛУ можно указать не более одного несамостоятельного котёнка.';
}
statusHelp.textContent = document.querySelector('#coaching [name="skill"]').value === 'ЛУ'
? 'Для ЛУ можно указать не более одного несамостоятельного котёнка.'
: 'Укажите самостоятельность каждого котёнка отдельно.';
}
// Returns a user-facing validation error when kitten statuses conflict.
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 '';
}