Files
RosterChief/teams/api.py
Bernard Siebens 98b8002a04 Add billing-ending banner, events CRUD, RBIHF import, public API, team photos, and sponsors
A large batch of club-management features built up over one session:

- Club dashboard banner warning admins 1 month before billing ends
- Full Events/EventSeries CRUD (recurrence builder, occurrence lifecycle,
  per-team permissions), with match->game rename and game-specific fields
  (score, competition, live status, external game ID)
- Django-admin competition dropdown, gated per-club by feature flag
- Auto-import of RBIHF fixtures (scrape -> diff -> preview -> confirm),
  with location/opponent dropdowns suggested from existing club data
- Feature-flag-gated Shop/Forms nav sections, reusing the same flag
  machinery for the RBIHF import button
- Team roster now scoped to members active this season or next, sorted and
  grouped by position
- Club sport type (ice hockey / other), shown in the control panel's club
  subtitle
- Per-season team photo upload from the team page
- New public read-only API (Django Ninja) at /api/v1/: news, team rosters,
  upcoming/live/per-team games, and sponsors -- auto-documented via Swagger
  UI, CORS-enabled for a club's own external website
- Club sponsors: admin-only CRUD (logo, URL, active date window) plus a
  date-windowed, optionally randomized API endpoint
- Assorted fixes: NullBooleanField dropdown rendering, cross-club event
  validation timing, searchable-select chip placement, btn-neutral ->
  default button style sweep, calendar-month chart windows

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R1gj3J1QPfP38XWpnpbFpy
2026-08-06 17:36:04 +02:00

123 lines
4.2 KiB
Python

"""Public read-only team/roster endpoints -- see api/urls.py for how this is
mounted. Roster building is a small helper (build_roster) rather than
inlined in the view so it can be unit-tested without going through Ninja's
request cycle.
"""
import uuid
from itertools import groupby
from ninja import Router, Schema
from ninja.errors import HttpError
from api.errors import require_club
from club.services.access import current_season
from .models import Team, TeamMembership, TeamPhoto
router = Router(tags=["teams"])
class TeamOut(Schema):
id: uuid.UUID
name: str
short_name: str
photo_url: str | None
class PlayerOut(Schema):
id: uuid.UUID
first_name: str
last_name: str
jersey_number: int | None
is_captain: bool
is_alternate_captain: bool
class PositionGroupOut(Schema):
position: str
players: list[PlayerOut]
class StaffMemberOut(Schema):
id: uuid.UUID
first_name: str
last_name: str
position: str
class RosterOut(Schema):
team: TeamOut
season: str | None
players: list[PositionGroupOut]
staff: list[StaffMemberOut]
def _to_team_out(team, request, photo=None) -> TeamOut:
photo_url = request.build_absolute_uri(photo.image.url) if photo else None
return TeamOut(id=team.pk, name=team.name, short_name=team.short_name, photo_url=photo_url)
def _to_player_out(membership) -> PlayerOut:
return PlayerOut(
id=membership.member_id,
first_name=membership.member.first_name,
last_name=membership.member.last_name,
jersey_number=membership.jersey_number,
is_captain=membership.is_captain,
is_alternate_captain=membership.is_alternate_captain,
)
def build_roster(team, request) -> RosterOut:
"""Current season's players -- grouped by position (so a consumer can pull
just e.g. "Forward" without filtering a flat list itself), each group
sorted by jersey number, groups themselves in Position.ordering order --
and staff, for `team`. No current season -> empty roster, same "nothing
to show, not an error" handling as management.views.MembershipListView."""
season = current_season(team.club)
if season is None:
return RosterOut(team=_to_team_out(team, request), season=None, players=[], staff=[])
photo = TeamPhoto.objects.filter(team=team, season=season).first()
memberships = TeamMembership.objects.filter(team=team, season=season).select_related("member", "position").order_by("position__ordering", "position__name", "jersey_number")
assignments = team.staff_assignments.filter(season=season).select_related("member", "position").order_by("position__ordering", "position__name", "member__last_name")
# groupby only groups consecutive runs -- relies on the queryset already
# being ordered by position first, which it is.
players = [PositionGroupOut(position=position_name, players=[_to_player_out(m) for m in members]) for position_name, members in groupby(memberships, key=lambda m: m.position.name)]
staff = [
StaffMemberOut(id=assignment.member_id, first_name=assignment.member.first_name, last_name=assignment.member.last_name, position=assignment.position.name)
for assignment in assignments
]
return RosterOut(team=_to_team_out(team, request, photo=photo), season=season.name, players=players, staff=staff)
@router.get("/", response=list[TeamOut], summary="List teams")
def list_teams(request):
club = require_club(request)
teams = list(Team.objects.filter(club=club).order_by("name"))
season = current_season(club)
photos_by_team_id = {}
if season is not None and teams:
photos_by_team_id = {photo.team_id: photo for photo in TeamPhoto.objects.filter(team__in=teams, season=season)}
return [_to_team_out(team, request, photo=photos_by_team_id.get(team.pk)) for team in teams]
@router.get("/{team_id}/roster/", response=RosterOut, summary="Current season's roster")
def get_roster(request, team_id: uuid.UUID):
club = require_club(request)
team = _get_team_or_404(club, team_id)
return build_roster(team, request)
def _get_team_or_404(club, team_id):
team = Team.objects.filter(club=club, pk=team_id).first()
if team is None:
raise HttpError(404, "No such team.")
return team