"""Coach views: the team's players and their self, analysed sessions.""" from collections.abc import Sequence from datetime import datetime from uuid import UUID from sqlalchemy import Select, and_, func, or_, select from app.common.base_repository import BaseRepository from app.core.pagination import Cursor from app.modules.academy.models import GroupPlayer from app.modules.accounts.models import Account from app.modules.reviews.models import Review from app.modules.sessions.models import SwingSession from app.modules.sessions.summary import summary_query from app.modules.settings.models import UserSettings RECENT_PER_MODE = 3 class CoachRepository(BaseRepository[Account]): model = Account async def visible_players(self, visible_ids) -> Sequence[Account]: """Accounts for a `visible_players_query` select, by name.""" query = select(Account).where(Account.id.in_(visible_ids)).order_by(Account.name, Account.created_at) return (await self.session.execute(query)).scalars().all() async def sessions_hidden(self, player_ids: list[UUID]) -> set[UUID]: """Players who turned off coach_can_see_sessions.""" query = select(UserSettings.account_id).where(UserSettings.account_id.in_(player_ids), UserSettings.coach_can_see_sessions.is_(False)) return set((await self.session.scalars(query)).all()) async def group_ids(self, player_ids: list[UUID]) -> dict[UUID, list[UUID]]: query = (select(GroupPlayer.player_id, GroupPlayer.group_id).where(GroupPlayer.player_id.in_(player_ids)) .order_by(GroupPlayer.group_id)) result: dict[UUID, list[UUID]] = {} for player_id, group_id in (await self.session.execute(query)).all(): result.setdefault(player_id, []).append(group_id) return result async def recent_sessions(self, owner_ids: list[UUID]) -> Sequence: """Per player and mode, the latest RECENT_PER_MODE+1 analysed self sessions (one extra for the delta).""" ranked = ( select(SwingSession.owner_id, SwingSession.mode, SwingSession.id, SwingSession.overall_score, SwingSession.created_at, SwingSession.report["focus_area"]["display_name"].astext.label("focus"), SwingSession.report, SwingSession.measurement_payload["schema_version"].astext.label("measurement_schema"), func.row_number().over(partition_by=(SwingSession.owner_id, SwingSession.mode), order_by=(SwingSession.created_at.desc(), SwingSession.id.desc())) .label("rn")) .where(*_reviewable(owner_ids)) .subquery() ) query = select(ranked).where(ranked.c.rn <= RECENT_PER_MODE + 1).order_by(ranked.c.rn) return (await self.session.execute(query)).all() async def pending_counts(self, owner_ids: list[UUID]) -> dict[UUID, int]: query = (select(SwingSession.owner_id, func.count()) .outerjoin(Review, Review.session_id == SwingSession.id) .where(*_reviewable(owner_ids), Review.session_id.is_(None)) .group_by(SwingSession.owner_id)) return {owner_id: count for owner_id, count in (await self.session.execute(query)).all()} def _reviewable(owner_ids: list[UUID]) -> tuple: return (SwingSession.owner_id.in_(owner_ids), SwingSession.is_self.is_(True), SwingSession.analyzed_at.is_not(None), SwingSession.deleted_at.is_(None)) def player_sessions_query(player_id: UUID, mode: str | None, cursor: Cursor | None, limit: int) -> Select: query = summary_query().where(SwingSession.owner_id == player_id, SwingSession.is_self.is_(True), SwingSession.analyzed_at.is_not(None)) if mode: query = query.where(SwingSession.mode == mode) if cursor: query = query.where(or_(SwingSession.created_at < cursor.created_at, and_(SwingSession.created_at == cursor.created_at, SwingSession.id < cursor.id))) return query.order_by(SwingSession.created_at.desc(), SwingSession.id.desc()).limit(limit) def open_queue_query(owner_ids: list[UUID]) -> Select: return (summary_query().where(*_reviewable(owner_ids), Review.session_id.is_(None)) .order_by(SwingSession.created_at, SwingSession.id)) def reviewed_since_query(owner_ids: list[UUID], since: datetime) -> Select: return (summary_query().where(*_reviewable(owner_ids), Review.updated_at >= since) .order_by(Review.updated_at.desc(), SwingSession.id))