Files
cwshed-clone/app/belki/domain.py
T

173 lines
6.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
from dataclasses import dataclass, field
import re
from typing import Literal
Independence = Literal["самостоятельно", "несамостоятельно"]
Skill = Literal["ЛУ", "ЗУ"]
Place = Literal["дупло", "расщелина"]
_CLOCK_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$")
def parse_clock(value: str) -> int:
if not isinstance(value, str) or not _CLOCK_RE.fullmatch(value):
raise ValueError("Время должно быть в формате HH:MM, например 05:07")
hours, minutes = value.split(":")
return int(hours) * 60 + int(minutes)
def format_clock(minutes: int) -> str:
if not isinstance(minutes, int) or not 0 <= minutes < 24 * 60:
raise ValueError("Время должно быть минутами внутри суток")
return f"{minutes // 60:02d}:{minutes % 60:02d}"
def _positive_id(value: int, label: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
raise ValueError(f"{label} должен быть положительным целым числом")
return value
def _points(value: float) -> float | int:
if value.is_integer():
return int(value)
return round(value, 2)
@dataclass(frozen=True)
class CoachingSession:
date: str
skill: Skill
start: str
end: str
escort_name: str
escort_id: int
kitten_name: str
kitten_id: int
kitten_independence: Independence = "самостоятельно"
extra_kittens: tuple[tuple[str, int, Independence], ...] = field(default_factory=tuple)
def __post_init__(self) -> None:
if self.skill not in ("ЛУ", "ЗУ"):
raise ValueError("Навык должен быть ЛУ или ЗУ")
parse_clock(self.start)
parse_clock(self.end)
for value, label in (
(self.escort_name, "Имя сопровождающего"),
(self.kitten_name, "Имя котёнка"),
(self.date, "Дата"),
):
if not isinstance(value, str) or not value.strip():
raise ValueError(f"{label} не может быть пустым")
_positive_id(self.escort_id, "ID сопровождающего")
_positive_id(self.kitten_id, "ID котёнка")
if self.kitten_independence not in ("самостоятельно", "несамостоятельно"):
raise ValueError("Некорректный статус самостоятельности")
for name, kitten_id, independence in self.extra_kittens:
if not name.strip():
raise ValueError("Имя дополнительного котёнка не может быть пустым")
_positive_id(kitten_id, "ID дополнительного котёнка")
if independence not in ("самостоятельно", "несамостоятельно"):
raise ValueError("Некорректный статус самостоятельности")
@staticmethod
def duration_minutes(start: str, end: str) -> int:
start_minutes = parse_clock(start)
end_minutes = parse_clock(end)
return (end_minutes - start_minutes) % (24 * 60)
@dataclass(frozen=True)
class CoachingResult:
minutes: int
escort_points: float | int
kitten_points: float | int
def calculate_coaching(session: CoachingSession) -> CoachingResult:
minutes = session.duration_minutes(session.start, session.end)
if minutes <= 0:
raise ValueError("Продолжительность захода должна быть больше нуля")
escort_multiplier = 1.5 if session.kitten_independence == "несамостоятельно" else 1.0
for _, _, independence in session.extra_kittens:
if independence == "несамостоятельно":
escort_multiplier += 0.5
return CoachingResult(
minutes=minutes,
escort_points=_points(minutes * escort_multiplier / 5),
kitten_points=_points(minutes * 2 / 5),
)
@dataclass(frozen=True)
class TrainingSession:
escort_name: str
escort_id: int
kitten_name: str
kitten_id: int
def __post_init__(self) -> None:
if not self.escort_name.strip() or not self.kitten_name.strip():
raise ValueError("Имена участников не могут быть пустыми")
_positive_id(self.escort_id, "ID сопровождающего")
_positive_id(self.kitten_id, "ID котёнка")
@dataclass(frozen=True)
class TrainingResult:
points: int = 25
def calculate_training(session: TrainingSession) -> TrainingResult:
return TrainingResult()
@dataclass(frozen=True)
class InspectionReport:
character_name: str
character_id: int
place: Place
inspections: int
resources: tuple[tuple[str, int], ...] = field(default_factory=tuple)
def __post_init__(self) -> None:
if not self.character_name.strip():
raise ValueError("Имя персонажа не может быть пустым")
_positive_id(self.character_id, "ID персонажа")
if self.place not in ("дупло", "расщелина"):
raise ValueError("Место должно быть дуплом или расщелиной")
if isinstance(self.inspections, bool) or not isinstance(self.inspections, int) or self.inspections < 0:
raise ValueError("Количество осмотров должно быть неотрицательным целым")
for name, amount in self.resources:
if not name.strip() or not isinstance(amount, int):
raise ValueError("Ресурс должен иметь название и целое количество")
@dataclass(frozen=True)
class InspectionResult:
points: int
def _inspection_resource_value(name: str) -> int:
normalized = " ".join(name.casefold().replace("ё", "е").split())
if "надпис" in normalized or "ядовит" in normalized:
return 0
if normalized in ("паутина", "паук"):
return 7
if normalized == "обычный мох":
return 3
if normalized == "водяной мох":
return 2
return 1
def calculate_inspection(report: InspectionReport) -> InspectionResult:
points = report.inspections * 2
points += sum(amount * _inspection_resource_value(name) for name, amount in report.resources)
return InspectionResult(points=points)