Files
cwshed-clone/app/belki/domain.py
T
2026-08-16 23:40:15 +03:00

197 lines
7.8 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
from difflib import SequenceMatcher
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("Некорректный статус самостоятельности")
if any(independence != self.kitten_independence for _, _, independence in self.extra_kittens):
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
kitten_count: int = 1
escort_multiplier: float = 1.0
def calculate_coaching(session: CoachingSession) -> CoachingResult:
minutes = session.duration_minutes(session.start, session.end)
if minutes <= 0:
raise ValueError("Продолжительность захода должна быть больше нуля")
kitten_count = 1 + len(session.extra_kittens)
# Several wards share one report: the second ward pays 1.5x, and each
# following ward adds a further 1.15x multiplier instead of another full
# base payout.
ward_multiplier = 1.0 if kitten_count == 1 else 1.5 * (1.15 ** (kitten_count - 2))
# The independence bonus applies to every skill, including зоркость (ЗУ),
# and is calculated separately for each non-independent kitten.
nonself_count = (session.kitten_independence == "несамостоятельно") + sum(
independence == "несамостоятельно" for _, _, independence in session.extra_kittens
)
nonself_bonus = minutes * 0.5 * nonself_count / 5
return CoachingResult(
minutes=minutes,
escort_points=_points(minutes * ward_multiplier / 5 + nonself_bonus),
kitten_points=_points(minutes / 5),
kitten_count=kitten_count,
escort_multiplier=round(ward_multiplier, 4),
)
@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) or amount < 0:
raise ValueError("Ресурс должен иметь название и неотрицательное целое количество")
@dataclass(frozen=True)
class InspectionResult:
points: int
def _inspection_resource_value(name: str) -> int:
normalized = " ".join(name.casefold().replace("ё", "е").split())
letters = re.sub(r"[^а-я]", "", normalized)
if "надпис" in letters or "ядовит" in letters:
return 0
if "лугов" in normalized and "зме" in normalized:
return 1
if (
"щитоморд" in letters
or "аспид" in letters
or letters in ("змея", "змеи")
or SequenceMatcher(None, letters, "змея").ratio() >= 0.8
):
return 0
if "паутин" in letters or "паутн" in letters:
return 7
if "обычн" in normalized and "мох" in normalized:
return 3
if "водян" in normalized and "мох" in 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)