diff --git a/backend/app/common/academy_access.py b/backend/app/common/academy_access.py new file mode 100644 index 0000000000000000000000000000000000000000..757616ba4528761af5af02efcbb9d82e0071a87e --- /dev/null +++ b/backend/app/common/academy_access.py @@ -0,0 +1,151 @@ +"""Who may act for an academy (a team) and which players they can see. Every coach-side module uses this. + +The team owner (teams.coach_id) is the implicit admin with every permission. Other staff need an active +academy_memberships row. Paused or removed staff get no academy access, even with an +unexpired token: a paused coach gets 403 on coach endpoints, a removed one is a coach with no academy. +A coach sees: every team player if admin or sees_all; otherwise players on their own roster (coach_players) +plus players in groups they coach. A player's coach_can_see_sessions=false hides their sessions from coaches. +""" + +from dataclasses import dataclass, field +from typing import Annotated +from uuid import UUID + +from fastapi import Depends +from sqlalchemy import select, union +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.dependencies import CurrentAccount, Db +from app.core.errors import Forbidden, NotFound +from app.modules.academy.models import AcademyMembership, CoachPlayer, GroupCoach, GroupPlayer +from app.modules.accounts.models import Account +from app.modules.settings.models import UserSettings +from app.modules.teams.models import Team + +PERMISSIONS = ("review", "drills", "goals", "library", "earnings") +ROLE_PERMISSIONS: dict[str, dict[str, bool]] = { + "admin": dict.fromkeys(PERMISSIONS, True), + "coach": {"review": True, "drills": True, "goals": True, "library": False, "earnings": False}, + "assistant": {"review": True, "drills": False, "goals": False, "library": False, "earnings": False}, +} + + +def normalize_permissions(role: str, requested: dict[str, bool] | None = None) -> dict[str, bool]: + """Role defaults, overridden by requested values. Admins always have all; assistants never drills/goals.""" + perms = {**ROLE_PERMISSIONS[role], **(requested or {})} + if role == "admin": + return dict(ROLE_PERMISSIONS["admin"]) + if role == "assistant": + perms.update(drills=False, goals=False) + return {k: bool(perms.get(k, False)) for k in PERMISSIONS} + + +@dataclass +class Staff: + """The caller acting as a coach. team_id is None for a coach account that has no academy yet.""" + + account: Account + team_id: UUID | None + role: str # admin | coach | assistant + sees_all: bool + permissions: dict[str, bool] = field(default_factory=dict) + is_owner: bool = False + + @property + def id(self) -> UUID: + return self.account.id + + @property + def is_admin(self) -> bool: + return self.team_id is not None and self.role == "admin" + + def require(self, permission: str) -> None: + if self.team_id is None or not self.permissions.get(permission, False): + raise Forbidden("Your academy role does not allow this.") + + +async def staff_context(db: AsyncSession, account: Account) -> Staff | None: + team_id = await db.scalar(select(Team.id).where(Team.coach_id == account.id)) + if team_id is not None: + return Staff(account, team_id, "admin", True, normalize_permissions("admin"), is_owner=True) + membership = await db.scalar(select(AcademyMembership).where( + AcademyMembership.account_id == account.id, AcademyMembership.status == "active") + .order_by(AcademyMembership.created_at.desc()).limit(1)) + if membership is not None: + return Staff(account, membership.team_id, membership.role, membership.sees_all or membership.role == "admin", + normalize_permissions(membership.role, membership.permissions)) + paused = await db.scalar(select(AcademyMembership.id).where( + AcademyMembership.account_id == account.id, AcademyMembership.status == "paused").limit(1)) + if account.role == "coach" and paused is None: + return Staff(account, None, "coach", False, {}) + return None + + +async def _staff(db: Db, account: CurrentAccount) -> Staff: + staff = await staff_context(db, account) + if staff is None: + raise Forbidden("Only coaches can do this.") + return staff + + +async def _admin(staff: Annotated[Staff, Depends(_staff)]) -> Staff: + if not staff.is_admin: + raise Forbidden("Only academy admins can do this.") + return staff + + +CurrentStaff = Annotated[Staff, Depends(_staff)] +CurrentAdmin = Annotated[Staff, Depends(_admin)] + + +def visible_players_query(staff: Staff): + """SELECT of the account ids of players this staff member can see (empty when there is no team).""" + on_team = select(Account.id).where(Account.team_id == staff.team_id, Account.role == "player") + if staff.team_id is None: + return on_team.where(False) + if staff.sees_all: + return on_team + rostered = select(CoachPlayer.player_id).where(CoachPlayer.team_id == staff.team_id, + CoachPlayer.coach_id == staff.id) + grouped = (select(GroupPlayer.player_id).join(GroupCoach, GroupCoach.group_id == GroupPlayer.group_id) + .where(GroupCoach.coach_id == staff.id)) + return on_team.where(Account.id.in_(union(rostered, grouped).subquery().select())) + + +async def visible_player_ids(db: AsyncSession, staff: Staff) -> list[UUID]: + return list((await db.scalars(visible_players_query(staff))).all()) + + +async def can_see_player(db: AsyncSession, staff: Staff, player_id: UUID) -> bool: + query = visible_players_query(staff).where(Account.id == player_id) + return await db.scalar(query) is not None + + +async def require_player(db: AsyncSession, staff: Staff, player_id: UUID) -> Account: + """The player, if this staff member can see them; otherwise 404 (no existence leak).""" + if not await can_see_player(db, staff, player_id): + raise NotFound("Player not on your team.", code="PLAYER_NOT_ON_TEAM") + return await db.get(Account, player_id) # type: ignore[return-value] + + +async def sessions_shared(db: AsyncSession, player_id: UUID) -> bool: + """False when the player turned off coach_can_see_sessions (no row means the default, true).""" + value = await db.scalar(select(UserSettings.coach_can_see_sessions).where(UserSettings.account_id == player_id)) + return True if value is None else value + + +async def coaches_of_player(db: AsyncSession, player: Account) -> list[UUID]: + """Account ids of every active staff member who can see this player (for alerts).""" + if player.team_id is None: + return [] + owner = await db.scalar(select(Team.coach_id).where(Team.id == player.team_id)) + ids = {owner} if owner else set() + rows = await db.execute(select(AcademyMembership.account_id, AcademyMembership.sees_all, AcademyMembership.role) + .where(AcademyMembership.team_id == player.team_id, AcademyMembership.status == "active")) + rostered = set((await db.scalars(select(CoachPlayer.coach_id).where(CoachPlayer.player_id == player.id))).all()) + grouped = set((await db.scalars(select(GroupCoach.coach_id).join( + GroupPlayer, GroupPlayer.group_id == GroupCoach.group_id).where(GroupPlayer.player_id == player.id))).all()) + for account_id, sees_all, role in rows: + if sees_all or role == "admin" or account_id in rostered or account_id in grouped: + ids.add(account_id) + return list(ids) diff --git a/backend/app/common/notify.py b/backend/app/common/notify.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb48425c31e657692026dd795f44ef18db634e1 --- /dev/null +++ b/backend/app/common/notify.py @@ -0,0 +1,56 @@ +"""Create an in-app notification and push it. Used by every module that produces a notification. + +The inbox row is written in the caller's transaction (deduplicated by recipient + event_key, so a retried +request never creates a second one). The push is best effort and honours the recipient's preference flag. +Push data carries notification_id, kind and target_json; review/session pushes keep the legacy +type=review.received + session_id keys so older app builds still route them. +""" + +import json +import logging +from uuid import UUID + +from sqlalchemy import delete, select +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.ext.asyncio import AsyncSession + +from app.integrations.push import PushClient +from app.modules.devices.models import Device +from app.modules.notifications.models import Notification +from app.modules.settings.models import UserSettings + +log = logging.getLogger(__name__) + +# kind -> the user_settings flag that turns its push off +PREFERENCE = {"review": "notify_coach", "drill": "notify_drills", "armcare": "notify_coach", + "result": "notify_results", "report": "notify_weekly"} + + +async def notify(db: AsyncSession, push: PushClient | None, recipient_id: UUID, *, kind: str, title: str, + body: str = "", target: dict | None = None, event_key: str) -> UUID | None: + """Returns the notification id, or None when this event was already delivered to this recipient.""" + target = {k: str(v) for k, v in (target or {}).items()} + notification_id = await db.scalar( + insert(Notification).values(recipient_id=recipient_id, kind=kind, title=title[:120], body=body[:300], + target=target, event_key=event_key[:160]) + .on_conflict_do_nothing(index_elements=["recipient_id", "event_key"]).returning(Notification.id)) + if notification_id is None or push is None: + return notification_id + flag = PREFERENCE.get(kind) + if flag and await db.scalar(select(getattr(UserSettings, flag)).where(UserSettings.account_id == recipient_id)) \ + is False: + return notification_id + tokens = list((await db.scalars(select(Device.push_token).where(Device.account_id == recipient_id))).all()) + if not tokens: + return notification_id + data = {"notification_id": str(notification_id), "kind": kind, "target_json": json.dumps(target)} + if kind == "review" and "session_id" in target: + data.update(type="review.received", session_id=target["session_id"]) + try: + dead = await push.send(tokens, data, notification={"title": title, "body": body}) + except Exception: # a push failure must never fail the request + log.exception("push: %s failed", kind) + return notification_id + if dead: + await db.execute(delete(Device).where(Device.push_token.in_(dead))) + return notification_id diff --git a/backend/app/common/schemas.py b/backend/app/common/schemas.py index a4812f24e55c7d64f61245214d13abee1d250ead..e959d7c69d2380363aa31df35f1e240a7704a7d1 100644 --- a/backend/app/common/schemas.py +++ b/backend/app/common/schemas.py @@ -1,6 +1,8 @@ """Base request/response models and the list envelope.""" +from datetime import datetime from typing import Generic, TypeVar +from uuid import UUID from pydantic import BaseModel, ConfigDict @@ -26,3 +28,12 @@ class Items(ResponseModel, Generic[T]): """A complete (unpaginated) list.""" items: list[T] + + +class MediaRef(ResponseModel): + """A short-lived authorised read URL for stored media. Refetch the owning resource when it expires.""" + + upload_id: UUID + url: str + expires_at: datetime + seconds: float | None = None diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 035993d38051daca9cc15bec8bcba88b4c9c1a34..bb5a71c6ee939cba6b43034554b6713f939df6d6 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -51,6 +51,10 @@ class Settings(BaseSettings): max_thumbnail_bytes: int = 5 * 1024 * 1024 max_video_seconds: float = 60.0 + # Consent: when true, new analysis needs an accepted consent event. A withdrawal always blocks. + require_analysis_consent: bool = False + consent_versions: list[str] = ["1.0"] + # Plans free_weekly_limit: int = 3 entitlement_window_days: int = 7 diff --git a/backend/app/jobs/exports.py b/backend/app/jobs/exports.py new file mode 100644 index 0000000000000000000000000000000000000000..c235740cf3763d753cd5a7ce50c065fc9126d1f4 --- /dev/null +++ b/backend/app/jobs/exports.py @@ -0,0 +1,63 @@ +"""Export worker: `python -m app.jobs.exports`. + +Processes queued 'videos' export jobs: presigns a download link for each of the owner's non-deleted session videos +and emails the list to the account address. The job ends 'ready' (links expire at expires_at) or 'failed'. +""" + +import asyncio +import logging +from datetime import UTC, datetime, timedelta + +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.config import get_settings +from app.core.database import get_session_factory +from app.integrations.email import EmailClient, get_email_client +from app.integrations.storage import StorageClient, get_storage +from app.modules.accounts.models import Account +from app.modules.sessions.models import SwingSession +from app.modules.settings.models import ExportJob +from app.modules.uploads.models import Upload + +log = logging.getLogger(__name__) + + +async def run_exports(db: AsyncSession, storage: StorageClient, email: EmailClient, + now: datetime | None = None) -> dict[str, int]: + now = now or datetime.now(UTC) + ttl = get_settings().download_url_ttl_s + jobs = (await db.scalars(select(ExportJob).where(ExportJob.scope == "videos", ExportJob.status == "queued") + .order_by(ExportJob.created_at).with_for_update(skip_locked=True))).all() + counts = {"ready": 0, "failed": 0} + for job in jobs: + try: + account = await db.get(Account, job.requester_id) + rows = (await db.execute( + select(SwingSession.created_at, Upload.object_key) + .join(Upload, Upload.id == SwingSession.video_upload_id) + .where(SwingSession.owner_id == job.requester_id, SwingSession.deleted_at.is_(None)) + .order_by(SwingSession.created_at))).all() + links = [f"{created.date().isoformat()}: {storage.presign_get(key)}" for created, key in rows] + body = ("Here are the links to your videos. They expire in " + f"{max(ttl // 60, 1)} minutes.\n\n" + ("\n".join(links) if links else "You have no videos.")) + await email.send(account.email, "Your videos", body) + job.status, job.expires_at, job.error_code = "ready", now + timedelta(seconds=ttl), None + counts["ready"] += 1 + except Exception: + log.exception("export %s failed", job.id) + job.status, job.error_code = "failed", "DELIVERY_FAILED" + counts["failed"] += 1 + await db.commit() + log.info("exports done: %s", counts) + return counts + + +async def main() -> dict[str, int]: + async with get_session_factory()() as db: + return await run_exports(db, get_storage(), get_email_client()) + + +if __name__ == "__main__": + logging.basicConfig(level=logging.INFO) + print(asyncio.run(main())) diff --git a/backend/app/main.py b/backend/app/main.py index ee24991c78c19f8bc9bb7255179b3f097ea5a83b..b27a4e97632ab8c986bfc672c084b753f9b8cdc4 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -11,24 +11,35 @@ from pydantic.json_schema import models_json_schema from app.core.config import get_settings from app.core.errors import register_error_handlers, unexpected_error_response +from app.modules.academy_org.controller import router as academy_org_router +from app.modules.academy_staff.controller import router as academy_staff_router from app.modules.accounts.controller import router as accounts_router from app.modules.api_audit.controller import router as audit_router from app.modules.api_audit.middleware import ApiAuditMiddleware +from app.modules.arm_care.controller import router as arm_care_router +from app.modules.assignments.controller import router as assignments_router from app.modules.auth.controller import router as auth_router from app.modules.billing.controller import router as billing_router from app.modules.catalog.controller import router as catalog_router from app.modules.coach.controller import router as coach_router from app.modules.devices.controller import router as devices_router from app.modules.drills.controller import router as drills_router +from app.modules.goals.controller import router as goals_router +from app.modules.notifications.controller import router as notifications_router +from app.modules.reporting.controller import router as reporting_router from app.modules.reviews.controller import router as reviews_router from app.modules.sessions.controller import router as sessions_router +from app.modules.settings.controller import router as settings_router from app.modules.swing_reports.controller import router as swing_reports_router from app.modules.teams.controller import router as teams_router +from app.modules.threads.controller import router as threads_router from app.modules.uploads.controller import router as uploads_router ROUTERS = ( auth_router, accounts_router, teams_router, uploads_router, sessions_router, swing_reports_router, drills_router, reviews_router, coach_router, devices_router, billing_router, catalog_router, audit_router, + settings_router, notifications_router, threads_router, goals_router, assignments_router, arm_care_router, + academy_staff_router, academy_org_router, reporting_router, ) diff --git a/backend/app/models.py b/backend/app/models.py index f4d52df0a3769d342f1d7fe02362a1ed2a2e8d62..f797b73de3fbdaaf82d221bfcdef0e0e4885857f 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,19 +1,39 @@ """Imports every model so Base.metadata is complete (Alembic, tests).""" from app.common.base_model import Base +from app.modules.academy.models import ( + AcademyMembership, + CoachAccessRequest, + CoachNote, + CoachPlayer, + GroupCoach, + GroupPlayer, + LibraryDrill, + PlayerGroup, + StaffCode, +) from app.modules.accounts.models import Account from app.modules.api_audit.models import ApiRequestLog +from app.modules.arm_care.models import ArmFeel, ArmOuting +from app.modules.assignments.models import AssignmentSet, DrillAssignment from app.modules.auth.models import AuthIdentity, PasswordReset, RefreshToken from app.modules.billing.models import Subscription from app.modules.devices.models import Device from app.modules.drills.models import DrillLog +from app.modules.goals.models import Goal from app.modules.idempotency.models import IdempotencyKey +from app.modules.notifications.models import Notification 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 +from app.modules.threads.models import Message, Thread from app.modules.uploads.models import Upload __all__ = [ "Base", "Account", "AuthIdentity", "PasswordReset", "RefreshToken", "Subscription", "Device", "DrillLog", "IdempotencyKey", "Review", "SwingSession", "Team", "Upload", "ApiRequestLog", + "AcademyMembership", "CoachAccessRequest", "CoachNote", "CoachPlayer", "GroupCoach", "GroupPlayer", + "LibraryDrill", "PlayerGroup", "StaffCode", "ArmFeel", "ArmOuting", "AssignmentSet", "DrillAssignment", + "Goal", "Notification", "ConsentEvent", "ExportJob", "UserSettings", "Message", "Thread", ] diff --git a/backend/app/modules/academy/__init__.py b/backend/app/modules/academy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/academy/models.py b/backend/app/modules/academy/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c92b46bcad040aac4d655b0888206e85cc151b97 --- /dev/null +++ b/backend/app/modules/academy/models.py @@ -0,0 +1,174 @@ +"""Academy (= an existing team) staff and organisation. The team's owner (teams.coach_id) is the implicit admin; +other staff have a membership row. Players belong through accounts.team_id as before. +""" + +import uuid +from datetime import datetime + +from sqlalchemy import ( + Boolean, + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + SmallInteger, + String, + Text, + UniqueConstraint, + text, +) +from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID +from sqlalchemy.orm import Mapped, mapped_column + +from app.common.base_model import Base, CreatedAtMixin, IdMixin, TimestampMixin + + +def _team() -> Mapped[uuid.UUID]: + return mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="CASCADE"), index=True) + + +def _account(nullable: bool = False) -> Mapped: + return mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL" if nullable else "CASCADE")) + + +class AcademyMembership(IdMixin, CreatedAtMixin, Base): + """A staff member of a team. permissions: {review, drills, goals, library, earnings} effective booleans.""" + + __tablename__ = "academy_memberships" + __table_args__ = ( + UniqueConstraint("team_id", "account_id"), + CheckConstraint("role IN ('admin', 'coach', 'assistant')", name="role"), + CheckConstraint("status IN ('active', 'paused', 'removed')", name="status"), + Index("ix_academy_memberships_account_id", "account_id"), + ) + + team_id: Mapped[uuid.UUID] = _team() + account_id: Mapped[uuid.UUID] = _account() + role: Mapped[str] = mapped_column(String(10)) + status: Mapped[str] = mapped_column(String(8), server_default="active") + sees_all: Mapped[bool] = mapped_column(Boolean, server_default="false") + permissions: Mapped[dict] = mapped_column(JSONB) + joined_with: Mapped[str | None] = mapped_column(String(16)) + version: Mapped[int] = mapped_column(Integer, server_default="1") + + +class StaffCode(IdMixin, CreatedAtMixin, Base): + """A code staff use to apply. uses is a counter locked with the row so the last use cannot be taken twice.""" + + __tablename__ = "staff_codes" + __table_args__ = ( + CheckConstraint("role IN ('coach', 'assistant')", name="role"), + CheckConstraint("approval IN ('admin', 'auto')", name="approval"), + CheckConstraint("uses >= 0 AND uses <= max_uses", name="uses"), + ) + + team_id: Mapped[uuid.UUID] = _team() + code: Mapped[str] = mapped_column(String(16), unique=True) + role: Mapped[str] = mapped_column(String(10)) + expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + max_uses: Mapped[int] = mapped_column(SmallInteger) + uses: Mapped[int] = mapped_column(SmallInteger, server_default="0") + approval: Mapped[str] = mapped_column(String(6)) + revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + created_by_id: Mapped[uuid.UUID | None] = _account(nullable=True) + + +class CoachAccessRequest(IdMixin, CreatedAtMixin, Base): + """An application to coach at a team. created_at is sent_at. At most one pending request per applicant.""" + + __tablename__ = "coach_access_requests" + __table_args__ = ( + CheckConstraint("status IN ('pending', 'approved', 'declined')", name="status"), + Index("uq_coach_access_requests_pending", "applicant_id", unique=True, + postgresql_where=text("status = 'pending'")), + Index("ix_coach_access_requests_team_id_created_at", "team_id", text("created_at DESC")), + ) + + applicant_id: Mapped[uuid.UUID] = _account() + team_id: Mapped[uuid.UUID] = _team() + staff_code_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("staff_codes.id", ondelete="SET NULL") + ) + code: Mapped[str] = mapped_column(String(16)) + status: Mapped[str] = mapped_column(String(8), server_default="pending") + decided_by_id: Mapped[uuid.UUID | None] = _account(nullable=True) + decided_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + +class PlayerGroup(IdMixin, CreatedAtMixin, Base): + __tablename__ = "player_groups" + __table_args__ = ( + CheckConstraint("focus IN ('Hitting', 'Pitching', 'Both')", name="focus"), + Index("uq_player_groups_team_id_name", "team_id", text("lower(name)"), unique=True), + ) + + team_id: Mapped[uuid.UUID] = _team() + name: Mapped[str] = mapped_column(String(80)) + focus: Mapped[str] = mapped_column(String(8)) + + +class GroupPlayer(Base): + __tablename__ = "group_players" + + group_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("player_groups.id", ondelete="CASCADE"), primary_key=True + ) + player_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True, index=True + ) + + +class GroupCoach(Base): + __tablename__ = "group_coaches" + + group_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("player_groups.id", ondelete="CASCADE"), primary_key=True + ) + coach_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True, index=True + ) + + +class CoachPlayer(CreatedAtMixin, Base): + """A player on one staff coach's own roster (in addition to group and sees_all visibility).""" + + __tablename__ = "coach_players" + + team_id: Mapped[uuid.UUID] = _team() + coach_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True + ) + player_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True, index=True + ) + + +class CoachNote(IdMixin, TimestampMixin, Base): + """A coach's private note on a player; only that coach can read it.""" + + __tablename__ = "coach_notes" + __table_args__ = (UniqueConstraint("team_id", "coach_id", "player_id"),) + + team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="CASCADE")) + coach_id: Mapped[uuid.UUID] = _account() + player_id: Mapped[uuid.UUID] = _account() + text: Mapped[str] = mapped_column(Text, server_default="") + version: Mapped[int] = mapped_column(Integer, server_default="0") + + +class LibraryDrill(IdMixin, CreatedAtMixin, Base): + """A team's own drill video. Assignments snapshot name/fixes, so deleting one never rewrites history.""" + + __tablename__ = "library_drills" + __table_args__ = (CheckConstraint("mode IN ('h', 'p')", name="mode"),) + + team_id: Mapped[uuid.UUID] = _team() + author_id: Mapped[uuid.UUID | None] = _account(nullable=True) + name: Mapped[str] = mapped_column(String(120)) + fixes: Mapped[str] = mapped_column(String(500), server_default="") + mode: Mapped[str] = mapped_column(String(1)) + fault_tags: Mapped[list[str]] = mapped_column(ARRAY(String(64)), server_default=text("'{}'")) + upload_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("uploads.id", ondelete="SET NULL") + ) diff --git a/backend/app/modules/academy_org/__init__.py b/backend/app/modules/academy_org/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/academy_org/controller.py b/backend/app/modules/academy_org/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..51dba6a81812fb6cd7a2cc845fb5457de0adf148 --- /dev/null +++ b/backend/app/modules/academy_org/controller.py @@ -0,0 +1,90 @@ +"""N28-N33 groups, private notes and roster additions; N35-N36 the academy drill library.""" + +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, Header, Query + +from app.common.academy_access import CurrentAdmin, CurrentStaff +from app.common.schemas import Page +from app.core.dependencies import Db, Paging, Storage +from app.modules.academy_org.schemas import ( + GroupEnvelope, + GroupIn, + GroupOut, + LibraryDrillIn, + LibraryDrillOut, + LibraryEnvelope, + MemberOut, + Mode, + NoteEnvelope, + NoteIn, + RosterAddIn, + RosterAddOut, +) +from app.modules.academy_org.service import OrgService +from app.modules.idempotency.service import run_idempotent + +router = APIRouter(prefix="/v1", tags=["academy_org"]) + + +def get_org_service(db: Db, storage: Storage) -> OrgService: + return OrgService(db, storage) + + +Service = Annotated[OrgService, Depends(get_org_service)] +IdempotencyKey = Annotated[str | None, Header(max_length=128)] + + +@router.get("/academy/groups", response_model=Page[GroupOut]) +async def list_groups(staff: CurrentStaff, service: Service, paging: Paging) -> Page[GroupOut]: + return await service.list_groups(staff, paging) + + +@router.post("/academy/groups", status_code=201, response_model=GroupEnvelope) +async def create_group(body: GroupIn, staff: CurrentAdmin, service: Service, db: Db, + idempotency_key: IdempotencyKey = None): + async def handler() -> GroupEnvelope: + return GroupEnvelope(group=await service.create_group(staff, body)) + + return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=201) + + +@router.get("/coach/players/{player_id}/note", response_model=NoteEnvelope) +async def get_note(player_id: UUID, staff: CurrentStaff, service: Service) -> NoteEnvelope: + return NoteEnvelope(note=await service.get_note(staff, player_id)) + + +@router.put("/coach/players/{player_id}/note", response_model=NoteEnvelope) +async def save_note(player_id: UUID, body: NoteIn, staff: CurrentStaff, service: Service) -> NoteEnvelope: + return NoteEnvelope(note=await service.save_note(staff, player_id, body)) + + +@router.get("/academy/members", response_model=Page[MemberOut]) +async def members(staff: CurrentStaff, service: Service, paging: Paging, + q: Annotated[str | None, Query(max_length=100)] = None) -> Page[MemberOut]: + return await service.members(staff, q.strip() if q else None, paging) + + +@router.post("/coach/roster/players", response_model=RosterAddOut) +async def add_roster_players(body: RosterAddIn, staff: CurrentStaff, service: Service, db: Db, + idempotency_key: IdempotencyKey = None): + async def handler() -> RosterAddOut: + return await service.add_to_roster(staff, body) + + return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=200) + + +@router.get("/academy/library", response_model=Page[LibraryDrillOut]) +async def library(staff: CurrentStaff, service: Service, paging: Paging, mode: Mode | None = None, + fault_tag: Annotated[str | None, Query(max_length=64)] = None) -> Page[LibraryDrillOut]: + return await service.library(staff, mode, fault_tag, paging) + + +@router.post("/academy/library", status_code=201, response_model=LibraryEnvelope) +async def publish_drill(body: LibraryDrillIn, staff: CurrentStaff, service: Service, db: Db, + idempotency_key: IdempotencyKey = None): + async def handler() -> LibraryEnvelope: + return LibraryEnvelope(drill=await service.publish_drill(staff, body)) + + return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=201) diff --git a/backend/app/modules/academy_org/repository.py b/backend/app/modules/academy_org/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..e818ecfa7bd703b3cb31ed39e371bfd5d0a6186b --- /dev/null +++ b/backend/app/modules/academy_org/repository.py @@ -0,0 +1,177 @@ +"""Groups, private coach notes, roster additions and the academy library. Database only.""" + +from collections.abc import Sequence +from datetime import datetime +from uuid import UUID + +from sqlalchemy import Select, and_, or_, select +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.exc import IntegrityError + +from app.common.base_repository import BaseRepository +from app.core.pagination import Cursor +from app.modules.academy.models import ( + AcademyMembership, + CoachNote, + CoachPlayer, + GroupCoach, + GroupPlayer, + LibraryDrill, + PlayerGroup, +) +from app.modules.accounts.models import Account +from app.modules.teams.models import Team +from app.modules.uploads.models import Upload + + +def _after(query: Select, created_at_col, id_col, cursor: Cursor | None, limit: int) -> Select: + if cursor: + query = query.where(or_(created_at_col < cursor.created_at, + and_(created_at_col == cursor.created_at, id_col < cursor.id))) + return query.order_by(created_at_col.desc(), id_col.desc()).limit(limit) + + +class OrgRepository(BaseRepository[PlayerGroup]): + model = PlayerGroup + + # ---- groups ---- + async def groups(self, team_id: UUID, coach_id: UUID | None, cursor: Cursor | None, limit: int): + """Team groups; with coach_id, only the groups that coach is on.""" + query = select(PlayerGroup).where(PlayerGroup.team_id == team_id) + if coach_id is not None: + query = query.where(PlayerGroup.id.in_(select(GroupCoach.group_id).where(GroupCoach.coach_id == coach_id))) + query = _after(query, PlayerGroup.created_at, PlayerGroup.id, cursor, limit) + return (await self.session.scalars(query)).all() + + async def group_players(self, group_ids: list[UUID]) -> dict[UUID, list[UUID]]: + rows = await self.session.execute(select(GroupPlayer.group_id, GroupPlayer.player_id) + .where(GroupPlayer.group_id.in_(group_ids)).order_by(GroupPlayer.player_id)) + out: dict[UUID, list[UUID]] = {} + for group_id, player_id in rows.all(): + out.setdefault(group_id, []).append(player_id) + return out + + async def group_coaches(self, group_ids: list[UUID]) -> dict[UUID, list[tuple[UUID, str]]]: + rows = await self.session.execute( + select(GroupCoach.group_id, Account.id, Account.name).join(Account, Account.id == GroupCoach.coach_id) + .where(GroupCoach.group_id.in_(group_ids)).order_by(Account.name, Account.id)) + out: dict[UUID, list[tuple[UUID, str]]] = {} + for group_id, coach_id, name in rows.all(): + out.setdefault(group_id, []).append((coach_id, name or "")) + return out + + async def team_player_ids(self, team_id: UUID, ids: Sequence[UUID]) -> set[UUID]: + query = select(Account.id).where(Account.id.in_(ids), Account.team_id == team_id, Account.role == "player") + return set((await self.session.scalars(query)).all()) + + async def team_staff_ids(self, team_id: UUID, ids: Sequence[UUID]) -> set[UUID]: + members = select(AcademyMembership.account_id).where( + AcademyMembership.team_id == team_id, AcademyMembership.status.in_(("active", "paused")), + AcademyMembership.account_id.in_(ids)) + found = set((await self.session.scalars(members)).all()) + owner = await self.session.scalar(select(Team.coach_id).where(Team.id == team_id, Team.coach_id.in_(ids))) + if owner is not None: + found.add(owner) + return found + + async def create_group(self, team_id: UUID, name: str, focus: str, coach_ids: list[UUID], + player_ids: list[UUID]) -> PlayerGroup | None: + """None when the name is taken (case-insensitive).""" + group = PlayerGroup(team_id=team_id, name=name, focus=focus) + try: + async with self.session.begin_nested(): + self.session.add(group) + await self.session.flush() + except IntegrityError: + return None + self.session.add_all([GroupCoach(group_id=group.id, coach_id=c) for c in coach_ids]) + self.session.add_all([GroupPlayer(group_id=group.id, player_id=p) for p in player_ids]) + await self.session.flush() + return group + + async def group_in_team(self, team_id: UUID, group_id: UUID) -> PlayerGroup | None: + return await self.session.scalar(select(PlayerGroup).where(PlayerGroup.id == group_id, + PlayerGroup.team_id == team_id)) + + async def is_group_coach(self, group_id: UUID, coach_id: UUID) -> bool: + return await self.session.scalar(select(GroupCoach.group_id).where( + GroupCoach.group_id == group_id, GroupCoach.coach_id == coach_id)) is not None + + # ---- notes ---- + async def note(self, team_id: UUID, coach_id: UUID, player_id: UUID, *, lock: bool = False) -> CoachNote | None: + query = select(CoachNote).where(CoachNote.team_id == team_id, CoachNote.coach_id == coach_id, + CoachNote.player_id == player_id) + if lock: + query = query.with_for_update() + return await self.session.scalar(query) + + async def insert_note(self, team_id: UUID, coach_id: UUID, player_id: UUID, text: str) -> CoachNote | None: + """None when a concurrent request created the note first.""" + stmt = (insert(CoachNote).values(team_id=team_id, coach_id=coach_id, player_id=player_id, text=text, + version=1) + .on_conflict_do_nothing().returning(CoachNote.id)) + if await self.session.scalar(stmt) is None: + return None + return await self.note(team_id, coach_id, player_id) + + # ---- roster ---- + async def members(self, team_id: UUID, coach_id: UUID, q: str | None, cursor: Cursor | None, limit: int): + query = (select(Account).where( + Account.team_id == team_id, Account.role == "player", + Account.id.not_in(select(CoachPlayer.player_id).where(CoachPlayer.team_id == team_id, + CoachPlayer.coach_id == coach_id)))) + if q: + escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + query = query.where(Account.name.ilike(f"%{escaped}%", escape="\\")) + return (await self.session.scalars(_after(query, Account.created_at, Account.id, cursor, limit))).all() + + async def player_group_ids(self, player_ids: list[UUID], team_id: UUID) -> dict[UUID, list[UUID]]: + rows = await self.session.execute( + select(GroupPlayer.player_id, GroupPlayer.group_id) + .join(PlayerGroup, PlayerGroup.id == GroupPlayer.group_id) + .where(GroupPlayer.player_id.in_(player_ids), PlayerGroup.team_id == team_id) + .order_by(GroupPlayer.group_id)) + out: dict[UUID, list[UUID]] = {} + for player_id, group_id in rows.all(): + out.setdefault(player_id, []).append(group_id) + return out + + async def add_to_roster(self, team_id: UUID, coach_id: UUID, player_ids: list[UUID]) -> set[UUID]: + stmt = (insert(CoachPlayer).values([{"team_id": team_id, "coach_id": coach_id, "player_id": p} + for p in player_ids]) + .on_conflict_do_nothing().returning(CoachPlayer.player_id)) + return set((await self.session.scalars(stmt)).all()) + + async def add_to_group(self, group_id: UUID, player_ids: list[UUID]) -> None: + await self.session.execute(insert(GroupPlayer).values([{"group_id": group_id, "player_id": p} + for p in player_ids]).on_conflict_do_nothing()) + + # ---- library ---- + async def library(self, team_id: UUID, mode: str | None, fault_tag: str | None, cursor: Cursor | None, + limit: int) -> Sequence[tuple[LibraryDrill, str | None, str | None]]: + """(drill, author name, object key).""" + query = self._library_select().where(LibraryDrill.team_id == team_id) + if mode: + query = query.where(LibraryDrill.mode == mode) + if fault_tag: + query = query.where(LibraryDrill.fault_tags.contains([fault_tag.lower()])) + query = _after(query, LibraryDrill.created_at, LibraryDrill.id, cursor, limit) + return [tuple(r) for r in (await self.session.execute(query)).all()] # type: ignore[misc] + + async def library_row(self, drill_id: UUID) -> tuple[LibraryDrill, str | None, str | None]: + row = (await self.session.execute(self._library_select().where(LibraryDrill.id == drill_id))).one() + return tuple(row) # type: ignore[return-value] + + @staticmethod + def _library_select() -> Select: + return (select(LibraryDrill, Account.name, Upload.object_key) + .outerjoin(Account, Account.id == LibraryDrill.author_id) + .outerjoin(Upload, Upload.id == LibraryDrill.upload_id)) + + async def upload(self, upload_id: UUID, owner_id: UUID) -> Upload | None: + return await self.session.scalar(select(Upload).where(Upload.id == upload_id, Upload.owner_id == owner_id) + .with_for_update()) + + async def attach(self, upload: Upload, when: datetime) -> None: + upload.attached_at = when + await self.session.flush() diff --git a/backend/app/modules/academy_org/schemas.py b/backend/app/modules/academy_org/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..0248fd6056cb61ddaa23fadf8a483e03f3065c3d --- /dev/null +++ b/backend/app/modules/academy_org/schemas.py @@ -0,0 +1,95 @@ +from datetime import datetime +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field, StringConstraints, field_validator + +from app.common.schemas import MediaRef, RequestModel, ResponseModel + +Focus = Literal["Hitting", "Pitching", "Both"] +Mode = Literal["h", "p"] +FaultTag = Annotated[str, StringConstraints(min_length=1, max_length=64)] + + +class GroupOut(ResponseModel): + id: UUID + name: str + focus: Focus + players: int + player_ids: list[UUID] + coaches: list[str] + coach_ids: list[UUID] + + +class GroupEnvelope(ResponseModel): + group: GroupOut + + +class GroupIn(RequestModel): + name: str = Field(min_length=1, max_length=80) + focus: Focus + coach_ids: list[UUID] = Field(default_factory=list, max_length=200) + player_ids: list[UUID] = Field(default_factory=list, max_length=1000) + + +class NoteOut(ResponseModel): + player_id: UUID + text: str + updated_at: datetime | None + version: int + + +class NoteEnvelope(ResponseModel): + note: NoteOut + + +class NoteIn(RequestModel): + text: str = Field(max_length=4000) + expected_version: int | None = Field(default=None, ge=0) + + +class MemberOut(ResponseModel): + id: UUID + name: str + focus: str + level: str | None + group_ids: list[UUID] + + +class RosterAddIn(RequestModel): + player_ids: list[UUID] = Field(min_length=1, max_length=100) + group_id: UUID | None = None + + +class RosterAddOut(ResponseModel): + added_player_ids: list[UUID] + already_present_player_ids: list[UUID] + + +class LibraryDrillOut(ResponseModel): + id: UUID + name: str + fixes: str + fault_tags: list[str] + by: str | None + author_id: UUID | None + mode: Mode + media: MediaRef | None + created_at: datetime + + +class LibraryEnvelope(ResponseModel): + drill: LibraryDrillOut + + +class LibraryDrillIn(RequestModel): + upload_id: UUID + name: str = Field(min_length=1, max_length=120) + mode: Mode + fault_tags: list[FaultTag] = Field(min_length=1, max_length=10) + fixes: str = Field(default="", max_length=500) + + @field_validator("fault_tags") + @classmethod + def lowercase_unique(cls, tags: list[str]) -> list[str]: + return list(dict.fromkeys(t.lower() for t in tags)) diff --git a/backend/app/modules/academy_org/service.py b/backend/app/modules/academy_org/service.py new file mode 100644 index 0000000000000000000000000000000000000000..76fcace4eff631962c57488184935277156bc478 --- /dev/null +++ b/backend/app/modules/academy_org/service.py @@ -0,0 +1,178 @@ +"""Academy groups (N28-N29), private coach notes (N30-N31), roster additions (N32-N33) and the library (N35-N36).""" + +from datetime import UTC, datetime, timedelta +from uuid import UUID + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.common.academy_access import Staff, require_player, visible_player_ids +from app.common.schemas import MediaRef, Page +from app.core.errors import Conflict, NotFound, Unprocessable +from app.core.pagination import PageParams, encode_cursor +from app.integrations.storage import StorageClient +from app.modules.academy.models import LibraryDrill, PlayerGroup +from app.modules.academy_org.repository import OrgRepository +from app.modules.academy_org.schemas import ( + GroupIn, + GroupOut, + LibraryDrillIn, + LibraryDrillOut, + MemberOut, + NoteIn, + NoteOut, + RosterAddIn, + RosterAddOut, +) + + +def _dedupe(ids: list[UUID]) -> list[UUID]: + return list(dict.fromkeys(ids)) + + +def _page(items: list, limit: int, created_at) -> Page: + """items holds up to limit+1 rows; created_at(item) gives (created_at, id) for the cursor.""" + next_cursor = None + if len(items) > limit: + items = items[:limit] + next_cursor = encode_cursor(*created_at(items[-1])) + return Page(items=items, next_cursor=next_cursor) + + +class OrgService: + def __init__(self, db: AsyncSession, storage: StorageClient): + self.db = db + self.storage = storage + self.repo = OrgRepository(db) + + # ---------- groups ---------- + async def _group_outs(self, groups: list[PlayerGroup], visible: set[UUID] | None) -> list[GroupOut]: + if not groups: + return [] + ids = [g.id for g in groups] + players = await self.repo.group_players(ids) + coaches = await self.repo.group_coaches(ids) + outs = [] + for g in groups: + player_ids = [p for p in players.get(g.id, []) if visible is None or p in visible] + outs.append(GroupOut(id=g.id, name=g.name, focus=g.focus, players=len(players.get(g.id, [])), + player_ids=player_ids, coaches=[n for _, n in coaches.get(g.id, [])], + coach_ids=[c for c, _ in coaches.get(g.id, [])])) + return outs + + async def list_groups(self, staff: Staff, paging: PageParams) -> Page[GroupOut]: + if staff.team_id is None: + return Page[GroupOut](items=[]) + rows = list(await self.repo.groups(staff.team_id, None if staff.sees_all else staff.id, + paging.cursor, paging.limit + 1)) + visible = None if staff.sees_all else set(await visible_player_ids(self.db, staff)) + outs = await self._group_outs(rows, visible) + by_id = {g.id: g for g in rows} + return _page(outs, paging.limit, lambda o: (by_id[o.id].created_at, o.id)) + + async def create_group(self, staff: Staff, body: GroupIn) -> GroupOut: + team_id = staff.team_id + assert team_id is not None + coach_ids, player_ids = _dedupe(body.coach_ids), _dedupe(body.player_ids) + if coach_ids and await self.repo.team_staff_ids(team_id, coach_ids) != set(coach_ids): + raise NotFound("Coach not found in your academy.") + if player_ids and await self.repo.team_player_ids(team_id, player_ids) != set(player_ids): + raise NotFound("Player not found in your academy.") + group = await self.repo.create_group(team_id, body.name, body.focus, coach_ids, player_ids) + if group is None: + raise Conflict("A group with this name already exists.", code="GROUP_NAME_TAKEN") + [out] = await self._group_outs([group], None) + return out + + # ---------- notes ---------- + @staticmethod + def _note_out(player_id: UUID, note) -> NoteOut: + if note is None: + return NoteOut(player_id=player_id, text="", updated_at=None, version=0) + return NoteOut(player_id=player_id, text=note.text, updated_at=note.updated_at, version=note.version) + + async def get_note(self, staff: Staff, player_id: UUID) -> NoteOut: + await require_player(self.db, staff, player_id) + return self._note_out(player_id, await self.repo.note(staff.team_id, staff.id, player_id)) # type: ignore[arg-type] + + async def save_note(self, staff: Staff, player_id: UUID, body: NoteIn) -> NoteOut: + await require_player(self.db, staff, player_id) + team_id = staff.team_id + assert team_id is not None + note = await self.repo.note(team_id, staff.id, player_id, lock=True) + stale = Conflict("This note changed. Refresh and try again.", code="STALE_VERSION") + if note is None: + if body.expected_version not in (None, 0): + raise stale + note = await self.repo.insert_note(team_id, staff.id, player_id, body.text) + if note is None: + raise stale + else: + if body.expected_version is not None and body.expected_version != note.version: + raise stale + note.text = body.text + note.version += 1 + note.updated_at = datetime.now(UTC) + await self.db.flush() + return self._note_out(player_id, note) + + # ---------- roster ---------- + async def members(self, staff: Staff, q: str | None, paging: PageParams) -> Page[MemberOut]: + if staff.team_id is None: + return Page[MemberOut](items=[]) + rows = list(await self.repo.members(staff.team_id, staff.id, q, paging.cursor, paging.limit + 1)) + groups = await self.repo.player_group_ids([r.id for r in rows], staff.team_id) if rows else {} + created = {r.id: r.created_at for r in rows} + items = [MemberOut(id=r.id, name=r.name or "", focus=r.focus, level=r.level, group_ids=groups.get(r.id, [])) + for r in rows] + return _page(items, paging.limit, lambda m: (created[m.id], m.id)) + + async def add_to_roster(self, staff: Staff, body: RosterAddIn) -> RosterAddOut: + player_ids = _dedupe(body.player_ids) + team_id = staff.team_id + if team_id is None or await self.repo.team_player_ids(team_id, player_ids) != set(player_ids): + raise NotFound("Player not found in your academy.") + if body.group_id is not None: + group = await self.repo.group_in_team(team_id, body.group_id) + if group is None or not (staff.is_admin or await self.repo.is_group_coach(group.id, staff.id)): + raise NotFound("Group not found.") + added = await self.repo.add_to_roster(team_id, staff.id, player_ids) + if body.group_id is not None: + await self.repo.add_to_group(body.group_id, player_ids) + return RosterAddOut(added_player_ids=[p for p in player_ids if p in added], + already_present_player_ids=[p for p in player_ids if p not in added]) + + # ---------- library ---------- + def _drill_out(self, row: tuple[LibraryDrill, str | None, str | None]) -> LibraryDrillOut: + drill, author, key = row + media = None + if drill.upload_id is not None and key is not None: + expires = datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl) + media = MediaRef(upload_id=drill.upload_id, url=self.storage.presign_get(key), expires_at=expires) + return LibraryDrillOut(id=drill.id, name=drill.name, fixes=drill.fixes, fault_tags=list(drill.fault_tags), + by=author, author_id=drill.author_id, mode=drill.mode, media=media, + created_at=drill.created_at) + + async def library(self, staff: Staff, mode: str | None, fault_tag: str | None, + paging: PageParams) -> Page[LibraryDrillOut]: + if staff.team_id is None: + return Page[LibraryDrillOut](items=[]) + rows = await self.repo.library(staff.team_id, mode, fault_tag, paging.cursor, paging.limit + 1) + return _page([self._drill_out(r) for r in rows], paging.limit, lambda d: (d.created_at, d.id)) + + async def publish_drill(self, staff: Staff, body: LibraryDrillIn) -> LibraryDrillOut: + staff.require("library") + upload = await self.repo.upload(body.upload_id, staff.id) + if upload is None: + raise NotFound("Upload not found.") + if upload.kind != "drill_video": + raise Unprocessable("This upload is not a drill video.", code="INVALID_MEDIA") + if upload.attached_at is not None: + raise Conflict("This video is already in use.", code="UPLOAD_ALREADY_USED") + if await self.storage.head(upload.object_key) is None: + raise Conflict("The video has not finished uploading.", code="UPLOAD_NOT_READY") + drill = LibraryDrill(team_id=staff.team_id, author_id=staff.id, name=body.name, fixes=body.fixes, + mode=body.mode, fault_tags=body.fault_tags, upload_id=upload.id) + self.db.add(drill) + await self.db.flush() + await self.repo.attach(upload, datetime.now(UTC)) + return self._drill_out(await self.repo.library_row(drill.id)) diff --git a/backend/app/modules/academy_staff/__init__.py b/backend/app/modules/academy_staff/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/academy_staff/controller.py b/backend/app/modules/academy_staff/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7d7cc702d66c2fae0b046117fd520bbdb32b5a --- /dev/null +++ b/backend/app/modules/academy_staff/controller.py @@ -0,0 +1,119 @@ +"""N26-N27 coaching access, N40-N43 academy coaches, N44-N45 access requests, N46-N48 staff codes.""" + +from datetime import date +from typing import Annotated, Literal +from uuid import UUID + +from fastapi import APIRouter, Header, Query, Response +from fastapi.responses import JSONResponse +from pydantic import BaseModel + +from app.common.academy_access import CurrentAdmin, CurrentStaff, staff_context +from app.common.schemas import Page +from app.core.dependencies import CurrentAccount, Db, Paging +from app.modules.academy_staff.schemas import ( + CoachAccessBody, + CoachAccessCreate, + CoachBody, + CoachOut, + CoachUpdate, + DecisionIn, + DecisionOut, + RequestPage, + StaffCodeBody, + StaffCodeCreate, + StaffCodeOut, +) +from app.modules.academy_staff.service import StaffService +from app.modules.idempotency.service import run_idempotent + +router = APIRouter(prefix="/v1", tags=["academy_staff"]) + +IdempotencyKey = Annotated[str | None, Header(max_length=128)] + + +class _Scoped(BaseModel): + """Idempotency payload that also covers the path id, so one key cannot replay across targets.""" + + target: UUID + body: dict + + +@router.get("/me/coach-access", response_model=CoachAccessBody) +async def get_coach_access(db: Db, account: CurrentAccount) -> CoachAccessBody: + return CoachAccessBody(coach_access=await StaffService(db).coach_access(account, await staff_context(db, account))) + + +@router.post("/me/coach-access", response_model=CoachAccessBody, status_code=201) +async def apply_for_coach_access(body: CoachAccessCreate, db: Db, account: CurrentAccount, + idempotency_key: IdempotencyKey = None) -> JSONResponse: + created = {"value": True} + + async def handler() -> CoachAccessBody: + access, created["value"] = await StaffService(db).apply(account, body.code) + return CoachAccessBody(coach_access=access) + + response = await run_idempotent(db, account.id, idempotency_key, body, handler, status_code=201) + if not created["value"]: + response.status_code = 200 + return response + + +@router.get("/academy/coaches", response_model=Page[CoachOut]) +async def list_coaches(db: Db, staff: CurrentStaff, + status: Literal["active", "paused", "removed", "all"] | None = None) -> Page[CoachOut]: + return Page(items=await StaffService(db).list_coaches(staff, status)) + + +@router.get("/academy/coaches/{coach_id}", response_model=CoachBody) +async def get_coach(coach_id: UUID, db: Db, staff: CurrentAdmin, activity_from: date | None = None, + activity_to: date | None = None) -> CoachBody: + return CoachBody(coach=await StaffService(db).get_coach(staff, coach_id, activity_from, activity_to)) + + +@router.patch("/academy/coaches/{coach_id}", response_model=CoachBody) +async def update_coach(coach_id: UUID, body: CoachUpdate, db: Db, staff: CurrentAdmin) -> CoachBody: + return CoachBody(coach=await StaffService(db).update_coach(staff, coach_id, body)) + + +@router.delete("/academy/coaches/{coach_id}", status_code=204) +async def remove_coach(coach_id: UUID, reassign_to: Annotated[UUID, Query()], db: Db, + staff: CurrentAdmin) -> Response: + await StaffService(db).remove_coach(staff, coach_id, reassign_to) + return Response(status_code=204) + + +@router.get("/academy/coach-requests", response_model=RequestPage) +async def list_requests(db: Db, staff: CurrentAdmin, paging: Paging, + status: Literal["pending", "approved", "declined", "all"] = "all") -> RequestPage: + return await StaffService(db).list_requests(staff, status, paging) + + +@router.post("/academy/coach-requests/{request_id}/decision", response_model=DecisionOut) +async def decide_request(request_id: UUID, body: DecisionIn, db: Db, staff: CurrentAdmin, + idempotency_key: IdempotencyKey = None) -> JSONResponse: + scoped = _Scoped(target=request_id, body=body.model_dump(mode="json")) + return await run_idempotent(db, staff.id, idempotency_key, scoped, + lambda: StaffService(db).decide(staff, request_id, body), status_code=200) + + +@router.get("/academy/staff-codes", response_model=Page[StaffCodeOut]) +async def list_codes(db: Db, staff: CurrentAdmin, paging: Paging, + status: Literal["active", "expired", "revoked", "all"] = "all") -> Page[StaffCodeOut]: + items, next_cursor = await StaffService(db).list_codes(staff, status, paging) + return Page(items=items, next_cursor=next_cursor) + + +@router.post("/academy/staff-codes", response_model=StaffCodeBody, status_code=201) +async def create_code(body: StaffCodeCreate, db: Db, staff: CurrentAdmin, + idempotency_key: IdempotencyKey = None) -> JSONResponse: + async def handler() -> StaffCodeBody: + return StaffCodeBody(staff_code=await StaffService(db).create_code(staff, body)) + + return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=201) + + +@router.delete("/academy/staff-codes/{code}", status_code=204) +async def revoke_code(code: str, db: Db, staff: CurrentAdmin) -> Response: + await StaffService(db).revoke_code(staff, code) + return Response(status_code=204) diff --git a/backend/app/modules/academy_staff/repository.py b/backend/app/modules/academy_staff/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..db1aad53295d366b8fbd0253350e0eb852c89b22 --- /dev/null +++ b/backend/app/modules/academy_staff/repository.py @@ -0,0 +1,166 @@ +"""Academy staff queries: memberships, access requests, staff codes, group links and activity aggregates.""" + +from datetime import datetime +from uuid import UUID + +from sqlalchemy import delete, func, select, update +from sqlalchemy.dialects.postgresql import insert + +from app.common.base_repository import BaseRepository +from app.core.pagination import Cursor +from app.modules.academy.models import ( + AcademyMembership, + CoachAccessRequest, + CoachPlayer, + GroupCoach, + PlayerGroup, + StaffCode, +) +from app.modules.accounts.models import Account +from app.modules.assignments.models import DrillAssignment +from app.modules.reviews.models import Review +from app.modules.sessions.models import SwingSession +from app.modules.teams.models import Team + + +class StaffRepository(BaseRepository[AcademyMembership]): + model = AcademyMembership + + # ----- teams and accounts ----- + async def team(self, team_id: UUID) -> Team | None: + return await self.session.get(Team, team_id) + + async def account(self, account_id: UUID) -> Account | None: + return await self.session.get(Account, account_id) + + # ----- memberships ----- + async def membership(self, team_id: UUID, account_id: UUID, *, lock: bool = False) -> AcademyMembership | None: + query = select(AcademyMembership).where(AcademyMembership.team_id == team_id, + AcademyMembership.account_id == account_id) + if lock: + query = query.with_for_update().execution_options(populate_existing=True) + return await self.session.scalar(query) + + async def memberships(self, team_id: UUID, statuses: list[str]) -> list[tuple[AcademyMembership, Account]]: + rows = await self.session.execute( + select(AcademyMembership, Account).join(Account, Account.id == AcademyMembership.account_id) + .where(AcademyMembership.team_id == team_id, AcademyMembership.status.in_(statuses)) + .order_by(AcademyMembership.created_at, AcademyMembership.id)) + return [(m, a) for m, a in rows.all()] + + async def admin_count(self, team_id: UUID) -> int: + return await self.session.scalar(select(func.count()).select_from(AcademyMembership).where( + AcademyMembership.team_id == team_id, AcademyMembership.role == "admin", + AcademyMembership.status == "active")) or 0 + + # ----- groups ----- + async def group_ids(self, team_id: UUID, coach_id: UUID) -> list[UUID]: + return list((await self.session.scalars( + select(GroupCoach.group_id).join(PlayerGroup, PlayerGroup.id == GroupCoach.group_id) + .where(PlayerGroup.team_id == team_id, GroupCoach.coach_id == coach_id) + .order_by(PlayerGroup.created_at, PlayerGroup.id))).all()) + + async def count_groups(self, team_id: UUID, group_ids: list[UUID]) -> int: + return await self.session.scalar(select(func.count()).select_from(PlayerGroup).where( + PlayerGroup.team_id == team_id, PlayerGroup.id.in_(group_ids))) or 0 + + async def set_groups(self, team_id: UUID, coach_id: UUID, group_ids: list[UUID]) -> None: + team_groups = select(PlayerGroup.id).where(PlayerGroup.team_id == team_id) + await self.session.execute(delete(GroupCoach).where(GroupCoach.coach_id == coach_id, + GroupCoach.group_id.in_(team_groups))) + await self.add_groups(coach_id, group_ids) + + async def add_groups(self, coach_id: UUID, group_ids: list[UUID]) -> None: + if group_ids: + await self.session.execute(insert(GroupCoach).values( + [{"group_id": g, "coach_id": coach_id} for g in set(group_ids)]).on_conflict_do_nothing()) + + async def move_responsibilities(self, team_id: UUID, from_id: UUID, to_id: UUID) -> None: + """Roster rows and group coaching go to the replacement; rows the replacement already has are dropped.""" + has = select(CoachPlayer.player_id).where(CoachPlayer.team_id == team_id, CoachPlayer.coach_id == to_id) + await self.session.execute(update(CoachPlayer).where( + CoachPlayer.team_id == team_id, CoachPlayer.coach_id == from_id, CoachPlayer.player_id.not_in(has)) + .values(coach_id=to_id)) + await self.session.execute(delete(CoachPlayer).where(CoachPlayer.team_id == team_id, + CoachPlayer.coach_id == from_id)) + old = await self.group_ids(team_id, from_id) + await self.set_groups(team_id, from_id, []) + await self.add_groups(to_id, old) + + # ----- activity ----- + async def review_activity(self, team_id: UUID, coach_id: UUID, start: datetime, end: datetime): + """(reviews, avg hours from session creation to the review) for reviews written in [start, end).""" + seconds = func.extract("epoch", Review.updated_at - SwingSession.created_at) + row = (await self.session.execute( + select(func.count(), func.avg(seconds) / 3600) + .select_from(Review).join(SwingSession, SwingSession.id == Review.session_id) + .join(Account, Account.id == SwingSession.owner_id) + .where(Account.team_id == team_id, Review.coach_id == coach_id, SwingSession.deleted_at.is_(None), + Review.updated_at >= start, Review.updated_at < end))).one() + return row[0], (round(float(row[1]), 1) if row[1] is not None else None) + + async def drills_set(self, team_id: UUID, coach_id: UUID, start: datetime, end: datetime) -> int: + return await self.session.scalar(select(func.count()).select_from(DrillAssignment).where( + DrillAssignment.team_id == team_id, DrillAssignment.assigned_by_id == coach_id, + DrillAssignment.created_at >= start, DrillAssignment.created_at < end)) or 0 + + async def count(self, query) -> int: + return await self.session.scalar(select(func.count()).select_from(query.subquery())) or 0 + + # ----- staff codes ----- + async def code_row(self, code: str, *, team_id: UUID | None = None, lock: bool = False) -> StaffCode | None: + query = select(StaffCode).where(StaffCode.code == code) + if team_id is not None: + query = query.where(StaffCode.team_id == team_id) + if lock: + query = query.with_for_update().execution_options(populate_existing=True) + return await self.session.scalar(query) + + async def code_exists(self, code: str) -> bool: + return await self.session.scalar(select(StaffCode.id).where(StaffCode.code == code)) is not None + + async def codes(self, team_id: UUID, status: str, now: datetime, limit: int, cursor: Cursor | None): + query = select(StaffCode).where(StaffCode.team_id == team_id) + if status == "active": + query = query.where(StaffCode.revoked_at.is_(None), StaffCode.expires_at > now) + elif status == "expired": + query = query.where(StaffCode.revoked_at.is_(None), StaffCode.expires_at <= now) + elif status == "revoked": + query = query.where(StaffCode.revoked_at.is_not(None)) + if cursor: + query = query.where( + (StaffCode.created_at < cursor.created_at) + | ((StaffCode.created_at == cursor.created_at) & (StaffCode.id < cursor.id))) + query = query.order_by(StaffCode.created_at.desc(), StaffCode.id.desc()).limit(limit + 1) + return list((await self.session.scalars(query)).all()) + + # ----- access requests ----- + async def latest_request(self, applicant_id: UUID) -> CoachAccessRequest | None: + return await self.session.scalar(select(CoachAccessRequest).where( + CoachAccessRequest.applicant_id == applicant_id) + .order_by(CoachAccessRequest.created_at.desc(), CoachAccessRequest.id.desc()).limit(1)) + + async def pending_request(self, applicant_id: UUID) -> CoachAccessRequest | None: + return await self.session.scalar(select(CoachAccessRequest).where( + CoachAccessRequest.applicant_id == applicant_id, CoachAccessRequest.status == "pending")) + + async def locked_request(self, team_id: UUID, request_id: UUID) -> CoachAccessRequest | None: + return await self.session.scalar(select(CoachAccessRequest).where( + CoachAccessRequest.id == request_id, CoachAccessRequest.team_id == team_id) + .with_for_update().execution_options(populate_existing=True)) + + async def requests(self, team_id: UUID, status: str, limit: int, cursor: Cursor | None): + query = (select(CoachAccessRequest, Account).join(Account, Account.id == CoachAccessRequest.applicant_id) + .where(CoachAccessRequest.team_id == team_id)) + if status != "all": + query = query.where(CoachAccessRequest.status == status) + if cursor: + query = query.where( + (CoachAccessRequest.created_at < cursor.created_at) + | ((CoachAccessRequest.created_at == cursor.created_at) & (CoachAccessRequest.id < cursor.id))) + query = query.order_by(CoachAccessRequest.created_at.desc(), CoachAccessRequest.id.desc()).limit(limit + 1) + return [(r, a) for r, a in (await self.session.execute(query)).all()] + + async def total_pending(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 diff --git a/backend/app/modules/academy_staff/schemas.py b/backend/app/modules/academy_staff/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..5740909e120bc3ba3e7cbf3a67c4fc7791f380de --- /dev/null +++ b/backend/app/modules/academy_staff/schemas.py @@ -0,0 +1,119 @@ +"""Academy staff shapes: coaching access, members, access requests and staff codes.""" + +from datetime import date, datetime +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field + +from app.common.schemas import Page, RequestModel, ResponseModel + +StaffRole = Literal["admin", "coach", "assistant"] +Permissions = dict[str, bool] + + +class CoachAccessOut(ResponseModel): + status: Literal["none", "pending", "approved", "declined"] + code: str | None + sent_at: datetime | None + + +class CoachAccessBody(ResponseModel): + coach_access: CoachAccessOut + + +class CoachAccessCreate(RequestModel): + code: Annotated[str, Field(min_length=6, max_length=64)] + + +class ActivityOut(ResponseModel): + reviews: int + avg_reply_hours: float | None + players: int + drills_set: int + period_start: date + period_end: date + + +class CoachOut(ResponseModel): + id: UUID + name: str + coaches: str + joined: datetime + joined_with: str | None + role: StaffRole + is_me: bool + sees_all: bool + group_ids: list[UUID] + permissions: Permissions | None + activity: ActivityOut | None + status: Literal["active", "paused", "removed"] + version: int + + +class CoachBody(ResponseModel): + coach: CoachOut + + +class PermissionsIn(RequestModel): + review: bool | None = None + drills: bool | None = None + goals: bool | None = None + library: bool | None = None + earnings: bool | None = None + + +class CoachUpdate(RequestModel): + role: StaffRole | None = None + sees_all: bool | None = None + group_ids: list[UUID] | None = None + permissions: PermissionsIn | None = None + status: Literal["active", "paused"] | None = None + expected_version: int | None = None + + +class RequestOut(ResponseModel): + id: UUID + user_id: UUID + name: str + code: str + at: datetime + also_player: bool + status: Literal["pending", "approved", "declined"] + + +class RequestPage(Page[RequestOut]): + total_pending: int + + +class DecisionIn(RequestModel): + decision: Literal["approve", "decline"] + role: Literal["coach", "assistant"] | None = None + sees_all: bool = False + group_ids: list[UUID] = Field(default_factory=list) + + +class DecisionOut(ResponseModel): + request: RequestOut + coach: CoachOut | None + + +class StaffCodeOut(ResponseModel): + code: str + role: Literal["coach", "assistant"] + expires: datetime + uses: int + max_uses: int + approval: Literal["admin", "auto"] + status: Literal["active", "expired", "revoked"] + + +class StaffCodeBody(ResponseModel): + staff_code: StaffCodeOut + + +class StaffCodeCreate(RequestModel): + role: Literal["coach", "assistant"] + expires_days: Literal[1, 7, 30] + max_uses: Literal[1, 5, 20] + approval: Literal["admin", "auto"] diff --git a/backend/app/modules/academy_staff/service.py b/backend/app/modules/academy_staff/service.py new file mode 100644 index 0000000000000000000000000000000000000000..11ceba26c0705826c3c8efef0d0a01c103a63ca4 --- /dev/null +++ b/backend/app/modules/academy_staff/service.py @@ -0,0 +1,346 @@ +"""Staff codes, coaching-access applications and academy member management.""" + +import calendar +import secrets +from dataclasses import dataclass +from datetime import UTC, date, datetime, time, timedelta +from uuid import UUID + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.common.academy_access import Staff, normalize_permissions, visible_players_query +from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable +from app.core.pagination import PageParams, encode_cursor +from app.core.rate_limit import RateLimiter +from app.modules.academy.models import AcademyMembership, CoachAccessRequest, StaffCode +from app.modules.academy_staff.repository import StaffRepository +from app.modules.academy_staff.schemas import ( + ActivityOut, + CoachAccessOut, + CoachOut, + CoachUpdate, + DecisionIn, + DecisionOut, + RequestOut, + RequestPage, + StaffCodeCreate, + StaffCodeOut, +) +from app.modules.accounts.models import Account +from app.modules.teams.models import Team + +CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # no 0/O/1/I/L +COACHES_LABEL = {"h": "Hitting", "p": "Pitching", "both": "Both"} +_apply_limiter = RateLimiter(10, 60.0) + + +def normalize_code(code: str) -> str: + return code.strip().upper() + + +def new_code() -> str: + pick = lambda n: "".join(secrets.choice(CODE_ALPHABET) for _ in range(n)) # noqa: E731 + return f"CV-{pick(4)}-{pick(2)}" + + +def _now() -> datetime: + return datetime.now(UTC) + + +def code_status(code: StaffCode, now: datetime) -> str: + if code.revoked_at is not None: + return "revoked" + return "expired" if code.expires_at <= now else "active" + + +def code_out(code: StaffCode, now: datetime) -> StaffCodeOut: + return StaffCodeOut(code=code.code, role=code.role, expires=code.expires_at, uses=code.uses, + max_uses=code.max_uses, approval=code.approval, status=code_status(code, now)) + + +@dataclass +class Member: + """One person on the academy staff, from a membership row or the synthesized owner.""" + + account: Account + role: str + status: str + sees_all: bool + permissions: dict[str, bool] + joined: datetime + joined_with: str | None + version: int + + +class StaffService: + def __init__(self, db: AsyncSession): + self.db = db + self.repo = StaffRepository(db) + + # ---------------------------------------------------------------- coaching access (applicant side) + + async def coach_access(self, account: Account, staff: Staff | None) -> CoachAccessOut: + latest = await self.repo.latest_request(account.id) + if staff is not None and staff.team_id is not None: + approved = latest is not None and latest.status == "approved" + return CoachAccessOut(status="approved", code=latest.code if approved else None, + sent_at=latest.created_at if approved else None) + if latest is None: + return CoachAccessOut(status="none", code=None, sent_at=None) + return CoachAccessOut(status=latest.status, code=latest.code, sent_at=latest.created_at) + + async def apply(self, account: Account, raw_code: str) -> tuple[CoachAccessOut, bool]: + """Returns (coach_access, created). Uses are counted at submission and a decline does not give one back.""" + _apply_limiter.hit(f"coach_apply:{account.id}") + code = normalize_code(raw_code) + row = await self.repo.code_row(code, lock=True) + if row is None: + raise Unprocessable("That code isn't valid.", code="CODE_INVALID") + pending = await self.repo.pending_request(account.id) + if pending is not None: + if pending.code == code: + return CoachAccessOut(status="pending", code=pending.code, sent_at=pending.created_at), False + raise Conflict("You already have a request waiting for approval.", code="REQUEST_PENDING") + team = await self.repo.team(row.team_id) + existing = await self.repo.membership(row.team_id, account.id) + if team.coach_id == account.id or (existing is not None and existing.status != "removed"): + raise Conflict("You are already on this academy's staff.", code="ALREADY_MEMBER") + now = _now() + if code_status(row, now) != "active" or row.uses >= row.max_uses: + raise Conflict("That code can't be used any more.", code="CODE_UNAVAILABLE") + row.uses += 1 + # A removed member re-enters only through an admin decision, whatever the code's approval mode. + auto = row.approval == "auto" and not (existing is not None and existing.status == "removed") + request = CoachAccessRequest(applicant_id=account.id, team_id=row.team_id, staff_code_id=row.id, + code=row.code, status="approved" if auto else "pending", + decided_at=now if auto else None) + self.db.add(request) + await self.db.flush() + await self.db.refresh(request) + if auto: + await self._upsert_membership(row.team_id, account.id, row.role, False, None, row.code) + return CoachAccessOut(status=request.status, code=request.code, sent_at=request.created_at), True + + # ---------------------------------------------------------------- members + + async def _team(self, staff: Staff) -> Team: + if staff.team_id is None: + raise Forbidden("Create or join an academy first.") + return await self.repo.team(staff.team_id) # type: ignore[return-value] + + def _owner(self, team: Team, account: Account) -> Member: + return Member(account, "admin", "active", True, normalize_permissions("admin"), team.created_at, None, 1) + + @staticmethod + def _member(membership: AcademyMembership, account: Account) -> Member: + return Member(account, membership.role, membership.status, membership.sees_all or membership.role == "admin", + normalize_permissions(membership.role, membership.permissions), membership.created_at, + membership.joined_with, membership.version) + + async def _find(self, team: Team, member_id: UUID) -> Member: + if member_id == team.coach_id: + return self._owner(team, await self.repo.account(member_id)) # type: ignore[arg-type] + membership = await self.repo.membership(team.id, member_id) + if membership is None: + raise NotFound("We couldn't find that coach.") + return self._member(membership, await self.repo.account(member_id)) # type: ignore[arg-type] + + @staticmethod + def _period(start: date | None, end: date | None) -> tuple[date, date]: + today = _now().date() + start = start or today.replace(day=1) + end = end or today.replace(day=calendar.monthrange(today.year, today.month)[1]) + if start > end: + raise Unprocessable("The start date is after the end date.", code="INVALID_PERIOD") + return start, end + + async def _out(self, team: Team, member: Member, me_id: UUID, start: date, end: date) -> CoachOut: + lo = datetime.combine(start, time.min, UTC) + hi = datetime.combine(end + timedelta(days=1), time.min, UTC) + who = Staff(member.account, team.id, member.role, member.sees_all, member.permissions) + reviews, avg_hours = await self.repo.review_activity(team.id, member.account.id, lo, hi) + activity = ActivityOut( + reviews=reviews, avg_reply_hours=avg_hours, players=await self.repo.count(visible_players_query(who)), + drills_set=await self.repo.drills_set(team.id, member.account.id, lo, hi), + period_start=start, period_end=end) + return CoachOut( + id=member.account.id, name=member.account.name, coaches=COACHES_LABEL[member.account.focus], + joined=member.joined, joined_with=member.joined_with, role=member.role, + is_me=member.account.id == me_id, sees_all=member.sees_all, + group_ids=await self.repo.group_ids(team.id, member.account.id), permissions=member.permissions, + activity=activity, status=member.status, version=member.version) + + async def list_coaches(self, staff: Staff, status: str | None) -> list[CoachOut]: + team = await self._team(staff) + statuses = {"active": ["active"], "paused": ["paused"], "removed": ["removed"], + "all": ["active", "paused", "removed"], None: ["active", "paused"]}[status] + members = [self._member(m, a) for m, a in await self.repo.memberships(team.id, statuses)] + if "active" in statuses: + owner = await self.repo.account(team.coach_id) + members.insert(0, self._owner(team, owner)) # type: ignore[arg-type] + start, end = self._period(None, None) + items = [await self._out(team, m, staff.id, start, end) for m in members] + if staff.role != "admin": # colleagues' staff code, permissions and activity are admin-only + items = [c.model_copy(update={"joined_with": None, "permissions": None, "activity": None}) + if not c.is_me else c for c in items] + return items + + async def get_coach(self, staff: Staff, coach_id: UUID, start: date | None, end: date | None) -> CoachOut: + team = await self._team(staff) + start, end = self._period(start, end) + return await self._out(team, await self._find(team, coach_id), staff.id, start, end) + + async def update_coach(self, staff: Staff, coach_id: UUID, patch: CoachUpdate) -> CoachOut: + values = patch.model_dump(exclude_unset=True, exclude={"expected_version"}) + if not values: + raise Unprocessable("Send at least one change.", code="NO_CHANGES") + team = await self._team(staff) + if coach_id == team.coach_id: + raise Conflict("The academy owner can't be changed.", code="OWNER_IMMUTABLE") + membership = await self.repo.membership(team.id, coach_id, lock=True) + if membership is None or membership.status == "removed": + raise NotFound("We couldn't find that coach.") + if patch.expected_version is not None and patch.expected_version != membership.version: + raise Conflict("This coach changed. Refresh and try again.", code="STALE_VERSION") + group_ids = patch.group_ids + if group_ids is not None and await self.repo.count_groups(team.id, group_ids) != len(set(group_ids)): + raise Unprocessable("A group isn't part of this academy.", code="INVALID_GROUP") + role = patch.role or membership.role + # The owner is always an admin, so the academy never runs out of admins through this endpoint. + given = patch.permissions.model_dump(exclude_none=True) if patch.permissions else None + if given is not None: + permissions = normalize_permissions(role, {**membership.permissions, **given}) + elif role != membership.role: + permissions = normalize_permissions(role) + else: + permissions = normalize_permissions(role, membership.permissions) + membership.role = role + membership.permissions = permissions + if patch.sees_all is not None: + membership.sees_all = patch.sees_all + if patch.status is not None: + membership.status = patch.status + membership.version += 1 + await self.db.flush() + if group_ids is not None: + await self.repo.set_groups(team.id, coach_id, group_ids) + await self.db.refresh(membership) + start, end = self._period(None, None) + member = self._member(membership, await self.repo.account(coach_id)) # type: ignore[arg-type] + return await self._out(team, member, staff.id, start, end) + + async def remove_coach(self, staff: Staff, coach_id: UUID, reassign_to: UUID) -> None: + team = await self._team(staff) + if coach_id == team.coach_id: + raise Conflict("The academy owner can't be removed.", code="OWNER_IMMUTABLE") + membership = await self.repo.membership(team.id, coach_id, lock=True) + if membership is None: + raise NotFound("We couldn't find that coach.") + if membership.status == "removed": + return + replacement = await self.repo.membership(team.id, reassign_to) + valid = reassign_to != coach_id and ( + reassign_to == team.coach_id or (replacement is not None and replacement.status == "active")) + if not valid: + raise Conflict("Choose another active coach to take over.", code="INVALID_REPLACEMENT") + await self.repo.move_responsibilities(team.id, coach_id, reassign_to) + membership.status = "removed" + membership.version += 1 + await self.db.flush() + + # ---------------------------------------------------------------- access requests (admin side) + + @staticmethod + def _request_out(request: CoachAccessRequest, applicant: Account) -> RequestOut: + return RequestOut(id=request.id, user_id=applicant.id, name=applicant.name, code=request.code, + at=request.created_at, also_player=applicant.role == "player", status=request.status) + + async def list_requests(self, staff: Staff, status: str, paging: PageParams) -> RequestPage: + rows = await self.repo.requests(staff.team_id, status, paging.limit, paging.cursor) # type: ignore[arg-type] + page = rows[:paging.limit] + next_cursor = encode_cursor(page[-1][0].created_at, page[-1][0].id) if len(rows) > paging.limit else None + return RequestPage(items=[self._request_out(r, a) for r, a in page], next_cursor=next_cursor, + total_pending=await self.repo.total_pending(staff.team_id)) # type: ignore[arg-type] + + async def decide(self, staff: Staff, request_id: UUID, body: DecisionIn) -> DecisionOut: + team = await self._team(staff) + request = await self.repo.locked_request(team.id, request_id) + if request is None: + raise NotFound("We couldn't find that request.") + applicant = await self.repo.account(request.applicant_id) + target = "approved" if body.decision == "approve" else "declined" + if request.status != "pending": + if request.status != target: + raise Conflict("This request was already decided.", code="REQUEST_ALREADY_DECIDED") + coach = None + if target == "approved": + coach = await self._out(team, await self._find(team, request.applicant_id), staff.id, + *self._period(None, None)) + return DecisionOut(request=self._request_out(request, applicant), coach=coach) # type: ignore[arg-type] + coach = None + if target == "approved": + if body.group_ids and await self.repo.count_groups(team.id, body.group_ids) != len(set(body.group_ids)): + raise Unprocessable("A group isn't part of this academy.", code="INVALID_GROUP") + code = await self.repo.code_row(request.code) + role = body.role or (code.role if code else "coach") + membership = await self._upsert_membership(team.id, request.applicant_id, role, body.sees_all, + body.group_ids, request.code) + coach = await self._out(team, self._member(membership, applicant), staff.id, # type: ignore[arg-type] + *self._period(None, None)) + request.status = target + request.decided_by_id = staff.id + request.decided_at = _now() + await self.db.flush() + return DecisionOut(request=self._request_out(request, applicant), coach=coach) # type: ignore[arg-type] + + async def _upsert_membership(self, team_id: UUID, account_id: UUID, role: str, sees_all: bool, + group_ids: list[UUID] | None, code: str) -> AcademyMembership: + """Creates the member, or reactivates one that was removed or paused, with the role's permissions.""" + permissions = normalize_permissions(role) + membership = await self.repo.membership(team_id, account_id, lock=True) + if membership is None: + membership = await self.repo.create(team_id=team_id, account_id=account_id, role=role, status="active", + sees_all=sees_all, permissions=permissions, joined_with=code) + else: + membership.role, membership.status, membership.sees_all = role, "active", sees_all + membership.permissions, membership.joined_with = permissions, code + membership.version += 1 + await self.db.flush() + await self.db.refresh(membership) + if group_ids: + await self.repo.add_groups(account_id, group_ids) + return membership + + # ---------------------------------------------------------------- staff codes + + async def list_codes(self, staff: Staff, status: str, paging: PageParams): + now = _now() + rows = await self.repo.codes(staff.team_id, status, now, paging.limit, paging.cursor) # type: ignore[arg-type] + page = rows[:paging.limit] + next_cursor = encode_cursor(page[-1].created_at, page[-1].id) if len(rows) > paging.limit else None + return [code_out(c, now) for c in page], next_cursor + + async def create_code(self, staff: Staff, body: StaffCodeCreate) -> StaffCodeOut: + for _ in range(10): + code = new_code() + if not await self.repo.code_exists(code): + break + else: + raise Conflict("Couldn't generate a code. Please try again.", code="CODE_COLLISION") + now = _now() + row = StaffCode(team_id=staff.team_id, code=code, role=body.role, + expires_at=now + timedelta(days=body.expires_days), + max_uses=body.max_uses, uses=0, approval=body.approval, created_by_id=staff.id) + self.db.add(row) + await self.db.flush() + await self.db.refresh(row) + return code_out(row, now) + + async def revoke_code(self, staff: Staff, raw_code: str) -> None: + row = await self.repo.code_row(normalize_code(raw_code), team_id=staff.team_id, lock=True) + if row is None: + raise NotFound("We couldn't find that code.") + if row.revoked_at is None: + row.revoked_at = _now() + await self.db.flush() + diff --git a/backend/app/modules/accounts/repository.py b/backend/app/modules/accounts/repository.py index ed749ce3613760a3d6b7b5b6558508dc534e2abd..4723a9348c9028cbf75373cad4b82cfe57e41efb 100644 --- a/backend/app/modules/accounts/repository.py +++ b/backend/app/modules/accounts/repository.py @@ -6,6 +6,7 @@ from uuid import UUID from sqlalchemy import exists, select from app.common.base_repository import BaseRepository +from app.modules.academy.models import CoachAccessRequest, GroupCoach, PlayerGroup from app.modules.accounts.models import Account from app.modules.sessions.models import SwingSession from app.modules.teams.models import Team @@ -38,3 +39,17 @@ class AccountRepository(BaseRepository[Account]): async def upload_keys(self, owner_id: UUID) -> Sequence[str]: return (await self.session.scalars(select(Upload.object_key).where(Upload.owner_id == owner_id))).all() + + async def latest_coach_request(self, account_id: UUID) -> CoachAccessRequest | None: + return await self.session.scalar(select(CoachAccessRequest).where( + CoachAccessRequest.applicant_id == account_id) + .order_by(CoachAccessRequest.created_at.desc(), CoachAccessRequest.id.desc()).limit(1)) + + async def team_name(self, team_id: UUID) -> str | None: + return await self.session.scalar(select(Team.name).where(Team.id == team_id)) + + async def coaching_group_ids(self, team_id: UUID, account_id: UUID) -> list[UUID]: + return list((await self.session.scalars( + select(GroupCoach.group_id).join(PlayerGroup, PlayerGroup.id == GroupCoach.group_id) + .where(PlayerGroup.team_id == team_id, GroupCoach.coach_id == account_id) + .order_by(PlayerGroup.created_at, PlayerGroup.id))).all()) diff --git a/backend/app/modules/accounts/schemas.py b/backend/app/modules/accounts/schemas.py index c52218ca1ea1b13ec042b6f9a3601b114e0b5176..032a46eeb7651b6f975005dd3faafd28fc50d18f 100644 --- a/backend/app/modules/accounts/schemas.py +++ b/backend/app/modules/accounts/schemas.py @@ -7,6 +7,7 @@ from uuid import UUID from pydantic import Field, field_validator from app.common.schemas import RequestModel, ResponseModel +from app.modules.academy_staff.schemas import CoachAccessOut from app.modules.accounts.models import Account from app.modules.billing.entitlement import Entitlement from app.modules.teams.schemas import TeamOut @@ -58,10 +59,30 @@ class UserBody(ResponseModel): user: UserOut +class AcademyOut(ResponseModel): + id: UUID + name: str + role: str + status: str + sees_all: bool + group_ids: list[UUID] + permissions: dict[str, bool] + + +class CapabilitiesOut(ResponseModel): + player: bool + coach: bool + academy_admin: bool + corporate_view: bool + + class MeOut(ResponseModel): user: UserOut team: TeamOut | None entitlement: Entitlement + academy: AcademyOut | None = None + coach_access: CoachAccessOut + capabilities: CapabilitiesOut def _not_null(cls, value): diff --git a/backend/app/modules/accounts/service.py b/backend/app/modules/accounts/service.py index e109b8a0c2c9153407ad07cd9e67b5b8aa946730..355c518bc321ecad4a978cc03877942cf12e5636 100644 --- a/backend/app/modules/accounts/service.py +++ b/backend/app/modules/accounts/service.py @@ -4,11 +4,13 @@ from decimal import Decimal from sqlalchemy.ext.asyncio import AsyncSession +from app.common.academy_access import staff_context from app.core.errors import Conflict from app.integrations.storage import StorageClient +from app.modules.academy_staff.schemas import CoachAccessOut from app.modules.accounts.models import Account from app.modules.accounts.repository import AccountRepository -from app.modules.accounts.schemas import MeOut, MeUpdate, UserOut +from app.modules.accounts.schemas import AcademyOut, CapabilitiesOut, MeOut, MeUpdate, UserOut from app.modules.billing.entitlement import EntitlementService from app.modules.teams.schemas import TeamOut @@ -34,8 +36,28 @@ class AccountService: t, coach_name = found team = TeamOut(id=t.id, code=t.code, name=t.name, coach_id=t.coach_id, coach_name=coach_name, coaching=t.coaching, created_at=t.created_at) + staff = await staff_context(self.db, account) + academy = None + if staff is not None and staff.team_id is not None: + academy = AcademyOut( + id=staff.team_id, name=await self.accounts.team_name(staff.team_id) or "", role=staff.role, + status="active", sees_all=staff.sees_all, + group_ids=await self.accounts.coaching_group_ids(staff.team_id, account.id), + permissions=staff.permissions) + latest = await self.accounts.latest_coach_request(account.id) + if academy is not None: + approved = latest is not None and latest.status == "approved" + access = CoachAccessOut(status="approved", code=latest.code if approved else None, + sent_at=latest.created_at if approved else None) + elif latest is None: + access = CoachAccessOut(status="none", code=None, sent_at=None) + else: + access = CoachAccessOut(status=latest.status, code=latest.code, sent_at=latest.created_at) + capabilities = CapabilitiesOut(player=account.role == "player", coach=staff is not None, + academy_admin=staff is not None and staff.is_admin, corporate_view=False) return MeOut(user=await self.user(account), team=team, - entitlement=await EntitlementService(self.db).get(account.id)) + entitlement=await EntitlementService(self.db).get(account.id), + academy=academy, coach_access=access, capabilities=capabilities) async def update(self, account: Account, patch: MeUpdate) -> UserOut: values = patch.model_dump(exclude_unset=True, exclude={"profile"}) diff --git a/backend/app/modules/arm_care/__init__.py b/backend/app/modules/arm_care/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/arm_care/controller.py b/backend/app/modules/arm_care/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..c4fd8a5181c0fd7a4fe18ce0e40c1fdda2c949d3 --- /dev/null +++ b/backend/app/modules/arm_care/controller.py @@ -0,0 +1,37 @@ +"""N23-N25: arm care (player only).""" + +from datetime import date +from typing import Annotated + +from fastapi import APIRouter, Depends, Header, Query + +from app.core.dependencies import CurrentPlayer, Db +from app.integrations.push import PushClient, get_push_client +from app.modules.arm_care.schemas import ArmCareEnvelope, FeelIn, FeelOut, OutingIn, OutingResult +from app.modules.arm_care.service import ArmCareService +from app.modules.idempotency.service import run_idempotent + +router = APIRouter(prefix="/v1/me/arm-care", tags=["arm-care"]) + + +@router.get("", response_model=ArmCareEnvelope) +async def get_arm_care(player: CurrentPlayer, db: Db, start: Annotated[date | None, Query(alias="from")] = None, + end: Annotated[date | None, Query(alias="to")] = None) -> ArmCareEnvelope: + return ArmCareEnvelope(arm_care=await ArmCareService(db).get(player, start, end)) + + +@router.post("/outings", status_code=201, response_model=OutingResult) +async def add_outing(body: OutingIn, player: CurrentPlayer, db: Db, + push: Annotated[PushClient, Depends(get_push_client)], + idempotency_key: Annotated[str | None, Header(max_length=128)] = None): + service = ArmCareService(db, push) + + async def handler() -> OutingResult: + return await service.add_outing(player, body) + + return await run_idempotent(db, player.id, idempotency_key, body, handler, status_code=201) + + +@router.put("/feel", response_model=FeelOut) +async def set_feel(body: FeelIn, player: CurrentPlayer, db: Db) -> FeelOut: + return await ArmCareService(db).set_feel(player, body) diff --git a/backend/app/modules/arm_care/models.py b/backend/app/modules/arm_care/models.py new file mode 100644 index 0000000000000000000000000000000000000000..2d17a81c6967677a2d37b0f08e984b0d4561bee1 --- /dev/null +++ b/backend/app/modules/arm_care/models.py @@ -0,0 +1,41 @@ +import uuid +from datetime import date + +from sqlalchemy import CheckConstraint, Date, ForeignKey, Index, SmallInteger, String, text +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column + +from app.common.base_model import Base, CreatedAtMixin, IdMixin + + +def _owner() -> Mapped[uuid.UUID]: + return mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE")) + + +class ArmOuting(IdMixin, CreatedAtMixin, Base): + """A game pitch count the player logged. local_date is the player's calendar day.""" + + __tablename__ = "arm_outings" + __table_args__ = ( + CheckConstraint("pitches BETWEEN 1 AND 200", name="pitches"), + CheckConstraint("source IN ('game')", name="source"), + Index("ix_arm_outings_owner_id_local_date", "owner_id", text("local_date DESC")), + ) + + owner_id: Mapped[uuid.UUID] = _owner() + local_date: Mapped[date] = mapped_column(Date) + pitches: Mapped[int] = mapped_column(SmallInteger) + source: Mapped[str] = mapped_column(String(8), server_default="game") + + +class ArmFeel(IdMixin, CreatedAtMixin, Base): + """Arm-feel reports; the newest one is the current feel.""" + + __tablename__ = "arm_feel_events" + __table_args__ = ( + CheckConstraint("feel IN ('sore', 'tight', 'good')", name="feel"), + Index("ix_arm_feel_events_owner_id_created_at", "owner_id", text("created_at DESC")), + ) + + owner_id: Mapped[uuid.UUID] = _owner() + feel: Mapped[str] = mapped_column(String(8)) diff --git a/backend/app/modules/arm_care/repository.py b/backend/app/modules/arm_care/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..eae9f7045a528fed8d72fd758aa23c10c6813721 --- /dev/null +++ b/backend/app/modules/arm_care/repository.py @@ -0,0 +1,30 @@ +from datetime import date +from uuid import UUID + +from sqlalchemy import select + +from app.common.base_repository import BaseRepository +from app.modules.accounts.models import Account +from app.modules.arm_care.models import ArmFeel, ArmOuting + + +class OutingRepository(BaseRepository[ArmOuting]): + model = ArmOuting + + async def in_range(self, owner_id: UUID, start: date, end: date) -> list[ArmOuting]: + query = (select(ArmOuting).where(ArmOuting.owner_id == owner_id, ArmOuting.local_date >= start, + ArmOuting.local_date <= end) + .order_by(ArmOuting.local_date.desc(), ArmOuting.created_at.desc(), ArmOuting.id.desc())) + return list((await self.session.scalars(query)).all()) + + +class FeelRepository(BaseRepository[ArmFeel]): + model = ArmFeel + + async def latest(self, owner_id: UUID) -> ArmFeel | None: + return await self.session.scalar(select(ArmFeel).where(ArmFeel.owner_id == owner_id) + .order_by(ArmFeel.created_at.desc(), ArmFeel.id.desc()).limit(1)) + + async def lock_owner(self, owner_id: UUID) -> None: + """Serialises one player's feel updates.""" + await self.session.scalar(select(Account.id).where(Account.id == owner_id).with_for_update()) diff --git a/backend/app/modules/arm_care/schemas.py b/backend/app/modules/arm_care/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..3c09dd2794f7392905c3d4ec65d72957b5d8a647 --- /dev/null +++ b/backend/app/modules/arm_care/schemas.py @@ -0,0 +1,53 @@ +from datetime import date, datetime +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field + +from app.common.schemas import RequestModel, ResponseModel + + +class OutingIn(RequestModel): + pitches: Annotated[int, Field(strict=True, ge=1, le=200)] + local_date: date | None = None + + +class FeelIn(RequestModel): + feel: Literal["sore", "tight", "good"] + + +class OutingOut(ResponseModel): + id: UUID + date: datetime + local_date: date + label: str + pitches: int + rest: str | None = None + rest_days: int | None = None + + +class ArmCareOut(ResponseModel): + outings: list[OutingOut] + feel: str | None + feel_recorded_at: datetime | None + daily_max: int | None = None + innings_last_12_months: int | None = None + innings_limit: int | None = None + rest_status: str = "unknown" + next_eligible_date: date | None = None + rule_version: str | None = None + unavailable_reason: str | None = "Age-specific policy and innings source not configured" + + +class ArmCareEnvelope(ResponseModel): + arm_care: ArmCareOut + + +class OutingResult(ResponseModel): + outing: OutingOut + arm_care: ArmCareOut + + +class FeelOut(ResponseModel): + feel: str + recorded_at: datetime diff --git a/backend/app/modules/arm_care/service.py b/backend/app/modules/arm_care/service.py new file mode 100644 index 0000000000000000000000000000000000000000..f440533df053955e551b0b2893477f09d64f134e --- /dev/null +++ b/backend/app/modules/arm_care/service.py @@ -0,0 +1,68 @@ +"""Arm care (N23-N25). No rest policy is configured, so the assessment is always "unknown".""" + +from datetime import UTC, date, datetime, timedelta + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.common.academy_access import coaches_of_player +from app.common.notify import notify +from app.core.errors import ValidationFailed +from app.integrations.push import PushClient +from app.modules.accounts.models import Account +from app.modules.arm_care.repository import FeelRepository, OutingRepository +from app.modules.arm_care.schemas import ArmCareOut, FeelIn, FeelOut, OutingIn, OutingOut, OutingResult + +DEFAULT_DAYS = 30 +MAX_DAYS = 366 + + +def _outing(o) -> OutingOut: + return OutingOut(id=o.id, date=o.created_at, local_date=o.local_date, label="Game, logged by you", + pitches=o.pitches) + + +class ArmCareService: + def __init__(self, db: AsyncSession, push: PushClient | None = None): + self.db = db + self.push = push + self.outings = OutingRepository(db) + self.feels = FeelRepository(db) + + async def get(self, player: Account, start: date | None = None, end: date | None = None) -> ArmCareOut: + today = datetime.now(UTC).date() + end = end or today + timedelta(days=1) # a player ahead of UTC may already log tomorrow's date + start = start or end - timedelta(days=DEFAULT_DAYS) + if end < start: + raise ValidationFailed(fields={"to": "Must be on or after from."}) + if (end - start).days > MAX_DAYS: + raise ValidationFailed(fields={"to": f"The range can be at most {MAX_DAYS} days."}) + rows = await self.outings.in_range(player.id, start, end) + latest = await self.feels.latest(player.id) + return ArmCareOut(outings=[_outing(o) for o in rows], feel=latest.feel if latest else None, + feel_recorded_at=latest.created_at if latest else None) + + async def add_outing(self, player: Account, body: OutingIn) -> OutingResult: + today = datetime.now(UTC).date() + local_date = body.local_date or today + # Timezones are not modelled yet, so a player up to a day ahead of UTC may be on "tomorrow". + if local_date > today + timedelta(days=1): + raise ValidationFailed(fields={"local_date": "Must not be in the future."}) + if (today - local_date).days > MAX_DAYS: + raise ValidationFailed(fields={"local_date": f"Must be within the last {MAX_DAYS} days."}) + outing = await self.outings.create(owner_id=player.id, local_date=local_date, pitches=body.pitches) + name = player.name or "Your player" + for coach_id in await coaches_of_player(self.db, player): + await notify(self.db, self.push, coach_id, kind="armcare", title=f"{name} logged {body.pitches} pitches", + target={}, event_key=f"outing:{outing.id}") + end = max(local_date, today) + start = max(min(local_date, today - timedelta(days=DEFAULT_DAYS)), end - timedelta(days=MAX_DAYS)) + arm_care = await self.get(player, start, end) + return OutingResult(outing=_outing(outing), arm_care=arm_care) + + async def set_feel(self, player: Account, body: FeelIn) -> FeelOut: + await self.feels.lock_owner(player.id) + latest = await self.feels.latest(player.id) + if latest is not None and latest.feel == body.feel and latest.created_at.date() == datetime.now(UTC).date(): + return FeelOut(feel=latest.feel, recorded_at=latest.created_at) + event = await self.feels.create(owner_id=player.id, feel=body.feel) + return FeelOut(feel=event.feel, recorded_at=event.created_at) diff --git a/backend/app/modules/assignments/__init__.py b/backend/app/modules/assignments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/assignments/controller.py b/backend/app/modules/assignments/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..5591ee7fe527ddc6eed1796fe070b3906f72a729 --- /dev/null +++ b/backend/app/modules/assignments/controller.py @@ -0,0 +1,61 @@ +"""N20-N22: drill assignments and set completion.""" + +from typing import Annotated, Literal +from uuid import UUID + +from fastapi import APIRouter, Depends, Header, Query +from pydantic import BaseModel + +from app.common.academy_access import CurrentStaff +from app.core.dependencies import CurrentAccount, CurrentPlayer, Db, Paging, Storage +from app.integrations.push import PushClient, get_push_client +from app.modules.assignments.schemas import AssignIn, AssignmentEnvelope, AssignmentPage, Mode, SetIn, SetResult +from app.modules.assignments.service import AssignmentService +from app.modules.idempotency.service import run_idempotent + +router = APIRouter(prefix="/v1", tags=["assignments"]) + + +class _Scoped(BaseModel): + """Idempotency payload that also covers the path id, so one key cannot replay across targets.""" + + target: UUID + body: dict + + +@router.get("/drill-assignments", response_model=AssignmentPage) +async def list_assignments( + mode: Annotated[Mode, Query()], account: CurrentAccount, db: Db, storage: Storage, paging: Paging, + player_id: UUID | None = None, status: Literal["open", "completed", "all"] = "all", +) -> AssignmentPage: + return await AssignmentService(db, storage).list(account, mode, player_id, status, paging) + + +@router.post("/coach/players/{player_id}/drill-assignments", status_code=201, response_model=AssignmentEnvelope) +async def assign_drill( + player_id: UUID, body: AssignIn, staff: CurrentStaff, db: Db, storage: Storage, + push: Annotated[PushClient, Depends(get_push_client)], + idempotency_key: Annotated[str | None, Header(max_length=128)] = None, +): + service = AssignmentService(db, storage, push) + + async def handler() -> AssignmentEnvelope: + return AssignmentEnvelope(assignment=await service.assign(staff, player_id, body)) + + scoped = _Scoped(target=player_id, body=body.model_dump(mode="json")) + return await run_idempotent(db, staff.id, idempotency_key, scoped, handler, status_code=201) + + +@router.post("/drill-assignments/{assignment_id}/sets", status_code=201, response_model=SetResult) +async def log_set( + assignment_id: UUID, body: SetIn, player: CurrentPlayer, db: Db, storage: Storage, + idempotency_key: Annotated[str | None, Header(max_length=128)] = None, +): + service = AssignmentService(db, storage) + + async def handler() -> SetResult: + return await service.log_set(player, assignment_id, body) + + return await run_idempotent(db, player.id, idempotency_key, + _Scoped(target=assignment_id, body=body.model_dump(mode="json")), handler, + status_code=201) diff --git a/backend/app/modules/assignments/models.py b/backend/app/modules/assignments/models.py new file mode 100644 index 0000000000000000000000000000000000000000..97c513e5b098b001af2a216efe47dda6b9292df2 --- /dev/null +++ b/backend/app/modules/assignments/models.py @@ -0,0 +1,55 @@ +import uuid +from datetime import date + +from sqlalchemy import CheckConstraint, Date, ForeignKey, Index, SmallInteger, String, UniqueConstraint, text +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column + +from app.common.base_model import Base, CreatedAtMixin, IdMixin + + +class DrillAssignment(IdMixin, CreatedAtMixin, Base): + """A drill a coach prescribed to one player. name/fixes are snapshots; progress is the count of its sets.""" + + __tablename__ = "drill_assignments" + __table_args__ = ( + CheckConstraint("mode IN ('h', 'p')", name="mode"), + CheckConstraint("drill_source IN ('catalog', 'library')", name="drill_source"), + CheckConstraint("sets BETWEEN 1 AND 10", name="sets"), + CheckConstraint("reps BETWEEN 1 AND 8", name="reps"), + Index("ix_drill_assignments_player_id_mode_created_at", "player_id", "mode", text("created_at DESC")), + ) + + team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="SET NULL")) + player_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE")) + assigned_by_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL") + ) + mode: Mapped[str] = mapped_column(String(1)) + drill_source: Mapped[str] = mapped_column(String(8)) + drill_id: Mapped[str] = mapped_column(String(40)) + name: Mapped[str] = mapped_column(String(120)) + fixes: Mapped[str] = mapped_column(String(500), server_default="") + sets: Mapped[int] = mapped_column(SmallInteger, server_default="3") + reps: Mapped[int] = mapped_column(SmallInteger, server_default="8") + due_date: Mapped[date] = mapped_column(Date) + session_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL") + ) + + +class AssignmentSet(IdMixin, CreatedAtMixin, Base): + """One completed set of an assignment; drill_log_id is the practice log written in the same transaction.""" + + __tablename__ = "assignment_sets" + __table_args__ = (UniqueConstraint("assignment_id", "set_number"),) + + assignment_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("drill_assignments.id", ondelete="CASCADE") + ) + set_number: Mapped[int] = mapped_column(SmallInteger) + reps_done: Mapped[int] = mapped_column(SmallInteger) + day: Mapped[date] = mapped_column(Date) + drill_log_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("drill_logs.id", ondelete="SET NULL") + ) diff --git a/backend/app/modules/assignments/repository.py b/backend/app/modules/assignments/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..f99b368722a721477c62edf232cdbfc7c02a983d --- /dev/null +++ b/backend/app/modules/assignments/repository.py @@ -0,0 +1,96 @@ +from datetime import date +from uuid import UUID + +from sqlalchemy import Select, exists, func, select, tuple_ + +from app.common.base_repository import BaseRepository +from app.core.pagination import Cursor +from app.modules.academy.models import LibraryDrill +from app.modules.accounts.models import Account +from app.modules.assignments.models import AssignmentSet, DrillAssignment +from app.modules.drills.models import DrillLog +from app.modules.sessions.models import SwingSession +from app.modules.uploads.models import Upload + + +class AssignmentRepository(BaseRepository[DrillAssignment]): + model = DrillAssignment + + def _done(self): + return (select(AssignmentSet.assignment_id, func.count().label("n")) + .group_by(AssignmentSet.assignment_id).subquery()) + + async def with_progress(self, assignment_id: UUID, *, player_id: UUID | None = None, lock: bool = False): + """(assignment, done, assigned_by name) or None.""" + query = select(DrillAssignment).where(DrillAssignment.id == assignment_id) + if player_id is not None: + query = query.where(DrillAssignment.player_id == player_id) + assignment = await self.session.scalar(query.with_for_update() if lock else query) + return assignment + + async def done_count(self, assignment_id: UUID) -> int: + return await self.session.scalar( + select(func.count()).select_from(AssignmentSet).where(AssignmentSet.assignment_id == assignment_id)) or 0 + + async def names(self, ids: set[UUID | None]) -> dict[UUID, str]: + ids = {i for i in ids if i} + if not ids: + return {} + rows = await self.session.execute(select(Account.id, Account.name).where(Account.id.in_(ids))) + return {i: n for i, n in rows} + + def list_query(self, *, mode: str, status: str, player_ids: Select | None, player_id: UUID | None, + team_id: UUID | None) -> Select: + done = self._done() + count = func.coalesce(done.c.n, 0) + query = (select(DrillAssignment, count).outerjoin(done, done.c.assignment_id == DrillAssignment.id) + .where(DrillAssignment.mode == mode)) + if player_id is not None: + query = query.where(DrillAssignment.player_id == player_id) + if player_ids is not None: + query = query.where(DrillAssignment.player_id.in_(player_ids), DrillAssignment.team_id == team_id) + if status == "open": + query = query.where(count < DrillAssignment.sets) + elif status == "completed": + query = query.where(count >= DrillAssignment.sets) + return query + + async def page(self, query: Select, cursor: Cursor | None, limit: int): + if cursor is not None: + query = query.where(tuple_(DrillAssignment.created_at, DrillAssignment.id) + < tuple_(cursor.created_at, cursor.id)) + query = query.order_by(DrillAssignment.created_at.desc(), DrillAssignment.id.desc()).limit(limit + 1) + return (await self.session.execute(query)).all() + + async def library_drill(self, drill_id: UUID, team_id: UUID | None) -> LibraryDrill | None: + return await self.session.scalar(select(LibraryDrill).where( + LibraryDrill.id == drill_id, LibraryDrill.team_id == team_id)) + + async def library_media_keys(self, drill_ids: set[UUID]) -> dict[UUID, tuple[UUID, str]]: + """library drill id -> (upload id, object key) for drills that still have a video.""" + if not drill_ids: + return {} + rows = await self.session.execute( + select(LibraryDrill.id, Upload.id, Upload.object_key) + .join(Upload, Upload.id == LibraryDrill.upload_id).where(LibraryDrill.id.in_(drill_ids))) + return {drill: (upload, key) for drill, upload, key in rows} + + async def owns_session(self, player_id: UUID, session_id: UUID) -> bool: + return bool(await self.session.scalar(select(exists().where( + SwingSession.id == session_id, SwingSession.owner_id == player_id, SwingSession.deleted_at.is_(None))))) + + async def existing_set(self, assignment_id: UUID, set_number: int) -> AssignmentSet | None: + return await self.session.scalar(select(AssignmentSet).where( + AssignmentSet.assignment_id == assignment_id, AssignmentSet.set_number == set_number)) + + async def add_set(self, assignment: DrillAssignment, set_number: int, reps_done: int, day: date) -> AssignmentSet: + log = DrillLog(owner_id=assignment.player_id, session_id=assignment.session_id, drill_id=assignment.drill_id, + assignment_id=assignment.id, reps=reps_done, day=day) + self.session.add(log) + await self.session.flush() + row = AssignmentSet(assignment_id=assignment.id, set_number=set_number, reps_done=reps_done, day=day, + drill_log_id=log.id) + self.session.add(row) + await self.session.flush() + await self.session.refresh(row) + return row diff --git a/backend/app/modules/assignments/schemas.py b/backend/app/modules/assignments/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..c576b89a53707e442995cd619ea122e9b67dbbc4 --- /dev/null +++ b/backend/app/modules/assignments/schemas.py @@ -0,0 +1,62 @@ +from datetime import date, datetime +from typing import Literal +from uuid import UUID + +from pydantic import Field + +from app.common.schemas import MediaRef, Page, RequestModel, ResponseModel + +Mode = Literal["h", "p"] + + +class AssignIn(RequestModel): + mode: Mode + drill_source: Literal["catalog", "library"] + drill_id: str = Field(min_length=1, max_length=40) + due_date: date + source_session_id: UUID | None = None + + +class SetIn(RequestModel): + set_number: int = Field(ge=1) + reps_done: int = Field(ge=1) + day: date + + +class AssignmentOut(ResponseModel): + id: UUID + player_id: UUID + mode: str + drill_id: str + drill_source: str + name: str + fixes: str + sets: int + reps: int + due: str + due_date: date + assigned_by: str | None + assigned_by_id: UUID | None + done: int + session_id: UUID | None + assigned_at: datetime + media: MediaRef | None + + +class AssignmentEnvelope(ResponseModel): + assignment: AssignmentOut + + +class SetLogOut(ResponseModel): + id: UUID + set_number: int + reps_done: int + day: date + + +class SetResult(ResponseModel): + assignment: AssignmentOut + set_log: SetLogOut + + +AssignmentPage = Page[AssignmentOut] diff --git a/backend/app/modules/assignments/service.py b/backend/app/modules/assignments/service.py new file mode 100644 index 0000000000000000000000000000000000000000..1c8ec4b9ccb96cea99fc07845c074320ffbc16ed --- /dev/null +++ b/backend/app/modules/assignments/service.py @@ -0,0 +1,151 @@ +"""Drill assignments (N20-N22). Progress is the number of AssignmentSet rows; each set also writes one drill log.""" + +from datetime import UTC, date, datetime, timedelta +from functools import cache +from uuid import UUID + +from ai_coach.knowledge import all_drills +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.notify import notify +from app.common.schemas import MediaRef +from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed +from app.core.pagination import PageParams, encode_cursor +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 + +DISCIPLINES = {"h": "hitting", "p": "pitching"} + + +@cache +def _catalog() -> dict[str, dict]: + return {d["id"]: d for d in all_drills()} + + +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 = MediaRef(upload_id=upload_id, url=self.storage.presign_get(key), + expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl)) + 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 = rows[:paging.limit] + items = await self._outs([(a, n) for a, n in page]) + cursor = encode_cursor(page[-1][0].created_at, page[-1][0].id) if len(rows) > paging.limit else None + 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 = _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)) diff --git a/backend/app/modules/coach/controller.py b/backend/app/modules/coach/controller.py index c6520d4bd6680aa3d61ac969cfc1865434c18b70..d860637f07f22b503c8ad5d8e60a8024ab440f43 100644 --- a/backend/app/modules/coach/controller.py +++ b/backend/app/modules/coach/controller.py @@ -6,8 +6,9 @@ from uuid import UUID from fastapi import APIRouter, Depends, Query +from app.common.academy_access import CurrentStaff from app.common.schemas import Items, Page -from app.core.dependencies import CurrentCoach, Db, Paging, Storage +from app.core.dependencies import Db, Paging, Storage from app.modules.coach.schemas import Mode, QueueResponse, RosterItem from app.modules.coach.service import CoachService from app.modules.sessions.summary import SessionSummary @@ -23,17 +24,20 @@ Service = Annotated[CoachService, Depends(get_coach_service)] @router.get("/coach/roster", response_model=Items[RosterItem]) -async def roster(coach: CurrentCoach, service: Service) -> Items[RosterItem]: - return Items[RosterItem](items=await service.roster(coach)) +async def roster(staff: CurrentStaff, service: Service, group_id: UUID | None = None) -> Items[RosterItem]: + items = await service.roster(staff) + if group_id is not None: + items = [i for i in items if group_id in i.group_ids] + return Items[RosterItem](items=items) @router.get("/coach/players/{player_id}/sessions", response_model=Page[SessionSummary]) -async def player_sessions(player_id: UUID, coach: CurrentCoach, service: Service, paging: Paging, +async def player_sessions(player_id: UUID, staff: CurrentStaff, service: Service, paging: Paging, mode: Mode | None = None) -> Page[SessionSummary]: - return await service.player_sessions(coach, player_id, mode, paging) + return await service.player_sessions(staff, player_id, mode, paging) @router.get("/coach/queue", response_model=QueueResponse) -async def queue(coach: CurrentCoach, service: Service, +async def queue(staff: CurrentStaff, service: Service, since: Annotated[datetime | None, Query()] = None) -> QueueResponse: - return await service.queue(coach, since) + return await service.queue(staff, since) diff --git a/backend/app/modules/coach/repository.py b/backend/app/modules/coach/repository.py index 63a4086850d495b209c197bbda567d2375cdba01..9153c0ca58169489fabbfe9f6fbc726b8129d6bf 100644 --- a/backend/app/modules/coach/repository.py +++ b/backend/app/modules/coach/repository.py @@ -8,11 +8,12 @@ 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.teams.models import Team +from app.modules.settings.models import UserSettings RECENT_PER_MODE = 3 @@ -20,16 +21,24 @@ RECENT_PER_MODE = 3 class CoachRepository(BaseRepository[Account]): model = Account - async def team_id_of(self, coach_id: UUID) -> UUID | None: - return await self.session.scalar(select(Team.id).where(Team.coach_id == coach_id)) - - async def players(self, team_id: UUID) -> Sequence[Account]: - query = (select(Account).where(Account.team_id == team_id, Account.role == "player") - .order_by(Account.name, Account.created_at)) + 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 player_on_team(self, player_id: UUID, team_id: UUID) -> bool: - return await self.exists_by(id=player_id, team_id=team_id, role="player") + 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).""" diff --git a/backend/app/modules/coach/schemas.py b/backend/app/modules/coach/schemas.py index 311d6ed7a76ed8d565b875bc782a134dca1e97b2..01287bd4b6f1838af6b24e049ccc5b882d5be389 100644 --- a/backend/app/modules/coach/schemas.py +++ b/backend/app/modules/coach/schemas.py @@ -34,6 +34,7 @@ class RosterItem(ResponseModel): email: str focus: str level: str | None + group_ids: list[UUID] = [] pending_count: int last: LastByMode recent: RecentByMode diff --git a/backend/app/modules/coach/service.py b/backend/app/modules/coach/service.py index 86fd0906c7f78f25f97f4910b0d7d10f1e0a0259..cba549d72d3419bb82a7f2a67cc447338a1e3bae 100644 --- a/backend/app/modules/coach/service.py +++ b/backend/app/modules/coach/service.py @@ -5,8 +5,9 @@ from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession +from app.common.academy_access import Staff, require_player, sessions_shared, visible_players_query from app.common.schemas import Page -from app.core.errors import NotFound +from app.core.errors import Forbidden from app.core.pagination import PageParams, encode_cursor from app.integrations.storage import StorageClient from app.modules.accounts.models import Account @@ -30,18 +31,21 @@ class CoachService: self.storage = storage self.repo = CoachRepository(db) - async def _players(self, coach: Account) -> list[Account]: - team_id = await self.repo.team_id_of(coach.id) - return list(await self.repo.players(team_id)) if team_id else [] + async def _players(self, staff: Staff) -> list[Account]: + return list(await self.repo.visible_players(visible_players_query(staff))) - async def roster(self, coach: Account) -> list[RosterItem]: - players = await self._players(coach) + async def roster(self, staff: Staff) -> list[RosterItem]: + players = await self._players(staff) if not players: return [] - ids = [p.id for p in players] - pending = await self.repo.pending_counts(ids) + all_ids = [p.id for p in players] + hidden = await self.repo.sessions_hidden(all_ids) + ids = [i for i in all_ids if i not in hidden] + groups = await self.repo.group_ids(all_ids) + pending = await self.repo.pending_counts(ids) if ids else {} by_key: dict[tuple[UUID, str], list] = {} - for row in await self.repo.recent_sessions(ids): # ordered newest first within each (owner, mode) + recent_rows = await self.repo.recent_sessions(ids) if ids else [] + for row in recent_rows: # ordered newest first within each (owner, mode) by_key.setdefault((row.owner_id, row.mode), []).append(row) items = [] @@ -59,14 +63,15 @@ class CoachService: delta=delta, created_at=newest.created_at, focus_name=newest.focus)) setattr(recent, mode, [r.overall_score for r in rows[:3] if r.overall_score is not None]) items.append(RosterItem(id=p.id, name=p.name, email=p.email, focus=p.focus, level=p.level, + group_ids=groups.get(p.id, []), pending_count=pending.get(p.id, 0), last=last, recent=recent)) return items - async def player_sessions(self, coach: Account, player_id: UUID, mode: str | None, + async def player_sessions(self, staff: Staff, player_id: UUID, mode: str | None, paging: PageParams) -> Page[SessionSummary]: - team_id = await self.repo.team_id_of(coach.id) - if team_id is None or not await self.repo.player_on_team(player_id, team_id): - raise NotFound("Player not on your team.", code="PLAYER_NOT_ON_TEAM") + await require_player(self.db, staff, player_id) + if not await sessions_shared(self.db, player_id): + raise Forbidden("This player does not share sessions with coaches.", code="SESSIONS_PRIVATE") query = player_sessions_query(player_id, mode, paging.cursor, paging.limit + 1) items = await load_summaries(self.db, self.storage, query) next_cursor = None @@ -75,11 +80,12 @@ class CoachService: next_cursor = encode_cursor(items[-1].created_at, items[-1].id) return Page[SessionSummary](items=items, next_cursor=next_cursor) - async def queue(self, coach: Account, since: datetime | None) -> QueueResponse: - players = await self._players(coach) - if not players: + async def queue(self, staff: Staff, since: datetime | None) -> QueueResponse: + players = await self._players(staff) + hidden = await self.repo.sessions_hidden([p.id for p in players]) + names = {p.id: p.name for p in players if p.id not in hidden} + if not names: return QueueResponse(open=[], reviewed_today=[]) - names = {p.id: p.name for p in players} ids = list(names) if since is None: since = start_of_today_utc() diff --git a/backend/app/modules/drills/models.py b/backend/app/modules/drills/models.py index 5e811265b5636b0ec558bf87aa57310971bff389..10f12718d60d37e69d1cc32486cc4170b595eeb2 100644 --- a/backend/app/modules/drills/models.py +++ b/backend/app/modules/drills/models.py @@ -21,6 +21,9 @@ class DrillLog(IdMixin, CreatedAtMixin, Base): session_id: Mapped[uuid.UUID | None] = mapped_column( UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL") ) - drill_id: Mapped[str] = mapped_column(String(16)) + drill_id: Mapped[str] = mapped_column(String(40)) + assignment_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("drill_assignments.id", ondelete="SET NULL") + ) reps: Mapped[int] = mapped_column(SmallInteger) day: Mapped[date] = mapped_column(Date) diff --git a/backend/app/modules/drills/schemas.py b/backend/app/modules/drills/schemas.py index fc6af280b75c8580fa70f7411c08f53d2eba179c..2e5d4db83ccc7c6478f88083c16d7dc1eb767dd0 100644 --- a/backend/app/modules/drills/schemas.py +++ b/backend/app/modules/drills/schemas.py @@ -17,6 +17,7 @@ class DrillLogOut(ResponseModel): id: UUID session_id: UUID | None drill_id: str + assignment_id: UUID | None reps: int day: date created_at: datetime diff --git a/backend/app/modules/goals/__init__.py b/backend/app/modules/goals/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/goals/controller.py b/backend/app/modules/goals/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c79b4fab23e038129a36cd6aeaf579620145a2 --- /dev/null +++ b/backend/app/modules/goals/controller.py @@ -0,0 +1,39 @@ +"""N16-N19: goals and milestones.""" + +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, Query + +from app.common.academy_access import CurrentStaff +from app.common.schemas import Page +from app.core.dependencies import CurrentAccount, CurrentPlayer, Db, Paging +from app.integrations.push import PushClient, get_push_client +from app.modules.goals.schemas import GoalEnvelope, GoalHistoryOut, GoalIn, MilestoneOut, Mode +from app.modules.goals.service import GoalService + +router = APIRouter(prefix="/v1", tags=["goals"]) + +ModeQuery = Annotated[Mode, Query()] + + +@router.get("/players/{player_id}/goals", response_model=GoalEnvelope) +async def get_goal(player_id: UUID, mode: ModeQuery, account: CurrentAccount, db: Db) -> GoalEnvelope: + return await GoalService(db).current(account, player_id, mode) + + +@router.put("/players/{player_id}/goals/{mode}", response_model=GoalEnvelope) +async def put_goal(player_id: UUID, mode: Mode, body: GoalIn, staff: CurrentStaff, db: Db, + push: Annotated[PushClient, Depends(get_push_client)]) -> GoalEnvelope: + return await GoalService(db, push).set(staff, player_id, mode, body) + + +@router.get("/players/{player_id}/goals/history", response_model=Page[GoalHistoryOut]) +async def goal_history(player_id: UUID, mode: ModeQuery, account: CurrentAccount, db: Db, + paging: Paging) -> Page[GoalHistoryOut]: + return await GoalService(db).history(account, player_id, mode, paging) + + +@router.get("/me/milestones", response_model=Page[MilestoneOut]) +async def milestones(mode: ModeQuery, player: CurrentPlayer, db: Db, paging: Paging) -> Page[MilestoneOut]: + return await GoalService(db).milestones(player, mode, paging) diff --git a/backend/app/modules/goals/models.py b/backend/app/modules/goals/models.py new file mode 100644 index 0000000000000000000000000000000000000000..3d59c3b704433f14b65558d6197dbfc511f58ffe --- /dev/null +++ b/backend/app/modules/goals/models.py @@ -0,0 +1,46 @@ +import uuid +from datetime import datetime +from decimal import Decimal + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, Numeric, SmallInteger, String, text +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column + +from app.common.base_model import Base, CreatedAtMixin, IdMixin + + +class Goal(IdMixin, CreatedAtMixin, Base): + """A coach-set goal. The active goal per (player, mode) has ended_at NULL; replaced goals are the history. + + created_at is set_at. outcome: met | not_met | superseded | unknown (NULL while active). + """ + + __tablename__ = "goals" + __table_args__ = ( + CheckConstraint("mode IN ('h', 'p')", name="mode"), + CheckConstraint("type IN ('groups', 'param', 'score')", name="type"), + CheckConstraint("outcome IS NULL OR outcome IN ('met', 'not_met', 'superseded', 'unknown')", name="outcome"), + Index("uq_goals_active", "player_id", "mode", unique=True, postgresql_where=text("ended_at IS NULL")), + Index("ix_goals_player_id_mode_created_at", "player_id", "mode", text("created_at DESC")), + ) + + player_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE")) + team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="SET NULL")) + mode: Mapped[str] = mapped_column(String(1)) + type: Mapped[str] = mapped_column(String(8)) + target: Mapped[Decimal] = mapped_column(Numeric(8, 2)) + metric_id: Mapped[str | None] = mapped_column(String(64)) + due: Mapped[str] = mapped_column(String(16)) + due_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) + weekly_practice_days: Mapped[int] = mapped_column(SmallInteger) + weekly_drill_sets: Mapped[int] = mapped_column(SmallInteger) + note: Mapped[str] = mapped_column(String(160), server_default="") + set_by_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL") + ) + ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + outcome: Mapped[str | None] = mapped_column(String(10)) + evaluated_session_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL") + ) + version: Mapped[int] = mapped_column(Integer, server_default="1") diff --git a/backend/app/modules/goals/repository.py b/backend/app/modules/goals/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..93ffb0831c816a5756cee34e3c76746fcbeb3d92 --- /dev/null +++ b/backend/app/modules/goals/repository.py @@ -0,0 +1,42 @@ +from datetime import datetime +from uuid import UUID + +from sqlalchemy import Select, select, tuple_ + +from app.common.base_repository import BaseRepository +from app.core.pagination import Cursor +from app.modules.accounts.models import Account +from app.modules.goals.models import Goal + + +class GoalRepository(BaseRepository[Goal]): + model = Goal + + async def active(self, player_id: UUID, mode: str, *, lock: bool = False, + team_id: UUID | None = None) -> Goal | None: + query = select(Goal).where(Goal.player_id == player_id, Goal.mode == mode, Goal.ended_at.is_(None)) + if team_id is not None: + query = query.where(Goal.team_id == team_id) + return await self.session.scalar(query.with_for_update() if lock else query) + + async def author_name(self, account_id: UUID | None) -> str | None: + return await self.session.scalar(select(Account.name).where(Account.id == account_id)) if account_id else None + + def _page(self, query: Select, cursor: Cursor | None, limit: int) -> Select: + if cursor is not None: + query = query.where(tuple_(Goal.created_at, Goal.id) < tuple_(cursor.created_at, cursor.id)) + return query.order_by(Goal.created_at.desc(), Goal.id.desc()).limit(limit + 1) + + async def ended(self, player_id: UUID, mode: str, cursor: Cursor | None, limit: int, *, met_only: bool = False, + team_id: UUID | None = None): + query = select(Goal).where(Goal.player_id == player_id, Goal.mode == mode, Goal.ended_at.is_not(None)) + if team_id is not None: + query = query.where(Goal.team_id == team_id) + if met_only: + query = query.where(Goal.outcome == "met") + return (await self.session.scalars(self._page(query, cursor, limit))).all() + + async def end(self, goal: Goal, now: datetime) -> None: + goal.ended_at = now + goal.outcome = "superseded" + await self.session.flush() diff --git a/backend/app/modules/goals/schemas.py b/backend/app/modules/goals/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..3bf671c8d5dc35971baccf01b2d3e8ac8153a9db --- /dev/null +++ b/backend/app/modules/goals/schemas.py @@ -0,0 +1,81 @@ +from datetime import datetime +from math import isfinite +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field, StrictFloat, StrictInt, field_validator + +from app.common.schemas import RequestModel, ResponseModel + +Mode = Literal["h", "p"] +Due = Literal["1 week", "2 weeks", "End of month"] + + +class WeeklyIn(RequestModel): + practice_days: Annotated[int, Field(strict=True, ge=1, le=7)] + drill_sets: Annotated[int, Field(strict=True, ge=1, le=30)] + + +class GoalIn(RequestModel): + type: Literal["groups", "param", "score"] + target: StrictInt | StrictFloat + metric_id: str | None = Field(None, max_length=64) + due: Due + weekly: WeeklyIn + note: str = Field("", max_length=160) + expected_version: int | None = Field(None, ge=0) + + @field_validator("target") + @classmethod + def _finite(cls, value: int | float) -> int | float: + if not isfinite(value): + raise ValueError("Must be a finite number.") + return value + + +class WeeklyOut(ResponseModel): + practice_days: int + drill_sets: int + + +class GoalOut(ResponseModel): + id: UUID + player_id: UUID + mode: str + type: str + target: int | float + metric_id: str | None + metric_name: str | None + due: str + due_at: datetime + set_at: datetime + set_by: str | None + set_by_id: UUID | None + note: str + weekly: WeeklyOut + version: int + + +class GoalEnvelope(ResponseModel): + goal: GoalOut | None + + +class GoalHistoryOut(ResponseModel): + id: UUID + text: str + range: str + met: bool | None + outcome: str | None + start_at: datetime + end_at: datetime | None + evaluated_session_id: UUID | None + + +class MilestoneOut(ResponseModel): + id: UUID + icon: str + tone: str + title: str + when: str + occurred_at: datetime + source_goal_id: UUID diff --git a/backend/app/modules/goals/service.py b/backend/app/modules/goals/service.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ca003c6abc2b06a83389fbdb7caf33e081fd2b --- /dev/null +++ b/backend/app/modules/goals/service.py @@ -0,0 +1,188 @@ +"""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, encode_cursor +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} + + +@cache +def _metrics() -> dict[str, dict]: + return {m["metric_id"]: m for m in registry.metrics()} + + +@cache +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)) + + @staticmethod + 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 = 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] + more = len(rows) > paging.limit + return Page[GoalHistoryOut](items=items, next_cursor=encode_cursor(page[-1].created_at, page[-1].id) + if more else None) + + 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 = 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] + more = len(rows) > paging.limit + return Page[MilestoneOut](items=items, next_cursor=encode_cursor(page[-1].created_at, page[-1].id) + if more else None) diff --git a/backend/app/modules/notifications/__init__.py b/backend/app/modules/notifications/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/notifications/controller.py b/backend/app/modules/notifications/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..8dc902e56be66775078a6bde79d859c73ea68dfe --- /dev/null +++ b/backend/app/modules/notifications/controller.py @@ -0,0 +1,34 @@ +"""N06 to N09: /notifications.""" + +from uuid import UUID + +from fastapi import APIRouter, Response + +from app.common.schemas import Page +from app.core.dependencies import CurrentAccount, Db, Paging +from app.modules.notifications.schemas import NotificationOut, ReadAllIn, UnreadCount +from app.modules.notifications.service import NotificationService + +router = APIRouter(prefix="/v1", tags=["notifications"]) + + +@router.get("/notifications", response_model=Page[NotificationOut]) +async def list_notifications(account: CurrentAccount, db: Db, paging: Paging) -> Page[NotificationOut]: + return await NotificationService(db).list(account, paging) + + +@router.get("/notifications/unread-count", response_model=UnreadCount) +async def unread_count(account: CurrentAccount, db: Db) -> UnreadCount: + return await NotificationService(db).unread_count(account) + + +@router.post("/notifications/read-all", status_code=204) +async def read_all(account: CurrentAccount, db: Db, body: ReadAllIn | None = None) -> Response: + await NotificationService(db).mark_all_read(account, body.through if body else None) + return Response(status_code=204) + + +@router.post("/notifications/{notification_id}/read", status_code=204) +async def read_one(notification_id: UUID, account: CurrentAccount, db: Db) -> Response: + await NotificationService(db).mark_read(account, notification_id) + return Response(status_code=204) diff --git a/backend/app/modules/notifications/models.py b/backend/app/modules/notifications/models.py new file mode 100644 index 0000000000000000000000000000000000000000..fb54dfbfe08e9c7663002ccb73218621799a5ded --- /dev/null +++ b/backend/app/modules/notifications/models.py @@ -0,0 +1,32 @@ +import uuid +from datetime import datetime + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, String, UniqueConstraint, text +from sqlalchemy.dialects.postgresql import JSONB, UUID +from sqlalchemy.orm import Mapped, mapped_column + +from app.common.base_model import Base, CreatedAtMixin, IdMixin + +KINDS = ("review", "drill", "armcare", "result", "report") + + +class Notification(IdMixin, CreatedAtMixin, Base): + """One in-app inbox item. event_key deduplicates retries of the same domain event per recipient.""" + + __tablename__ = "notifications" + __table_args__ = ( + CheckConstraint(f"kind IN ({', '.join(repr(k) for k in KINDS)})", name="kind"), + UniqueConstraint("recipient_id", "event_key"), + Index("ix_notifications_recipient_id_created_at", "recipient_id", text("created_at DESC"), "id"), + Index("ix_notifications_unread", "recipient_id", postgresql_where=text("read_at IS NULL")), + ) + + recipient_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE") + ) + kind: Mapped[str] = mapped_column(String(10)) + title: Mapped[str] = mapped_column(String(120)) + body: Mapped[str] = mapped_column(String(300), server_default="") + target: Mapped[dict] = mapped_column(JSONB, server_default=text("'{}'::jsonb")) + event_key: Mapped[str] = mapped_column(String(160)) + read_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/backend/app/modules/notifications/repository.py b/backend/app/modules/notifications/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..5e2cf284a2a6b727ccc0c2565a417308e9af2650 --- /dev/null +++ b/backend/app/modules/notifications/repository.py @@ -0,0 +1,38 @@ +from datetime import datetime +from uuid import UUID + +from sqlalchemy import func, select, tuple_, update + +from app.common.base_repository import BaseRepository +from app.core.pagination import Cursor +from app.modules.notifications.models import Notification + + +class NotificationRepository(BaseRepository[Notification]): + model = Notification + + async def page(self, recipient_id: UUID, cursor: Cursor | None, limit: int) -> list[Notification]: + query = select(Notification).where(Notification.recipient_id == recipient_id) + if cursor: + query = query.where(tuple_(Notification.created_at, Notification.id) < (cursor.created_at, cursor.id)) + result = await self.session.scalars( + query.order_by(Notification.created_at.desc(), Notification.id.desc()).limit(limit)) + return list(result.all()) + + async def unread_count(self, recipient_id: UUID) -> int: + return await self.session.scalar(select(func.count()).select_from(Notification).where( + Notification.recipient_id == recipient_id, Notification.read_at.is_(None))) or 0 + + async def mark_read(self, recipient_id: UUID, id_: UUID, now: datetime) -> bool: + """False when the notification does not exist or belongs to someone else.""" + row = await self.first_by(id=id_, recipient_id=recipient_id) + if row is None: + return False + if row.read_at is None: + await self.update(row, read_at=now) + return True + + async def mark_read_through(self, recipient_id: UUID, through: datetime, now: datetime) -> None: + await self.session.execute(update(Notification).where( + Notification.recipient_id == recipient_id, Notification.read_at.is_(None), + Notification.created_at <= through).values(read_at=now)) diff --git a/backend/app/modules/notifications/schemas.py b/backend/app/modules/notifications/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..dcddb1a046b00fd6d729e20ccc59271f5b298620 --- /dev/null +++ b/backend/app/modules/notifications/schemas.py @@ -0,0 +1,26 @@ +"""N06 to N09 bodies.""" + +from datetime import datetime +from uuid import UUID + +from pydantic import Field + +from app.common.schemas import RequestModel, ResponseModel + + +class NotificationOut(ResponseModel): + id: UUID + kind: str + title: str + body: str + at: datetime + read: bool + target: dict[str, str] + + +class UnreadCount(ResponseModel): + count: int = Field(ge=0) + + +class ReadAllIn(RequestModel): + through: datetime | None = None diff --git a/backend/app/modules/notifications/service.py b/backend/app/modules/notifications/service.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3ab248dc0f65eda13aa33404a666c1e2b8c230 --- /dev/null +++ b/backend/app/modules/notifications/service.py @@ -0,0 +1,39 @@ +"""N06 to N09: the in-app inbox. Listing never marks anything read.""" + +from datetime import UTC, datetime +from uuid import UUID + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.common.schemas import Page +from app.core.errors import NotFound +from app.core.pagination import PageParams, encode_cursor +from app.modules.accounts.models import Account +from app.modules.notifications.repository import NotificationRepository +from app.modules.notifications.schemas import NotificationOut, UnreadCount + + +class NotificationService: + def __init__(self, db: AsyncSession): + self.notifications = NotificationRepository(db) + + async def list(self, account: Account, paging: PageParams) -> Page[NotificationOut]: + rows = await self.notifications.page(account.id, paging.cursor, paging.limit + 1) + next_cursor = encode_cursor(rows[paging.limit - 1].created_at, rows[paging.limit - 1].id) \ + if len(rows) > paging.limit else None + items = [NotificationOut(id=r.id, kind=r.kind, title=r.title, body=r.body, at=r.created_at, + read=r.read_at is not None, target=r.target) for r in rows[:paging.limit]] + return Page[NotificationOut](items=items, next_cursor=next_cursor) + + async def unread_count(self, account: Account) -> UnreadCount: + return UnreadCount(count=await self.notifications.unread_count(account.id)) + + async def mark_read(self, account: Account, notification_id: UUID) -> None: + if not await self.notifications.mark_read(account.id, notification_id, datetime.now(UTC)): + raise NotFound() + + async def mark_all_read(self, account: Account, through: datetime | None) -> None: + now = datetime.now(UTC) + if through is not None and through.tzinfo is None: + through = through.replace(tzinfo=UTC) + await self.notifications.mark_read_through(account.id, min(through, now) if through else now, now) diff --git a/backend/app/modules/reporting/__init__.py b/backend/app/modules/reporting/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/reporting/controller.py b/backend/app/modules/reporting/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..4742c6c85cc9dc893d38a497de14b3f73a73381a --- /dev/null +++ b/backend/app/modules/reporting/controller.py @@ -0,0 +1,61 @@ +"""N37-N39 academy reporting and N49-N50 consent records.""" + +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, Header, Query +from fastapi.responses import JSONResponse + +from app.common.academy_access import CurrentAdmin +from app.core.dependencies import Db, Paging, Storage +from app.modules.idempotency.service import run_idempotent +from app.modules.reporting.schemas import ( + ConsentExportRequest, + ConsentPage, + CorporateResponse, + DashboardResponse, + EarningsResponse, + ExportResponse, +) +from app.modules.reporting.service import ReportingService + +router = APIRouter(prefix="/v1/academy", tags=["reporting"]) + + +def get_reporting_service(db: Db, storage: Storage) -> ReportingService: + return ReportingService(db, storage) + + +Service = Annotated[ReportingService, Depends(get_reporting_service)] +Month = Annotated[str | None, Query()] + + +@router.get("/dashboard", response_model=DashboardResponse) +async def dashboard(staff: CurrentAdmin, service: Service, month: Month = None) -> DashboardResponse: + return await service.dashboard(staff, month) + + +@router.get("/earnings", response_model=EarningsResponse) +async def earnings(staff: CurrentAdmin, service: Service, month: Month = None) -> EarningsResponse: + return await service.earnings(staff, month) + + +@router.get("/corp", response_model=CorporateResponse) +async def corporate(staff: CurrentAdmin, service: Service, month: Month = None) -> CorporateResponse: + await service.corporate(staff) + raise AssertionError("unreachable") + + +@router.get("/consent", response_model=ConsentPage) +async def consent(staff: CurrentAdmin, service: Service, paging: Paging, + group_id: UUID | None = None) -> ConsentPage: + return await service.consent(staff, group_id, paging.limit, paging.cursor) + + +@router.post("/consent/export", response_model=ExportResponse, status_code=201) +async def export_consent( + body: ConsentExportRequest, staff: CurrentAdmin, service: Service, db: Db, + idempotency_key: Annotated[str | None, Header(max_length=128)] = None, +) -> JSONResponse: + return await run_idempotent(db, staff.id, idempotency_key, body, lambda: service.export_consent(staff, body), + status_code=201) diff --git a/backend/app/modules/reporting/repository.py b/backend/app/modules/reporting/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..29b6876fd1ecec976884b0ee5c71fb328f58db34 --- /dev/null +++ b/backend/app/modules/reporting/repository.py @@ -0,0 +1,159 @@ +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 + diff --git a/backend/app/modules/reporting/schemas.py b/backend/app/modules/reporting/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..ffce76e6769edd0c86da783aa66e9e4425dba125 --- /dev/null +++ b/backend/app/modules/reporting/schemas.py @@ -0,0 +1,140 @@ +from datetime import datetime +from typing import Literal +from uuid import UUID + +from app.common.schemas import Page, RequestModel, ResponseModel + + +class Cards(ResponseModel): + g: int + y: int + r: int + + +class CoachActivity(ResponseModel): + id: UUID + name: str + coaches: str + reviews: int + + +class EarningsBar(ResponseModel): + month: str + amount_minor: int + + +class Dashboard(ResponseModel): + month: str + currency: str | None = None + earnings_minor: int | None = None + paying_players: int | None = None + per_player_minor: int | None = None + active_players: int + new_this_month: int + improving_pct: int | None + analyses_this_week: int + avg_review_hours: float | None + cards: Cards + coaches: list[CoachActivity] + pending_requests: int + not_filmed_7d: int + earnings_bars: list[EarningsBar] = [] + unavailable_reason: str | None = None + as_of: datetime + + +class DashboardResponse(ResponseModel): + dashboard: Dashboard + + +class Payout(ResponseModel): + id: UUID + scheduled_for: str + amount_minor: int | None + status: Literal["scheduled", "paid", "failed", "cancelled"] + paid_at: datetime | None + + +class Earnings(ResponseModel): + month: str + currency: str | None = None + month_minor: int | None = None + players: int | None = None + per_player_minor: int | None = None + ytd_minor: int | None = None + projected_minor: int | None = None + as_of: datetime + payouts: list[Payout] = [] + next_cursor: str | None = None + unavailable_reason: str | None = None + + +class EarningsResponse(ResponseModel): + earnings: Earnings + + +class CorpKpis(ResponseModel): + locations_live: int + active_players: int + analyses: int + improving_pct: int | None + + +class CorpLocation(ResponseModel): + id: UUID + name: str + active_players: int + improving_pct: int | None + + +class CorpFix(ResponseModel): + metric_id: str + label: str + mode: Literal["h", "p"] + affected_pct: int | None + + +class Corporate(ResponseModel): + month: str + as_of: datetime + kpis: CorpKpis + locations: list[CorpLocation] + fixes: list[CorpFix] + + +class CorporateResponse(ResponseModel): + corporate: Corporate + + +class ConsentItem(ResponseModel): + player_id: UUID + name: str + group: str + group_ids: list[UUID] + note: str + version: str | None + accepted_at: datetime | None + withdrawn_at: datetime | None + help_improve_ai: bool + + +class ConsentPage(Page[ConsentItem]): + accepted: int + ai_opt_in: int + + +class ConsentExportRequest(RequestModel): + format: Literal["csv"] = "csv" + group_id: UUID | None = None + + +class ExportOut(ResponseModel): + id: UUID + status: str + url: str + expires_at: datetime + filename: str + + +class ExportResponse(ResponseModel): + export: ExportOut diff --git a/backend/app/modules/reporting/service.py b/backend/app/modules/reporting/service.py new file mode 100644 index 0000000000000000000000000000000000000000..cadf54a771ce8d588890cbd1d3cff8f2f35a6fc2 --- /dev/null +++ b/backend/app/modules/reporting/service.py @@ -0,0 +1,181 @@ +"""Academy reporting: dashboard (N37), earnings (N38), corporate (N39) and consent records (N49-N50). + +Metric definitions (an academy is a team; players are accounts with role=player on it; all windows are UTC): +- active_players: distinct team players with >=1 analysed, non-deleted session whose analyzed_at is in the month. +- new_this_month: players whose account created_at is in the month (players have no join timestamp yet). +- improving_pct: among players with >=2 scored sessions analysed in the month, the share whose latest score is + above their earliest, rounded to a whole percent; null when no player has >=2. +- analyses_this_week: analysed, non-deleted sessions with analyzed_at in the last 7 days (not month-bound). +- avg_review_hours: mean of (review.updated_at - session.created_at) in hours for reviews updated in the month; + null when there are none. A re-sent review overwrites the row, so this is the latest send, not the first. +- cards: latest scored session per player up to the end of the month; the swing report carries no band field, + so thresholds apply to overall_score: g >= 80, y 60-79, r < 60. Unscored players are excluded. +- coaches: the owner plus active members; reviews = reviews updated in the month on team players' sessions. +- not_filmed_7d: team players with no non-deleted session created in the last 7 days (never-filmed included). +- Money has no ledger: every amount is null/empty with unavailable_reason. Players' coach_can_see_sessions does not + limit these academy-level aggregates. +""" + +import csv +import io +import re +import uuid +from datetime import UTC, datetime, timedelta + +import httpx +from sqlalchemy.ext.asyncio import AsyncSession + +from app.common.academy_access import Staff +from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed +from app.core.pagination import Cursor, encode_cursor +from app.integrations.storage import StorageClient +from app.modules.reporting.repository import ReportingRepository +from app.modules.reporting.schemas import ( + Cards, + CoachActivity, + ConsentExportRequest, + ConsentItem, + ConsentPage, + Dashboard, + DashboardResponse, + Earnings, + EarningsResponse, + ExportOut, + ExportResponse, +) + +REVENUE_UNAVAILABLE = "Revenue ledger not configured" +EXPORT_MAX_ROWS = 5000 +_MONTH = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$") +_FOCUS = {"h": "Hitting", "p": "Pitching", "both": "Both"} +_FORMULA_PREFIX = ("=", "+", "-", "@", "\t", "\r") + + +def month_bounds(month: str | None) -> tuple[str, datetime, datetime]: + if month is None: + now = datetime.now(UTC) + year, mon = now.year, now.month + else: + match = _MONTH.match(month) + if match is None: + raise ValidationFailed(fields={"month": "Use YYYY-MM."}) + year, mon = int(match[1]), int(match[2]) + start = datetime(year, mon, 1, tzinfo=UTC) + end = datetime(year + (mon == 12), mon % 12 + 1, 1, tzinfo=UTC) + return f"{year:04d}-{mon:02d}", start, end + + +def _safe_cell(value: object) -> str: + text = "" if value is None else str(value) + return "'" + text if text.startswith(_FORMULA_PREFIX) else text + + +def _day(value: datetime) -> str: + return f"{value.day} {value:%b %Y}" + + +class ReportingService: + def __init__(self, db: AsyncSession, storage: StorageClient): + self.db = db + self.storage = storage + self.repo = ReportingRepository(db) + + async def dashboard(self, staff: Staff, month: str | None) -> DashboardResponse: + staff.require("earnings") + label, start, end = month_bounds(month) + team = staff.team_id + now = datetime.now(UTC) + repo = self.repo + denominator, improved = await repo.improving(team, start, end) + scores = await repo.latest_scores(team, end) + reviews = await repo.reviews_by_coach(team, start, end) + coaches = [CoachActivity(id=cid, name=name, coaches=_FOCUS.get(focus, "Both"), reviews=reviews.get(cid, 0)) + for cid, name, focus in await repo.coach_rows(team)] + return DashboardResponse(dashboard=Dashboard( + month=label, + active_players=await repo.active_players(team, start, end), + new_this_month=await repo.new_players(team, start, end), + improving_pct=round(100 * improved / denominator) if denominator else None, + analyses_this_week=await repo.analyses_since(team, now - timedelta(days=7)), + avg_review_hours=await repo.avg_review_hours(team, start, end), + cards=Cards(g=sum(s >= 80 for s in scores), y=sum(60 <= s < 80 for s in scores), + r=sum(s < 60 for s in scores)), + coaches=coaches, + pending_requests=await repo.pending_requests(team), + not_filmed_7d=await repo.not_filmed_since(team, now - timedelta(days=7)), + unavailable_reason=REVENUE_UNAVAILABLE, + as_of=now, + )) + + async def earnings(self, staff: Staff, month: str | None) -> EarningsResponse: + staff.require("earnings") + label, _, _ = month_bounds(month) + return EarningsResponse(earnings=Earnings(month=label, as_of=datetime.now(UTC), + unavailable_reason=REVENUE_UNAVAILABLE)) + + async def corporate(self, staff: Staff) -> None: + # No corporate grant exists (capabilities.corporate_view is false for everyone). + raise Forbidden("Corporate reporting needs an organization grant.") + + async def _scope(self, staff: Staff, group_id: uuid.UUID | None) -> None: + if group_id is not None and not await self.repo.group_in_team(staff.team_id, group_id): + raise NotFound("Group not found.") + + @staticmethod + def _item(row) -> ConsentItem: + accepted = row["accepted"] + withdrawn_at = None if accepted else row["last_withdrawn"] + if accepted: + note = f"Accepted {_day(row['last_accepted'])}" + elif withdrawn_at is not None: + note = f"Withdrawn {_day(withdrawn_at)}" + else: + note = "Not yet accepted" + return ConsentItem( + player_id=row["player_id"], name=row["name"], group=row["group"] or "", + group_ids=row["group_ids"] or [], note=note, version=row["version"], + accepted_at=row["last_accepted"], withdrawn_at=withdrawn_at, help_improve_ai=row["help_improve_ai"]) + + async def consent(self, staff: Staff, group_id: uuid.UUID | None, limit: int, cursor: Cursor | None + ) -> ConsentPage: + await self._scope(staff, group_id) + accepted, ai_opt_in = await self.repo.consent_totals(staff.team_id, group_id) + rows = await self.repo.consent_rows(staff.team_id, group_id, limit + 1, cursor) + page = rows[:limit] + next_cursor = encode_cursor(page[-1]["created_at"], page[-1]["player_id"]) if len(rows) > limit else None + return ConsentPage(items=[self._item(r) for r in page], next_cursor=next_cursor, + accepted=accepted, ai_opt_in=ai_opt_in) + + async def export_consent(self, staff: Staff, body: ConsentExportRequest) -> ExportResponse: + await self._scope(staff, body.group_id) + rows = await self.repo.consent_rows(staff.team_id, body.group_id, EXPORT_MAX_ROWS + 1) + if len(rows) > EXPORT_MAX_ROWS: + raise Conflict(f"More than {EXPORT_MAX_ROWS} records; narrow the export by group.", + code="EXPORT_TOO_LARGE") + buffer = io.StringIO() + writer = csv.writer(buffer) + writer.writerow(["player_id", "name", "group", "status", "version", "accepted_at", "withdrawn_at", + "help_improve_ai"]) + for row in rows: + item = self._item(row) + status = "accepted" if row["accepted"] else ("withdrawn" if item.withdrawn_at else "none") + writer.writerow([_safe_cell(v) for v in ( + item.player_id, item.name, item.group, status, item.version or "", + item.accepted_at.isoformat() if item.accepted_at else "", + item.withdrawn_at.isoformat() if item.withdrawn_at else "", + "true" if item.help_improve_ai else "false")]) + + now = datetime.now(UTC) + export_id = uuid.uuid4() + key = f"exports/{staff.team_id}/{export_id}.csv" + async with httpx.AsyncClient() as http: + response = await http.put(self.storage.presign_put(key, "text/csv"), content=buffer.getvalue().encode(), + headers={"Content-Type": "text/csv"}) + response.raise_for_status() + expires_at = now + timedelta(seconds=self.storage.download_ttl) + filename = f"consent-{now:%Y-%m-%d}.csv" + job = await self.repo.add_export(id=export_id, requester_id=staff.id, team_id=staff.team_id, + scope="consent", status="ready", object_key=key, filename=filename, + expires_at=expires_at) + return ExportResponse(export=ExportOut(id=job.id, status="ready", url=self.storage.presign_get(key), + expires_at=expires_at, filename=filename)) diff --git a/backend/app/modules/reviews/controller.py b/backend/app/modules/reviews/controller.py index bb57ff4324bb76b98e3fae5d36de909b3c96c451..39a4b6090d2128d57c88b6961865a9ce64202e31 100644 --- a/backend/app/modules/reviews/controller.py +++ b/backend/app/modules/reviews/controller.py @@ -1,26 +1,28 @@ -"""F4: send or overwrite a coach review, then push to the player.""" +"""F4: send or overwrite a coach review, then notify the player.""" from typing import Annotated from uuid import UUID from fastapi import APIRouter, Depends, Response, status -from app.core.dependencies import CurrentCoach, Db +from app.common.academy_access import CurrentStaff +from app.core.dependencies import Db, Storage from app.integrations.push import PushClient, get_push_client -from app.modules.reviews.schemas import ReviewCreate, ReviewResponse +from app.modules.reviews.schemas import ReviewSubmit, ReviewSubmitted from app.modules.reviews.service import ReviewService router = APIRouter(prefix="/v1", tags=["reviews"]) -def get_review_service(db: Db, push: Annotated[PushClient, Depends(get_push_client)]) -> ReviewService: - return ReviewService(db, push) +def get_review_service(db: Db, storage: Storage, + push: Annotated[PushClient, Depends(get_push_client)]) -> ReviewService: + return ReviewService(db, storage, push) -@router.post("/sessions/{session_id}/review", status_code=status.HTTP_201_CREATED, response_model=ReviewResponse) -async def submit_review(session_id: UUID, body: ReviewCreate, coach: CurrentCoach, response: Response, - service: Annotated[ReviewService, Depends(get_review_service)]) -> ReviewResponse: - review, created = await service.submit(coach, session_id, body.cue, body.drill_id, body.verdicts) +@router.post("/sessions/{session_id}/review", status_code=status.HTTP_201_CREATED, response_model=ReviewSubmitted) +async def submit_review(session_id: UUID, body: ReviewSubmit, staff: CurrentStaff, response: Response, + service: Annotated[ReviewService, Depends(get_review_service)]) -> ReviewSubmitted: + result, created = await service.submit(staff, session_id, body) if not created: response.status_code = status.HTTP_200_OK - return ReviewResponse(review=review) + return result diff --git a/backend/app/modules/reviews/models.py b/backend/app/modules/reviews/models.py index 49ff741ecea6c5f718312e26069f316a10901d6d..efadcc2f95774a3de0662ca3c9aead6c5da26ca3 100644 --- a/backend/app/modules/reviews/models.py +++ b/backend/app/modules/reviews/models.py @@ -1,6 +1,7 @@ import uuid +from decimal import Decimal -from sqlalchemy import ForeignKey, String, Text +from sqlalchemy import ForeignKey, Numeric, String, Text from sqlalchemy.dialects.postgresql import JSONB, UUID from sqlalchemy.orm import Mapped, mapped_column @@ -15,9 +16,13 @@ class Review(TimestampMixin, Base): session_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="CASCADE"), primary_key=True ) - coach_id: Mapped[uuid.UUID] = mapped_column( - UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), index=True + coach_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL"), index=True ) cue: Mapped[str] = mapped_column(Text) drill_id: Mapped[str] = mapped_column(String(16)) verdicts: Mapped[dict] = mapped_column(JSONB) + voice_upload_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("uploads.id", ondelete="SET NULL") + ) + voice_seconds: Mapped[Decimal | None] = mapped_column(Numeric(6, 2)) diff --git a/backend/app/modules/reviews/repository.py b/backend/app/modules/reviews/repository.py index aebb1dcabd0618314e37cfd8fe8f0388167100e9..0ba4389ebb7c1842d131f5adfc7a5897d1e8830a 100644 --- a/backend/app/modules/reviews/repository.py +++ b/backend/app/modules/reviews/repository.py @@ -1,10 +1,12 @@ -"""Reviews, plus the reads F4 needs: the session, its owner's team, the coach's team and the owner's push tokens.""" +"""Reviews, plus what F4 needs: the session, its owner's team, the session thread and its review message, uploads.""" from collections.abc import Sequence +from datetime import UTC, datetime from typing import Any from uuid import UUID from sqlalchemy import delete, func, select +from sqlalchemy.dialects.postgresql import insert from app.common.base_repository import BaseRepository from app.modules.accounts.models import Account @@ -12,6 +14,8 @@ from app.modules.devices.models import Device from app.modules.reviews.models import Review from app.modules.sessions.models import SwingSession from app.modules.teams.models import Team +from app.modules.threads.models import Message, Thread +from app.modules.uploads.models import Upload class ReviewRepository(BaseRepository[Review]): @@ -23,7 +27,8 @@ class ReviewRepository(BaseRepository[Review]): async def live_session(self, session_id: UUID) -> SwingSession | None: return await self.session.scalar( - select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None))) + select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None)) + .with_for_update(of=SwingSession)) # serialises concurrent first reviews of one session async def team_id_of_account(self, account_id: UUID) -> UUID | None: return await self.session.scalar(select(Account.team_id).where(Account.id == account_id)) @@ -37,3 +42,36 @@ class ReviewRepository(BaseRepository[Review]): async def forget_tokens(self, tokens: list[str]) -> None: if tokens: await self.session.execute(delete(Device).where(Device.push_token.in_(tokens))) + + async def upload(self, upload_id: UUID) -> Upload | None: + return await self.session.get(Upload, upload_id) + + async def locked_upload(self, upload_id: UUID) -> Upload | None: + return await self.session.scalar(select(Upload).where(Upload.id == upload_id).with_for_update()) + + async def locked_session_thread(self, session: SwingSession, coach_id: UUID, team_id: UUID | None) -> Thread: + """The session's one thread, created if missing, locked for the counter update.""" + query = select(Thread).where(Thread.session_id == session.id).with_for_update() + thread = await self.session.scalar(query) + if thread is None: + await self.session.execute(insert(Thread).values( + session_id=session.id, player_id=session.owner_id, coach_id=coach_id, mode=session.mode, + team_id=team_id, status="reviewed").on_conflict_do_nothing()) + thread = await self.session.scalar(query) + return thread # type: ignore[return-value] + + async def post_review_message(self, thread: Thread, coach_id: UUID) -> None: + """Upsert the thread's single review message at the next sequence number (re-review = unread again).""" + seq = thread.last_seq + 1 + message = await self.session.scalar( + select(Message).where(Message.thread_id == thread.id, Message.kind == "review")) + if message is None: + self.session.add(Message(thread_id=thread.id, seq=seq, author_id=coach_id, kind="review")) + else: + message.seq, message.author_id = seq, coach_id + thread.last_seq = seq + thread.coach_read_seq = seq + thread.coach_id = coach_id + thread.status = "reviewed" + thread.updated_at = datetime.now(UTC) + await self.session.flush() diff --git a/backend/app/modules/reviews/schemas.py b/backend/app/modules/reviews/schemas.py index 57060b04341aa300d9d05f6aa8d1dc80d084e7c0..f88fe41d96e8d814fce727cae5c00e418fa16df0 100644 --- a/backend/app/modules/reviews/schemas.py +++ b/backend/app/modules/reviews/schemas.py @@ -4,18 +4,19 @@ from uuid import UUID from pydantic import Field -from app.common.schemas import RequestModel, ResponseModel +from app.common.schemas import MediaRef, RequestModel, ResponseModel class ReviewOut(ResponseModel): """The review shape every endpoint returns (GET /sessions/{id} and POST /sessions/{id}/review).""" - coach_id: UUID + coach_id: UUID | None coach_name: str cue: str drill_id: str verdicts: dict[str, str] at: datetime + voice_note: MediaRef | None = None class ReviewCreate(RequestModel): @@ -26,3 +27,15 @@ class ReviewCreate(RequestModel): class ReviewResponse(ResponseModel): review: ReviewOut + + +class ReviewSubmit(ReviewCreate): + """Voice fields: omitted keeps the prior attachment, explicit null removes it (see model_fields_set).""" + + voice_note_upload_id: UUID | None = None + voice_note_seconds: float | None = Field(default=None, gt=0, le=120) + + +class ReviewSubmitted(ResponseModel): + review: ReviewOut + thread_id: UUID diff --git a/backend/app/modules/reviews/service.py b/backend/app/modules/reviews/service.py index 0d25b7e21a9e04bc0432d690bfdf88f5a887afe4..cd47fa6e62a5f635b9a9d3220297bce6311c27dd 100644 --- a/backend/app/modules/reviews/service.py +++ b/backend/app/modules/reviews/service.py @@ -1,18 +1,25 @@ -"""F4: a coach reviews a player's own analysed session. One review per session; sending again overwrites.""" +"""F4: a coach reviews a player's own analysed session. One review per session; sending again overwrites. -import logging +One transaction: review, the session's thread, its single review message (re-review moves it to the next sequence +number so the player sees it as unread again) and the notification. +""" + +import hashlib +import json +from datetime import UTC, datetime, timedelta from functools import cache from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession -from app.core.errors import Forbidden, NotFound, ValidationFailed +from app.common.academy_access import Staff, can_see_player, sessions_shared +from app.common.notify import notify +from app.common.schemas import MediaRef +from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed from app.integrations.push import PushClient -from app.modules.accounts.models import Account +from app.integrations.storage import StorageClient from app.modules.reviews.repository import ReviewRepository -from app.modules.reviews.schemas import ReviewOut - -log = logging.getLogger(__name__) +from app.modules.reviews.schemas import ReviewOut, ReviewSubmit, ReviewSubmitted _DISCIPLINES = {"h": "hitting", "p": "pitching"} @@ -24,33 +31,45 @@ def drill_ids(discipline: str) -> frozenset[str]: return frozenset(d["id"] for d in all_drills() if d["discipline"] == discipline) +def _content_key(values: dict) -> str: + """Same review content -> same key, so a byte-identical resend never notifies twice.""" + raw = json.dumps(values, sort_keys=True, default=str) + return hashlib.sha256(raw.encode()).hexdigest()[:32] + + class ReviewService: - def __init__(self, db: AsyncSession, push: PushClient): + def __init__(self, db: AsyncSession, storage: StorageClient, push: PushClient): + self.db = db self.repo = ReviewRepository(db) + self.storage = storage self.push = push - async def submit(self, coach: Account, session_id: UUID, cue: str, drill_id: str, - verdicts: dict[str, str]) -> tuple[ReviewOut, bool]: - """Returns (review, created).""" + async def submit(self, staff: Staff, session_id: UUID, body: ReviewSubmit) -> tuple[ReviewSubmitted, bool]: + """Returns (response, created).""" + coach = staff.account session = await self.repo.live_session(session_id) if session is None: raise NotFound() - coach_team = await self.repo.team_id_of_coach(coach.id) - owner_team = await self.repo.team_id_of_account(session.owner_id) - if coach_team is None or owner_team != coach_team or not session.is_self or session.analyzed_at is None: + staff.require("review") + if (not await can_see_player(self.db, staff, session.owner_id) or not session.is_self + or session.analyzed_at is None or not await sessions_shared(self.db, session.owner_id)): raise Forbidden() fields: dict[str, str] = {} - if drill_id not in drill_ids(_DISCIPLINES[session.mode]): + if body.drill_id not in drill_ids(_DISCIPLINES[session.mode]): fields["drill_id"] = "Unknown drill for this session." metric_ids = {m.get("metric_id") for m in (session.report or {}).get("measurements", [])} - for key in verdicts: + for key in body.verdicts: if key not in metric_ids: fields[f"verdicts.{key}"] = "Not a metric on this session." + voice = self._voice_change(body, fields) if fields: raise ValidationFailed(fields=fields) + if voice and voice["voice_upload_id"] is not None: + await self._claim_audio(coach.id, voice["voice_upload_id"], session.id) - values = {"coach_id": coach.id, "cue": cue, "drill_id": drill_id, "verdicts": verdicts} + values = {"coach_id": coach.id, "cue": body.cue, "drill_id": body.drill_id, "verdicts": body.verdicts, + **voice} review = await self.repo.get(session.id) created = review is None if created: @@ -58,19 +77,54 @@ class ReviewService: else: review = await self.repo.overwrite(review, **values) - await self._notify(session.owner_id, session.id, coach.name) - return ReviewOut(coach_id=coach.id, coach_name=coach.name, cue=review.cue, drill_id=review.drill_id, - verdicts=review.verdicts, at=review.updated_at), created - - async def _notify(self, owner_id: UUID, session_id: UUID, coach_name: str) -> None: - tokens = list(await self.repo.push_tokens(owner_id)) - if not tokens: - return - try: - dead = await self.push.send( - tokens, {"type": "review.received", "session_id": str(session_id)}, - notification={"title": "New coach review", "body": f"{coach_name or 'Your coach'} reviewed your rep."}) - except Exception: # a push failure must never fail the review - log.exception("push: review.received failed") - return - await self.repo.forget_tokens(dead) + team_id = await self.repo.team_id_of_account(session.owner_id) + thread = await self.repo.locked_session_thread(session, coach.id, team_id) + await self.repo.post_review_message(thread, coach.id) + await notify(self.db, self.push, session.owner_id, kind="review", title="New coach review", + body=f"{coach.name or 'Your coach'} reviewed your rep.", + target={"thread_id": thread.id, "session_id": session.id}, + event_key=f"review:{session.id}:{_content_key(values)}") + + out = ReviewOut(coach_id=review.coach_id, coach_name=coach.name, cue=review.cue, drill_id=review.drill_id, + verdicts=review.verdicts, at=review.updated_at, voice_note=await self._voice_ref(review)) + return ReviewSubmitted(review=out, thread_id=thread.id), created + + @staticmethod + def _voice_change(body: ReviewSubmit, fields: dict[str, str]) -> dict: + """Column values to set for the voice note; empty when the request leaves it alone.""" + sent = body.model_fields_set + upload_id, seconds = body.voice_note_upload_id, body.voice_note_seconds + if "voice_note_upload_id" not in sent: + if seconds is not None: + fields["voice_note_upload_id"] = "Required with voice_note_seconds." + return {} + if upload_id is None: + if seconds is not None: + fields["voice_note_seconds"] = "Must be null when removing the voice note." + return {"voice_upload_id": None, "voice_seconds": None} + if seconds is None: + fields["voice_note_seconds"] = "Required with voice_note_upload_id." + return {"voice_upload_id": upload_id, "voice_seconds": seconds} + + async def _claim_audio(self, coach_id: UUID, upload_id: UUID, session_id: UUID) -> None: + upload = await self.repo.locked_upload(upload_id) + if upload is None or upload.owner_id != coach_id or upload.kind != "audio": + raise Unprocessable("Not a valid audio upload.", code="INVALID_UPLOAD") + if await self.storage.head(upload.object_key) is None: + raise Conflict("The upload has not finished. Please try again.", code="UPLOAD_NOT_READY") + if upload.attached_at is not None: + current = await self.repo.get(session_id) + if current is None or current.voice_upload_id != upload_id: + raise Unprocessable("This audio was already used.", code="UPLOAD_ALREADY_USED") + return # the same review re-sending its own voice note + await self.repo.update(upload, attached_at=datetime.now(UTC)) + + async def _voice_ref(self, review) -> MediaRef | None: + if review.voice_upload_id is None: + return None + upload = await self.repo.upload(review.voice_upload_id) + if upload is None: + return None + return MediaRef(upload_id=upload.id, url=self.storage.presign_get(upload.object_key), + expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl), + seconds=float(review.voice_seconds) if review.voice_seconds is not None else None) diff --git a/backend/app/modules/sessions/repository.py b/backend/app/modules/sessions/repository.py index 4f7ebfef52ad850e74415de8d690ae20af647466..e8c0d326775f0af94fd5d94dde5164ead6e5fa4a 100644 --- a/backend/app/modules/sessions/repository.py +++ b/backend/app/modules/sessions/repository.py @@ -1,7 +1,7 @@ from datetime import datetime from uuid import UUID -from sqlalchemy import Select, exists, func, select, tuple_ +from sqlalchemy import Select, func, select, tuple_ from app.common.base_repository import BaseRepository from app.core.pagination import Cursor @@ -9,7 +9,7 @@ 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.teams.models import Team +from app.modules.settings.models import ConsentEvent from app.modules.uploads.models import Upload @@ -49,13 +49,17 @@ class SessionRepository(BaseRepository[SwingSession]): async def review_with_coach_name(self, session_id: UUID) -> tuple[Review, str] | None: row = (await self.session.execute( - select(Review, Account.name).join(Account, Account.id == Review.coach_id) + select(Review, Account.name).outerjoin(Account, Account.id == Review.coach_id) .where(Review.session_id == session_id))).first() - return (row[0], row[1]) if row else None + return (row[0], row[1] or "") if row else None - async def is_team_coach(self, coach_id: UUID, player_id: UUID) -> bool: - return bool(await self.session.scalar(select(exists().where( - Account.id == player_id, Team.id == Account.team_id, Team.coach_id == coach_id)))) + async def analysis_consent_blocked(self, account_id: UUID, require_accepted: bool) -> bool: + """True when the latest analysis consent is a withdrawal, or (when required) there is no acceptance.""" + action = await self.session.scalar( + select(ConsentEvent.action) + .where(ConsentEvent.account_id == account_id, ConsentEvent.category == "analysis") + .order_by(ConsentEvent.created_at.desc(), ConsentEvent.id.desc()).limit(1)) + return action == "withdrawn" or (require_accepted and action is None) def summaries_query(self, owner_id: UUID, *, mode: str | None, is_self: bool | None, athlete_name: str | None, since: datetime | None, cursor: Cursor | None, limit: int) -> Select: diff --git a/backend/app/modules/sessions/service.py b/backend/app/modules/sessions/service.py index 4af8c51c368ad8945cc3b05ca2ae27cdad84ccc0..66c0bd79c5da7a26b0fe368b6a6b2a7445959cca 100644 --- a/backend/app/modules/sessions/service.py +++ b/backend/app/modules/sessions/service.py @@ -7,7 +7,8 @@ from uuid import UUID from sqlalchemy.ext.asyncio import AsyncSession -from app.common.schemas import Page +from app.common.academy_access import can_see_player, sessions_shared, staff_context +from app.common.schemas import MediaRef, Page from app.core.config import get_settings from app.core.errors import Forbidden, NotFound, Unprocessable, ValidationFailed from app.core.pagination import PageParams, encode_cursor @@ -90,6 +91,8 @@ class SessionService: # D2 async def create(self, account: Account, body: SessionIn) -> SessionOut: validate_marks(body) + if await self.sessions.analysis_consent_blocked(account.id, get_settings().require_analysis_consent): + raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED") await EntitlementService(self.db).ensure_can_analyze(account.id) video = await self._claimable(account, body.video_upload_id, "video", "video_upload_id") @@ -139,9 +142,11 @@ class SessionService: raise NotFound() is_owner = session.owner_id == viewer.id if not is_owner: - # A coach sees their team's players' own analysed reps; private_videos does not block the coach. - allowed = (session.is_self and session.analyzed_at is not None and viewer.role == "coach" - and await self.sessions.is_team_coach(viewer.id, session.owner_id)) + # Staff who can see the player see their own analysed reps, unless the player hid sessions from + # coaches (coach_can_see_sessions); private_videos does not block the coach. + staff = await staff_context(self.db, viewer) if session.is_self and session.analyzed_at else None + allowed = (staff is not None and await can_see_player(self.db, staff, session.owner_id) + and await sessions_shared(self.db, session.owner_id)) if not allowed: raise Forbidden() return await self._out(session, include_body_data=is_owner) @@ -152,8 +157,16 @@ class SessionService: review = None if review_row: r, coach_name = review_row + voice_note = None + if r.voice_upload_id is not None: + voice_keys = await self.uploads.object_keys(r.voice_upload_id) + if r.voice_upload_id in voice_keys: + voice_note = MediaRef( + upload_id=r.voice_upload_id, url=self.storage.presign_get(voice_keys[r.voice_upload_id]), + expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl), + seconds=float(r.voice_seconds) if r.voice_seconds is not None else None) review = ReviewOut(coach_id=r.coach_id, coach_name=coach_name, cue=r.cue, drill_id=r.drill_id, - verdicts=r.verdicts, at=r.updated_at) + verdicts=r.verdicts, at=r.updated_at, voice_note=voice_note) previous = await self.sessions.previous(s) thumb_key = keys.get(s.thumbnail_upload_id) if s.thumbnail_upload_id else None return SessionOut( diff --git a/backend/app/modules/settings/__init__.py b/backend/app/modules/settings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/settings/controller.py b/backend/app/modules/settings/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..616b77170f7ea100d9163b58dae50a9bcc84471a --- /dev/null +++ b/backend/app/modules/settings/controller.py @@ -0,0 +1,49 @@ +"""N01 to N05: /me/settings, /me/consent, /me/exports.""" + +from typing import Annotated + +from fastapi import APIRouter, Header, Response + +from app.core.dependencies import CurrentAccount, Db +from app.modules.idempotency.service import run_idempotent +from app.modules.settings.schemas import ( + ConsentIn, + ExportEnvelope, + ExportIn, + SettingsEnvelope, + SettingsPatch, +) +from app.modules.settings.service import SettingsService + +router = APIRouter(prefix="/v1", tags=["settings"]) +IdempotencyKey = Annotated[str | None, Header(max_length=128)] + + +@router.get("/me/settings", response_model=SettingsEnvelope) +async def read_settings(account: CurrentAccount, db: Db) -> SettingsEnvelope: + return SettingsEnvelope(settings=await SettingsService(db).get(account)) + + +@router.patch("/me/settings", response_model=SettingsEnvelope) +async def update_settings(body: SettingsPatch, account: CurrentAccount, db: Db) -> SettingsEnvelope: + return SettingsEnvelope(settings=await SettingsService(db).update(account, body)) + + +@router.post("/me/consent", status_code=201) +async def accept_consent(body: ConsentIn, account: CurrentAccount, db: Db, idempotency_key: IdempotencyKey = None): + service = SettingsService(db) + return await run_idempotent(db, account.id, idempotency_key, body, lambda: service.accept(account, body), + status_code=201) + + +@router.delete("/me/consent", status_code=204) +async def withdraw_consent(account: CurrentAccount, db: Db) -> Response: + await SettingsService(db).withdraw(account) + return Response(status_code=204) + + +@router.post("/me/exports", status_code=202, response_model=ExportEnvelope) +async def request_export(body: ExportIn, account: CurrentAccount, db: Db, idempotency_key: IdempotencyKey = None): + service = SettingsService(db) + return await run_idempotent(db, account.id, idempotency_key, body, lambda: service.request_export(account), + status_code=202) diff --git a/backend/app/modules/settings/models.py b/backend/app/modules/settings/models.py new file mode 100644 index 0000000000000000000000000000000000000000..2c32851313692853477e3781896bb12a0d074e55 --- /dev/null +++ b/backend/app/modules/settings/models.py @@ -0,0 +1,74 @@ +import uuid +from datetime import datetime + +from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column + +from app.common.base_model import Base, CreatedAtMixin, IdMixin, TimestampMixin + + +def _flag(default: bool) -> Mapped[bool]: + return mapped_column(Boolean, server_default="true" if default else "false") + + +class UserSettings(TimestampMixin, Base): + """Sharing and notification preferences. A missing row means the defaults; effective consent lives in events.""" + + __tablename__ = "user_settings" + + account_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True + ) + coach_can_see_sessions: Mapped[bool] = _flag(True) + share_with_parent: Mapped[bool] = _flag(False) + parent_email: Mapped[str | None] = mapped_column(String(254)) + auto_monthly_report: Mapped[bool] = _flag(False) + private_links: Mapped[bool] = _flag(False) + clips_as_examples: Mapped[bool] = _flag(False) + help_improve_ai: Mapped[bool] = _flag(False) + notify_results: Mapped[bool] = _flag(True) + notify_coach: Mapped[bool] = _flag(True) + notify_drills: Mapped[bool] = _flag(True) + notify_weekly: Mapped[bool] = _flag(True) + skip_filming_guide: Mapped[bool] = _flag(False) + timezone: Mapped[str | None] = mapped_column(String(64)) + version: Mapped[int] = mapped_column(Integer, server_default="1") + + +class ConsentEvent(IdMixin, CreatedAtMixin, Base): + """Append-only consent history. The latest 'analysis' event decides whether new analysis is allowed.""" + + __tablename__ = "consent_events" + __table_args__ = ( + CheckConstraint("category IN ('analysis', 'help_improve_ai', 'clips_as_examples')", name="category"), + CheckConstraint("action IN ('accepted', 'withdrawn')", name="action"), + Index("ix_consent_events_account_id_category_created_at", "account_id", "category", "created_at"), + ) + + account_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE")) + category: Mapped[str] = mapped_column(String(20)) + action: Mapped[str] = mapped_column(String(10)) + policy_version: Mapped[str | None] = mapped_column(String(16)) + + +class ExportJob(IdMixin, CreatedAtMixin, Base): + """A requested export (all videos for a player, consent CSV for an academy).""" + + __tablename__ = "export_jobs" + __table_args__ = ( + CheckConstraint("scope IN ('videos', 'consent')", name="scope"), + CheckConstraint("status IN ('queued', 'ready', 'failed', 'cancelled')", name="status"), + Index("ix_export_jobs_requester_id_status", "requester_id", "status"), + ) + + requester_id: Mapped[uuid.UUID] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE") + ) + team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="CASCADE")) + scope: Mapped[str] = mapped_column(String(10)) + status: Mapped[str] = mapped_column(String(10), server_default="queued") + object_key: Mapped[str | None] = mapped_column(Text) + filename: Mapped[str | None] = mapped_column(String(120)) + error_code: Mapped[str | None] = mapped_column(String(40)) + expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/backend/app/modules/settings/repository.py b/backend/app/modules/settings/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..b13e4e66032353c13b488d65a6e23949b04c53c0 --- /dev/null +++ b/backend/app/modules/settings/repository.py @@ -0,0 +1,39 @@ +from uuid import UUID + +from sqlalchemy import select +from sqlalchemy.dialects.postgresql import insert + +from app.common.base_repository import BaseRepository +from app.modules.settings.models import ConsentEvent, ExportJob, UserSettings + + +class SettingsRepository(BaseRepository[UserSettings]): + model = UserSettings + + async def locked(self, account_id: UUID) -> UserSettings: + """The account's row, created with the defaults if missing, locked until the request commits.""" + await self.session.execute( + insert(UserSettings).values(account_id=account_id).on_conflict_do_nothing(index_elements=["account_id"])) + row = await self.session.scalar( + select(UserSettings).where(UserSettings.account_id == account_id) + .with_for_update().execution_options(populate_existing=True)) + assert row is not None + return row + + +class ConsentRepository(BaseRepository[ConsentEvent]): + model = ConsentEvent + + async def latest(self, account_id: UUID, category: str = "analysis") -> ConsentEvent | None: + return await self.session.scalar( + select(ConsentEvent).where(ConsentEvent.account_id == account_id, ConsentEvent.category == category) + .order_by(ConsentEvent.created_at.desc(), ConsentEvent.id.desc()).limit(1)) + + +class ExportRepository(BaseRepository[ExportJob]): + model = ExportJob + + async def queued(self, requester_id: UUID, scope: str) -> ExportJob | None: + return await self.session.scalar( + select(ExportJob).where(ExportJob.requester_id == requester_id, ExportJob.scope == scope, + ExportJob.status == "queued").limit(1)) diff --git a/backend/app/modules/settings/schemas.py b/backend/app/modules/settings/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..770ff564e38fecc0bd99ac546535f0755bc19539 --- /dev/null +++ b/backend/app/modules/settings/schemas.py @@ -0,0 +1,80 @@ +"""N01 to N05 bodies.""" + +from datetime import datetime +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import AfterValidator, Field + +from app.common.schemas import RequestModel, ResponseModel +from app.modules.auth.schemas import normalize_email + +Email = Annotated[str, Field(max_length=254), AfterValidator(normalize_email)] + + +class SettingsOut(ResponseModel): + coach_can_see_sessions: bool + share_with_parent: bool + parent_email: str | None + auto_monthly_report: bool + private_links: bool + clips_as_examples: bool + help_improve_ai: bool + notify_results: bool + notify_coach: bool + notify_drills: bool + notify_weekly: bool + consented_at: datetime | None + consent_version: str | None + skip_filming_guide: bool + version: int + + +class SettingsEnvelope(ResponseModel): + settings: SettingsOut + + +class SettingsPatch(RequestModel): + coach_can_see_sessions: bool | None = Field(None, strict=True) + share_with_parent: bool | None = Field(None, strict=True) + parent_email: Email | None = None + auto_monthly_report: bool | None = Field(None, strict=True) + private_links: bool | None = Field(None, strict=True) + clips_as_examples: bool | None = Field(None, strict=True) + help_improve_ai: bool | None = Field(None, strict=True) + notify_results: bool | None = Field(None, strict=True) + notify_coach: bool | None = Field(None, strict=True) + notify_drills: bool | None = Field(None, strict=True) + notify_weekly: bool | None = Field(None, strict=True) + skip_filming_guide: bool | None = Field(None, strict=True) + expected_version: int | None = Field(None, ge=1) + + +class ConsentIn(RequestModel): + version: str = Field(min_length=1, max_length=16) + accepted: Literal[True] + + +class ConsentOut(ResponseModel): + version: str | None + accepted_at: datetime + withdrawn_at: datetime | None = None + + +class ConsentEnvelope(ResponseModel): + consent: ConsentOut + + +class ExportIn(RequestModel): + scope: Literal["videos"] + + +class ExportOut(ResponseModel): + id: UUID + status: str + requested_at: datetime + delivery: Literal["account_email"] = "account_email" + + +class ExportEnvelope(ResponseModel): + export: ExportOut diff --git a/backend/app/modules/settings/service.py b/backend/app/modules/settings/service.py new file mode 100644 index 0000000000000000000000000000000000000000..6d6a802a5faf975340877e93fd701eb93762651f --- /dev/null +++ b/backend/app/modules/settings/service.py @@ -0,0 +1,98 @@ +"""N01 to N05: preferences, consent history and the all-videos export request.""" + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.core.config import get_settings +from app.core.errors import Conflict, Unprocessable, ValidationFailed +from app.modules.accounts.models import Account +from app.modules.settings.models import UserSettings +from app.modules.settings.repository import ConsentRepository, ExportRepository, SettingsRepository +from app.modules.settings.schemas import ( + ConsentEnvelope, + ConsentIn, + ConsentOut, + ExportEnvelope, + ExportOut, + SettingsOut, + SettingsPatch, +) + +FLAGS = ("coach_can_see_sessions", "share_with_parent", "private_links", "clips_as_examples", "help_improve_ai", + "notify_results", "notify_coach", "notify_drills", "notify_weekly", "skip_filming_guide") +DEFAULTS = {"coach_can_see_sessions": True, "share_with_parent": False, "parent_email": None, + "auto_monthly_report": False, "private_links": False, "clips_as_examples": False, + "help_improve_ai": False, "notify_results": True, "notify_coach": True, "notify_drills": True, + "notify_weekly": True, "skip_filming_guide": False, "version": 1} +OPT_INS = ("help_improve_ai", "clips_as_examples") + + +class SettingsService: + def __init__(self, db: AsyncSession): + self.settings = SettingsRepository(db) + self.consents = ConsentRepository(db) + self.exports = ExportRepository(db) + + async def _out(self, account: Account, row: UserSettings | None) -> SettingsOut: + values = {k: getattr(row, k) for k in DEFAULTS} if row else dict(DEFAULTS) + event = await self.consents.latest(account.id) + accepted = event is not None and event.action == "accepted" + return SettingsOut(**values, consented_at=event.created_at if accepted else None, + consent_version=event.policy_version if accepted else None) + + # N01 + async def get(self, account: Account) -> SettingsOut: + return await self._out(account, await self.settings.get(account.id)) + + # N02 + async def update(self, account: Account, body: SettingsPatch) -> SettingsOut: + changes = body.model_dump(exclude_unset=True, exclude={"expected_version"}) + if not changes: + raise ValidationFailed(fields={"body": "Send at least one setting to change."}) + for name in (*FLAGS, "auto_monthly_report"): + if name in changes and changes[name] is None: + raise ValidationFailed(fields={name: "Must be true or false."}) + row = await self.settings.locked(account.id) + if body.expected_version is not None and body.expected_version != row.version: + raise Conflict("This item changed. Refresh and try again.", code="STALE_VERSION") + + share = changes.get("share_with_parent", row.share_with_parent) + email = changes["parent_email"] if "parent_email" in changes else row.parent_email + if changes.get("auto_monthly_report") and not (share and email): + raise Unprocessable( + "Turn on parent sharing and add a parent email first.", code="VALIDATION", + fields={"auto_monthly_report": "Requires share_with_parent and parent_email."}) + if not share: + changes["auto_monthly_report"] = False + + for name in OPT_INS: + if name in changes and changes[name] != getattr(row, name): + await self.consents.create(account_id=account.id, category=name, + action="accepted" if changes[name] else "withdrawn") + await self.settings.update(row, **changes, version=row.version + 1) + return await self._out(account, row) + + # N03 + async def accept(self, account: Account, body: ConsentIn) -> ConsentEnvelope: + if body.version not in get_settings().consent_versions: + raise Conflict("The terms changed. Please review the latest version.", code="TERMS_CHANGED") + event = await self.consents.latest(account.id) + if event is None or event.action != "accepted" or event.policy_version != body.version: + event = await self.consents.create(account_id=account.id, category="analysis", action="accepted", + policy_version=body.version) + return ConsentEnvelope(consent=ConsentOut(version=event.policy_version, accepted_at=event.created_at)) + + # N04 + async def withdraw(self, account: Account) -> None: + event = await self.consents.latest(account.id) + if event is not None and event.action == "accepted": + await self.consents.create(account_id=account.id, category="analysis", action="withdrawn", + policy_version=event.policy_version) + + # N05 + async def request_export(self, account: Account) -> ExportEnvelope: + if not account.email: + raise Unprocessable("Your account has no email address.", code="EMAIL_UNAVAILABLE") + if await self.exports.queued(account.id, "videos") is not None: + raise Conflict("An export is already on its way to your email.", code="EXPORT_IN_PROGRESS") + job = await self.exports.create(requester_id=account.id, scope="videos", status="queued") + return ExportEnvelope(export=ExportOut(id=job.id, status=job.status, requested_at=job.created_at)) diff --git a/backend/app/modules/swing_reports/repository.py b/backend/app/modules/swing_reports/repository.py index 5f934d20c5b8af29c15f3bf74d241bf42d45a707..ff1f0d11d76cd96be78f2b574ae675e8e7ff1925 100644 --- a/backend/app/modules/swing_reports/repository.py +++ b/backend/app/modules/swing_reports/repository.py @@ -4,6 +4,7 @@ from sqlalchemy import select from app.common.base_repository import BaseRepository from app.modules.sessions.models import SwingSession +from app.modules.settings.models import ConsentEvent class SwingReportRepository(BaseRepository[SwingSession]): @@ -15,3 +16,11 @@ class SwingReportRepository(BaseRepository[SwingSession]): select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None)) .with_for_update()) return result.scalars().first() + + async def analysis_consent_blocked(self, account_id: UUID, require_accepted: bool) -> bool: + """True when the latest analysis consent is a withdrawal, or (when required) there is no acceptance.""" + action = await self.session.scalar( + select(ConsentEvent.action) + .where(ConsentEvent.account_id == account_id, ConsentEvent.category == "analysis") + .order_by(ConsentEvent.created_at.desc(), ConsentEvent.id.desc()).limit(1)) + return action == "withdrawn" or (require_accepted and action is None) diff --git a/backend/app/modules/swing_reports/service.py b/backend/app/modules/swing_reports/service.py index 45a9f87705f92debecb9ffd61d29a24d7661ce65..f534344a1620b140830af83d67d42dbde21802a9 100644 --- a/backend/app/modules/swing_reports/service.py +++ b/backend/app/modules/swing_reports/service.py @@ -78,6 +78,8 @@ class SwingReportService: return session.report if parsed.analysis_revision < (session.analysis_revision or 0): raise Conflict("A newer revision of this analysis has already been reported.", code="STALE_REVISION") + if await self.sessions.analysis_consent_blocked(account.id, get_settings().require_analysis_consent): + raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED") ensure_coach_configured() if session.analyzed_at is None: await self.entitlements.ensure_can_analyze(account.id) diff --git a/backend/app/modules/threads/__init__.py b/backend/app/modules/threads/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/backend/app/modules/threads/controller.py b/backend/app/modules/threads/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..b05fb0543a2ac3286b1d7dfdcb84e57de8d3a768 --- /dev/null +++ b/backend/app/modules/threads/controller.py @@ -0,0 +1,75 @@ +"""N10-N15: conversations between players and coaches.""" + +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, Header, Query, Response, status +from pydantic import BaseModel + +from app.common.academy_access import CurrentStaff +from app.common.schemas import Page +from app.core.dependencies import CurrentAccount, Db, Paging, Storage +from app.integrations.push import PushClient, get_push_client +from app.modules.idempotency.service import run_idempotent +from app.modules.threads.schemas import EnsureThreadIn, MessageIn, ReadIn, SendResult, ThreadEnvelope, ThreadOut +from app.modules.threads.service import ThreadService + +router = APIRouter(prefix="/v1", tags=["threads"]) + + +def get_thread_service(db: Db, storage: Storage, + push: Annotated[PushClient, Depends(get_push_client)]) -> ThreadService: + return ThreadService(db, storage, push) + + +class _Scoped(BaseModel): + thread_id: str + body: dict + + +Service = Annotated[ThreadService, Depends(get_thread_service)] + + +@router.get("/threads", response_model=Page[ThreadOut]) +async def list_threads(account: CurrentAccount, service: Service, paging: Paging, mode: Annotated[ + str | None, Query(pattern="^[hp]$")] = None, player_id: UUID | None = None, + unread: bool | None = None) -> Page[ThreadOut]: + return await service.list_threads(account, paging, mode=mode, player_id=player_id, unread=unread) + + +@router.get("/threads/{thread_id}", response_model=ThreadEnvelope) +async def get_thread(thread_id: UUID, account: CurrentAccount, service: Service, + message_cursor: str | None = None, + message_limit: Annotated[int, Query(ge=1, le=100)] = 50) -> ThreadEnvelope: + return ThreadEnvelope(thread=await service.get(account, thread_id, message_cursor, message_limit)) + + +@router.get("/sessions/{session_id}/thread", response_model=ThreadEnvelope) +async def session_thread(session_id: UUID, account: CurrentAccount, service: Service) -> ThreadEnvelope: + return ThreadEnvelope(thread=await service.for_session(account, session_id)) + + +@router.post("/threads/{thread_id}/read", status_code=status.HTTP_204_NO_CONTENT) +async def mark_read(thread_id: UUID, body: ReadIn, account: CurrentAccount, service: Service) -> Response: + await service.mark_read(account, thread_id, body.last_message_id) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + +@router.post("/threads/{thread_id}/messages", status_code=status.HTTP_201_CREATED, response_model=SendResult) +async def send_message(thread_id: UUID, body: MessageIn, account: CurrentAccount, db: Db, service: Service, + idempotency_key: Annotated[str | None, Header()] = None): + # The key is scoped to the account, so the thread id is part of what must match on replay. + scoped = _Scoped(thread_id=str(thread_id), body=body.model_dump(mode="json")) + return await run_idempotent(db, account.id, idempotency_key, scoped, lambda: service.send(account, thread_id, body), + status_code=status.HTTP_201_CREATED) + + +@router.post("/coach/players/{player_id}/thread", status_code=status.HTTP_201_CREATED, + response_model=ThreadEnvelope) +async def ensure_thread(player_id: UUID, body: EnsureThreadIn, staff: CurrentStaff, response: Response, + service: Service) -> ThreadEnvelope: + thread, created = await service.ensure_general(staff, player_id, body) + if not created: + response.status_code = status.HTTP_200_OK + return ThreadEnvelope(thread=thread) + diff --git a/backend/app/modules/threads/models.py b/backend/app/modules/threads/models.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d8ef143572ad65ffafa90eb9b1afdf7d4fb9d2 --- /dev/null +++ b/backend/app/modules/threads/models.py @@ -0,0 +1,80 @@ +import uuid +from datetime import datetime +from decimal import Decimal + +from sqlalchemy import ( + CheckConstraint, + DateTime, + ForeignKey, + Index, + Integer, + Numeric, + String, + Text, + UniqueConstraint, + func, + text, +) +from sqlalchemy.dialects.postgresql import UUID +from sqlalchemy.orm import Mapped, mapped_column + +from app.common.base_model import Base, CreatedAtMixin, IdMixin + + +class Thread(IdMixin, CreatedAtMixin, Base): + """A player-coach conversation: one per reviewed session, or one general thread per (player, coach, mode). + + Read state is a per-side watermark on the message sequence (only two participants). + """ + + __tablename__ = "threads" + __table_args__ = ( + CheckConstraint("mode IN ('h', 'p')", name="mode"), + CheckConstraint("status IN ('waiting_for_coach', 'reviewed')", name="status"), + Index("uq_threads_general", "player_id", "coach_id", "mode", unique=True, + postgresql_where=text("session_id IS NULL")), + Index("ix_threads_player_id_updated_at", "player_id", text("updated_at DESC")), + Index("ix_threads_coach_id_updated_at", "coach_id", text("updated_at DESC")), + ) + + team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="SET NULL")) + player_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE")) + coach_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL") + ) + mode: Mapped[str] = mapped_column(String(1)) + session_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="CASCADE"), unique=True + ) + status: Mapped[str] = mapped_column(String(20), server_default="reviewed") + last_seq: Mapped[int] = mapped_column(Integer, server_default="0") + player_read_seq: Mapped[int] = mapped_column(Integer, server_default="0") + coach_read_seq: Mapped[int] = mapped_column(Integer, server_default="0") + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now()) + + +class Message(IdMixin, CreatedAtMixin, Base): + """kind text: text; voice: upload_id + seconds; session: session_id; review: rendered from the session's review.""" + + __tablename__ = "messages" + __table_args__ = ( + UniqueConstraint("thread_id", "seq"), + CheckConstraint("kind IN ('text', 'voice', 'session', 'review')", name="kind"), + CheckConstraint("kind <> 'text' OR text IS NOT NULL", name="text_body"), + CheckConstraint("kind <> 'voice' OR (upload_id IS NOT NULL AND seconds > 0)", name="voice_body"), + ) + + thread_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("threads.id", ondelete="CASCADE")) + seq: Mapped[int] = mapped_column(Integer) + author_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL") + ) + kind: Mapped[str] = mapped_column(String(8)) + text: Mapped[str | None] = mapped_column(Text) + upload_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("uploads.id", ondelete="SET NULL") + ) + seconds: Mapped[Decimal | None] = mapped_column(Numeric(6, 2)) + session_id: Mapped[uuid.UUID | None] = mapped_column( + UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL") + ) diff --git a/backend/app/modules/threads/repository.py b/backend/app/modules/threads/repository.py new file mode 100644 index 0000000000000000000000000000000000000000..64641ba49c5d591638b43d23084d190f9fb3e1e6 --- /dev/null +++ b/backend/app/modules/threads/repository.py @@ -0,0 +1,136 @@ +"""Threads and messages, plus the reads the thread views need from accounts, sessions, reviews and uploads.""" + +from collections.abc import Sequence +from datetime import datetime +from uuid import UUID + +from sqlalchemy import Select, and_, func, or_, select, tuple_, update +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.orm import aliased + +from app.common.base_repository import BaseRepository +from app.modules.accounts.models import Account +from app.modules.reviews.models import Review +from app.modules.sessions.models import SwingSession +from app.modules.threads.models import Message, Thread +from app.modules.uploads.models import Upload + + +class ThreadRepository(BaseRepository[Thread]): + model = Thread + + async def locked(self, thread_id: UUID) -> Thread | None: + return await self.session.scalar(select(Thread).where(Thread.id == thread_id).with_for_update()) + + async def for_session(self, session_id: UUID) -> Thread | None: + return await self.session.scalar(select(Thread).where(Thread.session_id == session_id)) + + async def general(self, player_id: UUID, coach_id: UUID, mode: str) -> Thread | None: + return await self.session.scalar(select(Thread).where( + Thread.player_id == player_id, Thread.coach_id == coach_id, Thread.mode == mode, + Thread.session_id.is_(None))) + + async def create_general(self, **values) -> Thread | None: + """None when a concurrent request created it first (partial unique index).""" + return await self.session.scalar( + insert(Thread).values(session_id=None, **values).on_conflict_do_nothing().returning(Thread)) + + def list_query(self, *, player_id: UUID, staff_id: UUID | None, team_id: UUID | None, + visible: Select | None, mode: str | None, + filter_player_id: UUID | None, unread: bool | None, cursor_at: datetime | None, + cursor_id: UUID | None, limit: int) -> Select: + access = [Thread.player_id == player_id] + if staff_id is not None: + if visible is not None: + access.append(and_(Thread.team_id == team_id, Thread.player_id.in_(visible))) + query = select(Thread).where(or_(*access)) + if mode: + query = query.where(Thread.mode == mode) + if filter_player_id: + query = query.where(Thread.player_id == filter_player_id) + if unread is not None: + has_unread = or_(and_(Thread.player_id == player_id, Thread.last_seq > Thread.player_read_seq), + and_(Thread.player_id != player_id, Thread.last_seq > Thread.coach_read_seq)) + query = query.where(has_unread if unread else ~has_unread) + if cursor_at is not None and cursor_id is not None: + query = query.where(tuple_(Thread.updated_at, Thread.id) < tuple_(cursor_at, cursor_id)) + return query.order_by(Thread.updated_at.desc(), Thread.id.desc()).limit(limit) + + async def run(self, query: Select) -> Sequence[Thread]: + return (await self.session.scalars(query)).all() + + async def latest_messages(self, thread_ids: list[UUID], per_thread: int, + before_seq: int | None = None) -> dict[UUID, list[Message]]: + """Newest `per_thread` messages of each thread, returned oldest first.""" + rank = func.row_number().over(partition_by=Message.thread_id, order_by=Message.seq.desc()).label("rank") + inner = select(Message.id, rank).where(Message.thread_id.in_(thread_ids)) + if before_seq is not None: + inner = inner.where(Message.seq < before_seq) + ranked = inner.subquery() + rows = (await self.session.scalars( + select(Message).join(ranked, ranked.c.id == Message.id).where(ranked.c.rank <= per_thread) + .order_by(Message.thread_id, Message.seq))).all() + grouped: dict[UUID, list[Message]] = {t: [] for t in thread_ids} + for message in rows: + grouped[message.thread_id].append(message) + return grouped + + async def message(self, message_id: UUID) -> Message | None: + return await self.session.get(Message, message_id) + + async def add_message(self, **values) -> Message: + message = Message(**values) + self.session.add(message) + await self.session.flush() + await self.session.refresh(message) + return message + + async def advance_read(self, thread_id: UUID, side: str, seq: int) -> None: + column = Thread.player_read_seq if side == "player" else Thread.coach_read_seq + await self.session.execute( + update(Thread).where(Thread.id == thread_id).values({column.key: func.greatest(column, seq)})) + + async def names(self, ids: set[UUID]) -> dict[UUID, str]: + rows = await self.session.execute(select(Account.id, Account.name).where(Account.id.in_(ids))) + return {i: n or "" for i, n in rows.all()} + + async def session_row(self, session_id: UUID) -> SwingSession | None: + return await self.session.get(SwingSession, session_id) + + async def session_infos(self, session_ids: set[UUID]) -> dict[UUID, tuple[SwingSession, int]]: + """Each live session with its 1-based ordinal among the owner's analysed reps of the same mode and athlete.""" + if not session_ids: + return {} + earlier = aliased(SwingSession) + ordinal = (select(func.count()).select_from(earlier).where( + earlier.owner_id == SwingSession.owner_id, earlier.mode == SwingSession.mode, + earlier.athlete["name"].astext == SwingSession.athlete["name"].astext, earlier.deleted_at.is_(None), + earlier.analyzed_at.is_not(None), earlier.created_at <= SwingSession.created_at, + earlier.id != SwingSession.id).correlate(SwingSession).scalar_subquery()) + rows = await self.session.execute(select(SwingSession, ordinal + 1).where( + SwingSession.id.in_(session_ids), SwingSession.deleted_at.is_(None))) + return {s.id: (s, n) for s, n in rows.all()} + + async def reviews(self, session_ids: set[UUID]) -> dict[UUID, Review]: + if not session_ids: + return {} + rows = await self.session.scalars(select(Review).where(Review.session_id.in_(session_ids))) + return {r.session_id: r for r in rows} + + async def uploads(self, ids: set[UUID]) -> dict[UUID, Upload]: + if not ids: + return {} + return {u.id: u for u in await self.session.scalars(select(Upload).where(Upload.id.in_(ids)))} + + async def upload(self, upload_id: UUID) -> Upload | None: + return await self.session.get(Upload, upload_id) + + async def locked_upload(self, upload_id: UUID) -> Upload | None: + return await self.session.scalar(select(Upload).where(Upload.id == upload_id).with_for_update()) + + async def upload_in_use(self, upload_id: UUID) -> bool: + """Backstop for rows attached before attached_at was reliably set.""" + used = await self.session.scalar(select(Message.id).where(Message.upload_id == upload_id).limit(1)) + if used is None: + used = await self.session.scalar(select(Review.session_id).where(Review.voice_upload_id == upload_id)) + return used is not None diff --git a/backend/app/modules/threads/schemas.py b/backend/app/modules/threads/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..e79b4549bb30d360807a7841442f195e0e677357 --- /dev/null +++ b/backend/app/modules/threads/schemas.py @@ -0,0 +1,111 @@ +from datetime import datetime +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import ConfigDict, Field + +from app.common.schemas import MediaRef, RequestModel, ResponseModel + + +class _MessageBase(ResponseModel): + model_config = ConfigDict(from_attributes=True, populate_by_name=True) + + id: UUID + author_id: UUID | None + from_: Literal["player", "coach"] = Field(alias="from") + at: datetime + + +class TextMessageOut(_MessageBase): + kind: Literal["text"] = "text" + text: str + + +class VoiceMessageOut(_MessageBase): + kind: Literal["voice"] = "voice" + seconds: float + audio: MediaRef | None + + +class SessionMessageOut(_MessageBase): + kind: Literal["session"] = "session" + session_id: UUID | None + label: str | None + score: int | None + + +class Finding(ResponseModel): + metric_id: str + name: str + verdict: Literal["agree", "change", "later"] + + +class ReviewMessageOut(_MessageBase): + kind: Literal["review"] = "review" + cue: str + voice_seconds: float | None + audio: MediaRef | None + findings: list[Finding] + drill_id: str | None + drill_name: str | None + assignment_id: UUID | None = None + + +MessageOut = Annotated[TextMessageOut | VoiceMessageOut | SessionMessageOut | ReviewMessageOut, + Field(discriminator="kind")] + + +class ThreadOut(ResponseModel): + id: UUID + mode: Literal["h", "p"] + session_id: UUID | None + session_label: str + score: int | None + tone: Literal["g", "y", "r"] + coach_id: UUID | None + coach_name: str + player_id: UUID + player_name: str + status: Literal["waiting_for_coach", "reviewed"] + unread_for_player: bool + unread_for_coach: bool + updated_at: datetime + messages: list[MessageOut] + next_message_cursor: str | None = None + + +class ThreadEnvelope(ResponseModel): + thread: ThreadOut + + +class SendResult(ResponseModel): + message: MessageOut + thread_status: Literal["waiting_for_coach", "reviewed"] + updated_at: datetime + + +class TextIn(RequestModel): + kind: Literal["text"] + text: str = Field(min_length=1, max_length=500) + + +class VoiceIn(RequestModel): + kind: Literal["voice"] + upload_id: UUID + seconds: float = Field(gt=0, le=120) + + +class SessionIn(RequestModel): + kind: Literal["session"] + session_id: UUID + + +MessageIn = Annotated[TextIn | VoiceIn | SessionIn, Field(discriminator="kind")] + + +class ReadIn(RequestModel): + last_message_id: UUID | None = None + + +class EnsureThreadIn(RequestModel): + mode: Literal["h", "p"] diff --git a/backend/app/modules/threads/service.py b/backend/app/modules/threads/service.py new file mode 100644 index 0000000000000000000000000000000000000000..1b947ed9a435df8e5a323659c106aeab3e85bbba --- /dev/null +++ b/backend/app/modules/threads/service.py @@ -0,0 +1,320 @@ +"""Conversations between a player and their coaches (N10-N15). + +Access: the player of a thread, or staff of the thread's academy who can see its player (CurrentStaff rules, so +paused or removed members lose access). Only the thread's own coach moves the coach read watermark. Anything else +is a 404. Read state is one watermark per side on Message.seq; +Thread.last_seq is the counter, incremented under a row lock. +""" + +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from functools import cache +from uuid import UUID + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.common.academy_access import ( + Staff, + can_see_player, + require_player, + sessions_shared, + staff_context, + visible_players_query, +) +from app.common.notify import notify +from app.common.schemas import MediaRef, Page +from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable +from app.core.pagination import PageParams, encode_cursor +from app.integrations.push import PushClient +from app.integrations.storage import StorageClient +from app.modules.accounts.models import Account +from app.modules.reviews.models import Review +from app.modules.sessions.models import SwingSession +from app.modules.threads.models import Message, Thread +from app.modules.threads.repository import ThreadRepository +from app.modules.threads.schemas import ( + EnsureThreadIn, + Finding, + MessageIn, + ReviewMessageOut, + SendResult, + SessionMessageOut, + TextMessageOut, + ThreadOut, + VoiceMessageOut, +) +from app.modules.uploads.models import Upload + +LIST_MESSAGES = 20 # messages included per thread in the list +TONE_GREEN_MIN = 80 # overall score at or above: "g"; at or above TONE_YELLOW_MIN: "y"; below: "r" +TONE_YELLOW_MIN = 60 +_SESSION_WORD = {"h": "Swing", "p": "Pitch"} + + +@cache +def drill_names() -> dict[str, str]: + from ai_coach.knowledge import all_drills + + return {d["id"]: d["name"] for d in all_drills()} + + +def tone(score: int | None) -> str: + if score is None: + return "y" + return "g" if score >= TONE_GREEN_MIN else "y" if score >= TONE_YELLOW_MIN else "r" + + +@dataclass +class Access: + thread: Thread + side: str # player | coach + staff: Staff | None + + +class ThreadService: + def __init__(self, db: AsyncSession, storage: StorageClient, push: PushClient | None = None): + self.db = db + self.repo = ThreadRepository(db) + self.storage = storage + self.push = push + + # ---------- access ---------- + + async def _access(self, account: Account, thread: Thread | None) -> Access: + if thread is None: + raise NotFound() + if thread.player_id == account.id: + return Access(thread, "player", None) + staff = await staff_context(self.db, account) + if (staff is not None and staff.team_id is not None and thread.team_id == staff.team_id + and await can_see_player(self.db, staff, thread.player_id)): + return Access(thread, "coach", staff) + raise NotFound() + + async def _load(self, account: Account, thread_id: UUID, *, lock: bool = False) -> Access: + thread = await (self.repo.locked(thread_id) if lock else self.repo.get(thread_id)) + return await self._access(account, thread) + + # ---------- reads ---------- + + async def list_threads(self, account: Account, paging: PageParams, *, mode: str | None, player_id: UUID | None, + unread: bool | None) -> Page[ThreadOut]: + staff = await staff_context(self.db, account) + if staff is None and player_id is not None and player_id != account.id: + player_id = None # a player cannot widen their scope + scoped = staff if staff is not None and staff.team_id is not None else None + visible = visible_players_query(scoped) if scoped else None + cursor = paging.cursor + rows = await self.repo.run(self.repo.list_query( + player_id=account.id, staff_id=scoped.id if scoped else None, + team_id=scoped.team_id if scoped else None, visible=visible, mode=mode, + filter_player_id=player_id, unread=unread, cursor_at=cursor.created_at if cursor else None, + cursor_id=cursor.id if cursor else None, limit=paging.limit + 1)) + page = list(rows[:paging.limit]) + out = await self._render(page, LIST_MESSAGES) + next_cursor = encode_cursor(page[-1].updated_at, page[-1].id) if len(rows) > paging.limit else None + return Page[ThreadOut](items=out, next_cursor=next_cursor) + + async def get(self, account: Account, thread_id: UUID, cursor: str | None, limit: int) -> ThreadOut: + access = await self._load(account, thread_id) + return (await self._render([access.thread], limit, before_seq=_seq(cursor)))[0] + + async def for_session(self, account: Account, session_id: UUID) -> ThreadOut: + session = await self.repo.session_row(session_id) + try: + if session is None or session.deleted_at is not None: + raise NotFound() + access = await self._access(account, await self.repo.for_session(session_id)) + except NotFound: + raise NotFound("No conversation for this session.", code="THREAD_NOT_FOUND") from None + return (await self._render([access.thread], LIST_MESSAGES))[0] + + # ---------- writes ---------- + + async def mark_read(self, account: Account, thread_id: UUID, last_message_id: UUID | None) -> None: + access = await self._load(account, thread_id) + if last_message_id is None: + return + if access.side == "coach" and account.id != access.thread.coach_id: + return # the watermark belongs to the thread's own coach + message = await self.repo.message(last_message_id) + if message is None or message.thread_id != thread_id: + raise Unprocessable("That message is not in this conversation.", code="MESSAGE_NOT_IN_THREAD") + await self.repo.advance_read(thread_id, access.side, message.seq) + + async def send(self, account: Account, thread_id: UUID, body: MessageIn) -> SendResult: + access = await self._load(account, thread_id, lock=True) + thread = access.thread + if access.staff is not None: + access.staff.require("review") + values: dict = {"kind": body.kind} + preview = "" + if body.kind == "text": + values["text"] = body.text + preview = body.text + elif body.kind == "voice": + await self._claim_audio(account, body.upload_id) + values.update(upload_id=body.upload_id, seconds=body.seconds) + preview = "Sent a voice message." + else: + await self._check_session(access, body.session_id) + values["session_id"] = body.session_id + preview = "Shared a session." + + now = datetime.now(UTC) + seq = thread.last_seq + 1 + message = await self.repo.add_message(thread_id=thread.id, seq=seq, author_id=account.id, created_at=now, + **values) + read = {"player_read_seq": seq} if access.side == "player" else ( + {"coach_read_seq": seq} if account.id == thread.coach_id else {}) + await self.repo.update(thread, last_seq=seq, updated_at=now, **read, + status="waiting_for_coach" if access.side == "player" else "reviewed") + recipient = thread.coach_id if access.side == "player" else thread.player_id + if recipient is not None: + await notify(self.db, self.push, recipient, kind="review", + title=f"{account.name or 'Someone'} sent a message", body=preview, + target={"thread_id": thread.id}, event_key=f"message:{message.id}") + out = (await self._render_messages(thread, [message]))[0] + return SendResult(message=out, thread_status=thread.status, updated_at=thread.updated_at) + + async def ensure_general(self, staff: Staff, player_id: UUID, body: EnsureThreadIn) -> tuple[ThreadOut, bool]: + staff.require("review") + player = await require_player(self.db, staff, player_id) + thread = await self.repo.general(player.id, staff.id, body.mode) + created = thread is None + if thread is None: + thread = await self.repo.create_general(team_id=staff.team_id, player_id=player.id, coach_id=staff.id, + mode=body.mode, status="reviewed") + if thread is None: # lost a race with a concurrent create + thread = await self.repo.general(player.id, staff.id, body.mode) + created = False + return (await self._render([thread], LIST_MESSAGES))[0], created + + async def _claim_audio(self, account: Account, upload_id: UUID) -> None: + upload = await self.repo.locked_upload(upload_id) + if upload is None or upload.owner_id != account.id or upload.kind != "audio": + raise Unprocessable("Not a valid audio upload.", code="INVALID_UPLOAD") + if upload.attached_at is not None or await self.repo.upload_in_use(upload_id): + raise Unprocessable("This audio was already used.", code="UPLOAD_ALREADY_USED") + if await self.storage.head(upload.object_key) is None: + raise Conflict("The upload has not finished. Please try again.", code="UPLOAD_NOT_READY") + await self.repo.update(upload, attached_at=datetime.now(UTC)) + + async def _check_session(self, access: Access, session_id: UUID) -> None: + session = await self.repo.session_row(session_id) + if session is None or session.deleted_at is not None or session.owner_id != access.thread.player_id: + raise NotFound() + if session.mode != access.thread.mode: + raise Unprocessable("This session is for the other mode.", code="MODE_MISMATCH") + if access.side == "coach" and not await sessions_shared(self.db, session.owner_id): + raise Forbidden("This player does not share sessions with coaches.") + + # ---------- rendering ---------- + + async def _render(self, threads: list[Thread], per_thread: int, before_seq: int | None = None) -> list[ThreadOut]: + if not threads: + return [] + grouped = await self.repo.latest_messages([t.id for t in threads], per_thread + 1, before_seq) + cursors: dict[UUID, str | None] = {} + for thread in threads: + messages = grouped[thread.id] + cursors[thread.id] = None + if len(messages) > per_thread: + messages = messages[1:] + cursors[thread.id] = str(messages[0].seq) + grouped[thread.id] = messages + flat = [m for t in threads for m in grouped[t.id]] + ctx = await self._context(threads, flat) + out = [] + for thread in threads: + session, ordinal = ctx.sessions.get(thread.session_id, (None, 0)) if thread.session_id else (None, 0) + score = session.overall_score if session else None + label = _label(session, ordinal) if session else "Latest session" + out.append(ThreadOut( # a deleted session renders as a tombstone: session_id null + id=thread.id, mode=thread.mode, session_id=session.id if session else None, session_label=label, + score=score, tone=tone(score), coach_id=thread.coach_id, + coach_name=ctx.names.get(thread.coach_id, "") if thread.coach_id else "", + player_id=thread.player_id, player_name=ctx.names.get(thread.player_id, ""), status=thread.status, + unread_for_player=thread.last_seq > thread.player_read_seq, + unread_for_coach=thread.last_seq > thread.coach_read_seq, updated_at=thread.updated_at, + messages=[self._message(thread, m, ctx) for m in grouped[thread.id]], + next_message_cursor=cursors[thread.id])) + return out + + async def _render_messages(self, thread: Thread, messages: list[Message]): + ctx = await self._context([thread], messages) + return [self._message(thread, m, ctx) for m in messages] + + async def _context(self, threads: list[Thread], messages: list[Message]) -> "_Context": + session_ids = {t.session_id for t in threads if t.session_id} | {m.session_id for m in messages if m.session_id} + reviews = await self.repo.reviews({t.session_id for t in threads if t.session_id and any( + m.thread_id == t.id and m.kind == "review" for m in messages)}) + upload_ids = {m.upload_id for m in messages if m.upload_id} | { + r.voice_upload_id for r in reviews.values() if r.voice_upload_id} + return _Context( + names=await self.repo.names({t.coach_id for t in threads if t.coach_id} | {t.player_id for t in threads}), + sessions=await self.repo.session_infos(session_ids), reviews=reviews, + uploads=await self.repo.uploads(upload_ids), storage=self.storage) + + def _message(self, thread: Thread, m: Message, ctx: "_Context"): + common = {"id": m.id, "author_id": m.author_id, "from": "player" if m.author_id == thread.player_id + else "coach", "at": m.created_at} + if m.kind == "text": + return TextMessageOut(**common, text=m.text or "") + if m.kind == "voice": + return VoiceMessageOut(**common, seconds=float(m.seconds or 0), + audio=ctx.media(m.upload_id, float(m.seconds) if m.seconds else None)) + if m.kind == "session": + session, ordinal = ctx.sessions.get(m.session_id, (None, 0)) + return SessionMessageOut(**common, session_id=session.id if session else None, + label=_label(session, ordinal) if session else None, + score=session.overall_score if session else None) + review = ctx.reviews.get(thread.session_id) + session = ctx.sessions.get(thread.session_id, (None, 0))[0] + if review is None: + return ReviewMessageOut(**common, cue="", voice_seconds=None, audio=None, findings=[], drill_id=None, + drill_name=None) + common["at"] = review.updated_at + seconds = float(review.voice_seconds) if review.voice_seconds is not None else None + return ReviewMessageOut( + **common, cue=review.cue, voice_seconds=seconds, audio=ctx.media(review.voice_upload_id, seconds), + findings=_findings(review, session), drill_id=review.drill_id, + drill_name=drill_names().get(review.drill_id)) + + +@dataclass +class _Context: + names: dict[UUID, str] + sessions: dict[UUID, tuple[SwingSession, int]] + reviews: dict[UUID, Review] + uploads: dict[UUID, Upload] + storage: StorageClient + + def media(self, upload_id: UUID | None, seconds: float | None) -> MediaRef | None: + upload = self.uploads.get(upload_id) if upload_id else None + if upload is None: + return None + return MediaRef(upload_id=upload.id, url=self.storage.presign_get(upload.object_key), + expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl), seconds=seconds) + + +def _label(session: SwingSession, ordinal: int) -> str: + return f"{_SESSION_WORD.get(session.mode, 'Swing')} {ordinal}" + + +def _findings(review: Review, session: SwingSession | None) -> list[Finding]: + names = {m.get("metric_id"): m.get("display_name") or m.get("name") + for m in ((session.report if session else None) or {}).get("measurements", [])} + return [Finding(metric_id=k, name=names.get(k) or k.replace("_", " ").title(), verdict=v) + for k, v in review.verdicts.items()] + + +def _seq(cursor: str | None) -> int | None: + if cursor is None: + return None + try: + return int(cursor) + except ValueError: + from app.core.errors import ValidationFailed + + raise ValidationFailed(fields={"message_cursor": "Invalid cursor."}) from None diff --git a/backend/app/modules/uploads/models.py b/backend/app/modules/uploads/models.py index 2d4146ea798e086bbad2c7e011ffc6a63c95e999..f3f2ebf60c306278212ad92e6ec2ba3a2e10d44b 100644 --- a/backend/app/modules/uploads/models.py +++ b/backend/app/modules/uploads/models.py @@ -13,14 +13,14 @@ class Upload(IdMixin, CreatedAtMixin, Base): __tablename__ = "uploads" __table_args__ = ( - CheckConstraint("kind IN ('video', 'thumbnail')", name="kind"), + CheckConstraint("kind IN ('video', 'thumbnail', 'audio', 'drill_video')", name="kind"), Index("ix_uploads_unattached_created_at", "created_at", postgresql_where=text("attached_at IS NULL")), ) owner_id: Mapped[uuid.UUID] = mapped_column( UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), index=True ) - kind: Mapped[str] = mapped_column(String(10)) + kind: Mapped[str] = mapped_column(String(12)) object_key: Mapped[str] = mapped_column(Text, unique=True) content_type: Mapped[str] = mapped_column(String(40)) size_bytes: Mapped[int] = mapped_column(BigInteger) diff --git a/backend/app/modules/uploads/schemas.py b/backend/app/modules/uploads/schemas.py index 57251ad278f237f8600207efd95d2ae48c59620e..3a0de786a032719e978487c8a3c69dbb0e3b4640 100644 --- a/backend/app/modules/uploads/schemas.py +++ b/backend/app/modules/uploads/schemas.py @@ -8,7 +8,7 @@ from app.common.schemas import RequestModel, ResponseModel class UploadIn(RequestModel): - kind: Literal["video", "thumbnail"] + kind: Literal["video", "thumbnail", "audio", "drill_video"] content_type: str = Field(min_length=1, max_length=40) size_bytes: int = Field(gt=0) duration_sec: float | None = Field(default=None, gt=0) diff --git a/backend/app/modules/uploads/service.py b/backend/app/modules/uploads/service.py index 8ef920e0598493c6b3cdf940ee0fa0df76a71099..2943902140f7d93a953a5bff532a98bc7cb1949d 100644 --- a/backend/app/modules/uploads/service.py +++ b/backend/app/modules/uploads/service.py @@ -5,8 +5,9 @@ from datetime import UTC, datetime, timedelta from sqlalchemy.ext.asyncio import AsyncSession +from app.common.academy_access import staff_context from app.core.config import get_settings -from app.core.errors import TooLarge, ValidationFailed +from app.core.errors import Forbidden, TooLarge, ValidationFailed from app.integrations.storage import StorageClient from app.modules.accounts.models import Account from app.modules.uploads.repository import UploadRepository @@ -16,31 +17,52 @@ from app.modules.uploads.schemas import UploadIn, UploadOut ALLOWED_TYPES = { "video": {"video/mp4": "mp4", "video/quicktime": "mov"}, "thumbnail": {"image/jpeg": "jpg"}, + "audio": {"audio/mp4": "m4a", "audio/aac": "aac", "audio/mpeg": "mp3"}, + "drill_video": {"video/mp4": "mp4", "video/quicktime": "mov"}, } -FOLDERS = {"video": "videos", "thumbnail": "thumbnails"} +FOLDERS = {"video": "videos", "thumbnail": "thumbnails", "audio": "audio", "drill_video": "drill-videos"} +MAX_AUDIO_BYTES = 5 * 1024 * 1024 +MAX_AUDIO_SECONDS = 120.0 +MAX_DRILL_VIDEO_SECONDS = 300.0 def max_bytes(kind: str) -> int: settings = get_settings() - return settings.max_video_bytes if kind == "video" else settings.max_thumbnail_bytes + if kind == "audio": + return MAX_AUDIO_BYTES + return settings.max_video_bytes if kind in ("video", "drill_video") else settings.max_thumbnail_bytes + + +def max_seconds(kind: str) -> float | None: + settings = get_settings() + return {"video": settings.max_video_seconds, "audio": MAX_AUDIO_SECONDS, + "drill_video": MAX_DRILL_VIDEO_SECONDS}.get(kind) class UploadService: def __init__(self, db: AsyncSession, storage: StorageClient): + self.db = db self.uploads = UploadRepository(db) self.storage = storage async def create(self, account: Account, body: UploadIn) -> UploadOut: - settings = get_settings() ext = ALLOWED_TYPES[body.kind].get(body.content_type) if ext is None: raise ValidationFailed(fields={"content_type": f"Not an accepted {body.kind} type."}) - if body.kind == "video": + if body.kind == "drill_video": + staff = await staff_context(self.db, account) + if staff is None: + raise Forbidden("Only coaches can do this.") + staff.require("library") + limit = max_seconds(body.kind) + if limit is not None: + label = {"video": "a video", "audio": "an audio note", "drill_video": "a drill video"}[body.kind] if body.duration_sec is None: - raise ValidationFailed(fields={"duration_sec": "Required for a video."}) - if body.duration_sec > settings.max_video_seconds: + raise ValidationFailed(fields={"duration_sec": f"Required for {label}."}) + if body.duration_sec > limit: + subject = "Clips" if body.kind == "video" else "This" raise ValidationFailed("Clip too long.", fields={ - "duration_sec": f"Clips can be at most {settings.max_video_seconds:g} seconds."}) + "duration_sec": f"{subject} can be at most {limit:g} seconds."}) if body.size_bytes > max_bytes(body.kind): raise TooLarge() diff --git a/backend/docs/FRONTEND_INTEGRATION.md b/backend/docs/FRONTEND_INTEGRATION.md index 6eef9c0e8dbcd91fd843d8d9bcc3fabd3f322630..8d64a66281e56d62b9e054612ab47137178b9c19 100644 --- a/backend/docs/FRONTEND_INTEGRATION.md +++ b/backend/docs/FRONTEND_INTEGRATION.md @@ -4,7 +4,7 @@ **Goal:** replace the local AsyncStorage store (`src/store`, `AppContext`) with API calls. Every screen keeps calling the same context actions; only the store layer changes. -**Status:** all 4 milestones are implemented. They are verified end to end against the real Supabase database and DigitalOcean Spaces bucket (713 QA checks, `backend/e2e/`). +**Status:** all 4 milestones are implemented. They are verified end to end against the real Supabase database and DigitalOcean Spaces bucket (713 QA checks, `backend/e2e/`). The coaching workflow and academy APIs (§14) are implemented and tested locally (465 e2e checks). ## 0. Sources of truth (read in this order) @@ -14,6 +14,7 @@ | Swing report (the analysis result) | `AI-coach-agent/docs/SWING_REPORT_API.md` | How to render scores, ratings, groups, focus area and measurements | | ML payload the app forwards | `backend/docs/reference/ml_contract_v1.md` | What the ML API returns and the app posts to us, unchanged | | This guide | `backend/docs/FRONTEND_INTEGRATION.md` | Flows, mapping from the old store, rules, edge cases | +| Coaching workflow contract | `backend/docs/reference/coaching_workflow_spec.md` and `coaching_workflow_decisions.md` | Spec IDs N01–N50 and C01–C08 used in §14 | When this guide and `openapi.json` disagree, `openapi.json` wins. Please report the mismatch. @@ -224,7 +225,7 @@ The full field list is in `SWING_REPORT_API.md`. The app renders; it never compu - **Register:** after the user grants permission and after each sign-in, call `POST /v1/devices {platform: "ios"|"android", push_token}` with the FCM token (201, or 200 if already registered). Calling it again is safe. A token registered by another account moves to the current one. - **Unregister:** on sign-out, `DELETE /v1/devices/{push_token}`. -- **Payload:** `data: {type: "review.received", session_id}` → open Result for `session_id`. It also carries a title and body notification. There is no `analysis.done` push, because the analysis is synchronous (§5). +- **Payload:** `data: {type: "review.received", session_id}` → open Result for `session_id`. It also carries a title and body notification. There is no `analysis.done` push, because the analysis is synchronous (§5). New pushes also carry `notification_id`, `kind` and `target_json`; see §14.5. ## 10. Plan and billing @@ -276,3 +277,428 @@ Use it for drill names and the review drill picker. `mode=p` returns pitching dr - StoreKit and Play purchases posted to `/billing/receipts`; catalog used for drill names. To check the backend at any time: `cd backend && .venv/bin/python e2e/qa_sessions_reports.py` against a running API (see `backend/e2e/README.md`). + +## 14. Coaching workflow and academy (settings, consent, notifications, threads, goals, assignments, arm care, staff, groups, library, reporting) + +This part replaces the `src/mock/*` adapters. Spec IDs (N01–N50, C01–C08) refer to `reference/coaching_workflow_spec.md`. It is covered by integration tests, the black-box suite `e2e/qa_coaching_workflow.py` and a contract test against the spec examples (`tests/integration/test_qa_contract.py`). + +### 14.1 Conventions (in addition to §1) + +- **Wrappers.** A single resource comes wrapped (`{settings:{...}}`, `{goal:{...}}`, `{thread:{...}}`). A list returns `{items, next_cursor}`. Unwrap these in the adapter. +- **Pagination.** Pass `?limit=1..200&cursor=`. A screen that needs the full set (badges, Queue Sent, CoachHistory) must follow `next_cursor`. Never treat the first page as the whole list. +- **Validation errors are 400 `VALIDATION`** with `fields`, as everywhere else in this API. The spec says 422; the existing client already handles 400. + - Named domain rules return 422 or 409 with a specific `code`. Each section below lists them. +- **`expected_version`.** Editable resources return `version`. Send it back as `expected_version`. On 409 `STALE_VERSION`, refetch and let the user retry. +- **`Idempotency-Key: `** is accepted on every POST that creates something: + - consent, exports, messages, assignments, set logs, arm-care outings; + - coach-access applications, staff codes, request decisions; + - groups, roster adds, library publishing, the consent CSV. + - Make one key per user action. Reuse it only when retrying, including after a timeout. +- **New HTTP method: PUT.** `src/api/client.ts` must add `PUT` to its method union. Goals, notes and arm feel use it. +- **Dates.** A date-only field (`due_date`, `day`, `local_date`) is the device's local `YYYY-MM-DD`. Instants are UTC. Server-side timezones are not modelled yet, so send local dates. +- **Media.** Audio and video always arrive as `MediaRef`: `{upload_id, url, expires_at, seconds?}`. + - `url` is a short-lived presigned GET. Never store it. + - When it expires, refetch the resource that contained it (thread, assignment, library). +- **Never show demo data.** Remove the AsyncStorage seed for these features. An absent value is `null`, an empty list or `unavailable_reason`. Render "not available yet", never a made-up number. +- **Reads never mark anything as read.** Use the explicit read endpoints. + +### 14.2 Account capabilities: what to show (C03) + +`GET /v1/me` now also returns: + +```json +{ + "academy": {"id": "...", "name": "Northside", "role": "admin|coach|assistant", "status": "active", + "sees_all": true, "group_ids": ["..."], + "permissions": {"review": true, "drills": true, "goals": true, "library": true, "earnings": true}}, + "coach_access": {"status": "none|pending|approved|declined", "code": null, "sent_at": null}, + "capabilities": {"player": true, "coach": false, "academy_admin": false, "corporate_view": false} +} +``` + +- `academy` is `null` when the account has no active academy role. +- An **academy** is the existing team. The coach who created the team is its implicit `admin`. +- **Drive navigation from `capabilities`, not from `user.role`:** + - `capabilities.coach` shows the coach tabs. + - `capabilities.academy_admin` shows the Team admin tools: Dashboard, Earnings, CoachRequests, StaffCodes, CoachManage, Consent and Groups. + - `corporate_view` is always false today, so hide CorpDash. +- **Dual role.** A player whose coaching application is approved has `capabilities.player` and `capabilities.coach` both true. Offer a mode switch and keep the player tabs working. +- Use `academy.permissions` to hide buttons. The server enforces them anyway with 403: + - `drills`: assign a drill. + - `goals`: set a goal. + - `library`: upload a drill video. + - `review`: review or message. +- **Assistants** always have `drills:false` and `goals:false`. +- **Refetch `/me`:** after a coach-access application, after an admin decision and when the app returns to the foreground. + - A paused coach gets 403 on coach endpoints. + - Route a 403 to a "your access is paused" screen. + +### 14.3 Screen → endpoint map + +| Screen / mock function | Call | Notes | +|---|---|---| +| Settings, Guide, ReportCard: `settings.get` | `GET /v1/me/settings` | | +| Settings toggle: `settings.update` | `PATCH /v1/me/settings` | Send only the changed fields plus `expected_version`. Use the returned values; roll back the toggle on failure. | +| Guide consent: `settings.consent` | `POST /v1/me/consent {version:"1.0", accepted:true}` | **Wait for 201 before opening the camera.** Don't continue on error (the mock fails open today). | +| Settings, withdraw consent | `DELETE /v1/me/consent` | 204 | +| Settings, Download all my videos | `POST /v1/me/exports {scope:"videos"}` | 202 means "queued", not "sent". Toast: "We'll email you the links." | +| Home bell | `GET /v1/notifications/unread-count` | | +| Notifications list | `GET /v1/notifications` | | +| Notification tap | `POST /v1/notifications/{id}/read`, then route by `target` | See §14.5 | +| Mark all read | `POST /v1/notifications/read-all {through: }` | | +| Messages, Home, CoachThreads, Queue Sent, CoachHistory: `threads.list` | `GET /v1/threads?mode=&unread=&player_id=` | `player_id` is for staff only | +| Thread: `threads.get` | `GET /v1/threads/{id}?message_cursor=` | | +| Thread open/scroll: `threads.markRead` | `POST /v1/threads/{id}/read {last_message_id}` | The id of the last message actually rendered | +| Composer: `threads.send` | `POST /v1/threads/{id}/messages` | See §14.4 | +| Result: `threads.forSession` | `GET /v1/sessions/{id}/thread` | 404 `THREAD_NOT_FOUND` means "no review card". Any other error is an error. | +| CoachPlayer Message: `threads.ensureForPlayer` | `POST /v1/coach/players/{player_id}/thread {mode}` | 201 new, 200 existing. Navigate to the returned id. | +| Review send | `POST /v1/sessions/{id}/review` | Returns `thread_id`. **Delete** the local `upsertReview` and the fake voice message. | +| Goal reads (Home, Progress, ReportCard, CoachPlayer, GoalEdit, CoachHistory): `goals.get` | `GET /v1/players/{player_id}/goals?mode=` | A player passes their own `user.id` | +| GoalEdit Save: `goals.save` | `PUT /v1/players/{player_id}/goals/{mode}` | | +| Progress, GoalEdit, CoachHistory: `goals.past` | `GET /v1/players/{player_id}/goals/history?mode=` | | +| Progress: `milestones(mode)` | `GET /v1/me/milestones?mode=` | Empty until goals are evaluated. Keep the locally derived milestones. | +| Drills, Drill, Messages, CoachPlayer, Queue, CoachHistory: `assignedDrills.list` | `GET /v1/drill-assignments?mode=&player_id=&status=open\|completed\|all` | | +| AssignDrillSheet: `assignedDrills.assign` | `POST /v1/coach/players/{player_id}/drill-assignments` | **The sheet must receive `playerId`.** | +| Drill "Mark set done": `assignedDrills.logSet` | `POST /v1/drill-assignments/{id}/sets` | The +/- rep counter stays local | +| ArmCare, pitching Home, ReportCard: `armCare.get` | `GET /v1/me/arm-care` | | +| ArmCare Add outing: `armCare.addOuting` | `POST /v1/me/arm-care/outings {pitches, local_date}` | | +| ArmCare feel: `armCare.setFeel` | `PUT /v1/me/arm-care/feel {feel}` | | +| Profile, CoachPending: `coachAccess.get` | `GET /v1/me/coach-access` | | +| CoachRequest Send: `coachAccess.request` | `POST /v1/me/coach-access {code}` | May return `approved` straight away (auto codes) | +| Roster group selector: `academy.groups` | `GET /v1/academy/groups` | Filter with `GET /v1/coach/roster?group_id=` or client-side on `group_ids` | +| CreateGroup: `academy.createGroup` | `POST /v1/academy/groups` | Send the **ids**, not names or a count | +| CoachPlayer note: `academy.note` / `saveNote` | `GET` / `PUT /v1/coach/players/{player_id}/note` | | +| AddPlayers search | `GET /v1/academy/members?q=` | Replaces the hardcoded `MEMBERS` list. Debounce it. | +| AddPlayers Add | `POST /v1/coach/roster/players {player_ids, group_id?}` | | +| DrillLib list: `academy.library` | `GET /v1/academy/library?mode=&fault_tag=` | | +| DrillLib Upload | `POST /v1/uploads {kind:"drill_video"}`, PUT the bytes, then `POST /v1/academy/library` | Needs a real picker and form | +| OwnerDash: `academy.dashboard` | `GET /v1/academy/dashboard?month=YYYY-MM` | | +| Earnings: `academy.earnings` | `GET /v1/academy/earnings?month=` | Every money field is null today. See §14.9. | +| CorpDash: `academy.corp` | `GET /v1/academy/corp` | Always 403 today. Hide it. | +| CoachRequests, CoachManage, CreateGroup: `academy.members` | `GET /v1/academy/coaches?status=` | | +| CoachManage: `academy.member` | `GET /v1/academy/coaches/{id}` | Activity is included (no separate endpoint) | +| CoachManage Save / Pause / Resume: `updateMember` | `PATCH /v1/academy/coaches/{id}` | | +| CoachManage Remove: `removeMember` | `DELETE /v1/academy/coaches/{id}?reassign_to=` | **Pass the selected replacement** | +| CoachRequests list, Team badge: `academy.requests` | `GET /v1/academy/coach-requests?status=pending` | The badge uses `total_pending` | +| Approve/decline: `academy.decide` | `POST /v1/academy/coach-requests/{id}/decision` | | +| StaffCodes: `codes`, `generateCode`, `revokeCode` | `GET`, `POST`, `DELETE /v1/academy/staff-codes[/{code}]` | Copy and share stay native | +| Consent list: `academy.consent` | `GET /v1/academy/consent?group_id=` | | +| Consent Export | `POST /v1/academy/consent/export {format:"csv"}` | Download `url` natively | + +### 14.4 Conversations + +#### Thread object (N10/N11/N12/N15) + +```json +{"id":"...","mode":"h","session_id":"...|null","session_label":"Swing 12","score":74,"tone":"g|y|r", + "coach_id":"...|null","coach_name":"Jamie","player_id":"...","player_name":"Alex", + "status":"waiting_for_coach|reviewed","unread_for_player":true,"unread_for_coach":false, + "updated_at":"...","messages":[...],"next_message_cursor":"...|null"} +``` + +- **Threads per player.** There is one thread per reviewed session, and one general thread per (player, coach, mode). + - A general thread has `session_id: null` and `session_label: "Latest session"`. +- **`tone`** is derived from `score`: g ≥ 80, y ≥ 60, r below 60. A missing score gives y. +- **`session_id` becomes `null`** once the session has been deleted. Show it as "This session was deleted". +- **`coach_id` is `null` and `coach_name` is `""`** if the coach deleted their account. The history stays. +- **`GET /v1/threads` includes the latest 20 messages per thread.** Open the thread for more. `next_message_cursor` loads **older** messages: `GET /v1/threads/{id}?message_cursor=...`. + - Each page comes back oldest first. + +#### Message union (discriminate on `kind`) + +Every message has `id`, `author_id`, `from` (`player|coach`) and `at`. + +| kind | extra fields | +|---|---| +| `text` | `text` | +| `voice` | `seconds`, `audio: MediaRef` | +| `session` | `session_id` (null when deleted), `label`, `score` | +| `review` | `cue`, `voice_seconds`, `audio: MediaRef\|null`, `findings: [{metric_id, name, verdict: agree\|change\|later}]`, `drill_id`, **`drill_name`**, `assignment_id` (null) | + +- The review message is produced by the server from the stored review. You can never POST `kind:"review"`. +- **Re-reviewing updates the same review message.** It moves to the newest position and is unread again for the player. + +#### Sending (N14) + +Use one of these bodies: + +```json +{"kind":"text","text":"1–500 chars"} +{"kind":"voice","upload_id":"