Coverage for api_client/client.py: 25.05%
810 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 20:17 +0000
1"""
2Type-safe API client for Missing Table backend.
4Provides a comprehensive client with:
5- Full type safety via Pydantic models
6- Automatic authentication handling
7- Retry logic with exponential backoff
8- Request/response logging
9- Error handling
10"""
12import logging
13from typing import TYPE_CHECKING, Any, TypeVar
14from urllib.parse import urljoin
16if TYPE_CHECKING:
17 from collections.abc import Callable
19import httpx
20from pydantic import BaseModel
22from .exceptions import (
23 APIError,
24 AuthenticationError,
25 AuthorizationError,
26 NotFoundError,
27 RateLimitError,
28 ServerError,
29 ValidationError,
30)
31from .models import (
32 AdminPlayerTeamAssignment,
33 AdminPlayerUpdate,
34 AdvanceWinnerRequest,
35 AgeGroupCreate,
36 AgeGroupUpdate,
37 BulkRenumberRequest,
38 BulkRosterCreate,
39 ChannelAccessRequestCreate,
40 ChannelAccessStatusUpdate,
41 DivisionCreate,
42 DivisionUpdate,
43 EnhancedGame,
44 GamePatch,
45 GenerateBracketRequest,
46 GoalEvent,
47 InviteRequestCreate,
48 InviteRequestStatusUpdate,
49 JerseyNumberUpdate,
50 LineupSave,
51 LiveMatchClock,
52 MatchSubmissionData,
53 MessageEvent,
54 PlayerCustomization,
55 PlayerHistoryCreate,
56 PlayerHistoryUpdate,
57 RefreshTokenRequest,
58 RoleUpdate,
59 RosterPlayerCreate,
60 RosterPlayerUpdate,
61 SeasonCreate,
62 SeasonUpdate,
63 Team,
64 TournamentCreate,
65 TournamentMatchCreate,
66 TournamentMatchUpdate,
67 UserProfileUpdate,
68)
70T = TypeVar("T", bound=BaseModel)
72logger = logging.getLogger(__name__)
75class MissingTableClient:
76 """Type-safe API client for Missing Table backend."""
78 def __init__(
79 self,
80 base_url: str = "http://localhost:8000",
81 access_token: str | None = None,
82 timeout: float = 30.0,
83 max_retries: int = 3,
84 ):
85 """
86 Initialize the API client.
88 Args:
89 base_url: Base URL of the API
90 access_token: JWT access token for authentication
91 timeout: Request timeout in seconds
92 max_retries: Maximum number of retry attempts
93 """
94 self.base_url = base_url.rstrip("/")
95 self._access_token = access_token
96 self._refresh_token: str | None = None
97 # Set to opt in to refresh-and-retry on a 401 (SB-1410): called with
98 # the new tokens so the caller can persist them.
99 self.on_token_refresh: Callable[[dict[str, Any]], None] | None = None
100 self.timeout = timeout
101 self.max_retries = max_retries
103 self._client = httpx.Client(
104 timeout=timeout,
105 follow_redirects=True,
106 )
108 def __enter__(self) -> "MissingTableClient":
109 """Context manager entry."""
110 return self
112 def __exit__(self, *args: Any) -> None:
113 """Context manager exit."""
114 self.close()
116 def close(self) -> None:
117 """Close the HTTP client."""
118 self._client.close()
120 def _get_headers(self) -> dict[str, str]:
121 """Get request headers with authentication."""
122 headers = {"Content-Type": "application/json"}
123 if self._access_token: 123 ↛ 125line 123 didn't jump to line 125 because the condition on line 123 was always true
124 headers["Authorization"] = f"Bearer {self._access_token}"
125 return headers
127 def _handle_response_error(self, response: httpx.Response) -> None:
128 """Handle HTTP error responses."""
129 try:
130 error_data = response.json()
131 except Exception:
132 error_data = {"detail": response.text}
134 error_message = error_data.get("detail", f"HTTP {response.status_code}")
136 if response.status_code == 401: 136 ↛ 138line 136 didn't jump to line 138 because the condition on line 136 was always true
137 raise AuthenticationError(error_message, response.status_code, error_data)
138 elif response.status_code == 403:
139 raise AuthorizationError(error_message, response.status_code, error_data)
140 elif response.status_code == 404:
141 raise NotFoundError(error_message, response.status_code, error_data)
142 elif response.status_code == 422:
143 raise ValidationError(error_message, response.status_code, error_data)
144 elif response.status_code == 429:
145 raise RateLimitError(error_message, response.status_code, error_data)
146 elif response.status_code >= 500:
147 raise ServerError(error_message, response.status_code, error_data)
148 else:
149 raise APIError(error_message, response.status_code, error_data)
151 def _request(
152 self,
153 method: str,
154 path: str,
155 json_data: dict[str, Any] | None = None,
156 params: dict[str, Any] | None = None,
157 timeout: float | None = None,
158 ) -> httpx.Response:
159 """Make an HTTP request with error handling.
161 `timeout` overrides the client's for this one request; left out, the
162 client's own applies, as it always has.
163 """
164 url = urljoin(self.base_url, path)
165 headers = self._get_headers()
167 logger.debug(f"{method} {url}")
168 if json_data:
169 logger.debug(f"Request body: {json_data}")
171 extra: dict[str, Any] = {} if timeout is None else {"timeout": timeout}
172 response = self._client.request(
173 method=method,
174 url=url,
175 headers=headers,
176 json=json_data,
177 params=params,
178 **extra,
179 )
181 if response.status_code == 401 and self._can_refresh(path):
182 tokens = self.refresh_access_token()
183 self.on_token_refresh(tokens)
184 response = self._client.request(
185 method=method,
186 url=url,
187 headers=self._get_headers(),
188 json=json_data,
189 params=params,
190 **extra,
191 )
193 if not response.is_success:
194 self._handle_response_error(response)
196 return response
198 def _can_refresh(self, path: str) -> bool:
199 """A 401 is retried once after a refresh, only when the caller opted in
200 and never for the auth endpoints themselves (no refresh loop)."""
201 return bool(self.on_token_refresh and self._refresh_token and not path.startswith("/api/auth/"))
203 def _request_multipart(
204 self,
205 method: str,
206 path: str,
207 files: dict[str, Any] | None = None,
208 data: dict[str, Any] | None = None,
209 params: dict[str, Any] | None = None,
210 ) -> httpx.Response:
211 """Make a multipart/form-data request (for file uploads)."""
212 url = urljoin(self.base_url, path)
213 # Omit Content-Type header; httpx sets multipart boundary automatically
214 headers = {}
215 if self._access_token:
216 headers["Authorization"] = f"Bearer {self._access_token}"
218 logger.debug(f"{method} {url} (multipart)")
220 response = self._client.request(
221 method=method,
222 url=url,
223 headers=headers,
224 files=files,
225 data=data,
226 params=params,
227 )
229 if not response.is_success:
230 self._handle_response_error(response)
232 return response
234 # Authentication endpoints
236 def login(self, username: str, password: str) -> dict[str, Any]:
237 """
238 Login with username and password.
240 Args:
241 username: Username (primary identifier)
242 password: User password
244 Returns:
245 Dict with access_token, refresh_token, and user info
246 """
247 response = self._request(
248 "POST",
249 "/api/auth/login",
250 json_data={"username": username, "password": password},
251 )
252 data = response.json()
254 # Handle nested session structure from API
255 if "session" in data:
256 session = data["session"]
257 self._access_token = session.get("access_token")
258 self._refresh_token = session.get("refresh_token")
259 # Return flattened structure for backward compatibility
260 return {
261 "access_token": self._access_token,
262 "refresh_token": self._refresh_token,
263 "token_type": session.get("token_type", "bearer"),
264 "user": data.get("user"),
265 "message": data.get("message"),
266 }
267 else:
268 # Fallback for flat structure
269 self._access_token = data.get("access_token")
270 self._refresh_token = data.get("refresh_token")
271 return data
273 def signup(
274 self,
275 username: str,
276 password: str,
277 display_name: str | None = None,
278 email: str | None = None,
279 invite_code: str | None = None,
280 ) -> dict[str, Any]:
281 """
282 Sign up a new user with username authentication.
284 Args:
285 username: Username (required, primary identifier)
286 password: User password
287 display_name: Optional display name
288 email: Optional email for notifications
289 invite_code: Optional invite code
291 Returns:
292 Dict with user info (may include access_token depending on API configuration)
293 """
294 payload = {"username": username, "password": password}
295 if display_name:
296 payload["display_name"] = display_name
297 if email:
298 payload["email"] = email
299 if invite_code:
300 payload["invite_code"] = invite_code
302 response = self._request("POST", "/api/auth/signup", json_data=payload)
303 data = response.json()
305 # Handle nested session structure if tokens are returned
306 if "session" in data:
307 session = data["session"]
308 self._access_token = session.get("access_token")
309 self._refresh_token = session.get("refresh_token")
311 return data
313 def logout(self) -> dict[str, Any]:
314 """Logout the current user."""
315 response = self._request("POST", "/api/auth/logout")
316 self._access_token = None
317 self._refresh_token = None
318 return response.json()
320 def refresh_access_token(self) -> dict[str, Any]:
321 """Refresh the access token using refresh token."""
322 if not self._refresh_token: 322 ↛ 323line 322 didn't jump to line 323 because the condition on line 322 was never true
323 raise AuthenticationError("No refresh token available")
325 model = RefreshTokenRequest(refresh_token=self._refresh_token)
326 response = self._request("POST", "/api/auth/refresh", json_data=model.model_dump())
327 data = response.json()
329 # Handle nested session structure
330 if "session" in data: 330 ↛ 331line 330 didn't jump to line 331 because the condition on line 330 was never true
331 session = data["session"]
332 self._access_token = session.get("access_token")
333 self._refresh_token = session.get("refresh_token")
334 # Return flattened structure for backward compatibility
335 return {
336 "access_token": self._access_token,
337 "refresh_token": self._refresh_token,
338 "token_type": session.get("token_type", "bearer"),
339 }
340 else:
341 # Fallback for flat structure
342 self._access_token = data.get("access_token")
343 return data
345 def get_profile(self) -> dict[str, Any]:
346 """Get current user's profile."""
347 response = self._request("GET", "/api/auth/profile")
348 return response.json()
350 def update_profile(self, display_name: str | None = None, team_id: int | None = None) -> dict[str, Any]:
351 """Update current user's profile."""
352 payload = {}
353 if display_name is not None:
354 payload["display_name"] = display_name
355 if team_id is not None:
356 payload["team_id"] = team_id
358 response = self._request("PUT", "/api/auth/profile", json_data=payload)
359 return response.json()
361 # Teams endpoints
363 def get_teams(
364 self,
365 game_type_id: int | None = None,
366 age_group_id: int | None = None,
367 ) -> list[dict[str, Any]]:
368 """Get all teams with optional filters."""
369 params = {}
370 if game_type_id is not None:
371 params["game_type_id"] = game_type_id
372 if age_group_id is not None:
373 params["age_group_id"] = age_group_id
375 response = self._request("GET", "/api/teams", params=params)
376 return response.json()
378 def get_team(self, team_id: int) -> dict[str, Any]:
379 """Get a specific team by ID."""
380 response = self._request("GET", f"/api/teams/{team_id}")
381 return response.json()
383 def create_team(self, team: Team) -> dict[str, Any]:
384 """Create a new team."""
385 response = self._request("POST", "/api/teams", json_data=team.model_dump(exclude_none=True))
386 return response.json()
388 def update_team(self, team_id: int, team: Team) -> dict[str, Any]:
389 """Update a team."""
390 response = self._request("PUT", f"/api/teams/{team_id}", json_data=team.model_dump(exclude_none=True))
391 return response.json()
393 def update_team_profile(
394 self,
395 team_id: int,
396 name: str,
397 city: str,
398 academy_team: bool = False,
399 club_id: int | None = None,
400 ) -> dict[str, Any]:
401 """Update a team, mirroring the backend's TeamUpdate exactly.
403 update_team() takes the full Team model, which requires age_group_ids
404 and division_id that PUT /api/teams/{id} ignores — and drops club_id
405 when it is None because of exclude_none, which the backend then reads
406 as "set club to null". Renaming a team through that path silently
407 detaches it from its club, taking the crest and colours with it.
409 This sends exactly the four fields the endpoint accepts, every time, so
410 club_id is only null when the caller means it (SB-824).
411 """
412 payload = {
413 "name": name,
414 "city": city,
415 "academy_team": academy_team,
416 "club_id": club_id,
417 }
418 response = self._request("PUT", f"/api/teams/{team_id}", json_data=payload)
419 return response.json()
421 def get_team_aliases(self, team_id: int) -> dict[str, Any]:
422 """Alternate strings that resolve to this team."""
423 response = self._request("GET", f"/api/admin/teams/{team_id}/aliases")
424 return response.json()
426 def add_team_alias(
427 self,
428 team_id: int,
429 external_name: str,
430 source: str = "mlssoccer.com",
431 kind: str = "feed_variant",
432 league_id: int | None = None,
433 ) -> dict[str, Any]:
434 """Record a string that should resolve to this team."""
435 payload: dict[str, Any] = {
436 "external_name": external_name,
437 "source": source,
438 "kind": kind,
439 }
440 if league_id is not None:
441 payload["league_id"] = league_id
442 response = self._request("POST", f"/api/admin/teams/{team_id}/aliases", json_data=payload)
443 return response.json()
445 def delete_team(self, team_id: int) -> dict[str, Any]:
446 """Delete a team."""
447 response = self._request("DELETE", f"/api/teams/{team_id}")
448 return response.json()
450 def merge_team(self, from_id: int, into_id: int, dry_run: bool = True) -> dict[str, Any]:
451 """Fold a duplicate team into another (admin only). Dry run by default."""
452 response = self._request(
453 "POST",
454 f"/api/admin/teams/{from_id}/merge-into/{into_id}",
455 params={"dry_run": str(dry_run).lower()},
456 )
457 return response.json()
459 # Games endpoints
461 def get_games(
462 self,
463 season_id: int | None = None,
464 age_group_id: int | None = None,
465 game_type_id: int | None = None,
466 match_type_id: int | None = None,
467 team_id: int | None = None,
468 limit: int | None = None,
469 upcoming: bool | None = None,
470 start_date: str | None = None,
471 end_date: str | None = None,
472 ) -> list[dict[str, Any]]:
473 """Get matches (games) with optional filters."""
474 params = {}
475 if season_id is not None:
476 params["season_id"] = season_id
477 if age_group_id is not None:
478 params["age_group_id"] = age_group_id
479 # Support both game_type_id (legacy) and match_type_id (current)
480 match_type = match_type_id if match_type_id is not None else game_type_id
481 if match_type is not None:
482 params["match_type_id"] = match_type
483 if team_id is not None:
484 params["team_id"] = team_id
485 if limit is not None:
486 params["limit"] = limit
487 if upcoming is not None:
488 params["upcoming"] = upcoming
489 if start_date is not None:
490 params["start_date"] = start_date
491 if end_date is not None:
492 params["end_date"] = end_date
494 response = self._request("GET", "/api/matches", params=params)
495 return response.json()
497 def get_game(self, game_id: int) -> dict[str, Any]:
498 """Get a specific match (game) by ID."""
499 response = self._request("GET", f"/api/matches/{game_id}")
500 return response.json()
502 def get_games_by_team(
503 self, team_id: int, season_id: int | None = None, age_group_id: int | None = None
504 ) -> list[dict[str, Any]]:
505 """Get all matches (games) for a specific team."""
506 params = {}
507 if season_id:
508 params["season_id"] = season_id
509 if age_group_id:
510 params["age_group_id"] = age_group_id
511 response = self._request("GET", f"/api/matches/team/{team_id}", params=params)
512 return response.json()
514 def create_game(self, game: EnhancedGame) -> dict[str, Any]:
515 """Create a new match (game)."""
516 # Convert game_type_id to match_type_id for API compatibility
517 game_data = game.model_dump(exclude_none=True)
518 if "game_type_id" in game_data:
519 game_data["match_type_id"] = game_data.pop("game_type_id")
520 response = self._request("POST", "/api/matches", json_data=game_data)
521 return response.json()
523 def update_game(self, game_id: int, game: EnhancedGame) -> dict[str, Any]:
524 """Update a match (game) - full update."""
525 # Convert game_type_id to match_type_id for API compatibility
526 game_data = game.model_dump(exclude_none=True)
527 if "game_type_id" in game_data:
528 game_data["match_type_id"] = game_data.pop("game_type_id")
529 response = self._request("PUT", f"/api/matches/{game_id}", json_data=game_data)
530 return response.json()
532 def patch_game(self, game_id: int, game_patch: GamePatch) -> dict[str, Any]:
533 """Partially update a match (game)."""
534 # Convert game_type_id to match_type_id for API compatibility
535 patch_data = game_patch.model_dump(exclude_none=True)
536 if "game_type_id" in patch_data:
537 patch_data["match_type_id"] = patch_data.pop("game_type_id")
538 response = self._request("PATCH", f"/api/matches/{game_id}", json_data=patch_data)
539 return response.json()
541 def delete_game(self, game_id: int) -> dict[str, Any]:
542 """Delete a match (game)."""
543 response = self._request("DELETE", f"/api/matches/{game_id}")
544 return response.json()
546 # Reference data endpoints
548 def get_age_groups(self) -> list[dict[str, Any]]:
549 """Get all age groups."""
550 response = self._request("GET", "/api/age-groups")
551 return response.json()
553 def create_age_group(self, age_group: AgeGroupCreate) -> dict[str, Any]:
554 """Create a new age group (admin only)."""
555 response = self._request("POST", "/api/age-groups", json_data=age_group.model_dump())
556 return response.json()
558 def update_age_group(self, age_group_id: int, age_group: AgeGroupUpdate) -> dict[str, Any]:
559 """Update an age group (admin only)."""
560 response = self._request("PUT", f"/api/age-groups/{age_group_id}", json_data=age_group.model_dump())
561 return response.json()
563 def delete_age_group(self, age_group_id: int) -> dict[str, Any]:
564 """Delete an age group (admin only)."""
565 response = self._request("DELETE", f"/api/age-groups/{age_group_id}")
566 return response.json()
568 def get_seasons(self) -> list[dict[str, Any]]:
569 """Get all seasons."""
570 response = self._request("GET", "/api/seasons")
571 return response.json()
573 def get_current_season(self) -> dict[str, Any]:
574 """Get the current season."""
575 response = self._request("GET", "/api/current-season")
576 return response.json()
578 def get_active_seasons(self) -> list[dict[str, Any]]:
579 """Get all active seasons."""
580 response = self._request("GET", "/api/active-seasons")
581 return response.json()
583 def create_season(self, season: SeasonCreate) -> dict[str, Any]:
584 """Create a new season (admin only)."""
585 response = self._request("POST", "/api/seasons", json_data=season.model_dump())
586 return response.json()
588 def update_season(self, season_id: int, season: SeasonUpdate) -> dict[str, Any]:
589 """Update a season (admin only)."""
590 response = self._request("PUT", f"/api/seasons/{season_id}", json_data=season.model_dump())
591 return response.json()
593 def delete_season(self, season_id: int) -> dict[str, Any]:
594 """Delete a season (admin only)."""
595 response = self._request("DELETE", f"/api/seasons/{season_id}")
596 return response.json()
598 def get_divisions(self) -> list[dict[str, Any]]:
599 """Get all divisions."""
600 response = self._request("GET", "/api/divisions")
601 return response.json()
603 def create_division(self, division: DivisionCreate) -> dict[str, Any]:
604 """Create a new division (admin only)."""
605 response = self._request("POST", "/api/divisions", json_data=division.model_dump(exclude_none=True))
606 return response.json()
608 def update_division(self, division_id: int, division: DivisionUpdate) -> dict[str, Any]:
609 """Update a division (admin only)."""
610 response = self._request(
611 "PUT", f"/api/divisions/{division_id}", json_data=division.model_dump(exclude_none=True)
612 )
613 return response.json()
615 def delete_division(self, division_id: int) -> dict[str, Any]:
616 """Delete a division (admin only)."""
617 response = self._request("DELETE", f"/api/divisions/{division_id}")
618 return response.json()
620 def get_game_types(self) -> list[dict[str, Any]]:
621 """Get all match types (game types)."""
622 response = self._request("GET", "/api/match-types")
623 return response.json()
625 def get_positions(self) -> list[dict[str, Any]]:
626 """Get all player positions."""
627 response = self._request("GET", "/api/positions")
628 return response.json()
630 # League table endpoints
632 def get_table(
633 self,
634 season_id: int | None = None,
635 age_group_id: int | None = None,
636 game_type_id: int | None = None,
637 division_id: int | None = None,
638 ) -> list[dict[str, Any]]:
639 """Get league standings table."""
640 params = {}
641 if season_id is not None:
642 params["season_id"] = season_id
643 if age_group_id is not None:
644 params["age_group_id"] = age_group_id
645 if game_type_id is not None:
646 params["game_type_id"] = game_type_id
647 if division_id is not None:
648 params["division_id"] = division_id
650 response = self._request("GET", "/api/table", params=params)
651 return response.json()
653 # Admin endpoints
655 def get_users(self) -> list[dict[str, Any]]:
656 """Get all users (admin only)."""
657 response = self._request("GET", "/api/auth/users")
658 return response.json()
660 def update_user_role(self, role_update: RoleUpdate) -> dict[str, Any]:
661 """Update a user's role (admin only)."""
662 response = self._request("PUT", "/api/auth/users/role", json_data=role_update.model_dump(exclude_none=True))
663 return response.json()
665 def delete_user(self, user_id: str) -> dict[str, Any]:
666 """Delete a user by ID (admin only)."""
667 response = self._request("DELETE", f"/api/auth/users/{user_id}")
668 return response.json()
670 # Utility endpoints
672 def health_check(self) -> dict[str, Any]:
673 """Check API health."""
674 response = self._request("GET", "/health")
675 return response.json()
677 def full_health_check(self) -> dict[str, Any]:
678 """Comprehensive health check."""
679 response = self._request("GET", "/health/full")
680 return response.json()
682 def get_csrf_token(self) -> str:
683 """Get CSRF token."""
684 response = self._request("GET", "/api/csrf-token")
685 return response.json()["csrf_token"]
687 # Club endpoints
689 def get_clubs(self, include_teams: bool = False) -> list[dict[str, Any]]:
690 """Get all clubs."""
691 params = {"include_teams": include_teams}
692 response = self._request("GET", "/api/clubs", params=params)
693 return response.json()
695 def get_club(self, club_id: int) -> dict[str, Any]:
696 """Get a specific club by ID."""
697 response = self._request("GET", f"/api/clubs/{club_id}")
698 return response.json()
700 def get_club_teams(self, club_id: int) -> list[dict[str, Any]]:
701 """Get all teams for a club."""
702 response = self._request("GET", f"/api/clubs/{club_id}/teams")
703 return response.json()
705 def create_club(
706 self,
707 name: str,
708 city: str | None = None,
709 description: str | None = None,
710 pro_academy: bool = False,
711 ) -> dict[str, Any]:
712 """Create a new club (admin only)."""
713 payload: dict[str, Any] = {"name": name}
714 if city:
715 payload["city"] = city
716 if description:
717 payload["description"] = description
718 # Sent unconditionally: False is a real answer, not an absent one.
719 payload["pro_academy"] = pro_academy
720 response = self._request("POST", "/api/clubs", json_data=payload)
721 return response.json()
723 def update_club(
724 self,
725 club_id: int,
726 name: str | None = None,
727 city: str | None = None,
728 description: str | None = None,
729 ) -> dict[str, Any]:
730 """Update a club (admin only)."""
731 payload = {}
732 if name:
733 payload["name"] = name
734 if city:
735 payload["city"] = city
736 if description:
737 payload["description"] = description
738 response = self._request("PUT", f"/api/clubs/{club_id}", json_data=payload)
739 return response.json()
741 def update_club_profile(
742 self,
743 club_id: int,
744 name: str,
745 city: str,
746 website: str | None = None,
747 description: str | None = None,
748 logo_url: str | None = None,
749 primary_color: str | None = None,
750 secondary_color: str | None = None,
751 pro_academy: bool = False,
752 ) -> dict[str, Any]:
753 """Update a club, mirroring the backend's Club model exactly.
755 PUT /api/clubs/{id} takes the full Club model — it is a replace, not a
756 patch. update_club() sends only the fields it was given, which fails
757 validation when city is omitted and, worse, would blank logo_url and
758 the brand colours if it did not: the crest and colours every IG card
759 and team header reads (SB-824).
761 Callers must read the club first and resend everything they are not
762 deliberately changing. pro_academy is part of that: it defaults to
763 False on the backend model, so omitting it un-flags the club (SB-842).
764 """
765 payload = {
766 "name": name,
767 "city": city,
768 "website": website,
769 "description": description,
770 "logo_url": logo_url,
771 "primary_color": primary_color,
772 "secondary_color": secondary_color,
773 "pro_academy": pro_academy,
774 }
775 response = self._request("PUT", f"/api/clubs/{club_id}", json_data=payload)
776 return response.json()
778 def delete_club(self, club_id: int) -> dict[str, Any]:
779 """Delete a club (admin only)."""
780 response = self._request("DELETE", f"/api/clubs/{club_id}")
781 return response.json()
783 def merge_club(self, from_id: int, into_id: int, dry_run: bool = True) -> dict[str, Any]:
784 """Fold a duplicate club into another (admin only). Dry run by default."""
785 response = self._request(
786 "POST",
787 f"/api/admin/clubs/{from_id}/merge-into/{into_id}",
788 params={"dry_run": str(dry_run).lower()},
789 )
790 return response.json()
792 def get_club_logo_gaps(self, season_id: int | None = None, include_all: bool = False) -> dict[str, Any]:
793 """Teams with no club, clubs with no crest, hot-linked crests (admin only)."""
794 params: dict[str, Any] = {}
795 if season_id:
796 params["season_id"] = season_id
797 if include_all:
798 params["all"] = "true"
799 response = self._request("GET", "/api/admin/clubs/logo-gaps", params=params)
800 return response.json()
802 # Invite endpoints
804 def validate_invite(self, invite_code: str) -> dict[str, Any]:
805 """Validate an invite code (public endpoint)."""
806 response = self._request("GET", f"/api/invites/validate/{invite_code}")
807 return response.json()
809 def get_my_invites(self, status: str | None = None) -> list[dict[str, Any]]:
810 """Get invites created by current user."""
811 params = {}
812 if status:
813 params["status"] = status
814 response = self._request("GET", "/api/invites/my-invites", params=params)
815 return response.json()
817 def cancel_invite(self, invite_id: str) -> dict[str, Any]:
818 """Cancel a pending invite."""
819 response = self._request("DELETE", f"/api/invites/{invite_id}")
820 return response.json()
822 # Admin invite creation endpoints
824 def create_club_manager_invite(self, club_id: int, email: str | None = None) -> dict[str, Any]:
825 """Create a club manager invite (admin only)."""
826 payload = {"club_id": club_id}
827 if email:
828 payload["email"] = email
829 response = self._request("POST", "/api/invites/admin/club-manager", json_data=payload)
830 return response.json()
832 def create_team_manager_invite(self, team_id: int, age_group_id: int, email: str | None = None) -> dict[str, Any]:
833 """Create a team manager invite (admin only)."""
834 payload = {
835 "invite_type": "team_manager",
836 "team_id": team_id,
837 "age_group_id": age_group_id,
838 }
839 if email:
840 payload["email"] = email
841 response = self._request("POST", "/api/invites/admin/team-manager", json_data=payload)
842 return response.json()
844 def create_team_player_invite_admin(
845 self, team_id: int, age_group_id: int, email: str | None = None
846 ) -> dict[str, Any]:
847 """Create a team player invite (admin only)."""
848 payload = {
849 "invite_type": "team_player",
850 "team_id": team_id,
851 "age_group_id": age_group_id,
852 }
853 if email:
854 payload["email"] = email
855 response = self._request("POST", "/api/invites/admin/team-player", json_data=payload)
856 return response.json()
858 def create_team_fan_invite_admin(self, team_id: int, age_group_id: int, email: str | None = None) -> dict[str, Any]:
859 """Create a team fan invite (admin only)."""
860 payload = {
861 "invite_type": "team_fan",
862 "team_id": team_id,
863 "age_group_id": age_group_id,
864 }
865 if email:
866 payload["email"] = email
867 response = self._request("POST", "/api/invites/admin/team-fan", json_data=payload)
868 return response.json()
870 def create_club_fan_invite_admin(
871 self, club_id: int, email: str | None = None, invite_request_id: str | None = None
872 ) -> dict[str, Any]:
873 """Create a club fan invite (admin only), optionally answering an invite request."""
874 payload = {"club_id": club_id}
875 if email:
876 payload["email"] = email
877 if invite_request_id:
878 payload["invite_request_id"] = invite_request_id
879 response = self._request("POST", "/api/invites/admin/club-fan", json_data=payload)
880 return response.json()
882 def retry_invite_testflight(self, invite_id: str) -> dict[str, Any]:
883 """Retry adding an iPhone beta invite's tester to TestFlight (admin only)."""
884 response = self._request("POST", f"/api/invites/admin/{invite_id}/testflight/retry")
885 return response.json()
887 # Club manager invite creation endpoints
889 def create_club_fan_invite(self, club_id: int, email: str | None = None) -> dict[str, Any]:
890 """Create a club fan invite (club manager or admin)."""
891 payload = {"club_id": club_id}
892 if email:
893 payload["email"] = email
894 response = self._request("POST", "/api/invites/club-manager/club-fan", json_data=payload)
895 return response.json()
897 # Team manager invite creation endpoints
899 def create_team_player_invite(
900 self, team_id: int, age_group_id: int, email: str | None = None, player_id: int | None = None
901 ) -> dict[str, Any]:
902 """Create a team player invite (team manager or admin)."""
903 payload: dict[str, Any] = {
904 "invite_type": "team_player",
905 "team_id": team_id,
906 "age_group_id": age_group_id,
907 }
908 if email:
909 payload["email"] = email
910 if player_id is not None:
911 payload["player_id"] = player_id
912 response = self._request("POST", "/api/invites/team-manager/team-player", json_data=payload)
913 return response.json()
915 def create_team_fan_invite(self, team_id: int, age_group_id: int, email: str | None = None) -> dict[str, Any]:
916 """Create a team fan invite (team manager or admin)."""
917 payload = {
918 "invite_type": "team_fan",
919 "team_id": team_id,
920 "age_group_id": age_group_id,
921 }
922 if email:
923 payload["email"] = email
924 response = self._request("POST", "/api/invites/team-manager/team-fan", json_data=payload)
925 return response.json()
927 def get_team_manager_assignments(self) -> list[dict[str, Any]]:
928 """Get team assignments for current team manager."""
929 response = self._request("GET", "/api/invites/team-manager/assignments")
930 return response.json()
932 # League endpoints
934 def get_leagues(self) -> list[dict[str, Any]]:
935 """Get all leagues."""
936 response = self._request("GET", "/api/leagues")
937 return response.json()
939 def get_league(self, league_id: int) -> dict[str, Any]:
940 """Get a specific league by ID."""
941 response = self._request("GET", f"/api/leagues/{league_id}")
942 return response.json()
944 def create_league(self, name: str, description: str | None = None, is_active: bool = True) -> dict[str, Any]:
945 """Create a new league (admin only)."""
946 payload = {"name": name, "is_active": is_active}
947 if description:
948 payload["description"] = description
949 response = self._request("POST", "/api/leagues", json_data=payload)
950 return response.json()
952 def update_league(
953 self,
954 league_id: int,
955 name: str | None = None,
956 description: str | None = None,
957 is_active: bool | None = None,
958 ) -> dict[str, Any]:
959 """Update a league (admin only)."""
960 payload = {}
961 if name is not None:
962 payload["name"] = name
963 if description is not None:
964 payload["description"] = description
965 if is_active is not None:
966 payload["is_active"] = is_active
967 response = self._request("PUT", f"/api/leagues/{league_id}", json_data=payload)
968 return response.json()
970 def delete_league(self, league_id: int) -> dict[str, Any]:
971 """Delete a league (admin only)."""
972 response = self._request("DELETE", f"/api/leagues/{league_id}")
973 return response.json()
975 # Auth extras
977 def get_me(self) -> dict[str, Any]:
978 """Get current authenticated user info."""
979 response = self._request("GET", "/api/auth/me")
980 return response.json()
982 def check_username_available(self, username: str) -> dict[str, Any]:
983 """Check if a username is available."""
984 response = self._request("GET", f"/api/auth/username-available/{username}")
985 return response.json()
987 # Profile photos
989 def upload_profile_photo(self, slot: str, file_path: str) -> dict[str, Any]:
990 """Upload a profile photo to a slot (multipart)."""
991 with open(file_path, "rb") as f:
992 response = self._request_multipart(
993 "POST",
994 f"/api/auth/profile/photo/{slot}",
995 files={"file": (file_path.split("/")[-1], f)},
996 )
997 return response.json()
999 def delete_profile_photo(self, slot: str) -> dict[str, Any]:
1000 """Delete a profile photo from a slot."""
1001 response = self._request("DELETE", f"/api/auth/profile/photo/{slot}")
1002 return response.json()
1004 def set_profile_photo_slot(self, slot: str) -> dict[str, Any]:
1005 """Set the active profile photo slot."""
1006 response = self._request("PUT", "/api/auth/profile/photo/profile-slot", json_data={"slot": slot})
1007 return response.json()
1009 # Profile customization
1011 def update_player_customization(self, customization: PlayerCustomization) -> dict[str, Any]:
1012 """Update player customization settings."""
1013 response = self._request(
1014 "PUT", "/api/auth/profile/customization", json_data=customization.model_dump(exclude_none=True)
1015 )
1016 return response.json()
1018 # Player history
1020 def get_player_history(self) -> list[dict[str, Any]]:
1021 """Get current user's player history."""
1022 response = self._request("GET", "/api/auth/profile/history")
1023 return response.json()
1025 def get_current_team_assignment(self) -> dict[str, Any]:
1026 """Get current team assignment for the authenticated player."""
1027 response = self._request("GET", "/api/auth/profile/history/current")
1028 return response.json()
1030 def get_all_current_teams(self) -> list[dict[str, Any]]:
1031 """Get all current team assignments for the authenticated player."""
1032 response = self._request("GET", "/api/auth/profile/teams/current")
1033 return response.json()
1035 def create_player_history(self, history: PlayerHistoryCreate) -> dict[str, Any]:
1036 """Create a player history entry."""
1037 response = self._request("POST", "/api/auth/profile/history", json_data=history.model_dump(exclude_none=True))
1038 return response.json()
1040 def update_player_history(self, history_id: int, history: PlayerHistoryUpdate) -> dict[str, Any]:
1041 """Update a player history entry."""
1042 response = self._request(
1043 "PUT", f"/api/auth/profile/history/{history_id}", json_data=history.model_dump(exclude_none=True)
1044 )
1045 return response.json()
1047 def delete_player_history(self, history_id: int) -> dict[str, Any]:
1048 """Delete a player history entry."""
1049 response = self._request("DELETE", f"/api/auth/profile/history/{history_id}")
1050 return response.json()
1052 # Admin user profile
1054 def admin_update_user_profile(self, profile: UserProfileUpdate) -> dict[str, Any]:
1055 """Update a user profile (admin only)."""
1056 response = self._request("PUT", "/api/auth/users/profile", json_data=profile.model_dump(exclude_none=True))
1057 return response.json()
1059 # Admin player management
1061 def get_admin_players(self, **params: Any) -> list[dict[str, Any]]:
1062 """Get players list (admin only)."""
1063 response = self._request("GET", "/api/admin/players", params=params or None)
1064 return response.json()
1066 def update_admin_player(self, player_id: int, update: AdminPlayerUpdate) -> dict[str, Any]:
1067 """Update a player (admin only)."""
1068 response = self._request(
1069 "PUT", f"/api/admin/players/{player_id}", json_data=update.model_dump(exclude_none=True)
1070 )
1071 return response.json()
1073 def add_admin_player_team(self, player_id: int, assignment: AdminPlayerTeamAssignment) -> dict[str, Any]:
1074 """Assign a player to a team (admin only)."""
1075 response = self._request(
1076 "POST", f"/api/admin/players/{player_id}/teams", json_data=assignment.model_dump(exclude_none=True)
1077 )
1078 return response.json()
1080 def end_admin_player_team(self, history_id: int) -> dict[str, Any]:
1081 """End a player's team assignment (admin only)."""
1082 response = self._request("PUT", f"/api/admin/players/teams/{history_id}/end")
1083 return response.json()
1085 # Team roster
1087 def get_team_roster(self, team_id: int, season_id: int | None = None) -> dict[str, Any]:
1088 """Get team roster for a season."""
1089 params = {}
1090 if season_id is not None:
1091 params["season_id"] = season_id
1092 response = self._request("GET", f"/api/teams/{team_id}/roster", params=params or None)
1093 return response.json()
1095 def create_roster_entry(self, team_id: int, entry: RosterPlayerCreate) -> dict[str, Any]:
1096 """Create a roster entry for a team."""
1097 response = self._request("POST", f"/api/teams/{team_id}/roster", json_data=entry.model_dump(exclude_none=True))
1098 return response.json()
1100 def bulk_create_roster(self, team_id: int, bulk: BulkRosterCreate) -> dict[str, Any]:
1101 """Bulk create roster entries for a team."""
1102 response = self._request(
1103 "POST", f"/api/teams/{team_id}/roster/bulk", json_data=bulk.model_dump(exclude_none=True)
1104 )
1105 return response.json()
1107 def update_roster_entry(self, team_id: int, player_id: int, update: RosterPlayerUpdate) -> dict[str, Any]:
1108 """Update a roster entry."""
1109 response = self._request(
1110 "PUT", f"/api/teams/{team_id}/roster/{player_id}", json_data=update.model_dump(exclude_none=True)
1111 )
1112 return response.json()
1114 def update_jersey_number(self, team_id: int, player_id: int, update: JerseyNumberUpdate) -> dict[str, Any]:
1115 """Update a player's jersey number."""
1116 response = self._request(
1117 "PUT", f"/api/teams/{team_id}/roster/{player_id}/number", json_data=update.model_dump(exclude_none=True)
1118 )
1119 return response.json()
1121 def bulk_renumber_roster(self, team_id: int, renumber: BulkRenumberRequest) -> dict[str, Any]:
1122 """Bulk renumber roster entries."""
1123 response = self._request(
1124 "POST", f"/api/teams/{team_id}/roster/renumber", json_data=renumber.model_dump(exclude_none=True)
1125 )
1126 return response.json()
1128 def delete_roster_entry(self, team_id: int, player_id: int) -> dict[str, Any]:
1129 """Delete a roster entry."""
1130 response = self._request("DELETE", f"/api/teams/{team_id}/roster/{player_id}")
1131 return response.json()
1133 # Team players & stats
1135 def get_team_players(self, team_id: int) -> list[dict[str, Any]]:
1136 """Get all players for a team."""
1137 response = self._request("GET", f"/api/teams/{team_id}/players")
1138 return response.json()
1140 def get_team_stats(
1141 self,
1142 team_id: int,
1143 season_id: int | None = None,
1144 match_type_id: int | list[int] | None = None,
1145 age_group_id: int | None = None,
1146 ) -> dict[str, Any]:
1147 """Get team stats.
1149 match_type_id narrows to a competition, or a list to total several
1150 (SB-433, SB-1599); age_group_id to one
1151 age group's players (SB-1258). Omit either for all.
1152 """
1153 params = {}
1154 if season_id is not None:
1155 params["season_id"] = season_id
1156 if match_type_id is not None:
1157 params["match_type_id"] = match_type_id
1158 if age_group_id is not None:
1159 params["age_group_id"] = age_group_id
1160 response = self._request("GET", f"/api/teams/{team_id}/stats", params=params or None)
1161 return response.json()
1163 def get_match_types(self) -> list[dict[str, Any]]:
1164 """Get the competition vocabulary (League, Friendly, Tournament, ...)."""
1165 response = self._request("GET", "/api/match-types")
1166 return response.json()
1168 # Team match types
1170 def add_team_match_type(self, team_id: int, match_type_id: int, age_group_id: int) -> dict[str, Any]:
1171 """Add a match type to a team."""
1172 response = self._request(
1173 "POST",
1174 f"/api/teams/{team_id}/match-types",
1175 json_data={"match_type_id": match_type_id, "age_group_id": age_group_id},
1176 )
1177 return response.json()
1179 def delete_team_match_type(self, team_id: int, match_type_id: int, age_group_id: int) -> dict[str, Any]:
1180 """Remove a match type from a team."""
1181 response = self._request("DELETE", f"/api/teams/{team_id}/match-types/{match_type_id}/{age_group_id}")
1182 return response.json()
1184 # Match live
1186 def get_live_matches(self) -> list[dict[str, Any]]:
1187 """Get all currently live matches."""
1188 response = self._request("GET", "/api/matches/live")
1189 return response.json()
1191 def get_live_match_state(self, match_id: int) -> dict[str, Any]:
1192 """Get live state for a match."""
1193 response = self._request("GET", f"/api/matches/{match_id}/live")
1194 return response.json()
1196 def update_match_clock(self, match_id: int, clock: LiveMatchClock) -> dict[str, Any]:
1197 """Update the match clock."""
1198 response = self._request(
1199 "POST", f"/api/matches/{match_id}/live/clock", json_data=clock.model_dump(exclude_none=True)
1200 )
1201 return response.json()
1203 def reopen_match(self, match_id: int) -> dict[str, Any]:
1204 """Reopen a match that was ended by mistake."""
1205 response = self._request("POST", f"/api/matches/{match_id}/live/reopen")
1206 return response.json()
1208 def post_goal(self, match_id: int, goal: GoalEvent) -> dict[str, Any]:
1209 """Record a goal event."""
1210 response = self._request(
1211 "POST", f"/api/matches/{match_id}/live/goal", json_data=goal.model_dump(exclude_none=True)
1212 )
1213 return response.json()
1215 def post_message(self, match_id: int, message: MessageEvent) -> dict[str, Any]:
1216 """Post a match message event."""
1217 response = self._request(
1218 "POST", f"/api/matches/{match_id}/live/message", json_data=message.model_dump(exclude_none=True)
1219 )
1220 return response.json()
1222 def delete_match_event(self, match_id: int, event_id: int) -> dict[str, Any]:
1223 """Delete a match event."""
1224 response = self._request("DELETE", f"/api/matches/{match_id}/live/events/{event_id}")
1225 return response.json()
1227 def get_match_events(self, match_id: int) -> list[dict[str, Any]]:
1228 """Get all events for a match."""
1229 response = self._request("GET", f"/api/matches/{match_id}/live/events")
1230 return response.json()
1232 # Match lineup
1234 def get_lineup(self, match_id: int, team_id: int) -> dict[str, Any]:
1235 """Get lineup for a team in a match."""
1236 response = self._request("GET", f"/api/matches/{match_id}/lineup/{team_id}")
1237 return response.json()
1239 def save_lineup(self, match_id: int, team_id: int, lineup: LineupSave) -> dict[str, Any]:
1240 """Save lineup for a team in a match."""
1241 response = self._request(
1242 "PUT", f"/api/matches/{match_id}/lineup/{team_id}", json_data=lineup.model_dump(exclude_none=True)
1243 )
1244 return response.json()
1246 # Match operations
1248 def submit_match_async(self, submission: MatchSubmissionData) -> dict[str, Any]:
1249 """Submit a match asynchronously via message queue."""
1250 response = self._request("POST", "/api/matches/submit", json_data=submission.model_dump(exclude_none=True))
1251 return response.json()
1253 def get_task_status(self, task_id: str) -> dict[str, Any]:
1254 """Get the status of an async task."""
1255 response = self._request("GET", f"/api/matches/task/{task_id}")
1256 return response.json()
1258 # Team mappings
1260 def create_team_mapping(self, team_id: int, age_group_id: int, division_id: int) -> dict[str, Any]:
1261 """Create a team mapping."""
1262 response = self._request(
1263 "POST",
1264 "/api/team-mappings",
1265 json_data={"team_id": team_id, "age_group_id": age_group_id, "division_id": division_id},
1266 )
1267 return response.json()
1269 def delete_team_mapping(self, team_id: int, age_group_id: int, division_id: int) -> dict[str, Any]:
1270 """Delete a team mapping."""
1271 response = self._request("DELETE", f"/api/team-mappings/{team_id}/{age_group_id}/{division_id}")
1272 return response.json()
1274 # Division guests (SB-1598)
1276 def list_division_guests(self, season_id: int, age_group_id: int | None = None) -> list[dict[str, Any]]:
1277 """Teams hidden from a table this season."""
1278 params: dict[str, Any] = {"season_id": season_id}
1279 if age_group_id:
1280 params["age_group_id"] = age_group_id
1281 response = self._request("GET", "/api/admin/division-guests", params=params)
1282 return response.json()
1284 def add_division_guest(
1285 self, team_id: int, division_id: int, age_group_id: int, season_id: int, reason: str
1286 ) -> dict[str, Any]:
1287 """Hide a team from one table; its matches still count for opponents."""
1288 response = self._request(
1289 "POST",
1290 "/api/admin/division-guests",
1291 json_data={
1292 "team_id": team_id,
1293 "division_id": division_id,
1294 "age_group_id": age_group_id,
1295 "season_id": season_id,
1296 "reason": reason,
1297 },
1298 )
1299 return response.json()
1301 def remove_division_guest(self, guest_id: int) -> dict[str, Any]:
1302 """Give a team its table row back."""
1303 response = self._request("DELETE", f"/api/admin/division-guests/{guest_id}")
1304 return response.json()
1306 # Club logo
1308 def upload_club_logo(self, club_id: int, file_path: str) -> dict[str, Any]:
1309 """Upload a club logo (multipart)."""
1310 with open(file_path, "rb") as f:
1311 response = self._request_multipart(
1312 "POST",
1313 f"/api/clubs/{club_id}/logo",
1314 files={"file": (file_path.split("/")[-1], f)},
1315 )
1316 return response.json()
1318 def upload_tournament_logo(self, tournament_id: int, file_path: str) -> dict[str, Any]:
1319 """Upload a tournament logo (multipart). Admin only."""
1320 with open(file_path, "rb") as f:
1321 response = self._request_multipart(
1322 "POST",
1323 f"/api/admin/tournaments/{tournament_id}/logo",
1324 files={"file": (file_path.split("/")[-1], f)},
1325 )
1326 return response.json()
1328 # Player stats
1330 def get_my_player_stats(self, season_id: int | None = None) -> dict[str, Any]:
1331 """Get current user's player stats."""
1332 params = {}
1333 if season_id is not None:
1334 params["season_id"] = season_id
1335 response = self._request("GET", "/api/me/player-stats", params=params or None)
1336 return response.json()
1338 def get_player_profile(self, user_id: str) -> dict[str, Any]:
1339 """Get a player's public profile."""
1340 response = self._request("GET", f"/api/players/{user_id}/profile")
1341 return response.json()
1343 def get_roster_player_stats(self, player_id: int, season_id: int | None = None) -> dict[str, Any]:
1344 """Get stats for a roster player."""
1345 params = {}
1346 if season_id is not None:
1347 params["season_id"] = season_id
1348 response = self._request("GET", f"/api/roster/{player_id}/stats", params=params or None)
1349 return response.json()
1351 # Leaderboards
1353 def get_goals_leaderboard(self, **params: Any) -> list[dict[str, Any]]:
1354 """Get the goals leaderboard."""
1355 response = self._request("GET", "/api/leaderboards/goals", params=params or None)
1356 return response.json()
1358 # Invite requests
1360 def create_invite_request(self, request: InviteRequestCreate) -> dict[str, Any]:
1361 """Submit a public invite request."""
1362 response = self._request("POST", "/api/invite-requests", json_data=request.model_dump(exclude_none=True))
1363 return response.json()
1365 def list_invite_requests(
1366 self,
1367 status: str | None = None,
1368 limit: int | None = None,
1369 offset: int | None = None,
1370 ios_beta: bool | None = None,
1371 ) -> list[dict[str, Any]]:
1372 """List invite requests (admin only)."""
1373 params: dict[str, Any] = {}
1374 if status is not None:
1375 params["status"] = status
1376 if ios_beta is not None:
1377 params["ios_beta"] = str(ios_beta).lower()
1378 if limit is not None:
1379 params["limit"] = limit
1380 if offset is not None:
1381 params["offset"] = offset
1382 response = self._request("GET", "/api/invite-requests", params=params or None)
1383 return response.json()
1385 def get_invite_request_stats(self) -> dict[str, Any]:
1386 """Get invite request statistics (admin only)."""
1387 response = self._request("GET", "/api/invite-requests/stats")
1388 return response.json()
1390 def get_invite_request(self, request_id: str) -> dict[str, Any]:
1391 """Get a specific invite request (admin only)."""
1392 response = self._request("GET", f"/api/invite-requests/{request_id}")
1393 return response.json()
1395 def update_invite_request_status(self, request_id: str, update: InviteRequestStatusUpdate) -> dict[str, Any]:
1396 """Update invite request status (admin only)."""
1397 response = self._request(
1398 "PUT", f"/api/invite-requests/{request_id}/status", json_data=update.model_dump(exclude_none=True)
1399 )
1400 return response.json()
1402 def delete_invite_request(self, request_id: str) -> dict[str, Any]:
1403 """Delete an invite request (admin only)."""
1404 response = self._request("DELETE", f"/api/invite-requests/{request_id}")
1405 return response.json()
1407 # Channel access requests
1409 def get_my_channel_request(self) -> dict[str, Any]:
1410 """Get the current user's channel access request."""
1411 response = self._request("GET", "/api/channel-requests/me")
1412 return response.json()
1414 def create_channel_request(self, request: ChannelAccessRequestCreate) -> dict[str, Any]:
1415 """Submit or update a channel access request (logged-in users)."""
1416 response = self._request("POST", "/api/channel-requests", json_data=request.model_dump(exclude_none=True))
1417 return response.json()
1419 def list_channel_requests(
1420 self,
1421 status: str | None = None,
1422 platform: str | None = None,
1423 team_id: int | None = None,
1424 limit: int | None = None,
1425 offset: int | None = None,
1426 ) -> list[dict[str, Any]]:
1427 """List channel access requests (admin/club_manager only)."""
1428 params: dict[str, Any] = {}
1429 if status:
1430 params["status"] = status
1431 if platform:
1432 params["platform"] = platform
1433 if team_id:
1434 params["team_id"] = team_id
1435 if limit is not None:
1436 params["limit"] = limit
1437 if offset is not None:
1438 params["offset"] = offset
1439 response = self._request("GET", "/api/channel-requests", params=params)
1440 return response.json()
1442 def get_channel_request_stats(self) -> dict[str, Any]:
1443 """Get channel access request statistics (admin/club_manager only)."""
1444 response = self._request("GET", "/api/channel-requests/stats")
1445 return response.json()
1447 def get_channel_request(self, request_id: str) -> dict[str, Any]:
1448 """Get a specific channel access request (admin/club_manager only)."""
1449 response = self._request("GET", f"/api/channel-requests/{request_id}")
1450 return response.json()
1452 def update_channel_request_status(self, request_id: str, update: ChannelAccessStatusUpdate) -> dict[str, Any]:
1453 """Update per-platform status on a channel access request (admin/club_manager only)."""
1454 response = self._request(
1455 "PUT",
1456 f"/api/channel-requests/{request_id}/status",
1457 json_data=update.model_dump(exclude_none=True),
1458 )
1459 return response.json()
1461 def delete_channel_request(self, request_id: str) -> dict[str, Any]:
1462 """Delete a channel access request (admin only)."""
1463 response = self._request("DELETE", f"/api/channel-requests/{request_id}")
1464 return response.json()
1466 # Playoffs
1468 def get_playoff_bracket(self, league_id: int, season_id: int, age_group_id: int) -> dict[str, Any]:
1469 """Get playoff bracket for a league/season/age group."""
1470 params = {"league_id": league_id, "season_id": season_id, "age_group_id": age_group_id}
1471 response = self._request("GET", "/api/playoffs/bracket", params=params)
1472 return response.json()
1474 def advance_playoff_winner(self, request: AdvanceWinnerRequest) -> dict[str, Any]:
1475 """Advance the winner of a completed bracket slot (team manager or admin)."""
1476 response = self._request("POST", "/api/playoffs/advance", json_data=request.model_dump())
1477 return response.json()
1479 def generate_playoff_bracket(self, request: GenerateBracketRequest) -> dict[str, Any]:
1480 """Generate playoff brackets from current standings (admin only)."""
1481 response = self._request("POST", "/api/admin/playoffs/generate", json_data=request.model_dump())
1482 return response.json()
1484 def advance_playoff_winner_admin(self, request: AdvanceWinnerRequest) -> dict[str, Any]:
1485 """Advance the winner of a completed bracket slot (admin only)."""
1486 response = self._request("POST", "/api/admin/playoffs/advance", json_data=request.model_dump())
1487 return response.json()
1489 def delete_playoff_bracket(self, league_id: int, season_id: int, age_group_id: int) -> dict[str, Any]:
1490 """Delete an entire playoff bracket and its matches (admin only)."""
1491 params = {"league_id": league_id, "season_id": season_id, "age_group_id": age_group_id}
1492 response = self._request("DELETE", "/api/admin/playoffs/bracket", params=params)
1493 return response.json()
1495 # Tournaments
1497 def get_active_tournaments(self) -> list[dict[str, Any]]:
1498 """Get all active tournaments (requires login)."""
1499 response = self._request("GET", "/api/tournaments")
1500 return response.json()
1502 def lookup_team(self, name: str) -> dict[str, Any]:
1503 """Look up a team by name and return exact + similar matches without creating (admin only).
1505 Returns:
1506 {"exact": team | None, "similar": [team, ...]}
1507 """
1508 response = self._request("GET", "/api/admin/teams/lookup", params={"name": name})
1509 return response.json()
1511 def create_tournament(self, tournament: TournamentCreate) -> dict[str, Any]:
1512 """Create a new tournament (admin only)."""
1513 response = self._request("POST", "/api/admin/tournaments", json_data=tournament.model_dump())
1514 return response.json()
1516 def get_tournament(self, tournament_id: int) -> dict[str, Any]:
1517 """Get tournament detail including its matches (requires login).
1519 The returned dict has a ``matches`` list; each match carries ``id``,
1520 ``home_team``/``away_team`` (with ``name``), scores, penalty scores,
1521 ``match_status`` and ``tournament_round`` — enough to map a screenshot
1522 row to an existing match for updates.
1523 """
1524 response = self._request("GET", f"/api/tournaments/{tournament_id}")
1525 return response.json()
1527 def get_tournament_matches(
1528 self,
1529 tournament_id: int,
1530 *,
1531 age_group_id: int | None = None,
1532 group: str | None = None,
1533 round: str | None = None,
1534 limit: int | None = None,
1535 offset: int | None = None,
1536 ) -> dict[str, Any]:
1537 """One page of a tournament's matches, filtered server-side (requires login, SB-1749).
1539 Returns ``{"matches", "total", "limit", "offset"}``. ``total`` is the
1540 exact number of matches the filters select, not the page length.
1541 """
1542 params = {
1543 "age_group_id": age_group_id,
1544 "group": group,
1545 "round": round,
1546 "limit": limit,
1547 "offset": offset,
1548 }
1549 response = self._request(
1550 "GET",
1551 f"/api/tournaments/{tournament_id}/matches",
1552 params={k: v for k, v in params.items() if v is not None},
1553 )
1554 return response.json()
1556 def get_tournament_filters(
1557 self, tournament_id: int, *, age_group_id: int | None = None, on_date: str | None = None
1558 ) -> dict[str, Any]:
1559 """The age groups and groups a tournament can be filtered by (requires login, SB-1749).
1561 ``groups`` is ``[]`` when the age group has none and ``None`` when the
1562 counts could not be computed; a ``None`` ``matches`` is likewise
1563 unknown, not zero.
1564 """
1565 params = {"age_group_id": age_group_id, "on_date": on_date}
1566 response = self._request(
1567 "GET",
1568 f"/api/tournaments/{tournament_id}/filters",
1569 params={k: v for k, v in params.items() if v is not None},
1570 )
1571 return response.json()
1573 def search_tournament_teams(self, tournament_id: int, q: str, *, limit: int | None = None) -> list[dict[str, Any]]:
1574 """Teams in a tournament whose team or club name contains ``q`` (requires login, SB-1870).
1576 Each is ``{team_id, name, club_id, club_name, logo_url, age_groups,
1577 league}``; ``league`` is None when the team is in no conference, or in
1578 both leagues'. A ``q`` under two characters returns ``[]``.
1579 """
1580 params = {"q": q, "limit": limit}
1581 response = self._request(
1582 "GET",
1583 f"/api/tournaments/{tournament_id}/teams",
1584 params={k: v for k, v in params.items() if v is not None},
1585 )
1586 return response.json()
1588 def create_tournament_match(self, tournament_id: int, match: TournamentMatchCreate) -> dict[str, Any]:
1589 """Add a match to a tournament (admin only)."""
1590 response = self._request(
1591 "POST",
1592 f"/api/admin/tournaments/{tournament_id}/matches",
1593 json_data=match.model_dump(),
1594 )
1595 return response.json()
1597 def update_tournament_match(
1598 self, tournament_id: int, match_id: int, match: TournamentMatchUpdate
1599 ) -> dict[str, Any]:
1600 """Partially update an existing tournament match (admin only).
1602 Only the fields set on ``match`` are sent (``exclude_none``), so scores
1603 and status can be filled in as results come in without disturbing the
1604 rest of the match. Returns the updated match row.
1605 """
1606 response = self._request(
1607 "PUT",
1608 f"/api/admin/tournaments/{tournament_id}/matches/{match_id}",
1609 json_data=match.model_dump(exclude_none=True),
1610 )
1611 return response.json()
1613 def delete_tournament_match(self, tournament_id: int, match_id: int) -> dict[str, Any]:
1614 """Delete a match from a tournament (admin only).
1616 The endpoint returns 204 No Content, so there's no JSON body to parse.
1617 """
1618 response = self._request(
1619 "DELETE",
1620 f"/api/admin/tournaments/{tournament_id}/matches/{match_id}",
1621 )
1622 if response.status_code == 204 or not response.content:
1623 return {"deleted": True, "match_id": match_id}
1624 return response.json()
1626 # Tournament Match of the Day (SB-1559)
1628 def get_motw(self, week_start: str | None = None) -> dict[str, Any]:
1629 """The Match of the Week for the week containing ``week_start`` (default this week)."""
1630 params = {"week_start": week_start} if week_start else None
1631 return self._request("GET", "/api/motw", params=params).json()
1633 def get_motw_candidates(self, week: str | None = None, limit: int = 5) -> dict[str, Any]:
1634 """Ranked Match of the Week candidates for a week (admin, SB-1551)."""
1635 params: dict[str, Any] = {"limit": limit}
1636 if week:
1637 params["week"] = week
1638 return self._request("GET", "/api/admin/motw/candidates", params=params).json()
1640 def get_leaderboards(
1641 self, age_group: str, league: str = "Homegrown", season: str | None = None, limit: int = 20
1642 ) -> dict[str, Any]:
1643 """Cross-conference stat boards for a league and age group (SB-1781)."""
1644 params: dict[str, Any] = {"age_group": age_group, "league": league, "limit": limit}
1645 if season:
1646 params["season"] = season
1647 return self._request("GET", "/api/leaderboards", params=params).json()
1649 def get_power_rating(
1650 self,
1651 age_group: str,
1652 league: str = "Homegrown",
1653 season: str | None = None,
1654 view: str | None = None,
1655 conference: str | None = None,
1656 ) -> dict[str, Any]:
1657 """The MT Power Rating for a league and age group, from its latest run (SB-1808)."""
1658 params: dict[str, Any] = {"age_group": age_group, "league": league}
1659 for key, value in (("season", season), ("view", view), ("conference", conference)):
1660 if value:
1661 params[key] = value
1662 return self._request("GET", "/api/rankings", params=params).json()
1664 def get_power_rating_team(
1665 self, team_id: int, age_group: str, league: str = "Homegrown", season: str | None = None
1666 ) -> dict[str, Any]:
1667 """One team in the latest Power Rating run: why it moved (SB-1808)."""
1668 params: dict[str, Any] = {"age_group": age_group, "league": league}
1669 if season:
1670 params["season"] = season
1671 return self._request("GET", f"/api/rankings/teams/{team_id}", params=params).json()
1673 def get_team_dossier(
1674 self, team_id: int, age_group_id: int | None = None, for_match_id: int | None = None
1675 ) -> dict[str, Any]:
1676 """One team at one age group, inside its own conference tables (SB-1780)."""
1677 params: dict[str, Any] = {}
1678 if age_group_id is not None:
1679 params["age_group_id"] = age_group_id
1680 if for_match_id is not None:
1681 params["for_match_id"] = for_match_id
1682 return self._request("GET", f"/api/teams/{team_id}/dossier", params=params or None).json()
1684 def get_matchup(self, match_id: int) -> dict[str, Any]:
1685 """Both teams of one match, each inside its own conference tables (SB-1782)."""
1686 return self._request("GET", f"/api/matches/{match_id}/matchup").json()
1688 def get_tournament_motd(
1689 self, tournament_id: int, date: str | None = None, age_group_id: int | None = None
1690 ) -> dict[str, Any]:
1691 """One day's pick (``motd``, null when unpicked) or, without ``date``, every pick (``picks``).
1693 ``age_group_id`` names the slot: that age group's pick for the day, or
1694 only its picks in the list.
1695 """
1696 params: dict[str, Any] = {}
1697 if date:
1698 params["date"] = date
1699 if age_group_id is not None:
1700 params["age_group_id"] = age_group_id
1701 return self._request("GET", f"/api/tournaments/{tournament_id}/motd", params=params or None).json()
1703 def set_tournament_motd(
1704 self,
1705 tournament_id: int,
1706 match_id: int,
1707 *,
1708 match_date: str | None = None,
1709 age_group_id: int | None = None,
1710 blurb: str | None = None,
1711 reasons: list[dict[str, Any]] | None = None,
1712 ) -> dict[str, Any]:
1713 """Feature a match for its tournament day and age group (admin). ``reasons`` None = not provided."""
1714 body: dict[str, Any] = {"match_id": match_id}
1715 if match_date:
1716 body["match_date"] = match_date
1717 if age_group_id is not None:
1718 body["age_group_id"] = age_group_id
1719 if blurb is not None:
1720 body["blurb"] = blurb
1721 if reasons is not None:
1722 body["reasons"] = reasons
1723 return self._request("POST", f"/api/admin/tournaments/{tournament_id}/motd", json_data=body).json()
1725 def clear_tournament_motd(
1726 self, tournament_id: int, match_date: str, age_group_id: int | None = None
1727 ) -> dict[str, Any]:
1728 """Unpick a tournament day, or one age group's pick for it (admin). Idempotent."""
1729 params = {"age_group_id": age_group_id} if age_group_id is not None else None
1730 return self._request(
1731 "DELETE", f"/api/admin/tournaments/{tournament_id}/motd/{match_date}", params=params
1732 ).json()
1734 # Ingest failures
1736 def get_ingest_failures(
1737 self, since: str | None = None, limit: int = 200, kind: str | None = None
1738 ) -> dict[str, Any]:
1739 """Names the match ingest could not resolve (admin or service account).
1741 `kind` (comma-separated) returns only those kinds — the conflict kinds
1742 (SB-1787) are left out unless named.
1743 """
1744 params: dict[str, Any] = {"limit": limit}
1745 if since: 1745 ↛ 1746line 1745 didn't jump to line 1746 because the condition on line 1745 was never true
1746 params["since"] = since
1747 if kind: 1747 ↛ 1748line 1747 didn't jump to line 1748 because the condition on line 1747 was never true
1748 params["kind"] = kind
1749 response = self._request("GET", "/api/admin/ingest-failures", params=params)
1750 return response.json()
1752 def resolve_ingest_failure(self, failure_id: int, note: str | None = None) -> dict[str, Any]:
1753 """Close one ingest failure by hand, recording why (admin only)."""
1754 response = self._request(
1755 "PATCH",
1756 f"/api/admin/ingest-failures/{failure_id}",
1757 json_data={"note": note},
1758 )
1759 return response.json()
1761 def get_agent_season_matches(
1762 self,
1763 season_id: int,
1764 start_date: str | None = None,
1765 end_date: str | None = None,
1766 league_ids: list[int] | None = None,
1767 page: int = 0,
1768 page_size: int | None = None,
1769 ) -> dict[str, Any]:
1770 """One page of a season's matches for the reconcile (service account). Stop at an empty page."""
1771 params: dict[str, Any] = {"season_id": season_id, "page": page}
1772 if start_date:
1773 params["start_date"] = start_date
1774 if end_date:
1775 params["end_date"] = end_date
1776 if league_ids:
1777 params["league_ids"] = ",".join(str(i) for i in league_ids)
1778 if page_size:
1779 params["page_size"] = page_size
1780 response = self._request("GET", "/api/agent/season-matches", params=params)
1781 return response.json()
1783 # A plan reads every team once and an apply re-checks and writes each
1784 # action; both outlast the default timeout on a large event.
1785 INGEST_PLAN_TIMEOUT = 180.0
1787 def plan_ingest(self, teams: list[dict[str, Any]], brackets: list[dict[str, Any]] | None = None) -> dict[str, Any]:
1788 """What a tournament's team names resolve to, and proposed fixes. Read-only (admin only)."""
1789 response = self._request(
1790 "POST",
1791 "/api/admin/ingest-plan",
1792 json_data={"teams": teams, "brackets": brackets},
1793 timeout=self.INGEST_PLAN_TIMEOUT,
1794 )
1795 return response.json()
1797 def apply_ingest_plan(
1798 self,
1799 plan_id: str,
1800 actions: list[dict[str, Any]],
1801 database: str | None,
1802 dry_run: bool = False,
1803 ) -> dict[str, Any]:
1804 """Ensure the approved actions of a reviewed ingest plan (admin only).
1806 `database` is the fingerprint from the plan; the server refuses a plan
1807 made against another database, or one that does not say.
1808 """
1809 response = self._request(
1810 "POST",
1811 "/api/admin/ingest-plan/apply",
1812 json_data={"plan_id": plan_id, "database": database, "actions": actions, "dry_run": dry_run},
1813 timeout=self.INGEST_PLAN_TIMEOUT,
1814 )
1815 return response.json()
1817 # MT AI gaps
1819 def get_ai_gaps(self, days: int = 30, tool: str | None = None) -> dict[str, Any]:
1820 """What MT AI could not answer: not_found and ambiguous tool calls, grouped (admin only)."""
1821 params: dict[str, Any] = {"days": days}
1822 if tool:
1823 params["tool"] = tool
1824 response = self._request("GET", "/api/admin/ai/gaps", params=params)
1825 return response.json()
1827 # Competition coverage
1829 def get_competition_coverage(self, season_id: int | None = None) -> dict[str, Any]:
1830 """Which conferences MT is actually receiving fixtures for (admin only)."""
1831 params: dict[str, Any] = {}
1832 if season_id:
1833 params["season_id"] = season_id
1834 response = self._request("GET", "/api/admin/coverage", params=params)
1835 return response.json()
1837 # Cache management
1839 def get_cache_stats(self) -> dict[str, Any]:
1840 """Get cache statistics and keys grouped by type (admin only)."""
1841 response = self._request("GET", "/api/admin/cache")
1842 return response.json()
1844 def clear_all_cache(self) -> dict[str, Any]:
1845 """Clear all DAO cache entries (admin only)."""
1846 response = self._request("DELETE", "/api/admin/cache")
1847 return response.json()
1849 def clear_cache_by_type(self, cache_type: str) -> dict[str, Any]:
1850 """Clear cache entries for a specific type (admin only)."""
1851 response = self._request("DELETE", f"/api/admin/cache/{cache_type}")
1852 return response.json()
1854 # Version
1856 def get_version(self) -> dict[str, Any]:
1857 """Get API version information."""
1858 response = self._request("GET", "/api/version")
1859 return response.json()