from datetime import datetime from uuid import UUID from sqlalchemy import Float, and_, cast, exists, func, or_, select from sqlalchemy.dialects.postgresql import distinct_on from sqlalchemy.ext.asyncio import AsyncSession from app.core.pagination import Cursor from app.modules.academy.models import AcademyMembership, CoachAccessRequest, GroupPlayer, PlayerGroup from app.modules.accounts.models import Account from app.modules.reviews.models import Review from app.modules.sessions.models import SwingSession from app.modules.settings.models import ConsentEvent, ExportJob, UserSettings from app.modules.teams.models import Team class ReportingRepository: """Read-only aggregates over other modules' tables, plus the ExportJob insert.""" def __init__(self, session: AsyncSession): self.session = session def _team_players(self, team_id: UUID): return select(Account.id).where(Account.team_id == team_id, Account.role == "player") def _scored(self, team_id: UUID, start: datetime | None = None, end: datetime | None = None): q = select(SwingSession.owner_id, SwingSession.overall_score, SwingSession.analyzed_at).where( SwingSession.owner_id.in_(self._team_players(team_id)), SwingSession.deleted_at.is_(None), SwingSession.analyzed_at.is_not(None), SwingSession.overall_score.is_not(None)) if start is not None: q = q.where(SwingSession.analyzed_at >= start) if end is not None: q = q.where(SwingSession.analyzed_at < end) return q async def active_players(self, team_id: UUID, start: datetime, end: datetime) -> int: q = select(func.count(func.distinct(SwingSession.owner_id))).where( SwingSession.owner_id.in_(self._team_players(team_id)), SwingSession.deleted_at.is_(None), SwingSession.analyzed_at >= start, SwingSession.analyzed_at < end) return await self.session.scalar(q) or 0 async def new_players(self, team_id: UUID, start: datetime, end: datetime) -> int: return await self.session.scalar(select(func.count()).select_from(Account).where( Account.team_id == team_id, Account.role == "player", Account.created_at >= start, Account.created_at < end)) or 0 async def analyses_since(self, team_id: UUID, since: datetime) -> int: return await self.session.scalar(select(func.count()).select_from(SwingSession).where( SwingSession.owner_id.in_(self._team_players(team_id)), SwingSession.deleted_at.is_(None), SwingSession.analyzed_at >= since)) or 0 async def improving(self, team_id: UUID, start: datetime, end: datetime) -> tuple[int, int]: """(players with >=2 scored sessions in the window, of those how many latest > earliest).""" s = self._scored(team_id, start, end).subquery() first = func.first_value(s.c.overall_score).over( partition_by=s.c.owner_id, order_by=s.c.analyzed_at.asc(), rows=(None, None)) last = func.first_value(s.c.overall_score).over( partition_by=s.c.owner_id, order_by=s.c.analyzed_at.desc(), rows=(None, None)) w = select(s.c.owner_id, first.label("first"), last.label("last"), func.count().over(partition_by=s.c.owner_id).label("n")).subquery() rows = (await self.session.execute( select(w.c.owner_id, func.max(w.c.first), func.max(w.c.last)).where(w.c.n >= 2) .group_by(w.c.owner_id))).all() return len(rows), sum(1 for _, f, la in rows if la > f) async def latest_scores(self, team_id: UUID, before: datetime) -> list[int]: s = self._scored(team_id, end=before).subquery() q = select(s.c.overall_score).ext(distinct_on(s.c.owner_id)).order_by(s.c.owner_id, s.c.analyzed_at.desc()) return list((await self.session.scalars(q)).all()) async def avg_review_hours(self, team_id: UUID, start: datetime, end: datetime) -> float | None: elapsed = cast(func.extract("epoch", Review.updated_at - SwingSession.created_at), Float) q = select(func.avg(elapsed)).select_from(Review).join( SwingSession, SwingSession.id == Review.session_id).where( SwingSession.owner_id.in_(self._team_players(team_id)), Review.updated_at >= start, Review.updated_at < end) seconds = await self.session.scalar(q) return None if seconds is None else round(max(seconds, 0) / 3600, 1) async def coach_rows(self, team_id: UUID) -> list[tuple[UUID, str, str]]: owner = select(Team.coach_id).where(Team.id == team_id) members = select(AcademyMembership.account_id).where( AcademyMembership.team_id == team_id, AcademyMembership.status == "active") rows = await self.session.execute(select(Account.id, Account.name, Account.focus).where( Account.id.in_(owner.union(members).subquery().select())).order_by(Account.name, Account.id)) return [tuple(r) for r in rows.all()] async def reviews_by_coach(self, team_id: UUID, start: datetime, end: datetime) -> dict[UUID, int]: rows = await self.session.execute( select(Review.coach_id, func.count()).join(SwingSession, SwingSession.id == Review.session_id).where( SwingSession.owner_id.in_(self._team_players(team_id)), Review.updated_at >= start, Review.updated_at < end).group_by(Review.coach_id)) return {coach_id: n for coach_id, n in rows.all()} async def pending_requests(self, team_id: UUID) -> int: return await self.session.scalar(select(func.count()).select_from(CoachAccessRequest).where( CoachAccessRequest.team_id == team_id, CoachAccessRequest.status == "pending")) or 0 async def not_filmed_since(self, team_id: UUID, since: datetime) -> int: filmed = exists().where(SwingSession.owner_id == Account.id, SwingSession.deleted_at.is_(None), SwingSession.created_at >= since) return await self.session.scalar(select(func.count()).select_from(Account).where( Account.team_id == team_id, Account.role == "player", ~filmed)) or 0 # ---- consent ---- async def group_in_team(self, team_id: UUID, group_id: UUID) -> bool: return await self.session.scalar(select(exists().where( PlayerGroup.id == group_id, PlayerGroup.team_id == team_id))) or False def _consent_base(self, team_id: UUID, group_id: UUID | None): def last(action: str): return (select(ConsentEvent.account_id, ConsentEvent.created_at, ConsentEvent.policy_version) .where(ConsentEvent.category == "analysis", ConsentEvent.action == action) .ext(distinct_on(ConsentEvent.account_id)) .order_by(ConsentEvent.account_id, ConsentEvent.created_at.desc()).subquery()) acc, wd = last("accepted"), last("withdrawn") gids = (select(func.array_agg(GroupPlayer.group_id)).where(GroupPlayer.player_id == Account.id) .correlate(Account).scalar_subquery()) first_group = (select(PlayerGroup.name).join(GroupPlayer, GroupPlayer.group_id == PlayerGroup.id) .where(GroupPlayer.player_id == Account.id).order_by(PlayerGroup.name).limit(1) .correlate(Account).scalar_subquery()) is_accepted = and_(acc.c.created_at.is_not(None), or_(wd.c.created_at.is_(None), acc.c.created_at > wd.c.created_at)) q = (select(Account.id.label("player_id"), Account.name, Account.created_at, first_group.label("group"), gids.label("group_ids"), acc.c.created_at.label("last_accepted"), acc.c.policy_version.label("version"), wd.c.created_at.label("last_withdrawn"), is_accepted.label("accepted"), func.coalesce(UserSettings.help_improve_ai, False).label("help_improve_ai")) .select_from(Account) .outerjoin(acc, acc.c.account_id == Account.id).outerjoin(wd, wd.c.account_id == Account.id) .outerjoin(UserSettings, UserSettings.account_id == Account.id) .where(Account.team_id == team_id, Account.role == "player")) if group_id is not None: q = q.where(exists().where(GroupPlayer.player_id == Account.id, GroupPlayer.group_id == group_id)) return q async def consent_totals(self, team_id: UUID, group_id: UUID | None) -> tuple[int, int]: b = self._consent_base(team_id, group_id).subquery() row = (await self.session.execute(select( func.count().filter(b.c.accepted), func.count().filter(b.c.help_improve_ai)))).one() return row[0], row[1] async def consent_rows(self, team_id: UUID, group_id: UUID | None, limit: int, cursor: Cursor | None = None): b = self._consent_base(team_id, group_id).subquery() q = select(b).order_by(b.c.created_at.desc(), b.c.player_id.desc()).limit(limit) if cursor is not None: q = q.where(or_(b.c.created_at < cursor.created_at, and_(b.c.created_at == cursor.created_at, b.c.player_id < cursor.id))) return (await self.session.execute(q)).mappings().all() async def add_export(self, **values) -> ExportJob: job = ExportJob(**values) self.session.add(job) await self.session.flush() return job