File size: 7,160 Bytes
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""Who may act for an academy (a team) and which players they can see. Every coach-side module uses this.

The team owner (teams.coach_id) is the implicit admin with every permission. Other staff need an active
academy_memberships row. Paused or removed staff get no academy access, even with an
unexpired token: a paused coach gets 403 on coach endpoints, a removed one is a coach with no academy.
A coach sees: every team player if admin or sees_all; otherwise players on their own roster (coach_players)
plus players in groups they coach. A player's coach_can_see_sessions=false hides their sessions from coaches.
"""

from dataclasses import dataclass, field
from typing import Annotated
from uuid import UUID

from fastapi import Depends
from sqlalchemy import select, union
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.dependencies import CurrentAccount, Db
from app.core.errors import Forbidden, NotFound
from app.modules.academy.models import AcademyMembership, CoachPlayer, GroupCoach, GroupPlayer
from app.modules.accounts.models import Account
from app.modules.settings.models import UserSettings
from app.modules.teams.models import Team

PERMISSIONS = ("review", "drills", "goals", "library", "earnings")
ROLE_PERMISSIONS: dict[str, dict[str, bool]] = {
    "admin": dict.fromkeys(PERMISSIONS, True),
    "coach": {"review": True, "drills": True, "goals": True, "library": False, "earnings": False},
    "assistant": {"review": True, "drills": False, "goals": False, "library": False, "earnings": False},
}


def normalize_permissions(role: str, requested: dict[str, bool] | None = None) -> dict[str, bool]:
    """Role defaults, overridden by requested values. Admins always have all; assistants never drills/goals."""
    perms = {**ROLE_PERMISSIONS[role], **(requested or {})}
    if role == "admin":
        return dict(ROLE_PERMISSIONS["admin"])
    if role == "assistant":
        perms.update(drills=False, goals=False)
    return {k: bool(perms.get(k, False)) for k in PERMISSIONS}


@dataclass
class Staff:
    """The caller acting as a coach. team_id is None for a coach account that has no academy yet."""

    account: Account
    team_id: UUID | None
    role: str  # admin | coach | assistant
    sees_all: bool
    permissions: dict[str, bool] = field(default_factory=dict)
    is_owner: bool = False

    @property
    def id(self) -> UUID:
        return self.account.id

    @property
    def is_admin(self) -> bool:
        return self.team_id is not None and self.role == "admin"

    def require(self, permission: str) -> None:
        if self.team_id is None or not self.permissions.get(permission, False):
            raise Forbidden("Your academy role does not allow this.")


async def staff_context(db: AsyncSession, account: Account) -> Staff | None:
    team_id = await db.scalar(select(Team.id).where(Team.coach_id == account.id))
    if team_id is not None:
        return Staff(account, team_id, "admin", True, normalize_permissions("admin"), is_owner=True)
    membership = await db.scalar(select(AcademyMembership).where(
        AcademyMembership.account_id == account.id, AcademyMembership.status == "active")
        .order_by(AcademyMembership.created_at.desc()).limit(1))
    if membership is not None:
        return Staff(account, membership.team_id, membership.role, membership.sees_all or membership.role == "admin",
                     normalize_permissions(membership.role, membership.permissions))
    paused = await db.scalar(select(AcademyMembership.id).where(
        AcademyMembership.account_id == account.id, AcademyMembership.status == "paused").limit(1))
    if account.role == "coach" and paused is None:
        return Staff(account, None, "coach", False, {})
    return None


async def _staff(db: Db, account: CurrentAccount) -> Staff:
    staff = await staff_context(db, account)
    if staff is None:
        raise Forbidden("Only coaches can do this.")
    return staff


async def _admin(staff: Annotated[Staff, Depends(_staff)]) -> Staff:
    if not staff.is_admin:
        raise Forbidden("Only academy admins can do this.")
    return staff


CurrentStaff = Annotated[Staff, Depends(_staff)]
CurrentAdmin = Annotated[Staff, Depends(_admin)]


def visible_players_query(staff: Staff):
    """SELECT of the account ids of players this staff member can see (empty when there is no team)."""
    on_team = select(Account.id).where(Account.team_id == staff.team_id, Account.role == "player")
    if staff.team_id is None:
        return on_team.where(False)
    if staff.sees_all:
        return on_team
    rostered = select(CoachPlayer.player_id).where(CoachPlayer.team_id == staff.team_id,
                                                   CoachPlayer.coach_id == staff.id)
    grouped = (select(GroupPlayer.player_id).join(GroupCoach, GroupCoach.group_id == GroupPlayer.group_id)
               .where(GroupCoach.coach_id == staff.id))
    return on_team.where(Account.id.in_(union(rostered, grouped).subquery().select()))


async def visible_player_ids(db: AsyncSession, staff: Staff) -> list[UUID]:
    return list((await db.scalars(visible_players_query(staff))).all())


async def can_see_player(db: AsyncSession, staff: Staff, player_id: UUID) -> bool:
    query = visible_players_query(staff).where(Account.id == player_id)
    return await db.scalar(query) is not None


async def require_player(db: AsyncSession, staff: Staff, player_id: UUID) -> Account:
    """The player, if this staff member can see them; otherwise 404 (no existence leak)."""
    if not await can_see_player(db, staff, player_id):
        raise NotFound("Player not on your team.", code="PLAYER_NOT_ON_TEAM")
    return await db.get(Account, player_id)  # type: ignore[return-value]


async def sessions_shared(db: AsyncSession, player_id: UUID) -> bool:
    """False when the player turned off coach_can_see_sessions (no row means the default, true)."""
    value = await db.scalar(select(UserSettings.coach_can_see_sessions).where(UserSettings.account_id == player_id))
    return True if value is None else value


async def coaches_of_player(db: AsyncSession, player: Account) -> list[UUID]:
    """Account ids of every active staff member who can see this player (for alerts)."""
    if player.team_id is None:
        return []
    owner = await db.scalar(select(Team.coach_id).where(Team.id == player.team_id))
    ids = {owner} if owner else set()
    rows = await db.execute(select(AcademyMembership.account_id, AcademyMembership.sees_all, AcademyMembership.role)
                            .where(AcademyMembership.team_id == player.team_id, AcademyMembership.status == "active"))
    rostered = set((await db.scalars(select(CoachPlayer.coach_id).where(CoachPlayer.player_id == player.id))).all())
    grouped = set((await db.scalars(select(GroupCoach.coach_id).join(
        GroupPlayer, GroupPlayer.group_id == GroupCoach.group_id).where(GroupPlayer.player_id == player.id))).all())
    for account_id, sees_all, role in rows:
        if sees_all or role == "admin" or account_id in rostered or account_id in grouped:
            ids.add(account_id)
    return list(ids)