Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
fe40b87
1
Parent(s): 1c10ad8
Automated Deploy: 3ea2037ab7d55d5b498f7e2ea0336818fc24f725
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- backend/app/common/academy_access.py +151 -0
- backend/app/common/notify.py +56 -0
- backend/app/common/schemas.py +11 -0
- backend/app/core/config.py +4 -0
- backend/app/jobs/exports.py +63 -0
- backend/app/main.py +11 -0
- backend/app/models.py +20 -0
- backend/app/modules/academy/__init__.py +0 -0
- backend/app/modules/academy/models.py +174 -0
- backend/app/modules/academy_org/__init__.py +0 -0
- backend/app/modules/academy_org/controller.py +90 -0
- backend/app/modules/academy_org/repository.py +177 -0
- backend/app/modules/academy_org/schemas.py +95 -0
- backend/app/modules/academy_org/service.py +178 -0
- backend/app/modules/academy_staff/__init__.py +0 -0
- backend/app/modules/academy_staff/controller.py +119 -0
- backend/app/modules/academy_staff/repository.py +166 -0
- backend/app/modules/academy_staff/schemas.py +119 -0
- backend/app/modules/academy_staff/service.py +346 -0
- backend/app/modules/accounts/repository.py +15 -0
- backend/app/modules/accounts/schemas.py +21 -0
- backend/app/modules/accounts/service.py +24 -2
- backend/app/modules/arm_care/__init__.py +0 -0
- backend/app/modules/arm_care/controller.py +37 -0
- backend/app/modules/arm_care/models.py +41 -0
- backend/app/modules/arm_care/repository.py +30 -0
- backend/app/modules/arm_care/schemas.py +53 -0
- backend/app/modules/arm_care/service.py +68 -0
- backend/app/modules/assignments/__init__.py +0 -0
- backend/app/modules/assignments/controller.py +61 -0
- backend/app/modules/assignments/models.py +55 -0
- backend/app/modules/assignments/repository.py +96 -0
- backend/app/modules/assignments/schemas.py +62 -0
- backend/app/modules/assignments/service.py +151 -0
- backend/app/modules/coach/controller.py +11 -7
- backend/app/modules/coach/repository.py +18 -9
- backend/app/modules/coach/schemas.py +1 -0
- backend/app/modules/coach/service.py +23 -17
- backend/app/modules/drills/models.py +4 -1
- backend/app/modules/drills/schemas.py +1 -0
- backend/app/modules/goals/__init__.py +0 -0
- backend/app/modules/goals/controller.py +39 -0
- backend/app/modules/goals/models.py +46 -0
- backend/app/modules/goals/repository.py +42 -0
- backend/app/modules/goals/schemas.py +81 -0
- backend/app/modules/goals/service.py +188 -0
- backend/app/modules/notifications/__init__.py +0 -0
- backend/app/modules/notifications/controller.py +34 -0
- backend/app/modules/notifications/models.py +32 -0
- backend/app/modules/notifications/repository.py +38 -0
backend/app/common/academy_access.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Who may act for an academy (a team) and which players they can see. Every coach-side module uses this.
|
| 2 |
+
|
| 3 |
+
The team owner (teams.coach_id) is the implicit admin with every permission. Other staff need an active
|
| 4 |
+
academy_memberships row. Paused or removed staff get no academy access, even with an
|
| 5 |
+
unexpired token: a paused coach gets 403 on coach endpoints, a removed one is a coach with no academy.
|
| 6 |
+
A coach sees: every team player if admin or sees_all; otherwise players on their own roster (coach_players)
|
| 7 |
+
plus players in groups they coach. A player's coach_can_see_sessions=false hides their sessions from coaches.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from dataclasses import dataclass, field
|
| 11 |
+
from typing import Annotated
|
| 12 |
+
from uuid import UUID
|
| 13 |
+
|
| 14 |
+
from fastapi import Depends
|
| 15 |
+
from sqlalchemy import select, union
|
| 16 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
+
|
| 18 |
+
from app.core.dependencies import CurrentAccount, Db
|
| 19 |
+
from app.core.errors import Forbidden, NotFound
|
| 20 |
+
from app.modules.academy.models import AcademyMembership, CoachPlayer, GroupCoach, GroupPlayer
|
| 21 |
+
from app.modules.accounts.models import Account
|
| 22 |
+
from app.modules.settings.models import UserSettings
|
| 23 |
+
from app.modules.teams.models import Team
|
| 24 |
+
|
| 25 |
+
PERMISSIONS = ("review", "drills", "goals", "library", "earnings")
|
| 26 |
+
ROLE_PERMISSIONS: dict[str, dict[str, bool]] = {
|
| 27 |
+
"admin": dict.fromkeys(PERMISSIONS, True),
|
| 28 |
+
"coach": {"review": True, "drills": True, "goals": True, "library": False, "earnings": False},
|
| 29 |
+
"assistant": {"review": True, "drills": False, "goals": False, "library": False, "earnings": False},
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def normalize_permissions(role: str, requested: dict[str, bool] | None = None) -> dict[str, bool]:
|
| 34 |
+
"""Role defaults, overridden by requested values. Admins always have all; assistants never drills/goals."""
|
| 35 |
+
perms = {**ROLE_PERMISSIONS[role], **(requested or {})}
|
| 36 |
+
if role == "admin":
|
| 37 |
+
return dict(ROLE_PERMISSIONS["admin"])
|
| 38 |
+
if role == "assistant":
|
| 39 |
+
perms.update(drills=False, goals=False)
|
| 40 |
+
return {k: bool(perms.get(k, False)) for k in PERMISSIONS}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class Staff:
|
| 45 |
+
"""The caller acting as a coach. team_id is None for a coach account that has no academy yet."""
|
| 46 |
+
|
| 47 |
+
account: Account
|
| 48 |
+
team_id: UUID | None
|
| 49 |
+
role: str # admin | coach | assistant
|
| 50 |
+
sees_all: bool
|
| 51 |
+
permissions: dict[str, bool] = field(default_factory=dict)
|
| 52 |
+
is_owner: bool = False
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def id(self) -> UUID:
|
| 56 |
+
return self.account.id
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
def is_admin(self) -> bool:
|
| 60 |
+
return self.team_id is not None and self.role == "admin"
|
| 61 |
+
|
| 62 |
+
def require(self, permission: str) -> None:
|
| 63 |
+
if self.team_id is None or not self.permissions.get(permission, False):
|
| 64 |
+
raise Forbidden("Your academy role does not allow this.")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
async def staff_context(db: AsyncSession, account: Account) -> Staff | None:
|
| 68 |
+
team_id = await db.scalar(select(Team.id).where(Team.coach_id == account.id))
|
| 69 |
+
if team_id is not None:
|
| 70 |
+
return Staff(account, team_id, "admin", True, normalize_permissions("admin"), is_owner=True)
|
| 71 |
+
membership = await db.scalar(select(AcademyMembership).where(
|
| 72 |
+
AcademyMembership.account_id == account.id, AcademyMembership.status == "active")
|
| 73 |
+
.order_by(AcademyMembership.created_at.desc()).limit(1))
|
| 74 |
+
if membership is not None:
|
| 75 |
+
return Staff(account, membership.team_id, membership.role, membership.sees_all or membership.role == "admin",
|
| 76 |
+
normalize_permissions(membership.role, membership.permissions))
|
| 77 |
+
paused = await db.scalar(select(AcademyMembership.id).where(
|
| 78 |
+
AcademyMembership.account_id == account.id, AcademyMembership.status == "paused").limit(1))
|
| 79 |
+
if account.role == "coach" and paused is None:
|
| 80 |
+
return Staff(account, None, "coach", False, {})
|
| 81 |
+
return None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
async def _staff(db: Db, account: CurrentAccount) -> Staff:
|
| 85 |
+
staff = await staff_context(db, account)
|
| 86 |
+
if staff is None:
|
| 87 |
+
raise Forbidden("Only coaches can do this.")
|
| 88 |
+
return staff
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
async def _admin(staff: Annotated[Staff, Depends(_staff)]) -> Staff:
|
| 92 |
+
if not staff.is_admin:
|
| 93 |
+
raise Forbidden("Only academy admins can do this.")
|
| 94 |
+
return staff
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
CurrentStaff = Annotated[Staff, Depends(_staff)]
|
| 98 |
+
CurrentAdmin = Annotated[Staff, Depends(_admin)]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def visible_players_query(staff: Staff):
|
| 102 |
+
"""SELECT of the account ids of players this staff member can see (empty when there is no team)."""
|
| 103 |
+
on_team = select(Account.id).where(Account.team_id == staff.team_id, Account.role == "player")
|
| 104 |
+
if staff.team_id is None:
|
| 105 |
+
return on_team.where(False)
|
| 106 |
+
if staff.sees_all:
|
| 107 |
+
return on_team
|
| 108 |
+
rostered = select(CoachPlayer.player_id).where(CoachPlayer.team_id == staff.team_id,
|
| 109 |
+
CoachPlayer.coach_id == staff.id)
|
| 110 |
+
grouped = (select(GroupPlayer.player_id).join(GroupCoach, GroupCoach.group_id == GroupPlayer.group_id)
|
| 111 |
+
.where(GroupCoach.coach_id == staff.id))
|
| 112 |
+
return on_team.where(Account.id.in_(union(rostered, grouped).subquery().select()))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
async def visible_player_ids(db: AsyncSession, staff: Staff) -> list[UUID]:
|
| 116 |
+
return list((await db.scalars(visible_players_query(staff))).all())
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
async def can_see_player(db: AsyncSession, staff: Staff, player_id: UUID) -> bool:
|
| 120 |
+
query = visible_players_query(staff).where(Account.id == player_id)
|
| 121 |
+
return await db.scalar(query) is not None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
async def require_player(db: AsyncSession, staff: Staff, player_id: UUID) -> Account:
|
| 125 |
+
"""The player, if this staff member can see them; otherwise 404 (no existence leak)."""
|
| 126 |
+
if not await can_see_player(db, staff, player_id):
|
| 127 |
+
raise NotFound("Player not on your team.", code="PLAYER_NOT_ON_TEAM")
|
| 128 |
+
return await db.get(Account, player_id) # type: ignore[return-value]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
async def sessions_shared(db: AsyncSession, player_id: UUID) -> bool:
|
| 132 |
+
"""False when the player turned off coach_can_see_sessions (no row means the default, true)."""
|
| 133 |
+
value = await db.scalar(select(UserSettings.coach_can_see_sessions).where(UserSettings.account_id == player_id))
|
| 134 |
+
return True if value is None else value
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
async def coaches_of_player(db: AsyncSession, player: Account) -> list[UUID]:
|
| 138 |
+
"""Account ids of every active staff member who can see this player (for alerts)."""
|
| 139 |
+
if player.team_id is None:
|
| 140 |
+
return []
|
| 141 |
+
owner = await db.scalar(select(Team.coach_id).where(Team.id == player.team_id))
|
| 142 |
+
ids = {owner} if owner else set()
|
| 143 |
+
rows = await db.execute(select(AcademyMembership.account_id, AcademyMembership.sees_all, AcademyMembership.role)
|
| 144 |
+
.where(AcademyMembership.team_id == player.team_id, AcademyMembership.status == "active"))
|
| 145 |
+
rostered = set((await db.scalars(select(CoachPlayer.coach_id).where(CoachPlayer.player_id == player.id))).all())
|
| 146 |
+
grouped = set((await db.scalars(select(GroupCoach.coach_id).join(
|
| 147 |
+
GroupPlayer, GroupPlayer.group_id == GroupCoach.group_id).where(GroupPlayer.player_id == player.id))).all())
|
| 148 |
+
for account_id, sees_all, role in rows:
|
| 149 |
+
if sees_all or role == "admin" or account_id in rostered or account_id in grouped:
|
| 150 |
+
ids.add(account_id)
|
| 151 |
+
return list(ids)
|
backend/app/common/notify.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Create an in-app notification and push it. Used by every module that produces a notification.
|
| 2 |
+
|
| 3 |
+
The inbox row is written in the caller's transaction (deduplicated by recipient + event_key, so a retried
|
| 4 |
+
request never creates a second one). The push is best effort and honours the recipient's preference flag.
|
| 5 |
+
Push data carries notification_id, kind and target_json; review/session pushes keep the legacy
|
| 6 |
+
type=review.received + session_id keys so older app builds still route them.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
from uuid import UUID
|
| 12 |
+
|
| 13 |
+
from sqlalchemy import delete, select
|
| 14 |
+
from sqlalchemy.dialects.postgresql import insert
|
| 15 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 16 |
+
|
| 17 |
+
from app.integrations.push import PushClient
|
| 18 |
+
from app.modules.devices.models import Device
|
| 19 |
+
from app.modules.notifications.models import Notification
|
| 20 |
+
from app.modules.settings.models import UserSettings
|
| 21 |
+
|
| 22 |
+
log = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
# kind -> the user_settings flag that turns its push off
|
| 25 |
+
PREFERENCE = {"review": "notify_coach", "drill": "notify_drills", "armcare": "notify_coach",
|
| 26 |
+
"result": "notify_results", "report": "notify_weekly"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
async def notify(db: AsyncSession, push: PushClient | None, recipient_id: UUID, *, kind: str, title: str,
|
| 30 |
+
body: str = "", target: dict | None = None, event_key: str) -> UUID | None:
|
| 31 |
+
"""Returns the notification id, or None when this event was already delivered to this recipient."""
|
| 32 |
+
target = {k: str(v) for k, v in (target or {}).items()}
|
| 33 |
+
notification_id = await db.scalar(
|
| 34 |
+
insert(Notification).values(recipient_id=recipient_id, kind=kind, title=title[:120], body=body[:300],
|
| 35 |
+
target=target, event_key=event_key[:160])
|
| 36 |
+
.on_conflict_do_nothing(index_elements=["recipient_id", "event_key"]).returning(Notification.id))
|
| 37 |
+
if notification_id is None or push is None:
|
| 38 |
+
return notification_id
|
| 39 |
+
flag = PREFERENCE.get(kind)
|
| 40 |
+
if flag and await db.scalar(select(getattr(UserSettings, flag)).where(UserSettings.account_id == recipient_id)) \
|
| 41 |
+
is False:
|
| 42 |
+
return notification_id
|
| 43 |
+
tokens = list((await db.scalars(select(Device.push_token).where(Device.account_id == recipient_id))).all())
|
| 44 |
+
if not tokens:
|
| 45 |
+
return notification_id
|
| 46 |
+
data = {"notification_id": str(notification_id), "kind": kind, "target_json": json.dumps(target)}
|
| 47 |
+
if kind == "review" and "session_id" in target:
|
| 48 |
+
data.update(type="review.received", session_id=target["session_id"])
|
| 49 |
+
try:
|
| 50 |
+
dead = await push.send(tokens, data, notification={"title": title, "body": body})
|
| 51 |
+
except Exception: # a push failure must never fail the request
|
| 52 |
+
log.exception("push: %s failed", kind)
|
| 53 |
+
return notification_id
|
| 54 |
+
if dead:
|
| 55 |
+
await db.execute(delete(Device).where(Device.push_token.in_(dead)))
|
| 56 |
+
return notification_id
|
backend/app/common/schemas.py
CHANGED
|
@@ -1,6 +1,8 @@
|
|
| 1 |
"""Base request/response models and the list envelope."""
|
| 2 |
|
|
|
|
| 3 |
from typing import Generic, TypeVar
|
|
|
|
| 4 |
|
| 5 |
from pydantic import BaseModel, ConfigDict
|
| 6 |
|
|
@@ -26,3 +28,12 @@ class Items(ResponseModel, Generic[T]):
|
|
| 26 |
"""A complete (unpaginated) list."""
|
| 27 |
|
| 28 |
items: list[T]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""Base request/response models and the list envelope."""
|
| 2 |
|
| 3 |
+
from datetime import datetime
|
| 4 |
from typing import Generic, TypeVar
|
| 5 |
+
from uuid import UUID
|
| 6 |
|
| 7 |
from pydantic import BaseModel, ConfigDict
|
| 8 |
|
|
|
|
| 28 |
"""A complete (unpaginated) list."""
|
| 29 |
|
| 30 |
items: list[T]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class MediaRef(ResponseModel):
|
| 34 |
+
"""A short-lived authorised read URL for stored media. Refetch the owning resource when it expires."""
|
| 35 |
+
|
| 36 |
+
upload_id: UUID
|
| 37 |
+
url: str
|
| 38 |
+
expires_at: datetime
|
| 39 |
+
seconds: float | None = None
|
backend/app/core/config.py
CHANGED
|
@@ -51,6 +51,10 @@ class Settings(BaseSettings):
|
|
| 51 |
max_thumbnail_bytes: int = 5 * 1024 * 1024
|
| 52 |
max_video_seconds: float = 60.0
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
# Plans
|
| 55 |
free_weekly_limit: int = 3
|
| 56 |
entitlement_window_days: int = 7
|
|
|
|
| 51 |
max_thumbnail_bytes: int = 5 * 1024 * 1024
|
| 52 |
max_video_seconds: float = 60.0
|
| 53 |
|
| 54 |
+
# Consent: when true, new analysis needs an accepted consent event. A withdrawal always blocks.
|
| 55 |
+
require_analysis_consent: bool = False
|
| 56 |
+
consent_versions: list[str] = ["1.0"]
|
| 57 |
+
|
| 58 |
# Plans
|
| 59 |
free_weekly_limit: int = 3
|
| 60 |
entitlement_window_days: int = 7
|
backend/app/jobs/exports.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export worker: `python -m app.jobs.exports`.
|
| 2 |
+
|
| 3 |
+
Processes queued 'videos' export jobs: presigns a download link for each of the owner's non-deleted session videos
|
| 4 |
+
and emails the list to the account address. The job ends 'ready' (links expire at expires_at) or 'failed'.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import asyncio
|
| 8 |
+
import logging
|
| 9 |
+
from datetime import UTC, datetime, timedelta
|
| 10 |
+
|
| 11 |
+
from sqlalchemy import select
|
| 12 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 13 |
+
|
| 14 |
+
from app.core.config import get_settings
|
| 15 |
+
from app.core.database import get_session_factory
|
| 16 |
+
from app.integrations.email import EmailClient, get_email_client
|
| 17 |
+
from app.integrations.storage import StorageClient, get_storage
|
| 18 |
+
from app.modules.accounts.models import Account
|
| 19 |
+
from app.modules.sessions.models import SwingSession
|
| 20 |
+
from app.modules.settings.models import ExportJob
|
| 21 |
+
from app.modules.uploads.models import Upload
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
async def run_exports(db: AsyncSession, storage: StorageClient, email: EmailClient,
|
| 27 |
+
now: datetime | None = None) -> dict[str, int]:
|
| 28 |
+
now = now or datetime.now(UTC)
|
| 29 |
+
ttl = get_settings().download_url_ttl_s
|
| 30 |
+
jobs = (await db.scalars(select(ExportJob).where(ExportJob.scope == "videos", ExportJob.status == "queued")
|
| 31 |
+
.order_by(ExportJob.created_at).with_for_update(skip_locked=True))).all()
|
| 32 |
+
counts = {"ready": 0, "failed": 0}
|
| 33 |
+
for job in jobs:
|
| 34 |
+
try:
|
| 35 |
+
account = await db.get(Account, job.requester_id)
|
| 36 |
+
rows = (await db.execute(
|
| 37 |
+
select(SwingSession.created_at, Upload.object_key)
|
| 38 |
+
.join(Upload, Upload.id == SwingSession.video_upload_id)
|
| 39 |
+
.where(SwingSession.owner_id == job.requester_id, SwingSession.deleted_at.is_(None))
|
| 40 |
+
.order_by(SwingSession.created_at))).all()
|
| 41 |
+
links = [f"{created.date().isoformat()}: {storage.presign_get(key)}" for created, key in rows]
|
| 42 |
+
body = ("Here are the links to your videos. They expire in "
|
| 43 |
+
f"{max(ttl // 60, 1)} minutes.\n\n" + ("\n".join(links) if links else "You have no videos."))
|
| 44 |
+
await email.send(account.email, "Your videos", body)
|
| 45 |
+
job.status, job.expires_at, job.error_code = "ready", now + timedelta(seconds=ttl), None
|
| 46 |
+
counts["ready"] += 1
|
| 47 |
+
except Exception:
|
| 48 |
+
log.exception("export %s failed", job.id)
|
| 49 |
+
job.status, job.error_code = "failed", "DELIVERY_FAILED"
|
| 50 |
+
counts["failed"] += 1
|
| 51 |
+
await db.commit()
|
| 52 |
+
log.info("exports done: %s", counts)
|
| 53 |
+
return counts
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
async def main() -> dict[str, int]:
|
| 57 |
+
async with get_session_factory()() as db:
|
| 58 |
+
return await run_exports(db, get_storage(), get_email_client())
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if __name__ == "__main__":
|
| 62 |
+
logging.basicConfig(level=logging.INFO)
|
| 63 |
+
print(asyncio.run(main()))
|
backend/app/main.py
CHANGED
|
@@ -11,24 +11,35 @@ from pydantic.json_schema import models_json_schema
|
|
| 11 |
|
| 12 |
from app.core.config import get_settings
|
| 13 |
from app.core.errors import register_error_handlers, unexpected_error_response
|
|
|
|
|
|
|
| 14 |
from app.modules.accounts.controller import router as accounts_router
|
| 15 |
from app.modules.api_audit.controller import router as audit_router
|
| 16 |
from app.modules.api_audit.middleware import ApiAuditMiddleware
|
|
|
|
|
|
|
| 17 |
from app.modules.auth.controller import router as auth_router
|
| 18 |
from app.modules.billing.controller import router as billing_router
|
| 19 |
from app.modules.catalog.controller import router as catalog_router
|
| 20 |
from app.modules.coach.controller import router as coach_router
|
| 21 |
from app.modules.devices.controller import router as devices_router
|
| 22 |
from app.modules.drills.controller import router as drills_router
|
|
|
|
|
|
|
|
|
|
| 23 |
from app.modules.reviews.controller import router as reviews_router
|
| 24 |
from app.modules.sessions.controller import router as sessions_router
|
|
|
|
| 25 |
from app.modules.swing_reports.controller import router as swing_reports_router
|
| 26 |
from app.modules.teams.controller import router as teams_router
|
|
|
|
| 27 |
from app.modules.uploads.controller import router as uploads_router
|
| 28 |
|
| 29 |
ROUTERS = (
|
| 30 |
auth_router, accounts_router, teams_router, uploads_router, sessions_router, swing_reports_router,
|
| 31 |
drills_router, reviews_router, coach_router, devices_router, billing_router, catalog_router, audit_router,
|
|
|
|
|
|
|
| 32 |
)
|
| 33 |
|
| 34 |
|
|
|
|
| 11 |
|
| 12 |
from app.core.config import get_settings
|
| 13 |
from app.core.errors import register_error_handlers, unexpected_error_response
|
| 14 |
+
from app.modules.academy_org.controller import router as academy_org_router
|
| 15 |
+
from app.modules.academy_staff.controller import router as academy_staff_router
|
| 16 |
from app.modules.accounts.controller import router as accounts_router
|
| 17 |
from app.modules.api_audit.controller import router as audit_router
|
| 18 |
from app.modules.api_audit.middleware import ApiAuditMiddleware
|
| 19 |
+
from app.modules.arm_care.controller import router as arm_care_router
|
| 20 |
+
from app.modules.assignments.controller import router as assignments_router
|
| 21 |
from app.modules.auth.controller import router as auth_router
|
| 22 |
from app.modules.billing.controller import router as billing_router
|
| 23 |
from app.modules.catalog.controller import router as catalog_router
|
| 24 |
from app.modules.coach.controller import router as coach_router
|
| 25 |
from app.modules.devices.controller import router as devices_router
|
| 26 |
from app.modules.drills.controller import router as drills_router
|
| 27 |
+
from app.modules.goals.controller import router as goals_router
|
| 28 |
+
from app.modules.notifications.controller import router as notifications_router
|
| 29 |
+
from app.modules.reporting.controller import router as reporting_router
|
| 30 |
from app.modules.reviews.controller import router as reviews_router
|
| 31 |
from app.modules.sessions.controller import router as sessions_router
|
| 32 |
+
from app.modules.settings.controller import router as settings_router
|
| 33 |
from app.modules.swing_reports.controller import router as swing_reports_router
|
| 34 |
from app.modules.teams.controller import router as teams_router
|
| 35 |
+
from app.modules.threads.controller import router as threads_router
|
| 36 |
from app.modules.uploads.controller import router as uploads_router
|
| 37 |
|
| 38 |
ROUTERS = (
|
| 39 |
auth_router, accounts_router, teams_router, uploads_router, sessions_router, swing_reports_router,
|
| 40 |
drills_router, reviews_router, coach_router, devices_router, billing_router, catalog_router, audit_router,
|
| 41 |
+
settings_router, notifications_router, threads_router, goals_router, assignments_router, arm_care_router,
|
| 42 |
+
academy_staff_router, academy_org_router, reporting_router,
|
| 43 |
)
|
| 44 |
|
| 45 |
|
backend/app/models.py
CHANGED
|
@@ -1,19 +1,39 @@
|
|
| 1 |
"""Imports every model so Base.metadata is complete (Alembic, tests)."""
|
| 2 |
|
| 3 |
from app.common.base_model import Base
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from app.modules.accounts.models import Account
|
| 5 |
from app.modules.api_audit.models import ApiRequestLog
|
|
|
|
|
|
|
| 6 |
from app.modules.auth.models import AuthIdentity, PasswordReset, RefreshToken
|
| 7 |
from app.modules.billing.models import Subscription
|
| 8 |
from app.modules.devices.models import Device
|
| 9 |
from app.modules.drills.models import DrillLog
|
|
|
|
| 10 |
from app.modules.idempotency.models import IdempotencyKey
|
|
|
|
| 11 |
from app.modules.reviews.models import Review
|
| 12 |
from app.modules.sessions.models import SwingSession
|
|
|
|
| 13 |
from app.modules.teams.models import Team
|
|
|
|
| 14 |
from app.modules.uploads.models import Upload
|
| 15 |
|
| 16 |
__all__ = [
|
| 17 |
"Base", "Account", "AuthIdentity", "PasswordReset", "RefreshToken", "Subscription", "Device", "DrillLog",
|
| 18 |
"IdempotencyKey", "Review", "SwingSession", "Team", "Upload", "ApiRequestLog",
|
|
|
|
|
|
|
|
|
|
| 19 |
]
|
|
|
|
| 1 |
"""Imports every model so Base.metadata is complete (Alembic, tests)."""
|
| 2 |
|
| 3 |
from app.common.base_model import Base
|
| 4 |
+
from app.modules.academy.models import (
|
| 5 |
+
AcademyMembership,
|
| 6 |
+
CoachAccessRequest,
|
| 7 |
+
CoachNote,
|
| 8 |
+
CoachPlayer,
|
| 9 |
+
GroupCoach,
|
| 10 |
+
GroupPlayer,
|
| 11 |
+
LibraryDrill,
|
| 12 |
+
PlayerGroup,
|
| 13 |
+
StaffCode,
|
| 14 |
+
)
|
| 15 |
from app.modules.accounts.models import Account
|
| 16 |
from app.modules.api_audit.models import ApiRequestLog
|
| 17 |
+
from app.modules.arm_care.models import ArmFeel, ArmOuting
|
| 18 |
+
from app.modules.assignments.models import AssignmentSet, DrillAssignment
|
| 19 |
from app.modules.auth.models import AuthIdentity, PasswordReset, RefreshToken
|
| 20 |
from app.modules.billing.models import Subscription
|
| 21 |
from app.modules.devices.models import Device
|
| 22 |
from app.modules.drills.models import DrillLog
|
| 23 |
+
from app.modules.goals.models import Goal
|
| 24 |
from app.modules.idempotency.models import IdempotencyKey
|
| 25 |
+
from app.modules.notifications.models import Notification
|
| 26 |
from app.modules.reviews.models import Review
|
| 27 |
from app.modules.sessions.models import SwingSession
|
| 28 |
+
from app.modules.settings.models import ConsentEvent, ExportJob, UserSettings
|
| 29 |
from app.modules.teams.models import Team
|
| 30 |
+
from app.modules.threads.models import Message, Thread
|
| 31 |
from app.modules.uploads.models import Upload
|
| 32 |
|
| 33 |
__all__ = [
|
| 34 |
"Base", "Account", "AuthIdentity", "PasswordReset", "RefreshToken", "Subscription", "Device", "DrillLog",
|
| 35 |
"IdempotencyKey", "Review", "SwingSession", "Team", "Upload", "ApiRequestLog",
|
| 36 |
+
"AcademyMembership", "CoachAccessRequest", "CoachNote", "CoachPlayer", "GroupCoach", "GroupPlayer",
|
| 37 |
+
"LibraryDrill", "PlayerGroup", "StaffCode", "ArmFeel", "ArmOuting", "AssignmentSet", "DrillAssignment",
|
| 38 |
+
"Goal", "Notification", "ConsentEvent", "ExportJob", "UserSettings", "Message", "Thread",
|
| 39 |
]
|
backend/app/modules/academy/__init__.py
ADDED
|
File without changes
|
backend/app/modules/academy/models.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Academy (= an existing team) staff and organisation. The team's owner (teams.coach_id) is the implicit admin;
|
| 2 |
+
other staff have a membership row. Players belong through accounts.team_id as before.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import uuid
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
|
| 8 |
+
from sqlalchemy import (
|
| 9 |
+
Boolean,
|
| 10 |
+
CheckConstraint,
|
| 11 |
+
DateTime,
|
| 12 |
+
ForeignKey,
|
| 13 |
+
Index,
|
| 14 |
+
Integer,
|
| 15 |
+
SmallInteger,
|
| 16 |
+
String,
|
| 17 |
+
Text,
|
| 18 |
+
UniqueConstraint,
|
| 19 |
+
text,
|
| 20 |
+
)
|
| 21 |
+
from sqlalchemy.dialects.postgresql import ARRAY, JSONB, UUID
|
| 22 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 23 |
+
|
| 24 |
+
from app.common.base_model import Base, CreatedAtMixin, IdMixin, TimestampMixin
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _team() -> Mapped[uuid.UUID]:
|
| 28 |
+
return mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="CASCADE"), index=True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _account(nullable: bool = False) -> Mapped:
|
| 32 |
+
return mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL" if nullable else "CASCADE"))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class AcademyMembership(IdMixin, CreatedAtMixin, Base):
|
| 36 |
+
"""A staff member of a team. permissions: {review, drills, goals, library, earnings} effective booleans."""
|
| 37 |
+
|
| 38 |
+
__tablename__ = "academy_memberships"
|
| 39 |
+
__table_args__ = (
|
| 40 |
+
UniqueConstraint("team_id", "account_id"),
|
| 41 |
+
CheckConstraint("role IN ('admin', 'coach', 'assistant')", name="role"),
|
| 42 |
+
CheckConstraint("status IN ('active', 'paused', 'removed')", name="status"),
|
| 43 |
+
Index("ix_academy_memberships_account_id", "account_id"),
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
team_id: Mapped[uuid.UUID] = _team()
|
| 47 |
+
account_id: Mapped[uuid.UUID] = _account()
|
| 48 |
+
role: Mapped[str] = mapped_column(String(10))
|
| 49 |
+
status: Mapped[str] = mapped_column(String(8), server_default="active")
|
| 50 |
+
sees_all: Mapped[bool] = mapped_column(Boolean, server_default="false")
|
| 51 |
+
permissions: Mapped[dict] = mapped_column(JSONB)
|
| 52 |
+
joined_with: Mapped[str | None] = mapped_column(String(16))
|
| 53 |
+
version: Mapped[int] = mapped_column(Integer, server_default="1")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class StaffCode(IdMixin, CreatedAtMixin, Base):
|
| 57 |
+
"""A code staff use to apply. uses is a counter locked with the row so the last use cannot be taken twice."""
|
| 58 |
+
|
| 59 |
+
__tablename__ = "staff_codes"
|
| 60 |
+
__table_args__ = (
|
| 61 |
+
CheckConstraint("role IN ('coach', 'assistant')", name="role"),
|
| 62 |
+
CheckConstraint("approval IN ('admin', 'auto')", name="approval"),
|
| 63 |
+
CheckConstraint("uses >= 0 AND uses <= max_uses", name="uses"),
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
team_id: Mapped[uuid.UUID] = _team()
|
| 67 |
+
code: Mapped[str] = mapped_column(String(16), unique=True)
|
| 68 |
+
role: Mapped[str] = mapped_column(String(10))
|
| 69 |
+
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
| 70 |
+
max_uses: Mapped[int] = mapped_column(SmallInteger)
|
| 71 |
+
uses: Mapped[int] = mapped_column(SmallInteger, server_default="0")
|
| 72 |
+
approval: Mapped[str] = mapped_column(String(6))
|
| 73 |
+
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
| 74 |
+
created_by_id: Mapped[uuid.UUID | None] = _account(nullable=True)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class CoachAccessRequest(IdMixin, CreatedAtMixin, Base):
|
| 78 |
+
"""An application to coach at a team. created_at is sent_at. At most one pending request per applicant."""
|
| 79 |
+
|
| 80 |
+
__tablename__ = "coach_access_requests"
|
| 81 |
+
__table_args__ = (
|
| 82 |
+
CheckConstraint("status IN ('pending', 'approved', 'declined')", name="status"),
|
| 83 |
+
Index("uq_coach_access_requests_pending", "applicant_id", unique=True,
|
| 84 |
+
postgresql_where=text("status = 'pending'")),
|
| 85 |
+
Index("ix_coach_access_requests_team_id_created_at", "team_id", text("created_at DESC")),
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
applicant_id: Mapped[uuid.UUID] = _account()
|
| 89 |
+
team_id: Mapped[uuid.UUID] = _team()
|
| 90 |
+
staff_code_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 91 |
+
UUID(as_uuid=True), ForeignKey("staff_codes.id", ondelete="SET NULL")
|
| 92 |
+
)
|
| 93 |
+
code: Mapped[str] = mapped_column(String(16))
|
| 94 |
+
status: Mapped[str] = mapped_column(String(8), server_default="pending")
|
| 95 |
+
decided_by_id: Mapped[uuid.UUID | None] = _account(nullable=True)
|
| 96 |
+
decided_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class PlayerGroup(IdMixin, CreatedAtMixin, Base):
|
| 100 |
+
__tablename__ = "player_groups"
|
| 101 |
+
__table_args__ = (
|
| 102 |
+
CheckConstraint("focus IN ('Hitting', 'Pitching', 'Both')", name="focus"),
|
| 103 |
+
Index("uq_player_groups_team_id_name", "team_id", text("lower(name)"), unique=True),
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
team_id: Mapped[uuid.UUID] = _team()
|
| 107 |
+
name: Mapped[str] = mapped_column(String(80))
|
| 108 |
+
focus: Mapped[str] = mapped_column(String(8))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class GroupPlayer(Base):
|
| 112 |
+
__tablename__ = "group_players"
|
| 113 |
+
|
| 114 |
+
group_id: Mapped[uuid.UUID] = mapped_column(
|
| 115 |
+
UUID(as_uuid=True), ForeignKey("player_groups.id", ondelete="CASCADE"), primary_key=True
|
| 116 |
+
)
|
| 117 |
+
player_id: Mapped[uuid.UUID] = mapped_column(
|
| 118 |
+
UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True, index=True
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class GroupCoach(Base):
|
| 123 |
+
__tablename__ = "group_coaches"
|
| 124 |
+
|
| 125 |
+
group_id: Mapped[uuid.UUID] = mapped_column(
|
| 126 |
+
UUID(as_uuid=True), ForeignKey("player_groups.id", ondelete="CASCADE"), primary_key=True
|
| 127 |
+
)
|
| 128 |
+
coach_id: Mapped[uuid.UUID] = mapped_column(
|
| 129 |
+
UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True, index=True
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class CoachPlayer(CreatedAtMixin, Base):
|
| 134 |
+
"""A player on one staff coach's own roster (in addition to group and sees_all visibility)."""
|
| 135 |
+
|
| 136 |
+
__tablename__ = "coach_players"
|
| 137 |
+
|
| 138 |
+
team_id: Mapped[uuid.UUID] = _team()
|
| 139 |
+
coach_id: Mapped[uuid.UUID] = mapped_column(
|
| 140 |
+
UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True
|
| 141 |
+
)
|
| 142 |
+
player_id: Mapped[uuid.UUID] = mapped_column(
|
| 143 |
+
UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"), primary_key=True, index=True
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class CoachNote(IdMixin, TimestampMixin, Base):
|
| 148 |
+
"""A coach's private note on a player; only that coach can read it."""
|
| 149 |
+
|
| 150 |
+
__tablename__ = "coach_notes"
|
| 151 |
+
__table_args__ = (UniqueConstraint("team_id", "coach_id", "player_id"),)
|
| 152 |
+
|
| 153 |
+
team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="CASCADE"))
|
| 154 |
+
coach_id: Mapped[uuid.UUID] = _account()
|
| 155 |
+
player_id: Mapped[uuid.UUID] = _account()
|
| 156 |
+
text: Mapped[str] = mapped_column(Text, server_default="")
|
| 157 |
+
version: Mapped[int] = mapped_column(Integer, server_default="0")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class LibraryDrill(IdMixin, CreatedAtMixin, Base):
|
| 161 |
+
"""A team's own drill video. Assignments snapshot name/fixes, so deleting one never rewrites history."""
|
| 162 |
+
|
| 163 |
+
__tablename__ = "library_drills"
|
| 164 |
+
__table_args__ = (CheckConstraint("mode IN ('h', 'p')", name="mode"),)
|
| 165 |
+
|
| 166 |
+
team_id: Mapped[uuid.UUID] = _team()
|
| 167 |
+
author_id: Mapped[uuid.UUID | None] = _account(nullable=True)
|
| 168 |
+
name: Mapped[str] = mapped_column(String(120))
|
| 169 |
+
fixes: Mapped[str] = mapped_column(String(500), server_default="")
|
| 170 |
+
mode: Mapped[str] = mapped_column(String(1))
|
| 171 |
+
fault_tags: Mapped[list[str]] = mapped_column(ARRAY(String(64)), server_default=text("'{}'"))
|
| 172 |
+
upload_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 173 |
+
UUID(as_uuid=True), ForeignKey("uploads.id", ondelete="SET NULL")
|
| 174 |
+
)
|
backend/app/modules/academy_org/__init__.py
ADDED
|
File without changes
|
backend/app/modules/academy_org/controller.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""N28-N33 groups, private notes and roster additions; N35-N36 the academy drill library."""
|
| 2 |
+
|
| 3 |
+
from typing import Annotated
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, Depends, Header, Query
|
| 7 |
+
|
| 8 |
+
from app.common.academy_access import CurrentAdmin, CurrentStaff
|
| 9 |
+
from app.common.schemas import Page
|
| 10 |
+
from app.core.dependencies import Db, Paging, Storage
|
| 11 |
+
from app.modules.academy_org.schemas import (
|
| 12 |
+
GroupEnvelope,
|
| 13 |
+
GroupIn,
|
| 14 |
+
GroupOut,
|
| 15 |
+
LibraryDrillIn,
|
| 16 |
+
LibraryDrillOut,
|
| 17 |
+
LibraryEnvelope,
|
| 18 |
+
MemberOut,
|
| 19 |
+
Mode,
|
| 20 |
+
NoteEnvelope,
|
| 21 |
+
NoteIn,
|
| 22 |
+
RosterAddIn,
|
| 23 |
+
RosterAddOut,
|
| 24 |
+
)
|
| 25 |
+
from app.modules.academy_org.service import OrgService
|
| 26 |
+
from app.modules.idempotency.service import run_idempotent
|
| 27 |
+
|
| 28 |
+
router = APIRouter(prefix="/v1", tags=["academy_org"])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_org_service(db: Db, storage: Storage) -> OrgService:
|
| 32 |
+
return OrgService(db, storage)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
Service = Annotated[OrgService, Depends(get_org_service)]
|
| 36 |
+
IdempotencyKey = Annotated[str | None, Header(max_length=128)]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@router.get("/academy/groups", response_model=Page[GroupOut])
|
| 40 |
+
async def list_groups(staff: CurrentStaff, service: Service, paging: Paging) -> Page[GroupOut]:
|
| 41 |
+
return await service.list_groups(staff, paging)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@router.post("/academy/groups", status_code=201, response_model=GroupEnvelope)
|
| 45 |
+
async def create_group(body: GroupIn, staff: CurrentAdmin, service: Service, db: Db,
|
| 46 |
+
idempotency_key: IdempotencyKey = None):
|
| 47 |
+
async def handler() -> GroupEnvelope:
|
| 48 |
+
return GroupEnvelope(group=await service.create_group(staff, body))
|
| 49 |
+
|
| 50 |
+
return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=201)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@router.get("/coach/players/{player_id}/note", response_model=NoteEnvelope)
|
| 54 |
+
async def get_note(player_id: UUID, staff: CurrentStaff, service: Service) -> NoteEnvelope:
|
| 55 |
+
return NoteEnvelope(note=await service.get_note(staff, player_id))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@router.put("/coach/players/{player_id}/note", response_model=NoteEnvelope)
|
| 59 |
+
async def save_note(player_id: UUID, body: NoteIn, staff: CurrentStaff, service: Service) -> NoteEnvelope:
|
| 60 |
+
return NoteEnvelope(note=await service.save_note(staff, player_id, body))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@router.get("/academy/members", response_model=Page[MemberOut])
|
| 64 |
+
async def members(staff: CurrentStaff, service: Service, paging: Paging,
|
| 65 |
+
q: Annotated[str | None, Query(max_length=100)] = None) -> Page[MemberOut]:
|
| 66 |
+
return await service.members(staff, q.strip() if q else None, paging)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@router.post("/coach/roster/players", response_model=RosterAddOut)
|
| 70 |
+
async def add_roster_players(body: RosterAddIn, staff: CurrentStaff, service: Service, db: Db,
|
| 71 |
+
idempotency_key: IdempotencyKey = None):
|
| 72 |
+
async def handler() -> RosterAddOut:
|
| 73 |
+
return await service.add_to_roster(staff, body)
|
| 74 |
+
|
| 75 |
+
return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=200)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@router.get("/academy/library", response_model=Page[LibraryDrillOut])
|
| 79 |
+
async def library(staff: CurrentStaff, service: Service, paging: Paging, mode: Mode | None = None,
|
| 80 |
+
fault_tag: Annotated[str | None, Query(max_length=64)] = None) -> Page[LibraryDrillOut]:
|
| 81 |
+
return await service.library(staff, mode, fault_tag, paging)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@router.post("/academy/library", status_code=201, response_model=LibraryEnvelope)
|
| 85 |
+
async def publish_drill(body: LibraryDrillIn, staff: CurrentStaff, service: Service, db: Db,
|
| 86 |
+
idempotency_key: IdempotencyKey = None):
|
| 87 |
+
async def handler() -> LibraryEnvelope:
|
| 88 |
+
return LibraryEnvelope(drill=await service.publish_drill(staff, body))
|
| 89 |
+
|
| 90 |
+
return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=201)
|
backend/app/modules/academy_org/repository.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Groups, private coach notes, roster additions and the academy library. Database only."""
|
| 2 |
+
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from uuid import UUID
|
| 6 |
+
|
| 7 |
+
from sqlalchemy import Select, and_, or_, select
|
| 8 |
+
from sqlalchemy.dialects.postgresql import insert
|
| 9 |
+
from sqlalchemy.exc import IntegrityError
|
| 10 |
+
|
| 11 |
+
from app.common.base_repository import BaseRepository
|
| 12 |
+
from app.core.pagination import Cursor
|
| 13 |
+
from app.modules.academy.models import (
|
| 14 |
+
AcademyMembership,
|
| 15 |
+
CoachNote,
|
| 16 |
+
CoachPlayer,
|
| 17 |
+
GroupCoach,
|
| 18 |
+
GroupPlayer,
|
| 19 |
+
LibraryDrill,
|
| 20 |
+
PlayerGroup,
|
| 21 |
+
)
|
| 22 |
+
from app.modules.accounts.models import Account
|
| 23 |
+
from app.modules.teams.models import Team
|
| 24 |
+
from app.modules.uploads.models import Upload
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _after(query: Select, created_at_col, id_col, cursor: Cursor | None, limit: int) -> Select:
|
| 28 |
+
if cursor:
|
| 29 |
+
query = query.where(or_(created_at_col < cursor.created_at,
|
| 30 |
+
and_(created_at_col == cursor.created_at, id_col < cursor.id)))
|
| 31 |
+
return query.order_by(created_at_col.desc(), id_col.desc()).limit(limit)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class OrgRepository(BaseRepository[PlayerGroup]):
|
| 35 |
+
model = PlayerGroup
|
| 36 |
+
|
| 37 |
+
# ---- groups ----
|
| 38 |
+
async def groups(self, team_id: UUID, coach_id: UUID | None, cursor: Cursor | None, limit: int):
|
| 39 |
+
"""Team groups; with coach_id, only the groups that coach is on."""
|
| 40 |
+
query = select(PlayerGroup).where(PlayerGroup.team_id == team_id)
|
| 41 |
+
if coach_id is not None:
|
| 42 |
+
query = query.where(PlayerGroup.id.in_(select(GroupCoach.group_id).where(GroupCoach.coach_id == coach_id)))
|
| 43 |
+
query = _after(query, PlayerGroup.created_at, PlayerGroup.id, cursor, limit)
|
| 44 |
+
return (await self.session.scalars(query)).all()
|
| 45 |
+
|
| 46 |
+
async def group_players(self, group_ids: list[UUID]) -> dict[UUID, list[UUID]]:
|
| 47 |
+
rows = await self.session.execute(select(GroupPlayer.group_id, GroupPlayer.player_id)
|
| 48 |
+
.where(GroupPlayer.group_id.in_(group_ids)).order_by(GroupPlayer.player_id))
|
| 49 |
+
out: dict[UUID, list[UUID]] = {}
|
| 50 |
+
for group_id, player_id in rows.all():
|
| 51 |
+
out.setdefault(group_id, []).append(player_id)
|
| 52 |
+
return out
|
| 53 |
+
|
| 54 |
+
async def group_coaches(self, group_ids: list[UUID]) -> dict[UUID, list[tuple[UUID, str]]]:
|
| 55 |
+
rows = await self.session.execute(
|
| 56 |
+
select(GroupCoach.group_id, Account.id, Account.name).join(Account, Account.id == GroupCoach.coach_id)
|
| 57 |
+
.where(GroupCoach.group_id.in_(group_ids)).order_by(Account.name, Account.id))
|
| 58 |
+
out: dict[UUID, list[tuple[UUID, str]]] = {}
|
| 59 |
+
for group_id, coach_id, name in rows.all():
|
| 60 |
+
out.setdefault(group_id, []).append((coach_id, name or ""))
|
| 61 |
+
return out
|
| 62 |
+
|
| 63 |
+
async def team_player_ids(self, team_id: UUID, ids: Sequence[UUID]) -> set[UUID]:
|
| 64 |
+
query = select(Account.id).where(Account.id.in_(ids), Account.team_id == team_id, Account.role == "player")
|
| 65 |
+
return set((await self.session.scalars(query)).all())
|
| 66 |
+
|
| 67 |
+
async def team_staff_ids(self, team_id: UUID, ids: Sequence[UUID]) -> set[UUID]:
|
| 68 |
+
members = select(AcademyMembership.account_id).where(
|
| 69 |
+
AcademyMembership.team_id == team_id, AcademyMembership.status.in_(("active", "paused")),
|
| 70 |
+
AcademyMembership.account_id.in_(ids))
|
| 71 |
+
found = set((await self.session.scalars(members)).all())
|
| 72 |
+
owner = await self.session.scalar(select(Team.coach_id).where(Team.id == team_id, Team.coach_id.in_(ids)))
|
| 73 |
+
if owner is not None:
|
| 74 |
+
found.add(owner)
|
| 75 |
+
return found
|
| 76 |
+
|
| 77 |
+
async def create_group(self, team_id: UUID, name: str, focus: str, coach_ids: list[UUID],
|
| 78 |
+
player_ids: list[UUID]) -> PlayerGroup | None:
|
| 79 |
+
"""None when the name is taken (case-insensitive)."""
|
| 80 |
+
group = PlayerGroup(team_id=team_id, name=name, focus=focus)
|
| 81 |
+
try:
|
| 82 |
+
async with self.session.begin_nested():
|
| 83 |
+
self.session.add(group)
|
| 84 |
+
await self.session.flush()
|
| 85 |
+
except IntegrityError:
|
| 86 |
+
return None
|
| 87 |
+
self.session.add_all([GroupCoach(group_id=group.id, coach_id=c) for c in coach_ids])
|
| 88 |
+
self.session.add_all([GroupPlayer(group_id=group.id, player_id=p) for p in player_ids])
|
| 89 |
+
await self.session.flush()
|
| 90 |
+
return group
|
| 91 |
+
|
| 92 |
+
async def group_in_team(self, team_id: UUID, group_id: UUID) -> PlayerGroup | None:
|
| 93 |
+
return await self.session.scalar(select(PlayerGroup).where(PlayerGroup.id == group_id,
|
| 94 |
+
PlayerGroup.team_id == team_id))
|
| 95 |
+
|
| 96 |
+
async def is_group_coach(self, group_id: UUID, coach_id: UUID) -> bool:
|
| 97 |
+
return await self.session.scalar(select(GroupCoach.group_id).where(
|
| 98 |
+
GroupCoach.group_id == group_id, GroupCoach.coach_id == coach_id)) is not None
|
| 99 |
+
|
| 100 |
+
# ---- notes ----
|
| 101 |
+
async def note(self, team_id: UUID, coach_id: UUID, player_id: UUID, *, lock: bool = False) -> CoachNote | None:
|
| 102 |
+
query = select(CoachNote).where(CoachNote.team_id == team_id, CoachNote.coach_id == coach_id,
|
| 103 |
+
CoachNote.player_id == player_id)
|
| 104 |
+
if lock:
|
| 105 |
+
query = query.with_for_update()
|
| 106 |
+
return await self.session.scalar(query)
|
| 107 |
+
|
| 108 |
+
async def insert_note(self, team_id: UUID, coach_id: UUID, player_id: UUID, text: str) -> CoachNote | None:
|
| 109 |
+
"""None when a concurrent request created the note first."""
|
| 110 |
+
stmt = (insert(CoachNote).values(team_id=team_id, coach_id=coach_id, player_id=player_id, text=text,
|
| 111 |
+
version=1)
|
| 112 |
+
.on_conflict_do_nothing().returning(CoachNote.id))
|
| 113 |
+
if await self.session.scalar(stmt) is None:
|
| 114 |
+
return None
|
| 115 |
+
return await self.note(team_id, coach_id, player_id)
|
| 116 |
+
|
| 117 |
+
# ---- roster ----
|
| 118 |
+
async def members(self, team_id: UUID, coach_id: UUID, q: str | None, cursor: Cursor | None, limit: int):
|
| 119 |
+
query = (select(Account).where(
|
| 120 |
+
Account.team_id == team_id, Account.role == "player",
|
| 121 |
+
Account.id.not_in(select(CoachPlayer.player_id).where(CoachPlayer.team_id == team_id,
|
| 122 |
+
CoachPlayer.coach_id == coach_id))))
|
| 123 |
+
if q:
|
| 124 |
+
escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
| 125 |
+
query = query.where(Account.name.ilike(f"%{escaped}%", escape="\\"))
|
| 126 |
+
return (await self.session.scalars(_after(query, Account.created_at, Account.id, cursor, limit))).all()
|
| 127 |
+
|
| 128 |
+
async def player_group_ids(self, player_ids: list[UUID], team_id: UUID) -> dict[UUID, list[UUID]]:
|
| 129 |
+
rows = await self.session.execute(
|
| 130 |
+
select(GroupPlayer.player_id, GroupPlayer.group_id)
|
| 131 |
+
.join(PlayerGroup, PlayerGroup.id == GroupPlayer.group_id)
|
| 132 |
+
.where(GroupPlayer.player_id.in_(player_ids), PlayerGroup.team_id == team_id)
|
| 133 |
+
.order_by(GroupPlayer.group_id))
|
| 134 |
+
out: dict[UUID, list[UUID]] = {}
|
| 135 |
+
for player_id, group_id in rows.all():
|
| 136 |
+
out.setdefault(player_id, []).append(group_id)
|
| 137 |
+
return out
|
| 138 |
+
|
| 139 |
+
async def add_to_roster(self, team_id: UUID, coach_id: UUID, player_ids: list[UUID]) -> set[UUID]:
|
| 140 |
+
stmt = (insert(CoachPlayer).values([{"team_id": team_id, "coach_id": coach_id, "player_id": p}
|
| 141 |
+
for p in player_ids])
|
| 142 |
+
.on_conflict_do_nothing().returning(CoachPlayer.player_id))
|
| 143 |
+
return set((await self.session.scalars(stmt)).all())
|
| 144 |
+
|
| 145 |
+
async def add_to_group(self, group_id: UUID, player_ids: list[UUID]) -> None:
|
| 146 |
+
await self.session.execute(insert(GroupPlayer).values([{"group_id": group_id, "player_id": p}
|
| 147 |
+
for p in player_ids]).on_conflict_do_nothing())
|
| 148 |
+
|
| 149 |
+
# ---- library ----
|
| 150 |
+
async def library(self, team_id: UUID, mode: str | None, fault_tag: str | None, cursor: Cursor | None,
|
| 151 |
+
limit: int) -> Sequence[tuple[LibraryDrill, str | None, str | None]]:
|
| 152 |
+
"""(drill, author name, object key)."""
|
| 153 |
+
query = self._library_select().where(LibraryDrill.team_id == team_id)
|
| 154 |
+
if mode:
|
| 155 |
+
query = query.where(LibraryDrill.mode == mode)
|
| 156 |
+
if fault_tag:
|
| 157 |
+
query = query.where(LibraryDrill.fault_tags.contains([fault_tag.lower()]))
|
| 158 |
+
query = _after(query, LibraryDrill.created_at, LibraryDrill.id, cursor, limit)
|
| 159 |
+
return [tuple(r) for r in (await self.session.execute(query)).all()] # type: ignore[misc]
|
| 160 |
+
|
| 161 |
+
async def library_row(self, drill_id: UUID) -> tuple[LibraryDrill, str | None, str | None]:
|
| 162 |
+
row = (await self.session.execute(self._library_select().where(LibraryDrill.id == drill_id))).one()
|
| 163 |
+
return tuple(row) # type: ignore[return-value]
|
| 164 |
+
|
| 165 |
+
@staticmethod
|
| 166 |
+
def _library_select() -> Select:
|
| 167 |
+
return (select(LibraryDrill, Account.name, Upload.object_key)
|
| 168 |
+
.outerjoin(Account, Account.id == LibraryDrill.author_id)
|
| 169 |
+
.outerjoin(Upload, Upload.id == LibraryDrill.upload_id))
|
| 170 |
+
|
| 171 |
+
async def upload(self, upload_id: UUID, owner_id: UUID) -> Upload | None:
|
| 172 |
+
return await self.session.scalar(select(Upload).where(Upload.id == upload_id, Upload.owner_id == owner_id)
|
| 173 |
+
.with_for_update())
|
| 174 |
+
|
| 175 |
+
async def attach(self, upload: Upload, when: datetime) -> None:
|
| 176 |
+
upload.attached_at = when
|
| 177 |
+
await self.session.flush()
|
backend/app/modules/academy_org/schemas.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from typing import Annotated, Literal
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
|
| 5 |
+
from pydantic import Field, StringConstraints, field_validator
|
| 6 |
+
|
| 7 |
+
from app.common.schemas import MediaRef, RequestModel, ResponseModel
|
| 8 |
+
|
| 9 |
+
Focus = Literal["Hitting", "Pitching", "Both"]
|
| 10 |
+
Mode = Literal["h", "p"]
|
| 11 |
+
FaultTag = Annotated[str, StringConstraints(min_length=1, max_length=64)]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class GroupOut(ResponseModel):
|
| 15 |
+
id: UUID
|
| 16 |
+
name: str
|
| 17 |
+
focus: Focus
|
| 18 |
+
players: int
|
| 19 |
+
player_ids: list[UUID]
|
| 20 |
+
coaches: list[str]
|
| 21 |
+
coach_ids: list[UUID]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class GroupEnvelope(ResponseModel):
|
| 25 |
+
group: GroupOut
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class GroupIn(RequestModel):
|
| 29 |
+
name: str = Field(min_length=1, max_length=80)
|
| 30 |
+
focus: Focus
|
| 31 |
+
coach_ids: list[UUID] = Field(default_factory=list, max_length=200)
|
| 32 |
+
player_ids: list[UUID] = Field(default_factory=list, max_length=1000)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class NoteOut(ResponseModel):
|
| 36 |
+
player_id: UUID
|
| 37 |
+
text: str
|
| 38 |
+
updated_at: datetime | None
|
| 39 |
+
version: int
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class NoteEnvelope(ResponseModel):
|
| 43 |
+
note: NoteOut
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class NoteIn(RequestModel):
|
| 47 |
+
text: str = Field(max_length=4000)
|
| 48 |
+
expected_version: int | None = Field(default=None, ge=0)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class MemberOut(ResponseModel):
|
| 52 |
+
id: UUID
|
| 53 |
+
name: str
|
| 54 |
+
focus: str
|
| 55 |
+
level: str | None
|
| 56 |
+
group_ids: list[UUID]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class RosterAddIn(RequestModel):
|
| 60 |
+
player_ids: list[UUID] = Field(min_length=1, max_length=100)
|
| 61 |
+
group_id: UUID | None = None
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class RosterAddOut(ResponseModel):
|
| 65 |
+
added_player_ids: list[UUID]
|
| 66 |
+
already_present_player_ids: list[UUID]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class LibraryDrillOut(ResponseModel):
|
| 70 |
+
id: UUID
|
| 71 |
+
name: str
|
| 72 |
+
fixes: str
|
| 73 |
+
fault_tags: list[str]
|
| 74 |
+
by: str | None
|
| 75 |
+
author_id: UUID | None
|
| 76 |
+
mode: Mode
|
| 77 |
+
media: MediaRef | None
|
| 78 |
+
created_at: datetime
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class LibraryEnvelope(ResponseModel):
|
| 82 |
+
drill: LibraryDrillOut
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class LibraryDrillIn(RequestModel):
|
| 86 |
+
upload_id: UUID
|
| 87 |
+
name: str = Field(min_length=1, max_length=120)
|
| 88 |
+
mode: Mode
|
| 89 |
+
fault_tags: list[FaultTag] = Field(min_length=1, max_length=10)
|
| 90 |
+
fixes: str = Field(default="", max_length=500)
|
| 91 |
+
|
| 92 |
+
@field_validator("fault_tags")
|
| 93 |
+
@classmethod
|
| 94 |
+
def lowercase_unique(cls, tags: list[str]) -> list[str]:
|
| 95 |
+
return list(dict.fromkeys(t.lower() for t in tags))
|
backend/app/modules/academy_org/service.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Academy groups (N28-N29), private coach notes (N30-N31), roster additions (N32-N33) and the library (N35-N36)."""
|
| 2 |
+
|
| 3 |
+
from datetime import UTC, datetime, timedelta
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
+
|
| 8 |
+
from app.common.academy_access import Staff, require_player, visible_player_ids
|
| 9 |
+
from app.common.schemas import MediaRef, Page
|
| 10 |
+
from app.core.errors import Conflict, NotFound, Unprocessable
|
| 11 |
+
from app.core.pagination import PageParams, encode_cursor
|
| 12 |
+
from app.integrations.storage import StorageClient
|
| 13 |
+
from app.modules.academy.models import LibraryDrill, PlayerGroup
|
| 14 |
+
from app.modules.academy_org.repository import OrgRepository
|
| 15 |
+
from app.modules.academy_org.schemas import (
|
| 16 |
+
GroupIn,
|
| 17 |
+
GroupOut,
|
| 18 |
+
LibraryDrillIn,
|
| 19 |
+
LibraryDrillOut,
|
| 20 |
+
MemberOut,
|
| 21 |
+
NoteIn,
|
| 22 |
+
NoteOut,
|
| 23 |
+
RosterAddIn,
|
| 24 |
+
RosterAddOut,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _dedupe(ids: list[UUID]) -> list[UUID]:
|
| 29 |
+
return list(dict.fromkeys(ids))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _page(items: list, limit: int, created_at) -> Page:
|
| 33 |
+
"""items holds up to limit+1 rows; created_at(item) gives (created_at, id) for the cursor."""
|
| 34 |
+
next_cursor = None
|
| 35 |
+
if len(items) > limit:
|
| 36 |
+
items = items[:limit]
|
| 37 |
+
next_cursor = encode_cursor(*created_at(items[-1]))
|
| 38 |
+
return Page(items=items, next_cursor=next_cursor)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class OrgService:
|
| 42 |
+
def __init__(self, db: AsyncSession, storage: StorageClient):
|
| 43 |
+
self.db = db
|
| 44 |
+
self.storage = storage
|
| 45 |
+
self.repo = OrgRepository(db)
|
| 46 |
+
|
| 47 |
+
# ---------- groups ----------
|
| 48 |
+
async def _group_outs(self, groups: list[PlayerGroup], visible: set[UUID] | None) -> list[GroupOut]:
|
| 49 |
+
if not groups:
|
| 50 |
+
return []
|
| 51 |
+
ids = [g.id for g in groups]
|
| 52 |
+
players = await self.repo.group_players(ids)
|
| 53 |
+
coaches = await self.repo.group_coaches(ids)
|
| 54 |
+
outs = []
|
| 55 |
+
for g in groups:
|
| 56 |
+
player_ids = [p for p in players.get(g.id, []) if visible is None or p in visible]
|
| 57 |
+
outs.append(GroupOut(id=g.id, name=g.name, focus=g.focus, players=len(players.get(g.id, [])),
|
| 58 |
+
player_ids=player_ids, coaches=[n for _, n in coaches.get(g.id, [])],
|
| 59 |
+
coach_ids=[c for c, _ in coaches.get(g.id, [])]))
|
| 60 |
+
return outs
|
| 61 |
+
|
| 62 |
+
async def list_groups(self, staff: Staff, paging: PageParams) -> Page[GroupOut]:
|
| 63 |
+
if staff.team_id is None:
|
| 64 |
+
return Page[GroupOut](items=[])
|
| 65 |
+
rows = list(await self.repo.groups(staff.team_id, None if staff.sees_all else staff.id,
|
| 66 |
+
paging.cursor, paging.limit + 1))
|
| 67 |
+
visible = None if staff.sees_all else set(await visible_player_ids(self.db, staff))
|
| 68 |
+
outs = await self._group_outs(rows, visible)
|
| 69 |
+
by_id = {g.id: g for g in rows}
|
| 70 |
+
return _page(outs, paging.limit, lambda o: (by_id[o.id].created_at, o.id))
|
| 71 |
+
|
| 72 |
+
async def create_group(self, staff: Staff, body: GroupIn) -> GroupOut:
|
| 73 |
+
team_id = staff.team_id
|
| 74 |
+
assert team_id is not None
|
| 75 |
+
coach_ids, player_ids = _dedupe(body.coach_ids), _dedupe(body.player_ids)
|
| 76 |
+
if coach_ids and await self.repo.team_staff_ids(team_id, coach_ids) != set(coach_ids):
|
| 77 |
+
raise NotFound("Coach not found in your academy.")
|
| 78 |
+
if player_ids and await self.repo.team_player_ids(team_id, player_ids) != set(player_ids):
|
| 79 |
+
raise NotFound("Player not found in your academy.")
|
| 80 |
+
group = await self.repo.create_group(team_id, body.name, body.focus, coach_ids, player_ids)
|
| 81 |
+
if group is None:
|
| 82 |
+
raise Conflict("A group with this name already exists.", code="GROUP_NAME_TAKEN")
|
| 83 |
+
[out] = await self._group_outs([group], None)
|
| 84 |
+
return out
|
| 85 |
+
|
| 86 |
+
# ---------- notes ----------
|
| 87 |
+
@staticmethod
|
| 88 |
+
def _note_out(player_id: UUID, note) -> NoteOut:
|
| 89 |
+
if note is None:
|
| 90 |
+
return NoteOut(player_id=player_id, text="", updated_at=None, version=0)
|
| 91 |
+
return NoteOut(player_id=player_id, text=note.text, updated_at=note.updated_at, version=note.version)
|
| 92 |
+
|
| 93 |
+
async def get_note(self, staff: Staff, player_id: UUID) -> NoteOut:
|
| 94 |
+
await require_player(self.db, staff, player_id)
|
| 95 |
+
return self._note_out(player_id, await self.repo.note(staff.team_id, staff.id, player_id)) # type: ignore[arg-type]
|
| 96 |
+
|
| 97 |
+
async def save_note(self, staff: Staff, player_id: UUID, body: NoteIn) -> NoteOut:
|
| 98 |
+
await require_player(self.db, staff, player_id)
|
| 99 |
+
team_id = staff.team_id
|
| 100 |
+
assert team_id is not None
|
| 101 |
+
note = await self.repo.note(team_id, staff.id, player_id, lock=True)
|
| 102 |
+
stale = Conflict("This note changed. Refresh and try again.", code="STALE_VERSION")
|
| 103 |
+
if note is None:
|
| 104 |
+
if body.expected_version not in (None, 0):
|
| 105 |
+
raise stale
|
| 106 |
+
note = await self.repo.insert_note(team_id, staff.id, player_id, body.text)
|
| 107 |
+
if note is None:
|
| 108 |
+
raise stale
|
| 109 |
+
else:
|
| 110 |
+
if body.expected_version is not None and body.expected_version != note.version:
|
| 111 |
+
raise stale
|
| 112 |
+
note.text = body.text
|
| 113 |
+
note.version += 1
|
| 114 |
+
note.updated_at = datetime.now(UTC)
|
| 115 |
+
await self.db.flush()
|
| 116 |
+
return self._note_out(player_id, note)
|
| 117 |
+
|
| 118 |
+
# ---------- roster ----------
|
| 119 |
+
async def members(self, staff: Staff, q: str | None, paging: PageParams) -> Page[MemberOut]:
|
| 120 |
+
if staff.team_id is None:
|
| 121 |
+
return Page[MemberOut](items=[])
|
| 122 |
+
rows = list(await self.repo.members(staff.team_id, staff.id, q, paging.cursor, paging.limit + 1))
|
| 123 |
+
groups = await self.repo.player_group_ids([r.id for r in rows], staff.team_id) if rows else {}
|
| 124 |
+
created = {r.id: r.created_at for r in rows}
|
| 125 |
+
items = [MemberOut(id=r.id, name=r.name or "", focus=r.focus, level=r.level, group_ids=groups.get(r.id, []))
|
| 126 |
+
for r in rows]
|
| 127 |
+
return _page(items, paging.limit, lambda m: (created[m.id], m.id))
|
| 128 |
+
|
| 129 |
+
async def add_to_roster(self, staff: Staff, body: RosterAddIn) -> RosterAddOut:
|
| 130 |
+
player_ids = _dedupe(body.player_ids)
|
| 131 |
+
team_id = staff.team_id
|
| 132 |
+
if team_id is None or await self.repo.team_player_ids(team_id, player_ids) != set(player_ids):
|
| 133 |
+
raise NotFound("Player not found in your academy.")
|
| 134 |
+
if body.group_id is not None:
|
| 135 |
+
group = await self.repo.group_in_team(team_id, body.group_id)
|
| 136 |
+
if group is None or not (staff.is_admin or await self.repo.is_group_coach(group.id, staff.id)):
|
| 137 |
+
raise NotFound("Group not found.")
|
| 138 |
+
added = await self.repo.add_to_roster(team_id, staff.id, player_ids)
|
| 139 |
+
if body.group_id is not None:
|
| 140 |
+
await self.repo.add_to_group(body.group_id, player_ids)
|
| 141 |
+
return RosterAddOut(added_player_ids=[p for p in player_ids if p in added],
|
| 142 |
+
already_present_player_ids=[p for p in player_ids if p not in added])
|
| 143 |
+
|
| 144 |
+
# ---------- library ----------
|
| 145 |
+
def _drill_out(self, row: tuple[LibraryDrill, str | None, str | None]) -> LibraryDrillOut:
|
| 146 |
+
drill, author, key = row
|
| 147 |
+
media = None
|
| 148 |
+
if drill.upload_id is not None and key is not None:
|
| 149 |
+
expires = datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl)
|
| 150 |
+
media = MediaRef(upload_id=drill.upload_id, url=self.storage.presign_get(key), expires_at=expires)
|
| 151 |
+
return LibraryDrillOut(id=drill.id, name=drill.name, fixes=drill.fixes, fault_tags=list(drill.fault_tags),
|
| 152 |
+
by=author, author_id=drill.author_id, mode=drill.mode, media=media,
|
| 153 |
+
created_at=drill.created_at)
|
| 154 |
+
|
| 155 |
+
async def library(self, staff: Staff, mode: str | None, fault_tag: str | None,
|
| 156 |
+
paging: PageParams) -> Page[LibraryDrillOut]:
|
| 157 |
+
if staff.team_id is None:
|
| 158 |
+
return Page[LibraryDrillOut](items=[])
|
| 159 |
+
rows = await self.repo.library(staff.team_id, mode, fault_tag, paging.cursor, paging.limit + 1)
|
| 160 |
+
return _page([self._drill_out(r) for r in rows], paging.limit, lambda d: (d.created_at, d.id))
|
| 161 |
+
|
| 162 |
+
async def publish_drill(self, staff: Staff, body: LibraryDrillIn) -> LibraryDrillOut:
|
| 163 |
+
staff.require("library")
|
| 164 |
+
upload = await self.repo.upload(body.upload_id, staff.id)
|
| 165 |
+
if upload is None:
|
| 166 |
+
raise NotFound("Upload not found.")
|
| 167 |
+
if upload.kind != "drill_video":
|
| 168 |
+
raise Unprocessable("This upload is not a drill video.", code="INVALID_MEDIA")
|
| 169 |
+
if upload.attached_at is not None:
|
| 170 |
+
raise Conflict("This video is already in use.", code="UPLOAD_ALREADY_USED")
|
| 171 |
+
if await self.storage.head(upload.object_key) is None:
|
| 172 |
+
raise Conflict("The video has not finished uploading.", code="UPLOAD_NOT_READY")
|
| 173 |
+
drill = LibraryDrill(team_id=staff.team_id, author_id=staff.id, name=body.name, fixes=body.fixes,
|
| 174 |
+
mode=body.mode, fault_tags=body.fault_tags, upload_id=upload.id)
|
| 175 |
+
self.db.add(drill)
|
| 176 |
+
await self.db.flush()
|
| 177 |
+
await self.repo.attach(upload, datetime.now(UTC))
|
| 178 |
+
return self._drill_out(await self.repo.library_row(drill.id))
|
backend/app/modules/academy_staff/__init__.py
ADDED
|
File without changes
|
backend/app/modules/academy_staff/controller.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""N26-N27 coaching access, N40-N43 academy coaches, N44-N45 access requests, N46-N48 staff codes."""
|
| 2 |
+
|
| 3 |
+
from datetime import date
|
| 4 |
+
from typing import Annotated, Literal
|
| 5 |
+
from uuid import UUID
|
| 6 |
+
|
| 7 |
+
from fastapi import APIRouter, Header, Query, Response
|
| 8 |
+
from fastapi.responses import JSONResponse
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
|
| 11 |
+
from app.common.academy_access import CurrentAdmin, CurrentStaff, staff_context
|
| 12 |
+
from app.common.schemas import Page
|
| 13 |
+
from app.core.dependencies import CurrentAccount, Db, Paging
|
| 14 |
+
from app.modules.academy_staff.schemas import (
|
| 15 |
+
CoachAccessBody,
|
| 16 |
+
CoachAccessCreate,
|
| 17 |
+
CoachBody,
|
| 18 |
+
CoachOut,
|
| 19 |
+
CoachUpdate,
|
| 20 |
+
DecisionIn,
|
| 21 |
+
DecisionOut,
|
| 22 |
+
RequestPage,
|
| 23 |
+
StaffCodeBody,
|
| 24 |
+
StaffCodeCreate,
|
| 25 |
+
StaffCodeOut,
|
| 26 |
+
)
|
| 27 |
+
from app.modules.academy_staff.service import StaffService
|
| 28 |
+
from app.modules.idempotency.service import run_idempotent
|
| 29 |
+
|
| 30 |
+
router = APIRouter(prefix="/v1", tags=["academy_staff"])
|
| 31 |
+
|
| 32 |
+
IdempotencyKey = Annotated[str | None, Header(max_length=128)]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _Scoped(BaseModel):
|
| 36 |
+
"""Idempotency payload that also covers the path id, so one key cannot replay across targets."""
|
| 37 |
+
|
| 38 |
+
target: UUID
|
| 39 |
+
body: dict
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@router.get("/me/coach-access", response_model=CoachAccessBody)
|
| 43 |
+
async def get_coach_access(db: Db, account: CurrentAccount) -> CoachAccessBody:
|
| 44 |
+
return CoachAccessBody(coach_access=await StaffService(db).coach_access(account, await staff_context(db, account)))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@router.post("/me/coach-access", response_model=CoachAccessBody, status_code=201)
|
| 48 |
+
async def apply_for_coach_access(body: CoachAccessCreate, db: Db, account: CurrentAccount,
|
| 49 |
+
idempotency_key: IdempotencyKey = None) -> JSONResponse:
|
| 50 |
+
created = {"value": True}
|
| 51 |
+
|
| 52 |
+
async def handler() -> CoachAccessBody:
|
| 53 |
+
access, created["value"] = await StaffService(db).apply(account, body.code)
|
| 54 |
+
return CoachAccessBody(coach_access=access)
|
| 55 |
+
|
| 56 |
+
response = await run_idempotent(db, account.id, idempotency_key, body, handler, status_code=201)
|
| 57 |
+
if not created["value"]:
|
| 58 |
+
response.status_code = 200
|
| 59 |
+
return response
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@router.get("/academy/coaches", response_model=Page[CoachOut])
|
| 63 |
+
async def list_coaches(db: Db, staff: CurrentStaff,
|
| 64 |
+
status: Literal["active", "paused", "removed", "all"] | None = None) -> Page[CoachOut]:
|
| 65 |
+
return Page(items=await StaffService(db).list_coaches(staff, status))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@router.get("/academy/coaches/{coach_id}", response_model=CoachBody)
|
| 69 |
+
async def get_coach(coach_id: UUID, db: Db, staff: CurrentAdmin, activity_from: date | None = None,
|
| 70 |
+
activity_to: date | None = None) -> CoachBody:
|
| 71 |
+
return CoachBody(coach=await StaffService(db).get_coach(staff, coach_id, activity_from, activity_to))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@router.patch("/academy/coaches/{coach_id}", response_model=CoachBody)
|
| 75 |
+
async def update_coach(coach_id: UUID, body: CoachUpdate, db: Db, staff: CurrentAdmin) -> CoachBody:
|
| 76 |
+
return CoachBody(coach=await StaffService(db).update_coach(staff, coach_id, body))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@router.delete("/academy/coaches/{coach_id}", status_code=204)
|
| 80 |
+
async def remove_coach(coach_id: UUID, reassign_to: Annotated[UUID, Query()], db: Db,
|
| 81 |
+
staff: CurrentAdmin) -> Response:
|
| 82 |
+
await StaffService(db).remove_coach(staff, coach_id, reassign_to)
|
| 83 |
+
return Response(status_code=204)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@router.get("/academy/coach-requests", response_model=RequestPage)
|
| 87 |
+
async def list_requests(db: Db, staff: CurrentAdmin, paging: Paging,
|
| 88 |
+
status: Literal["pending", "approved", "declined", "all"] = "all") -> RequestPage:
|
| 89 |
+
return await StaffService(db).list_requests(staff, status, paging)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@router.post("/academy/coach-requests/{request_id}/decision", response_model=DecisionOut)
|
| 93 |
+
async def decide_request(request_id: UUID, body: DecisionIn, db: Db, staff: CurrentAdmin,
|
| 94 |
+
idempotency_key: IdempotencyKey = None) -> JSONResponse:
|
| 95 |
+
scoped = _Scoped(target=request_id, body=body.model_dump(mode="json"))
|
| 96 |
+
return await run_idempotent(db, staff.id, idempotency_key, scoped,
|
| 97 |
+
lambda: StaffService(db).decide(staff, request_id, body), status_code=200)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@router.get("/academy/staff-codes", response_model=Page[StaffCodeOut])
|
| 101 |
+
async def list_codes(db: Db, staff: CurrentAdmin, paging: Paging,
|
| 102 |
+
status: Literal["active", "expired", "revoked", "all"] = "all") -> Page[StaffCodeOut]:
|
| 103 |
+
items, next_cursor = await StaffService(db).list_codes(staff, status, paging)
|
| 104 |
+
return Page(items=items, next_cursor=next_cursor)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@router.post("/academy/staff-codes", response_model=StaffCodeBody, status_code=201)
|
| 108 |
+
async def create_code(body: StaffCodeCreate, db: Db, staff: CurrentAdmin,
|
| 109 |
+
idempotency_key: IdempotencyKey = None) -> JSONResponse:
|
| 110 |
+
async def handler() -> StaffCodeBody:
|
| 111 |
+
return StaffCodeBody(staff_code=await StaffService(db).create_code(staff, body))
|
| 112 |
+
|
| 113 |
+
return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=201)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@router.delete("/academy/staff-codes/{code}", status_code=204)
|
| 117 |
+
async def revoke_code(code: str, db: Db, staff: CurrentAdmin) -> Response:
|
| 118 |
+
await StaffService(db).revoke_code(staff, code)
|
| 119 |
+
return Response(status_code=204)
|
backend/app/modules/academy_staff/repository.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Academy staff queries: memberships, access requests, staff codes, group links and activity aggregates."""
|
| 2 |
+
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import delete, func, select, update
|
| 7 |
+
from sqlalchemy.dialects.postgresql import insert
|
| 8 |
+
|
| 9 |
+
from app.common.base_repository import BaseRepository
|
| 10 |
+
from app.core.pagination import Cursor
|
| 11 |
+
from app.modules.academy.models import (
|
| 12 |
+
AcademyMembership,
|
| 13 |
+
CoachAccessRequest,
|
| 14 |
+
CoachPlayer,
|
| 15 |
+
GroupCoach,
|
| 16 |
+
PlayerGroup,
|
| 17 |
+
StaffCode,
|
| 18 |
+
)
|
| 19 |
+
from app.modules.accounts.models import Account
|
| 20 |
+
from app.modules.assignments.models import DrillAssignment
|
| 21 |
+
from app.modules.reviews.models import Review
|
| 22 |
+
from app.modules.sessions.models import SwingSession
|
| 23 |
+
from app.modules.teams.models import Team
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class StaffRepository(BaseRepository[AcademyMembership]):
|
| 27 |
+
model = AcademyMembership
|
| 28 |
+
|
| 29 |
+
# ----- teams and accounts -----
|
| 30 |
+
async def team(self, team_id: UUID) -> Team | None:
|
| 31 |
+
return await self.session.get(Team, team_id)
|
| 32 |
+
|
| 33 |
+
async def account(self, account_id: UUID) -> Account | None:
|
| 34 |
+
return await self.session.get(Account, account_id)
|
| 35 |
+
|
| 36 |
+
# ----- memberships -----
|
| 37 |
+
async def membership(self, team_id: UUID, account_id: UUID, *, lock: bool = False) -> AcademyMembership | None:
|
| 38 |
+
query = select(AcademyMembership).where(AcademyMembership.team_id == team_id,
|
| 39 |
+
AcademyMembership.account_id == account_id)
|
| 40 |
+
if lock:
|
| 41 |
+
query = query.with_for_update().execution_options(populate_existing=True)
|
| 42 |
+
return await self.session.scalar(query)
|
| 43 |
+
|
| 44 |
+
async def memberships(self, team_id: UUID, statuses: list[str]) -> list[tuple[AcademyMembership, Account]]:
|
| 45 |
+
rows = await self.session.execute(
|
| 46 |
+
select(AcademyMembership, Account).join(Account, Account.id == AcademyMembership.account_id)
|
| 47 |
+
.where(AcademyMembership.team_id == team_id, AcademyMembership.status.in_(statuses))
|
| 48 |
+
.order_by(AcademyMembership.created_at, AcademyMembership.id))
|
| 49 |
+
return [(m, a) for m, a in rows.all()]
|
| 50 |
+
|
| 51 |
+
async def admin_count(self, team_id: UUID) -> int:
|
| 52 |
+
return await self.session.scalar(select(func.count()).select_from(AcademyMembership).where(
|
| 53 |
+
AcademyMembership.team_id == team_id, AcademyMembership.role == "admin",
|
| 54 |
+
AcademyMembership.status == "active")) or 0
|
| 55 |
+
|
| 56 |
+
# ----- groups -----
|
| 57 |
+
async def group_ids(self, team_id: UUID, coach_id: UUID) -> list[UUID]:
|
| 58 |
+
return list((await self.session.scalars(
|
| 59 |
+
select(GroupCoach.group_id).join(PlayerGroup, PlayerGroup.id == GroupCoach.group_id)
|
| 60 |
+
.where(PlayerGroup.team_id == team_id, GroupCoach.coach_id == coach_id)
|
| 61 |
+
.order_by(PlayerGroup.created_at, PlayerGroup.id))).all())
|
| 62 |
+
|
| 63 |
+
async def count_groups(self, team_id: UUID, group_ids: list[UUID]) -> int:
|
| 64 |
+
return await self.session.scalar(select(func.count()).select_from(PlayerGroup).where(
|
| 65 |
+
PlayerGroup.team_id == team_id, PlayerGroup.id.in_(group_ids))) or 0
|
| 66 |
+
|
| 67 |
+
async def set_groups(self, team_id: UUID, coach_id: UUID, group_ids: list[UUID]) -> None:
|
| 68 |
+
team_groups = select(PlayerGroup.id).where(PlayerGroup.team_id == team_id)
|
| 69 |
+
await self.session.execute(delete(GroupCoach).where(GroupCoach.coach_id == coach_id,
|
| 70 |
+
GroupCoach.group_id.in_(team_groups)))
|
| 71 |
+
await self.add_groups(coach_id, group_ids)
|
| 72 |
+
|
| 73 |
+
async def add_groups(self, coach_id: UUID, group_ids: list[UUID]) -> None:
|
| 74 |
+
if group_ids:
|
| 75 |
+
await self.session.execute(insert(GroupCoach).values(
|
| 76 |
+
[{"group_id": g, "coach_id": coach_id} for g in set(group_ids)]).on_conflict_do_nothing())
|
| 77 |
+
|
| 78 |
+
async def move_responsibilities(self, team_id: UUID, from_id: UUID, to_id: UUID) -> None:
|
| 79 |
+
"""Roster rows and group coaching go to the replacement; rows the replacement already has are dropped."""
|
| 80 |
+
has = select(CoachPlayer.player_id).where(CoachPlayer.team_id == team_id, CoachPlayer.coach_id == to_id)
|
| 81 |
+
await self.session.execute(update(CoachPlayer).where(
|
| 82 |
+
CoachPlayer.team_id == team_id, CoachPlayer.coach_id == from_id, CoachPlayer.player_id.not_in(has))
|
| 83 |
+
.values(coach_id=to_id))
|
| 84 |
+
await self.session.execute(delete(CoachPlayer).where(CoachPlayer.team_id == team_id,
|
| 85 |
+
CoachPlayer.coach_id == from_id))
|
| 86 |
+
old = await self.group_ids(team_id, from_id)
|
| 87 |
+
await self.set_groups(team_id, from_id, [])
|
| 88 |
+
await self.add_groups(to_id, old)
|
| 89 |
+
|
| 90 |
+
# ----- activity -----
|
| 91 |
+
async def review_activity(self, team_id: UUID, coach_id: UUID, start: datetime, end: datetime):
|
| 92 |
+
"""(reviews, avg hours from session creation to the review) for reviews written in [start, end)."""
|
| 93 |
+
seconds = func.extract("epoch", Review.updated_at - SwingSession.created_at)
|
| 94 |
+
row = (await self.session.execute(
|
| 95 |
+
select(func.count(), func.avg(seconds) / 3600)
|
| 96 |
+
.select_from(Review).join(SwingSession, SwingSession.id == Review.session_id)
|
| 97 |
+
.join(Account, Account.id == SwingSession.owner_id)
|
| 98 |
+
.where(Account.team_id == team_id, Review.coach_id == coach_id, SwingSession.deleted_at.is_(None),
|
| 99 |
+
Review.updated_at >= start, Review.updated_at < end))).one()
|
| 100 |
+
return row[0], (round(float(row[1]), 1) if row[1] is not None else None)
|
| 101 |
+
|
| 102 |
+
async def drills_set(self, team_id: UUID, coach_id: UUID, start: datetime, end: datetime) -> int:
|
| 103 |
+
return await self.session.scalar(select(func.count()).select_from(DrillAssignment).where(
|
| 104 |
+
DrillAssignment.team_id == team_id, DrillAssignment.assigned_by_id == coach_id,
|
| 105 |
+
DrillAssignment.created_at >= start, DrillAssignment.created_at < end)) or 0
|
| 106 |
+
|
| 107 |
+
async def count(self, query) -> int:
|
| 108 |
+
return await self.session.scalar(select(func.count()).select_from(query.subquery())) or 0
|
| 109 |
+
|
| 110 |
+
# ----- staff codes -----
|
| 111 |
+
async def code_row(self, code: str, *, team_id: UUID | None = None, lock: bool = False) -> StaffCode | None:
|
| 112 |
+
query = select(StaffCode).where(StaffCode.code == code)
|
| 113 |
+
if team_id is not None:
|
| 114 |
+
query = query.where(StaffCode.team_id == team_id)
|
| 115 |
+
if lock:
|
| 116 |
+
query = query.with_for_update().execution_options(populate_existing=True)
|
| 117 |
+
return await self.session.scalar(query)
|
| 118 |
+
|
| 119 |
+
async def code_exists(self, code: str) -> bool:
|
| 120 |
+
return await self.session.scalar(select(StaffCode.id).where(StaffCode.code == code)) is not None
|
| 121 |
+
|
| 122 |
+
async def codes(self, team_id: UUID, status: str, now: datetime, limit: int, cursor: Cursor | None):
|
| 123 |
+
query = select(StaffCode).where(StaffCode.team_id == team_id)
|
| 124 |
+
if status == "active":
|
| 125 |
+
query = query.where(StaffCode.revoked_at.is_(None), StaffCode.expires_at > now)
|
| 126 |
+
elif status == "expired":
|
| 127 |
+
query = query.where(StaffCode.revoked_at.is_(None), StaffCode.expires_at <= now)
|
| 128 |
+
elif status == "revoked":
|
| 129 |
+
query = query.where(StaffCode.revoked_at.is_not(None))
|
| 130 |
+
if cursor:
|
| 131 |
+
query = query.where(
|
| 132 |
+
(StaffCode.created_at < cursor.created_at)
|
| 133 |
+
| ((StaffCode.created_at == cursor.created_at) & (StaffCode.id < cursor.id)))
|
| 134 |
+
query = query.order_by(StaffCode.created_at.desc(), StaffCode.id.desc()).limit(limit + 1)
|
| 135 |
+
return list((await self.session.scalars(query)).all())
|
| 136 |
+
|
| 137 |
+
# ----- access requests -----
|
| 138 |
+
async def latest_request(self, applicant_id: UUID) -> CoachAccessRequest | None:
|
| 139 |
+
return await self.session.scalar(select(CoachAccessRequest).where(
|
| 140 |
+
CoachAccessRequest.applicant_id == applicant_id)
|
| 141 |
+
.order_by(CoachAccessRequest.created_at.desc(), CoachAccessRequest.id.desc()).limit(1))
|
| 142 |
+
|
| 143 |
+
async def pending_request(self, applicant_id: UUID) -> CoachAccessRequest | None:
|
| 144 |
+
return await self.session.scalar(select(CoachAccessRequest).where(
|
| 145 |
+
CoachAccessRequest.applicant_id == applicant_id, CoachAccessRequest.status == "pending"))
|
| 146 |
+
|
| 147 |
+
async def locked_request(self, team_id: UUID, request_id: UUID) -> CoachAccessRequest | None:
|
| 148 |
+
return await self.session.scalar(select(CoachAccessRequest).where(
|
| 149 |
+
CoachAccessRequest.id == request_id, CoachAccessRequest.team_id == team_id)
|
| 150 |
+
.with_for_update().execution_options(populate_existing=True))
|
| 151 |
+
|
| 152 |
+
async def requests(self, team_id: UUID, status: str, limit: int, cursor: Cursor | None):
|
| 153 |
+
query = (select(CoachAccessRequest, Account).join(Account, Account.id == CoachAccessRequest.applicant_id)
|
| 154 |
+
.where(CoachAccessRequest.team_id == team_id))
|
| 155 |
+
if status != "all":
|
| 156 |
+
query = query.where(CoachAccessRequest.status == status)
|
| 157 |
+
if cursor:
|
| 158 |
+
query = query.where(
|
| 159 |
+
(CoachAccessRequest.created_at < cursor.created_at)
|
| 160 |
+
| ((CoachAccessRequest.created_at == cursor.created_at) & (CoachAccessRequest.id < cursor.id)))
|
| 161 |
+
query = query.order_by(CoachAccessRequest.created_at.desc(), CoachAccessRequest.id.desc()).limit(limit + 1)
|
| 162 |
+
return [(r, a) for r, a in (await self.session.execute(query)).all()]
|
| 163 |
+
|
| 164 |
+
async def total_pending(self, team_id: UUID) -> int:
|
| 165 |
+
return await self.session.scalar(select(func.count()).select_from(CoachAccessRequest).where(
|
| 166 |
+
CoachAccessRequest.team_id == team_id, CoachAccessRequest.status == "pending")) or 0
|
backend/app/modules/academy_staff/schemas.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Academy staff shapes: coaching access, members, access requests and staff codes."""
|
| 2 |
+
|
| 3 |
+
from datetime import date, datetime
|
| 4 |
+
from typing import Annotated, Literal
|
| 5 |
+
from uuid import UUID
|
| 6 |
+
|
| 7 |
+
from pydantic import Field
|
| 8 |
+
|
| 9 |
+
from app.common.schemas import Page, RequestModel, ResponseModel
|
| 10 |
+
|
| 11 |
+
StaffRole = Literal["admin", "coach", "assistant"]
|
| 12 |
+
Permissions = dict[str, bool]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class CoachAccessOut(ResponseModel):
|
| 16 |
+
status: Literal["none", "pending", "approved", "declined"]
|
| 17 |
+
code: str | None
|
| 18 |
+
sent_at: datetime | None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class CoachAccessBody(ResponseModel):
|
| 22 |
+
coach_access: CoachAccessOut
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class CoachAccessCreate(RequestModel):
|
| 26 |
+
code: Annotated[str, Field(min_length=6, max_length=64)]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ActivityOut(ResponseModel):
|
| 30 |
+
reviews: int
|
| 31 |
+
avg_reply_hours: float | None
|
| 32 |
+
players: int
|
| 33 |
+
drills_set: int
|
| 34 |
+
period_start: date
|
| 35 |
+
period_end: date
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class CoachOut(ResponseModel):
|
| 39 |
+
id: UUID
|
| 40 |
+
name: str
|
| 41 |
+
coaches: str
|
| 42 |
+
joined: datetime
|
| 43 |
+
joined_with: str | None
|
| 44 |
+
role: StaffRole
|
| 45 |
+
is_me: bool
|
| 46 |
+
sees_all: bool
|
| 47 |
+
group_ids: list[UUID]
|
| 48 |
+
permissions: Permissions | None
|
| 49 |
+
activity: ActivityOut | None
|
| 50 |
+
status: Literal["active", "paused", "removed"]
|
| 51 |
+
version: int
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class CoachBody(ResponseModel):
|
| 55 |
+
coach: CoachOut
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class PermissionsIn(RequestModel):
|
| 59 |
+
review: bool | None = None
|
| 60 |
+
drills: bool | None = None
|
| 61 |
+
goals: bool | None = None
|
| 62 |
+
library: bool | None = None
|
| 63 |
+
earnings: bool | None = None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class CoachUpdate(RequestModel):
|
| 67 |
+
role: StaffRole | None = None
|
| 68 |
+
sees_all: bool | None = None
|
| 69 |
+
group_ids: list[UUID] | None = None
|
| 70 |
+
permissions: PermissionsIn | None = None
|
| 71 |
+
status: Literal["active", "paused"] | None = None
|
| 72 |
+
expected_version: int | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class RequestOut(ResponseModel):
|
| 76 |
+
id: UUID
|
| 77 |
+
user_id: UUID
|
| 78 |
+
name: str
|
| 79 |
+
code: str
|
| 80 |
+
at: datetime
|
| 81 |
+
also_player: bool
|
| 82 |
+
status: Literal["pending", "approved", "declined"]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class RequestPage(Page[RequestOut]):
|
| 86 |
+
total_pending: int
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class DecisionIn(RequestModel):
|
| 90 |
+
decision: Literal["approve", "decline"]
|
| 91 |
+
role: Literal["coach", "assistant"] | None = None
|
| 92 |
+
sees_all: bool = False
|
| 93 |
+
group_ids: list[UUID] = Field(default_factory=list)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class DecisionOut(ResponseModel):
|
| 97 |
+
request: RequestOut
|
| 98 |
+
coach: CoachOut | None
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class StaffCodeOut(ResponseModel):
|
| 102 |
+
code: str
|
| 103 |
+
role: Literal["coach", "assistant"]
|
| 104 |
+
expires: datetime
|
| 105 |
+
uses: int
|
| 106 |
+
max_uses: int
|
| 107 |
+
approval: Literal["admin", "auto"]
|
| 108 |
+
status: Literal["active", "expired", "revoked"]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class StaffCodeBody(ResponseModel):
|
| 112 |
+
staff_code: StaffCodeOut
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class StaffCodeCreate(RequestModel):
|
| 116 |
+
role: Literal["coach", "assistant"]
|
| 117 |
+
expires_days: Literal[1, 7, 30]
|
| 118 |
+
max_uses: Literal[1, 5, 20]
|
| 119 |
+
approval: Literal["admin", "auto"]
|
backend/app/modules/academy_staff/service.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Staff codes, coaching-access applications and academy member management."""
|
| 2 |
+
|
| 3 |
+
import calendar
|
| 4 |
+
import secrets
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from datetime import UTC, date, datetime, time, timedelta
|
| 7 |
+
from uuid import UUID
|
| 8 |
+
|
| 9 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
+
|
| 11 |
+
from app.common.academy_access import Staff, normalize_permissions, visible_players_query
|
| 12 |
+
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable
|
| 13 |
+
from app.core.pagination import PageParams, encode_cursor
|
| 14 |
+
from app.core.rate_limit import RateLimiter
|
| 15 |
+
from app.modules.academy.models import AcademyMembership, CoachAccessRequest, StaffCode
|
| 16 |
+
from app.modules.academy_staff.repository import StaffRepository
|
| 17 |
+
from app.modules.academy_staff.schemas import (
|
| 18 |
+
ActivityOut,
|
| 19 |
+
CoachAccessOut,
|
| 20 |
+
CoachOut,
|
| 21 |
+
CoachUpdate,
|
| 22 |
+
DecisionIn,
|
| 23 |
+
DecisionOut,
|
| 24 |
+
RequestOut,
|
| 25 |
+
RequestPage,
|
| 26 |
+
StaffCodeCreate,
|
| 27 |
+
StaffCodeOut,
|
| 28 |
+
)
|
| 29 |
+
from app.modules.accounts.models import Account
|
| 30 |
+
from app.modules.teams.models import Team
|
| 31 |
+
|
| 32 |
+
CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # no 0/O/1/I/L
|
| 33 |
+
COACHES_LABEL = {"h": "Hitting", "p": "Pitching", "both": "Both"}
|
| 34 |
+
_apply_limiter = RateLimiter(10, 60.0)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def normalize_code(code: str) -> str:
|
| 38 |
+
return code.strip().upper()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def new_code() -> str:
|
| 42 |
+
pick = lambda n: "".join(secrets.choice(CODE_ALPHABET) for _ in range(n)) # noqa: E731
|
| 43 |
+
return f"CV-{pick(4)}-{pick(2)}"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _now() -> datetime:
|
| 47 |
+
return datetime.now(UTC)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def code_status(code: StaffCode, now: datetime) -> str:
|
| 51 |
+
if code.revoked_at is not None:
|
| 52 |
+
return "revoked"
|
| 53 |
+
return "expired" if code.expires_at <= now else "active"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def code_out(code: StaffCode, now: datetime) -> StaffCodeOut:
|
| 57 |
+
return StaffCodeOut(code=code.code, role=code.role, expires=code.expires_at, uses=code.uses,
|
| 58 |
+
max_uses=code.max_uses, approval=code.approval, status=code_status(code, now))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
class Member:
|
| 63 |
+
"""One person on the academy staff, from a membership row or the synthesized owner."""
|
| 64 |
+
|
| 65 |
+
account: Account
|
| 66 |
+
role: str
|
| 67 |
+
status: str
|
| 68 |
+
sees_all: bool
|
| 69 |
+
permissions: dict[str, bool]
|
| 70 |
+
joined: datetime
|
| 71 |
+
joined_with: str | None
|
| 72 |
+
version: int
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class StaffService:
|
| 76 |
+
def __init__(self, db: AsyncSession):
|
| 77 |
+
self.db = db
|
| 78 |
+
self.repo = StaffRepository(db)
|
| 79 |
+
|
| 80 |
+
# ---------------------------------------------------------------- coaching access (applicant side)
|
| 81 |
+
|
| 82 |
+
async def coach_access(self, account: Account, staff: Staff | None) -> CoachAccessOut:
|
| 83 |
+
latest = await self.repo.latest_request(account.id)
|
| 84 |
+
if staff is not None and staff.team_id is not None:
|
| 85 |
+
approved = latest is not None and latest.status == "approved"
|
| 86 |
+
return CoachAccessOut(status="approved", code=latest.code if approved else None,
|
| 87 |
+
sent_at=latest.created_at if approved else None)
|
| 88 |
+
if latest is None:
|
| 89 |
+
return CoachAccessOut(status="none", code=None, sent_at=None)
|
| 90 |
+
return CoachAccessOut(status=latest.status, code=latest.code, sent_at=latest.created_at)
|
| 91 |
+
|
| 92 |
+
async def apply(self, account: Account, raw_code: str) -> tuple[CoachAccessOut, bool]:
|
| 93 |
+
"""Returns (coach_access, created). Uses are counted at submission and a decline does not give one back."""
|
| 94 |
+
_apply_limiter.hit(f"coach_apply:{account.id}")
|
| 95 |
+
code = normalize_code(raw_code)
|
| 96 |
+
row = await self.repo.code_row(code, lock=True)
|
| 97 |
+
if row is None:
|
| 98 |
+
raise Unprocessable("That code isn't valid.", code="CODE_INVALID")
|
| 99 |
+
pending = await self.repo.pending_request(account.id)
|
| 100 |
+
if pending is not None:
|
| 101 |
+
if pending.code == code:
|
| 102 |
+
return CoachAccessOut(status="pending", code=pending.code, sent_at=pending.created_at), False
|
| 103 |
+
raise Conflict("You already have a request waiting for approval.", code="REQUEST_PENDING")
|
| 104 |
+
team = await self.repo.team(row.team_id)
|
| 105 |
+
existing = await self.repo.membership(row.team_id, account.id)
|
| 106 |
+
if team.coach_id == account.id or (existing is not None and existing.status != "removed"):
|
| 107 |
+
raise Conflict("You are already on this academy's staff.", code="ALREADY_MEMBER")
|
| 108 |
+
now = _now()
|
| 109 |
+
if code_status(row, now) != "active" or row.uses >= row.max_uses:
|
| 110 |
+
raise Conflict("That code can't be used any more.", code="CODE_UNAVAILABLE")
|
| 111 |
+
row.uses += 1
|
| 112 |
+
# A removed member re-enters only through an admin decision, whatever the code's approval mode.
|
| 113 |
+
auto = row.approval == "auto" and not (existing is not None and existing.status == "removed")
|
| 114 |
+
request = CoachAccessRequest(applicant_id=account.id, team_id=row.team_id, staff_code_id=row.id,
|
| 115 |
+
code=row.code, status="approved" if auto else "pending",
|
| 116 |
+
decided_at=now if auto else None)
|
| 117 |
+
self.db.add(request)
|
| 118 |
+
await self.db.flush()
|
| 119 |
+
await self.db.refresh(request)
|
| 120 |
+
if auto:
|
| 121 |
+
await self._upsert_membership(row.team_id, account.id, row.role, False, None, row.code)
|
| 122 |
+
return CoachAccessOut(status=request.status, code=request.code, sent_at=request.created_at), True
|
| 123 |
+
|
| 124 |
+
# ---------------------------------------------------------------- members
|
| 125 |
+
|
| 126 |
+
async def _team(self, staff: Staff) -> Team:
|
| 127 |
+
if staff.team_id is None:
|
| 128 |
+
raise Forbidden("Create or join an academy first.")
|
| 129 |
+
return await self.repo.team(staff.team_id) # type: ignore[return-value]
|
| 130 |
+
|
| 131 |
+
def _owner(self, team: Team, account: Account) -> Member:
|
| 132 |
+
return Member(account, "admin", "active", True, normalize_permissions("admin"), team.created_at, None, 1)
|
| 133 |
+
|
| 134 |
+
@staticmethod
|
| 135 |
+
def _member(membership: AcademyMembership, account: Account) -> Member:
|
| 136 |
+
return Member(account, membership.role, membership.status, membership.sees_all or membership.role == "admin",
|
| 137 |
+
normalize_permissions(membership.role, membership.permissions), membership.created_at,
|
| 138 |
+
membership.joined_with, membership.version)
|
| 139 |
+
|
| 140 |
+
async def _find(self, team: Team, member_id: UUID) -> Member:
|
| 141 |
+
if member_id == team.coach_id:
|
| 142 |
+
return self._owner(team, await self.repo.account(member_id)) # type: ignore[arg-type]
|
| 143 |
+
membership = await self.repo.membership(team.id, member_id)
|
| 144 |
+
if membership is None:
|
| 145 |
+
raise NotFound("We couldn't find that coach.")
|
| 146 |
+
return self._member(membership, await self.repo.account(member_id)) # type: ignore[arg-type]
|
| 147 |
+
|
| 148 |
+
@staticmethod
|
| 149 |
+
def _period(start: date | None, end: date | None) -> tuple[date, date]:
|
| 150 |
+
today = _now().date()
|
| 151 |
+
start = start or today.replace(day=1)
|
| 152 |
+
end = end or today.replace(day=calendar.monthrange(today.year, today.month)[1])
|
| 153 |
+
if start > end:
|
| 154 |
+
raise Unprocessable("The start date is after the end date.", code="INVALID_PERIOD")
|
| 155 |
+
return start, end
|
| 156 |
+
|
| 157 |
+
async def _out(self, team: Team, member: Member, me_id: UUID, start: date, end: date) -> CoachOut:
|
| 158 |
+
lo = datetime.combine(start, time.min, UTC)
|
| 159 |
+
hi = datetime.combine(end + timedelta(days=1), time.min, UTC)
|
| 160 |
+
who = Staff(member.account, team.id, member.role, member.sees_all, member.permissions)
|
| 161 |
+
reviews, avg_hours = await self.repo.review_activity(team.id, member.account.id, lo, hi)
|
| 162 |
+
activity = ActivityOut(
|
| 163 |
+
reviews=reviews, avg_reply_hours=avg_hours, players=await self.repo.count(visible_players_query(who)),
|
| 164 |
+
drills_set=await self.repo.drills_set(team.id, member.account.id, lo, hi),
|
| 165 |
+
period_start=start, period_end=end)
|
| 166 |
+
return CoachOut(
|
| 167 |
+
id=member.account.id, name=member.account.name, coaches=COACHES_LABEL[member.account.focus],
|
| 168 |
+
joined=member.joined, joined_with=member.joined_with, role=member.role,
|
| 169 |
+
is_me=member.account.id == me_id, sees_all=member.sees_all,
|
| 170 |
+
group_ids=await self.repo.group_ids(team.id, member.account.id), permissions=member.permissions,
|
| 171 |
+
activity=activity, status=member.status, version=member.version)
|
| 172 |
+
|
| 173 |
+
async def list_coaches(self, staff: Staff, status: str | None) -> list[CoachOut]:
|
| 174 |
+
team = await self._team(staff)
|
| 175 |
+
statuses = {"active": ["active"], "paused": ["paused"], "removed": ["removed"],
|
| 176 |
+
"all": ["active", "paused", "removed"], None: ["active", "paused"]}[status]
|
| 177 |
+
members = [self._member(m, a) for m, a in await self.repo.memberships(team.id, statuses)]
|
| 178 |
+
if "active" in statuses:
|
| 179 |
+
owner = await self.repo.account(team.coach_id)
|
| 180 |
+
members.insert(0, self._owner(team, owner)) # type: ignore[arg-type]
|
| 181 |
+
start, end = self._period(None, None)
|
| 182 |
+
items = [await self._out(team, m, staff.id, start, end) for m in members]
|
| 183 |
+
if staff.role != "admin": # colleagues' staff code, permissions and activity are admin-only
|
| 184 |
+
items = [c.model_copy(update={"joined_with": None, "permissions": None, "activity": None})
|
| 185 |
+
if not c.is_me else c for c in items]
|
| 186 |
+
return items
|
| 187 |
+
|
| 188 |
+
async def get_coach(self, staff: Staff, coach_id: UUID, start: date | None, end: date | None) -> CoachOut:
|
| 189 |
+
team = await self._team(staff)
|
| 190 |
+
start, end = self._period(start, end)
|
| 191 |
+
return await self._out(team, await self._find(team, coach_id), staff.id, start, end)
|
| 192 |
+
|
| 193 |
+
async def update_coach(self, staff: Staff, coach_id: UUID, patch: CoachUpdate) -> CoachOut:
|
| 194 |
+
values = patch.model_dump(exclude_unset=True, exclude={"expected_version"})
|
| 195 |
+
if not values:
|
| 196 |
+
raise Unprocessable("Send at least one change.", code="NO_CHANGES")
|
| 197 |
+
team = await self._team(staff)
|
| 198 |
+
if coach_id == team.coach_id:
|
| 199 |
+
raise Conflict("The academy owner can't be changed.", code="OWNER_IMMUTABLE")
|
| 200 |
+
membership = await self.repo.membership(team.id, coach_id, lock=True)
|
| 201 |
+
if membership is None or membership.status == "removed":
|
| 202 |
+
raise NotFound("We couldn't find that coach.")
|
| 203 |
+
if patch.expected_version is not None and patch.expected_version != membership.version:
|
| 204 |
+
raise Conflict("This coach changed. Refresh and try again.", code="STALE_VERSION")
|
| 205 |
+
group_ids = patch.group_ids
|
| 206 |
+
if group_ids is not None and await self.repo.count_groups(team.id, group_ids) != len(set(group_ids)):
|
| 207 |
+
raise Unprocessable("A group isn't part of this academy.", code="INVALID_GROUP")
|
| 208 |
+
role = patch.role or membership.role
|
| 209 |
+
# The owner is always an admin, so the academy never runs out of admins through this endpoint.
|
| 210 |
+
given = patch.permissions.model_dump(exclude_none=True) if patch.permissions else None
|
| 211 |
+
if given is not None:
|
| 212 |
+
permissions = normalize_permissions(role, {**membership.permissions, **given})
|
| 213 |
+
elif role != membership.role:
|
| 214 |
+
permissions = normalize_permissions(role)
|
| 215 |
+
else:
|
| 216 |
+
permissions = normalize_permissions(role, membership.permissions)
|
| 217 |
+
membership.role = role
|
| 218 |
+
membership.permissions = permissions
|
| 219 |
+
if patch.sees_all is not None:
|
| 220 |
+
membership.sees_all = patch.sees_all
|
| 221 |
+
if patch.status is not None:
|
| 222 |
+
membership.status = patch.status
|
| 223 |
+
membership.version += 1
|
| 224 |
+
await self.db.flush()
|
| 225 |
+
if group_ids is not None:
|
| 226 |
+
await self.repo.set_groups(team.id, coach_id, group_ids)
|
| 227 |
+
await self.db.refresh(membership)
|
| 228 |
+
start, end = self._period(None, None)
|
| 229 |
+
member = self._member(membership, await self.repo.account(coach_id)) # type: ignore[arg-type]
|
| 230 |
+
return await self._out(team, member, staff.id, start, end)
|
| 231 |
+
|
| 232 |
+
async def remove_coach(self, staff: Staff, coach_id: UUID, reassign_to: UUID) -> None:
|
| 233 |
+
team = await self._team(staff)
|
| 234 |
+
if coach_id == team.coach_id:
|
| 235 |
+
raise Conflict("The academy owner can't be removed.", code="OWNER_IMMUTABLE")
|
| 236 |
+
membership = await self.repo.membership(team.id, coach_id, lock=True)
|
| 237 |
+
if membership is None:
|
| 238 |
+
raise NotFound("We couldn't find that coach.")
|
| 239 |
+
if membership.status == "removed":
|
| 240 |
+
return
|
| 241 |
+
replacement = await self.repo.membership(team.id, reassign_to)
|
| 242 |
+
valid = reassign_to != coach_id and (
|
| 243 |
+
reassign_to == team.coach_id or (replacement is not None and replacement.status == "active"))
|
| 244 |
+
if not valid:
|
| 245 |
+
raise Conflict("Choose another active coach to take over.", code="INVALID_REPLACEMENT")
|
| 246 |
+
await self.repo.move_responsibilities(team.id, coach_id, reassign_to)
|
| 247 |
+
membership.status = "removed"
|
| 248 |
+
membership.version += 1
|
| 249 |
+
await self.db.flush()
|
| 250 |
+
|
| 251 |
+
# ---------------------------------------------------------------- access requests (admin side)
|
| 252 |
+
|
| 253 |
+
@staticmethod
|
| 254 |
+
def _request_out(request: CoachAccessRequest, applicant: Account) -> RequestOut:
|
| 255 |
+
return RequestOut(id=request.id, user_id=applicant.id, name=applicant.name, code=request.code,
|
| 256 |
+
at=request.created_at, also_player=applicant.role == "player", status=request.status)
|
| 257 |
+
|
| 258 |
+
async def list_requests(self, staff: Staff, status: str, paging: PageParams) -> RequestPage:
|
| 259 |
+
rows = await self.repo.requests(staff.team_id, status, paging.limit, paging.cursor) # type: ignore[arg-type]
|
| 260 |
+
page = rows[:paging.limit]
|
| 261 |
+
next_cursor = encode_cursor(page[-1][0].created_at, page[-1][0].id) if len(rows) > paging.limit else None
|
| 262 |
+
return RequestPage(items=[self._request_out(r, a) for r, a in page], next_cursor=next_cursor,
|
| 263 |
+
total_pending=await self.repo.total_pending(staff.team_id)) # type: ignore[arg-type]
|
| 264 |
+
|
| 265 |
+
async def decide(self, staff: Staff, request_id: UUID, body: DecisionIn) -> DecisionOut:
|
| 266 |
+
team = await self._team(staff)
|
| 267 |
+
request = await self.repo.locked_request(team.id, request_id)
|
| 268 |
+
if request is None:
|
| 269 |
+
raise NotFound("We couldn't find that request.")
|
| 270 |
+
applicant = await self.repo.account(request.applicant_id)
|
| 271 |
+
target = "approved" if body.decision == "approve" else "declined"
|
| 272 |
+
if request.status != "pending":
|
| 273 |
+
if request.status != target:
|
| 274 |
+
raise Conflict("This request was already decided.", code="REQUEST_ALREADY_DECIDED")
|
| 275 |
+
coach = None
|
| 276 |
+
if target == "approved":
|
| 277 |
+
coach = await self._out(team, await self._find(team, request.applicant_id), staff.id,
|
| 278 |
+
*self._period(None, None))
|
| 279 |
+
return DecisionOut(request=self._request_out(request, applicant), coach=coach) # type: ignore[arg-type]
|
| 280 |
+
coach = None
|
| 281 |
+
if target == "approved":
|
| 282 |
+
if body.group_ids and await self.repo.count_groups(team.id, body.group_ids) != len(set(body.group_ids)):
|
| 283 |
+
raise Unprocessable("A group isn't part of this academy.", code="INVALID_GROUP")
|
| 284 |
+
code = await self.repo.code_row(request.code)
|
| 285 |
+
role = body.role or (code.role if code else "coach")
|
| 286 |
+
membership = await self._upsert_membership(team.id, request.applicant_id, role, body.sees_all,
|
| 287 |
+
body.group_ids, request.code)
|
| 288 |
+
coach = await self._out(team, self._member(membership, applicant), staff.id, # type: ignore[arg-type]
|
| 289 |
+
*self._period(None, None))
|
| 290 |
+
request.status = target
|
| 291 |
+
request.decided_by_id = staff.id
|
| 292 |
+
request.decided_at = _now()
|
| 293 |
+
await self.db.flush()
|
| 294 |
+
return DecisionOut(request=self._request_out(request, applicant), coach=coach) # type: ignore[arg-type]
|
| 295 |
+
|
| 296 |
+
async def _upsert_membership(self, team_id: UUID, account_id: UUID, role: str, sees_all: bool,
|
| 297 |
+
group_ids: list[UUID] | None, code: str) -> AcademyMembership:
|
| 298 |
+
"""Creates the member, or reactivates one that was removed or paused, with the role's permissions."""
|
| 299 |
+
permissions = normalize_permissions(role)
|
| 300 |
+
membership = await self.repo.membership(team_id, account_id, lock=True)
|
| 301 |
+
if membership is None:
|
| 302 |
+
membership = await self.repo.create(team_id=team_id, account_id=account_id, role=role, status="active",
|
| 303 |
+
sees_all=sees_all, permissions=permissions, joined_with=code)
|
| 304 |
+
else:
|
| 305 |
+
membership.role, membership.status, membership.sees_all = role, "active", sees_all
|
| 306 |
+
membership.permissions, membership.joined_with = permissions, code
|
| 307 |
+
membership.version += 1
|
| 308 |
+
await self.db.flush()
|
| 309 |
+
await self.db.refresh(membership)
|
| 310 |
+
if group_ids:
|
| 311 |
+
await self.repo.add_groups(account_id, group_ids)
|
| 312 |
+
return membership
|
| 313 |
+
|
| 314 |
+
# ---------------------------------------------------------------- staff codes
|
| 315 |
+
|
| 316 |
+
async def list_codes(self, staff: Staff, status: str, paging: PageParams):
|
| 317 |
+
now = _now()
|
| 318 |
+
rows = await self.repo.codes(staff.team_id, status, now, paging.limit, paging.cursor) # type: ignore[arg-type]
|
| 319 |
+
page = rows[:paging.limit]
|
| 320 |
+
next_cursor = encode_cursor(page[-1].created_at, page[-1].id) if len(rows) > paging.limit else None
|
| 321 |
+
return [code_out(c, now) for c in page], next_cursor
|
| 322 |
+
|
| 323 |
+
async def create_code(self, staff: Staff, body: StaffCodeCreate) -> StaffCodeOut:
|
| 324 |
+
for _ in range(10):
|
| 325 |
+
code = new_code()
|
| 326 |
+
if not await self.repo.code_exists(code):
|
| 327 |
+
break
|
| 328 |
+
else:
|
| 329 |
+
raise Conflict("Couldn't generate a code. Please try again.", code="CODE_COLLISION")
|
| 330 |
+
now = _now()
|
| 331 |
+
row = StaffCode(team_id=staff.team_id, code=code, role=body.role,
|
| 332 |
+
expires_at=now + timedelta(days=body.expires_days),
|
| 333 |
+
max_uses=body.max_uses, uses=0, approval=body.approval, created_by_id=staff.id)
|
| 334 |
+
self.db.add(row)
|
| 335 |
+
await self.db.flush()
|
| 336 |
+
await self.db.refresh(row)
|
| 337 |
+
return code_out(row, now)
|
| 338 |
+
|
| 339 |
+
async def revoke_code(self, staff: Staff, raw_code: str) -> None:
|
| 340 |
+
row = await self.repo.code_row(normalize_code(raw_code), team_id=staff.team_id, lock=True)
|
| 341 |
+
if row is None:
|
| 342 |
+
raise NotFound("We couldn't find that code.")
|
| 343 |
+
if row.revoked_at is None:
|
| 344 |
+
row.revoked_at = _now()
|
| 345 |
+
await self.db.flush()
|
| 346 |
+
|
backend/app/modules/accounts/repository.py
CHANGED
|
@@ -6,6 +6,7 @@ from uuid import UUID
|
|
| 6 |
from sqlalchemy import exists, select
|
| 7 |
|
| 8 |
from app.common.base_repository import BaseRepository
|
|
|
|
| 9 |
from app.modules.accounts.models import Account
|
| 10 |
from app.modules.sessions.models import SwingSession
|
| 11 |
from app.modules.teams.models import Team
|
|
@@ -38,3 +39,17 @@ class AccountRepository(BaseRepository[Account]):
|
|
| 38 |
|
| 39 |
async def upload_keys(self, owner_id: UUID) -> Sequence[str]:
|
| 40 |
return (await self.session.scalars(select(Upload.object_key).where(Upload.owner_id == owner_id))).all()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from sqlalchemy import exists, select
|
| 7 |
|
| 8 |
from app.common.base_repository import BaseRepository
|
| 9 |
+
from app.modules.academy.models import CoachAccessRequest, GroupCoach, PlayerGroup
|
| 10 |
from app.modules.accounts.models import Account
|
| 11 |
from app.modules.sessions.models import SwingSession
|
| 12 |
from app.modules.teams.models import Team
|
|
|
|
| 39 |
|
| 40 |
async def upload_keys(self, owner_id: UUID) -> Sequence[str]:
|
| 41 |
return (await self.session.scalars(select(Upload.object_key).where(Upload.owner_id == owner_id))).all()
|
| 42 |
+
|
| 43 |
+
async def latest_coach_request(self, account_id: UUID) -> CoachAccessRequest | None:
|
| 44 |
+
return await self.session.scalar(select(CoachAccessRequest).where(
|
| 45 |
+
CoachAccessRequest.applicant_id == account_id)
|
| 46 |
+
.order_by(CoachAccessRequest.created_at.desc(), CoachAccessRequest.id.desc()).limit(1))
|
| 47 |
+
|
| 48 |
+
async def team_name(self, team_id: UUID) -> str | None:
|
| 49 |
+
return await self.session.scalar(select(Team.name).where(Team.id == team_id))
|
| 50 |
+
|
| 51 |
+
async def coaching_group_ids(self, team_id: UUID, account_id: UUID) -> list[UUID]:
|
| 52 |
+
return list((await self.session.scalars(
|
| 53 |
+
select(GroupCoach.group_id).join(PlayerGroup, PlayerGroup.id == GroupCoach.group_id)
|
| 54 |
+
.where(PlayerGroup.team_id == team_id, GroupCoach.coach_id == account_id)
|
| 55 |
+
.order_by(PlayerGroup.created_at, PlayerGroup.id))).all())
|
backend/app/modules/accounts/schemas.py
CHANGED
|
@@ -7,6 +7,7 @@ from uuid import UUID
|
|
| 7 |
from pydantic import Field, field_validator
|
| 8 |
|
| 9 |
from app.common.schemas import RequestModel, ResponseModel
|
|
|
|
| 10 |
from app.modules.accounts.models import Account
|
| 11 |
from app.modules.billing.entitlement import Entitlement
|
| 12 |
from app.modules.teams.schemas import TeamOut
|
|
@@ -58,10 +59,30 @@ class UserBody(ResponseModel):
|
|
| 58 |
user: UserOut
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
class MeOut(ResponseModel):
|
| 62 |
user: UserOut
|
| 63 |
team: TeamOut | None
|
| 64 |
entitlement: Entitlement
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
def _not_null(cls, value):
|
|
|
|
| 7 |
from pydantic import Field, field_validator
|
| 8 |
|
| 9 |
from app.common.schemas import RequestModel, ResponseModel
|
| 10 |
+
from app.modules.academy_staff.schemas import CoachAccessOut
|
| 11 |
from app.modules.accounts.models import Account
|
| 12 |
from app.modules.billing.entitlement import Entitlement
|
| 13 |
from app.modules.teams.schemas import TeamOut
|
|
|
|
| 59 |
user: UserOut
|
| 60 |
|
| 61 |
|
| 62 |
+
class AcademyOut(ResponseModel):
|
| 63 |
+
id: UUID
|
| 64 |
+
name: str
|
| 65 |
+
role: str
|
| 66 |
+
status: str
|
| 67 |
+
sees_all: bool
|
| 68 |
+
group_ids: list[UUID]
|
| 69 |
+
permissions: dict[str, bool]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class CapabilitiesOut(ResponseModel):
|
| 73 |
+
player: bool
|
| 74 |
+
coach: bool
|
| 75 |
+
academy_admin: bool
|
| 76 |
+
corporate_view: bool
|
| 77 |
+
|
| 78 |
+
|
| 79 |
class MeOut(ResponseModel):
|
| 80 |
user: UserOut
|
| 81 |
team: TeamOut | None
|
| 82 |
entitlement: Entitlement
|
| 83 |
+
academy: AcademyOut | None = None
|
| 84 |
+
coach_access: CoachAccessOut
|
| 85 |
+
capabilities: CapabilitiesOut
|
| 86 |
|
| 87 |
|
| 88 |
def _not_null(cls, value):
|
backend/app/modules/accounts/service.py
CHANGED
|
@@ -4,11 +4,13 @@ from decimal import Decimal
|
|
| 4 |
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
|
|
|
|
| 7 |
from app.core.errors import Conflict
|
| 8 |
from app.integrations.storage import StorageClient
|
|
|
|
| 9 |
from app.modules.accounts.models import Account
|
| 10 |
from app.modules.accounts.repository import AccountRepository
|
| 11 |
-
from app.modules.accounts.schemas import MeOut, MeUpdate, UserOut
|
| 12 |
from app.modules.billing.entitlement import EntitlementService
|
| 13 |
from app.modules.teams.schemas import TeamOut
|
| 14 |
|
|
@@ -34,8 +36,28 @@ class AccountService:
|
|
| 34 |
t, coach_name = found
|
| 35 |
team = TeamOut(id=t.id, code=t.code, name=t.name, coach_id=t.coach_id, coach_name=coach_name,
|
| 36 |
coaching=t.coaching, created_at=t.created_at)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
return MeOut(user=await self.user(account), team=team,
|
| 38 |
-
entitlement=await EntitlementService(self.db).get(account.id)
|
|
|
|
| 39 |
|
| 40 |
async def update(self, account: Account, patch: MeUpdate) -> UserOut:
|
| 41 |
values = patch.model_dump(exclude_unset=True, exclude={"profile"})
|
|
|
|
| 4 |
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
|
| 7 |
+
from app.common.academy_access import staff_context
|
| 8 |
from app.core.errors import Conflict
|
| 9 |
from app.integrations.storage import StorageClient
|
| 10 |
+
from app.modules.academy_staff.schemas import CoachAccessOut
|
| 11 |
from app.modules.accounts.models import Account
|
| 12 |
from app.modules.accounts.repository import AccountRepository
|
| 13 |
+
from app.modules.accounts.schemas import AcademyOut, CapabilitiesOut, MeOut, MeUpdate, UserOut
|
| 14 |
from app.modules.billing.entitlement import EntitlementService
|
| 15 |
from app.modules.teams.schemas import TeamOut
|
| 16 |
|
|
|
|
| 36 |
t, coach_name = found
|
| 37 |
team = TeamOut(id=t.id, code=t.code, name=t.name, coach_id=t.coach_id, coach_name=coach_name,
|
| 38 |
coaching=t.coaching, created_at=t.created_at)
|
| 39 |
+
staff = await staff_context(self.db, account)
|
| 40 |
+
academy = None
|
| 41 |
+
if staff is not None and staff.team_id is not None:
|
| 42 |
+
academy = AcademyOut(
|
| 43 |
+
id=staff.team_id, name=await self.accounts.team_name(staff.team_id) or "", role=staff.role,
|
| 44 |
+
status="active", sees_all=staff.sees_all,
|
| 45 |
+
group_ids=await self.accounts.coaching_group_ids(staff.team_id, account.id),
|
| 46 |
+
permissions=staff.permissions)
|
| 47 |
+
latest = await self.accounts.latest_coach_request(account.id)
|
| 48 |
+
if academy is not None:
|
| 49 |
+
approved = latest is not None and latest.status == "approved"
|
| 50 |
+
access = CoachAccessOut(status="approved", code=latest.code if approved else None,
|
| 51 |
+
sent_at=latest.created_at if approved else None)
|
| 52 |
+
elif latest is None:
|
| 53 |
+
access = CoachAccessOut(status="none", code=None, sent_at=None)
|
| 54 |
+
else:
|
| 55 |
+
access = CoachAccessOut(status=latest.status, code=latest.code, sent_at=latest.created_at)
|
| 56 |
+
capabilities = CapabilitiesOut(player=account.role == "player", coach=staff is not None,
|
| 57 |
+
academy_admin=staff is not None and staff.is_admin, corporate_view=False)
|
| 58 |
return MeOut(user=await self.user(account), team=team,
|
| 59 |
+
entitlement=await EntitlementService(self.db).get(account.id),
|
| 60 |
+
academy=academy, coach_access=access, capabilities=capabilities)
|
| 61 |
|
| 62 |
async def update(self, account: Account, patch: MeUpdate) -> UserOut:
|
| 63 |
values = patch.model_dump(exclude_unset=True, exclude={"profile"})
|
backend/app/modules/arm_care/__init__.py
ADDED
|
File without changes
|
backend/app/modules/arm_care/controller.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""N23-N25: arm care (player only)."""
|
| 2 |
+
|
| 3 |
+
from datetime import date
|
| 4 |
+
from typing import Annotated
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, Depends, Header, Query
|
| 7 |
+
|
| 8 |
+
from app.core.dependencies import CurrentPlayer, Db
|
| 9 |
+
from app.integrations.push import PushClient, get_push_client
|
| 10 |
+
from app.modules.arm_care.schemas import ArmCareEnvelope, FeelIn, FeelOut, OutingIn, OutingResult
|
| 11 |
+
from app.modules.arm_care.service import ArmCareService
|
| 12 |
+
from app.modules.idempotency.service import run_idempotent
|
| 13 |
+
|
| 14 |
+
router = APIRouter(prefix="/v1/me/arm-care", tags=["arm-care"])
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@router.get("", response_model=ArmCareEnvelope)
|
| 18 |
+
async def get_arm_care(player: CurrentPlayer, db: Db, start: Annotated[date | None, Query(alias="from")] = None,
|
| 19 |
+
end: Annotated[date | None, Query(alias="to")] = None) -> ArmCareEnvelope:
|
| 20 |
+
return ArmCareEnvelope(arm_care=await ArmCareService(db).get(player, start, end))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@router.post("/outings", status_code=201, response_model=OutingResult)
|
| 24 |
+
async def add_outing(body: OutingIn, player: CurrentPlayer, db: Db,
|
| 25 |
+
push: Annotated[PushClient, Depends(get_push_client)],
|
| 26 |
+
idempotency_key: Annotated[str | None, Header(max_length=128)] = None):
|
| 27 |
+
service = ArmCareService(db, push)
|
| 28 |
+
|
| 29 |
+
async def handler() -> OutingResult:
|
| 30 |
+
return await service.add_outing(player, body)
|
| 31 |
+
|
| 32 |
+
return await run_idempotent(db, player.id, idempotency_key, body, handler, status_code=201)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@router.put("/feel", response_model=FeelOut)
|
| 36 |
+
async def set_feel(body: FeelIn, player: CurrentPlayer, db: Db) -> FeelOut:
|
| 37 |
+
return await ArmCareService(db).set_feel(player, body)
|
backend/app/modules/arm_care/models.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import date
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import CheckConstraint, Date, ForeignKey, Index, SmallInteger, String, text
|
| 5 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 6 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 7 |
+
|
| 8 |
+
from app.common.base_model import Base, CreatedAtMixin, IdMixin
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _owner() -> Mapped[uuid.UUID]:
|
| 12 |
+
return mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ArmOuting(IdMixin, CreatedAtMixin, Base):
|
| 16 |
+
"""A game pitch count the player logged. local_date is the player's calendar day."""
|
| 17 |
+
|
| 18 |
+
__tablename__ = "arm_outings"
|
| 19 |
+
__table_args__ = (
|
| 20 |
+
CheckConstraint("pitches BETWEEN 1 AND 200", name="pitches"),
|
| 21 |
+
CheckConstraint("source IN ('game')", name="source"),
|
| 22 |
+
Index("ix_arm_outings_owner_id_local_date", "owner_id", text("local_date DESC")),
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
owner_id: Mapped[uuid.UUID] = _owner()
|
| 26 |
+
local_date: Mapped[date] = mapped_column(Date)
|
| 27 |
+
pitches: Mapped[int] = mapped_column(SmallInteger)
|
| 28 |
+
source: Mapped[str] = mapped_column(String(8), server_default="game")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ArmFeel(IdMixin, CreatedAtMixin, Base):
|
| 32 |
+
"""Arm-feel reports; the newest one is the current feel."""
|
| 33 |
+
|
| 34 |
+
__tablename__ = "arm_feel_events"
|
| 35 |
+
__table_args__ = (
|
| 36 |
+
CheckConstraint("feel IN ('sore', 'tight', 'good')", name="feel"),
|
| 37 |
+
Index("ix_arm_feel_events_owner_id_created_at", "owner_id", text("created_at DESC")),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
owner_id: Mapped[uuid.UUID] = _owner()
|
| 41 |
+
feel: Mapped[str] = mapped_column(String(8))
|
backend/app/modules/arm_care/repository.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import date
|
| 2 |
+
from uuid import UUID
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import select
|
| 5 |
+
|
| 6 |
+
from app.common.base_repository import BaseRepository
|
| 7 |
+
from app.modules.accounts.models import Account
|
| 8 |
+
from app.modules.arm_care.models import ArmFeel, ArmOuting
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class OutingRepository(BaseRepository[ArmOuting]):
|
| 12 |
+
model = ArmOuting
|
| 13 |
+
|
| 14 |
+
async def in_range(self, owner_id: UUID, start: date, end: date) -> list[ArmOuting]:
|
| 15 |
+
query = (select(ArmOuting).where(ArmOuting.owner_id == owner_id, ArmOuting.local_date >= start,
|
| 16 |
+
ArmOuting.local_date <= end)
|
| 17 |
+
.order_by(ArmOuting.local_date.desc(), ArmOuting.created_at.desc(), ArmOuting.id.desc()))
|
| 18 |
+
return list((await self.session.scalars(query)).all())
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FeelRepository(BaseRepository[ArmFeel]):
|
| 22 |
+
model = ArmFeel
|
| 23 |
+
|
| 24 |
+
async def latest(self, owner_id: UUID) -> ArmFeel | None:
|
| 25 |
+
return await self.session.scalar(select(ArmFeel).where(ArmFeel.owner_id == owner_id)
|
| 26 |
+
.order_by(ArmFeel.created_at.desc(), ArmFeel.id.desc()).limit(1))
|
| 27 |
+
|
| 28 |
+
async def lock_owner(self, owner_id: UUID) -> None:
|
| 29 |
+
"""Serialises one player's feel updates."""
|
| 30 |
+
await self.session.scalar(select(Account.id).where(Account.id == owner_id).with_for_update())
|
backend/app/modules/arm_care/schemas.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import date, datetime
|
| 2 |
+
from typing import Annotated, Literal
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
|
| 5 |
+
from pydantic import Field
|
| 6 |
+
|
| 7 |
+
from app.common.schemas import RequestModel, ResponseModel
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class OutingIn(RequestModel):
|
| 11 |
+
pitches: Annotated[int, Field(strict=True, ge=1, le=200)]
|
| 12 |
+
local_date: date | None = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class FeelIn(RequestModel):
|
| 16 |
+
feel: Literal["sore", "tight", "good"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class OutingOut(ResponseModel):
|
| 20 |
+
id: UUID
|
| 21 |
+
date: datetime
|
| 22 |
+
local_date: date
|
| 23 |
+
label: str
|
| 24 |
+
pitches: int
|
| 25 |
+
rest: str | None = None
|
| 26 |
+
rest_days: int | None = None
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ArmCareOut(ResponseModel):
|
| 30 |
+
outings: list[OutingOut]
|
| 31 |
+
feel: str | None
|
| 32 |
+
feel_recorded_at: datetime | None
|
| 33 |
+
daily_max: int | None = None
|
| 34 |
+
innings_last_12_months: int | None = None
|
| 35 |
+
innings_limit: int | None = None
|
| 36 |
+
rest_status: str = "unknown"
|
| 37 |
+
next_eligible_date: date | None = None
|
| 38 |
+
rule_version: str | None = None
|
| 39 |
+
unavailable_reason: str | None = "Age-specific policy and innings source not configured"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class ArmCareEnvelope(ResponseModel):
|
| 43 |
+
arm_care: ArmCareOut
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class OutingResult(ResponseModel):
|
| 47 |
+
outing: OutingOut
|
| 48 |
+
arm_care: ArmCareOut
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class FeelOut(ResponseModel):
|
| 52 |
+
feel: str
|
| 53 |
+
recorded_at: datetime
|
backend/app/modules/arm_care/service.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Arm care (N23-N25). No rest policy is configured, so the assessment is always "unknown"."""
|
| 2 |
+
|
| 3 |
+
from datetime import UTC, date, datetime, timedelta
|
| 4 |
+
|
| 5 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
+
|
| 7 |
+
from app.common.academy_access import coaches_of_player
|
| 8 |
+
from app.common.notify import notify
|
| 9 |
+
from app.core.errors import ValidationFailed
|
| 10 |
+
from app.integrations.push import PushClient
|
| 11 |
+
from app.modules.accounts.models import Account
|
| 12 |
+
from app.modules.arm_care.repository import FeelRepository, OutingRepository
|
| 13 |
+
from app.modules.arm_care.schemas import ArmCareOut, FeelIn, FeelOut, OutingIn, OutingOut, OutingResult
|
| 14 |
+
|
| 15 |
+
DEFAULT_DAYS = 30
|
| 16 |
+
MAX_DAYS = 366
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _outing(o) -> OutingOut:
|
| 20 |
+
return OutingOut(id=o.id, date=o.created_at, local_date=o.local_date, label="Game, logged by you",
|
| 21 |
+
pitches=o.pitches)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class ArmCareService:
|
| 25 |
+
def __init__(self, db: AsyncSession, push: PushClient | None = None):
|
| 26 |
+
self.db = db
|
| 27 |
+
self.push = push
|
| 28 |
+
self.outings = OutingRepository(db)
|
| 29 |
+
self.feels = FeelRepository(db)
|
| 30 |
+
|
| 31 |
+
async def get(self, player: Account, start: date | None = None, end: date | None = None) -> ArmCareOut:
|
| 32 |
+
today = datetime.now(UTC).date()
|
| 33 |
+
end = end or today + timedelta(days=1) # a player ahead of UTC may already log tomorrow's date
|
| 34 |
+
start = start or end - timedelta(days=DEFAULT_DAYS)
|
| 35 |
+
if end < start:
|
| 36 |
+
raise ValidationFailed(fields={"to": "Must be on or after from."})
|
| 37 |
+
if (end - start).days > MAX_DAYS:
|
| 38 |
+
raise ValidationFailed(fields={"to": f"The range can be at most {MAX_DAYS} days."})
|
| 39 |
+
rows = await self.outings.in_range(player.id, start, end)
|
| 40 |
+
latest = await self.feels.latest(player.id)
|
| 41 |
+
return ArmCareOut(outings=[_outing(o) for o in rows], feel=latest.feel if latest else None,
|
| 42 |
+
feel_recorded_at=latest.created_at if latest else None)
|
| 43 |
+
|
| 44 |
+
async def add_outing(self, player: Account, body: OutingIn) -> OutingResult:
|
| 45 |
+
today = datetime.now(UTC).date()
|
| 46 |
+
local_date = body.local_date or today
|
| 47 |
+
# Timezones are not modelled yet, so a player up to a day ahead of UTC may be on "tomorrow".
|
| 48 |
+
if local_date > today + timedelta(days=1):
|
| 49 |
+
raise ValidationFailed(fields={"local_date": "Must not be in the future."})
|
| 50 |
+
if (today - local_date).days > MAX_DAYS:
|
| 51 |
+
raise ValidationFailed(fields={"local_date": f"Must be within the last {MAX_DAYS} days."})
|
| 52 |
+
outing = await self.outings.create(owner_id=player.id, local_date=local_date, pitches=body.pitches)
|
| 53 |
+
name = player.name or "Your player"
|
| 54 |
+
for coach_id in await coaches_of_player(self.db, player):
|
| 55 |
+
await notify(self.db, self.push, coach_id, kind="armcare", title=f"{name} logged {body.pitches} pitches",
|
| 56 |
+
target={}, event_key=f"outing:{outing.id}")
|
| 57 |
+
end = max(local_date, today)
|
| 58 |
+
start = max(min(local_date, today - timedelta(days=DEFAULT_DAYS)), end - timedelta(days=MAX_DAYS))
|
| 59 |
+
arm_care = await self.get(player, start, end)
|
| 60 |
+
return OutingResult(outing=_outing(outing), arm_care=arm_care)
|
| 61 |
+
|
| 62 |
+
async def set_feel(self, player: Account, body: FeelIn) -> FeelOut:
|
| 63 |
+
await self.feels.lock_owner(player.id)
|
| 64 |
+
latest = await self.feels.latest(player.id)
|
| 65 |
+
if latest is not None and latest.feel == body.feel and latest.created_at.date() == datetime.now(UTC).date():
|
| 66 |
+
return FeelOut(feel=latest.feel, recorded_at=latest.created_at)
|
| 67 |
+
event = await self.feels.create(owner_id=player.id, feel=body.feel)
|
| 68 |
+
return FeelOut(feel=event.feel, recorded_at=event.created_at)
|
backend/app/modules/assignments/__init__.py
ADDED
|
File without changes
|
backend/app/modules/assignments/controller.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""N20-N22: drill assignments and set completion."""
|
| 2 |
+
|
| 3 |
+
from typing import Annotated, Literal
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, Depends, Header, Query
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
|
| 9 |
+
from app.common.academy_access import CurrentStaff
|
| 10 |
+
from app.core.dependencies import CurrentAccount, CurrentPlayer, Db, Paging, Storage
|
| 11 |
+
from app.integrations.push import PushClient, get_push_client
|
| 12 |
+
from app.modules.assignments.schemas import AssignIn, AssignmentEnvelope, AssignmentPage, Mode, SetIn, SetResult
|
| 13 |
+
from app.modules.assignments.service import AssignmentService
|
| 14 |
+
from app.modules.idempotency.service import run_idempotent
|
| 15 |
+
|
| 16 |
+
router = APIRouter(prefix="/v1", tags=["assignments"])
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class _Scoped(BaseModel):
|
| 20 |
+
"""Idempotency payload that also covers the path id, so one key cannot replay across targets."""
|
| 21 |
+
|
| 22 |
+
target: UUID
|
| 23 |
+
body: dict
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@router.get("/drill-assignments", response_model=AssignmentPage)
|
| 27 |
+
async def list_assignments(
|
| 28 |
+
mode: Annotated[Mode, Query()], account: CurrentAccount, db: Db, storage: Storage, paging: Paging,
|
| 29 |
+
player_id: UUID | None = None, status: Literal["open", "completed", "all"] = "all",
|
| 30 |
+
) -> AssignmentPage:
|
| 31 |
+
return await AssignmentService(db, storage).list(account, mode, player_id, status, paging)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@router.post("/coach/players/{player_id}/drill-assignments", status_code=201, response_model=AssignmentEnvelope)
|
| 35 |
+
async def assign_drill(
|
| 36 |
+
player_id: UUID, body: AssignIn, staff: CurrentStaff, db: Db, storage: Storage,
|
| 37 |
+
push: Annotated[PushClient, Depends(get_push_client)],
|
| 38 |
+
idempotency_key: Annotated[str | None, Header(max_length=128)] = None,
|
| 39 |
+
):
|
| 40 |
+
service = AssignmentService(db, storage, push)
|
| 41 |
+
|
| 42 |
+
async def handler() -> AssignmentEnvelope:
|
| 43 |
+
return AssignmentEnvelope(assignment=await service.assign(staff, player_id, body))
|
| 44 |
+
|
| 45 |
+
scoped = _Scoped(target=player_id, body=body.model_dump(mode="json"))
|
| 46 |
+
return await run_idempotent(db, staff.id, idempotency_key, scoped, handler, status_code=201)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@router.post("/drill-assignments/{assignment_id}/sets", status_code=201, response_model=SetResult)
|
| 50 |
+
async def log_set(
|
| 51 |
+
assignment_id: UUID, body: SetIn, player: CurrentPlayer, db: Db, storage: Storage,
|
| 52 |
+
idempotency_key: Annotated[str | None, Header(max_length=128)] = None,
|
| 53 |
+
):
|
| 54 |
+
service = AssignmentService(db, storage)
|
| 55 |
+
|
| 56 |
+
async def handler() -> SetResult:
|
| 57 |
+
return await service.log_set(player, assignment_id, body)
|
| 58 |
+
|
| 59 |
+
return await run_idempotent(db, player.id, idempotency_key,
|
| 60 |
+
_Scoped(target=assignment_id, body=body.model_dump(mode="json")), handler,
|
| 61 |
+
status_code=201)
|
backend/app/modules/assignments/models.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import date
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import CheckConstraint, Date, ForeignKey, Index, SmallInteger, String, UniqueConstraint, text
|
| 5 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 6 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 7 |
+
|
| 8 |
+
from app.common.base_model import Base, CreatedAtMixin, IdMixin
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class DrillAssignment(IdMixin, CreatedAtMixin, Base):
|
| 12 |
+
"""A drill a coach prescribed to one player. name/fixes are snapshots; progress is the count of its sets."""
|
| 13 |
+
|
| 14 |
+
__tablename__ = "drill_assignments"
|
| 15 |
+
__table_args__ = (
|
| 16 |
+
CheckConstraint("mode IN ('h', 'p')", name="mode"),
|
| 17 |
+
CheckConstraint("drill_source IN ('catalog', 'library')", name="drill_source"),
|
| 18 |
+
CheckConstraint("sets BETWEEN 1 AND 10", name="sets"),
|
| 19 |
+
CheckConstraint("reps BETWEEN 1 AND 8", name="reps"),
|
| 20 |
+
Index("ix_drill_assignments_player_id_mode_created_at", "player_id", "mode", text("created_at DESC")),
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="SET NULL"))
|
| 24 |
+
player_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))
|
| 25 |
+
assigned_by_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 26 |
+
UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL")
|
| 27 |
+
)
|
| 28 |
+
mode: Mapped[str] = mapped_column(String(1))
|
| 29 |
+
drill_source: Mapped[str] = mapped_column(String(8))
|
| 30 |
+
drill_id: Mapped[str] = mapped_column(String(40))
|
| 31 |
+
name: Mapped[str] = mapped_column(String(120))
|
| 32 |
+
fixes: Mapped[str] = mapped_column(String(500), server_default="")
|
| 33 |
+
sets: Mapped[int] = mapped_column(SmallInteger, server_default="3")
|
| 34 |
+
reps: Mapped[int] = mapped_column(SmallInteger, server_default="8")
|
| 35 |
+
due_date: Mapped[date] = mapped_column(Date)
|
| 36 |
+
session_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 37 |
+
UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL")
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class AssignmentSet(IdMixin, CreatedAtMixin, Base):
|
| 42 |
+
"""One completed set of an assignment; drill_log_id is the practice log written in the same transaction."""
|
| 43 |
+
|
| 44 |
+
__tablename__ = "assignment_sets"
|
| 45 |
+
__table_args__ = (UniqueConstraint("assignment_id", "set_number"),)
|
| 46 |
+
|
| 47 |
+
assignment_id: Mapped[uuid.UUID] = mapped_column(
|
| 48 |
+
UUID(as_uuid=True), ForeignKey("drill_assignments.id", ondelete="CASCADE")
|
| 49 |
+
)
|
| 50 |
+
set_number: Mapped[int] = mapped_column(SmallInteger)
|
| 51 |
+
reps_done: Mapped[int] = mapped_column(SmallInteger)
|
| 52 |
+
day: Mapped[date] = mapped_column(Date)
|
| 53 |
+
drill_log_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 54 |
+
UUID(as_uuid=True), ForeignKey("drill_logs.id", ondelete="SET NULL")
|
| 55 |
+
)
|
backend/app/modules/assignments/repository.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import date
|
| 2 |
+
from uuid import UUID
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import Select, exists, func, select, tuple_
|
| 5 |
+
|
| 6 |
+
from app.common.base_repository import BaseRepository
|
| 7 |
+
from app.core.pagination import Cursor
|
| 8 |
+
from app.modules.academy.models import LibraryDrill
|
| 9 |
+
from app.modules.accounts.models import Account
|
| 10 |
+
from app.modules.assignments.models import AssignmentSet, DrillAssignment
|
| 11 |
+
from app.modules.drills.models import DrillLog
|
| 12 |
+
from app.modules.sessions.models import SwingSession
|
| 13 |
+
from app.modules.uploads.models import Upload
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class AssignmentRepository(BaseRepository[DrillAssignment]):
|
| 17 |
+
model = DrillAssignment
|
| 18 |
+
|
| 19 |
+
def _done(self):
|
| 20 |
+
return (select(AssignmentSet.assignment_id, func.count().label("n"))
|
| 21 |
+
.group_by(AssignmentSet.assignment_id).subquery())
|
| 22 |
+
|
| 23 |
+
async def with_progress(self, assignment_id: UUID, *, player_id: UUID | None = None, lock: bool = False):
|
| 24 |
+
"""(assignment, done, assigned_by name) or None."""
|
| 25 |
+
query = select(DrillAssignment).where(DrillAssignment.id == assignment_id)
|
| 26 |
+
if player_id is not None:
|
| 27 |
+
query = query.where(DrillAssignment.player_id == player_id)
|
| 28 |
+
assignment = await self.session.scalar(query.with_for_update() if lock else query)
|
| 29 |
+
return assignment
|
| 30 |
+
|
| 31 |
+
async def done_count(self, assignment_id: UUID) -> int:
|
| 32 |
+
return await self.session.scalar(
|
| 33 |
+
select(func.count()).select_from(AssignmentSet).where(AssignmentSet.assignment_id == assignment_id)) or 0
|
| 34 |
+
|
| 35 |
+
async def names(self, ids: set[UUID | None]) -> dict[UUID, str]:
|
| 36 |
+
ids = {i for i in ids if i}
|
| 37 |
+
if not ids:
|
| 38 |
+
return {}
|
| 39 |
+
rows = await self.session.execute(select(Account.id, Account.name).where(Account.id.in_(ids)))
|
| 40 |
+
return {i: n for i, n in rows}
|
| 41 |
+
|
| 42 |
+
def list_query(self, *, mode: str, status: str, player_ids: Select | None, player_id: UUID | None,
|
| 43 |
+
team_id: UUID | None) -> Select:
|
| 44 |
+
done = self._done()
|
| 45 |
+
count = func.coalesce(done.c.n, 0)
|
| 46 |
+
query = (select(DrillAssignment, count).outerjoin(done, done.c.assignment_id == DrillAssignment.id)
|
| 47 |
+
.where(DrillAssignment.mode == mode))
|
| 48 |
+
if player_id is not None:
|
| 49 |
+
query = query.where(DrillAssignment.player_id == player_id)
|
| 50 |
+
if player_ids is not None:
|
| 51 |
+
query = query.where(DrillAssignment.player_id.in_(player_ids), DrillAssignment.team_id == team_id)
|
| 52 |
+
if status == "open":
|
| 53 |
+
query = query.where(count < DrillAssignment.sets)
|
| 54 |
+
elif status == "completed":
|
| 55 |
+
query = query.where(count >= DrillAssignment.sets)
|
| 56 |
+
return query
|
| 57 |
+
|
| 58 |
+
async def page(self, query: Select, cursor: Cursor | None, limit: int):
|
| 59 |
+
if cursor is not None:
|
| 60 |
+
query = query.where(tuple_(DrillAssignment.created_at, DrillAssignment.id)
|
| 61 |
+
< tuple_(cursor.created_at, cursor.id))
|
| 62 |
+
query = query.order_by(DrillAssignment.created_at.desc(), DrillAssignment.id.desc()).limit(limit + 1)
|
| 63 |
+
return (await self.session.execute(query)).all()
|
| 64 |
+
|
| 65 |
+
async def library_drill(self, drill_id: UUID, team_id: UUID | None) -> LibraryDrill | None:
|
| 66 |
+
return await self.session.scalar(select(LibraryDrill).where(
|
| 67 |
+
LibraryDrill.id == drill_id, LibraryDrill.team_id == team_id))
|
| 68 |
+
|
| 69 |
+
async def library_media_keys(self, drill_ids: set[UUID]) -> dict[UUID, tuple[UUID, str]]:
|
| 70 |
+
"""library drill id -> (upload id, object key) for drills that still have a video."""
|
| 71 |
+
if not drill_ids:
|
| 72 |
+
return {}
|
| 73 |
+
rows = await self.session.execute(
|
| 74 |
+
select(LibraryDrill.id, Upload.id, Upload.object_key)
|
| 75 |
+
.join(Upload, Upload.id == LibraryDrill.upload_id).where(LibraryDrill.id.in_(drill_ids)))
|
| 76 |
+
return {drill: (upload, key) for drill, upload, key in rows}
|
| 77 |
+
|
| 78 |
+
async def owns_session(self, player_id: UUID, session_id: UUID) -> bool:
|
| 79 |
+
return bool(await self.session.scalar(select(exists().where(
|
| 80 |
+
SwingSession.id == session_id, SwingSession.owner_id == player_id, SwingSession.deleted_at.is_(None)))))
|
| 81 |
+
|
| 82 |
+
async def existing_set(self, assignment_id: UUID, set_number: int) -> AssignmentSet | None:
|
| 83 |
+
return await self.session.scalar(select(AssignmentSet).where(
|
| 84 |
+
AssignmentSet.assignment_id == assignment_id, AssignmentSet.set_number == set_number))
|
| 85 |
+
|
| 86 |
+
async def add_set(self, assignment: DrillAssignment, set_number: int, reps_done: int, day: date) -> AssignmentSet:
|
| 87 |
+
log = DrillLog(owner_id=assignment.player_id, session_id=assignment.session_id, drill_id=assignment.drill_id,
|
| 88 |
+
assignment_id=assignment.id, reps=reps_done, day=day)
|
| 89 |
+
self.session.add(log)
|
| 90 |
+
await self.session.flush()
|
| 91 |
+
row = AssignmentSet(assignment_id=assignment.id, set_number=set_number, reps_done=reps_done, day=day,
|
| 92 |
+
drill_log_id=log.id)
|
| 93 |
+
self.session.add(row)
|
| 94 |
+
await self.session.flush()
|
| 95 |
+
await self.session.refresh(row)
|
| 96 |
+
return row
|
backend/app/modules/assignments/schemas.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import date, datetime
|
| 2 |
+
from typing import Literal
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
|
| 5 |
+
from pydantic import Field
|
| 6 |
+
|
| 7 |
+
from app.common.schemas import MediaRef, Page, RequestModel, ResponseModel
|
| 8 |
+
|
| 9 |
+
Mode = Literal["h", "p"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class AssignIn(RequestModel):
|
| 13 |
+
mode: Mode
|
| 14 |
+
drill_source: Literal["catalog", "library"]
|
| 15 |
+
drill_id: str = Field(min_length=1, max_length=40)
|
| 16 |
+
due_date: date
|
| 17 |
+
source_session_id: UUID | None = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SetIn(RequestModel):
|
| 21 |
+
set_number: int = Field(ge=1)
|
| 22 |
+
reps_done: int = Field(ge=1)
|
| 23 |
+
day: date
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class AssignmentOut(ResponseModel):
|
| 27 |
+
id: UUID
|
| 28 |
+
player_id: UUID
|
| 29 |
+
mode: str
|
| 30 |
+
drill_id: str
|
| 31 |
+
drill_source: str
|
| 32 |
+
name: str
|
| 33 |
+
fixes: str
|
| 34 |
+
sets: int
|
| 35 |
+
reps: int
|
| 36 |
+
due: str
|
| 37 |
+
due_date: date
|
| 38 |
+
assigned_by: str | None
|
| 39 |
+
assigned_by_id: UUID | None
|
| 40 |
+
done: int
|
| 41 |
+
session_id: UUID | None
|
| 42 |
+
assigned_at: datetime
|
| 43 |
+
media: MediaRef | None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class AssignmentEnvelope(ResponseModel):
|
| 47 |
+
assignment: AssignmentOut
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SetLogOut(ResponseModel):
|
| 51 |
+
id: UUID
|
| 52 |
+
set_number: int
|
| 53 |
+
reps_done: int
|
| 54 |
+
day: date
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class SetResult(ResponseModel):
|
| 58 |
+
assignment: AssignmentOut
|
| 59 |
+
set_log: SetLogOut
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
AssignmentPage = Page[AssignmentOut]
|
backend/app/modules/assignments/service.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Drill assignments (N20-N22). Progress is the number of AssignmentSet rows; each set also writes one drill log."""
|
| 2 |
+
|
| 3 |
+
from datetime import UTC, date, datetime, timedelta
|
| 4 |
+
from functools import cache
|
| 5 |
+
from uuid import UUID
|
| 6 |
+
|
| 7 |
+
from ai_coach.knowledge import all_drills
|
| 8 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
+
|
| 10 |
+
from app.common.academy_access import (
|
| 11 |
+
Staff,
|
| 12 |
+
require_player,
|
| 13 |
+
sessions_shared,
|
| 14 |
+
staff_context,
|
| 15 |
+
visible_players_query,
|
| 16 |
+
)
|
| 17 |
+
from app.common.notify import notify
|
| 18 |
+
from app.common.schemas import MediaRef
|
| 19 |
+
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed
|
| 20 |
+
from app.core.pagination import PageParams, encode_cursor
|
| 21 |
+
from app.integrations.push import PushClient
|
| 22 |
+
from app.integrations.storage import StorageClient
|
| 23 |
+
from app.modules.accounts.models import Account
|
| 24 |
+
from app.modules.assignments.models import DrillAssignment
|
| 25 |
+
from app.modules.assignments.repository import AssignmentRepository
|
| 26 |
+
from app.modules.assignments.schemas import AssignIn, AssignmentOut, AssignmentPage, SetIn, SetLogOut, SetResult
|
| 27 |
+
|
| 28 |
+
DISCIPLINES = {"h": "hitting", "p": "pitching"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@cache
|
| 32 |
+
def _catalog() -> dict[str, dict]:
|
| 33 |
+
return {d["id"]: d for d in all_drills()}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def due_label(due: date, today: date) -> str:
|
| 37 |
+
days = (due - today).days
|
| 38 |
+
if days == 0:
|
| 39 |
+
return "Today"
|
| 40 |
+
if days == 1:
|
| 41 |
+
return "Tomorrow"
|
| 42 |
+
if 1 < days < 7:
|
| 43 |
+
return f"{due:%A}"
|
| 44 |
+
return f"{due:%b} {due.day:02d}"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class AssignmentService:
|
| 48 |
+
def __init__(self, db: AsyncSession, storage: StorageClient | None = None, push: PushClient | None = None):
|
| 49 |
+
self.db = db
|
| 50 |
+
self.storage = storage
|
| 51 |
+
self.push = push
|
| 52 |
+
self.repo = AssignmentRepository(db)
|
| 53 |
+
|
| 54 |
+
async def _outs(self, rows: list[tuple[DrillAssignment, int]]) -> list[AssignmentOut]:
|
| 55 |
+
names = await self.repo.names({a.assigned_by_id for a, _ in rows})
|
| 56 |
+
library = {UUID(a.drill_id) for a, _ in rows if a.drill_source == "library"}
|
| 57 |
+
media = await self.repo.library_media_keys(library)
|
| 58 |
+
today = datetime.now(UTC).date()
|
| 59 |
+
out = []
|
| 60 |
+
for a, done in rows:
|
| 61 |
+
ref = None
|
| 62 |
+
if a.drill_source == "library" and self.storage is not None and UUID(a.drill_id) in media:
|
| 63 |
+
upload_id, key = media[UUID(a.drill_id)]
|
| 64 |
+
ref = MediaRef(upload_id=upload_id, url=self.storage.presign_get(key),
|
| 65 |
+
expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl))
|
| 66 |
+
out.append(AssignmentOut(
|
| 67 |
+
id=a.id, player_id=a.player_id, mode=a.mode, drill_id=a.drill_id, drill_source=a.drill_source,
|
| 68 |
+
name=a.name, fixes=a.fixes, sets=a.sets, reps=a.reps, due=due_label(a.due_date, today),
|
| 69 |
+
due_date=a.due_date, assigned_by=names.get(a.assigned_by_id) if a.assigned_by_id else None,
|
| 70 |
+
assigned_by_id=a.assigned_by_id, done=int(done), session_id=a.session_id,
|
| 71 |
+
assigned_at=a.created_at, media=ref))
|
| 72 |
+
return out
|
| 73 |
+
|
| 74 |
+
async def _one(self, assignment: DrillAssignment) -> AssignmentOut:
|
| 75 |
+
return (await self._outs([(assignment, await self.repo.done_count(assignment.id))]))[0]
|
| 76 |
+
|
| 77 |
+
async def list(self, account: Account, mode: str, player_id: UUID | None, status: str,
|
| 78 |
+
paging: PageParams) -> AssignmentPage:
|
| 79 |
+
if account.role == "player":
|
| 80 |
+
if player_id is not None and player_id != account.id:
|
| 81 |
+
raise NotFound()
|
| 82 |
+
query = self.repo.list_query(mode=mode, status=status, player_ids=None, player_id=account.id,
|
| 83 |
+
team_id=None)
|
| 84 |
+
else:
|
| 85 |
+
staff = await staff_context(self.db, account)
|
| 86 |
+
if staff is None:
|
| 87 |
+
raise Forbidden("Only coaches can do this.")
|
| 88 |
+
if player_id is not None:
|
| 89 |
+
await require_player(self.db, staff, player_id)
|
| 90 |
+
query = self.repo.list_query(mode=mode, status=status, player_ids=visible_players_query(staff),
|
| 91 |
+
player_id=player_id, team_id=staff.team_id)
|
| 92 |
+
rows = await self.repo.page(query, paging.cursor, paging.limit)
|
| 93 |
+
page = rows[:paging.limit]
|
| 94 |
+
items = await self._outs([(a, n) for a, n in page])
|
| 95 |
+
cursor = encode_cursor(page[-1][0].created_at, page[-1][0].id) if len(rows) > paging.limit else None
|
| 96 |
+
return AssignmentPage(items=items, next_cursor=cursor)
|
| 97 |
+
|
| 98 |
+
async def _source(self, staff: Staff, body: AssignIn) -> tuple[str, str]:
|
| 99 |
+
"""(name, fixes) snapshot of the drill, or the error to raise."""
|
| 100 |
+
if body.drill_source == "catalog":
|
| 101 |
+
drill = _catalog().get(body.drill_id)
|
| 102 |
+
if drill is None:
|
| 103 |
+
raise NotFound("Drill not found.", code="DRILL_NOT_FOUND")
|
| 104 |
+
if drill["discipline"] != DISCIPLINES[body.mode]:
|
| 105 |
+
raise Unprocessable("This drill is for the other mode.", code="MODE_MISMATCH")
|
| 106 |
+
fixes = ", ".join(f.replace("_", " ").capitalize() for f in drill.get("faults", []))
|
| 107 |
+
return drill["name"], fixes
|
| 108 |
+
try:
|
| 109 |
+
library_id = UUID(body.drill_id)
|
| 110 |
+
except ValueError as exc:
|
| 111 |
+
raise ValidationFailed(fields={"drill_id": "Must be a library drill id."}) from exc
|
| 112 |
+
drill = await self.repo.library_drill(library_id, staff.team_id)
|
| 113 |
+
if drill is None:
|
| 114 |
+
raise NotFound("Drill not found.", code="DRILL_NOT_FOUND")
|
| 115 |
+
if drill.mode != body.mode:
|
| 116 |
+
raise Unprocessable("This drill is for the other mode.", code="MODE_MISMATCH")
|
| 117 |
+
return drill.name, drill.fixes
|
| 118 |
+
|
| 119 |
+
async def assign(self, staff: Staff, player_id: UUID, body: AssignIn) -> AssignmentOut:
|
| 120 |
+
staff.require("drills")
|
| 121 |
+
player = await require_player(self.db, staff, player_id)
|
| 122 |
+
if body.due_date < datetime.now(UTC).date():
|
| 123 |
+
raise ValidationFailed(fields={"due_date": "Must not be in the past."})
|
| 124 |
+
name, fixes = await self._source(staff, body)
|
| 125 |
+
if body.source_session_id is not None and not (
|
| 126 |
+
await sessions_shared(self.db, player_id) and await self.repo.owns_session(player_id,
|
| 127 |
+
body.source_session_id)):
|
| 128 |
+
raise NotFound("Session not found.", code="SESSION_NOT_FOUND")
|
| 129 |
+
assignment = await self.repo.create(
|
| 130 |
+
team_id=staff.team_id, player_id=player.id, assigned_by_id=staff.id, mode=body.mode,
|
| 131 |
+
drill_source=body.drill_source, drill_id=body.drill_id, name=name, fixes=fixes, sets=3, reps=8,
|
| 132 |
+
due_date=body.due_date, session_id=body.source_session_id)
|
| 133 |
+
await notify(self.db, self.push, player.id, kind="drill", title="New drill assigned", body=name, target={},
|
| 134 |
+
event_key=f"assignment:{assignment.id}")
|
| 135 |
+
return (await self._outs([(assignment, 0)]))[0]
|
| 136 |
+
|
| 137 |
+
async def log_set(self, player: Account, assignment_id: UUID, body: SetIn) -> SetResult:
|
| 138 |
+
assignment = await self.repo.with_progress(assignment_id, player_id=player.id, lock=True)
|
| 139 |
+
if assignment is None:
|
| 140 |
+
raise NotFound()
|
| 141 |
+
if body.set_number > assignment.sets:
|
| 142 |
+
raise Unprocessable(f"This drill has {assignment.sets} sets.", code="SET_OUT_OF_RANGE")
|
| 143 |
+
if body.reps_done > assignment.reps:
|
| 144 |
+
raise Unprocessable(f"At most {assignment.reps} reps per set.", code="REPS_OUT_OF_RANGE")
|
| 145 |
+
row = await self.repo.existing_set(assignment.id, body.set_number)
|
| 146 |
+
if row is not None and (row.reps_done, row.day) != (body.reps_done, body.day):
|
| 147 |
+
raise Conflict("That set was already logged with different values.", code="SET_ALREADY_LOGGED")
|
| 148 |
+
if row is None:
|
| 149 |
+
row = await self.repo.add_set(assignment, body.set_number, body.reps_done, body.day)
|
| 150 |
+
return SetResult(assignment=await self._one(assignment),
|
| 151 |
+
set_log=SetLogOut(id=row.id, set_number=row.set_number, reps_done=row.reps_done, day=row.day))
|
backend/app/modules/coach/controller.py
CHANGED
|
@@ -6,8 +6,9 @@ from uuid import UUID
|
|
| 6 |
|
| 7 |
from fastapi import APIRouter, Depends, Query
|
| 8 |
|
|
|
|
| 9 |
from app.common.schemas import Items, Page
|
| 10 |
-
from app.core.dependencies import
|
| 11 |
from app.modules.coach.schemas import Mode, QueueResponse, RosterItem
|
| 12 |
from app.modules.coach.service import CoachService
|
| 13 |
from app.modules.sessions.summary import SessionSummary
|
|
@@ -23,17 +24,20 @@ Service = Annotated[CoachService, Depends(get_coach_service)]
|
|
| 23 |
|
| 24 |
|
| 25 |
@router.get("/coach/roster", response_model=Items[RosterItem])
|
| 26 |
-
async def roster(
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
@router.get("/coach/players/{player_id}/sessions", response_model=Page[SessionSummary])
|
| 31 |
-
async def player_sessions(player_id: UUID,
|
| 32 |
mode: Mode | None = None) -> Page[SessionSummary]:
|
| 33 |
-
return await service.player_sessions(
|
| 34 |
|
| 35 |
|
| 36 |
@router.get("/coach/queue", response_model=QueueResponse)
|
| 37 |
-
async def queue(
|
| 38 |
since: Annotated[datetime | None, Query()] = None) -> QueueResponse:
|
| 39 |
-
return await service.queue(
|
|
|
|
| 6 |
|
| 7 |
from fastapi import APIRouter, Depends, Query
|
| 8 |
|
| 9 |
+
from app.common.academy_access import CurrentStaff
|
| 10 |
from app.common.schemas import Items, Page
|
| 11 |
+
from app.core.dependencies import Db, Paging, Storage
|
| 12 |
from app.modules.coach.schemas import Mode, QueueResponse, RosterItem
|
| 13 |
from app.modules.coach.service import CoachService
|
| 14 |
from app.modules.sessions.summary import SessionSummary
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
@router.get("/coach/roster", response_model=Items[RosterItem])
|
| 27 |
+
async def roster(staff: CurrentStaff, service: Service, group_id: UUID | None = None) -> Items[RosterItem]:
|
| 28 |
+
items = await service.roster(staff)
|
| 29 |
+
if group_id is not None:
|
| 30 |
+
items = [i for i in items if group_id in i.group_ids]
|
| 31 |
+
return Items[RosterItem](items=items)
|
| 32 |
|
| 33 |
|
| 34 |
@router.get("/coach/players/{player_id}/sessions", response_model=Page[SessionSummary])
|
| 35 |
+
async def player_sessions(player_id: UUID, staff: CurrentStaff, service: Service, paging: Paging,
|
| 36 |
mode: Mode | None = None) -> Page[SessionSummary]:
|
| 37 |
+
return await service.player_sessions(staff, player_id, mode, paging)
|
| 38 |
|
| 39 |
|
| 40 |
@router.get("/coach/queue", response_model=QueueResponse)
|
| 41 |
+
async def queue(staff: CurrentStaff, service: Service,
|
| 42 |
since: Annotated[datetime | None, Query()] = None) -> QueueResponse:
|
| 43 |
+
return await service.queue(staff, since)
|
backend/app/modules/coach/repository.py
CHANGED
|
@@ -8,11 +8,12 @@ from sqlalchemy import Select, and_, func, or_, select
|
|
| 8 |
|
| 9 |
from app.common.base_repository import BaseRepository
|
| 10 |
from app.core.pagination import Cursor
|
|
|
|
| 11 |
from app.modules.accounts.models import Account
|
| 12 |
from app.modules.reviews.models import Review
|
| 13 |
from app.modules.sessions.models import SwingSession
|
| 14 |
from app.modules.sessions.summary import summary_query
|
| 15 |
-
from app.modules.
|
| 16 |
|
| 17 |
RECENT_PER_MODE = 3
|
| 18 |
|
|
@@ -20,16 +21,24 @@ RECENT_PER_MODE = 3
|
|
| 20 |
class CoachRepository(BaseRepository[Account]):
|
| 21 |
model = Account
|
| 22 |
|
| 23 |
-
async def
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
async def players(self, team_id: UUID) -> Sequence[Account]:
|
| 27 |
-
query = (select(Account).where(Account.team_id == team_id, Account.role == "player")
|
| 28 |
-
.order_by(Account.name, Account.created_at))
|
| 29 |
return (await self.session.execute(query)).scalars().all()
|
| 30 |
|
| 31 |
-
async def
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
async def recent_sessions(self, owner_ids: list[UUID]) -> Sequence:
|
| 35 |
"""Per player and mode, the latest RECENT_PER_MODE+1 analysed self sessions (one extra for the delta)."""
|
|
|
|
| 8 |
|
| 9 |
from app.common.base_repository import BaseRepository
|
| 10 |
from app.core.pagination import Cursor
|
| 11 |
+
from app.modules.academy.models import GroupPlayer
|
| 12 |
from app.modules.accounts.models import Account
|
| 13 |
from app.modules.reviews.models import Review
|
| 14 |
from app.modules.sessions.models import SwingSession
|
| 15 |
from app.modules.sessions.summary import summary_query
|
| 16 |
+
from app.modules.settings.models import UserSettings
|
| 17 |
|
| 18 |
RECENT_PER_MODE = 3
|
| 19 |
|
|
|
|
| 21 |
class CoachRepository(BaseRepository[Account]):
|
| 22 |
model = Account
|
| 23 |
|
| 24 |
+
async def visible_players(self, visible_ids) -> Sequence[Account]:
|
| 25 |
+
"""Accounts for a `visible_players_query` select, by name."""
|
| 26 |
+
query = select(Account).where(Account.id.in_(visible_ids)).order_by(Account.name, Account.created_at)
|
|
|
|
|
|
|
|
|
|
| 27 |
return (await self.session.execute(query)).scalars().all()
|
| 28 |
|
| 29 |
+
async def sessions_hidden(self, player_ids: list[UUID]) -> set[UUID]:
|
| 30 |
+
"""Players who turned off coach_can_see_sessions."""
|
| 31 |
+
query = select(UserSettings.account_id).where(UserSettings.account_id.in_(player_ids),
|
| 32 |
+
UserSettings.coach_can_see_sessions.is_(False))
|
| 33 |
+
return set((await self.session.scalars(query)).all())
|
| 34 |
+
|
| 35 |
+
async def group_ids(self, player_ids: list[UUID]) -> dict[UUID, list[UUID]]:
|
| 36 |
+
query = (select(GroupPlayer.player_id, GroupPlayer.group_id).where(GroupPlayer.player_id.in_(player_ids))
|
| 37 |
+
.order_by(GroupPlayer.group_id))
|
| 38 |
+
result: dict[UUID, list[UUID]] = {}
|
| 39 |
+
for player_id, group_id in (await self.session.execute(query)).all():
|
| 40 |
+
result.setdefault(player_id, []).append(group_id)
|
| 41 |
+
return result
|
| 42 |
|
| 43 |
async def recent_sessions(self, owner_ids: list[UUID]) -> Sequence:
|
| 44 |
"""Per player and mode, the latest RECENT_PER_MODE+1 analysed self sessions (one extra for the delta)."""
|
backend/app/modules/coach/schemas.py
CHANGED
|
@@ -34,6 +34,7 @@ class RosterItem(ResponseModel):
|
|
| 34 |
email: str
|
| 35 |
focus: str
|
| 36 |
level: str | None
|
|
|
|
| 37 |
pending_count: int
|
| 38 |
last: LastByMode
|
| 39 |
recent: RecentByMode
|
|
|
|
| 34 |
email: str
|
| 35 |
focus: str
|
| 36 |
level: str | None
|
| 37 |
+
group_ids: list[UUID] = []
|
| 38 |
pending_count: int
|
| 39 |
last: LastByMode
|
| 40 |
recent: RecentByMode
|
backend/app/modules/coach/service.py
CHANGED
|
@@ -5,8 +5,9 @@ from uuid import UUID
|
|
| 5 |
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
|
|
|
|
| 8 |
from app.common.schemas import Page
|
| 9 |
-
from app.core.errors import
|
| 10 |
from app.core.pagination import PageParams, encode_cursor
|
| 11 |
from app.integrations.storage import StorageClient
|
| 12 |
from app.modules.accounts.models import Account
|
|
@@ -30,18 +31,21 @@ class CoachService:
|
|
| 30 |
self.storage = storage
|
| 31 |
self.repo = CoachRepository(db)
|
| 32 |
|
| 33 |
-
async def _players(self,
|
| 34 |
-
|
| 35 |
-
return list(await self.repo.players(team_id)) if team_id else []
|
| 36 |
|
| 37 |
-
async def roster(self,
|
| 38 |
-
players = await self._players(
|
| 39 |
if not players:
|
| 40 |
return []
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
by_key: dict[tuple[UUID, str], list] = {}
|
| 44 |
-
|
|
|
|
| 45 |
by_key.setdefault((row.owner_id, row.mode), []).append(row)
|
| 46 |
|
| 47 |
items = []
|
|
@@ -59,14 +63,15 @@ class CoachService:
|
|
| 59 |
delta=delta, created_at=newest.created_at, focus_name=newest.focus))
|
| 60 |
setattr(recent, mode, [r.overall_score for r in rows[:3] if r.overall_score is not None])
|
| 61 |
items.append(RosterItem(id=p.id, name=p.name, email=p.email, focus=p.focus, level=p.level,
|
|
|
|
| 62 |
pending_count=pending.get(p.id, 0), last=last, recent=recent))
|
| 63 |
return items
|
| 64 |
|
| 65 |
-
async def player_sessions(self,
|
| 66 |
paging: PageParams) -> Page[SessionSummary]:
|
| 67 |
-
|
| 68 |
-
if
|
| 69 |
-
raise
|
| 70 |
query = player_sessions_query(player_id, mode, paging.cursor, paging.limit + 1)
|
| 71 |
items = await load_summaries(self.db, self.storage, query)
|
| 72 |
next_cursor = None
|
|
@@ -75,11 +80,12 @@ class CoachService:
|
|
| 75 |
next_cursor = encode_cursor(items[-1].created_at, items[-1].id)
|
| 76 |
return Page[SessionSummary](items=items, next_cursor=next_cursor)
|
| 77 |
|
| 78 |
-
async def queue(self,
|
| 79 |
-
players = await self._players(
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
return QueueResponse(open=[], reviewed_today=[])
|
| 82 |
-
names = {p.id: p.name for p in players}
|
| 83 |
ids = list(names)
|
| 84 |
if since is None:
|
| 85 |
since = start_of_today_utc()
|
|
|
|
| 5 |
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
|
| 8 |
+
from app.common.academy_access import Staff, require_player, sessions_shared, visible_players_query
|
| 9 |
from app.common.schemas import Page
|
| 10 |
+
from app.core.errors import Forbidden
|
| 11 |
from app.core.pagination import PageParams, encode_cursor
|
| 12 |
from app.integrations.storage import StorageClient
|
| 13 |
from app.modules.accounts.models import Account
|
|
|
|
| 31 |
self.storage = storage
|
| 32 |
self.repo = CoachRepository(db)
|
| 33 |
|
| 34 |
+
async def _players(self, staff: Staff) -> list[Account]:
|
| 35 |
+
return list(await self.repo.visible_players(visible_players_query(staff)))
|
|
|
|
| 36 |
|
| 37 |
+
async def roster(self, staff: Staff) -> list[RosterItem]:
|
| 38 |
+
players = await self._players(staff)
|
| 39 |
if not players:
|
| 40 |
return []
|
| 41 |
+
all_ids = [p.id for p in players]
|
| 42 |
+
hidden = await self.repo.sessions_hidden(all_ids)
|
| 43 |
+
ids = [i for i in all_ids if i not in hidden]
|
| 44 |
+
groups = await self.repo.group_ids(all_ids)
|
| 45 |
+
pending = await self.repo.pending_counts(ids) if ids else {}
|
| 46 |
by_key: dict[tuple[UUID, str], list] = {}
|
| 47 |
+
recent_rows = await self.repo.recent_sessions(ids) if ids else []
|
| 48 |
+
for row in recent_rows: # ordered newest first within each (owner, mode)
|
| 49 |
by_key.setdefault((row.owner_id, row.mode), []).append(row)
|
| 50 |
|
| 51 |
items = []
|
|
|
|
| 63 |
delta=delta, created_at=newest.created_at, focus_name=newest.focus))
|
| 64 |
setattr(recent, mode, [r.overall_score for r in rows[:3] if r.overall_score is not None])
|
| 65 |
items.append(RosterItem(id=p.id, name=p.name, email=p.email, focus=p.focus, level=p.level,
|
| 66 |
+
group_ids=groups.get(p.id, []),
|
| 67 |
pending_count=pending.get(p.id, 0), last=last, recent=recent))
|
| 68 |
return items
|
| 69 |
|
| 70 |
+
async def player_sessions(self, staff: Staff, player_id: UUID, mode: str | None,
|
| 71 |
paging: PageParams) -> Page[SessionSummary]:
|
| 72 |
+
await require_player(self.db, staff, player_id)
|
| 73 |
+
if not await sessions_shared(self.db, player_id):
|
| 74 |
+
raise Forbidden("This player does not share sessions with coaches.", code="SESSIONS_PRIVATE")
|
| 75 |
query = player_sessions_query(player_id, mode, paging.cursor, paging.limit + 1)
|
| 76 |
items = await load_summaries(self.db, self.storage, query)
|
| 77 |
next_cursor = None
|
|
|
|
| 80 |
next_cursor = encode_cursor(items[-1].created_at, items[-1].id)
|
| 81 |
return Page[SessionSummary](items=items, next_cursor=next_cursor)
|
| 82 |
|
| 83 |
+
async def queue(self, staff: Staff, since: datetime | None) -> QueueResponse:
|
| 84 |
+
players = await self._players(staff)
|
| 85 |
+
hidden = await self.repo.sessions_hidden([p.id for p in players])
|
| 86 |
+
names = {p.id: p.name for p in players if p.id not in hidden}
|
| 87 |
+
if not names:
|
| 88 |
return QueueResponse(open=[], reviewed_today=[])
|
|
|
|
| 89 |
ids = list(names)
|
| 90 |
if since is None:
|
| 91 |
since = start_of_today_utc()
|
backend/app/modules/drills/models.py
CHANGED
|
@@ -21,6 +21,9 @@ class DrillLog(IdMixin, CreatedAtMixin, Base):
|
|
| 21 |
session_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 22 |
UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL")
|
| 23 |
)
|
| 24 |
-
drill_id: Mapped[str] = mapped_column(String(
|
|
|
|
|
|
|
|
|
|
| 25 |
reps: Mapped[int] = mapped_column(SmallInteger)
|
| 26 |
day: Mapped[date] = mapped_column(Date)
|
|
|
|
| 21 |
session_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 22 |
UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL")
|
| 23 |
)
|
| 24 |
+
drill_id: Mapped[str] = mapped_column(String(40))
|
| 25 |
+
assignment_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 26 |
+
UUID(as_uuid=True), ForeignKey("drill_assignments.id", ondelete="SET NULL")
|
| 27 |
+
)
|
| 28 |
reps: Mapped[int] = mapped_column(SmallInteger)
|
| 29 |
day: Mapped[date] = mapped_column(Date)
|
backend/app/modules/drills/schemas.py
CHANGED
|
@@ -17,6 +17,7 @@ class DrillLogOut(ResponseModel):
|
|
| 17 |
id: UUID
|
| 18 |
session_id: UUID | None
|
| 19 |
drill_id: str
|
|
|
|
| 20 |
reps: int
|
| 21 |
day: date
|
| 22 |
created_at: datetime
|
|
|
|
| 17 |
id: UUID
|
| 18 |
session_id: UUID | None
|
| 19 |
drill_id: str
|
| 20 |
+
assignment_id: UUID | None
|
| 21 |
reps: int
|
| 22 |
day: date
|
| 23 |
created_at: datetime
|
backend/app/modules/goals/__init__.py
ADDED
|
File without changes
|
backend/app/modules/goals/controller.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""N16-N19: goals and milestones."""
|
| 2 |
+
|
| 3 |
+
from typing import Annotated
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, Depends, Query
|
| 7 |
+
|
| 8 |
+
from app.common.academy_access import CurrentStaff
|
| 9 |
+
from app.common.schemas import Page
|
| 10 |
+
from app.core.dependencies import CurrentAccount, CurrentPlayer, Db, Paging
|
| 11 |
+
from app.integrations.push import PushClient, get_push_client
|
| 12 |
+
from app.modules.goals.schemas import GoalEnvelope, GoalHistoryOut, GoalIn, MilestoneOut, Mode
|
| 13 |
+
from app.modules.goals.service import GoalService
|
| 14 |
+
|
| 15 |
+
router = APIRouter(prefix="/v1", tags=["goals"])
|
| 16 |
+
|
| 17 |
+
ModeQuery = Annotated[Mode, Query()]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@router.get("/players/{player_id}/goals", response_model=GoalEnvelope)
|
| 21 |
+
async def get_goal(player_id: UUID, mode: ModeQuery, account: CurrentAccount, db: Db) -> GoalEnvelope:
|
| 22 |
+
return await GoalService(db).current(account, player_id, mode)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@router.put("/players/{player_id}/goals/{mode}", response_model=GoalEnvelope)
|
| 26 |
+
async def put_goal(player_id: UUID, mode: Mode, body: GoalIn, staff: CurrentStaff, db: Db,
|
| 27 |
+
push: Annotated[PushClient, Depends(get_push_client)]) -> GoalEnvelope:
|
| 28 |
+
return await GoalService(db, push).set(staff, player_id, mode, body)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@router.get("/players/{player_id}/goals/history", response_model=Page[GoalHistoryOut])
|
| 32 |
+
async def goal_history(player_id: UUID, mode: ModeQuery, account: CurrentAccount, db: Db,
|
| 33 |
+
paging: Paging) -> Page[GoalHistoryOut]:
|
| 34 |
+
return await GoalService(db).history(account, player_id, mode, paging)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@router.get("/me/milestones", response_model=Page[MilestoneOut])
|
| 38 |
+
async def milestones(mode: ModeQuery, player: CurrentPlayer, db: Db, paging: Paging) -> Page[MilestoneOut]:
|
| 39 |
+
return await GoalService(db).milestones(player, mode, paging)
|
backend/app/modules/goals/models.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
from decimal import Decimal
|
| 4 |
+
|
| 5 |
+
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, Numeric, SmallInteger, String, text
|
| 6 |
+
from sqlalchemy.dialects.postgresql import UUID
|
| 7 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 8 |
+
|
| 9 |
+
from app.common.base_model import Base, CreatedAtMixin, IdMixin
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Goal(IdMixin, CreatedAtMixin, Base):
|
| 13 |
+
"""A coach-set goal. The active goal per (player, mode) has ended_at NULL; replaced goals are the history.
|
| 14 |
+
|
| 15 |
+
created_at is set_at. outcome: met | not_met | superseded | unknown (NULL while active).
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
__tablename__ = "goals"
|
| 19 |
+
__table_args__ = (
|
| 20 |
+
CheckConstraint("mode IN ('h', 'p')", name="mode"),
|
| 21 |
+
CheckConstraint("type IN ('groups', 'param', 'score')", name="type"),
|
| 22 |
+
CheckConstraint("outcome IS NULL OR outcome IN ('met', 'not_met', 'superseded', 'unknown')", name="outcome"),
|
| 23 |
+
Index("uq_goals_active", "player_id", "mode", unique=True, postgresql_where=text("ended_at IS NULL")),
|
| 24 |
+
Index("ix_goals_player_id_mode_created_at", "player_id", "mode", text("created_at DESC")),
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
player_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))
|
| 28 |
+
team_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="SET NULL"))
|
| 29 |
+
mode: Mapped[str] = mapped_column(String(1))
|
| 30 |
+
type: Mapped[str] = mapped_column(String(8))
|
| 31 |
+
target: Mapped[Decimal] = mapped_column(Numeric(8, 2))
|
| 32 |
+
metric_id: Mapped[str | None] = mapped_column(String(64))
|
| 33 |
+
due: Mapped[str] = mapped_column(String(16))
|
| 34 |
+
due_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
|
| 35 |
+
weekly_practice_days: Mapped[int] = mapped_column(SmallInteger)
|
| 36 |
+
weekly_drill_sets: Mapped[int] = mapped_column(SmallInteger)
|
| 37 |
+
note: Mapped[str] = mapped_column(String(160), server_default="")
|
| 38 |
+
set_by_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 39 |
+
UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="SET NULL")
|
| 40 |
+
)
|
| 41 |
+
ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
| 42 |
+
outcome: Mapped[str | None] = mapped_column(String(10))
|
| 43 |
+
evaluated_session_id: Mapped[uuid.UUID | None] = mapped_column(
|
| 44 |
+
UUID(as_uuid=True), ForeignKey("sessions.id", ondelete="SET NULL")
|
| 45 |
+
)
|
| 46 |
+
version: Mapped[int] = mapped_column(Integer, server_default="1")
|
backend/app/modules/goals/repository.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from uuid import UUID
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import Select, select, tuple_
|
| 5 |
+
|
| 6 |
+
from app.common.base_repository import BaseRepository
|
| 7 |
+
from app.core.pagination import Cursor
|
| 8 |
+
from app.modules.accounts.models import Account
|
| 9 |
+
from app.modules.goals.models import Goal
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class GoalRepository(BaseRepository[Goal]):
|
| 13 |
+
model = Goal
|
| 14 |
+
|
| 15 |
+
async def active(self, player_id: UUID, mode: str, *, lock: bool = False,
|
| 16 |
+
team_id: UUID | None = None) -> Goal | None:
|
| 17 |
+
query = select(Goal).where(Goal.player_id == player_id, Goal.mode == mode, Goal.ended_at.is_(None))
|
| 18 |
+
if team_id is not None:
|
| 19 |
+
query = query.where(Goal.team_id == team_id)
|
| 20 |
+
return await self.session.scalar(query.with_for_update() if lock else query)
|
| 21 |
+
|
| 22 |
+
async def author_name(self, account_id: UUID | None) -> str | None:
|
| 23 |
+
return await self.session.scalar(select(Account.name).where(Account.id == account_id)) if account_id else None
|
| 24 |
+
|
| 25 |
+
def _page(self, query: Select, cursor: Cursor | None, limit: int) -> Select:
|
| 26 |
+
if cursor is not None:
|
| 27 |
+
query = query.where(tuple_(Goal.created_at, Goal.id) < tuple_(cursor.created_at, cursor.id))
|
| 28 |
+
return query.order_by(Goal.created_at.desc(), Goal.id.desc()).limit(limit + 1)
|
| 29 |
+
|
| 30 |
+
async def ended(self, player_id: UUID, mode: str, cursor: Cursor | None, limit: int, *, met_only: bool = False,
|
| 31 |
+
team_id: UUID | None = None):
|
| 32 |
+
query = select(Goal).where(Goal.player_id == player_id, Goal.mode == mode, Goal.ended_at.is_not(None))
|
| 33 |
+
if team_id is not None:
|
| 34 |
+
query = query.where(Goal.team_id == team_id)
|
| 35 |
+
if met_only:
|
| 36 |
+
query = query.where(Goal.outcome == "met")
|
| 37 |
+
return (await self.session.scalars(self._page(query, cursor, limit))).all()
|
| 38 |
+
|
| 39 |
+
async def end(self, goal: Goal, now: datetime) -> None:
|
| 40 |
+
goal.ended_at = now
|
| 41 |
+
goal.outcome = "superseded"
|
| 42 |
+
await self.session.flush()
|
backend/app/modules/goals/schemas.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from math import isfinite
|
| 3 |
+
from typing import Annotated, Literal
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from pydantic import Field, StrictFloat, StrictInt, field_validator
|
| 7 |
+
|
| 8 |
+
from app.common.schemas import RequestModel, ResponseModel
|
| 9 |
+
|
| 10 |
+
Mode = Literal["h", "p"]
|
| 11 |
+
Due = Literal["1 week", "2 weeks", "End of month"]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class WeeklyIn(RequestModel):
|
| 15 |
+
practice_days: Annotated[int, Field(strict=True, ge=1, le=7)]
|
| 16 |
+
drill_sets: Annotated[int, Field(strict=True, ge=1, le=30)]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class GoalIn(RequestModel):
|
| 20 |
+
type: Literal["groups", "param", "score"]
|
| 21 |
+
target: StrictInt | StrictFloat
|
| 22 |
+
metric_id: str | None = Field(None, max_length=64)
|
| 23 |
+
due: Due
|
| 24 |
+
weekly: WeeklyIn
|
| 25 |
+
note: str = Field("", max_length=160)
|
| 26 |
+
expected_version: int | None = Field(None, ge=0)
|
| 27 |
+
|
| 28 |
+
@field_validator("target")
|
| 29 |
+
@classmethod
|
| 30 |
+
def _finite(cls, value: int | float) -> int | float:
|
| 31 |
+
if not isfinite(value):
|
| 32 |
+
raise ValueError("Must be a finite number.")
|
| 33 |
+
return value
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class WeeklyOut(ResponseModel):
|
| 37 |
+
practice_days: int
|
| 38 |
+
drill_sets: int
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class GoalOut(ResponseModel):
|
| 42 |
+
id: UUID
|
| 43 |
+
player_id: UUID
|
| 44 |
+
mode: str
|
| 45 |
+
type: str
|
| 46 |
+
target: int | float
|
| 47 |
+
metric_id: str | None
|
| 48 |
+
metric_name: str | None
|
| 49 |
+
due: str
|
| 50 |
+
due_at: datetime
|
| 51 |
+
set_at: datetime
|
| 52 |
+
set_by: str | None
|
| 53 |
+
set_by_id: UUID | None
|
| 54 |
+
note: str
|
| 55 |
+
weekly: WeeklyOut
|
| 56 |
+
version: int
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class GoalEnvelope(ResponseModel):
|
| 60 |
+
goal: GoalOut | None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class GoalHistoryOut(ResponseModel):
|
| 64 |
+
id: UUID
|
| 65 |
+
text: str
|
| 66 |
+
range: str
|
| 67 |
+
met: bool | None
|
| 68 |
+
outcome: str | None
|
| 69 |
+
start_at: datetime
|
| 70 |
+
end_at: datetime | None
|
| 71 |
+
evaluated_session_id: UUID | None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class MilestoneOut(ResponseModel):
|
| 75 |
+
id: UUID
|
| 76 |
+
icon: str
|
| 77 |
+
tone: str
|
| 78 |
+
title: str
|
| 79 |
+
when: str
|
| 80 |
+
occurred_at: datetime
|
| 81 |
+
source_goal_id: UUID
|
backend/app/modules/goals/service.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Coach-set goals (N16-N19). The active goal has ended_at NULL; a change ends it and inserts a new version."""
|
| 2 |
+
|
| 3 |
+
from calendar import monthrange
|
| 4 |
+
from datetime import UTC, date, datetime, time, timedelta
|
| 5 |
+
from functools import cache
|
| 6 |
+
from uuid import UUID
|
| 7 |
+
|
| 8 |
+
from ai_coach.swing_report import repository as registry
|
| 9 |
+
from sqlalchemy.exc import IntegrityError
|
| 10 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 11 |
+
|
| 12 |
+
from app.common.academy_access import Staff, can_see_player, require_player, staff_context
|
| 13 |
+
from app.common.notify import notify
|
| 14 |
+
from app.common.schemas import Page
|
| 15 |
+
from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed
|
| 16 |
+
from app.core.pagination import PageParams, encode_cursor
|
| 17 |
+
from app.integrations.push import PushClient
|
| 18 |
+
from app.modules.accounts.models import Account
|
| 19 |
+
from app.modules.goals.models import Goal
|
| 20 |
+
from app.modules.goals.repository import GoalRepository
|
| 21 |
+
from app.modules.goals.schemas import GoalEnvelope, GoalHistoryOut, GoalIn, GoalOut, MilestoneOut, WeeklyOut
|
| 22 |
+
|
| 23 |
+
DUE_DAYS = {"1 week": 7, "2 weeks": 14}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@cache
|
| 27 |
+
def _metrics() -> dict[str, dict]:
|
| 28 |
+
return {m["metric_id"]: m for m in registry.metrics()}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@cache
|
| 32 |
+
def _group_count() -> int:
|
| 33 |
+
return len(registry.groups())
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _num(goal: Goal) -> int | float:
|
| 37 |
+
return float(goal.target) if goal.type == "param" else int(goal.target)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _metric_name(metric_id: str | None) -> str | None:
|
| 41 |
+
return _metrics()[metric_id]["display_name"] if metric_id in _metrics() else None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _out(goal: Goal, set_by: str | None) -> GoalOut:
|
| 45 |
+
return GoalOut(
|
| 46 |
+
id=goal.id, player_id=goal.player_id, mode=goal.mode, type=goal.type, target=_num(goal),
|
| 47 |
+
metric_id=goal.metric_id, metric_name=_metric_name(goal.metric_id), due=goal.due, due_at=goal.due_at,
|
| 48 |
+
set_at=goal.created_at, set_by=set_by, set_by_id=goal.set_by_id, note=goal.note,
|
| 49 |
+
weekly=WeeklyOut(practice_days=goal.weekly_practice_days, drill_sets=goal.weekly_drill_sets),
|
| 50 |
+
version=goal.version)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _due_at(due: str, now: datetime) -> datetime:
|
| 54 |
+
today = now.date()
|
| 55 |
+
last = today if due not in DUE_DAYS else today + timedelta(days=DUE_DAYS[due])
|
| 56 |
+
if due == "End of month":
|
| 57 |
+
last = today.replace(day=monthrange(today.year, today.month)[1])
|
| 58 |
+
return datetime.combine(last, time(23, 59, 59), tzinfo=UTC)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _fmt(day: date | datetime, year: bool = False) -> str:
|
| 62 |
+
return f"{day:%b} {day.day}" + (f", {day.year}" if year else "")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _text(goal: Goal) -> str:
|
| 66 |
+
target = _num(goal)
|
| 67 |
+
if goal.type == "groups":
|
| 68 |
+
return f"Get {target} of {_group_count()} groups on target"
|
| 69 |
+
if goal.type == "score":
|
| 70 |
+
return f"Reach a score of {target}"
|
| 71 |
+
metric = _metrics().get(goal.metric_id or "")
|
| 72 |
+
name = metric["display_name"] if metric else "Metric"
|
| 73 |
+
return f"Get {name} to {target:g}" + (f" {metric['unit']}" if metric and metric.get("unit") else "")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _range(goal: Goal) -> str:
|
| 77 |
+
start, end = goal.created_at, goal.ended_at
|
| 78 |
+
if end is None:
|
| 79 |
+
return f"From {_fmt(start, True)}"
|
| 80 |
+
if start.year == end.year:
|
| 81 |
+
return f"{_fmt(start)} to {_fmt(end, True)}"
|
| 82 |
+
return f"{_fmt(start, True)} to {_fmt(end, True)}"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _met(goal: Goal) -> bool | None:
|
| 86 |
+
return {"met": True, "not_met": False}.get(goal.outcome or "")
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class GoalService:
|
| 90 |
+
def __init__(self, db: AsyncSession, push: PushClient | None = None):
|
| 91 |
+
self.db = db
|
| 92 |
+
self.push = push
|
| 93 |
+
self.goals = GoalRepository(db)
|
| 94 |
+
|
| 95 |
+
async def _authorize_read(self, account: Account, player_id: UUID) -> UUID | None:
|
| 96 |
+
"""Returns the team that scopes the goals a reader may see (None: a player sees all their own)."""
|
| 97 |
+
if account.role == "player":
|
| 98 |
+
if account.id != player_id:
|
| 99 |
+
raise NotFound()
|
| 100 |
+
return None
|
| 101 |
+
staff = await staff_context(self.db, account)
|
| 102 |
+
if staff is None:
|
| 103 |
+
raise Forbidden("Only coaches can do this.")
|
| 104 |
+
if not await can_see_player(self.db, staff, player_id):
|
| 105 |
+
raise NotFound("Player not on your team.", code="PLAYER_NOT_ON_TEAM")
|
| 106 |
+
return staff.team_id
|
| 107 |
+
|
| 108 |
+
async def current(self, account: Account, player_id: UUID, mode: str) -> GoalEnvelope:
|
| 109 |
+
team_id = await self._authorize_read(account, player_id)
|
| 110 |
+
goal = await self.goals.active(player_id, mode, team_id=team_id)
|
| 111 |
+
if goal is None:
|
| 112 |
+
return GoalEnvelope(goal=None)
|
| 113 |
+
return GoalEnvelope(goal=_out(goal, await self.goals.author_name(goal.set_by_id)))
|
| 114 |
+
|
| 115 |
+
def _validate(self, mode: str, body: GoalIn) -> None:
|
| 116 |
+
fields: dict[str, str] = {}
|
| 117 |
+
target = body.target
|
| 118 |
+
if body.type == "groups":
|
| 119 |
+
groups = _group_count() if mode == "h" else 0
|
| 120 |
+
if isinstance(target, float) and not target.is_integer() or not 1 <= target <= groups:
|
| 121 |
+
fields["target"] = f"Must be a whole number from 1 to {groups}." if groups else "Not available."
|
| 122 |
+
elif body.type == "score":
|
| 123 |
+
if isinstance(target, float) and not target.is_integer() or not 50 <= target <= 100:
|
| 124 |
+
fields["target"] = "Must be a whole number from 50 to 100."
|
| 125 |
+
elif not -50 <= target <= 500:
|
| 126 |
+
fields["target"] = "Must be from -50 to 500."
|
| 127 |
+
if body.type == "param":
|
| 128 |
+
if not body.metric_id or body.metric_id not in _metrics() or mode != "h":
|
| 129 |
+
fields["metric_id"] = "Choose a known metric."
|
| 130 |
+
elif body.metric_id is not None:
|
| 131 |
+
fields["metric_id"] = "Only used with a param goal."
|
| 132 |
+
if fields:
|
| 133 |
+
raise ValidationFailed(fields=fields)
|
| 134 |
+
|
| 135 |
+
async def set(self, staff: Staff, player_id: UUID, mode: str, body: GoalIn) -> GoalEnvelope:
|
| 136 |
+
staff.require("goals")
|
| 137 |
+
player = await require_player(self.db, staff, player_id)
|
| 138 |
+
self._validate(mode, body)
|
| 139 |
+
target = body.target if body.type == "param" else int(body.target)
|
| 140 |
+
active = await self.goals.active(player_id, mode, lock=True)
|
| 141 |
+
if active is not None and self._same(active, body, target):
|
| 142 |
+
return GoalEnvelope(goal=_out(active, await self.goals.author_name(active.set_by_id)))
|
| 143 |
+
current_version = active.version if active else 0
|
| 144 |
+
if body.expected_version is not None and body.expected_version != current_version:
|
| 145 |
+
raise Conflict("This goal changed. Refresh and try again.", code="STALE_VERSION")
|
| 146 |
+
now = datetime.now(UTC)
|
| 147 |
+
if active is not None:
|
| 148 |
+
await self.goals.end(active, now)
|
| 149 |
+
try:
|
| 150 |
+
async with self.db.begin_nested():
|
| 151 |
+
goal = await self.goals.create(
|
| 152 |
+
player_id=player_id, team_id=player.team_id, mode=mode, type=body.type, target=target,
|
| 153 |
+
metric_id=body.metric_id, due=body.due, due_at=_due_at(body.due, now),
|
| 154 |
+
weekly_practice_days=body.weekly.practice_days, weekly_drill_sets=body.weekly.drill_sets,
|
| 155 |
+
note=body.note, set_by_id=staff.id, version=current_version + 1)
|
| 156 |
+
except IntegrityError as exc: # a concurrent first goal won the race
|
| 157 |
+
raise Conflict("This goal changed. Refresh and try again.", code="STALE_VERSION") from exc
|
| 158 |
+
await notify(self.db, self.push, player_id, kind="drill", title="Your coach set a new goal",
|
| 159 |
+
body=_text(goal), target={}, event_key=f"goal:{goal.id}")
|
| 160 |
+
return GoalEnvelope(goal=_out(goal, staff.account.name))
|
| 161 |
+
|
| 162 |
+
@staticmethod
|
| 163 |
+
def _same(goal: Goal, body: GoalIn, target: int | float) -> bool:
|
| 164 |
+
return (goal.type, float(goal.target), goal.metric_id, goal.due, goal.weekly_practice_days,
|
| 165 |
+
goal.weekly_drill_sets, goal.note) == (
|
| 166 |
+
body.type, float(target), body.metric_id, body.due, body.weekly.practice_days, body.weekly.drill_sets,
|
| 167 |
+
body.note)
|
| 168 |
+
|
| 169 |
+
async def history(self, account: Account, player_id: UUID, mode: str, paging: PageParams) -> Page[GoalHistoryOut]:
|
| 170 |
+
team_id = await self._authorize_read(account, player_id)
|
| 171 |
+
rows = list(await self.goals.ended(player_id, mode, paging.cursor, paging.limit, team_id=team_id))
|
| 172 |
+
page = rows[:paging.limit]
|
| 173 |
+
items = [GoalHistoryOut(id=g.id, text=_text(g), range=_range(g), met=_met(g), outcome=g.outcome,
|
| 174 |
+
start_at=g.created_at, end_at=g.ended_at, evaluated_session_id=g.evaluated_session_id)
|
| 175 |
+
for g in page]
|
| 176 |
+
more = len(rows) > paging.limit
|
| 177 |
+
return Page[GoalHistoryOut](items=items, next_cursor=encode_cursor(page[-1].created_at, page[-1].id)
|
| 178 |
+
if more else None)
|
| 179 |
+
|
| 180 |
+
async def milestones(self, account: Account, mode: str, paging: PageParams) -> Page[MilestoneOut]:
|
| 181 |
+
rows = list(await self.goals.ended(account.id, mode, paging.cursor, paging.limit, met_only=True))
|
| 182 |
+
page = rows[:paging.limit]
|
| 183 |
+
items = [MilestoneOut(id=g.id, icon="flag", tone="b", title=f"Goal met: {_text(g)}",
|
| 184 |
+
when=_fmt(g.ended_at, True), occurred_at=g.ended_at, source_goal_id=g.id) # type: ignore[arg-type]
|
| 185 |
+
for g in page]
|
| 186 |
+
more = len(rows) > paging.limit
|
| 187 |
+
return Page[MilestoneOut](items=items, next_cursor=encode_cursor(page[-1].created_at, page[-1].id)
|
| 188 |
+
if more else None)
|
backend/app/modules/notifications/__init__.py
ADDED
|
File without changes
|
backend/app/modules/notifications/controller.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""N06 to N09: /notifications."""
|
| 2 |
+
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
|
| 5 |
+
from fastapi import APIRouter, Response
|
| 6 |
+
|
| 7 |
+
from app.common.schemas import Page
|
| 8 |
+
from app.core.dependencies import CurrentAccount, Db, Paging
|
| 9 |
+
from app.modules.notifications.schemas import NotificationOut, ReadAllIn, UnreadCount
|
| 10 |
+
from app.modules.notifications.service import NotificationService
|
| 11 |
+
|
| 12 |
+
router = APIRouter(prefix="/v1", tags=["notifications"])
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@router.get("/notifications", response_model=Page[NotificationOut])
|
| 16 |
+
async def list_notifications(account: CurrentAccount, db: Db, paging: Paging) -> Page[NotificationOut]:
|
| 17 |
+
return await NotificationService(db).list(account, paging)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@router.get("/notifications/unread-count", response_model=UnreadCount)
|
| 21 |
+
async def unread_count(account: CurrentAccount, db: Db) -> UnreadCount:
|
| 22 |
+
return await NotificationService(db).unread_count(account)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@router.post("/notifications/read-all", status_code=204)
|
| 26 |
+
async def read_all(account: CurrentAccount, db: Db, body: ReadAllIn | None = None) -> Response:
|
| 27 |
+
await NotificationService(db).mark_all_read(account, body.through if body else None)
|
| 28 |
+
return Response(status_code=204)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@router.post("/notifications/{notification_id}/read", status_code=204)
|
| 32 |
+
async def read_one(notification_id: UUID, account: CurrentAccount, db: Db) -> Response:
|
| 33 |
+
await NotificationService(db).mark_read(account, notification_id)
|
| 34 |
+
return Response(status_code=204)
|
backend/app/modules/notifications/models.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import uuid
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, String, UniqueConstraint, text
|
| 5 |
+
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
| 6 |
+
from sqlalchemy.orm import Mapped, mapped_column
|
| 7 |
+
|
| 8 |
+
from app.common.base_model import Base, CreatedAtMixin, IdMixin
|
| 9 |
+
|
| 10 |
+
KINDS = ("review", "drill", "armcare", "result", "report")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Notification(IdMixin, CreatedAtMixin, Base):
|
| 14 |
+
"""One in-app inbox item. event_key deduplicates retries of the same domain event per recipient."""
|
| 15 |
+
|
| 16 |
+
__tablename__ = "notifications"
|
| 17 |
+
__table_args__ = (
|
| 18 |
+
CheckConstraint(f"kind IN ({', '.join(repr(k) for k in KINDS)})", name="kind"),
|
| 19 |
+
UniqueConstraint("recipient_id", "event_key"),
|
| 20 |
+
Index("ix_notifications_recipient_id_created_at", "recipient_id", text("created_at DESC"), "id"),
|
| 21 |
+
Index("ix_notifications_unread", "recipient_id", postgresql_where=text("read_at IS NULL")),
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
recipient_id: Mapped[uuid.UUID] = mapped_column(
|
| 25 |
+
UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE")
|
| 26 |
+
)
|
| 27 |
+
kind: Mapped[str] = mapped_column(String(10))
|
| 28 |
+
title: Mapped[str] = mapped_column(String(120))
|
| 29 |
+
body: Mapped[str] = mapped_column(String(300), server_default="")
|
| 30 |
+
target: Mapped[dict] = mapped_column(JSONB, server_default=text("'{}'::jsonb"))
|
| 31 |
+
event_key: Mapped[str] = mapped_column(String(160))
|
| 32 |
+
read_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
|
backend/app/modules/notifications/repository.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime
|
| 2 |
+
from uuid import UUID
|
| 3 |
+
|
| 4 |
+
from sqlalchemy import func, select, tuple_, update
|
| 5 |
+
|
| 6 |
+
from app.common.base_repository import BaseRepository
|
| 7 |
+
from app.core.pagination import Cursor
|
| 8 |
+
from app.modules.notifications.models import Notification
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class NotificationRepository(BaseRepository[Notification]):
|
| 12 |
+
model = Notification
|
| 13 |
+
|
| 14 |
+
async def page(self, recipient_id: UUID, cursor: Cursor | None, limit: int) -> list[Notification]:
|
| 15 |
+
query = select(Notification).where(Notification.recipient_id == recipient_id)
|
| 16 |
+
if cursor:
|
| 17 |
+
query = query.where(tuple_(Notification.created_at, Notification.id) < (cursor.created_at, cursor.id))
|
| 18 |
+
result = await self.session.scalars(
|
| 19 |
+
query.order_by(Notification.created_at.desc(), Notification.id.desc()).limit(limit))
|
| 20 |
+
return list(result.all())
|
| 21 |
+
|
| 22 |
+
async def unread_count(self, recipient_id: UUID) -> int:
|
| 23 |
+
return await self.session.scalar(select(func.count()).select_from(Notification).where(
|
| 24 |
+
Notification.recipient_id == recipient_id, Notification.read_at.is_(None))) or 0
|
| 25 |
+
|
| 26 |
+
async def mark_read(self, recipient_id: UUID, id_: UUID, now: datetime) -> bool:
|
| 27 |
+
"""False when the notification does not exist or belongs to someone else."""
|
| 28 |
+
row = await self.first_by(id=id_, recipient_id=recipient_id)
|
| 29 |
+
if row is None:
|
| 30 |
+
return False
|
| 31 |
+
if row.read_at is None:
|
| 32 |
+
await self.update(row, read_at=now)
|
| 33 |
+
return True
|
| 34 |
+
|
| 35 |
+
async def mark_read_through(self, recipient_id: UUID, through: datetime, now: datetime) -> None:
|
| 36 |
+
await self.session.execute(update(Notification).where(
|
| 37 |
+
Notification.recipient_id == recipient_id, Notification.read_at.is_(None),
|
| 38 |
+
Notification.created_at <= through).values(read_at=now))
|