Skip to main content

sunday_slate/entries/
model.rs

1use crate::fantasy_teams::FantasyTeamId;
2use crate::media::Media;
3use nfl_data::TeamAbbr;
4use nfl_data::slates::SlateId;
5
6pub use nfl_model::NflPlayerId;
7
8/// A lineup's nine roster slots. Stored as TEXT (`"QB"`, `"RB1"`, ...) in
9/// `entry_slots.roster_slot`; the sqlx derive decodes that column directly.
10#[derive(
11    Debug,
12    Clone,
13    Copy,
14    PartialEq,
15    Eq,
16    Hash,
17    sqlx::Type,
18    strum::Display,
19    strum::EnumString,
20    strum::EnumIter,
21)]
22#[sqlx(rename_all = "UPPERCASE")]
23#[strum(serialize_all = "UPPERCASE")]
24pub enum RosterSlot {
25    Qb,
26    Rb1,
27    Rb2,
28    Wr1,
29    Wr2,
30    Wr3,
31    Te,
32    Flex,
33    Def,
34}
35
36impl RosterSlot {
37    /// The position a slot draws from, without its ordinal: `Rb1` and `Rb2`
38    /// are both `"RB"`. This is the display label the entry page shows, kept
39    /// next to the slot so a new variant cannot drift from its label.
40    pub fn position_label(self) -> &'static str {
41        use RosterSlot::*;
42        match self {
43            Qb => "QB",
44            Rb1 | Rb2 => "RB",
45            Wr1 | Wr2 | Wr3 => "WR",
46            Te => "TE",
47            Flex => "FLEX",
48            Def => "DEF",
49        }
50    }
51
52    /// Whether this slot takes a team defense rather than a player.
53    pub fn is_defense(self) -> bool {
54        matches!(self, RosterSlot::Def)
55    }
56
57    /// What the picker's search field invites you to type. FLEX and DEF get
58    /// words because "Search FLEXs" and "Search DEFs" don't read as English.
59    pub fn search_placeholder(self) -> String {
60        match self {
61            RosterSlot::Flex => "Search players".into(),
62            slot if slot.is_defense() => "Search defenses".into(),
63            slot => format!("Search {}s", slot.position_label()),
64        }
65    }
66
67    /// Parse the picker's submitted value into what this slot holds. The slot
68    /// decides whether the string is a player id or a team abbr.
69    pub fn parse_value(self, raw: String) -> Result<PlayerOrDefenseId, String> {
70        if self.is_defense() {
71            raw.parse()
72                .map(PlayerOrDefenseId::Defense)
73                .map_err(|_| format!("{raw} is not a team abbr."))
74        } else {
75            Ok(PlayerOrDefenseId::Player(NflPlayerId(raw)))
76        }
77    }
78
79    /// The picker's empty-state noun: "No defenses match ..." for DEF.
80    pub fn search_noun(self) -> &'static str {
81        if self.is_defense() {
82            "defenses"
83        } else {
84            "players"
85        }
86    }
87
88    pub fn dom_id(self) -> &'static str {
89        match self {
90            Self::Qb => "qb",
91            Self::Rb1 => "rb1",
92            Self::Rb2 => "rb2",
93            Self::Wr1 => "wr1",
94            Self::Wr2 => "wr2",
95            Self::Wr3 => "wr3",
96            Self::Te => "te",
97            Self::Flex => "flex",
98            Self::Def => "def",
99        }
100    }
101}
102
103pub use nfl_model::PlayerOrDefenseId;
104
105/// One `entry_slots` row, typed: which slot and what it holds.
106#[derive(Debug, Clone, PartialEq)]
107pub struct EntrySlot {
108    pub slot: RosterSlot,
109    pub value: PlayerOrDefenseId,
110}
111
112/// The one lineup invariant the schema can't enforce: all nine slots present.
113/// (Valid slot names, payload shape, and per-entry uniqueness are CHECK/UNIQUE
114/// constraints on `entry_slots`.)
115#[derive(Debug, PartialEq, thiserror::Error)]
116pub enum LineupError {
117    #[error("missing {0} slot")]
118    MissingSlot(RosterSlot),
119}
120
121/// Total — an entry exists in a contest, so all nine slots are filled.
122#[derive(Debug, Clone, PartialEq)]
123pub struct Lineup {
124    pub qb: NflPlayerId,
125    pub rb1: NflPlayerId,
126    pub rb2: NflPlayerId,
127    pub wr1: NflPlayerId,
128    pub wr2: NflPlayerId,
129    pub wr3: NflPlayerId,
130    pub te: NflPlayerId,
131    pub flex: NflPlayerId,
132    pub def: TeamAbbr,
133}
134
135impl Lineup {
136    /// The eight player slots in roster order, each paired with the slot it
137    /// fills. Kept next to the fields so a caller that walks the lineup
138    /// cannot miss a slot.
139    pub fn player_slots(&self) -> [(RosterSlot, &NflPlayerId); 8] {
140        use RosterSlot::*;
141        [
142            (Qb, &self.qb),
143            (Rb1, &self.rb1),
144            (Rb2, &self.rb2),
145            (Wr1, &self.wr1),
146            (Wr2, &self.wr2),
147            (Wr3, &self.wr3),
148            (Te, &self.te),
149            (Flex, &self.flex),
150        ]
151    }
152
153    /// The eight player ids in roster order.
154    pub fn player_ids(&self) -> [&NflPlayerId; 8] {
155        self.player_slots().map(|(_, id)| id)
156    }
157
158    /// The nine `EntrySlot`s the lineup maps to, in roster order — the
159    /// inverse of [`Self::from_slots`].
160    pub(crate) fn to_slots(&self) -> Vec<EntrySlot> {
161        let mut slots: Vec<EntrySlot> = self
162            .player_slots()
163            .into_iter()
164            .map(|(slot, id)| EntrySlot {
165                slot,
166                value: PlayerOrDefenseId::Player(id.clone()),
167            })
168            .collect();
169        slots.push(EntrySlot {
170            slot: RosterSlot::Def,
171            value: PlayerOrDefenseId::Defense(self.def),
172        });
173        slots
174    }
175
176    /// Assemble one entry's slots into a total lineup, reporting the first
177    /// hole. A slot whose value kind doesn't match (impossible for rows read
178    /// through the schema) fills nothing and so surfaces as that slot missing.
179    pub(crate) fn from_slots(
180        slots: impl IntoIterator<Item = EntrySlot>,
181    ) -> Result<Lineup, LineupError> {
182        use RosterSlot::*;
183
184        #[derive(Default)]
185        struct Builder {
186            qb: Option<NflPlayerId>,
187            rb1: Option<NflPlayerId>,
188            rb2: Option<NflPlayerId>,
189            wr1: Option<NflPlayerId>,
190            wr2: Option<NflPlayerId>,
191            wr3: Option<NflPlayerId>,
192            te: Option<NflPlayerId>,
193            flex: Option<NflPlayerId>,
194            def: Option<TeamAbbr>,
195        }
196
197        let mut b = Builder::default();
198        for EntrySlot { slot, value } in slots {
199            match (slot, value) {
200                (Qb, PlayerOrDefenseId::Player(p)) => b.qb = Some(p),
201                (Rb1, PlayerOrDefenseId::Player(p)) => b.rb1 = Some(p),
202                (Rb2, PlayerOrDefenseId::Player(p)) => b.rb2 = Some(p),
203                (Wr1, PlayerOrDefenseId::Player(p)) => b.wr1 = Some(p),
204                (Wr2, PlayerOrDefenseId::Player(p)) => b.wr2 = Some(p),
205                (Wr3, PlayerOrDefenseId::Player(p)) => b.wr3 = Some(p),
206                (Te, PlayerOrDefenseId::Player(p)) => b.te = Some(p),
207                (Flex, PlayerOrDefenseId::Player(p)) => b.flex = Some(p),
208                (Def, PlayerOrDefenseId::Defense(t)) => b.def = Some(t),
209                _ => {}
210            }
211        }
212        let take = |v: Option<NflPlayerId>, slot| v.ok_or(LineupError::MissingSlot(slot));
213        Ok(Lineup {
214            qb: take(b.qb, Qb)?,
215            rb1: take(b.rb1, Rb1)?,
216            rb2: take(b.rb2, Rb2)?,
217            wr1: take(b.wr1, Wr1)?,
218            wr2: take(b.wr2, Wr2)?,
219            wr3: take(b.wr3, Wr3)?,
220            te: take(b.te, Te)?,
221            flex: take(b.flex, Flex)?,
222            def: b.def.ok_or(LineupError::MissingSlot(Def))?,
223        })
224    }
225}
226
227/// An entry seen from its contest's side: the contest is context, the fantasy
228/// team is data — the symmetric view to [`FantasyTeamEntry`].
229#[derive(Debug, Clone, PartialEq)]
230pub struct ContestEntry {
231    /// The `/entries/{id}` link target.
232    pub id: EntryId,
233    pub fantasy_team: FantasyTeamId,
234    pub team_name: String,
235    pub owner_name: String,
236    pub logo: Option<Media>,
237    pub lineup: Lineup,
238}
239
240/// An entry seen from its fantasy team's side: the fantasy team is context
241/// (the owning [`FantasyTeamEntries`]), the contest is data. The contest-major
242/// view is the symmetric [`ContestEntry`]; a player-picks view gets a struct
243/// carrying both ids.
244#[derive(Debug, Clone, PartialEq)]
245pub struct FantasyTeamEntry {
246    pub slate_id: SlateId,
247    pub lineup: Lineup,
248}
249
250/// Aggregate root: a fantasy team and its contest entries. Ownership is the
251/// fantasy team↔entry relationship.
252#[derive(Debug, Clone, PartialEq)]
253pub struct FantasyTeamEntries {
254    pub id: FantasyTeamId,
255    pub name: String,
256    pub owner_name: String,
257    pub logo: Option<Media>,
258    pub entries: Vec<FantasyTeamEntry>,
259}
260
261/// An entry's id as an opaque token — the `/entries/{id}` route key.
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, sqlx::Type)]
263#[sqlx(transparent)]
264pub struct EntryId(pub i64);
265
266/// One entry loaded for display: its lineup plus the context the page needs —
267/// slate, league, and owning fantasy team.
268#[derive(Debug, Clone)]
269pub struct EntryDetails {
270    pub id: EntryId,
271    pub league_id: i64,
272    pub slate_id: SlateId,
273    pub team: EntryTeam,
274    pub lineup: Lineup,
275}
276
277/// The owning fantasy team, as the entry page needs it.
278#[derive(Debug, Clone)]
279pub struct EntryTeam {
280    pub id: FantasyTeamId,
281    /// Who owns the entry — the page shows unplayed picks to this user alone.
282    pub user_id: i64,
283    pub name: String,
284    pub owner_name: String,
285    pub logo: Option<Media>,
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use std::str::FromStr;
292    use strum::IntoEnumIterator;
293
294    fn player(slot: RosterSlot, gsis: &str) -> EntrySlot {
295        EntrySlot {
296            slot,
297            value: PlayerOrDefenseId::Player(NflPlayerId(gsis.to_string())),
298        }
299    }
300
301    fn full_slots() -> Vec<EntrySlot> {
302        use RosterSlot::*;
303        vec![
304            player(Qb, "00-1"),
305            player(Rb1, "00-2"),
306            player(Rb2, "00-3"),
307            player(Wr1, "00-4"),
308            player(Wr2, "00-5"),
309            player(Wr3, "00-6"),
310            player(Te, "00-7"),
311            player(Flex, "00-8"),
312            EntrySlot {
313                slot: Def,
314                value: PlayerOrDefenseId::Defense(TeamAbbr::KC),
315            },
316        ]
317    }
318
319    #[test]
320    fn roster_slot_strings_round_trip_the_db_forms() {
321        // The DB CHECK constraint speaks these exact strings; pin them.
322        let names: Vec<String> = RosterSlot::iter().map(|s| s.to_string()).collect();
323        assert_eq!(
324            names,
325            ["QB", "RB1", "RB2", "WR1", "WR2", "WR3", "TE", "FLEX", "DEF"]
326        );
327        for slot in RosterSlot::iter() {
328            assert_eq!(RosterSlot::from_str(&slot.to_string()), Ok(slot));
329        }
330    }
331
332    #[test]
333    fn position_label_drops_the_slot_ordinal() {
334        let labels: Vec<&str> = RosterSlot::iter().map(|s| s.position_label()).collect();
335        assert_eq!(
336            labels,
337            ["QB", "RB", "RB", "WR", "WR", "WR", "TE", "FLEX", "DEF"]
338        );
339    }
340
341    #[test]
342    fn player_slots_covers_every_slot_but_def_in_roster_order() {
343        let lineup = Lineup::from_slots(full_slots()).expect("nine valid slots");
344        let slots: Vec<RosterSlot> = lineup.player_slots().map(|(s, _)| s).into();
345        let expected: Vec<RosterSlot> = RosterSlot::iter()
346            .filter(|s| *s != RosterSlot::Def)
347            .collect();
348        assert_eq!(slots, expected);
349        let ids: Vec<&NflPlayerId> = lineup.player_ids().into();
350        assert_eq!(ids.first(), Some(&&NflPlayerId("00-1".into())));
351        assert_eq!(ids.last(), Some(&&NflPlayerId("00-8".into())));
352    }
353
354    #[test]
355    fn from_slots_builds_a_total_lineup() {
356        let lineup = Lineup::from_slots(full_slots()).expect("nine valid slots");
357        assert_eq!(lineup.qb, NflPlayerId("00-1".into()));
358        assert_eq!(lineup.flex, NflPlayerId("00-8".into()));
359        assert_eq!(lineup.def, TeamAbbr::KC);
360    }
361
362    #[test]
363    fn from_slots_rejects_missing_slot() {
364        let mut slots = full_slots();
365        slots.pop(); // drop DEF
366        let err = Lineup::from_slots(slots).unwrap_err();
367        assert_eq!(err, LineupError::MissingSlot(RosterSlot::Def));
368    }
369
370    #[test]
371    fn from_slots_reports_mismatched_value_as_missing() {
372        // DEF carrying a player can't come from the DB (CHECK constraint);
373        // if constructed anyway it fills nothing, so DEF reads as missing.
374        let mut slots = full_slots();
375        slots[8] = player(RosterSlot::Def, "00-9");
376        let err = Lineup::from_slots(slots).unwrap_err();
377        assert_eq!(err, LineupError::MissingSlot(RosterSlot::Def));
378    }
379}