File size: 8,825 Bytes
fe40b87
 
ae2c68f
fe40b87
 
 
 
 
ae2c68f
 
 
fe40b87
ae2c68f
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
 
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
 
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae2c68f
fe40b87
 
 
 
 
 
 
 
 
ae2c68f
 
fe40b87
 
 
ae2c68f
 
 
 
 
 
 
fe40b87
ae2c68f
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"""Academy groups (N28-N29), private coach notes (N30-N31), roster additions (N32-N33) and the library (N35-N36)."""

from datetime import UTC, datetime
from uuid import UUID

from sqlalchemy.ext.asyncio import AsyncSession

from app.common.academy_access import Staff, require_player, visible_player_ids
from app.common.media import media_ref
from app.common.schemas import Page
from app.common.uploads import UploadErrors, claim_upload
from app.core.errors import Conflict, NotFound, Unprocessable
from app.core.pagination import PageParams, paginate
from app.integrations.storage import StorageClient
from app.modules.academy.models import LibraryDrill, PlayerGroup
from app.modules.academy_org.repository import OrgRepository
from app.modules.academy_org.schemas import (
    GroupIn,
    GroupOut,
    LibraryDrillIn,
    LibraryDrillOut,
    MemberOut,
    NoteIn,
    NoteOut,
    RosterAddIn,
    RosterAddOut,
)


def _dedupe(ids: list[UUID]) -> list[UUID]:
    return list(dict.fromkeys(ids))


