"""Drill assignments (N20-N22). Progress is the number of AssignmentSet rows; each set also writes one drill log.""" from datetime import UTC, date, datetime from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession from app.common.academy_access import ( Staff, require_player, sessions_shared, staff_context, visible_players_query, ) from app.common.labels import DISCIPLINES, drill_catalog from app.common.media import media_ref from app.common.notify import notify from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed from app.core.pagination import PageParams, paginate from app.integrations.push import PushClient from app.integrations.storage import StorageClient from app.modules.accounts.models import Account from app.modules.assignments.models import DrillAssignment from app.modules.assignments.repository import AssignmentRepository from app.modules.assignments.schemas import AssignIn, AssignmentOut, AssignmentPage, SetIn, SetLogOut, SetResult def due_label(due: date, today: date) -> str: days = (due - today).days if days == 0: return "Today" if days == 1: return "Tomorrow" if 1 < days < 7: return f"{due:%A}" return f"{due:%b} {due.day:02d}" class AssignmentService: def __init__(self, db: AsyncSession, storage: StorageClient | None = None, push: PushClient | None = None): self.db = db self.storage = storage self.push = push self.repo = AssignmentRepository(db) async def _outs(self, rows: list[tuple[DrillAssignment, int]]) -> list[AssignmentOut]: names = await self.repo.names({a.assigned_by_id for a, _ in rows}) library = {UUID(a.drill_id) for a, _ in rows if a.drill_source == "library"} media = await self.repo.library_media_keys(library) today = datetime.now(UTC).date() out = [] for a, done in rows: ref = None if a.drill_source == "library" and self.storage is not None and UUID(a.drill_id) in media: upload_id, key = media[UUID(a.drill_id)] ref = media_ref(self.storage, upload_id, key) out.append(AssignmentOut( id=a.id, player_id=a.player_id, mode=a.mode, drill_id=a.drill_id, drill_source=a.drill_source, name=a.name, fixes=a.fixes, sets=a.sets, reps=a.reps, due=due_label(a.due_date, today), due_date=a.due_date, assigned_by=names.get(a.assigned_by_id) if a.assigned_by_id else None, assigned_by_id=a.assigned_by_id, done=int(done), session_id=a.session_id, assigned_at=a.created_at, media=ref)) return out async def _one(self, assignment: DrillAssignment) -> AssignmentOut: return (await self._outs([(assignment, await self.repo.done_count(assignment.id))]))[0] async def list(self, account: Account, mode: str, player_id: UUID | None, status: str, paging: PageParams) -> AssignmentPage: if account.role == "player": if player_id is not None and player_id != account.id: raise NotFound() query = self.repo.list_query(mode=mode, status=status, player_ids=None, player_id=account.id, team_id=None) else: staff = await staff_context(self.db, account) if staff is None: raise Forbidden("Only coaches can do this.") if player_id is not None: await require_player(self.db, staff, player_id) query = self.repo.list_query(mode=mode, status=status, player_ids=visible_players_query(staff), player_id=player_id, team_id=staff.team_id) rows = await self.repo.page(query, paging.cursor, paging.limit) page, cursor = paginate(rows, paging.limit, lambda r: (r[0].created_at, r[0].id)) items = await self._outs([(a, n) for a, n in page]) return AssignmentPage(items=items, next_cursor=cursor) async def _source(self, staff: Staff, body: AssignIn) -> tuple[str, str]: """(name, fixes) snapshot of the drill, or the error to raise.""" if body.drill_source == "catalog": drill = drill_catalog().get(body.drill_id) if drill is None: raise NotFound("Drill not found.", code="DRILL_NOT_FOUND") if drill["discipline"] != DISCIPLINES[body.mode]: raise Unprocessable("This drill is for the other mode.", code="MODE_MISMATCH") fixes = ", ".join(f.replace("_", " ").capitalize() for f in drill.get("faults", [])) return drill["name"], fixes try: library_id = UUID(body.drill_id) except ValueError as exc: raise ValidationFailed(fields={"drill_id": "Must be a library drill id."}) from exc drill = await self.repo.library_drill(library_id, staff.team_id) if drill is None: raise NotFound("Drill not found.", code="DRILL_NOT_FOUND") if drill.mode != body.mode: raise Unprocessable("This drill is for the other mode.", code="MODE_MISMATCH") return drill.name, drill.fixes async def assign(self, staff: Staff, player_id: UUID, body: AssignIn) -> AssignmentOut: staff.require("drills") player = await require_player(self.db, staff, player_id) if body.due_date < datetime.now(UTC).date(): raise ValidationFailed(fields={"due_date": "Must not be in the past."}) name, fixes = await self._source(staff, body) if body.source_session_id is not None and not ( await sessions_shared(self.db, player_id) and await self.repo.owns_session(player_id, body.source_session_id)): raise NotFound("Session not found.", code="SESSION_NOT_FOUND") assignment = await self.repo.create( team_id=staff.team_id, player_id=player.id, assigned_by_id=staff.id, mode=body.mode, drill_source=body.drill_source, drill_id=body.drill_id, name=name, fixes=fixes, sets=3, reps=8, due_date=body.due_date, session_id=body.source_session_id) await notify(self.db, self.push, player.id, kind="drill", title="New drill assigned", body=name, target={}, event_key=f"assignment:{assignment.id}") return (await self._outs([(assignment, 0)]))[0] async def log_set(self, player: Account, assignment_id: UUID, body: SetIn) -> SetResult: assignment = await self.repo.with_progress(assignment_id, player_id=player.id, lock=True) if assignment is None: raise NotFound() if body.set_number > assignment.sets: raise Unprocessable(f"This drill has {assignment.sets} sets.", code="SET_OUT_OF_RANGE") if body.reps_done > assignment.reps: raise Unprocessable(f"At most {assignment.reps} reps per set.", code="REPS_OUT_OF_RANGE") row = await self.repo.existing_set(assignment.id, body.set_number) if row is not None and (row.reps_done, row.day) != (body.reps_done, body.day): raise Conflict("That set was already logged with different values.", code="SET_ALREADY_LOGGED") if row is None: row = await self.repo.add_set(assignment, body.set_number, body.reps_done, body.day) return SetResult(assignment=await self._one(assignment), set_log=SetLogOut(id=row.id, set_number=row.set_number, reps_done=row.reps_done, day=row.day))