Skip to main content

nfl_data/scoring/
service.rs

1//! Scoring assembly a handler can call: load the stats a set of contests
2//! needs, then score each fantasy team's entries against them.
3
4use crate::{NflData, NflDataError, SeasonWeek, TeamAbbr, Week};
5use nfl_model::NflPlayerId;
6use std::collections::{HashMap, HashSet};
7
8use crate::scoring::{self, PointsPerGame, WeekStats};
9
10/// Season-to-date FPPG and games played for both NFL Players and Team DST
11#[derive(Debug, Default)]
12pub struct SeasonAverages {
13    pub players: HashMap<NflPlayerId, PointsPerGame>,
14    pub dsts: HashMap<TeamAbbr, PointsPerGame>,
15}
16
17/// Averages for every week of `before`'s season strictly before that week, so
18/// the cutoff week and other seasons' rows never participate.
19pub async fn season_averages(
20    nfl: &NflData,
21    before: SeasonWeek,
22    ids: &[impl AsRef<str>],
23) -> Result<SeasonAverages, NflDataError> {
24    let wanted: HashSet<&str> = ids.iter().map(|i| i.as_ref()).collect();
25    let mut players: HashMap<NflPlayerId, (f64, u32)> = HashMap::new();
26    let mut dsts: HashMap<TeamAbbr, (f64, u32)> = HashMap::new();
27    for week in 1..before.week.0 {
28        let season_week = SeasonWeek {
29            season: before.season,
30            week: Week(week),
31        };
32        for line in nfl.player_week_stats(season_week).await? {
33            if !wanted.contains(line.gsis_id.as_str()) {
34                continue;
35            }
36            let (points, games) = players
37                .entry(NflPlayerId(line.gsis_id.clone()))
38                .or_insert_with(|| (0.0, 0));
39            *points += scoring::score_player(&line).total;
40            *games += 1;
41        }
42        for t in nfl.team_week_stats(season_week).await? {
43            let (points, games) = dsts.entry(t.team).or_insert_with(|| (0.0, 0));
44            *points += scoring::score_defense(&t).total;
45            *games += 1;
46        }
47    }
48    Ok(SeasonAverages {
49        players: players
50            .into_iter()
51            .map(|(id, (points, games))| {
52                (
53                    id,
54                    PointsPerGame {
55                        avg_points: points / games as f64,
56                        games_played: games as u8,
57                    },
58                )
59            })
60            .collect(),
61        dsts: dsts
62            .into_iter()
63            .map(|(team, (points, games))| {
64                (
65                    team,
66                    PointsPerGame {
67                        avg_points: points / games as f64,
68                        games_played: games as u8,
69                    },
70                )
71            })
72            .collect(),
73    })
74}
75
76/// Load all fantasy stats for completed weeks.
77pub async fn week_stats(
78    nfl: &NflData,
79    weeks: impl IntoIterator<Item = SeasonWeek>,
80) -> Result<HashMap<SeasonWeek, WeekStats>, NflDataError> {
81    let mut stats: HashMap<SeasonWeek, WeekStats> = HashMap::new();
82    let mut seen: HashSet<SeasonWeek> = HashSet::new();
83    for week in weeks {
84        if !seen.insert(week) {
85            continue;
86        }
87        let players: HashMap<NflPlayerId, _> = nfl
88            .player_week_stats(week)
89            .await?
90            .into_iter()
91            .map(|p| (NflPlayerId(p.gsis_id.clone()), p))
92            .collect();
93        let defenses: HashMap<_, _> = nfl
94            .team_week_stats(week)
95            .await?
96            .into_iter()
97            .map(|t| (t.team, t))
98            .collect();
99        if players.is_empty() || defenses.is_empty() {
100            continue;
101        }
102        stats.insert(week, WeekStats { players, defenses });
103    }
104    Ok(stats)
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::PlayerWeekStats;
111    use crate::{NflData, Season, SeasonWeek, TeamWeekStats};
112
113    fn week(season: u16, week: u8) -> SeasonWeek {
114        SeasonWeek::new(Season(season), Week(week)).expect("valid fixture week")
115    }
116
117    /// Every scoring count zero except receptions, so the total is exactly
118    /// `0.5 * receptions` with no threshold bonus in play.
119    fn receptions(season_week: SeasonWeek, receptions: u32) -> PlayerWeekStats {
120        PlayerWeekStats {
121            season_week,
122            gsis_id: "00-RB".into(),
123            team: TeamAbbr::KC,
124            opponent: Some(TeamAbbr::BUF),
125            completions: 0,
126            attempts: 0,
127            passing_yards: 0,
128            passing_tds: 0,
129            passing_interceptions: 0,
130            rushing_attempts: 0,
131            rushing_yards: 0,
132            rushing_tds: 0,
133            targets: 0,
134            receptions,
135            receiving_yards: 0,
136            receiving_tds: 0,
137            fumbles_lost: 0,
138            two_point_conversions: 0,
139            special_teams_tds: 0,
140            fumble_recovery_tds: 0,
141        }
142    }
143
144    fn defense(season_week: SeasonWeek, points_allowed: i32) -> TeamWeekStats {
145        TeamWeekStats {
146            season_week,
147            team: TeamAbbr::KC,
148            opponent: TeamAbbr::BUF,
149            game_id: format!("{}_{:02}_BUF_KC", season_week.season, season_week.week.0),
150            sacks: 0,
151            interceptions: 0,
152            fumble_recoveries: 0,
153            safeties: 0,
154            touchdowns: 0,
155            blocked_kicks: 0,
156            conversion_returns: 0,
157            points_allowed,
158        }
159    }
160
161    async fn seeded() -> NflData {
162        let nfl = NflData::in_memory().await.expect("in-memory handle");
163        // 2025 week 1: 20 receptions = 10.00, a shutout = 10.00.
164        nfl.seed_week_stats_for_test(
165            Season(2025),
166            &[receptions(week(2025, 1), 20)],
167            &[defense(week(2025, 1), 0)],
168        )
169        .await
170        .expect("seed 2025");
171        // 2026 week 1: 40 receptions = 20.00, 7 points allowed = 4.00.
172        nfl.seed_week_stats_for_test(
173            Season(2026),
174            &[receptions(week(2026, 1), 40)],
175            &[defense(week(2026, 1), 7)],
176        )
177        .await
178        .expect("seed 2026");
179        nfl
180    }
181
182    #[tokio::test]
183    async fn season_week_week_stats_keys_each_season_separately() {
184        let nfl = seeded().await;
185        let stats = week_stats(
186            &nfl,
187            [week(2025, 1), week(2026, 1), week(2025, 1), week(2025, 1)],
188        )
189        .await
190        .expect("load stats");
191
192        assert_eq!(stats.len(), 2, "the duplicate identity collapses");
193        let id = NflPlayerId("00-RB".into());
194
195        let older = &stats[&week(2025, 1)];
196        assert_eq!(scoring::score_player(&older.players[&id]).total, 10.0);
197        assert_eq!(
198            scoring::score_defense(&older.defenses[&TeamAbbr::KC]).total,
199            10.0
200        );
201
202        let newer = &stats[&week(2026, 1)];
203        assert_eq!(scoring::score_player(&newer.players[&id]).total, 20.0);
204        assert_eq!(
205            scoring::score_defense(&newer.defenses[&TeamAbbr::KC]).total,
206            4.0
207        );
208    }
209
210    #[tokio::test]
211    async fn season_week_week_stats_skips_a_week_without_defenses() {
212        let nfl = NflData::in_memory().await.expect("in-memory handle");
213        nfl.seed_week_stats_for_test(Season(2025), &[receptions(week(2025, 2), 20)], &[])
214            .await
215            .expect("seed players only");
216
217        assert!(
218            week_stats(&nfl, [week(2025, 2)])
219                .await
220                .expect("load stats")
221                .is_empty()
222        );
223    }
224
225    #[tokio::test]
226    async fn season_week_season_averages_stop_before_the_cutoff_week() {
227        let nfl = NflData::in_memory().await.expect("in-memory handle");
228        // Prior weeks: 20 receptions (10.00) and 40 receptions (20.00).
229        // The cutoff week and the other season's week 18 must not count.
230        nfl.seed_week_stats_for_test(
231            Season(2025),
232            &[
233                receptions(week(2025, 18), 20),
234                receptions(week(2025, 19), 40),
235                receptions(week(2025, 20), 900),
236            ],
237            &[
238                defense(week(2025, 18), 0),
239                defense(week(2025, 19), 0),
240                defense(week(2025, 20), 0),
241            ],
242        )
243        .await
244        .expect("seed 2025");
245        nfl.seed_week_stats_for_test(
246            Season(2026),
247            &[receptions(week(2026, 18), 800)],
248            &[defense(week(2026, 18), 0)],
249        )
250        .await
251        .expect("seed 2026");
252
253        let averages = season_averages(&nfl, week(2025, 20), &["00-RB"])
254            .await
255            .expect("averages");
256        let player = averages.players[&NflPlayerId("00-RB".into())];
257        assert_eq!(player.games_played, 2);
258        assert_eq!(player.avg_points, 15.0);
259        // Both DST weeks allowed a shutout: 10.00 each.
260        let dst = averages.dsts[&TeamAbbr::KC];
261        assert_eq!(dst.games_played, 2);
262        assert_eq!(dst.avg_points, 10.0);
263    }
264
265    #[tokio::test]
266    async fn season_week_season_averages_of_week_one_are_empty() {
267        let nfl = seeded().await;
268        let averages = season_averages(&nfl, week(2025, 1), &["00-RB"])
269            .await
270            .expect("averages");
271        assert!(averages.players.is_empty());
272        assert!(averages.dsts.is_empty());
273    }
274}