class OrgService:
    def __init__(self, db: AsyncSession, storage: StorageClient):
        self.db = db
        self.storage = storage
        self.repo = OrgRepository(db)

    # ---------- groups ----------
    async def _group_outs(self, groups: list[PlayerGroup], visible: set[UUID] | None) -> list[GroupOut]:
        if not groups:
            return []
        ids = [g.id for g in groups]
        players = await self.repo.group_players(ids)
        coaches = await self.repo.group_coaches(ids)
        outs = []
        for g in groups:
            player_ids = [p for p in players.get(g.id, []) if visible is None or p in visible]
            outs.append(GroupOut(id=g.id, name=g.name, focus=g.focus, players=len(players.get(g.id, [])),
                                 player_ids=player_ids, coaches=[n for _, n in coaches.get(g.id, [])],
                                 coach_ids=[c for c, _ in coaches.get(g.id, [])]))
        return outs

    async def list_groups(self, staff: Staff, paging: PageParams) -> Page[GroupOut]:
        if staff.team_id is None:
            return Page[GroupOut](items=[])
        rows = list(await self.repo.groups(staff.team_id, None if staff.sees_all else staff.id,
                                           paging.cursor, paging.limit + 1))
        visible = None if staff.sees_all else set(await visible_player_ids(self.db, staff))
        outs = await self._group_outs(rows, visible)
        by_id = {g.id: g for g in rows}
        items, next_cursor = paginate(outs, paging.limit, lambda o: (by_id[o.id].created_at, o.id))
        return Page[GroupOut](items=items, next_cursor=next_cursor)

    async def create_group(self, staff: Staff, body: GroupIn) -> GroupOut:
        team_id = staff.team_id
        assert team_id is not None
        coach_ids, player_ids = _dedupe(body.coach_ids), _dedupe(body.player_ids)
        if coach_ids and await self.repo.team_staff_ids(team_id, coach_ids) != set(coach_ids):
            raise NotFound("Coach not found in your academy.")
        if player_ids and await self.repo.team_player_ids(team_id, player_ids) != set(player_ids):
            raise NotFound("Player not found in your academy.")
        group = await self.repo.create_group(team_id, body.name, body.focus, coach_ids, player_ids)
        if group is None:
            raise Conflict("A group with this name already exists.", code="GROUP_NAME_TAKEN")
        [out] = await self._group_outs([group], None)
        return out

    # ---------- notes ----------
    @staticmethod
    def _note_out(player_id: UUID, note) -> NoteOut:
        if note is None:
            return NoteOut(player_id=player_id, text="", updated_at=None, version=0)
        return NoteOut(player_id=player_id, text=note.text, updated_at=note.updated_at, version=note.version)

    async def get_note(self, staff: Staff, player_id: UUID) -> NoteOut:
        await require_player(self.db, staff, player_id)
        return self._note_out(player_id, await self.repo.note(staff.team_id, staff.id, player_id))  # type: ignore[arg-type]

    async def save_note(self, staff: Staff, player_id: UUID, body: NoteIn) -> NoteOut:
        await require_player(self.db, staff, player_id)
        team_id = staff.team_id
        assert team_id is not None
        note = await self.repo.note(team_id, staff.id, player_id, lock=True)
        stale = Conflict("This note changed. Refresh and try again.", code="STALE_VERSION")
        if note is None:
            if body.expected_version not in (None, 0):
                raise stale
            note = await self.repo.insert_note(team_id, staff.id, player_id, body.text)
            if note is None:
                raise stale
        else:
            if body.expected_version is not None and body.expected_version != note.version:
                raise stale
            note.text = body.text
            note.version += 1
            note.updated_at = datetime.now(UTC)
            await self.db.flush()
        return self._note_out(player_id, note)

    # ---------- roster ----------
    async def members(self, staff: Staff, q: str | None, paging: PageParams) -> Page[MemberOut]:
        if staff.team_id is None:
            return Page[MemberOut](items=[])
        rows = list(await self.repo.members(staff.team_id, staff.id, q, paging.cursor, paging.limit + 1))
        groups = await self.repo.player_group_ids([r.id for r in rows], staff.team_id) if rows else {}
        created = {r.id: r.created_at for r in rows}
        items = [MemberOut(id=r.id, name=r.name or "", focus=r.focus, level=r.level, group_ids=groups.get(r.id, []))
                 for r in rows]
        items, next_cursor = paginate(items, paging.limit, lambda m: (created[m.id], m.id))
        return Page[MemberOut](items=items, next_cursor=next_cursor)

    async def add_to_roster(self, staff: Staff, body: RosterAddIn) -> RosterAddOut:
        player_ids = _dedupe(body.player_ids)
        team_id = staff.team_id
        if team_id is None or await self.repo.team_player_ids(team_id, player_ids) != set(player_ids):
            raise NotFound("Player not found in your academy.")
        if body.group_id is not None:
            group = await self.repo.group_in_team(team_id, body.group_id)
            if group is None or not (staff.is_admin or await self.repo.is_group_coach(group.id, staff.id)):
                raise NotFound("Group not found.")
        added = await self.repo.add_to_roster(team_id, staff.id, player_ids)
        if body.group_id is not None:
            await self.repo.add_to_group(body.group_id, player_ids)
        return RosterAddOut(added_player_ids=[p for p in player_ids if p in added],
                            already_present_player_ids=[p for p in player_ids if p not in added])

    # ---------- library ----------
    def _drill_out(self, row: tuple[LibraryDrill, str | None, str | None]) -> LibraryDrillOut:
        drill, author, key = row
        media = None
        if drill.upload_id is not None and key is not None:
            media = media_ref(self.storage, drill.upload_id, key)
        return LibraryDrillOut(id=drill.id, name=drill.name, fixes=drill.fixes, fault_tags=list(drill.fault_tags),
                               by=author, author_id=drill.author_id, mode=drill.mode, media=media,
                               created_at=drill.created_at)

    async def library(self, staff: Staff, mode: str | None, fault_tag: str | None,
                      paging: PageParams) -> Page[LibraryDrillOut]:
        if staff.team_id is None:
            return Page[LibraryDrillOut](items=[])
        rows = await self.repo.library(staff.team_id, mode, fault_tag, paging.cursor, paging.limit + 1)
        items, next_cursor = paginate([self._drill_out(r) for r in rows], paging.limit)
        return Page[LibraryDrillOut](items=items, next_cursor=next_cursor)

    async def publish_drill(self, staff: Staff, body: LibraryDrillIn) -> LibraryDrillOut:
        staff.require("library")
        await claim_upload(
            self.db, self.storage, body.upload_id, owner_id=staff.id, kind="drill_video",
            errors=UploadErrors(
                invalid=NotFound("Upload not found."),
                used=Conflict("This video is already in use.", code="UPLOAD_ALREADY_USED"),
                not_ready=Conflict("The video has not finished uploading.", code="UPLOAD_NOT_READY"),
                wrong_kind=Unprocessable("This upload is not a drill video.", code="INVALID_MEDIA")))
        drill = LibraryDrill(team_id=staff.team_id, author_id=staff.id, name=body.name, fixes=body.fixes,
                             mode=body.mode, fault_tags=body.fault_tags, upload_id=body.upload_id)
        self.db.add(drill)
        await self.db.flush()
        return self._drill_out(await self.repo.library_row(drill.id))