Skip to main content

nfl_model/
model.rs

1use std::fmt::{Display, Formatter};
2use time::OffsetDateTime;
3
4use crate::{SeasonWeek, TeamAbbr};
5
6const DEFAULT_SEASON: u16 = 2026;
7
8#[derive(
9    Debug,
10    Clone,
11    Copy,
12    PartialEq,
13    Eq,
14    PartialOrd,
15    Ord,
16    Hash,
17    serde::Serialize,
18    serde::Deserialize,
19    sqlx::Type,
20)]
21#[sqlx(transparent)]
22#[serde(transparent)]
23pub struct Season(pub u16);
24
25impl Display for Season {
26    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
27        write!(f, "{}", self.0)
28    }
29}
30
31impl Default for Season {
32    fn default() -> Self {
33        Season(DEFAULT_SEASON)
34    }
35}
36
37#[derive(
38    Debug,
39    Clone,
40    Copy,
41    PartialEq,
42    Eq,
43    PartialOrd,
44    Ord,
45    Hash,
46    serde::Serialize,
47    serde::Deserialize,
48    sqlx::Type,
49)]
50#[sqlx(transparent)]
51#[serde(transparent)]
52pub struct Week(pub u8);
53
54impl Display for Week {
55    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
56        write!(f, "{}", self.0)
57    }
58}
59
60/// Stored as TEXT "REG"/"POST". Upstream playoff game types (WC/DIV/CON/SB)
61/// map to Post at ingest.
62#[repr(u8)]
63#[derive(
64    Default,
65    Debug,
66    Clone,
67    Copy,
68    PartialEq,
69    Eq,
70    Hash,
71    serde::Serialize,
72    serde::Deserialize,
73    strum::EnumString,
74    strum::IntoStaticStr,
75    sqlx::Type,
76)]
77#[serde(rename_all = "UPPERCASE")]
78#[strum(serialize_all = "UPPERCASE", ascii_case_insensitive)]
79pub enum SeasonType {
80    #[default]
81    Reg = 0,
82    Post = 1,
83}
84
85impl SeasonType {
86    pub fn is_reg(&self) -> bool {
87        self == &SeasonType::Reg
88    }
89}
90
91impl Display for SeasonType {
92    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
93        f.write_str(self.into())
94    }
95}
96
97impl From<SeasonType> for u8 {
98    fn from(value: SeasonType) -> Self {
99        value as u8
100    }
101}
102
103impl From<SeasonType> for u32 {
104    fn from(value: SeasonType) -> Self {
105        value as u32
106    }
107}
108
109impl TryFrom<u8> for SeasonType {
110    type Error = ();
111
112    fn try_from(value: u8) -> Result<Self, Self::Error> {
113        match value {
114            0 => Ok(Self::Reg),
115            1 => Ok(Self::Post),
116            _ => Err(()),
117        }
118    }
119}
120
121#[derive(Debug, Clone, PartialEq)]
122pub struct Game {
123    pub game_id: String,
124    pub season_week: SeasonWeek,
125    /// UTC. None when upstream omits the kickoff time (some historical games).
126    pub kickoff: Option<OffsetDateTime>,
127    pub home_team: TeamAbbr,
128    pub away_team: TeamAbbr,
129    pub home_score: Option<i32>,
130    pub away_score: Option<i32>,
131}
132
133impl Game {
134    /// Kickoff in US Eastern local wall-clock time, or `None` when the kickoff
135    /// is unknown. The stored kickoff is an instant, so DST is resolved from
136    /// the transition instants for its year.
137    pub fn kickoff_eastern(&self) -> Option<OffsetDateTime> {
138        self.kickoff.map(crate::eastern::to_eastern)
139    }
140}
141
142#[derive(Debug, Clone, PartialEq)]
143pub struct Player {
144    pub gsis_id: String,
145    pub espn_id: Option<String>,
146    pub full_name: String,
147    pub first_name: Option<String>,
148    pub last_name: Option<String>,
149    pub position: Option<String>,
150    pub latest_team: Option<TeamAbbr>,
151    pub headshot_url: Option<String>,
152}
153
154/// One player's place on a team's roster in a single week. This survives
155/// mid-season trades: a player appears under each team for the weeks he was
156/// actually there.
157#[derive(Debug, Clone, PartialEq)]
158pub struct WeeklyRosterEntry {
159    pub season_week: SeasonWeek,
160    pub team: TeamAbbr,
161    /// None for players without a GSIS assignment yet (upstream leaves it empty).
162    pub gsis_id: Option<String>,
163    pub espn_id: Option<String>,
164    pub full_name: String,
165    /// Surname with any generational suffix already stripped by upstream
166    /// ("Dante Fowler Jr." -> "Fowler"). Sort candidate lists on this.
167    pub last_name: Option<String>,
168    pub position: Option<String>,
169}
170
171#[derive(Debug, Clone, PartialEq)]
172pub struct PlayerWeekStats {
173    pub season_week: SeasonWeek,
174    pub gsis_id: String,
175    pub team: TeamAbbr,
176    pub opponent: Option<TeamAbbr>,
177    pub completions: u32,
178    pub attempts: u32,
179    pub passing_yards: i32,
180    pub passing_tds: u32,
181    pub passing_interceptions: u32,
182    pub rushing_attempts: u32,
183    pub rushing_yards: i32,
184    pub rushing_tds: u32,
185    pub targets: u32,
186    pub receptions: u32,
187    pub receiving_yards: i32,
188    pub receiving_tds: u32,
189    /// Sum of upstream rushing/receiving/sack fumbles lost.
190    pub fumbles_lost: u32,
191    /// Sum of upstream passing/rushing/receiving 2pt conversions.
192    pub two_point_conversions: u32,
193    pub special_teams_tds: u32,
194    /// Offensive fumble-recovery TDs (recovering a fumble and scoring) —
195    /// FanDuel's FU/TD.
196    pub fumble_recovery_tds: u32,
197}
198
199/// One team's per-week DST line, aggregated from play-by-play. Every field is
200/// a FanDuel DST scoring input. `touchdowns` collapses defensive, return, and
201/// special-teams TDs (all score +6). `points_allowed` is the opponent's
202/// offensive points (FanDuel's points-allowed), not the scoreboard total.
203#[derive(Debug, Clone, PartialEq)]
204pub struct TeamWeekStats {
205    pub season_week: SeasonWeek,
206    pub team: TeamAbbr,
207    pub opponent: TeamAbbr,
208    pub game_id: String,
209    /// Whole team sacks (one per sack play — includes uncredited strip-sacks).
210    pub sacks: u32,
211    pub interceptions: u32,
212    pub fumble_recoveries: u32,
213    pub safeties: u32,
214    /// Non-offensive TDs: defensive, return, and special-teams (+6 each).
215    pub touchdowns: u32,
216    pub blocked_kicks: u32,
217    /// Defensive extra-point and two-point returns (+2 each).
218    pub conversion_returns: u32,
219    /// Opponent's offensive points — FanDuel's DST points-allowed.
220    pub points_allowed: i32,
221}
222
223#[cfg(test)]
224mod kickoff_eastern_tests {
225    use super::*;
226    use time::Weekday;
227    use time::macros::datetime;
228
229    fn game(kickoff: Option<time::OffsetDateTime>) -> Game {
230        Game {
231            game_id: "x".into(),
232            season_week: SeasonWeek {
233                season: Season(2025),
234                week: Week(1),
235            },
236            kickoff,
237            home_team: TeamAbbr::LA,
238            away_team: TeamAbbr::SF,
239            home_score: None,
240            away_score: None,
241        }
242    }
243
244    #[test]
245    fn converts_utc_to_eastern_edt() {
246        // 2025-09-07 17:00 UTC == 13:00 EDT (-4), a Sunday.
247        let et = game(Some(datetime!(2025-09-07 17:00 UTC)))
248            .kickoff_eastern()
249            .unwrap();
250        assert_eq!(et.weekday(), Weekday::Sunday);
251        assert_eq!(et.time(), time::macros::time!(13:00));
252    }
253
254    #[test]
255    fn converts_utc_to_eastern_est() {
256        // 2026-01-10 21:30 UTC == 16:30 EST (-5), a Saturday.
257        let et = game(Some(datetime!(2026-01-10 21:30 UTC)))
258            .kickoff_eastern()
259            .unwrap();
260        assert_eq!(et.weekday(), Weekday::Saturday);
261        assert_eq!(et.time(), time::macros::time!(16:30));
262    }
263
264    #[test]
265    fn none_when_kickoff_missing() {
266        assert!(game(None).kickoff_eastern().is_none());
267    }
268}