refactor(services): un seul endroit pour annoncer un match planifie

Seconde moitie d ARCH-003.

Les memes vingt lignes vivaient dans trois routes -- matches.create_match,
matches.edit_match et team_matches.create_match : formater la date et
l heure, puis parcourir deux listes paralleles pour apparier un joueur avec
la ligne de participation qu une reaction Discord doit pouvoir retrouver.

Trois copies, donc trois occasions de diverger. Elles avaient deja diverge :

  create_match  lisait les heures des variables qu il venait d analyser, et
                affichait 'TBD' des qu une des deux manquait ;
  edit_match    les relisait depuis la ligne enregistree et substituait
                l heure de debut a une heure de fin absente.

Un match avec une heure de debut et pas de fin annoncait donc une heure
dans une route et 'TBD' dans l autre, pour la meme donnee.
app/services/scheduling.py retient la regle la plus soigneuse des deux.

zip_participants() isole l appariement par index, qui n est correct que
tant que les deux listes sont construites en phase -- desormais un seul
endroit a relire au lieu de trois, et une liste plus courte donne None,
converti en reference vers le match lui-meme.

matches.py 711 -> 687 lignes, team_matches.py 347 -> 337.

9 tests sur le service seul, sans base ni requete.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
GGThed
2026-08-08 17:24:39 -04:00
co-authored by Claude Opus 5
parent 5c87064a17
commit 0cd9a186ee
4 changed files with 222 additions and 60 deletions
+16 -40
View File
@@ -25,7 +25,7 @@ from app.models import (
PersonalNote,
)
from datetime import datetime, timedelta
from app.discord_bot import send_schedule_notification
from app.services.scheduling import notify_participants, zip_participants
matches_bp = Blueprint('matches', __name__, url_prefix='/matches')
@@ -375,25 +375,14 @@ def create_match(tryout_id):
db.session.commit()
# Discord notifications
event_date_str = date_obj.strftime('%Y-%m-%d')
event_time_str = (
f"{start_time.strftime('%I:%M %p')} - {end_time.strftime('%I:%M %p')}"
if start_time and end_time
else 'TBD'
notify_participants(
title=match.title,
date=date_obj,
start_time=start_time,
end_time=end_time,
participants=zip_participants(notified_player_ids, notified_participant_ids),
fallback_id=match.id,
)
for i, player_id in enumerate(notified_player_ids):
reference_id = (
notified_participant_ids[i] if i < len(notified_participant_ids) else match.id
)
send_schedule_notification(
user_id=player_id,
event_type='match',
event_title=match.title,
event_date=event_date_str,
event_time=event_time_str,
reference_id=reference_id,
)
flash(_('Match scheduled successfully!'), 'success')
return redirect(url_for('tryouts.view_tryout', tryout_id=tryout_id))
@@ -553,27 +542,14 @@ def edit_match(match_id):
db.session.commit()
# Discord notifications
end_time_val = match.end_time or (match.start_time if match.start_time else None)
if match.start_time and end_time_val:
event_time_str = (
f"{match.start_time.strftime('%I:%M %p')} - {end_time_val.strftime('%I:%M %p')}"
)
else:
event_time_str = 'TBD'
event_date_str = match.date.strftime('%Y-%m-%d')
for i, player_id in enumerate(notified_player_ids):
reference_id = (
notified_participant_ids[i] if i < len(notified_participant_ids) else match.id
)
send_schedule_notification(
user_id=player_id,
event_type='match',
event_title=match.title,
event_date=event_date_str,
event_time=event_time_str,
reference_id=reference_id,
)
notify_participants(
title=match.title,
date=match.date,
start_time=match.start_time,
end_time=match.end_time,
participants=zip_participants(notified_player_ids, notified_participant_ids),
fallback_id=match.id,
)
flash(_('Match updated successfully!'), 'success')
return redirect(url_for('tryouts.view_tryout', tryout_id=tryout.id))
+10 -20
View File
@@ -19,7 +19,7 @@ from app.models import (
)
from app.permissions import can_manage_org_team, coach_org_teams, visible_org_teams
from datetime import datetime, timedelta
from app.discord_bot import send_schedule_notification
from app.services.scheduling import notify_participants, zip_participants
team_matches_bp = Blueprint('team_matches', __name__, url_prefix='/team-matches')
@@ -204,27 +204,17 @@ def create_match(team_id):
db.session.commit()
# Discord notifications
event_date_str = date_obj.strftime('%Y-%m-%d')
event_time_str = (
f"{start_time.strftime('%I:%M %p')} - {end_time.strftime('%I:%M %p')}"
if start_time and end_time
else 'TBD'
notify_participants(
title=team_match.title,
date=date_obj,
start_time=start_time,
end_time=end_time,
participants=zip_participants(
[tp.player_id for tp in team_players], notified_participant_ids
),
fallback_id=team_match.id,
)
for i, tp in enumerate(team_players):
reference_id = (
notified_participant_ids[i] if i < len(notified_participant_ids) else team_match.id
)
send_schedule_notification(
user_id=tp.player_id,
event_type='match',
event_title=team_match.title,
event_date=event_date_str,
event_time=event_time_str,
reference_id=reference_id,
)
flash(_('Team match "%(title)s" scheduled successfully!', title=title), 'success')
return redirect(url_for('team_matches.list_matches'))
+96
View File
@@ -0,0 +1,96 @@
"""Announcing a scheduled match to the people who have to be there.
The same twenty lines appeared three times — matches.create_match,
matches.edit_match and team_matches.create_match — each formatting the date
and time itself, then walking two parallel lists in lockstep to pair a
player with the participant row that a Discord reaction has to find again
(ARCH-003).
Three copies meant three chances to drift, and they had:
create_match read the times from local variables it had just parsed, while
edit_match re-derived them from the saved row and substituted the start
time for a missing end time. The rule kept here is the more careful of the
two.
"""
import logging
from app.discord_bot import send_schedule_notification
logger = logging.getLogger(__name__)
#: What the bot shows when a match has no usable time.
TIME_UNKNOWN = 'TBD'
def format_event_time(start_time, end_time):
"""Render a match's time range the way the Discord message expects.
Args:
start_time: A time, or None.
end_time: A time, or None. Falls back to start_time, so a match with
only a start still announces something useful.
Returns:
str: 'HH:MM AM - HH:MM PM', or TIME_UNKNOWN.
"""
if not start_time:
return TIME_UNKNOWN
finish = end_time or start_time
return f'{start_time.strftime("%I:%M %p")} - {finish.strftime("%I:%M %p")}'
def zip_participants(player_ids, participant_ids):
"""Pair each player with the participant row that was created for them.
The routes build these as two parallel lists, appended in step. Pairing
them by index is what the original code did, and it is only correct as
long as they stay in step — hence one place to look at rather than
three. A short participant list yields None, which
:func:`notify_participants` turns into the fallback reference.
Args:
player_ids: Player primary keys, in creation order.
participant_ids: Participant row ids, in the same order.
Yields:
tuple[int, int | None]: (player_id, participant_id).
"""
for index, player_id in enumerate(player_ids):
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):
"""Tell each participant that a match has been scheduled or changed.
Args:
title: Match title, shown in the message.
date: The match date.
start_time: Start time, or None.
end_time: End time, or None.
participants: Iterable of (player_id, participant_id) pairs.
participant_id is what a Discord reaction resolves back to, so
attendance lands on the right row.
fallback_id: Reference to use when a participant row has no id —
the match's own, which the bot can still act on.
Returns:
int: How many notifications were handed to the bot.
"""
event_date = date.strftime('%Y-%m-%d')
event_time = format_event_time(start_time, end_time)
sent = 0
for player_id, participant_id in participants:
if not player_id:
continue
send_schedule_notification(
user_id=player_id,
event_type='match',
event_title=title,
event_date=event_date,
event_time=event_time,
reference_id=participant_id or fallback_id,
)
sent += 1
return sent