Skip to main content

sunday_slate/fantasy_teams/
contest_entries.rs

1//! Pure view assembly for the team detail page: a fantasy team's scored
2//! contests ordered best-first, top-10 flags, and the score to beat.
3
4use nfl_data::slates::{Slate, SlateId};
5
6use crate::scoring::format_points;
7use crate::standings::standings::{COUNTING_SCORES, by_points_desc, top_n_sum_sorted};
8
9/// One scored contest on the team detail page.
10pub struct ContestRow {
11    /// The `/contests/{id}` link target, and the tie-break in `season_view`.
12    pub contest: SlateId,
13    pub name: String,
14    pub points: f64,
15    /// In the top 10 — counts toward the season total.
16    pub counts: bool,
17    /// Lowest of the top 10 — the score to beat.
18    pub score_to_beat: bool,
19}
20
21impl ContestRow {
22    /// The points as `"1,247.50"`.
23    pub fn points_str(&self) -> String {
24        format_points(self.points)
25    }
26}
27
28/// A fantasy team's season: rows by score descending, total from the
29/// counting rows, `None` when no contest scored.
30pub struct SeasonView {
31    pub rows: Vec<ContestRow>,
32    pub total: Option<f64>,
33}
34
35impl SeasonView {
36    /// The total as `"1,247.50"`, or `None` when no contest scored.
37    pub fn total_str(&self) -> Option<String> {
38        self.total.map(format_points)
39    }
40
41    /// The header label under the total: "season total" at 10 or fewer scored
42    /// contests, "best-10 total" above that.
43    pub fn total_label(&self) -> &'static str {
44        if self.rows.len() > COUNTING_SCORES {
45            "best-10 total"
46        } else {
47            "season total"
48        }
49    }
50}
51
52/// Order scored contests best-first, ties by slate id, then flag the
53/// counting rows. Only a team with ten or more scores gets a score to beat.
54pub fn season_view(scored: Vec<(Slate, f64)>) -> SeasonView {
55    let mut scored = scored;
56    scored.sort_by(|a, b| by_points_desc(&a.1, &b.1).then_with(|| a.0.id.0.cmp(&b.0.id.0)));
57    let total = (!scored.is_empty()).then(|| top_n_sum_sorted(scored.iter().map(|(_, p)| *p)));
58    let displaceable = scored.len() >= COUNTING_SCORES;
59    let rows = scored
60        .into_iter()
61        .enumerate()
62        .map(|(i, (slate, points))| ContestRow {
63            contest: slate.id,
64            name: slate.name,
65            points,
66            counts: i < COUNTING_SCORES,
67            score_to_beat: displaceable && i == COUNTING_SCORES - 1,
68        })
69        .collect();
70    SeasonView { rows, total }
71}
72
73#[cfg(test)]
74mod tests {
75    use super::*;
76
77    fn contest(id: i64, name: &str) -> Slate {
78        Slate {
79            id: SlateId(id),
80            season_week: nfl_data::SeasonWeek {
81                season: nfl_data::Season(2026),
82                week: nfl_data::Week(1),
83            },
84            name: name.to_string(),
85            kickoff: None,
86            multiday: false,
87        }
88    }
89
90    /// Contests 1..=n, contest i scoring i points.
91    fn scored(n: i64) -> Vec<(Slate, f64)> {
92        (1..=n)
93            .map(|i| (contest(i, &format!("Week {i}")), i as f64))
94            .collect()
95    }
96
97    #[test]
98    fn orders_by_score_descending_then_contest_id() {
99        let view = season_view(vec![
100            (contest(1, "Week 1"), 10.0),
101            (contest(2, "Week 2"), 30.0),
102            (contest(3, "Week 3"), 10.0),
103        ]);
104        let order: Vec<i64> = view.rows.iter().map(|r| r.contest.0).collect();
105        assert_eq!(order, vec![2, 1, 3], "score desc, tie broken by id");
106    }
107
108    #[test]
109    fn under_ten_scores_all_count_and_nothing_to_beat() {
110        let view = season_view(scored(3));
111        assert!(view.rows.iter().all(|r| r.counts));
112        assert!(view.rows.iter().all(|r| !r.score_to_beat));
113        assert_eq!(view.total, Some(6.0));
114    }
115
116    #[test]
117    fn exactly_ten_scores_marks_the_last() {
118        let view = season_view(scored(10));
119        assert!(view.rows.iter().all(|r| r.counts));
120        let marked: Vec<i64> = view
121            .rows
122            .iter()
123            .filter(|r| r.score_to_beat)
124            .map(|r| r.contest.0)
125            .collect();
126        assert_eq!(marked, vec![1], "lowest of the ten");
127        assert_eq!(view.total, Some(55.0));
128    }
129
130    #[test]
131    fn over_ten_scores_mutes_the_tail() {
132        let view = season_view(scored(12));
133        assert_eq!(view.rows.len(), 12);
134        assert!(view.rows[..10].iter().all(|r| r.counts));
135        assert!(view.rows[10..].iter().all(|r| !r.counts));
136        assert!(view.rows[9].score_to_beat, "tenth row is the score to beat");
137        assert_eq!(
138            view.rows.iter().filter(|r| r.score_to_beat).count(),
139            1,
140            "exactly one mark"
141        );
142        // 12+11+...+3 = 75; the 2.0 and 1.0 rows do not count.
143        assert_eq!(view.total, Some(75.0));
144    }
145
146    #[test]
147    fn total_label_stays_season_total_through_ten_scores() {
148        assert_eq!(season_view(scored(10)).total_label(), "season total");
149    }
150
151    #[test]
152    fn total_label_flips_to_best_ten_at_eleven_scores() {
153        assert_eq!(season_view(scored(11)).total_label(), "best-10 total");
154    }
155
156    #[test]
157    fn no_scores_means_no_rows_and_blank_total() {
158        let view = season_view(vec![]);
159        assert!(view.rows.is_empty());
160        assert_eq!(view.total, None);
161        assert_eq!(view.total_str(), None);
162    }
163
164    #[test]
165    fn standings_and_team_detail_totals_agree_on_the_same_scores() {
166        // More than ten scores, so the truncation bites. Both paths must
167        // total the same raw scores identically.
168        use crate::fantasy_teams::FantasyTeamId;
169        use crate::standings::standings::{ScoredFantasyTeam, rank};
170
171        let raw: Vec<(i64, f64)> = (1..=13).map(|c| (c, c as f64)).collect();
172
173        let standings_total = rank(vec![ScoredFantasyTeam {
174            id: FantasyTeamId(1),
175            name: "Alpha".into(),
176            owner_name: "Owner".into(),
177            logo: None,
178            entered: raw.iter().map(|(c, _)| SlateId(*c)).collect(),
179            scores: raw.iter().map(|(c, p)| (SlateId(*c), *p)).collect(),
180        }])[0]
181            .total;
182
183        let team_detail_total = season_view(
184            raw.iter()
185                .map(|(c, p)| (contest(*c, &format!("Week {c}")), *p))
186                .collect(),
187        )
188        .total;
189
190        assert_eq!(standings_total, team_detail_total);
191        assert_eq!(standings_total, Some(85.0), "top 10 of 1..=13 = 4+..+13");
192    }
193}