Compare commits
7
Commits
4a2e2f053f
..
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e5903b131 | ||
|
|
bd9ed4bdc7 | ||
|
|
a9b33b30f5 | ||
|
|
32c112ceea | ||
|
|
30069d782f | ||
|
|
d994d88c12 | ||
|
|
b9791d1547 |
+22
-1
@@ -686,6 +686,7 @@ class TeamTryoutsBot(commands.Bot):
|
|||||||
event_date: str,
|
event_date: str,
|
||||||
event_time: str,
|
event_time: str,
|
||||||
reference_id: int,
|
reference_id: int,
|
||||||
|
change_kind: str = 'scheduled',
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Send a schedule addition notification to a player.
|
"""Send a schedule addition notification to a player.
|
||||||
|
|
||||||
@@ -696,6 +697,7 @@ class TeamTryoutsBot(commands.Bot):
|
|||||||
event_date: Date string.
|
event_date: Date string.
|
||||||
event_time: Time string.
|
event_time: Time string.
|
||||||
reference_id: ID of the MatchParticipant or TryoutRegistration record.
|
reference_id: ID of the MatchParticipant or TryoutRegistration record.
|
||||||
|
change_kind: 'scheduled' (new match / added player) or 'modified' (date/time changed).
|
||||||
"""
|
"""
|
||||||
# Look up the DB user to get their Discord user ID
|
# Look up the DB user to get their Discord user ID
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
@@ -712,6 +714,19 @@ class TeamTryoutsBot(commands.Bot):
|
|||||||
|
|
||||||
event_name = "Match" if event_type == 'match' else "Tryout"
|
event_name = "Match" if event_type == 'match' else "Tryout"
|
||||||
|
|
||||||
|
if change_kind == 'modified':
|
||||||
|
message = (
|
||||||
|
f"📅 **{event_name} Modified**\n\n"
|
||||||
|
f"The {event_type} date and/or time has been modified for "
|
||||||
|
f"**{event_title}**.\n"
|
||||||
|
f"The new date and/or time is:\n"
|
||||||
|
f"**Date:** {event_date}\n"
|
||||||
|
f"**Time:** {event_time}\n\n"
|
||||||
|
"Please confirm your attendance:\n"
|
||||||
|
f"{CHECK_EMOJI} - Confirm attendance\n"
|
||||||
|
f"{CROSS_EMOJI} - Decline"
|
||||||
|
)
|
||||||
|
else:
|
||||||
message = (
|
message = (
|
||||||
f"📅 **{event_name} Scheduled**\n\n"
|
f"📅 **{event_name} Scheduled**\n\n"
|
||||||
f"You have been added to the following {event_type}:\n"
|
f"You have been added to the following {event_type}:\n"
|
||||||
@@ -1444,8 +1459,13 @@ def send_schedule_notification(
|
|||||||
event_date: str,
|
event_date: str,
|
||||||
event_time: str,
|
event_time: str,
|
||||||
reference_id: int,
|
reference_id: int,
|
||||||
|
change_kind: str = 'scheduled',
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""Queue a schedule addition notification to be sent by the bot."""
|
"""Queue a schedule addition notification to be sent by the bot.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
change_kind: 'scheduled' (new match / added player) or 'modified' (date/time changed).
|
||||||
|
"""
|
||||||
return _enqueue(
|
return _enqueue(
|
||||||
'schedule_addition',
|
'schedule_addition',
|
||||||
{
|
{
|
||||||
@@ -1455,6 +1475,7 @@ def send_schedule_notification(
|
|||||||
'event_date': event_date,
|
'event_date': event_date,
|
||||||
'event_time': event_time,
|
'event_time': event_time,
|
||||||
'reference_id': reference_id,
|
'reference_id': reference_id,
|
||||||
|
'change_kind': change_kind,
|
||||||
},
|
},
|
||||||
description=f'the {event_type} notification for user {user_id}',
|
description=f'the {event_type} notification for user {user_id}',
|
||||||
)
|
)
|
||||||
|
|||||||
+18
-4
@@ -324,8 +324,9 @@ def _create_database():
|
|||||||
def _stop(*_args):
|
def _stop(*_args):
|
||||||
"""Stop the PostgreSQL server with a fast shutdown.
|
"""Stop the PostgreSQL server with a fast shutdown.
|
||||||
|
|
||||||
Registered as ``atexit`` and signal handler so it fires on Ctrl+C,
|
Registered as an ``atexit`` handler so it fires on normal exit. Signal
|
||||||
normal exit, and terminal close.
|
handling goes through ``_handle_stop_signal``, which also stops the
|
||||||
|
server but then re-raises so the process actually exits.
|
||||||
"""
|
"""
|
||||||
global _started
|
global _started
|
||||||
global _stopped_system_service_name
|
global _stopped_system_service_name
|
||||||
@@ -349,6 +350,19 @@ def _stop(*_args):
|
|||||||
_start_system_service(srv)
|
_start_system_service(srv)
|
||||||
|
|
||||||
|
|
||||||
|
def _handle_stop_signal(signum, frame):
|
||||||
|
"""Stop PostgreSQL, then let the interpreter shut down normally.
|
||||||
|
|
||||||
|
``_stop`` alone would swallow Ctrl+C: it stops the server and restores the
|
||||||
|
system service, then returns without exiting, leaving the dev server
|
||||||
|
running against a stopped database and the terminal frozen. Re-raising
|
||||||
|
``KeyboardInterrupt`` hands control back to the framework, which exits;
|
||||||
|
the ``atexit`` registration then runs ``_stop`` again (idempotent).
|
||||||
|
"""
|
||||||
|
_stop()
|
||||||
|
raise KeyboardInterrupt
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Public API
|
# Public API
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -420,9 +434,9 @@ def start() -> str:
|
|||||||
_started = True
|
_started = True
|
||||||
atexit.register(_stop)
|
atexit.register(_stop)
|
||||||
with contextlib.suppress(ValueError, OSError):
|
with contextlib.suppress(ValueError, OSError):
|
||||||
signal.signal(signal.SIGINT, _stop)
|
signal.signal(signal.SIGINT, _handle_stop_signal)
|
||||||
with contextlib.suppress(AttributeError, ValueError, OSError):
|
with contextlib.suppress(AttributeError, ValueError, OSError):
|
||||||
signal.signal(signal.SIGBREAK, _stop) # type: ignore[attr-defined]
|
signal.signal(signal.SIGBREAK, _handle_stop_signal) # type: ignore[attr-defined]
|
||||||
|
|
||||||
logger.info('Local PostgreSQL ready — DATABASE_URL=%s', DATABASE_URL)
|
logger.info('Local PostgreSQL ready — DATABASE_URL=%s', DATABASE_URL)
|
||||||
return DATABASE_URL
|
return DATABASE_URL
|
||||||
|
|||||||
@@ -61,7 +61,14 @@ class OrgTeam(db.Model):
|
|||||||
return [tp.player for tp in self.team_players]
|
return [tp.player for tp in self.team_players]
|
||||||
|
|
||||||
def get_players_with_status(self):
|
def get_players_with_status(self):
|
||||||
return [
|
rows = [
|
||||||
{'player': tp.player, 'status': tp.status, 'position': tp.position}
|
{
|
||||||
|
'player': tp.player,
|
||||||
|
'status': tp.status,
|
||||||
|
'position': tp.position,
|
||||||
|
'is_team_representative': tp.is_team_representative,
|
||||||
|
}
|
||||||
for tp in self.team_players
|
for tp in self.team_players
|
||||||
]
|
]
|
||||||
|
# The responsible heads the roster; everyone else keeps roster order.
|
||||||
|
return sorted(rows, key=lambda row: not row['is_team_representative'])
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ class TeamPlayer(db.Model):
|
|||||||
player_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
|
player_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
|
||||||
org_team_id = db.Column(db.Integer, db.ForeignKey('org_teams.id'), nullable=False)
|
org_team_id = db.Column(db.Integer, db.ForeignKey('org_teams.id'), nullable=False)
|
||||||
status = db.Column(db.String(20), nullable=False, default='starter')
|
status = db.Column(db.String(20), nullable=False, default='starter')
|
||||||
|
#: A player an admin named as their team's responsible ("joueur
|
||||||
|
#: responsable") — see app/permissions.py. Grants match-management
|
||||||
|
#: rights for that one team and nothing else.
|
||||||
|
is_team_representative = db.Column(db.Boolean, nullable=False, default=False)
|
||||||
position = db.Column(db.String(50), nullable=True)
|
position = db.Column(db.String(50), nullable=True)
|
||||||
added_at = db.Column(db.DateTime, default=utc_now_naive)
|
added_at = db.Column(db.DateTime, default=utc_now_naive)
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ class Admin(User):
|
|||||||
def can_manage_this_org_team(self, org_team):
|
def can_manage_this_org_team(self, org_team):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def can_designate_team_representative(self):
|
||||||
|
return True
|
||||||
|
|
||||||
def get_visible_tryouts(self):
|
def get_visible_tryouts(self):
|
||||||
from app.models.tryout.tryout import Tryout
|
from app.models.tryout.tryout import Tryout
|
||||||
|
|
||||||
|
|||||||
@@ -103,5 +103,20 @@ class User(UserMixin, db.Model):
|
|||||||
def can_manage_this_org_team(self, org_team):
|
def can_manage_this_org_team(self, org_team):
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def can_manage_team_matches(self, org_team):
|
||||||
|
"""Whether the user may manage this team's matches and practices.
|
||||||
|
|
||||||
|
Broader than :meth:`can_manage_this_org_team`: a player named as the
|
||||||
|
team's responsible joins whoever administers it. The rule itself
|
||||||
|
lives in ``app.permissions``.
|
||||||
|
"""
|
||||||
|
from app.permissions import can_manage_team_matches
|
||||||
|
|
||||||
|
return can_manage_team_matches(self, org_team)
|
||||||
|
|
||||||
|
def can_designate_team_representative(self):
|
||||||
|
"""Whether the user may name a team's responsible. President only."""
|
||||||
|
return False
|
||||||
|
|
||||||
def get_visible_tryouts(self):
|
def get_visible_tryouts(self):
|
||||||
return []
|
return []
|
||||||
|
|||||||
@@ -158,6 +158,78 @@ def can_manage_org_team(user, org_team):
|
|||||||
return bool(org_team) and user.can_manage_this_org_team(org_team)
|
return bool(org_team) and user.can_manage_this_org_team(org_team)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Team representatives ("joueurs responsables")
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def is_team_representative(user, org_team):
|
||||||
|
"""Whether the user is the named responsible of this organisation team.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
user: The acting user.
|
||||||
|
org_team: The team concerned.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool
|
||||||
|
"""
|
||||||
|
if not user or not org_team:
|
||||||
|
return False
|
||||||
|
|
||||||
|
from app.models import TeamPlayer
|
||||||
|
|
||||||
|
return (
|
||||||
|
TeamPlayer.query.filter_by(
|
||||||
|
player_id=user.id,
|
||||||
|
org_team_id=org_team.id,
|
||||||
|
is_team_representative=True,
|
||||||
|
).first()
|
||||||
|
is not None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def representative_org_teams(user):
|
||||||
|
"""Organisation teams the user is the responsible of, ordered by name.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
user: The acting user.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list[OrgTeam]: Possibly empty.
|
||||||
|
"""
|
||||||
|
from app.models import OrgTeam, TeamPlayer
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return []
|
||||||
|
return (
|
||||||
|
OrgTeam.query.join(TeamPlayer, TeamPlayer.org_team_id == OrgTeam.id)
|
||||||
|
.filter(
|
||||||
|
TeamPlayer.player_id == user.id,
|
||||||
|
TeamPlayer.is_team_representative.is_(True),
|
||||||
|
)
|
||||||
|
.order_by(OrgTeam.name)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def can_manage_team_matches(user, org_team):
|
||||||
|
"""Whether the user may manage this team's matches and practices.
|
||||||
|
|
||||||
|
The staff rule (see :func:`can_manage_org_team`) *plus* the player named
|
||||||
|
as the team's responsible. Deliberately narrower than
|
||||||
|
``can_manage_org_team``: a responsible schedules and edits matches, but
|
||||||
|
does not administer the roster.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
user: The acting user.
|
||||||
|
org_team: The team concerned.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool
|
||||||
|
"""
|
||||||
|
return can_manage_org_team(user, org_team) or is_team_representative(user, org_team)
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Reach over players
|
# Reach over players
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
+269
-61
@@ -3,11 +3,13 @@
|
|||||||
Uses polymorphic isinstance checks instead of role-string comparisons.
|
Uses polymorphic isinstance checks instead of role-string comparisons.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import math
|
||||||
|
|
||||||
from flask import Blueprint, flash, redirect, render_template, request, url_for
|
from flask import Blueprint, flash, redirect, render_template, request, url_for
|
||||||
from flask_babel import gettext as _
|
from flask_babel import gettext as _
|
||||||
from flask_login import current_user, login_required
|
from flask_login import current_user, login_required
|
||||||
from marshmallow import ValidationError
|
from marshmallow import ValidationError
|
||||||
from sqlalchemy import func
|
from sqlalchemy import false, func, select
|
||||||
from sqlalchemy.orm import aliased
|
from sqlalchemy.orm import aliased
|
||||||
|
|
||||||
from app.extensions import db
|
from app.extensions import db
|
||||||
@@ -16,14 +18,18 @@ from app.models import (
|
|||||||
EVALUATION_CRITERIA,
|
EVALUATION_CRITERIA,
|
||||||
GAME_POSITIONS,
|
GAME_POSITIONS,
|
||||||
Admin,
|
Admin,
|
||||||
|
Coach,
|
||||||
Evaluation,
|
Evaluation,
|
||||||
|
Manager,
|
||||||
Player,
|
Player,
|
||||||
|
Scout,
|
||||||
Tryout,
|
Tryout,
|
||||||
TryoutRegistration,
|
TryoutRegistration,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
from app.pagination import paginate
|
from app.pagination import DEFAULT_PER_PAGE, MAX_PER_PAGE
|
||||||
from app.responders import respond_after_change
|
from app.responders import respond_after_change
|
||||||
|
from app.time_utils import utc_now_naive
|
||||||
from app.validators import EvaluationSchema
|
from app.validators import EvaluationSchema
|
||||||
|
|
||||||
evaluations_bp = Blueprint('evaluations', __name__, url_prefix='/evaluations')
|
evaluations_bp = Blueprint('evaluations', __name__, url_prefix='/evaluations')
|
||||||
@@ -37,95 +43,286 @@ def _users_by_id(user_ids):
|
|||||||
return {user.id: user for user in User.query.filter(User.id.in_(wanted)).all()}
|
return {user.id: user for user in User.query.filter(User.id.in_(wanted)).all()}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_score(score_value):
|
||||||
|
"""Turn a raw form value into a criterion score (1..10), or None.
|
||||||
|
|
||||||
|
A blank value means "not assessed". Anything else outside 1..10 is a
|
||||||
|
validation error, matching the single-player form's ``EvaluationSchema``
|
||||||
|
-- a coach must not be able to quietly turn 11 or 0 into "no score"
|
||||||
|
(QUA-003).
|
||||||
|
"""
|
||||||
|
if score_value is None or str(score_value).strip() == '':
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
score = int(score_value)
|
||||||
|
except (TypeError, ValueError) as exc:
|
||||||
|
raise ValidationError('A score must be a whole number from 1 to 10.') from exc
|
||||||
|
if not 1 <= score <= 10:
|
||||||
|
raise ValidationError('Scores run from 1 to 10.')
|
||||||
|
return score
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_evaluation(evaluation, scores, comments, position):
|
||||||
|
"""Write validated scores, comments and position onto an Evaluation."""
|
||||||
|
evaluation.apply_scores(scores)
|
||||||
|
evaluation.comments = comments
|
||||||
|
evaluation.position_recommendation = position
|
||||||
|
|
||||||
|
|
||||||
|
def _visible_evaluations_query(user):
|
||||||
|
"""Evaluations the acting user is allowed to see, as a query.
|
||||||
|
|
||||||
|
Admins and scouts see everything. Managers and coaches see the
|
||||||
|
evaluations authored by managers and coaches inside the tryouts they
|
||||||
|
manage; players never reach the evaluation pages.
|
||||||
|
"""
|
||||||
|
if isinstance(user, (Admin, Scout)):
|
||||||
|
return Evaluation.query
|
||||||
|
tryout_ids = [t.id for t in user.get_visible_tryouts()]
|
||||||
|
if not tryout_ids:
|
||||||
|
return Evaluation.query.filter(false())
|
||||||
|
evaluator_alias = aliased(User, name='visible_evaluator')
|
||||||
|
return (
|
||||||
|
Evaluation.query
|
||||||
|
.join(evaluator_alias, Evaluation.evaluator_id == evaluator_alias.id)
|
||||||
|
.filter(evaluator_alias.role.in_(['manager', 'coach']))
|
||||||
|
.filter(Evaluation.tryout_id.in_(tryout_ids))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _visible_evaluation_ids(user):
|
||||||
|
"""A ``select`` of the ids of evaluations the acting user may see."""
|
||||||
|
ids = _visible_evaluations_query(user).with_entities(Evaluation.id).subquery()
|
||||||
|
return select(ids.c.id)
|
||||||
|
|
||||||
|
|
||||||
|
def _average(values):
|
||||||
|
"""Mean of the non-None values, rounded to one decimal (or None)."""
|
||||||
|
values = [value for value in values if value is not None]
|
||||||
|
if not values:
|
||||||
|
return None
|
||||||
|
return round(sum(values) / len(values), 1)
|
||||||
|
|
||||||
|
|
||||||
|
def _aggregate(evaluations):
|
||||||
|
"""Per-criterion averages plus a combined overall average."""
|
||||||
|
criterion_averages = [
|
||||||
|
(label, _average([getattr(e, field) for e in evaluations]))
|
||||||
|
for field, label in EVALUATION_CRITERIA
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
'criterion_averages': criterion_averages,
|
||||||
|
'combined_average': _average([e.overall_score for e in evaluations]),
|
||||||
|
'count': len(evaluations),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _evaluation_view(evaluation, evaluator, tryout):
|
||||||
|
"""Shape an Evaluation for the templates (scores in criterion order)."""
|
||||||
|
return {
|
||||||
|
'evaluation': evaluation,
|
||||||
|
'evaluator': evaluator,
|
||||||
|
'tryout': tryout,
|
||||||
|
'scores': [getattr(evaluation, field) for field, _ in EVALUATION_CRITERIA],
|
||||||
|
'overall': evaluation.overall_score,
|
||||||
|
'position': evaluation.position_recommendation,
|
||||||
|
'comment': evaluation.comments,
|
||||||
|
'date': evaluation.created_at,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _players_by_average(user):
|
||||||
|
"""Players with visible evaluations, best combined average first."""
|
||||||
|
visible_ids = _visible_evaluation_ids(user)
|
||||||
|
rows = (
|
||||||
|
db.session.query(
|
||||||
|
Evaluation.player_id,
|
||||||
|
func.avg(Evaluation.overall_score).label('avg_score'),
|
||||||
|
)
|
||||||
|
.filter(Evaluation.id.in_(visible_ids))
|
||||||
|
.group_by(Evaluation.player_id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
players_by_id = _users_by_id(row.player_id for row in rows)
|
||||||
|
ordered = [
|
||||||
|
(players_by_id[row.player_id], row.avg_score)
|
||||||
|
for row in rows
|
||||||
|
if row.player_id in players_by_id and isinstance(players_by_id[row.player_id], Player)
|
||||||
|
]
|
||||||
|
ordered.sort(
|
||||||
|
key=lambda pair: (
|
||||||
|
pair[1] is None,
|
||||||
|
-(pair[1] if pair[1] is not None else 0),
|
||||||
|
pair[0].username.lower(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return ordered
|
||||||
|
|
||||||
|
|
||||||
@evaluations_bp.route('')
|
@evaluations_bp.route('')
|
||||||
@login_required
|
@login_required
|
||||||
def list_evaluations():
|
def list_evaluations():
|
||||||
"""List all evaluations accessible to the current user."""
|
"""List player evaluations grouped by player, with a per-player view."""
|
||||||
user = current_user
|
user = current_user
|
||||||
|
|
||||||
if isinstance(user, Player):
|
if isinstance(user, Player):
|
||||||
flash(_('You do not have permission to view evaluations.'), 'danger')
|
flash(_('You do not have permission to view evaluations.'), 'danger')
|
||||||
return redirect(url_for('main.dashboard'))
|
return redirect(url_for('main.dashboard'))
|
||||||
|
|
||||||
sort_column = request.args.get('sort', 'created_at')
|
sort_column = request.args.get('sort', 'overall_score')
|
||||||
sort_order = request.args.get('order', 'desc')
|
sort_order = request.args.get('order', 'desc')
|
||||||
if sort_order not in ('asc', 'desc'):
|
if sort_order not in ('asc', 'desc'):
|
||||||
sort_order = 'desc'
|
sort_order = 'desc'
|
||||||
|
|
||||||
player_alias = aliased(User, name='eval_player')
|
visible_ids = _visible_evaluation_ids(user)
|
||||||
evaluator_alias = aliased(User, name='eval_evaluator')
|
|
||||||
|
|
||||||
sort_map = {
|
aggregate = (
|
||||||
'tryout': Tryout.title,
|
|
||||||
'player': player_alias.username,
|
|
||||||
'evaluator': evaluator_alias.username,
|
|
||||||
'mecanics_score': Evaluation.mecanics_score,
|
|
||||||
'cohesion_score': Evaluation.cohesion_score,
|
|
||||||
'communication_score': Evaluation.communication_score,
|
|
||||||
'gamesense_score': Evaluation.gamesense_score,
|
|
||||||
'versatility_score': Evaluation.versatility_score,
|
|
||||||
'discipline_score': Evaluation.discipline_score,
|
|
||||||
'analysis_score': Evaluation.analysis_score,
|
|
||||||
'sport_ethics_score': Evaluation.sport_ethics_score,
|
|
||||||
'mental_score': Evaluation.mental_score,
|
|
||||||
'overall_score': Evaluation.overall_score,
|
|
||||||
'position_recommendation': Evaluation.position_recommendation,
|
|
||||||
'created_at': Evaluation.created_at,
|
|
||||||
}
|
|
||||||
|
|
||||||
sort_expr = sort_map.get(sort_column, Evaluation.created_at)
|
|
||||||
if sort_order == 'asc':
|
|
||||||
sort_expr = sort_expr.asc()
|
|
||||||
else:
|
|
||||||
sort_expr = sort_expr.desc()
|
|
||||||
|
|
||||||
if isinstance(user, Admin):
|
|
||||||
evaluations_page = paginate(
|
|
||||||
Evaluation.query.outerjoin(Tryout, Evaluation.tryout_id == Tryout.id)
|
|
||||||
.outerjoin(player_alias, Evaluation.player_id == player_alias.id)
|
|
||||||
.outerjoin(evaluator_alias, Evaluation.evaluator_id == evaluator_alias.id)
|
|
||||||
.order_by(sort_expr, Evaluation.id)
|
|
||||||
)
|
|
||||||
avg_scores = (
|
|
||||||
db.session.query(
|
db.session.query(
|
||||||
Evaluation.player_id,
|
Evaluation.player_id,
|
||||||
func.count(Evaluation.id).label('eval_count'),
|
func.count(Evaluation.id).label('eval_count'),
|
||||||
func.avg(Evaluation.overall_score).label('avg_score'),
|
func.avg(Evaluation.overall_score).label('avg_score'),
|
||||||
|
func.max(Evaluation.created_at).label('last_eval'),
|
||||||
)
|
)
|
||||||
|
.filter(Evaluation.id.in_(visible_ids))
|
||||||
.group_by(Evaluation.player_id)
|
.group_by(Evaluation.player_id)
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
players_by_id = _users_by_id(row.player_id for row in avg_scores)
|
|
||||||
player_scores = {}
|
players_by_id = _users_by_id(row.player_id for row in aggregate)
|
||||||
for row in avg_scores:
|
grouped = []
|
||||||
p = players_by_id.get(row.player_id)
|
for row in aggregate:
|
||||||
if p:
|
player = players_by_id.get(row.player_id)
|
||||||
player_scores[p.id] = {
|
if not player or not isinstance(player, Player):
|
||||||
'player': p,
|
continue
|
||||||
|
grouped.append(
|
||||||
|
{
|
||||||
|
'player': player,
|
||||||
|
'avg': round(row.avg_score, 1) if row.avg_score is not None else None,
|
||||||
'count': row.eval_count,
|
'count': row.eval_count,
|
||||||
'avg': round(row.avg_score, 1) if row.avg_score else 0,
|
'last_eval': row.last_eval,
|
||||||
|
'evaluations': [],
|
||||||
}
|
}
|
||||||
else:
|
|
||||||
# Everyone still here evaluates: players were redirected above, and
|
|
||||||
# can_evaluate() is true for the four remaining roles. The former
|
|
||||||
# `else` branch listed evaluations *received* — a player's view,
|
|
||||||
# unreachable from this point (ARCH-007).
|
|
||||||
evaluations_page = paginate(
|
|
||||||
Evaluation.query.outerjoin(Tryout, Evaluation.tryout_id == Tryout.id)
|
|
||||||
.outerjoin(player_alias, Evaluation.player_id == player_alias.id)
|
|
||||||
.outerjoin(evaluator_alias, Evaluation.evaluator_id == evaluator_alias.id)
|
|
||||||
.filter(Evaluation.evaluator_id == user.id)
|
|
||||||
.order_by(sort_expr, Evaluation.id)
|
|
||||||
)
|
)
|
||||||
player_scores = {}
|
|
||||||
|
def sort_value(entry):
|
||||||
|
if sort_column == 'player':
|
||||||
|
return entry['player'].username.lower()
|
||||||
|
if sort_column == 'count':
|
||||||
|
return entry['count']
|
||||||
|
if sort_column == 'created_at':
|
||||||
|
return entry['last_eval'] or utc_now_naive()
|
||||||
|
return entry['avg'] if entry['avg'] is not None else float('-inf')
|
||||||
|
|
||||||
|
grouped.sort(key=sort_value, reverse=(sort_order == 'desc'))
|
||||||
|
|
||||||
|
page = request.args.get('page', 1, type=int) or 1
|
||||||
|
page = max(1, page)
|
||||||
|
per_page = request.args.get('per_page', DEFAULT_PER_PAGE, type=int) or DEFAULT_PER_PAGE
|
||||||
|
per_page = max(1, min(per_page, MAX_PER_PAGE))
|
||||||
|
|
||||||
|
total = len(grouped)
|
||||||
|
pages = math.ceil(total / per_page) if total else 1
|
||||||
|
page = min(page, pages)
|
||||||
|
start = (page - 1) * per_page
|
||||||
|
page_items = grouped[start:start + per_page]
|
||||||
|
|
||||||
|
players_on_page = {entry['player'].id: entry for entry in page_items}
|
||||||
|
if players_on_page:
|
||||||
|
evaluations = (
|
||||||
|
Evaluation.query
|
||||||
|
.filter(Evaluation.player_id.in_(players_on_page))
|
||||||
|
.filter(Evaluation.id.in_(visible_ids))
|
||||||
|
.order_by(Evaluation.created_at.desc(), Evaluation.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
evaluators_by_id = _users_by_id(e.evaluator_id for e in evaluations)
|
||||||
|
tryout_ids = [e.tryout_id for e in evaluations if e.tryout_id]
|
||||||
|
tryouts_by_id = (
|
||||||
|
{t.id: t for t in Tryout.query.filter(Tryout.id.in_(tryout_ids)).all()}
|
||||||
|
if tryout_ids
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
for evaluation in evaluations:
|
||||||
|
players_on_page[evaluation.player_id]['evaluations'].append(
|
||||||
|
_evaluation_view(
|
||||||
|
evaluation,
|
||||||
|
evaluators_by_id.get(evaluation.evaluator_id),
|
||||||
|
tryouts_by_id.get(evaluation.tryout_id),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
pagination = {
|
||||||
|
'page': page,
|
||||||
|
'pages': pages,
|
||||||
|
'total': total,
|
||||||
|
'has_prev': page > 1,
|
||||||
|
'has_next': page < pages,
|
||||||
|
'prev_num': page - 1,
|
||||||
|
'next_num': page + 1,
|
||||||
|
}
|
||||||
|
|
||||||
return render_template(
|
return render_template(
|
||||||
'pages/evaluations.html',
|
'pages/evaluations.html',
|
||||||
evaluations=evaluations_page.items,
|
players=page_items,
|
||||||
pagination=evaluations_page,
|
pagination=pagination,
|
||||||
player_scores=player_scores,
|
|
||||||
sort_column=sort_column,
|
sort_column=sort_column,
|
||||||
sort_order=sort_order,
|
sort_order=sort_order,
|
||||||
|
evaluation_criteria=EVALUATION_CRITERIA,
|
||||||
|
first_player_id=grouped[0]['player'].id if grouped else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@evaluations_bp.route('/player/<int:player_id>')
|
||||||
|
@login_required
|
||||||
|
def player_evaluations(player_id):
|
||||||
|
"""One player's evaluations, with prev/next navigation between players."""
|
||||||
|
user = current_user
|
||||||
|
if not user.can_evaluate():
|
||||||
|
flash(_('You do not have permission to view evaluations.'), 'danger')
|
||||||
|
return redirect(url_for('main.dashboard'))
|
||||||
|
|
||||||
|
player = db.get_or_404(User, player_id)
|
||||||
|
if not isinstance(player, Player):
|
||||||
|
flash(_('Can only view evaluations for players.'), 'danger')
|
||||||
|
return redirect(url_for('evaluations.list_evaluations'))
|
||||||
|
|
||||||
|
ordered = _players_by_average(user)
|
||||||
|
index = next((i for i, (p, _avg) in enumerate(ordered) if p.id == player.id), None)
|
||||||
|
prev_player = ordered[index - 1][0] if index is not None and index > 0 else None
|
||||||
|
next_player = ordered[index + 1][0] if index is not None and index + 1 < len(ordered) else None
|
||||||
|
|
||||||
|
visible_ids = _visible_evaluation_ids(user)
|
||||||
|
evaluations = (
|
||||||
|
Evaluation.query
|
||||||
|
.filter(Evaluation.player_id == player.id)
|
||||||
|
.filter(Evaluation.id.in_(visible_ids))
|
||||||
|
.order_by(Evaluation.created_at.desc(), Evaluation.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
evaluators_by_id = _users_by_id(e.evaluator_id for e in evaluations)
|
||||||
|
tryout_ids = [e.tryout_id for e in evaluations if e.tryout_id]
|
||||||
|
tryouts_by_id = (
|
||||||
|
{t.id: t for t in Tryout.query.filter(Tryout.id.in_(tryout_ids)).all()}
|
||||||
|
if tryout_ids
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
evaluation_views = [
|
||||||
|
_evaluation_view(e, evaluators_by_id.get(e.evaluator_id), tryouts_by_id.get(e.tryout_id))
|
||||||
|
for e in evaluations
|
||||||
|
]
|
||||||
|
|
||||||
|
aggregates = _aggregate(evaluations)
|
||||||
|
|
||||||
|
return render_template(
|
||||||
|
'pages/player_evaluations.html',
|
||||||
|
player=player,
|
||||||
|
evaluations=evaluation_views,
|
||||||
|
prev_player=prev_player,
|
||||||
|
next_player=next_player,
|
||||||
|
criterion_averages=aggregates['criterion_averages'],
|
||||||
|
combined_average=aggregates['combined_average'],
|
||||||
|
evaluation_count=aggregates['count'],
|
||||||
|
evaluation_criteria=EVALUATION_CRITERIA,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -317,6 +514,7 @@ def batch_evaluate(tryout_id):
|
|||||||
|
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
saved = 0
|
saved = 0
|
||||||
|
try:
|
||||||
for entry in players:
|
for entry in players:
|
||||||
pid = entry['player'].id
|
pid = entry['player'].id
|
||||||
scores = {
|
scores = {
|
||||||
@@ -338,6 +536,16 @@ def batch_evaluate(tryout_id):
|
|||||||
_apply_evaluation(evaluation, scores, comments, position)
|
_apply_evaluation(evaluation, scores, comments, position)
|
||||||
db.session.add(evaluation)
|
db.session.add(evaluation)
|
||||||
saved += 1
|
saved += 1
|
||||||
|
except ValidationError:
|
||||||
|
db.session.rollback()
|
||||||
|
flash(_('Scores must be whole numbers from 1 to 10.'), 'danger')
|
||||||
|
return render_template(
|
||||||
|
'pages/batch_evaluate.html',
|
||||||
|
tryout=tryout,
|
||||||
|
players=players,
|
||||||
|
evaluation_criteria=EVALUATION_CRITERIA,
|
||||||
|
game_positions=GAME_POSITIONS,
|
||||||
|
)
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
flash(f'Saved evaluations for {saved} player(s).', 'success')
|
flash(f'Saved evaluations for {saved} player(s).', 'success')
|
||||||
|
|||||||
+82
-37
@@ -224,7 +224,6 @@ def api_events():
|
|||||||
|
|
||||||
for match in matches:
|
for match in matches:
|
||||||
tryout = tryouts_by_id[match.tryout_id]
|
tryout = tryouts_by_id[match.tryout_id]
|
||||||
match_color = '#10b981' if match.match_type == 'team_vs_team' else '#f59e0b'
|
|
||||||
# 'description' used to be participants_str + '<br>' + description.
|
# 'description' used to be participants_str + '<br>' + description.
|
||||||
# Building presentation markup inside a JSON field is what carried
|
# Building presentation markup inside a JSON field is what carried
|
||||||
# the stored XSS: the browser dropped it straight into innerHTML,
|
# the stored XSS: the browser dropped it straight into innerHTML,
|
||||||
@@ -255,7 +254,6 @@ def api_events():
|
|||||||
'id': f'match_{match.id}',
|
'id': f'match_{match.id}',
|
||||||
'title': match.title,
|
'title': match.title,
|
||||||
'type': 'match',
|
'type': 'match',
|
||||||
'color': match_color,
|
|
||||||
'extendedProps': {
|
'extendedProps': {
|
||||||
'location': match.location or tryout.location or 'TBD',
|
'location': match.location or tryout.location or 'TBD',
|
||||||
'status': match.status,
|
'status': match.status,
|
||||||
@@ -301,7 +299,6 @@ def api_events():
|
|||||||
'id': f'team_match_{team_match.id}',
|
'id': f'team_match_{team_match.id}',
|
||||||
'title': team_match.title,
|
'title': team_match.title,
|
||||||
'type': 'team_match',
|
'type': 'team_match',
|
||||||
'color': '#3b82f6',
|
|
||||||
'extendedProps': {
|
'extendedProps': {
|
||||||
'location': team_match.location or 'TBD',
|
'location': team_match.location or 'TBD',
|
||||||
'status': team_match.status,
|
'status': team_match.status,
|
||||||
@@ -334,7 +331,6 @@ def api_events():
|
|||||||
'id': f'one_on_one_{ooo.id}',
|
'id': f'one_on_one_{ooo.id}',
|
||||||
'title': f'1:1 - {ooo.player.full_name} & {ooo.coach.full_name}',
|
'title': f'1:1 - {ooo.player.full_name} & {ooo.coach.full_name}',
|
||||||
'type': 'one_on_one',
|
'type': 'one_on_one',
|
||||||
'color': '#8b5cf6',
|
|
||||||
'extendedProps': {
|
'extendedProps': {
|
||||||
'location': 'Discord / Voice Chat',
|
'location': 'Discord / Voice Chat',
|
||||||
'status': 'approved',
|
'status': 'approved',
|
||||||
@@ -570,6 +566,12 @@ def edit_match(match_id):
|
|||||||
flash_validation_errors(err)
|
flash_validation_errors(err)
|
||||||
return rerender()
|
return rerender()
|
||||||
|
|
||||||
|
# Snapshot the date/time before we overwrite them, so we can detect
|
||||||
|
# whether only these fields changed and choose the right Discord message.
|
||||||
|
old_date = match.date
|
||||||
|
old_start = match.start_time
|
||||||
|
old_end = match.end_time
|
||||||
|
|
||||||
# Assigned only once the whole form has been accepted. Assigning as
|
# Assigned only once the whole form has been accepted. Assigning as
|
||||||
# each field was read meant a form rejected halfway had already
|
# each field was read meant a form rejected halfway had already
|
||||||
# changed the record in the session.
|
# changed the record in the session.
|
||||||
@@ -581,60 +583,103 @@ def edit_match(match_id):
|
|||||||
match.location = data['location']
|
match.location = data['location']
|
||||||
match.status = data['status']
|
match.status = data['status']
|
||||||
|
|
||||||
notified_player_ids = []
|
time_changed = (
|
||||||
notified_participant_ids = []
|
match.date != old_date or match.start_time != old_start or match.end_time != old_end
|
||||||
|
)
|
||||||
# Capture old participant ids before any deletion, so we can purge
|
|
||||||
# their pending Discord notifications once the change is committed.
|
|
||||||
stale_participant_ids = [
|
|
||||||
p.id for p in MatchParticipant.query.filter_by(match_id=match.id).all()
|
|
||||||
]
|
|
||||||
|
|
||||||
|
# Build the desired participant set and reconcile it against the
|
||||||
|
# existing participants, rather than deleting and recreating everyone.
|
||||||
|
# This preserves attendance_confirmed for players who stay.
|
||||||
|
desired = set()
|
||||||
if match.match_type == 'team_vs_team':
|
if match.match_type == 'team_vs_team':
|
||||||
teams_changed = data['team1_id'] != match.team1_id or data['team2_id'] != match.team2_id
|
|
||||||
if teams_changed:
|
|
||||||
MatchParticipant.query.filter_by(match_id=match.id).delete()
|
|
||||||
match.team1_id = data['team1_id']
|
match.team1_id = data['team1_id']
|
||||||
match.team2_id = data['team2_id']
|
match.team2_id = data['team2_id']
|
||||||
notified_player_ids, notified_participant_ids = create_participants(match, data)
|
for team_id in (data['team1_id'], data['team2_id']):
|
||||||
else:
|
|
||||||
# Same teams: the roster stands, but everyone is told again,
|
|
||||||
# because the date or the time may have moved.
|
|
||||||
# Reuse the existing participant ids so reference_id is always
|
|
||||||
# a real participant row, never the match id (fallback).
|
|
||||||
for team_id in (match.team1_id, match.team2_id):
|
|
||||||
if team_id:
|
if team_id:
|
||||||
for member in TeamMember.query.filter_by(team_id=team_id).all():
|
for member in TeamMember.query.filter_by(team_id=team_id).all():
|
||||||
notified_player_ids.append(member.player_id)
|
desired.add(member.player_id)
|
||||||
existing = MatchParticipant.query.filter_by(
|
elif match.match_type == 'player_vs_player':
|
||||||
match_id=match.id, player_id=member.player_id
|
for pid in data['team1_player_ids']:
|
||||||
).first()
|
desired.add(pid)
|
||||||
if existing:
|
for pid in data['team2_player_ids']:
|
||||||
notified_participant_ids.append(existing.id)
|
desired.add(pid)
|
||||||
stale_participant_ids = [
|
|
||||||
pid for pid in stale_participant_ids if pid != existing.id
|
|
||||||
]
|
|
||||||
else:
|
else:
|
||||||
MatchParticipant.query.filter_by(match_id=match.id).delete()
|
for pid in data['player_ids']:
|
||||||
notified_player_ids, notified_participant_ids = create_participants(match, data)
|
desired.add(pid)
|
||||||
|
|
||||||
|
existing = {
|
||||||
|
p.player_id: p for p in MatchParticipant.query.filter_by(match_id=match.id).all()
|
||||||
|
}
|
||||||
|
|
||||||
|
removed_ids = []
|
||||||
|
notified_player_ids = []
|
||||||
|
notified_participant_ids = []
|
||||||
|
kept_ids = set()
|
||||||
|
|
||||||
|
for player_id, participant in list(existing.items()):
|
||||||
|
if player_id in desired:
|
||||||
|
kept_ids.add(player_id)
|
||||||
|
notified_player_ids.append(player_id)
|
||||||
|
notified_participant_ids.append(participant.id)
|
||||||
|
else:
|
||||||
|
removed_ids.append(participant.id)
|
||||||
|
db.session.delete(participant)
|
||||||
|
|
||||||
|
# New players get new participant rows.
|
||||||
|
for player_id in desired - set(existing.keys()):
|
||||||
|
participant = MatchParticipant(match_id=match.id, player_id=player_id)
|
||||||
|
db.session.add(participant)
|
||||||
|
db.session.flush()
|
||||||
|
notified_player_ids.append(player_id)
|
||||||
|
notified_participant_ids.append(participant.id)
|
||||||
|
kept_ids.add(player_id)
|
||||||
|
|
||||||
|
# When the date or time changed, reset attendance on everyone who
|
||||||
|
# stayed. They'll be asked to re-confirm via the modified message.
|
||||||
|
if time_changed:
|
||||||
|
for participant in MatchParticipant.query.filter_by(match_id=match.id).all():
|
||||||
|
if participant.player_id in kept_ids:
|
||||||
|
participant.attendance_confirmed = False
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
# Purge Discord pending entries for participants that no longer exist.
|
# Purge Discord pending entries for participants that no longer exist.
|
||||||
# This runs after the commit so the bot only sees the durable state.
|
if removed_ids:
|
||||||
if stale_participant_ids:
|
|
||||||
from app.discord_bot import purge_pending_for_participants
|
from app.discord_bot import purge_pending_for_participants
|
||||||
|
|
||||||
purge_pending_for_participants(stale_participant_ids)
|
purge_pending_for_participants(removed_ids)
|
||||||
|
|
||||||
|
# Decide whether and what to notify.
|
||||||
|
if time_changed:
|
||||||
|
# All current participants get the "modified" message.
|
||||||
|
all_current = list(zip(notified_player_ids, notified_participant_ids))
|
||||||
notify_participants(
|
notify_participants(
|
||||||
title=match.title,
|
title=match.title,
|
||||||
date=match.date,
|
date=match.date,
|
||||||
start_time=match.start_time,
|
start_time=match.start_time,
|
||||||
end_time=match.end_time,
|
end_time=match.end_time,
|
||||||
participants=zip_participants(notified_player_ids, notified_participant_ids),
|
participants=all_current,
|
||||||
fallback_id=match.id,
|
fallback_id=match.id,
|
||||||
|
change_kind='modified',
|
||||||
)
|
)
|
||||||
|
elif desired - set(existing.keys()):
|
||||||
|
# Only the newly added players are told about the match.
|
||||||
|
new_player_ids = desired - set(existing.keys())
|
||||||
|
new_pairs = [
|
||||||
|
(pid, nid)
|
||||||
|
for pid, nid in zip(notified_player_ids, notified_participant_ids)
|
||||||
|
if pid in new_player_ids
|
||||||
|
]
|
||||||
|
notify_participants(
|
||||||
|
title=match.title,
|
||||||
|
date=match.date,
|
||||||
|
start_time=match.start_time,
|
||||||
|
end_time=match.end_time,
|
||||||
|
participants=new_pairs,
|
||||||
|
fallback_id=match.id,
|
||||||
|
change_kind='scheduled',
|
||||||
|
)
|
||||||
|
# else: nothing changed that needs a notification.
|
||||||
|
|
||||||
flash(_('Match updated successfully!'), 'success')
|
flash(_('Match updated successfully!'), 'success')
|
||||||
return respond_after_change(url_for('tryouts.view_tryout', tryout_id=tryout.id))
|
return respond_after_change(url_for('tryouts.view_tryout', tryout_id=tryout.id))
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ from app.models import (
|
|||||||
TeamPlayer,
|
TeamPlayer,
|
||||||
)
|
)
|
||||||
from app.pagination import paginate
|
from app.pagination import paginate
|
||||||
from app.permissions import can_manage_org_team, coach_org_teams, visible_org_teams
|
from app.permissions import coach_org_teams, representative_org_teams, visible_org_teams
|
||||||
from app.responders import respond_after_change
|
from app.responders import respond_after_change
|
||||||
from app.routes.matches import default_end_time
|
from app.routes.matches import default_end_time
|
||||||
from app.services.scheduling import notify_participants, zip_participants
|
from app.services.scheduling import notify_participants, zip_participants
|
||||||
@@ -36,10 +36,11 @@ team_matches_bp = Blueprint('team_matches', __name__, url_prefix='/team-matches'
|
|||||||
def can_manage_team_match(team):
|
def can_manage_team_match(team):
|
||||||
"""Whether the current user can manage matches for this team.
|
"""Whether the current user can manage matches for this team.
|
||||||
|
|
||||||
Same rule as administering the team itself, so it is the same call.
|
Everyone who administers the team, plus the player named as its
|
||||||
This function used to restate it, and the restatement drifted.
|
responsible. Narrower than administering the team itself: a responsible
|
||||||
|
schedules and edits matches, but does not touch the roster.
|
||||||
"""
|
"""
|
||||||
return can_manage_org_team(current_user, team)
|
return current_user.can_manage_team_matches(team)
|
||||||
|
|
||||||
|
|
||||||
def season_locked():
|
def season_locked():
|
||||||
@@ -300,13 +301,13 @@ def delete_match(match_id):
|
|||||||
@login_required
|
@login_required
|
||||||
def api_manageable_teams():
|
def api_manageable_teams():
|
||||||
"""API endpoint returning teams the current user can schedule matches for."""
|
"""API endpoint returning teams the current user can schedule matches for."""
|
||||||
if not current_user.can_schedule_matches():
|
|
||||||
return jsonify([])
|
|
||||||
|
|
||||||
if isinstance(current_user, (Admin, Manager)):
|
if isinstance(current_user, (Admin, Manager)):
|
||||||
teams = OrgTeam.query.order_by(OrgTeam.name).all()
|
teams = OrgTeam.query.order_by(OrgTeam.name).all()
|
||||||
elif isinstance(current_user, Coach):
|
elif isinstance(current_user, Coach):
|
||||||
teams = coach_org_teams(current_user)
|
teams = coach_org_teams(current_user)
|
||||||
|
elif isinstance(current_user, Player):
|
||||||
|
# A responsible schedules matches for their own team(s) only.
|
||||||
|
teams = representative_org_teams(current_user)
|
||||||
else:
|
else:
|
||||||
return jsonify([])
|
return jsonify([])
|
||||||
|
|
||||||
|
|||||||
+35
-3
@@ -26,7 +26,7 @@ from app.models import (
|
|||||||
Tryout,
|
Tryout,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
from app.permissions import visible_org_teams
|
from app.permissions import representative_org_teams, visible_org_teams
|
||||||
from app.responders import respond_after_change
|
from app.responders import respond_after_change
|
||||||
from app.time_utils import utc_now_naive
|
from app.time_utils import utc_now_naive
|
||||||
from app.validators import NoteContentSchema, OrgTeamSchema, TeamPlayerSchema, TeamStaffSchema
|
from app.validators import NoteContentSchema, OrgTeamSchema, TeamPlayerSchema, TeamStaffSchema
|
||||||
@@ -40,10 +40,12 @@ def list_teams():
|
|||||||
"""List all organization teams visible to the current user."""
|
"""List all organization teams visible to the current user."""
|
||||||
can_manage = current_user.can_manage_teams()
|
can_manage = current_user.can_manage_teams()
|
||||||
|
|
||||||
if isinstance(current_user, Player):
|
# A player reaches this page only as a team's responsible; anyone else
|
||||||
|
# is sent to their own view.
|
||||||
|
if isinstance(current_user, Player) and not representative_org_teams(current_user):
|
||||||
flash(_('Use My Team(s) to view your teams.'), 'info')
|
flash(_('Use My Team(s) to view your teams.'), 'info')
|
||||||
return redirect(url_for('teams.my_teams'))
|
return redirect(url_for('teams.my_teams'))
|
||||||
if not isinstance(current_user, (Admin, Coach, Manager)):
|
if not isinstance(current_user, (Admin, Coach, Manager, Player)):
|
||||||
flash(_('You do not have permission to view teams.'), 'danger')
|
flash(_('You do not have permission to view teams.'), 'danger')
|
||||||
return redirect(url_for('main.dashboard'))
|
return redirect(url_for('main.dashboard'))
|
||||||
|
|
||||||
@@ -563,6 +565,36 @@ def toggle_player_status(team_id, player_id):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@teams_bp.route('/<int:team_id>/toggle_representative/<int:player_id>', methods=['POST'])
|
||||||
|
@json_endpoint
|
||||||
|
@login_required
|
||||||
|
def toggle_player_representative(team_id, player_id):
|
||||||
|
"""Name or un-name a player as their team's responsible (president only).
|
||||||
|
|
||||||
|
The responsible gains match-management rights for this one team. The
|
||||||
|
flag itself stays a president's decision: this is deliberately the one
|
||||||
|
roster action a responsible cannot perform on their own team.
|
||||||
|
"""
|
||||||
|
db.get_or_404(OrgTeam, team_id)
|
||||||
|
if not current_user.can_designate_team_representative():
|
||||||
|
return jsonify({'error': 'Permission denied'}), 403
|
||||||
|
|
||||||
|
tp = TeamPlayer.query.filter_by(player_id=player_id, org_team_id=team_id).first()
|
||||||
|
if not tp:
|
||||||
|
return jsonify({'error': 'Player not found on this team'}), 404
|
||||||
|
|
||||||
|
tp.is_team_representative = not tp.is_team_representative
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
'success': True,
|
||||||
|
'player_id': player_id,
|
||||||
|
'is_team_representative': tp.is_team_representative,
|
||||||
|
'player_name': tp.player.username,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@teams_bp.route('/<int:team_id>/add-team-note', methods=['POST'])
|
@teams_bp.route('/<int:team_id>/add-team-note', methods=['POST'])
|
||||||
@login_required
|
@login_required
|
||||||
def add_team_note(team_id):
|
def add_team_note(team_id):
|
||||||
|
|||||||
@@ -60,7 +60,9 @@ def zip_participants(player_ids, participant_ids):
|
|||||||
yield player_id, participant_ids[index] if index < len(participant_ids) else None
|
yield player_id, participant_ids[index] if index < len(participant_ids) else None
|
||||||
|
|
||||||
|
|
||||||
def notify_participants(*, title, date, start_time, end_time, participants, fallback_id):
|
def notify_participants(
|
||||||
|
*, title, date, start_time, end_time, participants, fallback_id, change_kind='scheduled'
|
||||||
|
):
|
||||||
"""Tell each participant that a match has been scheduled or changed.
|
"""Tell each participant that a match has been scheduled or changed.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -73,6 +75,8 @@ def notify_participants(*, title, date, start_time, end_time, participants, fall
|
|||||||
attendance lands on the right row.
|
attendance lands on the right row.
|
||||||
fallback_id: Reference to use when a participant row has no id —
|
fallback_id: Reference to use when a participant row has no id —
|
||||||
the match's own, which the bot can still act on.
|
the match's own, which the bot can still act on.
|
||||||
|
change_kind: 'scheduled' (new match / new player added) or
|
||||||
|
'modified' (date/time changed for existing players).
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
int: How many notifications were handed to the bot.
|
int: How many notifications were handed to the bot.
|
||||||
@@ -91,6 +95,7 @@ def notify_participants(*, title, date, start_time, end_time, participants, fall
|
|||||||
event_date=event_date,
|
event_date=event_date,
|
||||||
event_time=event_time,
|
event_time=event_time,
|
||||||
reference_id=participant_id or fallback_id,
|
reference_id=participant_id or fallback_id,
|
||||||
|
change_kind=change_kind,
|
||||||
)
|
)
|
||||||
sent += 1
|
sent += 1
|
||||||
return sent
|
return sent
|
||||||
|
|||||||
+189
-15
@@ -1043,6 +1043,10 @@ a:hover { color: var(--primary-dark); }
|
|||||||
|
|
||||||
.fc {
|
.fc {
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
--fc-border-color: var(--gray-200);
|
||||||
|
--fc-page-bg-color: transparent;
|
||||||
|
--fc-neutral-bg-color: var(--gray-50);
|
||||||
|
--fc-today-bg-color: var(--info-light);
|
||||||
}
|
}
|
||||||
|
|
||||||
.fc-toolbar {
|
.fc-toolbar {
|
||||||
@@ -1055,24 +1059,29 @@ a:hover { color: var(--primary-dark); }
|
|||||||
color: var(--gray-900);
|
color: var(--gray-900);
|
||||||
}
|
}
|
||||||
|
|
||||||
.fc-button {
|
.fc .fc-button {
|
||||||
background: var(--primary) !important;
|
background: var(--gray-50) !important;
|
||||||
border: none !important;
|
border: 1px solid var(--gray-200) !important;
|
||||||
|
color: var(--gray-700) !important;
|
||||||
border-radius: var(--radius-sm) !important;
|
border-radius: var(--radius-sm) !important;
|
||||||
padding: 6px 12px !important;
|
padding: 6px 12px !important;
|
||||||
font-size: 0.85rem !important;
|
font-size: 0.85rem !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.fc-button:hover {
|
.fc .fc-button:hover {
|
||||||
background: var(--primary-dark) !important;
|
background: var(--gray-100) !important;
|
||||||
|
color: var(--gray-900) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.fc-button-primary:not(:disabled).fc-button-active,
|
.fc .fc-button-primary:not(:disabled).fc-button-active,
|
||||||
.fc-button-primary:not(:disabled):active {
|
.fc .fc-button-primary:not(:disabled):active {
|
||||||
background: var(--primary-dark) !important;
|
background: var(--primary) !important;
|
||||||
|
border-color: var(--primary) !important;
|
||||||
|
color: #fff !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.fc-daygrid-day {
|
.fc-daygrid-day,
|
||||||
|
.fc-timegrid-slot {
|
||||||
transition: var(--transition);
|
transition: var(--transition);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1080,16 +1089,111 @@ a:hover { color: var(--primary-dark); }
|
|||||||
background: var(--gray-50);
|
background: var(--gray-50);
|
||||||
}
|
}
|
||||||
|
|
||||||
.fc-event {
|
/* Event cards (scoped to the main calendar: the tryout mini-calendar keeps
|
||||||
border-radius: var(--radius-sm);
|
its inline event colors) */
|
||||||
padding: 2px 4px;
|
#calendar .fc-event {
|
||||||
font-size: 0.8rem;
|
border: none !important;
|
||||||
|
border-radius: var(--radius-sm) !important;
|
||||||
|
padding: 3px 6px !important;
|
||||||
|
font-size: 0.8rem !important;
|
||||||
|
background-color: var(--fc-event-bg, var(--primary)) !important;
|
||||||
|
color: #fff !important;
|
||||||
|
box-shadow: var(--shadow);
|
||||||
}
|
}
|
||||||
|
|
||||||
.fc-event-title {
|
#calendar .fc-event-body {
|
||||||
font-weight: 600;
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#calendar .fc-event-body i {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
#calendar .fc-event-text {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 0 4px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#calendar .fc-event-time {
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
#calendar .fc-event-title {
|
||||||
|
font-weight: 600 !important;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Event type colors (semantic, light theme) */
|
||||||
|
#calendar .fc-event--team { --fc-event-bg: #10b981; }
|
||||||
|
#calendar .fc-event--scrim { --fc-event-bg: #f59e0b; }
|
||||||
|
#calendar .fc-event--team-match { --fc-event-bg: #3b82f6; }
|
||||||
|
#calendar .fc-event--one-on-one { --fc-event-bg: #8b5cf6; }
|
||||||
|
|
||||||
|
#calendar .fc-now-indicator {
|
||||||
|
border-color: var(--danger);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Dark theme: the calendar chrome reacts to the light/dark switch */
|
||||||
|
[data-theme="dark"] .fc {
|
||||||
|
--fc-border-color: var(--border-color);
|
||||||
|
--fc-neutral-bg-color: var(--bg-secondary);
|
||||||
|
--fc-today-bg-color: rgba(59, 130, 246, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .fc-toolbar-title {
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .fc .fc-button {
|
||||||
|
background: var(--bg-tertiary) !important;
|
||||||
|
border-color: var(--border-color) !important;
|
||||||
|
color: var(--text-secondary) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .fc .fc-button:hover {
|
||||||
|
background: var(--bg-secondary) !important;
|
||||||
|
color: var(--text-primary) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .fc .fc-button-primary:not(:disabled).fc-button-active,
|
||||||
|
[data-theme="dark"] .fc .fc-button-primary:not(:disabled):active {
|
||||||
|
background: var(--primary) !important;
|
||||||
|
border-color: var(--primary) !important;
|
||||||
|
color: #fff !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .fc-daygrid-day:hover {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .fc-daygrid-day-number,
|
||||||
|
[data-theme="dark"] .fc-col-header-cell-cushion,
|
||||||
|
[data-theme="dark"] .fc-timegrid-axis-cushion,
|
||||||
|
[data-theme="dark"] .fc-timegrid-slot-label-cushion {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Pastel event chips with dark text keep contrast on a dark background. */
|
||||||
|
[data-theme="dark"] #calendar .fc-event {
|
||||||
|
color: var(--gray-900) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] #calendar .fc-event--team { --fc-event-bg: #d1fae5; }
|
||||||
|
[data-theme="dark"] #calendar .fc-event--scrim { --fc-event-bg: #fef3c7; }
|
||||||
|
[data-theme="dark"] #calendar .fc-event--team-match { --fc-event-bg: #dbeafe; }
|
||||||
|
[data-theme="dark"] #calendar .fc-event--one-on-one { --fc-event-bg: #ede9fe; }
|
||||||
|
|
||||||
.btn-group {
|
.btn-group {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
@@ -2122,3 +2226,73 @@ a:hover { color: var(--primary-dark); }
|
|||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Evaluation comments - separate grid so long notes stay readable */
|
||||||
|
.eval-comments {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.eval-comments-title {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
margin: 0 0 4px;
|
||||||
|
font-size: 0.95rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.eval-comment {
|
||||||
|
background: var(--gray-50);
|
||||||
|
border: 1px solid var(--gray-200);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
padding: 12px 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.eval-comment-text {
|
||||||
|
margin: 0 0 10px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
color: var(--gray-800);
|
||||||
|
}
|
||||||
|
|
||||||
|
.eval-comment-meta {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--gray-500);
|
||||||
|
}
|
||||||
|
|
||||||
|
.eval-comment-author strong {
|
||||||
|
color: var(--gray-700);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .eval-comment {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
border-color: var(--border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .eval-comment-text {
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .eval-comment-meta {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .eval-comment-author strong {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.eval-comments-empty {
|
||||||
|
margin: 8px 0 0;
|
||||||
|
color: var(--gray-500);
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-theme="dark"] .eval-comments-empty {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|||||||
@@ -137,12 +137,18 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
headerToolbar: {
|
headerToolbar: {
|
||||||
left: 'prev,next today',
|
left: 'prev,next today',
|
||||||
center: 'title',
|
center: 'title',
|
||||||
right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
|
right: ''
|
||||||
},
|
},
|
||||||
events: '/matches/api/events',
|
events: '/matches/api/events',
|
||||||
eventClick: function(info) {
|
eventClick: function(info) {
|
||||||
showEventModal(info.event);
|
showEventModal(info.event);
|
||||||
},
|
},
|
||||||
|
eventClassNames: function(arg) {
|
||||||
|
return [eventClassName(arg.event)];
|
||||||
|
},
|
||||||
|
eventContent: function(arg) {
|
||||||
|
return renderEventContent(arg);
|
||||||
|
},
|
||||||
dateClick: function(info) {
|
dateClick: function(info) {
|
||||||
if (canScheduleMatches) {
|
if (canScheduleMatches) {
|
||||||
var dateStr = info.dateStr;
|
var dateStr = info.dateStr;
|
||||||
@@ -158,7 +164,11 @@ document.addEventListener('DOMContentLoaded', function() {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
slotMinTime: '12:00:00',
|
slotMinTime: '12:00:00',
|
||||||
slotMaxTime: '24:00:00'
|
slotMaxTime: '24:00:00',
|
||||||
|
slotEventOverlap: true,
|
||||||
|
dayMaxEvents: false,
|
||||||
|
nowIndicator: true,
|
||||||
|
height: 'auto'
|
||||||
});
|
});
|
||||||
calendar.render();
|
calendar.render();
|
||||||
|
|
||||||
@@ -177,6 +187,41 @@ function changeView(viewName) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function eventClassName(event) {
|
||||||
|
var props = event.extendedProps || {};
|
||||||
|
if (props.type === 'team_match') { return 'fc-event--team-match'; }
|
||||||
|
if (props.type === 'one_on_one') { return 'fc-event--one-on-one'; }
|
||||||
|
return props.match_type === 'team_vs_team' ? 'fc-event--team' : 'fc-event--scrim';
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventIcon(type, matchType) {
|
||||||
|
if (type === 'team_match') { return 'fa-trophy'; }
|
||||||
|
if (type === 'one_on_one') { return 'fa-user-friends'; }
|
||||||
|
if (matchType === 'team_vs_team') { return 'fa-shield-alt'; }
|
||||||
|
if (matchType === 'player_vs_player') { return 'fa-users'; }
|
||||||
|
return 'fa-gamepad';
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderEventContent(arg) {
|
||||||
|
// Built with DOM nodes + textContent: the title comes from a JSON endpoint
|
||||||
|
// and has never been HTML-escaped, so it must not reach innerHTML.
|
||||||
|
var props = arg.event.extendedProps || {};
|
||||||
|
var wrap = makeEl('div', 'fc-event-body');
|
||||||
|
|
||||||
|
var icon = makeEl('i', 'fas ' + eventIcon(props.type, props.match_type));
|
||||||
|
icon.setAttribute('aria-hidden', 'true');
|
||||||
|
wrap.appendChild(icon);
|
||||||
|
|
||||||
|
var text = makeEl('span', 'fc-event-text');
|
||||||
|
if (!arg.event.allDay && arg.timeText && arg.view.type.indexOf('dayGrid') === 0) {
|
||||||
|
text.appendChild(makeEl('span', 'fc-event-time', arg.timeText));
|
||||||
|
}
|
||||||
|
text.appendChild(makeEl('span', 'fc-event-title', arg.event.title));
|
||||||
|
wrap.appendChild(text);
|
||||||
|
|
||||||
|
return { domNodes: [wrap] };
|
||||||
|
}
|
||||||
|
|
||||||
// --- Create Event Modal ---
|
// --- Create Event Modal ---
|
||||||
function showCreateEventModal(dateStr) {
|
function showCreateEventModal(dateStr) {
|
||||||
document.getElementById('createEventDate').textContent = dateStr;
|
document.getElementById('createEventDate').textContent = dateStr;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
{% block breadcrumb %}<span class="breadcrumb">Home / Evaluations</span>{% endblock %}
|
{% block breadcrumb %}<span class="breadcrumb">Home / Evaluations</span>{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{% set sort_column = sort_column | default('created_at') %}
|
{% set sort_column = sort_column | default('overall_score') %}
|
||||||
{% set sort_order = sort_order | default('desc') %}
|
{% set sort_order = sort_order | default('desc') %}
|
||||||
|
|
||||||
{% macro sort_link(column, label) %}
|
{% macro sort_link(column, label) %}
|
||||||
@@ -22,76 +22,111 @@
|
|||||||
</th>
|
</th>
|
||||||
{% endmacro %}
|
{% endmacro %}
|
||||||
|
|
||||||
{% if current_user.role == 'admin' and player_scores %}
|
<div class="view-toggle mb-3">
|
||||||
<div class="stats-grid mb-4">
|
<a href="{{ url_for('evaluations.list_evaluations') }}" class="btn btn-sm btn-primary">
|
||||||
{% for pid, data in player_scores.items() %}
|
<i class="fas fa-table"></i> {{ _('Table') }}
|
||||||
<div class="stat-card stat-card-sm">
|
</a>
|
||||||
<div class="stat-icon bg-info">
|
{% if first_player_id %}
|
||||||
<i class="fas fa-user"></i>
|
<a href="{{ url_for('evaluations.player_evaluations', player_id=first_player_id) }}" class="btn btn-sm btn-outline">
|
||||||
</div>
|
<i class="fas fa-user"></i> {{ _('By player') }}
|
||||||
<div class="stat-info">
|
</a>
|
||||||
<h3>{{ data.player.username[:12] }}</h3>
|
|
||||||
<p>Avg: <strong>{{ data.avg }}</strong> / {{ data.count }} evals</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endfor %}
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<h3><i class="fas fa-clipboard-list"></i>
|
<h3><i class="fas fa-clipboard-list"></i> {{ _('Player Evaluations') }}</h3>
|
||||||
{% if current_user.role == 'player' %}
|
|
||||||
My Evaluations
|
|
||||||
{% else %}
|
|
||||||
All Evaluations
|
|
||||||
{% endif %}
|
|
||||||
</h3>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="table-container">
|
<div class="table-container">
|
||||||
<table class="table">
|
<table class="table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
{{ sort_link('tryout', 'Tryout') }}
|
<th></th>
|
||||||
{{ sort_link('player', 'Player') }}
|
{{ sort_link('player', 'Player') }}
|
||||||
{{ sort_link('evaluator', 'Evaluator') }}
|
{{ sort_link('overall_score', 'Average') }}
|
||||||
{{ sort_link('mecanics_score', 'Mecanics') }}
|
{{ sort_link('count', 'Evaluations') }}
|
||||||
{{ sort_link('cohesion_score', 'Cohesion') }}
|
<th>{{ _('Open') }}</th>
|
||||||
{{ sort_link('communication_score', 'Communication') }}
|
|
||||||
{{ sort_link('gamesense_score', 'Gamesense') }}
|
|
||||||
{{ sort_link('versatility_score', 'Versatility') }}
|
|
||||||
{{ sort_link('discipline_score', 'Discipline') }}
|
|
||||||
{{ sort_link('analysis_score', 'Analysis') }}
|
|
||||||
{{ sort_link('sport_ethics_score', 'Sport Ethics') }}
|
|
||||||
{{ sort_link('mental_score', 'Mental') }}
|
|
||||||
{{ sort_link('overall_score', 'Overall') }}
|
|
||||||
{{ sort_link('position_recommendation', 'Position') }}
|
|
||||||
{{ sort_link('created_at', 'Date') }}
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for eval in evaluations %}
|
{% for entry in players %}
|
||||||
|
<tr class="eval-row" data-action="toggle-player-evals" data-target="evals-{{ entry.player.id }}">
|
||||||
|
<td><i class="fas fa-chevron-right eval-chevron"></i></td>
|
||||||
|
<td>
|
||||||
|
<a href="{{ url_for('evaluations.player_evaluations', player_id=entry.player.id) }}" class="player-link">
|
||||||
|
{{ entry.player.username }}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td><span class="score">{{ entry.avg | round(1) if entry.avg is not none else '-' }}</span></td>
|
||||||
|
<td>{{ entry.count }}</td>
|
||||||
|
<td>
|
||||||
|
<a href="{{ url_for('evaluations.player_evaluations', player_id=entry.player.id) }}" class="btn btn-sm btn-outline" title="{{ _('Open player view') }}">
|
||||||
|
<i class="fas fa-external-link-alt"></i>
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr class="eval-detail hidden" id="evals-{{ entry.player.id }}">
|
||||||
|
<td colspan="5">
|
||||||
|
<div class="eval-detail-inner">
|
||||||
|
<table class="table table-sm">
|
||||||
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{ eval.tryout.title if eval.tryout else 'Deleted Tryout' }}</td>
|
<th>{{ _('Evaluator') }}</th>
|
||||||
<td>{{ eval.player.username if eval.player else 'Deleted Player' }}</td>
|
<th>{{ _('Tryout') }}</th>
|
||||||
<td>{{ eval.evaluator.username if eval.evaluator else 'Deleted Evaluator' }}</td>
|
{% for field, label in evaluation_criteria %}
|
||||||
<td>{{ eval.mecanics_score or '-' }}</td>
|
<th>{{ label }}</th>
|
||||||
<td>{{ eval.cohesion_score or '-' }}</td>
|
{% endfor %}
|
||||||
<td>{{ eval.communication_score or '-' }}</td>
|
<th>{{ _('Overall') }}</th>
|
||||||
<td>{{ eval.gamesense_score or '-' }}</td>
|
<th>{{ _('Position') }}</th>
|
||||||
<td>{{ eval.versatility_score or '-' }}</td>
|
<th>{{ _('Date') }}</th>
|
||||||
<td>{{ eval.discipline_score or '-' }}</td>
|
</tr>
|
||||||
<td>{{ eval.analysis_score or '-' }}</td>
|
</thead>
|
||||||
<td>{{ eval.sport_ethics_score or '-' }}</td>
|
<tbody>
|
||||||
<td>{{ eval.mental_score or '-' }}</td>
|
{% for ev in entry.evaluations %}
|
||||||
<td><span class="score">{{ eval.overall_score or '-' }}</span></td>
|
<tr>
|
||||||
<td><span class="badge badge-info">{{ eval.position_recommendation or 'N/A' }}</span></td>
|
<td>{{ ev.evaluator.username if ev.evaluator else _('Deleted evaluator') }}</td>
|
||||||
<td>{{ eval.created_at.strftime('%m/%d/%Y') }}</td>
|
<td>{{ ev.tryout.title if ev.tryout else _('Deleted tryout') }}</td>
|
||||||
|
{% for score in ev.scores %}
|
||||||
|
<td>{{ score if score is not none else '-' }}</td>
|
||||||
|
{% endfor %}
|
||||||
|
<td><span class="score">{{ ev.overall | round(1) if ev.overall is not none else '-' }}</span></td>
|
||||||
|
<td>{{ ev.position or '-' }}</td>
|
||||||
|
<td>{{ ev.date.strftime('%m/%d/%Y') if ev.date else '-' }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
{% else %}
|
{% else %}
|
||||||
<tr>
|
<tr>
|
||||||
<td colspan="15" class="text-center">
|
<td colspan="{{ evaluation_criteria | length + 5 }}" class="text-center">{{ _('No evaluations for this player.') }}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
{% if entry.evaluations %}
|
||||||
|
{% set comment_evals = entry.evaluations | selectattr('comment') | list %}
|
||||||
|
<div class="eval-comments">
|
||||||
|
<h4 class="eval-comments-title"><i class="fas fa-comments"></i> {{ _('Comments') }}</h4>
|
||||||
|
{% if comment_evals %}
|
||||||
|
{% for ev in comment_evals %}
|
||||||
|
<article class="eval-comment">
|
||||||
|
<p class="eval-comment-text">{{ ev.comment }}</p>
|
||||||
|
<footer class="eval-comment-meta">
|
||||||
|
<span class="eval-comment-author">{{ _('Evaluator') }} : <strong>{{ ev.evaluator.username if ev.evaluator else _('Deleted evaluator') }}</strong></span>
|
||||||
|
<span class="eval-comment-context">{{ ev.tryout.title if ev.tryout else _('Deleted tryout') }} · {{ ev.date.strftime('%m/%d/%Y') if ev.date else '-' }}</span>
|
||||||
|
</footer>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
{% else %}
|
||||||
|
<p class="eval-comments-empty">{{ _('No comments') }}</p>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr>
|
||||||
|
<td colspan="5" class="text-center">
|
||||||
<div class="empty-state">
|
<div class="empty-state">
|
||||||
<i class="fas fa-clipboard"></i>
|
<i class="fas fa-clipboard"></i>
|
||||||
<h3>{{ _('No evaluations yet') }}</h3>
|
<h3>{{ _('No evaluations yet') }}</h3>
|
||||||
@@ -106,3 +141,36 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}
|
||||||
|
<style>
|
||||||
|
.view-toggle { display: flex; gap: 8px; }
|
||||||
|
.eval-row { cursor: pointer; }
|
||||||
|
.eval-chevron { transition: transform 0.15s ease; font-size: 0.75rem; }
|
||||||
|
.eval-detail-inner { padding: 8px 4px; }
|
||||||
|
.eval-detail-inner .table { margin-bottom: 0; }
|
||||||
|
.player-nav { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.is-disabled { opacity: 0.5; pointer-events: none; }
|
||||||
|
</style>
|
||||||
|
<script nonce="{{ csp_nonce }}">
|
||||||
|
function togglePlayerEvals(element, event) {
|
||||||
|
if (event.target.closest('a')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var detail = document.getElementById(element.getAttribute('data-target'));
|
||||||
|
if (!detail) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var chevron = element.querySelector('.eval-chevron');
|
||||||
|
var isHidden = detail.classList.contains('hidden');
|
||||||
|
if (isHidden) {
|
||||||
|
detail.classList.remove('hidden');
|
||||||
|
if (chevron) chevron.classList.add('fa-rotate-90');
|
||||||
|
} else {
|
||||||
|
detail.classList.add('hidden');
|
||||||
|
if (chevron) chevron.classList.remove('fa-rotate-90');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
registerActions({ 'toggle-player-evals': togglePlayerEvals });
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
|
|||||||
@@ -10,6 +10,16 @@
|
|||||||
<div class="card mb-4">
|
<div class="card mb-4">
|
||||||
<div class="card-header">
|
<div class="card-header">
|
||||||
<h3><i class="fas fa-users"></i> {{ team.name }}</h3>
|
<h3><i class="fas fa-users"></i> {{ team.name }}</h3>
|
||||||
|
<div class="card-actions">
|
||||||
|
{% if current_user.can_manage_team_matches(team) %}
|
||||||
|
<a href="{{ url_for('team_matches.create_match', team_id=team.id) }}" class="btn btn-sm btn-success" title="{{ _('Schedule Team Match') }}">
|
||||||
|
<i class="fas fa-plus"></i> {{ _('Match') }}
|
||||||
|
</a>
|
||||||
|
<a href="{{ url_for('team_matches.create_match', team_id=team.id, type='practice') }}" class="btn btn-sm btn-info" title="{{ _('Schedule Practice') }}">
|
||||||
|
<i class="fas fa-dumbbell"></i> {{ _('Practice') }}
|
||||||
|
</a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- Staff bar -->
|
<!-- Staff bar -->
|
||||||
<div class="team-staff-bar">
|
<div class="team-staff-bar">
|
||||||
@@ -61,6 +71,9 @@
|
|||||||
<div class="user-mini">
|
<div class="user-mini">
|
||||||
<div class="avatar-sm">{{ entry.player.username[:2] | upper }}</div>
|
<div class="avatar-sm">{{ entry.player.username[:2] | upper }}</div>
|
||||||
<a href="{{ url_for('users.view_user', user_id=entry.player.id) }}">{{ entry.player.username }}</a>
|
<a href="{{ url_for('users.view_user', user_id=entry.player.id) }}">{{ entry.player.username }}</a>
|
||||||
|
{% if entry.is_team_representative %}
|
||||||
|
<span class="badge badge-info" title="{{ _('Team representative') }}">{{ _('Representative') }}</span>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
{% extends "layouts/base.html" %}
|
||||||
|
{% block title %}{{ player.username }} - {{ _('Evaluations') }} - UdeS team manager{% endblock %}
|
||||||
|
{% block page_title %}{{ _('Player Evaluations') }}{% endblock %}
|
||||||
|
{% block breadcrumb %}<span class="breadcrumb">Home / <a href="{{ url_for('evaluations.list_evaluations') }}">{{ _('Evaluations') }}</a> / {{ player.username }}</span>{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="view-toggle mb-3">
|
||||||
|
<a href="{{ url_for('evaluations.list_evaluations') }}" class="btn btn-sm btn-outline">
|
||||||
|
<i class="fas fa-table"></i> {{ _('Table') }}
|
||||||
|
</a>
|
||||||
|
<a href="{{ url_for('evaluations.player_evaluations', player_id=player.id) }}" class="btn btn-sm btn-primary">
|
||||||
|
<i class="fas fa-user"></i> {{ _('By player') }}
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card mb-4">
|
||||||
|
<div class="card-header">
|
||||||
|
<h3><i class="fas fa-user"></i> {{ player.username }}</h3>
|
||||||
|
<div class="player-nav">
|
||||||
|
{% if prev_player %}
|
||||||
|
<a href="{{ url_for('evaluations.player_evaluations', player_id=prev_player.id) }}" class="btn btn-sm btn-secondary" title="{{ prev_player.username }}">
|
||||||
|
<i class="fas fa-chevron-left"></i> {{ prev_player.username }}
|
||||||
|
</a>
|
||||||
|
{% else %}
|
||||||
|
<span class="btn btn-sm btn-secondary is-disabled" aria-disabled="true"><i class="fas fa-chevron-left"></i></span>
|
||||||
|
{% endif %}
|
||||||
|
{% if next_player %}
|
||||||
|
<a href="{{ url_for('evaluations.player_evaluations', player_id=next_player.id) }}" class="btn btn-sm btn-secondary" title="{{ next_player.username }}">
|
||||||
|
{{ next_player.username }} <i class="fas fa-chevron-right"></i>
|
||||||
|
</a>
|
||||||
|
{% else %}
|
||||||
|
<span class="btn btn-sm btn-secondary is-disabled" aria-disabled="true"><i class="fas fa-chevron-right"></i></span>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="stats-grid mb-4">
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-icon bg-info"><i class="fas fa-star"></i></div>
|
||||||
|
<div class="stat-info">
|
||||||
|
<h3>{{ combined_average | round(1) if combined_average is not none else '-' }}</h3>
|
||||||
|
<p>{{ _('Combined average') }} · {{ evaluation_count }} {{ _('evaluations') }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% for label, avg in criterion_averages %}
|
||||||
|
<div class="stat-card stat-card-sm">
|
||||||
|
<div class="stat-icon bg-info"><i class="fas fa-chart-bar"></i></div>
|
||||||
|
<div class="stat-info">
|
||||||
|
<h3>{{ avg | round(1) if avg is not none else '-' }}</h3>
|
||||||
|
<p>{{ label }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="table-container">
|
||||||
|
<table class="table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>{{ _('Evaluator') }}</th>
|
||||||
|
<th>{{ _('Tryout') }}</th>
|
||||||
|
{% for field, label in evaluation_criteria %}
|
||||||
|
<th>{{ label }}</th>
|
||||||
|
{% endfor %}
|
||||||
|
<th>{{ _('Overall') }}</th>
|
||||||
|
<th>{{ _('Position') }}</th>
|
||||||
|
<th>{{ _('Date') }}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for ev in evaluations %}
|
||||||
|
<tr>
|
||||||
|
<td>{{ ev.evaluator.username if ev.evaluator else _('Deleted evaluator') }}</td>
|
||||||
|
<td>{{ ev.tryout.title if ev.tryout else _('Deleted tryout') }}</td>
|
||||||
|
{% for score in ev.scores %}
|
||||||
|
<td>{{ score if score is not none else '-' }}</td>
|
||||||
|
{% endfor %}
|
||||||
|
<td><span class="score">{{ ev.overall | round(1) if ev.overall is not none else '-' }}</span></td>
|
||||||
|
<td>{{ ev.position or '-' }}</td>
|
||||||
|
<td>{{ ev.date.strftime('%m/%d/%Y') if ev.date else '-' }}</td>
|
||||||
|
</tr>
|
||||||
|
{% else %}
|
||||||
|
<tr>
|
||||||
|
<td colspan="{{ evaluation_criteria | length + 5 }}" class="text-center">
|
||||||
|
<div class="empty-state">
|
||||||
|
<i class="fas fa-clipboard"></i>
|
||||||
|
<h3>{{ _('No evaluations for this player yet') }}</h3>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if evaluations %}
|
||||||
|
{% set comment_evals = evaluations | selectattr('comment') | list %}
|
||||||
|
<div class="card mt-4">
|
||||||
|
<div class="card-header">
|
||||||
|
<h3><i class="fas fa-comments"></i> {{ _('Comments') }}</h3>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
{% if comment_evals %}
|
||||||
|
<div class="eval-comments">
|
||||||
|
{% for ev in comment_evals %}
|
||||||
|
<article class="eval-comment">
|
||||||
|
<p class="eval-comment-text">{{ ev.comment }}</p>
|
||||||
|
<footer class="eval-comment-meta">
|
||||||
|
<span class="eval-comment-author">{{ _('Evaluator') }} : <strong>{{ ev.evaluator.username if ev.evaluator else _('Deleted evaluator') }}</strong></span>
|
||||||
|
<span class="eval-comment-context">{{ ev.tryout.title if ev.tryout else _('Deleted tryout') }} · {{ ev.date.strftime('%m/%d/%Y') if ev.date else '-' }}</span>
|
||||||
|
</footer>
|
||||||
|
</article>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="empty-state">
|
||||||
|
<i class="fas fa-comments"></i>
|
||||||
|
<h3>{{ _('No comments') }}</h3>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block scripts %}
|
||||||
|
<style>
|
||||||
|
.view-toggle { display: flex; gap: 8px; }
|
||||||
|
.player-nav { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.is-disabled { opacity: 0.5; pointer-events: none; }
|
||||||
|
</style>
|
||||||
|
{% endblock %}
|
||||||
@@ -93,7 +93,7 @@
|
|||||||
<span class="badge badge-{{ m.status }}">{{ m.status }}</span>
|
<span class="badge badge-{{ m.status }}">{{ m.status }}</span>
|
||||||
</td>
|
</td>
|
||||||
<td class="eval-actions">
|
<td class="eval-actions">
|
||||||
{% set can_manage_this = (current_user.role in ['admin', 'manager']) or (current_user.role == 'coach' and m.org_team.coaches.filter_by(id=current_user.id).first()) or (current_user.role == 'coach' and m.org_team.coach_id == current_user.id) %}
|
{% set can_manage_this = current_user.can_manage_team_matches(m.org_team) %}
|
||||||
{% if can_manage_this %}
|
{% if can_manage_this %}
|
||||||
<a href="{{ url_for('team_matches.edit_match', match_id=m.id) }}" class="btn btn-sm btn-outline" title="{{ _('Edit Match') }}">
|
<a href="{{ url_for('team_matches.edit_match', match_id=m.id) }}" class="btn btn-sm btn-outline" title="{{ _('Edit Match') }}">
|
||||||
<i class="fas fa-edit"></i>
|
<i class="fas fa-edit"></i>
|
||||||
|
|||||||
@@ -127,7 +127,7 @@
|
|||||||
<a href="{{ url_for('team_matches.list_matches') }}?team_id={{ team.id }}" class="btn btn-sm btn-outline" title="{{ _('View Team Matches') }}">
|
<a href="{{ url_for('team_matches.list_matches') }}?team_id={{ team.id }}" class="btn btn-sm btn-outline" title="{{ _('View Team Matches') }}">
|
||||||
<i class="fas fa-futbol"></i> {{ _('Matches') }}
|
<i class="fas fa-futbol"></i> {{ _('Matches') }}
|
||||||
</a>
|
</a>
|
||||||
{% if current_user.can_schedule_matches() and (current_user.role in ['admin', 'manager'] or (current_user.role == 'coach' and team.coaches.filter_by(id=current_user.id).first()) or (current_user.role == 'coach' and team.coach_id == current_user.id)) %}
|
{% if current_user.can_manage_team_matches(team) %}
|
||||||
<a href="{{ url_for('team_matches.create_match', team_id=team.id) }}" class="btn btn-sm btn-success" title="{{ _('Schedule Team Match') }}">
|
<a href="{{ url_for('team_matches.create_match', team_id=team.id) }}" class="btn btn-sm btn-success" title="{{ _('Schedule Team Match') }}">
|
||||||
<i class="fas fa-plus"></i> {{ _('Match') }}
|
<i class="fas fa-plus"></i> {{ _('Match') }}
|
||||||
</a>
|
</a>
|
||||||
@@ -159,6 +159,9 @@
|
|||||||
<div class="user-mini">
|
<div class="user-mini">
|
||||||
<div class="avatar-sm">{{ entry.player.username[:2] | upper }}</div>
|
<div class="avatar-sm">{{ entry.player.username[:2] | upper }}</div>
|
||||||
<a href="{{ url_for('users.view_user', user_id=entry.player.id) }}">{{ entry.player.username }}</a>
|
<a href="{{ url_for('users.view_user', user_id=entry.player.id) }}">{{ entry.player.username }}</a>
|
||||||
|
{% if entry.is_team_representative %}
|
||||||
|
<span class="badge badge-info" title="{{ _('Team representative') }}">{{ _('Representative') }}</span>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
@@ -180,6 +183,16 @@
|
|||||||
<td>{{ entry.player.phone or '-' }}</td>
|
<td>{{ entry.player.phone or '-' }}</td>
|
||||||
{% if can_manage_team %}
|
{% if can_manage_team %}
|
||||||
<td>
|
<td>
|
||||||
|
{% if current_user.can_designate_team_representative() %}
|
||||||
|
<button type="button"
|
||||||
|
class="btn btn-sm representative-toggle-btn {% if entry.is_team_representative %}btn-warning{% else %}btn-outline{% endif %}"
|
||||||
|
data-team-id="{{ team.id }}"
|
||||||
|
data-player-id="{{ entry.player.id }}"
|
||||||
|
data-action="toggle-representative"
|
||||||
|
title="{{ _('Name as team representative') }}">
|
||||||
|
<i class="fas fa-star"></i>
|
||||||
|
</button>
|
||||||
|
{% endif %}
|
||||||
<form method="POST" data-ajax action="{{ url_for('teams.remove_player', team_id=team.id, player_id=entry.player.id) }}" class="inline-form" data-confirm="{{ _('Remove %(player)s from %(team)s?', player=entry.player.username, team=team.name) }}">
|
<form method="POST" data-ajax action="{{ url_for('teams.remove_player', team_id=team.id, player_id=entry.player.id) }}" class="inline-form" data-confirm="{{ _('Remove %(player)s from %(team)s?', player=entry.player.username, team=team.name) }}">
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
|
||||||
<button type="submit" class="btn btn-sm btn-danger">
|
<button type="submit" class="btn btn-sm btn-danger">
|
||||||
@@ -341,6 +354,35 @@ function toggleStatus(btn) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toggleRepresentative(btn) {
|
||||||
|
var teamId = btn.getAttribute('data-team-id');
|
||||||
|
var playerId = btn.getAttribute('data-player-id');
|
||||||
|
|
||||||
|
fetch('/teams/' + teamId + '/toggle_representative/' + playerId, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'X-CSRFToken': '{{ csrf_token() }}',
|
||||||
|
'Content-Type': 'application/json'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then(function(response) { return response.json(); })
|
||||||
|
.then(function(data) {
|
||||||
|
if (data.success) {
|
||||||
|
if (data.is_team_representative) {
|
||||||
|
btn.classList.remove('btn-outline');
|
||||||
|
btn.classList.add('btn-warning');
|
||||||
|
} else {
|
||||||
|
btn.classList.remove('btn-warning');
|
||||||
|
btn.classList.add('btn-outline');
|
||||||
|
}
|
||||||
|
window.TT.refreshPage(window.location.pathname);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(function(error) {
|
||||||
|
console.error('Error:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
var currentEditTeamId = null;
|
var currentEditTeamId = null;
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
@@ -416,6 +458,7 @@ registerActions({
|
|||||||
'hide-create-form': hideCreateForm,
|
'hide-create-form': hideCreateForm,
|
||||||
'hide-edit-form': hideEditForm,
|
'hide-edit-form': hideEditForm,
|
||||||
'toggle-status': toggleStatus,
|
'toggle-status': toggleStatus,
|
||||||
|
'toggle-representative': toggleRepresentative,
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
Binary file not shown.
@@ -1826,9 +1826,16 @@ msgid "Enter position (optional)"
|
|||||||
msgstr "Enter position (optional)"
|
msgstr "Enter position (optional)"
|
||||||
|
|
||||||
#: app/templates/pages/evaluate_player.html:121
|
#: app/templates/pages/evaluate_player.html:121
|
||||||
|
#: app/templates/pages/player_evaluations.html
|
||||||
|
#: app/templates/pages/evaluations.html
|
||||||
msgid "Comments"
|
msgid "Comments"
|
||||||
msgstr "Comments"
|
msgstr "Comments"
|
||||||
|
|
||||||
|
#: app/templates/pages/player_evaluations.html
|
||||||
|
#: app/templates/pages/evaluations.html
|
||||||
|
msgid "No comments"
|
||||||
|
msgstr "No comments"
|
||||||
|
|
||||||
#: app/templates/pages/evaluate_player.html:122
|
#: app/templates/pages/evaluate_player.html:122
|
||||||
msgid "Enter your evaluation notes..."
|
msgid "Enter your evaluation notes..."
|
||||||
msgstr "Enter your evaluation notes..."
|
msgstr "Enter your evaluation notes..."
|
||||||
@@ -3040,6 +3047,18 @@ msgstr "View Profile"
|
|||||||
msgid "Availability"
|
msgid "Availability"
|
||||||
msgstr "Availability"
|
msgstr "Availability"
|
||||||
|
|
||||||
|
#: app/templates/pages/my_teams.html:65 app/templates/pages/teams.html:163
|
||||||
|
msgid "Representative"
|
||||||
|
msgstr "Representative"
|
||||||
|
|
||||||
|
#: app/templates/pages/my_teams.html:65 app/templates/pages/teams.html:163
|
||||||
|
msgid "Team representative"
|
||||||
|
msgstr "Team representative"
|
||||||
|
|
||||||
|
#: app/templates/pages/teams.html:192
|
||||||
|
msgid "Name as team representative"
|
||||||
|
msgstr "Name as team representative"
|
||||||
|
|
||||||
#~ msgid "×"
|
#~ msgid "×"
|
||||||
#~ msgstr "×"
|
#~ msgstr "×"
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -1836,9 +1836,16 @@ msgid "Enter position (optional)"
|
|||||||
msgstr "Saisir un poste (facultatif)"
|
msgstr "Saisir un poste (facultatif)"
|
||||||
|
|
||||||
#: app/templates/pages/evaluate_player.html:121
|
#: app/templates/pages/evaluate_player.html:121
|
||||||
|
#: app/templates/pages/player_evaluations.html
|
||||||
|
#: app/templates/pages/evaluations.html
|
||||||
msgid "Comments"
|
msgid "Comments"
|
||||||
msgstr "Commentaires"
|
msgstr "Commentaires"
|
||||||
|
|
||||||
|
#: app/templates/pages/player_evaluations.html
|
||||||
|
#: app/templates/pages/evaluations.html
|
||||||
|
msgid "No comments"
|
||||||
|
msgstr "Aucun commentaire"
|
||||||
|
|
||||||
#: app/templates/pages/evaluate_player.html:122
|
#: app/templates/pages/evaluate_player.html:122
|
||||||
msgid "Enter your evaluation notes..."
|
msgid "Enter your evaluation notes..."
|
||||||
msgstr "Vos notes d’évaluation..."
|
msgstr "Vos notes d’évaluation..."
|
||||||
@@ -3063,6 +3070,18 @@ msgstr "Voir le profil"
|
|||||||
msgid "Availability"
|
msgid "Availability"
|
||||||
msgstr "Disponibilités"
|
msgstr "Disponibilités"
|
||||||
|
|
||||||
|
#: app/templates/pages/my_teams.html:65 app/templates/pages/teams.html:163
|
||||||
|
msgid "Representative"
|
||||||
|
msgstr "Responsable"
|
||||||
|
|
||||||
|
#: app/templates/pages/my_teams.html:65 app/templates/pages/teams.html:163
|
||||||
|
msgid "Team representative"
|
||||||
|
msgstr "Responsable d’équipe"
|
||||||
|
|
||||||
|
#: app/templates/pages/teams.html:192
|
||||||
|
msgid "Name as team representative"
|
||||||
|
msgstr "Nommer comme responsable d’équipe"
|
||||||
|
|
||||||
#~ msgid "×"
|
#~ msgid "×"
|
||||||
#~ msgstr "×"
|
#~ msgstr "×"
|
||||||
|
|
||||||
|
|||||||
@@ -128,3 +128,18 @@ Générer la migration initiale depuis les modèles « pour avancer en
|
|||||||
attendant ». Ça produit un dépôt qui a l'air d'avoir des migrations, une
|
attendant ». Ça produit un dépôt qui a l'air d'avoir des migrations, une
|
||||||
production estampillée sur un état qu'elle n'a pas, et la dérive préservée
|
production estampillée sur un état qu'elle n'a pas, et la dérive préservée
|
||||||
sous une couche de plus.
|
sous une couche de plus.
|
||||||
|
|
||||||
|
## Ajouts de colonnes faits à la main
|
||||||
|
|
||||||
|
En attendant Alembic, une colonne ajoutée à un modèle doit être rattrapée sur
|
||||||
|
les bases existantes par un script, en plus du modèle (pour les installations
|
||||||
|
neuves, via `create_all()`). `migrations/add_tryout_coaches.py` a ouvert la
|
||||||
|
voie ; `migrations/add_team_representative.py` ajoute
|
||||||
|
`team_players.is_team_representative` de la même façon : lecture du catalogue,
|
||||||
|
`ALTER TABLE ... ADD COLUMN` idempotent, rien si la colonne est déjà là.
|
||||||
|
|
||||||
|
Le script trouve sa base tout seul : `DATABASE_URL` s'il est défini (production,
|
||||||
|
CI), sinon les valeurs `LOCAL_PG*` de `app/.env` — le serveur de développement
|
||||||
|
est réutilisé s'il répond, sinon (re)démarré puis arrêté à la fin du script :
|
||||||
|
|
||||||
|
python migrations/add_team_representative.py
|
||||||
|
|||||||
@@ -64,6 +64,31 @@ voulue, elle n'est écrite nulle part ailleurs qu'ici.
|
|||||||
| Coach | rattaché à l'équipe, par la relation m2m **ou** par la colonne héritée |
|
| Coach | rattaché à l'équipe, par la relation m2m **ou** par la colonne héritée |
|
||||||
| Recruteur, Joueur | toujours faux |
|
| Recruteur, Joueur | toujours faux |
|
||||||
|
|
||||||
|
### `can_manage_team_matches(team)`
|
||||||
|
|
||||||
|
Plus étroite que `can_manage_this_org_team`, et c'est voulu : elle répond à
|
||||||
|
« peut-on gérer les matchs et les entraînements de cette équipe ? ».
|
||||||
|
|
||||||
|
| Rôle | Règle |
|
||||||
|
|---|---|
|
||||||
|
| Président, Gérant | toujours vrai |
|
||||||
|
| Coach | rattaché à l'équipe (m2m **ou** colonne héritée) |
|
||||||
|
| Joueur responsable | vrai pour **sa seule** équipe |
|
||||||
|
| Recruteur, Joueur | faux |
|
||||||
|
|
||||||
|
### Le joueur responsable
|
||||||
|
|
||||||
|
Un **joueur responsable** est un joueur qu'un **président** désigne, depuis la
|
||||||
|
page Équipes, sur la ligne de son équipe (étoile à côté du bouton de retrait).
|
||||||
|
Il peut planifier, modifier et supprimer les **matchs et entraînements** de
|
||||||
|
cette équipe, et rien d'autre : ni l'effectif, ni les notes, ni le statut
|
||||||
|
partant/remplaçant, qui restent réservés au personnel.
|
||||||
|
|
||||||
|
Le drapeau vit sur `team_players.is_team_representative` (voir
|
||||||
|
`docs/database-schema.md`). La désignation est la décision du président —
|
||||||
|
`can_designate_team_representative()`, vrai seulement pour `Admin` — pour
|
||||||
|
qu'un responsable ne puisse pas se reproduire lui-même.
|
||||||
|
|
||||||
## Le piège : deux façons d'être rattaché
|
## Le piège : deux façons d'être rattaché
|
||||||
|
|
||||||
C'est le point le plus coûteux de tout le modèle d'autorisation, et il est
|
C'est le point le plus coûteux de tout le modèle d'autorisation, et il est
|
||||||
@@ -117,6 +142,9 @@ contexte de requête.
|
|||||||
| `attached_org_teams(user)` | Les équipes auxquelles cette personne est rattachée, quel que soit son rôle |
|
| `attached_org_teams(user)` | Les équipes auxquelles cette personne est rattachée, quel que soit son rôle |
|
||||||
| `visible_org_teams(user)` | Ce qu'elle a le droit de voir |
|
| `visible_org_teams(user)` | Ce qu'elle a le droit de voir |
|
||||||
| `can_manage_org_team(user, team)` | Peut-elle administrer cette équipe |
|
| `can_manage_org_team(user, team)` | Peut-elle administrer cette équipe |
|
||||||
|
| `can_manage_team_matches(user, team)` | Peut-elle gérer les matchs et entraînements de cette équipe |
|
||||||
|
| `is_team_representative(user, team)` | Est-elle le responsable désigné de cette équipe |
|
||||||
|
| `representative_org_teams(user)` | Les équipes dont elle est le responsable |
|
||||||
| `coach_player_ids(coach)` | Les joueurs qu'il encadre |
|
| `coach_player_ids(coach)` | Les joueurs qu'il encadre |
|
||||||
| `coach_can_access_player(coach, id)` | Peut-il lire la fiche de ce joueur |
|
| `coach_can_access_player(coach, id)` | Peut-il lire la fiche de ce joueur |
|
||||||
| `can_manage_player_contract(user, id)` | Peut-elle déposer un contrat pour lui |
|
| `can_manage_player_contract(user, id)` | Peut-elle déposer un contrat pour lui |
|
||||||
|
|||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""Migration: add the `is_team_representative` flag to `team_players`.
|
||||||
|
|
||||||
|
A team's responsible ("joueur responsable") is a player an admin names to
|
||||||
|
manage that team's matches and practices. The flag lives on the roster row,
|
||||||
|
beside `status` and `position`.
|
||||||
|
|
||||||
|
`db.create_all()` creates missing tables and never alters an existing one, so
|
||||||
|
a database that already has `team_players` needs this script. Fresh installs
|
||||||
|
get the column from the model.
|
||||||
|
|
||||||
|
Where it connects
|
||||||
|
-----------------
|
||||||
|
The script finds its own database, so there is no URL to remember:
|
||||||
|
|
||||||
|
1. If `DATABASE_URL` is already set, it is used and nothing else is touched.
|
||||||
|
That is the production and CI path.
|
||||||
|
2. Otherwise the local values from `app/.env` are used. If the development
|
||||||
|
server in `instance/pgdata/` answers a connection it is reused as-is; if it
|
||||||
|
does not, it is (re)started and stopped again when this script exits. This
|
||||||
|
is the `LOCAL_PG=true` block of `app/.env.example`.
|
||||||
|
3. If neither is available the script explains what to set and stops.
|
||||||
|
|
||||||
|
So a laptop with the `LOCAL_PG=true` block runs the migration with a single
|
||||||
|
command:
|
||||||
|
|
||||||
|
python migrations/add_team_representative.py
|
||||||
|
|
||||||
|
Usage: python migrations/add_team_representative.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, PROJECT_ROOT)
|
||||||
|
|
||||||
|
# Loaded before anything else reads the environment: app.local_postgres reads
|
||||||
|
# LOCAL_PG_PORT / LOCAL_PG_USER / LOCAL_PG_DATABASE at import time, and without
|
||||||
|
# this they would fall back to that module's defaults instead of app/.env.
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
_ENV_FILE = os.path.join(PROJECT_ROOT, 'app', '.env')
|
||||||
|
load_dotenv(_ENV_FILE if os.path.exists(_ENV_FILE) else None)
|
||||||
|
|
||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from app.extensions import db
|
||||||
|
|
||||||
|
|
||||||
|
def _local_database():
|
||||||
|
"""The development URL and port, read from the LOCAL_PG_* variables."""
|
||||||
|
from app.local_postgres import DATABASE_URL, PORT
|
||||||
|
|
||||||
|
return DATABASE_URL, PORT
|
||||||
|
|
||||||
|
|
||||||
|
def _postgres_answers(url):
|
||||||
|
"""Whether `url` is a working PostgreSQL connection right now.
|
||||||
|
|
||||||
|
A bare TCP probe is not enough here: a server killed part-way through its
|
||||||
|
startup can leave the port listening while every connection is refused,
|
||||||
|
and trusting that evidence fails the migration for a reason that looks
|
||||||
|
nothing like its cause.
|
||||||
|
"""
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
|
||||||
|
from app.app import normalise_database_url
|
||||||
|
|
||||||
|
try:
|
||||||
|
engine = create_engine(
|
||||||
|
normalise_database_url(url), connect_args={'connect_timeout': 2}
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
with engine.connect():
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def _stop_local_server():
|
||||||
|
"""Fast-stop the local development server, if a postmaster is alive.
|
||||||
|
|
||||||
|
Called only before (re)starting it: `pg_ctl status` calls a half-dead
|
||||||
|
postmaster "running", so `start()` would leave the broken one in place.
|
||||||
|
"""
|
||||||
|
from app.local_postgres import DATADIR, _find_binary
|
||||||
|
|
||||||
|
pg_ctl = _find_binary('pg_ctl')
|
||||||
|
if not pg_ctl:
|
||||||
|
return
|
||||||
|
subprocess.run(
|
||||||
|
[str(pg_ctl), 'stop', '-m', 'fast', '-D', str(DATADIR)],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_database_url():
|
||||||
|
"""Pick the database to migrate.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
tuple[str, str]: the connection URL and a note saying where it came
|
||||||
|
from, for the log line.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
SystemExit: when neither a URL nor a usable local server is available.
|
||||||
|
"""
|
||||||
|
explicit = os.environ.get('DATABASE_URL')
|
||||||
|
if explicit:
|
||||||
|
return explicit, 'DATABASE_URL'
|
||||||
|
|
||||||
|
url, port = _local_database()
|
||||||
|
if _postgres_answers(url):
|
||||||
|
return url, f'local PostgreSQL already running on port {port}'
|
||||||
|
|
||||||
|
if os.getenv('LOCAL_PG', '').strip().lower() == 'true':
|
||||||
|
from app.local_postgres import start
|
||||||
|
|
||||||
|
_stop_local_server()
|
||||||
|
return start(), f'local PostgreSQL started on port {port}'
|
||||||
|
|
||||||
|
raise SystemExit(
|
||||||
|
'No database to migrate.\n'
|
||||||
|
' Set DATABASE_URL to a connection string, or set LOCAL_PG=true in\n'
|
||||||
|
' app/.env to use the local development server (see app/.env.example,\n'
|
||||||
|
' DEVELOPMENT block).'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# A migration must never start the Discord bot: two instances fight over
|
||||||
|
# the same gateway session, and neither belongs to a script whose only job
|
||||||
|
# is to run an ALTER.
|
||||||
|
os.environ['ENABLE_DISCORD_BOT'] = 'false'
|
||||||
|
|
||||||
|
url, source = resolve_database_url()
|
||||||
|
os.environ['DATABASE_URL'] = url
|
||||||
|
|
||||||
|
# Imported here, after the environment is settled, so create_app() reads
|
||||||
|
# the URL this script resolved rather than a missing one.
|
||||||
|
from app.app import create_app
|
||||||
|
|
||||||
|
print(f'[INFO] Database: {source}.')
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
with app.app_context():
|
||||||
|
already_there = db.session.execute(
|
||||||
|
text(
|
||||||
|
"SELECT 1 FROM information_schema.columns "
|
||||||
|
"WHERE table_name = 'team_players' "
|
||||||
|
"AND column_name = 'is_team_representative'"
|
||||||
|
)
|
||||||
|
).scalar()
|
||||||
|
|
||||||
|
if already_there:
|
||||||
|
print("Column 'team_players.is_team_representative' already exists. Skipping.")
|
||||||
|
return
|
||||||
|
|
||||||
|
db.session.execute(
|
||||||
|
text(
|
||||||
|
"ALTER TABLE team_players "
|
||||||
|
"ADD COLUMN is_team_representative BOOLEAN NOT NULL DEFAULT FALSE"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
print("Added 'team_players.is_team_representative'.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -179,3 +179,61 @@ class TestThroughTheForm:
|
|||||||
evaluation = Evaluation.query.one()
|
evaluation = Evaluation.query.one()
|
||||||
assert evaluation.mecanics_score is None
|
assert evaluation.mecanics_score is None
|
||||||
assert evaluation.overall_score == 4
|
assert evaluation.overall_score == 4
|
||||||
|
|
||||||
|
|
||||||
|
class TestBatchEvaluate:
|
||||||
|
"""The batch page drives the same two helpers the single-player form does,
|
||||||
|
through ``{field}_{player_id}`` names. The helpers were lost once, in a
|
||||||
|
refactor, and the page 500'd on every POST until someone noticed."""
|
||||||
|
|
||||||
|
def _submit(self, client, setup, **fields):
|
||||||
|
data = {'player_ids': [str(setup['player_id'])]}
|
||||||
|
data.update(fields)
|
||||||
|
return client.post(
|
||||||
|
f'/evaluations/{setup["tryout_id"]}/batch',
|
||||||
|
data=data,
|
||||||
|
follow_redirects=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_a_valid_batch_evaluation_is_stored(self, app, client, evaluation_setup):
|
||||||
|
pid = evaluation_setup['player_id']
|
||||||
|
self._submit(
|
||||||
|
client,
|
||||||
|
evaluation_setup,
|
||||||
|
**{
|
||||||
|
f'mecanics_score_{pid}': '8',
|
||||||
|
f'mental_score_{pid}': '6',
|
||||||
|
f'comments_{pid}': 'Solid.',
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
evaluation = Evaluation.query.one()
|
||||||
|
assert evaluation.mecanics_score == 8
|
||||||
|
assert evaluation.overall_score == 7
|
||||||
|
assert evaluation.comments == 'Solid.'
|
||||||
|
assert evaluation.position_recommendation is None
|
||||||
|
|
||||||
|
def test_an_out_of_range_batch_score_stores_nothing(self, app, client, evaluation_setup):
|
||||||
|
pid = evaluation_setup['player_id']
|
||||||
|
self._submit(
|
||||||
|
client,
|
||||||
|
evaluation_setup,
|
||||||
|
**{f'mecanics_score_{pid}': '11', f'mental_score_{pid}': '6'},
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
assert Evaluation.query.count() == 0
|
||||||
|
|
||||||
|
def test_a_second_batch_submission_replaces_the_first(self, app, client, evaluation_setup):
|
||||||
|
pid = evaluation_setup['player_id']
|
||||||
|
self._submit(
|
||||||
|
client, evaluation_setup, **{f'mecanics_score_{pid}': '8', f'mental_score_{pid}': '4'}
|
||||||
|
)
|
||||||
|
self._submit(
|
||||||
|
client, evaluation_setup, **{f'mecanics_score_{pid}': '4', f'mental_score_{pid}': '4'}
|
||||||
|
)
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
evaluation = Evaluation.query.one()
|
||||||
|
assert evaluation.overall_score == 4
|
||||||
|
|||||||
@@ -0,0 +1,248 @@
|
|||||||
|
"""Player-specific evaluation views (the "By player" toggle and its page).
|
||||||
|
|
||||||
|
These pages regroup the flat evaluation table by player: one row per player in
|
||||||
|
the table view, and a dedicated page per player with left/right navigation and
|
||||||
|
per-criterion averages. Visibility follows the viewer's role — managers and
|
||||||
|
coaches see staff-authored evaluations inside their own tryouts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import Evaluation, Tryout
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def staff_setup(app, as_role, make_user):
|
||||||
|
"""A coach who manages one tryout, plus staff, a player, and a foreign tryout."""
|
||||||
|
coach_id = as_role('coach', username='viewer_coach')
|
||||||
|
manager_id = make_user('manager', username='other_manager')
|
||||||
|
admin_id = make_user('admin', username='the_admin')
|
||||||
|
player_id = make_user('player', username='the_player')
|
||||||
|
outsider_id = make_user('coach', username='outsider_coach')
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
tryout = Tryout(
|
||||||
|
title='Spring',
|
||||||
|
game='Valorant',
|
||||||
|
date=date(2030, 4, 1),
|
||||||
|
created_by=coach_id,
|
||||||
|
coach_id=coach_id,
|
||||||
|
)
|
||||||
|
db.session.add(tryout)
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
other_tryout = Tryout(
|
||||||
|
title='Other',
|
||||||
|
game='Valorant',
|
||||||
|
date=date(2030, 5, 1),
|
||||||
|
created_by=outsider_id,
|
||||||
|
)
|
||||||
|
db.session.add(other_tryout)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
'coach_id': coach_id,
|
||||||
|
'manager_id': manager_id,
|
||||||
|
'admin_id': admin_id,
|
||||||
|
'player_id': player_id,
|
||||||
|
'tryout_id': tryout.id,
|
||||||
|
'other_tryout_id': other_tryout.id,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestVisibility:
|
||||||
|
def test_coach_sees_staff_evaluations_only_in_their_tryout(self, app, client, staff_setup):
|
||||||
|
with app.app_context():
|
||||||
|
db.session.add(
|
||||||
|
Evaluation(
|
||||||
|
tryout_id=staff_setup['tryout_id'],
|
||||||
|
player_id=staff_setup['player_id'],
|
||||||
|
evaluator_id=staff_setup['manager_id'],
|
||||||
|
overall_score=7,
|
||||||
|
comments='manager in own tryout',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.add(
|
||||||
|
Evaluation(
|
||||||
|
tryout_id=staff_setup['tryout_id'],
|
||||||
|
player_id=staff_setup['player_id'],
|
||||||
|
evaluator_id=staff_setup['admin_id'],
|
||||||
|
overall_score=5,
|
||||||
|
comments='admin authored',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.add(
|
||||||
|
Evaluation(
|
||||||
|
tryout_id=staff_setup['other_tryout_id'],
|
||||||
|
player_id=staff_setup['player_id'],
|
||||||
|
evaluator_id=staff_setup['manager_id'],
|
||||||
|
overall_score=9,
|
||||||
|
comments='manager other tryout',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
body = client.get(f"/evaluations/player/{staff_setup['player_id']}").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert 'manager in own tryout' in body
|
||||||
|
assert 'admin authored' not in body
|
||||||
|
assert 'manager other tryout' not in body
|
||||||
|
|
||||||
|
def test_admin_sees_every_evaluation(self, app, client, as_role, make_user):
|
||||||
|
admin_id = as_role('admin', username='boss')
|
||||||
|
coach_id = make_user('coach', username='some_coach')
|
||||||
|
player_id = make_user('player', username='star')
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
tryout = Tryout(
|
||||||
|
title='T',
|
||||||
|
game='Valorant',
|
||||||
|
date=date(2030, 1, 1),
|
||||||
|
created_by=admin_id,
|
||||||
|
)
|
||||||
|
db.session.add(tryout)
|
||||||
|
db.session.flush()
|
||||||
|
db.session.add(
|
||||||
|
Evaluation(
|
||||||
|
tryout_id=tryout.id,
|
||||||
|
player_id=player_id,
|
||||||
|
evaluator_id=coach_id,
|
||||||
|
overall_score=6,
|
||||||
|
comments='coach comment',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.add(
|
||||||
|
Evaluation(
|
||||||
|
tryout_id=tryout.id,
|
||||||
|
player_id=player_id,
|
||||||
|
evaluator_id=admin_id,
|
||||||
|
overall_score=4,
|
||||||
|
comments='admin comment',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
body = client.get(f'/evaluations/player/{player_id}').get_data(as_text=True)
|
||||||
|
|
||||||
|
assert 'coach comment' in body
|
||||||
|
assert 'admin comment' in body
|
||||||
|
|
||||||
|
def test_a_player_cannot_open_the_player_page(self, client, as_role):
|
||||||
|
player_id = as_role('player')
|
||||||
|
response = client.get(f'/evaluations/player/{player_id}', follow_redirects=False)
|
||||||
|
assert response.status_code in (301, 302)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAggregates:
|
||||||
|
def test_combined_and_per_criterion_averages(self, app, client, as_role, make_user):
|
||||||
|
coach_id = as_role('coach', username='agg_coach')
|
||||||
|
coach2_id = make_user('coach', username='agg_coach2')
|
||||||
|
player_id = make_user('player', username='agg_player')
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
tryout = Tryout(
|
||||||
|
title='Agg',
|
||||||
|
game='Valorant',
|
||||||
|
date=date(2030, 1, 1),
|
||||||
|
created_by=coach_id,
|
||||||
|
coach_id=coach_id,
|
||||||
|
)
|
||||||
|
db.session.add(tryout)
|
||||||
|
db.session.flush()
|
||||||
|
first = Evaluation(tryout_id=tryout.id, player_id=player_id, evaluator_id=coach_id)
|
||||||
|
first.apply_scores({'mecanics_score': 8, 'mental_score': 6})
|
||||||
|
second = Evaluation(tryout_id=tryout.id, player_id=player_id, evaluator_id=coach2_id)
|
||||||
|
second.apply_scores({'mecanics_score': 4, 'mental_score': 8})
|
||||||
|
db.session.add_all([first, second])
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
body = client.get(f'/evaluations/player/{player_id}').get_data(as_text=True)
|
||||||
|
|
||||||
|
# overall: (7 + 6) / 2 = 6.5; mecanics: 6.0; mental: 7.0.
|
||||||
|
assert '6.5' in body
|
||||||
|
assert '6.0' in body
|
||||||
|
assert '7.0' in body
|
||||||
|
|
||||||
|
|
||||||
|
class TestNavigation:
|
||||||
|
def test_players_are_ordered_best_first_with_arrows(self, app, client, as_role, make_user):
|
||||||
|
coach_id = as_role('coach', username='order_coach')
|
||||||
|
high = make_user('player', username='zzz_high')
|
||||||
|
mid = make_user('player', username='aaa_mid')
|
||||||
|
low = make_user('player', username='mmm_low')
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
tryout = Tryout(
|
||||||
|
title='Order',
|
||||||
|
game='Valorant',
|
||||||
|
date=date(2030, 1, 1),
|
||||||
|
created_by=coach_id,
|
||||||
|
coach_id=coach_id,
|
||||||
|
)
|
||||||
|
db.session.add(tryout)
|
||||||
|
db.session.flush()
|
||||||
|
for player_id, score in [(high, 8), (mid, 5), (low, 3)]:
|
||||||
|
db.session.add(
|
||||||
|
Evaluation(
|
||||||
|
tryout_id=tryout.id,
|
||||||
|
player_id=player_id,
|
||||||
|
evaluator_id=coach_id,
|
||||||
|
overall_score=score,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
best = client.get(f'/evaluations/player/{high}').get_data(as_text=True)
|
||||||
|
middle = client.get(f'/evaluations/player/{mid}').get_data(as_text=True)
|
||||||
|
worst = client.get(f'/evaluations/player/{low}').get_data(as_text=True)
|
||||||
|
|
||||||
|
# Best: no previous (left arrow disabled), next is the middle player.
|
||||||
|
assert 'aria-disabled="true"' in best
|
||||||
|
assert f'/evaluations/player/{mid}' in best
|
||||||
|
assert f'/evaluations/player/{low}' not in best
|
||||||
|
|
||||||
|
# Middle: both arrows active, pointing at the neighbours.
|
||||||
|
assert f'/evaluations/player/{high}' in middle
|
||||||
|
assert f'/evaluations/player/{low}' in middle
|
||||||
|
assert 'aria-disabled="true"' not in middle
|
||||||
|
|
||||||
|
# Worst: no next (right arrow disabled), previous is the middle player.
|
||||||
|
assert 'aria-disabled="true"' in worst
|
||||||
|
assert f'/evaluations/player/{mid}' in worst
|
||||||
|
assert f'/evaluations/player/{high}' not in worst
|
||||||
|
|
||||||
|
|
||||||
|
class TestTableView:
|
||||||
|
def test_table_groups_by_player_and_keeps_the_comment(self, app, client, as_role, make_user):
|
||||||
|
coach_id = as_role('coach', username='table_coach')
|
||||||
|
player_id = make_user('player', username='table_player')
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
tryout = Tryout(
|
||||||
|
title='T',
|
||||||
|
game='Valorant',
|
||||||
|
date=date(2030, 1, 1),
|
||||||
|
created_by=coach_id,
|
||||||
|
coach_id=coach_id,
|
||||||
|
)
|
||||||
|
db.session.add(tryout)
|
||||||
|
db.session.flush()
|
||||||
|
db.session.add(
|
||||||
|
Evaluation(
|
||||||
|
tryout_id=tryout.id,
|
||||||
|
player_id=player_id,
|
||||||
|
evaluator_id=coach_id,
|
||||||
|
overall_score=7,
|
||||||
|
comments='a distinctive comment',
|
||||||
|
)
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
body = client.get('/evaluations').get_data(as_text=True)
|
||||||
|
|
||||||
|
assert 'table_player' in body
|
||||||
|
assert f'/evaluations/player/{player_id}' in body
|
||||||
|
assert 'a distinctive comment' in body
|
||||||
@@ -69,6 +69,21 @@ class TestNotifying:
|
|||||||
assert [call['reference_id'] for call in sent] == [11, 22]
|
assert [call['reference_id'] for call in sent] == [11, 22]
|
||||||
assert {call['event_date'] for call in sent} == {'2030-04-01'}
|
assert {call['event_date'] for call in sent} == {'2030-04-01'}
|
||||||
assert {call['event_time'] for call in sent} == {'07:00 PM - 09:00 PM'}
|
assert {call['event_time'] for call in sent} == {'07:00 PM - 09:00 PM'}
|
||||||
|
assert {call['change_kind'] for call in sent} == {'scheduled'}
|
||||||
|
|
||||||
|
def test_modified_kind_is_forwarded(self, sent):
|
||||||
|
"""A modified notification carries 'modified' to the bot."""
|
||||||
|
scheduling.notify_participants(
|
||||||
|
title='Scrim',
|
||||||
|
date=date(2030, 4, 1),
|
||||||
|
start_time=time(19, 0),
|
||||||
|
end_time=time(21, 0),
|
||||||
|
participants=[(1, 11)],
|
||||||
|
fallback_id=99,
|
||||||
|
change_kind='modified',
|
||||||
|
)
|
||||||
|
|
||||||
|
assert sent[0]['change_kind'] == 'modified'
|
||||||
|
|
||||||
def test_a_participant_without_a_row_falls_back_to_the_match(self, sent):
|
def test_a_participant_without_a_row_falls_back_to_the_match(self, sent):
|
||||||
"""A Discord reaction resolves the reference back to a record; the
|
"""A Discord reaction resolves the reference back to a record; the
|
||||||
|
|||||||
@@ -0,0 +1,348 @@
|
|||||||
|
"""Team representative ("joueur responsable") — the rule and the routes.
|
||||||
|
|
||||||
|
A player an admin names as their team's responsible may create, edit and
|
||||||
|
delete that team's matches and practices, and nothing else. Designation
|
||||||
|
itself is the president's decision, never the responsible's.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import date, time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import AppSettings, OrgTeam, TeamMatch, TeamPlayer, User
|
||||||
|
from app.permissions import (
|
||||||
|
can_manage_team_matches,
|
||||||
|
is_team_representative,
|
||||||
|
representative_org_teams,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _redirected(response):
|
||||||
|
return response.status_code in (301, 302)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_world(app, make_user):
|
||||||
|
"""Two teams, a responsible on the first, a plain player on it too."""
|
||||||
|
with app.app_context():
|
||||||
|
admin_id = make_user('admin')
|
||||||
|
rep_id = make_user('player')
|
||||||
|
plain_id = make_user('player')
|
||||||
|
|
||||||
|
team = OrgTeam(name='Varsity', created_by=admin_id)
|
||||||
|
other = OrgTeam(name='JV', created_by=admin_id)
|
||||||
|
db.session.add_all([team, other])
|
||||||
|
db.session.flush()
|
||||||
|
|
||||||
|
# Added plain-first on purpose: the roster must still show the
|
||||||
|
# responsible at the top, not last, and a test whose world added the
|
||||||
|
# responsible first would pass without the ordering ever running.
|
||||||
|
db.session.add_all(
|
||||||
|
[
|
||||||
|
TeamPlayer(player_id=plain_id, org_team_id=team.id),
|
||||||
|
TeamPlayer(player_id=rep_id, org_team_id=team.id, is_team_representative=True),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# create/delete matches are gated on the season for non-presidents,
|
||||||
|
# and the responsible is one of them.
|
||||||
|
AppSettings.set_bool('season_active', True)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'admin': admin_id,
|
||||||
|
'rep': rep_id,
|
||||||
|
'plain': plain_id,
|
||||||
|
'team': team.id,
|
||||||
|
'other': other.id,
|
||||||
|
'rep_username': db.session.get(User, rep_id).username,
|
||||||
|
'plain_username': db.session.get(User, plain_id).username,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _make_match(app, world, title, team_key='team'):
|
||||||
|
with app.app_context():
|
||||||
|
match = TeamMatch(
|
||||||
|
org_team_id=world[team_key],
|
||||||
|
title=title,
|
||||||
|
date=date(2026, 10, 1),
|
||||||
|
start_time=time(10, 0),
|
||||||
|
end_time=time(11, 0),
|
||||||
|
created_by=world['admin'],
|
||||||
|
)
|
||||||
|
db.session.add(match)
|
||||||
|
db.session.commit()
|
||||||
|
return match.id
|
||||||
|
|
||||||
|
|
||||||
|
def _login_as(client, login, username):
|
||||||
|
"""Switch the test client to another existing account."""
|
||||||
|
client.post('/auth/logout', follow_redirects=False)
|
||||||
|
response = login(username)
|
||||||
|
assert _redirected(response), f'could not log in as {username}'
|
||||||
|
|
||||||
|
|
||||||
|
class TestTheRule:
|
||||||
|
"""The permission itself, without a request in the way."""
|
||||||
|
|
||||||
|
def test_a_rep_manages_their_team(self, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
with app.app_context():
|
||||||
|
rep = db.session.get(User, world['rep'])
|
||||||
|
team = db.session.get(OrgTeam, world['team'])
|
||||||
|
|
||||||
|
assert is_team_representative(rep, team) is True
|
||||||
|
assert can_manage_team_matches(rep, team) is True
|
||||||
|
assert rep.can_manage_team_matches(team) is True
|
||||||
|
|
||||||
|
def test_a_rep_manages_no_other_team(self, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
with app.app_context():
|
||||||
|
rep = db.session.get(User, world['rep'])
|
||||||
|
other = db.session.get(OrgTeam, world['other'])
|
||||||
|
|
||||||
|
assert is_team_representative(rep, other) is False
|
||||||
|
assert can_manage_team_matches(rep, other) is False
|
||||||
|
|
||||||
|
def test_a_rep_is_not_a_roster_manager(self, app, make_user):
|
||||||
|
"""Match rights only: the roster stays staff-only."""
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
with app.app_context():
|
||||||
|
rep = db.session.get(User, world['rep'])
|
||||||
|
team = db.session.get(OrgTeam, world['team'])
|
||||||
|
|
||||||
|
assert rep.can_manage_this_org_team(team) is False
|
||||||
|
assert rep.can_manage_teams() is False
|
||||||
|
assert rep.can_schedule_matches() is False
|
||||||
|
|
||||||
|
def test_a_plain_player_manages_nothing(self, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
with app.app_context():
|
||||||
|
plain = db.session.get(User, world['plain'])
|
||||||
|
team = db.session.get(OrgTeam, world['team'])
|
||||||
|
|
||||||
|
assert can_manage_team_matches(plain, team) is False
|
||||||
|
|
||||||
|
def test_representative_org_teams_is_scoped(self, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
with app.app_context():
|
||||||
|
rep = db.session.get(User, world['rep'])
|
||||||
|
assert [team.id for team in representative_org_teams(rep)] == [world['team']]
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('role', ['admin', 'manager', 'coach', 'player', 'scout'])
|
||||||
|
def test_only_the_president_may_designate(self, app, make_user, role):
|
||||||
|
with app.app_context():
|
||||||
|
user = db.session.get(User, make_user(role))
|
||||||
|
assert user.can_designate_team_representative() == (role == 'admin')
|
||||||
|
|
||||||
|
|
||||||
|
class TestMatchManagement:
|
||||||
|
"""The routes the feature exists for: matches and practices."""
|
||||||
|
|
||||||
|
def test_a_rep_schedules_a_match(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
f'/team-matches/{world["team"]}/create',
|
||||||
|
data={'title': 'Rep Match', 'date': '2026-10-01', 'start_time': '10:00'},
|
||||||
|
follow_redirects=False,
|
||||||
|
)
|
||||||
|
assert _redirected(response)
|
||||||
|
with app.app_context():
|
||||||
|
assert TeamMatch.query.filter_by(title='Rep Match').count() == 1
|
||||||
|
|
||||||
|
def test_a_rep_schedules_a_practice(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
f'/team-matches/{world["team"]}/create?type=practice',
|
||||||
|
data={'title': 'Evening Scrim', 'date': '2026-10-02', 'start_time': '18:00'},
|
||||||
|
follow_redirects=False,
|
||||||
|
)
|
||||||
|
assert _redirected(response)
|
||||||
|
with app.app_context():
|
||||||
|
match = TeamMatch.query.filter_by(title='Evening Scrim').first()
|
||||||
|
assert match is not None
|
||||||
|
assert match.opponent is None
|
||||||
|
|
||||||
|
def test_a_rep_edits_a_match(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
match_id = _make_match(app, world, title='Before')
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
f'/team-matches/{match_id}/edit',
|
||||||
|
data={'title': 'After', 'date': '2026-10-03', 'start_time': '12:00'},
|
||||||
|
follow_redirects=False,
|
||||||
|
)
|
||||||
|
assert _redirected(response)
|
||||||
|
with app.app_context():
|
||||||
|
assert db.session.get(TeamMatch, match_id).title == 'After'
|
||||||
|
|
||||||
|
def test_a_rep_deletes_a_match(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
match_id = _make_match(app, world, title='Doomed')
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
response = client.post(f'/team-matches/{match_id}/delete', data={}, follow_redirects=False)
|
||||||
|
assert _redirected(response)
|
||||||
|
with app.app_context():
|
||||||
|
assert db.session.get(TeamMatch, match_id) is None
|
||||||
|
|
||||||
|
def test_a_rep_does_not_schedule_for_another_team(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
client.post(
|
||||||
|
f'/team-matches/{world["other"]}/create',
|
||||||
|
data={'title': 'Sneaky', 'date': '2026-10-01', 'start_time': '10:00'},
|
||||||
|
follow_redirects=False,
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
assert TeamMatch.query.filter_by(title='Sneaky').count() == 0
|
||||||
|
|
||||||
|
def test_a_rep_does_not_delete_another_teams_match(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
match_id = _make_match(app, world, title='Elsewhere', team_key='other')
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
client.post(f'/team-matches/{match_id}/delete', data={}, follow_redirects=False)
|
||||||
|
with app.app_context():
|
||||||
|
assert db.session.get(TeamMatch, match_id) is not None
|
||||||
|
|
||||||
|
def test_a_plain_player_does_not_schedule(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['plain_username'])
|
||||||
|
|
||||||
|
client.post(
|
||||||
|
f'/team-matches/{world["team"]}/create',
|
||||||
|
data={'title': 'Nope', 'date': '2026-10-01', 'start_time': '10:00'},
|
||||||
|
follow_redirects=False,
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
assert TeamMatch.query.filter_by(title='Nope').count() == 0
|
||||||
|
|
||||||
|
def test_a_rep_does_not_touch_the_roster(self, app, client, login, make_user):
|
||||||
|
"""Decision 3: matches only, never the roster."""
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
newcomer_id = make_user('player')
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
client.post(
|
||||||
|
f'/teams/{world["team"]}/add_player',
|
||||||
|
data={'player_id': str(newcomer_id), 'status': 'starter'},
|
||||||
|
follow_redirects=False,
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
added = TeamPlayer.query.filter_by(
|
||||||
|
player_id=newcomer_id, org_team_id=world['team']
|
||||||
|
).first()
|
||||||
|
assert added is None
|
||||||
|
|
||||||
|
def test_a_rep_does_not_toggle_a_roster_status(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
response = client.post(f'/teams/{world["team"]}/toggle_status/{world["plain"]}', json={})
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
class TestDesignation:
|
||||||
|
"""Only the president names a responsible."""
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('role', ['manager', 'coach', 'player', 'scout'])
|
||||||
|
def test_a_non_president_cannot_designate(self, app, client, as_role, make_user, role):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
target_id = make_user('player')
|
||||||
|
as_role(role)
|
||||||
|
|
||||||
|
response = client.post(f'/teams/{world["team"]}/toggle_representative/{target_id}', json={})
|
||||||
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
def test_the_president_designates_a_rep(self, app, client, as_role, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
as_role('admin')
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
f'/teams/{world["team"]}/toggle_representative/{world["plain"]}', json={}
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.get_json()['is_team_representative'] is True
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
row = TeamPlayer.query.filter_by(
|
||||||
|
player_id=world['plain'], org_team_id=world['team']
|
||||||
|
).one()
|
||||||
|
assert row.is_team_representative is True
|
||||||
|
|
||||||
|
def test_a_rep_cannot_promote_another_player(self, app, client, login, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
response = client.post(
|
||||||
|
f'/teams/{world["team"]}/toggle_representative/{world["plain"]}', json={}
|
||||||
|
)
|
||||||
|
assert response.status_code == 403
|
||||||
|
with app.app_context():
|
||||||
|
row = TeamPlayer.query.filter_by(
|
||||||
|
player_id=world['plain'], org_team_id=world['team']
|
||||||
|
).one()
|
||||||
|
assert row.is_team_representative is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestReachingThePage:
|
||||||
|
"""Reuse of the teams page, scoped (decision 4)."""
|
||||||
|
|
||||||
|
def test_a_plain_player_is_sent_to_their_own_view(self, client, login, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['plain_username'])
|
||||||
|
|
||||||
|
response = client.get('/teams', follow_redirects=False)
|
||||||
|
assert _redirected(response)
|
||||||
|
assert '/teams/my-teams' in response.headers['Location']
|
||||||
|
|
||||||
|
def test_a_rep_settles_on_the_teams_page(self, client, login, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
assert client.get('/teams').status_code == 200
|
||||||
|
|
||||||
|
def test_the_page_offers_matches_but_not_the_roster(self, client, login, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
html = client.get('/teams').get_data(as_text=True)
|
||||||
|
assert f'/team-matches/{world["team"]}/create' in html
|
||||||
|
assert f'/teams/{world["team"]}/add_player' not in html
|
||||||
|
|
||||||
|
def test_the_my_teams_page_offers_the_schedule_buttons(self, client, login, app, make_user):
|
||||||
|
"""A player's nav only has "My Team(s)", so the rep schedules there."""
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['rep_username'])
|
||||||
|
|
||||||
|
html = client.get('/teams/my-teams').get_data(as_text=True)
|
||||||
|
assert f'/team-matches/{world["team"]}/create' in html
|
||||||
|
assert 'create?type=practice' in html
|
||||||
|
|
||||||
|
def test_the_my_teams_page_is_silent_for_a_plain_player(self, client, login, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
_login_as(client, login, world['plain_username'])
|
||||||
|
|
||||||
|
html = client.get('/teams/my-teams').get_data(as_text=True)
|
||||||
|
assert f'/team-matches/{world["team"]}/create' not in html
|
||||||
|
|
||||||
|
|
||||||
|
class TestRosterOrder:
|
||||||
|
"""The responsible heads the roster, on both pages that render it."""
|
||||||
|
|
||||||
|
def test_the_responsible_is_listed_first(self, app, make_user):
|
||||||
|
world = _build_world(app, make_user)
|
||||||
|
with app.app_context():
|
||||||
|
team = db.session.get(OrgTeam, world['team'])
|
||||||
|
roster = team.get_players_with_status()
|
||||||
|
|
||||||
|
assert [row['player'].id for row in roster] == [world['rep'], world['plain']]
|
||||||
|
assert roster[0]['is_team_representative'] is True
|
||||||
|
assert roster[1]['is_team_representative'] is False
|
||||||
Reference in New Issue
Block a user