Skip to main content

sunday_slate/contests/
service.rs

1//! Contest views over the published NFL snapshot, plus pure contest-list
2//! assembly.
3
4use crate::entries::Lineup;
5use crate::scoring::service as scoring_service;
6#[cfg(test)]
7use crate::{entries::NflPlayerId, live::identity::LiveIdentityIndex, tests as test_support};
8#[cfg(test)]
9use nfl_data::Player;
10use nfl_data::{SeasonWeek, Snapshot};
11use std::cmp::Ordering;
12use std::cmp::Reverse;
13use std::collections::HashSet;
14use std::sync::Arc;
15use time::{Date, format_description::BorrowedFormatItem};
16
17use nfl_data::Game;
18use nfl_data::slates::{Slate, SlateId, SlateStatus};
19use time::OffsetDateTime;
20
21use crate::entries::store as entries_store;
22use crate::entries::{ContestEntry, EntryId};
23use crate::fantasy_teams::store as fantasy_teams_store;
24use crate::fantasy_teams::{self, FantasyTeamId, LeagueTeam};
25use crate::live::{self, Coverage, LINEUP_REGULATION_MINUTES, LiveContestSnapshot};
26use crate::scoring;
27use crate::standings::standings::{self, ScoredFantasyTeam};
28use crate::{AppError, AppState};
29
30pub struct OfficialResults {
31    pub snapshot: Arc<Snapshot>,
32    pub slates: HashSet<SlateId>,
33}
34
35pub async fn official_contest_weeks(state: &AppState) -> Result<OfficialResults, AppError> {
36    let snapshot = state.nfl.snapshot();
37    let now = state.now();
38    let slates = snapshot
39        .slates()
40        .filter(|slate| !(state.config.live_dev_feed && state.live.snapshot(slate.id).is_some()))
41        .filter(|slate| slate.locked(now) && snapshot.stats_available(&slate.id))
42        .map(|slate| slate.id)
43        .collect();
44    Ok(OfficialResults { snapshot, slates })
45}
46
47pub fn listed_contests<'a>(
48    contests: impl Iterator<Item = &'a Slate>,
49    current_week: Option<SeasonWeek>,
50    now: OffsetDateTime,
51) -> Vec<Slate> {
52    contests
53        .filter(|slate| !slate.upcoming(now) || current_week == Some(slate.season_week))
54        .cloned()
55        .collect()
56}
57
58/// A contest's winning fantasy team, for display.
59pub struct WinnerRow {
60    pub name: String,
61    pub owner_name: String,
62    pub points: f64,
63}
64
65impl WinnerRow {
66    pub fn points_str(&self) -> String {
67        scoring::format_points(self.points)
68    }
69}
70
71/// An upcoming contest's kickoff, as the middle column's headline and
72/// sub-line: "Sunday" over "1:00pm ET".
73pub struct Kickoff {
74    pub weekday: String,
75    pub time: String,
76}
77
78impl Kickoff {
79    /// Rendered in US Eastern wall-clock time. Converting the instant keeps
80    /// this correct for inputs with any stored offset.
81    fn new(kickoff: OffsetDateTime) -> Self {
82        use time::macros::format_description;
83        let k = nfl_data::to_eastern(kickoff);
84        let time = k
85            .format(format_description!(
86                "[hour repr:12 padding:none]:[minute][period case:lower]"
87            ))
88            .expect("kickoff carries a time");
89        Self {
90            weekday: k
91                .format(format_description!("[weekday]"))
92                .expect("kickoff carries a weekday"),
93            time: format!("{time} ET"),
94        }
95    }
96}
97
98/// One rendered contest-list row.
99pub struct ContestRow {
100    /// The `/contests/{id}` link target.
101    pub id: SlateId,
102    pub name: String,
103    pub dates: String,
104    /// Upcoming rows only.
105    pub kickoff: Option<Kickoff>,
106    pub entry_count: usize,
107    pub winners: Vec<WinnerRow>,
108    pub state: SlateStatus,
109    pub pending_official: bool,
110}
111impl ContestRow {
112    pub fn is_live(&self) -> bool {
113        self.state == SlateStatus::Live
114    }
115
116    pub fn is_finished(&self) -> bool {
117        self.state == SlateStatus::Finished
118    }
119}
120
121/// The winners of a finished contest: every entered team tied at the top
122/// score. Empty when no entry scored above zero, which also covers a contest
123/// with no entries at all.
124fn winners(contest: SlateId, teams: &[ScoredFantasyTeam]) -> Vec<WinnerRow> {
125    let scored: Vec<(&ScoredFantasyTeam, f64)> = teams
126        .iter()
127        .filter_map(|t| {
128            let (_, points) = t.scores.iter().find(|(cid, _)| *cid == contest)?;
129            Some((t, *points))
130        })
131        .collect();
132    let Some(top) = scoring::winning_score(scored.iter().map(|(_, p)| *p)) else {
133        return Vec::new();
134    };
135    scored
136        .iter()
137        .filter(|(_, p)| scoring::ties(*p, top))
138        .map(|(t, p)| WinnerRow {
139            name: t.name.clone(),
140            owner_name: t.owner_name.clone(),
141            points: *p,
142        })
143        .collect()
144}
145
146/// Fold contests and scored fantasy teams into display rows, newest first.
147/// Winners show only once a contest has finished.
148pub fn contest_list(
149    contests: &[Slate],
150    teams: &[ScoredFantasyTeam],
151    now: OffsetDateTime,
152) -> Vec<ContestRow> {
153    let mut dated: Vec<(Option<OffsetDateTime>, ContestRow)> = contests
154        .iter()
155        .map(|slate| {
156            let state = slate.status(now);
157            let first = slate.kickoff.map(nfl_data::to_eastern);
158            let dates = first.map_or_else(String::new, |first| {
159                let day = first.date();
160                let last = if slate.multiday {
161                    day.next_day().unwrap_or(day)
162                } else {
163                    day
164                };
165                format_dates(day, last)
166            });
167            let row = ContestRow {
168                id: slate.id,
169                name: slate.name.clone(),
170                dates,
171                kickoff: match (state, first) {
172                    (SlateStatus::Upcoming, Some(kickoff)) => Some(Kickoff::new(kickoff)),
173                    _ => None,
174                },
175                entry_count: teams
176                    .iter()
177                    .filter(|t| t.entered.contains(&slate.id))
178                    .count(),
179                winners: match state {
180                    SlateStatus::Finished => winners(slate.id, teams),
181                    _ => Vec::new(),
182                },
183                state,
184                pending_official: false,
185            };
186            (first, row)
187        })
188        .collect();
189
190    // Newest first; contests with no resolvable kickoff sort last (stable).
191    dated.sort_by_key(|(first, _)| Reverse(*first));
192    dated.into_iter().map(|(_, row)| row).collect()
193}
194
195/// "Sep 7" for one day, "Jan 10–11" within a month, "Nov 30 – Dec 1" across.
196fn format_dates(first: Date, last: Date) -> String {
197    use time::macros::format_description;
198    let month_day = format_description!("[month repr:short] [day padding:none]");
199    let day = format_description!("[day padding:none]");
200    // Both descriptions ask only for components a `Date` carries, so
201    // formatting cannot fail.
202    let fmt =
203        |d: Date, desc: &[BorrowedFormatItem<'_>]| d.format(desc).expect("date components only");
204    let f = fmt(first, month_day);
205    if first == last {
206        f
207    } else if first.month() == last.month() {
208        format!("{f}–{}", fmt(last, day))
209    } else {
210        format!("{f} – {}", fmt(last, month_day))
211    }
212}
213
214#[cfg(test)]
215mod contest_list_tests {
216    use super::*;
217    use nfl_data::{Season, SeasonWeek, Week};
218    use time::macros::{date, datetime};
219
220    /// A fixed "now" late enough that every Sept 2025 contest is finished.
221    fn now() -> OffsetDateTime {
222        datetime!(2026 - 01 - 01 0:00 UTC)
223    }
224
225    /// A 1:00pm Eastern kickoff on `date`.
226    fn kickoff(date: Date) -> OffsetDateTime {
227        date.with_hms(13, 0, 0)
228            .expect("valid time")
229            .assume_offset(nfl_data::eastern_offset(date))
230    }
231
232    fn contest(id: i64, name: &str, kickoff: Option<OffsetDateTime>, multiday: bool) -> Slate {
233        Slate {
234            id: SlateId(id),
235            season_week: SeasonWeek {
236                season: Season(2026),
237                week: Week(1),
238            },
239            name: name.into(),
240            kickoff,
241            multiday,
242        }
243    }
244
245    fn team(name: &str, entered: &[i64], scores: &[(i64, f64)]) -> ScoredFantasyTeam {
246        ScoredFantasyTeam {
247            id: FantasyTeamId(0),
248            name: name.into(),
249            owner_name: "Owner".into(),
250            logo: None,
251            entered: entered.iter().map(|c| SlateId(*c)).collect(),
252            scores: scores.iter().map(|(c, p)| (SlateId(*c), *p)).collect(),
253        }
254    }
255
256    fn one_day(id: i64, name: &str, day: Date) -> Slate {
257        contest(id, name, Some(kickoff(day)), false)
258    }
259
260    #[test]
261    fn upcoming_contest_shows_kickoff_and_no_winner() {
262        let rows = contest_list(
263            &[one_day(1, "Week 2", date!(2025 - 09 - 14))],
264            &[team("Alpha", &[1], &[(1, 13.0)])],
265            datetime!(2025 - 09 - 10 12:00 UTC),
266        );
267        assert_eq!(rows[0].state, SlateStatus::Upcoming);
268        assert!(rows[0].winners.is_empty(), "upcoming shows no winner");
269        let kickoff = rows[0].kickoff.as_ref().expect("kickoff shown");
270        assert_eq!(kickoff.weekday, "Sunday");
271        assert_eq!(kickoff.time, "1:00pm ET");
272    }
273
274    #[test]
275    fn stored_utc_kickoff_displays_in_eastern() {
276        // Sunday Nov 8, 8 PM EST; a UTC-date read would say Monday Nov 9.
277        let rows = contest_list(
278            &[contest(
279                1,
280                "Week 10",
281                Some(datetime!(2026-11-09 01:00 UTC)),
282                false,
283            )],
284            &[],
285            datetime!(2026-11-05 12:00 UTC),
286        );
287        assert_eq!(rows[0].dates, "Nov 8");
288        let kickoff = rows[0].kickoff.as_ref().expect("upcoming shows kickoff");
289        assert_eq!(kickoff.weekday, "Sunday");
290        assert_eq!(kickoff.time, "8:00pm ET");
291    }
292
293    #[test]
294    fn live_contest_has_no_winner() {
295        let rows = contest_list(
296            &[one_day(1, "Week 2", date!(2025 - 09 - 14))],
297            &[team("Alpha", &[1], &[(1, 13.0)])],
298            datetime!(2025 - 09 - 14 20:00 UTC),
299        );
300        assert!(rows[0].is_live());
301        assert!(rows[0].winners.is_empty(), "live shows no winner");
302        assert!(rows[0].kickoff.is_none());
303    }
304
305    #[test]
306    fn a_contest_stays_live_until_its_last_gameday_is_over() {
307        // A Sunday-to-Monday slate is still live late Monday Eastern.
308        let rows = contest_list(
309            &[contest(
310                1,
311                "Week 2",
312                Some(datetime!(2025-09-14 17:00 UTC)),
313                true,
314            )],
315            &[team("Alpha", &[1], &[(1, 13.0)])],
316            datetime!(2025-09-16 02:00 UTC),
317        );
318        assert!(rows[0].is_live());
319        assert_eq!(rows[0].dates, "Sep 14–15");
320    }
321
322    #[test]
323    fn finished_contest_shows_winner() {
324        let rows = contest_list(
325            &[one_day(1, "Week 1", date!(2025 - 09 - 07))],
326            &[team("Alpha", &[1], &[(1, 13.0)])],
327            datetime!(2025 - 09 - 09 12:00 UTC),
328        );
329        assert!(rows[0].is_finished());
330        assert_eq!(rows[0].winners.len(), 1);
331        assert_eq!(rows[0].winners[0].name, "Alpha");
332    }
333
334    #[test]
335    fn winner_is_top_score_with_entry_count() {
336        let rows = contest_list(
337            &[one_day(1, "Week 1", date!(2025 - 09 - 07))],
338            &[
339                team("Alpha", &[1], &[(1, 13.0)]),
340                team("Bravo", &[1], &[(1, 5.0)]),
341            ],
342            now(),
343        );
344        assert_eq!(rows.len(), 1);
345        assert_eq!(rows[0].name, "Week 1");
346        assert_eq!(rows[0].entry_count, 2);
347        assert_eq!(rows[0].winners.len(), 1);
348        assert_eq!(rows[0].winners[0].name, "Alpha");
349        assert_eq!(rows[0].winners[0].points, 13.0);
350    }
351
352    #[test]
353    fn tied_top_scores_all_win() {
354        let rows = contest_list(
355            &[one_day(1, "Week 1", date!(2025 - 09 - 07))],
356            &[
357                team("Alpha", &[1], &[(1, 50.0)]),
358                team("Bravo", &[1], &[(1, 50.0)]),
359                team("Charlie", &[1], &[(1, 10.0)]),
360            ],
361            now(),
362        );
363        let names: Vec<&str> = rows[0].winners.iter().map(|w| w.name.as_str()).collect();
364        assert_eq!(names, vec!["Alpha", "Bravo"]);
365    }
366
367    #[test]
368    fn winners_survive_a_sub_cent_scoring_difference() {
369        // Two identical lineups whose sums land a bit apart must both win.
370        let rows = contest_list(
371            &[one_day(1, "Week 1", date!(2025 - 09 - 07))],
372            &[
373                team("Alpha", &[1], &[(1, 50.0)]),
374                team("Bravo", &[1], &[(1, 50.0 + 1e-12)]),
375            ],
376            now(),
377        );
378        let names: Vec<&str> = rows[0].winners.iter().map(|w| w.name.as_str()).collect();
379        assert_eq!(names, vec!["Alpha", "Bravo"]);
380    }
381
382    #[test]
383    fn zero_top_score_suppresses_winners() {
384        let rows = contest_list(
385            &[one_day(1, "Week 1", date!(2025 - 09 - 14))],
386            &[
387                team("Alpha", &[1], &[(1, 0.0)]),
388                team("Bravo", &[1], &[(1, 0.0)]),
389            ],
390            now(),
391        );
392        assert!(rows[0].winners.is_empty(), "no 0-point winner");
393        assert_eq!(rows[0].entry_count, 2);
394    }
395
396    #[test]
397    fn contest_without_entries_is_schedule_only() {
398        let rows = contest_list(
399            &[one_day(1, "Week 2", date!(2025 - 09 - 14))],
400            &[team("Alpha", &[], &[])],
401            now(),
402        );
403        assert_eq!(rows[0].entry_count, 0);
404        assert!(rows[0].winners.is_empty());
405    }
406
407    #[test]
408    fn sorts_newest_first_undated_last() {
409        let rows = contest_list(
410            &[
411                one_day(1, "Week 1", date!(2025 - 09 - 07)),
412                one_day(2, "Week 2", date!(2025 - 09 - 14)),
413                contest(3, "Mystery", None, false),
414            ],
415            &[],
416            now(),
417        );
418        let names: Vec<&str> = rows.iter().map(|r| r.name.as_str()).collect();
419        assert_eq!(names, vec!["Week 2", "Week 1", "Mystery"]);
420    }
421
422    #[test]
423    fn lists_started_contests_and_all_current_week_slates() {
424        let at = datetime!(2025 - 09 - 10 18:00 UTC);
425        let past = one_day(1, "Week 1", date!(2025 - 09 - 07));
426        let live = one_day(2, "Live", date!(2025 - 09 - 10));
427        let current_week = SeasonWeek {
428            week: Week(2),
429            ..past.season_week
430        };
431        let holiday = Slate {
432            season_week: current_week,
433            ..one_day(3, "Holiday", date!(2025 - 09 - 11))
434        };
435        let main = Slate {
436            season_week: current_week,
437            ..one_day(4, "Week 2", date!(2025 - 09 - 14))
438        };
439        let other = one_day(5, "Other week", date!(2025 - 09 - 21));
440        let contests = [past, live, holiday, main, other];
441
442        let listed = listed_contests(contests.iter(), Some(current_week), at);
443        assert_eq!(
444            listed.iter().map(|c| c.id).collect::<Vec<_>>(),
445            vec![SlateId(1), SlateId(2), SlateId(3), SlateId(4)]
446        );
447    }
448
449    #[test]
450    fn date_display_single_day_and_ranges() {
451        let rows = contest_list(
452            &[
453                one_day(1, "Single", date!(2025 - 09 - 07)),
454                contest(2, "SameMonth", Some(datetime!(2026-01-10 17:00 UTC)), true),
455                contest(3, "CrossMonth", Some(datetime!(2025-11-30 17:00 UTC)), true),
456                contest(4, "NoDate", None, false),
457            ],
458            &[],
459            now(),
460        );
461        let by_name = |n: &str| rows.iter().find(|r| r.name == n).unwrap();
462        assert_eq!(by_name("Single").dates, "Sep 7");
463        assert_eq!(by_name("SameMonth").dates, "Jan 10–11");
464        assert_eq!(by_name("CrossMonth").dates, "Nov 30 – Dec 1");
465        assert_eq!(by_name("NoDate").dates, "");
466    }
467
468    #[test]
469    fn winner_row_formatting() {
470        let w = WinnerRow {
471            name: "Gridiron Giants".into(),
472            owner_name: "Mike".into(),
473            points: 142.5,
474        };
475        assert_eq!(w.points_str(), "142.50");
476    }
477}
478
479/// A league fantasy team entered in one contest. `points` is `Some` when the
480/// contest's NFL week resolves.
481pub struct ContestEntrant {
482    pub id: EntryId,
483    pub name: String,
484    pub owner_name: String,
485    pub logo: Option<String>,
486    pub points: Option<f64>,
487}
488
489/// A rendered contest entry row. Pre-results, `rank` and `points` are `None`
490/// and `winner` is false on every row.
491pub struct EntryRow {
492    /// The `/entries/{id}` link target.
493    pub id: EntryId,
494    pub rank: Option<u32>,
495    pub name: String,
496    pub owner_name: String,
497    pub logo: Option<String>,
498    pub points: Option<f64>,
499    pub coverage: Coverage,
500    pub winner: bool,
501    /// The viewer's own entry, highlighted in every contest state; pinned first
502    /// and linked while the slate is open.
503    pub mine: bool,
504    /// The entry's remaining regulation game-clock minutes, `Some` only on the
505    /// Provisional path; the official and pre-kickoff ranks keep it `None`.
506    pub minutes_remaining: Option<f64>,
507}
508
509impl EntryRow {
510    /// An entrant as an unranked, unscored row — the shared base for both
511    /// list states.
512    fn unscored(e: ContestEntrant) -> EntryRow {
513        EntryRow {
514            id: e.id,
515            rank: None,
516            name: e.name,
517            owner_name: e.owner_name,
518            logo: e.logo,
519            points: None,
520            coverage: Coverage::Unavailable,
521            winner: false,
522            mine: false,
523            minutes_remaining: None,
524        }
525    }
526
527    /// Up to two initials from the fantasy team name, for the logo fallback.
528    pub fn monogram(&self) -> String {
529        fantasy_teams::monogram(&self.name)
530    }
531
532    /// The points as `"1,247.50"`, or `None` pre-results.
533    pub fn points_str(&self) -> Option<String> {
534        self.points.map(scoring::format_points)
535    }
536
537    /// The whole minutes remaining, or `None` when the row has no live meters.
538    pub fn minutes_str(&self) -> Option<String> {
539        self.minutes_remaining.map(|m| m.round().to_string())
540    }
541
542    /// Band of the fill fraction: ≥50% `ok`, 10%–50% `warn`, <10% `low`.
543    /// `None` minutes render as full (unreachable — the template guards on Some).
544    pub fn minutes_band(&self) -> &'static str {
545        let pct = self.minutes_pct_inner();
546        if pct >= 50.0 {
547            "ok"
548        } else if pct >= 10.0 {
549            "warn"
550        } else {
551            "low"
552        }
553    }
554
555    /// Width of the fill bar, 0–100, rounded.
556    pub fn minutes_pct(&self) -> u8 {
557        self.minutes_pct_inner().round() as u8
558    }
559
560    fn minutes_pct_inner(&self) -> f64 {
561        self.minutes_remaining
562            .unwrap_or(LINEUP_REGULATION_MINUTES)
563            .clamp(0.0, LINEUP_REGULATION_MINUTES)
564            / LINEUP_REGULATION_MINUTES
565            * 100.0
566    }
567}
568
569pub fn entrants(
570    entries: &[ContestEntry],
571    points: impl Fn(&Lineup) -> Option<f64>,
572) -> Vec<ContestEntrant> {
573    entries
574        .iter()
575        .map(|e| ContestEntrant {
576            id: e.id,
577            name: e.team_name.clone(),
578            owner_name: e.owner_name.clone(),
579            logo: e.logo.as_ref().map(|m| m.url()),
580            points: points(&e.lineup),
581        })
582        .collect()
583}
584
585/// Rank one contest's entrants. Results show only when every entrant scored
586/// and some score beat zero — the gate the contest list applies to its winner
587/// column. Otherwise rows keep case-insensitive name order with no rank,
588/// points, or winner.
589pub fn rank_contest_entries(entrants: Vec<ContestEntrant>) -> Vec<EntryRow> {
590    let all_scored = !entrants.is_empty() && entrants.iter().all(|e| e.points.is_some());
591    let top = all_scored
592        .then(|| scoring::winning_score(entrants.iter().filter_map(|e| e.points)))
593        .flatten();
594
595    let mut rows: Vec<EntryRow> = entrants
596        .into_iter()
597        .map(|e| {
598            let has_score = e.points.is_some();
599            let points = top.and(e.points);
600            let mut row = EntryRow::unscored(e);
601            row.points = points;
602            row.coverage = if has_score {
603                Coverage::Complete
604            } else {
605                Coverage::Unavailable
606            };
607            row
608        })
609        .collect();
610
611    let Some(top) = top else {
612        rows.sort_by_key(|r| r.name.to_lowercase());
613        return rows;
614    };
615
616    // `top` is Some only when every entrant scored, so every row has points.
617    let points = |r: &EntryRow| r.points.expect("resolved: every entrant scored");
618    rows.sort_by(|a, b| {
619        standings::by_points_desc(&points(a), &points(b))
620            .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
621    });
622    let ranks = standings::shared_ranks(rows.iter().map(|r| r.points));
623    for (r, rank) in rows.iter_mut().zip(ranks) {
624        r.rank = rank;
625        r.winner = scoring::ties(points(r), top);
626    }
627    rows
628}
629
630/// Rank contest entries against the process-local Tank01 snapshot.
631///
632/// Partial totals participate in numeric ordering but never crown a winner.
633pub fn rank_live_entries(
634    entries: &[ContestEntry],
635    snapshot: &LiveContestSnapshot,
636    now: OffsetDateTime,
637) -> Vec<EntryRow> {
638    let mut rows: Vec<EntryRow> = entries
639        .iter()
640        .map(|entry| {
641            let total = live::score_live_lineup(&entry.lineup, snapshot, now);
642            EntryRow {
643                id: entry.id,
644                rank: None,
645                name: entry.team_name.clone(),
646                owner_name: entry.owner_name.clone(),
647                logo: entry.logo.as_ref().map(|logo| logo.url()),
648                points: total.points,
649                coverage: total.coverage,
650                winner: false,
651                mine: false,
652                minutes_remaining: Some(live::lineup_minutes_remaining(
653                    &entry.lineup,
654                    snapshot,
655                    now,
656                )),
657            }
658        })
659        .collect();
660    rows.sort_by(|a, b| {
661        match (a.points, b.points) {
662            (Some(a), Some(b)) => standings::by_points_desc(&a, &b),
663            (Some(_), None) => Ordering::Less,
664            (None, Some(_)) => Ordering::Greater,
665            (None, None) => Ordering::Equal,
666        }
667        .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
668    });
669    let ranks = standings::shared_ranks(rows.iter().map(|row| row.points));
670    for (row, rank) in rows.iter_mut().zip(ranks) {
671        row.rank = rank;
672    }
673    rows
674}
675
676fn mark_my_entry(rows: &mut [EntryRow], mine: Option<EntryId>) -> Option<usize> {
677    let mine = mine?;
678    rows.iter_mut().enumerate().find_map(|(index, row)| {
679        (row.id == mine).then(|| {
680            row.mine = true;
681            index
682        })
683    })
684}
685
686/// Entrants as rows in the order given (entry order), never scored: the
687/// pre-kickoff roll call. The viewer's own entry, when given, is pinned first
688/// and marked `mine`, so the page leads with "you're in".
689fn rows_in_entry_order(entrants: Vec<ContestEntrant>, mine: Option<EntryId>) -> Vec<EntryRow> {
690    let mut rows: Vec<EntryRow> = entrants.into_iter().map(EntryRow::unscored).collect();
691    if let Some(i) = mark_my_entry(&mut rows, mine)
692        && i > 0
693    {
694        let row = rows.remove(i);
695        rows.insert(0, row);
696    }
697    rows
698}
699
700/// A slate game for display: its id, matchup, and Eastern kickoff.
701pub struct GameRow {
702    pub id: String,
703    pub matchup: String,
704    pub kickoff: Option<String>,
705}
706
707/// A day for display: `"Sun, Oct 5"`. Formats in whatever offset `dt` carries,
708/// so callers pass Eastern.
709pub fn format_day(dt: OffsetDateTime) -> String {
710    use time::macros::format_description;
711    let fmt = format_description!("[weekday repr:short], [month repr:short] [day padding:none]");
712    dt.format(fmt).unwrap_or_default()
713}
714
715/// A kickoff for display: `"Sun, Oct 5 · 1:00 PM"`. Formats in whatever offset
716/// `et` carries, so callers pass Eastern.
717pub fn format_kickoff(et: OffsetDateTime) -> String {
718    use time::macros::format_description;
719    let time_fmt = format_description!("[hour repr:12 padding:none]:[minute] [period]");
720    format!(
721        "{} · {}",
722        format_day(et),
723        et.format(time_fmt).unwrap_or_default()
724    )
725}
726
727/// Display rows for a slate, chronological; games with no kickoff sort last.
728pub fn game_rows(games: &[Game]) -> Vec<GameRow> {
729    let mut rows: Vec<(Option<OffsetDateTime>, GameRow)> = games
730        .iter()
731        .map(|g| {
732            let et = g.kickoff_eastern();
733            (
734                et,
735                GameRow {
736                    id: g.game_id.clone(),
737                    matchup: format!("{} @ {}", g.away_team.as_str(), g.home_team.as_str()),
738                    kickoff: et.map(format_kickoff),
739                },
740            )
741        })
742        .collect();
743    // `is_none()` first puts kickoff-less games last; `Option` orders `None`
744    // before `Some`.
745    rows.sort_by(|a, b| {
746        (a.0.is_none(), a.0, &a.1.matchup).cmp(&(b.0.is_none(), b.0, &b.1.matchup))
747    });
748    rows.into_iter().map(|(_, r)| r).collect()
749}
750
751/// A league team with no entry in an upcoming contest: the "still to enter"
752/// roll call under the entered list.
753pub struct WaitingRow {
754    pub name: String,
755    pub owner_name: String,
756    pub logo: Option<String>,
757    /// The viewer's own team, pinned first, highlighted, and linked to the
758    /// lineup editor.
759    pub mine: bool,
760}
761
762impl WaitingRow {
763    /// Up to two initials from the fantasy team name, for the logo fallback.
764    pub fn monogram(&self) -> String {
765        fantasy_teams::monogram(&self.name)
766    }
767}
768
769/// The league's teams with no entry in this contest, in the store's name
770/// order. The viewer's own team, when it is one of them, is pinned first and
771/// marked `mine`, so the page leads with "you're not in yet".
772fn waiting_rows(
773    teams: Vec<LeagueTeam>,
774    entered: &HashSet<FantasyTeamId>,
775    viewer: Option<FantasyTeamId>,
776) -> Vec<WaitingRow> {
777    let mut rows: Vec<WaitingRow> = teams
778        .into_iter()
779        .filter(|t| !entered.contains(&t.id))
780        .map(|t| WaitingRow {
781            name: t.name,
782            owner_name: t.owner_name,
783            logo: t.logo.as_ref().map(|m| m.url()),
784            mine: Some(t.id) == viewer,
785        })
786        .collect();
787    if let Some(i) = rows.iter().position(|r| r.mine)
788        && i > 0
789    {
790        let row = rows.remove(i);
791        rows.insert(0, row);
792    }
793    rows
794}
795
796/// The pre-kickoff header: entries stay open until the slate's first kickoff,
797/// so the page leads with when that is and how long is left.
798pub struct Upcoming {
799    /// `"Sun, Nov 23 · 1:00 PM ET"`.
800    pub kickoff: String,
801    /// `"in 1 hour"` — how long until entries lock.
802    pub countdown: String,
803}
804
805/// How far away `to` is, at the coarsest sensible unit: minutes under an hour,
806/// hours under 36 hours, calendar days thereafter. Calendar-day counts use
807/// Eastern dates. Kickoff is a deadline, so once it arrives the answer stops
808/// counting rather than going negative.
809pub fn time_until(from: OffsetDateTime, to: OffsetDateTime) -> String {
810    let d = to - from;
811    let minutes = d.whole_minutes();
812    if minutes < 1 {
813        return "now".to_string();
814    }
815    let (n, unit) = if minutes < 60 {
816        (minutes, "minute")
817    } else if d.whole_hours() < 36 {
818        (d.whole_hours(), "hour")
819    } else {
820        let from_date = nfl_data::to_eastern(from).date();
821        let to_date = nfl_data::to_eastern(to).date();
822        (
823            i64::from(to_date.to_julian_day() - from_date.to_julian_day()),
824            "day",
825        )
826    };
827    let s = if n == 1 { "" } else { "s" };
828    format!("in {n} {unit}{s}")
829}
830
831/// Everything the contest details page shows.
832pub struct ContestDetails {
833    pub name: String,
834    /// The slate, shown only before its first kickoff. Once the games are
835    /// under way the entry rows carry the contest.
836    pub games: Vec<GameRow>,
837    pub rows: Vec<EntryRow>,
838    /// League teams with no entry yet, empty outside the pre-kickoff window.
839    pub waiting: Vec<WaitingRow>,
840    /// The pre-kickoff header. `Some` exactly while the slate is upcoming —
841    /// the same window in which `games` is non-empty.
842    pub upcoming: Option<Upcoming>,
843    /// The viewer's committed entry, when their team entered this contest.
844    pub my_entry: Option<EntryId>,
845    /// Whether lineups may still be entered: the slate has games and has not
846    /// kicked off.
847    pub entries_open: bool,
848    pub score: ContestScoreMeta,
849}
850
851#[derive(Default)]
852pub struct ContestScoreMeta {
853    pub coverage: Coverage,
854    pub events_url: Option<String>,
855    pub active: bool,
856    pub delayed: bool,
857    pub official: bool,
858}
859
860fn contest_score_meta(
861    source: &live::ContestScores,
862    contest: SlateId,
863    league_id: i64,
864    rows: &[EntryRow],
865    now: OffsetDateTime,
866    stream_eligible: bool,
867) -> ContestScoreMeta {
868    match source {
869        live::ContestScores::Official(_) => ContestScoreMeta {
870            coverage: Coverage::Complete,
871            events_url: None,
872            active: false,
873            delayed: false,
874            official: true,
875        },
876        live::ContestScores::Provisional(snapshot) => {
877            let delayed = snapshot.is_delayed(now);
878            let has_partial = rows.iter().any(|row| row.coverage == Coverage::Partial);
879            let has_unavailable = rows.iter().any(|row| row.coverage == Coverage::Unavailable);
880            let has_usable = rows.iter().any(|row| row.coverage != Coverage::Unavailable);
881            let coverage = if has_partial || (has_unavailable && has_usable) {
882                Coverage::Partial
883            } else if !rows.is_empty() && !has_usable {
884                Coverage::Unavailable
885            } else {
886                Coverage::Complete
887            };
888            ContestScoreMeta {
889                coverage,
890                events_url: stream_eligible
891                    .then(|| format!("/contests/{}/events?league_id={league_id}", contest.0)),
892                active: snapshot.has_active_game(),
893                delayed,
894                official: false,
895            }
896        }
897        live::ContestScores::Upcoming => ContestScoreMeta {
898            coverage: Coverage::Unavailable,
899            events_url: None,
900            active: false,
901            delayed: false,
902            official: false,
903        },
904        live::ContestScores::Unavailable => ContestScoreMeta {
905            coverage: Coverage::Unavailable,
906            events_url: stream_eligible
907                .then(|| format!("/contests/{}/events?league_id={league_id}", contest.0)),
908            active: false,
909            delayed: true,
910            official: false,
911        },
912    }
913}
914
915pub async fn details_for_league(
916    state: &AppState,
917    league_id: i64,
918    viewer: Option<FantasyTeamId>,
919    id: SlateId,
920) -> Result<Option<ContestDetails>, AppError> {
921    let snapshot = state.nfl.snapshot();
922    let Some(slate) = snapshot.slate(&id) else {
923        return Ok(None);
924    };
925    let name = slate.name.clone();
926    let now = state.now_eastern();
927    let games = snapshot.games_for_slate(&id);
928
929    let entries = entries_store::by_contest(state.db.reader(), id, league_id).await?;
930
931    let upcoming = slate.upcoming(now);
932    let first = slate.kickoff.map(nfl_data::to_eastern);
933
934    let source = live::load_contest_scores(state, id).await?;
935    let stream_eligible = live::stream_eligible(state, id, &source).await?;
936    let my_entry = viewer.and_then(|team| {
937        entries
938            .iter()
939            .find(|e| e.fantasy_team == team)
940            .map(|e| e.id)
941    });
942    let mut rows = if upcoming {
943        rows_in_entry_order(entrants(&entries, |_| None), my_entry)
944    } else {
945        match &source {
946            live::ContestScores::Official(snapshot) => {
947                rank_contest_entries(entrants(&entries, |lineup| {
948                    Some(scoring_service::lineup_total(lineup, snapshot, id))
949                }))
950            }
951            live::ContestScores::Provisional(snapshot) => {
952                rank_live_entries(&entries, snapshot, now)
953            }
954            live::ContestScores::Upcoming | live::ContestScores::Unavailable => {
955                rank_contest_entries(entrants(&entries, |_| None))
956            }
957        }
958    };
959    if !upcoming {
960        let _ = mark_my_entry(&mut rows, my_entry);
961    }
962
963    let waiting = if upcoming {
964        let entered: HashSet<FantasyTeamId> = entries.iter().map(|e| e.fantasy_team).collect();
965        let teams = fantasy_teams_store::by_league(state.db.reader(), league_id).await?;
966        waiting_rows(teams, &entered, viewer)
967    } else {
968        Vec::new()
969    };
970
971    let header = match (upcoming, first) {
972        (true, Some(first)) => Some(Upcoming {
973            kickoff: format!("{} ET", format_kickoff(first)),
974            countdown: time_until(now, first),
975        }),
976        _ => None,
977    };
978
979    let score = contest_score_meta(&source, id, league_id, &rows, now, stream_eligible);
980    Ok(Some(ContestDetails {
981        name,
982        entries_open: upcoming,
983        games: if upcoming {
984            game_rows(games)
985        } else {
986            Vec::new()
987        },
988        rows,
989        waiting,
990        upcoming: header,
991        my_entry,
992        score,
993    }))
994}
995
996#[cfg(test)]
997mod tests {
998    use std::collections::HashMap;
999    use std::sync::Arc;
1000
1001    use super::*;
1002    use crate::entries::Lineup;
1003    use crate::live::{LiveContestSnapshot, LiveGameState};
1004    use crate::tests::TestApp;
1005    use crate::tests::factories::{self, TeamOptions};
1006    use nfl_data::scoring::WeekStats;
1007    use nfl_data::{Game, LiveGamePhase, Season, TeamAbbr, Week};
1008    use sqlx::SqlitePool;
1009    use time::OffsetDateTime;
1010    use time::macros::datetime;
1011
1012    /// `id` is the entry the row must keep as `rank_contest_entries` reorders.
1013    fn entrant_with_id(id: i64, name: &str, points: Option<f64>) -> ContestEntrant {
1014        ContestEntrant {
1015            id: EntryId(id),
1016            name: name.to_string(),
1017            owner_name: "Owner".to_string(),
1018            logo: None,
1019            points,
1020        }
1021    }
1022
1023    fn entrant(name: &str, points: Option<f64>) -> ContestEntrant {
1024        entrant_with_id(1, name, points)
1025    }
1026
1027    fn game(id: &str, away: &str, home: &str, kickoff: Option<OffsetDateTime>) -> Game {
1028        Game {
1029            game_id: id.into(),
1030            season_week: SeasonWeek {
1031                season: Season(2025),
1032                week: Week(19),
1033            },
1034            kickoff,
1035            away_team: away.parse().unwrap(),
1036            home_team: home.parse().unwrap(),
1037            home_score: None,
1038            away_score: None,
1039        }
1040    }
1041    #[test]
1042    fn time_until_picks_the_coarsest_sensible_unit() {
1043        let at = datetime!(2025 - 11 - 23 12:00 -5);
1044        let case = |later, expect: &str| assert_eq!(time_until(at, later), expect);
1045        case(datetime!(2025 - 11 - 23 12:00:30 -5), "now");
1046        case(datetime!(2025 - 11 - 23 11:00 -5), "now"); // past: stop counting
1047        case(datetime!(2025 - 11 - 23 12:01 -5), "in 1 minute");
1048        case(datetime!(2025 - 11 - 23 12:45 -5), "in 45 minutes");
1049        case(datetime!(2025 - 11 - 23 13:30 -5), "in 1 hour");
1050        case(datetime!(2025 - 11 - 24 12:00 -5), "in 24 hours");
1051        case(datetime!(2025 - 11 - 26 12:00 -5), "in 3 days");
1052        case(datetime!(2025 - 11 - 24 23:59 -5), "in 35 hours");
1053        case(datetime!(2025 - 11 - 25 00:00 -5), "in 2 days");
1054    }
1055    #[test]
1056    fn time_until_uses_eastern_dates_for_transition_instants() {
1057        assert_eq!(
1058            time_until(
1059                datetime!(2025 - 11 - 02 04:30 UTC),
1060                datetime!(2025 - 11 - 06 18:00 UTC),
1061            ),
1062            "in 4 days"
1063        );
1064        assert_eq!(
1065            time_until(
1066                datetime!(2025 - 11 - 01 23:30 -5),
1067                datetime!(2025 - 11 - 06 13:00 -5),
1068            ),
1069            "in 4 days"
1070        );
1071    }
1072
1073    #[test]
1074    fn time_until_normalizes_utc_midnight_before_counting_days() {
1075        assert_eq!(
1076            time_until(
1077                datetime!(2025 - 11 - 23 12:00 UTC),
1078                datetime!(2025 - 11 - 25 00:00 UTC),
1079            ),
1080            "in 1 day"
1081        );
1082    }
1083
1084    #[test]
1085    fn time_until_uses_calendar_days_for_multi_day_deadlines() {
1086        // Thursday afternoon to Sunday's kickoff spans three calendar dates,
1087        // although fewer than 72 hours elapse.
1088        let at = datetime!(2025 - 09 - 04 16:00 -4);
1089        let kickoff = datetime!(2025 - 09 - 07 13:00 -4);
1090        assert_eq!(time_until(at, kickoff), "in 3 days");
1091    }
1092
1093    #[test]
1094    fn resolved_entrants_rank_desc_with_shared_ties_and_winners() {
1095        let rows = rank_contest_entries(vec![
1096            entrant("Ccc", Some(10.0)),
1097            entrant("Aaa", Some(50.0)),
1098            entrant("Bbb", Some(50.0)),
1099        ]);
1100        assert_eq!(rows[0].name, "Aaa");
1101        assert_eq!(rows[0].rank, Some(1));
1102        assert!(rows[0].winner);
1103        assert_eq!(rows[1].name, "Bbb");
1104        assert_eq!(rows[1].rank, Some(1), "ties share a rank");
1105        assert!(rows[1].winner, "ties all win");
1106        assert_eq!(rows[2].rank, Some(3));
1107        assert!(!rows[2].winner);
1108        assert_eq!(rows[2].points_str().as_deref(), Some("10.00"));
1109    }
1110
1111    #[test]
1112    fn each_row_keeps_its_own_entry_id_through_the_sort() {
1113        // The rows come in name order and leave in score order, so a row that
1114        // kept its neighbour's id would link every reader to the wrong entry.
1115        let rows = rank_contest_entries(vec![
1116            entrant_with_id(10, "Ccc", Some(10.0)),
1117            entrant_with_id(50, "Aaa", Some(50.0)),
1118            entrant_with_id(30, "Bbb", Some(30.0)),
1119        ]);
1120        let pairs: Vec<(&str, EntryId)> = rows.iter().map(|r| (r.name.as_str(), r.id)).collect();
1121        assert_eq!(
1122            pairs,
1123            [
1124                ("Aaa", EntryId(50)),
1125                ("Bbb", EntryId(30)),
1126                ("Ccc", EntryId(10))
1127            ]
1128        );
1129    }
1130
1131    #[test]
1132    fn co_winners_survive_a_sub_cent_scoring_difference() {
1133        // Two lineups whose sums land a bit apart display the same figure, so
1134        // both must take rank 1 and a trophy.
1135        let rows = rank_contest_entries(vec![
1136            entrant("Aaa", Some(50.0)),
1137            entrant("Bbb", Some(50.0 + 1e-12)),
1138        ]);
1139        assert_eq!(rows[0].points_str(), rows[1].points_str());
1140        assert_eq!(rows[0].rank, Some(1));
1141        assert_eq!(rows[1].rank, Some(1), "ties share a rank");
1142        assert!(rows[0].winner && rows[1].winner, "ties all win");
1143    }
1144
1145    #[test]
1146    fn zero_top_score_keeps_the_pre_results_state() {
1147        // Week stats exist but the slate's games are unplayed: everyone
1148        // scores 0.0. The gate must hide points, ranks, and winners.
1149        let rows = rank_contest_entries(vec![
1150            entrant("Zebra", Some(0.0)),
1151            entrant("Apple", Some(0.0)),
1152        ]);
1153        assert_eq!(rows[0].name, "Apple", "name order pre-results");
1154        assert_eq!(rows[0].rank, None);
1155        assert_eq!(rows[0].points, None);
1156        assert!(!rows[0].winner);
1157        assert_eq!(rows[0].points_str(), None);
1158    }
1159
1160    #[test]
1161    fn unresolved_week_keeps_name_order_without_points() {
1162        let rows = rank_contest_entries(vec![entrant("zebra", None), entrant("Apple", None)]);
1163        assert_eq!(rows[0].name, "Apple", "case-insensitive name order");
1164        assert_eq!(rows[1].name, "zebra");
1165        assert!(rows.iter().all(|r| r.rank.is_none() && r.points.is_none()));
1166    }
1167    #[test]
1168    fn minutes_view_methods_bands_and_label() {
1169        let row = |minutes| EntryRow {
1170            id: EntryId(1),
1171            rank: None,
1172            name: "Turf Titans".into(),
1173            owner_name: "Mike".into(),
1174            logo: None,
1175            points: None,
1176            coverage: Coverage::Unavailable,
1177            winner: false,
1178            mine: false,
1179            minutes_remaining: minutes,
1180        };
1181
1182        let full = row(Some(342.0));
1183        assert_eq!(full.minutes_str().as_deref(), Some("342"));
1184        assert_eq!(full.minutes_band(), "ok");
1185        assert_eq!(full.minutes_pct(), 63);
1186
1187        let ten = row(Some(54.0));
1188        assert_eq!(ten.minutes_band(), "warn", "exactly 10% is still warn");
1189        assert_eq!(ten.minutes_pct(), 10);
1190
1191        let under = row(Some(53.9));
1192        assert_eq!(under.minutes_band(), "low", "just under 10% flips to low");
1193        assert_eq!(under.minutes_pct(), 10, "9.98 pct rounds back up to 10");
1194
1195        let empty = row(None);
1196        assert_eq!(empty.minutes_str(), None);
1197        assert_eq!(empty.minutes_band(), "ok");
1198        assert_eq!(empty.minutes_pct(), 100);
1199    }
1200
1201    #[test]
1202    fn provisional_rows_rank_numeric_totals_without_winners() {
1203        let game = game("live", "BUF", "KC", None);
1204        let player_a = Player {
1205            position: Some("RB".into()),
1206            ..factories::player("a", "A Runner")
1207        };
1208        let player_b = Player {
1209            position: Some("RB".into()),
1210            ..factories::player("b", "B Runner")
1211        };
1212        let identity = Arc::new(LiveIdentityIndex::from_sources(&[player_a, player_b], &[]));
1213        let state = LiveGameState {
1214            game: game.clone(),
1215            tank01_game_id: Some("live".into()),
1216            phase: LiveGamePhase::InProgress,
1217            period: Some("2".into()),
1218            clock: Some("08:00".into()),
1219            home_score: Some(14),
1220            away_score: Some(7),
1221            status_observed: true,
1222            players: HashMap::from([
1223                (NflPlayerId("a".into()), factories::rb_stats("a", 19, 100)),
1224                (NflPlayerId("b".into()), factories::rb_stats("b", 19, 50)),
1225            ]),
1226            player_section_present: true,
1227            player_identity_incomplete: false,
1228            player_observed_at: None,
1229            player_stale: false,
1230            defenses: HashMap::from([(
1231                TeamAbbr::KC,
1232                nfl_data::LiveTeamStats {
1233                    team: TeamAbbr::KC,
1234                    opponent: TeamAbbr::BUF,
1235                    sacks: 0,
1236                    interceptions: 0,
1237                    fumble_recoveries: 0,
1238                    safeties: 0,
1239                    touchdowns: 0,
1240                    blocked_kicks: 0,
1241                    conversion_returns: 0,
1242                    points_allowed: Some(0),
1243                    dst_present: true,
1244                    team_stats_present: true,
1245                },
1246            )]),
1247            defense_observed_at: HashMap::new(),
1248            defense_stale: HashMap::new(),
1249            last_error: None,
1250        };
1251        let snapshot = LiveContestSnapshot {
1252            contest: SlateId(1),
1253            games: vec![game],
1254            stats: WeekStats::default(),
1255            game_states: HashMap::from([("live".into(), state)]),
1256            identity,
1257            identity_outcomes: Default::default(),
1258            latest_error: None,
1259            revision: 1,
1260        };
1261        let lineup = |id: &str| {
1262            let id = NflPlayerId(id.to_owned());
1263            Lineup {
1264                qb: id.clone(),
1265                rb1: id.clone(),
1266                rb2: id.clone(),
1267                wr1: id.clone(),
1268                wr2: id.clone(),
1269                wr3: id.clone(),
1270                te: id.clone(),
1271                flex: id,
1272                def: TeamAbbr::KC,
1273            }
1274        };
1275        let entries = vec![
1276            ContestEntry {
1277                id: EntryId(1),
1278                fantasy_team: FantasyTeamId(1),
1279                team_name: "B".into(),
1280                owner_name: "Owner B".into(),
1281                logo: None,
1282                lineup: lineup("b"),
1283            },
1284            ContestEntry {
1285                id: EntryId(2),
1286                fantasy_team: FantasyTeamId(2),
1287                team_name: "A".into(),
1288                owner_name: "Owner A".into(),
1289                logo: None,
1290                lineup: lineup("a"),
1291            },
1292        ];
1293
1294        let rows = rank_live_entries(&entries, &snapshot, datetime!(2025 - 09 - 07 18:00 UTC));
1295
1296        assert_eq!(rows[0].id, EntryId(2));
1297        assert!(rows[0].points.unwrap() > rows[1].points.unwrap());
1298        assert!(rows.iter().all(|row| !row.winner));
1299        assert!(rows.iter().all(|row| row.rank.is_some()));
1300    }
1301
1302    #[test]
1303    fn no_entrants_is_fine() {
1304        assert!(rank_contest_entries(vec![]).is_empty());
1305    }
1306
1307    #[test]
1308    fn game_rows_are_chronological_with_eastern_kickoffs() {
1309        let rows = game_rows(&[
1310            game("b", "BUF", "JAX", Some(datetime!(2026-01-11 18:00 UTC))),
1311            game("a", "LA", "CAR", Some(datetime!(2026-01-10 21:30 UTC))),
1312            game("c", "SF", "PHI", None),
1313        ]);
1314        assert_eq!(rows.len(), 3);
1315        assert_eq!(rows[0].matchup, "LA @ CAR");
1316        assert_eq!(rows[0].kickoff.as_deref(), Some("Sat, Jan 10 · 4:30 PM"));
1317        assert_eq!(rows[1].matchup, "BUF @ JAX");
1318        assert_eq!(rows[1].kickoff.as_deref(), Some("Sun, Jan 11 · 1:00 PM"));
1319        assert_eq!(rows[2].matchup, "SF @ PHI", "kickoff-less games sort last");
1320        assert_eq!(rows[2].kickoff, None);
1321    }
1322
1323    #[sqlx::test]
1324    async fn details_none_for_unknown_contest(pool: SqlitePool) {
1325        let app = TestApp::from_pool(pool.clone()).await;
1326        let fixture = factories::team(&pool, TeamOptions::default()).await;
1327        let details = details_for_league(&app.state(), fixture.league.id, None, SlateId(999))
1328            .await
1329            .expect("assemble");
1330        assert!(details.is_none());
1331    }
1332
1333    #[sqlx::test]
1334    async fn details_excludes_other_leagues(pool: SqlitePool) {
1335        let app = TestApp::from_pool(pool.clone()).await;
1336        let mine = factories::team(&pool, TeamOptions::default()).await;
1337        let other = factories::team(&pool, TeamOptions::default()).await;
1338        let week = SeasonWeek {
1339            season: Season(2026),
1340            week: Week(1),
1341        };
1342        let game = Game {
1343            game_id: "2026_01_BUF_KC".into(),
1344            season_week: week,
1345            kickoff: Some(datetime!(2026 - 09 - 13 17:00 UTC)),
1346            home_team: TeamAbbr::KC,
1347            away_team: TeamAbbr::BUF,
1348            home_score: None,
1349            away_score: None,
1350        };
1351        let wk1 = test_support::publish_slate(&app, week, &[game], &[]).await;
1352        factories::full_entry(&pool, wk1, other.team.id, "00-B").await;
1353
1354        let details = details_for_league(&app.state(), mine.league.id, None, wk1)
1355            .await
1356            .expect("assemble")
1357            .expect("contest exists");
1358        assert!(details.rows.is_empty(), "other league's entries invisible");
1359    }
1360}