Spaces:
Running on T4
Running on T4
Download backend/app/modules/goals/service.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 9.03 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/goals/service.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/modules/goals/service.py
-
curl -L -o service.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/goals/service.py
9.03 kB
| """Coach-set goals (N16-N19). The active goal has ended_at NULL; a change ends it and inserts a new version.""" | |
| from calendar import monthrange | |
| from datetime import UTC, date, datetime, time, timedelta | |
| from functools import cache | |
| from uuid import UUID | |
| from ai_coach.swing_report import repository as registry | |
| from sqlalchemy.exc import IntegrityError | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from app.common.academy_access import Staff, can_see_player, require_player, staff_context | |
| from app.common.notify import notify | |
| from app.common.schemas import Page | |
| from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed | |
| from app.core.pagination import PageParams, paginate | |
| from app.integrations.push import PushClient | |
| from app.modules.accounts.models import Account | |
| from app.modules.goals.models import Goal | |
| from app.modules.goals.repository import GoalRepository | |
| from app.modules.goals.schemas import GoalEnvelope, GoalHistoryOut, GoalIn, GoalOut, MilestoneOut, WeeklyOut | |
| DUE_DAYS = {"1 week": 7, "2 weeks": 14} | |
| def _metrics() -> dict[str, dict]: | |
| return {m["metric_id"]: m for m in registry.metrics()} | |
| def _group_count() -> int: | |
| return len(registry.groups()) | |
| def _num(goal: Goal) -> int | float: | |
| return float(goal.target) if goal.type == "param" else int(goal.target) | |
| def _metric_name(metric_id: str | None) -> str | None: | |
| return _metrics()[metric_id]["display_name"] if metric_id in _metrics() else None | |
| def _out(goal: Goal, set_by: str | None) -> GoalOut: | |
| return GoalOut( | |
| id=goal.id, player_id=goal.player_id, mode=goal.mode, type=goal.type, target=_num(goal), | |
| metric_id=goal.metric_id, metric_name=_metric_name(goal.metric_id), due=goal.due, due_at=goal.due_at, | |
| set_at=goal.created_at, set_by=set_by, set_by_id=goal.set_by_id, note=goal.note, | |
| weekly=WeeklyOut(practice_days=goal.weekly_practice_days, drill_sets=goal.weekly_drill_sets), | |
| version=goal.version) | |
| def _due_at(due: str, now: datetime) -> datetime: | |
| today = now.date() | |
| last = today if due not in DUE_DAYS else today + timedelta(days=DUE_DAYS[due]) | |
| if due == "End of month": | |
| last = today.replace(day=monthrange(today.year, today.month)[1]) | |
| return datetime.combine(last, time(23, 59, 59), tzinfo=UTC) | |
| def _fmt(day: date | datetime, year: bool = False) -> str: | |
| return f"{day:%b} {day.day}" + (f", {day.year}" if year else "") | |
| def _text(goal: Goal) -> str: | |
| target = _num(goal) | |
| if goal.type == "groups": | |
| return f"Get {target} of {_group_count()} groups on target" | |
| if goal.type == "score": | |
| return f"Reach a score of {target}" | |
| metric = _metrics().get(goal.metric_id or "") | |
| name = metric["display_name"] if metric else "Metric" | |
| return f"Get {name} to {target:g}" + (f" {metric['unit']}" if metric and metric.get("unit") else "") | |
| def _range(goal: Goal) -> str: | |
| start, end = goal.created_at, goal.ended_at | |
| if end is None: | |
| return f"From {_fmt(start, True)}" | |
| if start.year == end.year: | |
| return f"{_fmt(start)} to {_fmt(end, True)}" | |
| return f"{_fmt(start, True)} to {_fmt(end, True)}" | |
| def _met(goal: Goal) -> bool | None: | |
| return {"met": True, "not_met": False}.get(goal.outcome or "") | |
| class GoalService: | |
| def __init__(self, db: AsyncSession, push: PushClient | None = None): | |
| self.db = db | |
| self.push = push | |
| self.goals = GoalRepository(db) | |
| async def _authorize_read(self, account: Account, player_id: UUID) -> UUID | None: | |
| """Returns the team that scopes the goals a reader may see (None: a player sees all their own).""" | |
| if account.role == "player": | |
| if account.id != player_id: | |
| raise NotFound() | |
| return None | |
| staff = await staff_context(self.db, account) | |
| if staff is None: | |
| raise Forbidden("Only coaches can do this.") | |
| if not await can_see_player(self.db, staff, player_id): | |
| raise NotFound("Player not on your team.", code="PLAYER_NOT_ON_TEAM") | |
| return staff.team_id | |
| async def current(self, account: Account, player_id: UUID, mode: str) -> GoalEnvelope: | |
| team_id = await self._authorize_read(account, player_id) | |
| goal = await self.goals.active(player_id, mode, team_id=team_id) | |
| if goal is None: | |
| return GoalEnvelope(goal=None) | |
| return GoalEnvelope(goal=_out(goal, await self.goals.author_name(goal.set_by_id))) | |
| def _validate(self, mode: str, body: GoalIn) -> None: | |
| fields: dict[str, str] = {} | |
| target = body.target | |
| if body.type == "groups": | |
| groups = _group_count() if mode == "h" else 0 | |
| if isinstance(target, float) and not target.is_integer() or not 1 <= target <= groups: | |
| fields["target"] = f"Must be a whole number from 1 to {groups}." if groups else "Not available." | |
| elif body.type == "score": | |
| if isinstance(target, float) and not target.is_integer() or not 50 <= target <= 100: | |
| fields["target"] = "Must be a whole number from 50 to 100." | |
| elif not -50 <= target <= 500: | |
| fields["target"] = "Must be from -50 to 500." | |
| if body.type == "param": | |
| if not body.metric_id or body.metric_id not in _metrics() or mode != "h": | |
| fields["metric_id"] = "Choose a known metric." | |
| elif body.metric_id is not None: | |
| fields["metric_id"] = "Only used with a param goal." | |
| if fields: | |
| raise ValidationFailed(fields=fields) | |
| async def set(self, staff: Staff, player_id: UUID, mode: str, body: GoalIn) -> GoalEnvelope: | |
| staff.require("goals") | |
| player = await require_player(self.db, staff, player_id) | |
| self._validate(mode, body) | |
| target = body.target if body.type == "param" else int(body.target) | |
| active = await self.goals.active(player_id, mode, lock=True) | |
| if active is not None and self._same(active, body, target): | |
| return GoalEnvelope(goal=_out(active, await self.goals.author_name(active.set_by_id))) | |
| current_version = active.version if active else 0 | |
| if body.expected_version is not None and body.expected_version != current_version: | |
| raise Conflict("This goal changed. Refresh and try again.", code="STALE_VERSION") | |
| now = datetime.now(UTC) | |
| if active is not None: | |
| await self.goals.end(active, now) | |
| try: | |
| async with self.db.begin_nested(): | |
| goal = await self.goals.create( | |
| player_id=player_id, team_id=player.team_id, mode=mode, type=body.type, target=target, | |
| metric_id=body.metric_id, due=body.due, due_at=_due_at(body.due, now), | |
| weekly_practice_days=body.weekly.practice_days, weekly_drill_sets=body.weekly.drill_sets, | |
| note=body.note, set_by_id=staff.id, version=current_version + 1) | |
| except IntegrityError as exc: # a concurrent first goal won the race | |
| raise Conflict("This goal changed. Refresh and try again.", code="STALE_VERSION") from exc | |
| await notify(self.db, self.push, player_id, kind="drill", title="Your coach set a new goal", | |
| body=_text(goal), target={}, event_key=f"goal:{goal.id}") | |
| return GoalEnvelope(goal=_out(goal, staff.account.name)) | |
| def _same(goal: Goal, body: GoalIn, target: int | float) -> bool: | |
| return (goal.type, float(goal.target), goal.metric_id, goal.due, goal.weekly_practice_days, | |
| goal.weekly_drill_sets, goal.note) == ( | |
| body.type, float(target), body.metric_id, body.due, body.weekly.practice_days, body.weekly.drill_sets, | |
| body.note) | |
| async def history(self, account: Account, player_id: UUID, mode: str, paging: PageParams) -> Page[GoalHistoryOut]: | |
| team_id = await self._authorize_read(account, player_id) | |
| rows = list(await self.goals.ended(player_id, mode, paging.cursor, paging.limit, team_id=team_id)) | |
| page, next_cursor = paginate(rows, paging.limit) | |
| items = [GoalHistoryOut(id=g.id, text=_text(g), range=_range(g), met=_met(g), outcome=g.outcome, | |
| start_at=g.created_at, end_at=g.ended_at, evaluated_session_id=g.evaluated_session_id) | |
| for g in page] | |
| return Page[GoalHistoryOut](items=items, next_cursor=next_cursor) | |
| async def milestones(self, account: Account, mode: str, paging: PageParams) -> Page[MilestoneOut]: | |
| rows = list(await self.goals.ended(account.id, mode, paging.cursor, paging.limit, met_only=True)) | |
| page, next_cursor = paginate(rows, paging.limit) | |
| items = [MilestoneOut(id=g.id, icon="flag", tone="b", title=f"Goal met: {_text(g)}", | |
| when=_fmt(g.ended_at, True), occurred_at=g.ended_at, source_goal_id=g.id) # type: ignore[arg-type] | |
| for g in page] | |
| return Page[MilestoneOut](items=items, next_cursor=next_cursor) | |