from django.shortcuts import render from django.contrib.auth.decorators import login_required from calendars.models import Event, EventParticipation from clubs.models import Team from django.utils import timezone @login_required def dashboard(request): user = request.user events_with_participation = [] children_events = [] # Get user's own events player_teams = [] if hasattr(user, 'team') and user.team: player_teams = [user.team] coached_teams = user.coached_teams.all() assisted_teams = user.assisted_teams.all() from itertools import chain all_teams = list(set(chain(player_teams, coached_teams, assisted_teams))) if all_teams: user_events = Event.objects.filter(team__in=all_teams) opened_games = Event.objects.filter(game__opened_for_teams__in=all_teams) events = (user_events | opened_games).distinct().select_related('game', 'training').prefetch_related('team__players', 'eventparticipation_set__user').order_by('start_time') for event in events: participations = event.eventparticipation_set.all() accepted_count = sum(1 for p in participations if p.status == 'attending') required_players = event.game.min_players if hasattr(event, 'game') else 0 player_participations = [] team_players = event.team.players.all() participation_map = {p.user_id: p.status for p in participations} for player in team_players: status = participation_map.get(player.id, 'maybe') player_participations.append({'player': player, 'status': status}) days_until_event = (event.start_time - timezone.now()).days events_with_participation.append({ 'event': event, 'accepted_count': accepted_count, 'required_players': required_players, 'player_participations': player_participations, 'days_until_event': days_until_event }) # Get children's events if hasattr(user, 'children'): for child in user.children.all(): child_events_list = [] if child.team: child_user_events = Event.objects.filter(team=child.team) child_opened_games = Event.objects.filter(game__opened_for_teams=child.team) child_events = (child_user_events | child_opened_games).distinct().select_related('game', 'training').order_by('start_time') for event in child_events: participation, created = EventParticipation.objects.get_or_create(user=child, event=event) child_events_list.append({'event': event, 'participation': participation}) children_events.append({'child': child, 'events': child_events_list}) context = { 'events_with_participation': events_with_participation, 'children_events': children_events, 'now': timezone.now() } return render(request, 'dashboard/dashboard.html', context)