fix(domain): validate report calendar dates
This commit is contained in:
1 parent
7f16c12255
commit
1455b8cfbf
3 files changed
+22
-1
No files matched your search
+14
-1
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime
|
||||||
from difflib import SequenceMatcher
|
from difflib import SequenceMatcher
|
||||||
from math import ceil, isfinite
|
from math import ceil, isfinite
|
||||||
import re
|
import re
|
||||||
@@ -18,6 +19,7 @@ Skill = Literal["ЛУ", "ЗУ"]
|
|||||||
Place = Literal["дупло", "расщелина"]
|
Place = Literal["дупло", "расщелина"]
|
||||||
|
|
||||||
_CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
|
_CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
|
||||||
|
_DATE_RE = re.compile(r"^\d{1,2}\.\d{1,2}$")
|
||||||
|
|
||||||
# The goal calculator is public. These limits keep accidental and hostile
|
# The goal calculator is public. These limits keep accidental and hostile
|
||||||
# values from turning a simple estimate into an unbounded exponentiation.
|
# values from turning a simple estimate into an unbounded exponentiation.
|
||||||
@@ -37,6 +39,17 @@ def parse_clock(value: str) -> int:
|
|||||||
return int(hours) * 60 + int(minutes)
|
return int(hours) * 60 + int(minutes)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_report_date(value: str) -> tuple[int, int]:
|
||||||
|
"""Validate a report date in ``ДД.ММ`` form without imposing a year."""
|
||||||
|
if not isinstance(value, str) or not _DATE_RE.fullmatch(value):
|
||||||
|
raise ValueError("Дата должна быть в формате ДД.ММ, например 15.08")
|
||||||
|
try:
|
||||||
|
parsed = datetime.strptime(f"2000.{value}", "%Y.%d.%m")
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValueError("Укажите существующую дату в формате ДД.ММ") from exc
|
||||||
|
return parsed.day, parsed.month
|
||||||
|
|
||||||
|
|
||||||
def format_clock(minutes: int) -> str:
|
def format_clock(minutes: int) -> str:
|
||||||
"""Преобразует количество минут от начала суток обратно в строку 'HH:MM'."""
|
"""Преобразует количество минут от начала суток обратно в строку 'HH:MM'."""
|
||||||
if not isinstance(minutes, int) or not 0 <= minutes < 24 * 60:
|
if not isinstance(minutes, int) or not 0 <= minutes < 24 * 60:
|
||||||
@@ -76,12 +89,12 @@ class CoachingSession:
|
|||||||
"""Валидирует данные сессии при создании."""
|
"""Валидирует данные сессии при создании."""
|
||||||
if self.skill not in ("ЛУ", "ЗУ"):
|
if self.skill not in ("ЛУ", "ЗУ"):
|
||||||
raise ValueError("Навык должен быть ЛУ или ЗУ")
|
raise ValueError("Навык должен быть ЛУ или ЗУ")
|
||||||
|
parse_report_date(self.date)
|
||||||
parse_clock(self.start)
|
parse_clock(self.start)
|
||||||
parse_clock(self.end)
|
parse_clock(self.end)
|
||||||
for value, label in (
|
for value, label in (
|
||||||
(self.escort_name, "Имя сопровождающего"),
|
(self.escort_name, "Имя сопровождающего"),
|
||||||
(self.kitten_name, "Имя котёнка"),
|
(self.kitten_name, "Имя котёнка"),
|
||||||
(self.date, "Дата"),
|
|
||||||
):
|
):
|
||||||
if not isinstance(value, str) or not value.strip():
|
if not isinstance(value, str) or not value.strip():
|
||||||
raise ValueError(f"{label} не может быть пустым")
|
raise ValueError(f"{label} не может быть пустым")
|
||||||
|
|||||||
@@ -69,6 +69,7 @@
|
|||||||
- 2026-08-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response.
|
- 2026-08-25: long-lived authenticated admin refresh WebSockets now have a separate eight-connection pool, so they cannot consume all 32 request workers; additional connections receive an explicit temporary-unavailable response.
|
||||||
- 2026-08-25: application validation now bounds names, attachment and feather rows, and descriptive text for both web and VK submissions. Stored attachment and review links must be HTTPS; the optional profile link is restricted to a real VK host.
|
- 2026-08-25: application validation now bounds names, attachment and feather rows, and descriptive text for both web and VK submissions. Stored attachment and review links must be HTTPS; the optional profile link is restricted to a real VK host.
|
||||||
- 2026-08-25: admin history sorting now tolerates legacy records whose IDs were stored as strings, preserving numeric order for valid IDs instead of failing the complete history view.
|
- 2026-08-25: admin history sorting now tolerates legacy records whose IDs were stored as strings, preserving numeric order for valid IDs instead of failing the complete history view.
|
||||||
|
- 2026-08-25: coaching sessions now validate a real calendar date in `ДД.ММ` form before any calculation or persistence; free-form dates remain accepted after parser normalization.
|
||||||
- 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback.
|
- 2026-08-25: one-line VK/web recognition now gives explicit role labels priority over position. `сопровождающий`/`наставник`/`учитель` identify the escort, while `ученик`/`котёнок`/`бельчонок`/`подопечный` identify the ward; unlabeled pairs retain the original order-based fallback.
|
||||||
- 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation.
|
- 2026-08-25: corrected Russian UX copy in the VK help and attachment flow; the web identity hint now accurately says that a manually completed pair applies only to the current calculation.
|
||||||
- 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model.
|
- 2026-08-25: natural input normalizes Unicode spaces, dash variants, `ID`/`№` prefixes, spaced IDs, common date/time separators, and close role-label typos before extracting structured fields. Natasha was evaluated for Russian NER through Context7 but not added: game nicknames are better anchored by user-provided IDs and local role context than a generic person model.
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from app.belki.domain import (
|
|||||||
calculate_training,
|
calculate_training,
|
||||||
format_clock,
|
format_clock,
|
||||||
parse_clock,
|
parse_clock,
|
||||||
|
parse_report_date,
|
||||||
)
|
)
|
||||||
from app.belki.reports import render_coaching, render_inspection, render_training
|
from app.belki.reports import render_coaching, render_inspection, render_training
|
||||||
|
|
||||||
@@ -28,6 +29,12 @@ class ClockTests(unittest.TestCase):
|
|||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
parse_clock("5:5")
|
parse_clock("5:5")
|
||||||
|
|
||||||
|
def test_report_date_requires_a_real_calendar_day(self):
|
||||||
|
self.assertEqual(parse_report_date("29.02"), (29, 2))
|
||||||
|
for value in ("31.02", "32.01", "15/08", "today"):
|
||||||
|
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||||
|
parse_report_date(value)
|
||||||
|
|
||||||
|
|
||||||
class CalculationTests(unittest.TestCase):
|
class CalculationTests(unittest.TestCase):
|
||||||
def test_goal_rejects_non_finite_and_unbounded_input(self):
|
def test_goal_rejects_non_finite_and_unbounded_input(self):
|
||||||
|
|||||||
Reference in new issue
Block a user