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
This commit is contained in:
2026-08-06 17:36:04 +02:00
parent 6ad0d6658c
commit 98b8002a04
101 changed files with 6165 additions and 135 deletions

View File

@@ -1,7 +1,7 @@
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from .models import Position, StaffAssignment, Team, TeamMembership
from .models import Position, StaffAssignment, Team, TeamMembership, TeamPhoto
class TeamMembershipInline(admin.TabularInline):
@@ -20,12 +20,26 @@ class StaffAssignmentInline(admin.TabularInline):
raw_id_fields = ("member",)
class TeamPhotoInline(admin.TabularInline):
"""One photo per season, shown on the Team page."""
model = TeamPhoto
extra = 0
@admin.register(Team)
class TeamAdmin(admin.ModelAdmin):
list_display = ["name", "short_name", "club"]
list_filter = ["club"]
search_fields = ["name", "short_name"]
inlines = [TeamMembershipInline, StaffAssignmentInline]
inlines = [TeamMembershipInline, StaffAssignmentInline, TeamPhotoInline]
@admin.register(TeamPhoto)
class TeamPhotoAdmin(admin.ModelAdmin):
list_display = ["team", "season"]
list_filter = ["team__club", "season"]
search_fields = ["team__name"]
@admin.register(Position)

122
teams/api.py Normal file
View File

@@ -0,0 +1,122 @@
"""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

View File

@@ -0,0 +1,33 @@
# Generated by Django 6.0.6 on 2026-08-06 13:56
import django.db.models.deletion
import teams.models
import uuid
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('club', '0018_club_sport_type'),
('teams', '0006_alter_position_ordering'),
]
operations = [
migrations.CreateModel(
name='TeamPhoto',
fields=[
('created', models.DateTimeField(auto_now_add=True, verbose_name='created')),
('modified', models.DateTimeField(auto_now=True, verbose_name='modified')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('image', models.ImageField(upload_to=teams.models.team_photo_path, verbose_name='image')),
('season', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='team_photos', to='club.season', verbose_name='season')),
('team', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='photos', to='teams.team', verbose_name='team')),
],
options={
'verbose_name': 'team photo',
'verbose_name_plural': 'team photos',
'constraints': [models.UniqueConstraint(fields=('team', 'season'), name='unique_team_photo_per_season')],
},
),
]

View File

@@ -22,6 +22,31 @@ class Team(ClubScopedModel):
return self.name
def team_photo_path(instance, filename):
return f"clubs/{instance.team.club.slug}/teams/{instance.team_id}/{instance.season.name}/{filename}"
class TeamPhoto(UUIDModel):
"""One team photo per season -- a team's makeup changes every season, so
this can't be a plain field on Team. No club FK of its own: club is
already reachable via team.club, same reasoning as NewsPhoto being owned
by News rather than club-scoped itself."""
team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="photos", verbose_name=_("team"))
season = models.ForeignKey(Season, on_delete=models.PROTECT, related_name="team_photos", verbose_name=_("season"))
image = models.ImageField(_("image"), upload_to=team_photo_path)
class Meta:
verbose_name = _("team photo")
verbose_name_plural = _("team photos")
constraints = [
models.UniqueConstraint(fields=["team", "season"], name="unique_team_photo_per_season"),
]
def __str__(self):
return f"{self.team} - {self.season}"
class Position(ClubScopedModel):
name = models.CharField(_("name"), max_length=255)
short_name = models.CharField(_("short name"), max_length=255)

View File

@@ -8,7 +8,7 @@ from django.test import TestCase
from club.models import Club, Season
from members.models import Member
from .models import Position, StaffAssignment, Team, TeamMembership
from .models import Position, StaffAssignment, Team, TeamMembership, TeamPhoto
class TeamsTestCase(TestCase):
@@ -153,3 +153,38 @@ class RosterCleanTests(TeamsTestCase):
def test_staffassignment_accepts_same_club(self):
StaffAssignment(team=self.team, member=self.member, season=self.season, position=self.coach).full_clean()
class TeamPhotoModelTests(TeamsTestCase):
def test_can_set_a_photo(self):
photo = TeamPhoto.objects.create(team=self.team, season=self.season, image="clubs/ajax-united/teams/x/26-27/pic.jpg")
self.assertEqual(str(photo), "First Team - 26-27")
self.assertEqual(list(self.team.photos.all()), [photo])
def test_only_one_photo_per_team_and_season(self):
TeamPhoto.objects.create(team=self.team, season=self.season, image="clubs/ajax-united/teams/x/26-27/pic.jpg")
with self.assertRaises(IntegrityError):
TeamPhoto.objects.create(team=self.team, season=self.season, image="clubs/ajax-united/teams/x/26-27/pic2.jpg")
def test_the_same_team_can_have_a_photo_in_a_different_season(self):
other_season = Season.objects.create(club=self.club, start_date=datetime.date(2000, 1, 1), end_date=datetime.date(2000, 12, 31))
TeamPhoto.objects.create(team=self.team, season=self.season, image="clubs/ajax-united/teams/x/26-27/pic.jpg")
TeamPhoto.objects.create(team=self.team, season=other_season, image="clubs/ajax-united/teams/x/00-00/pic.jpg")
self.assertEqual(self.team.photos.count(), 2)
def test_season_is_protected_while_a_photo_references_it(self):
TeamPhoto.objects.create(team=self.team, season=self.season, image="clubs/ajax-united/teams/x/26-27/pic.jpg")
with self.assertRaises(ProtectedError):
self.season.delete()
def test_deleting_the_team_deletes_its_photos(self):
TeamPhoto.objects.create(team=self.team, season=self.season, image="clubs/ajax-united/teams/x/26-27/pic.jpg")
self.team.delete()
self.assertEqual(TeamPhoto.objects.count(), 0)