feat: add standalone goal calculator
This commit is contained in:
1 parent
0041e683fe
commit
b948331b72
3 files changed
+89
No files matched your search
@@ -15,6 +15,7 @@ from .domain import (
|
||||
calculate_coaching,
|
||||
calculate_inspection,
|
||||
calculate_training,
|
||||
calculate_goal,
|
||||
)
|
||||
from .reports import render_coaching, render_inspection, render_training
|
||||
from .identity import IdentityDirectory
|
||||
@@ -186,6 +187,30 @@ def calculate_payload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
result = calculate_inspection(report)
|
||||
return {"mode": mode, "result": asdict(result), "message": render_inspection(report, result)}
|
||||
if mode == "goal":
|
||||
def _number_value(key: str) -> float:
|
||||
value = _required(payload, key)
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ApiError(f"Поле {key} должно быть числом") from exc
|
||||
|
||||
minutes = _int(payload, "minutes_per_session")
|
||||
result = calculate_goal(
|
||||
current_points=_number_value("current_points"),
|
||||
target_points=_number_value("target_points"),
|
||||
minutes_per_session=minutes,
|
||||
skill=str(payload.get("skill", "ЛУ")),
|
||||
kitten_independence=str(payload.get("kitten_independence", "самостоятельно")),
|
||||
kitten_count=_int(payload, "kitten_count"),
|
||||
)
|
||||
message = (
|
||||
f"Осталось добрать: {result.remaining_points} баллов.\n"
|
||||
f"За один заход ({result.minutes_per_session} мин): {result.points_per_session} баллов.\n"
|
||||
f"Нужно заходов: {result.sessions}.\n"
|
||||
f"Общее время: {result.total_minutes} минут ({result.total_hours} ч)."
|
||||
)
|
||||
return {"mode": mode, "result": asdict(result), "message": message}
|
||||
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
||||
if isinstance(exc, ApiError):
|
||||
raise
|
||||
|
||||
@@ -110,6 +110,58 @@ class CoachingResult:
|
||||
escort_multiplier: float = 1.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GoalResult:
|
||||
"""Результат обратного расчёта цели по баллам."""
|
||||
current_points: float | int
|
||||
target_points: float | int
|
||||
remaining_points: float | int
|
||||
minutes_per_session: int
|
||||
points_per_session: float | int
|
||||
sessions: int
|
||||
total_minutes: int
|
||||
total_hours: float | int
|
||||
|
||||
|
||||
def calculate_goal(
|
||||
*,
|
||||
current_points: float,
|
||||
target_points: float,
|
||||
minutes_per_session: int,
|
||||
skill: Skill = "ЛУ",
|
||||
kitten_independence: Independence = "самостоятельно",
|
||||
kitten_count: int = 1,
|
||||
) -> GoalResult:
|
||||
"""Рассчитывает, сколько времени нужно до целевого числа баллов."""
|
||||
if skill not in ("ЛУ", "ЗУ"):
|
||||
raise ValueError("Навык должен быть ЛУ или ЗУ")
|
||||
if kitten_independence not in ("самостоятельно", "несамостоятельно"):
|
||||
raise ValueError("Некорректный статус самостоятельности")
|
||||
if current_points < 0 or target_points < 0:
|
||||
raise ValueError("Баллы не могут быть отрицательными")
|
||||
if minutes_per_session <= 0:
|
||||
raise ValueError("Продолжительность захода должна быть больше нуля")
|
||||
if kitten_count <= 0:
|
||||
raise ValueError("Количество котят должно быть положительным")
|
||||
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)
|
||||
remaining = _points(max(target_points - current_points, 0))
|
||||
sessions = 0 if remaining == 0 else int(-(-remaining / points_per_session))
|
||||
total_minutes = sessions * minutes_per_session
|
||||
total_hours_value = total_minutes / 60
|
||||
total_hours = int(total_hours_value) if total_hours_value.is_integer() else round(total_hours_value, 2)
|
||||
return GoalResult(
|
||||
current_points=_points(current_points), target_points=_points(target_points),
|
||||
remaining_points=remaining, minutes_per_session=minutes_per_session,
|
||||
points_per_session=points_per_session, sessions=sessions,
|
||||
total_minutes=total_minutes, total_hours=total_hours,
|
||||
)
|
||||
|
||||
|
||||
def calculate_coaching(session: CoachingSession) -> CoachingResult:
|
||||
"""
|
||||
Рассчитывает баллы за сессию тренировки.
|
||||
|
||||
@@ -32,6 +32,18 @@ class ApiTests(unittest.TestCase):
|
||||
with self.assertRaises(ApiError):
|
||||
calculate_payload({"mode": "unknown"})
|
||||
|
||||
def test_goal_calculator_returns_remaining_points_and_hours(self):
|
||||
response = calculate_payload({
|
||||
"mode": "goal", "current_points": 10, "target_points": 34,
|
||||
"minutes_per_session": 20, "skill": "ЛУ",
|
||||
"kitten_independence": "самостоятельно", "kitten_count": 1,
|
||||
})
|
||||
self.assertEqual(response["result"]["remaining_points"], 24)
|
||||
self.assertEqual(response["result"]["points_per_session"], 4)
|
||||
self.assertEqual(response["result"]["sessions"], 6)
|
||||
self.assertEqual(response["result"]["total_hours"], 2)
|
||||
self.assertIn("Осталось добрать: 24", response["message"])
|
||||
|
||||
def test_calculate_inspection_payload(self):
|
||||
response = calculate_payload(
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user