Skip to main content

sunday_slate/fantasy_teams/
open_contests.rs

1//! Pure view assembly for the owner's open-contests section on the team
2//! detail page: contests still worth acting on, soonest first.
3
4use std::collections::{HashMap, HashSet};
5
6use time::OffsetDateTime;
7
8use crate::contests::service::{format_kickoff, time_until};
9use crate::entries::EntryId;
10use nfl_data::slates::{Slate, SlateId, SlateStatus};
11
12/// What an open-contest row offers the owner.
13pub enum OpenAction {
14    /// Entered, pre-kickoff: the row links to the lineup at `/entries/{id}`.
15    ViewEntry(EntryId),
16    /// Not entered, pre-kickoff: a button into `/contests/{id}/draft-entry`.
17    /// `true` when a partial draft exists to resume.
18    Draft(bool),
19    /// Entered and live: the row links to `/contests/{id}`.
20    Live,
21}
22
23/// One row in the open-contests section.
24pub struct OpenContestRow {
25    pub contest: SlateId,
26    pub name: String,
27    /// Pre-kickoff: "Kicks off Sun, Sep 7 · 1:00 PM ET — locks in 3 days".
28    /// `None` exactly when the contest is live.
29    pub status: Option<String>,
30    pub action: OpenAction,
31}
32
33/// Select and order the owner's open contests: published slate, not
34/// finished, and either entered or still open for entry. Live contests the
35/// team did not enter are dropped — nothing there is actionable. Soonest
36/// kickoff first, ties by contest id.
37pub fn open_contests(
38    contests: &[Slate],
39    entries: &HashMap<SlateId, EntryId>,
40    resumable: &HashSet<SlateId>,
41    now: OffsetDateTime,
42) -> Vec<OpenContestRow> {
43    let mut rows: Vec<(OffsetDateTime, OpenContestRow)> = contests
44        .iter()
45        .filter_map(|c| {
46            let first = nfl_data::to_eastern(c.kickoff?);
47            let entry = entries.get(&c.id).copied();
48            let (status, action) = match c.status(now) {
49                SlateStatus::Finished => return None,
50                SlateStatus::Live => {
51                    entry?;
52                    (None, OpenAction::Live)
53                }
54                SlateStatus::Upcoming => {
55                    let status = format!(
56                        "Kicks off {} ET — locks {}",
57                        format_kickoff(first),
58                        time_until(now, first)
59                    );
60                    let action = match entry {
61                        Some(id) => OpenAction::ViewEntry(id),
62                        None => OpenAction::Draft(resumable.contains(&c.id)),
63                    };
64                    (Some(status), action)
65                }
66            };
67            Some((
68                first,
69                OpenContestRow {
70                    contest: c.id,
71                    name: c.name.clone(),
72                    status,
73                    action,
74                },
75            ))
76        })
77        .collect();
78    rows.sort_by_key(|(first, row)| (*first, row.contest.0));
79    rows.into_iter().map(|(_, r)| r).collect()
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use nfl_data::{Season, SeasonWeek, Week};
86    use time::macros::datetime;
87
88    fn slate(id: i64, name: &str, kickoff: OffsetDateTime, multiday: bool) -> Slate {
89        Slate {
90            id: SlateId(id),
91            season_week: SeasonWeek {
92                season: Season(2026),
93                week: Week(1),
94            },
95            name: name.to_string(),
96            kickoff: Some(kickoff),
97            multiday,
98        }
99    }
100
101    /// A one-day slate kicking off Sun, Sep 7 2025 at 1:00 PM ET.
102    fn week1() -> Slate {
103        let k = datetime!(2025 - 09 - 07 13:00 -4);
104        slate(1, "Week 1", k, false)
105    }
106
107    /// Three days before week1's kickoff.
108    const NOW: OffsetDateTime = datetime!(2025 - 09 - 04 13:00 -4);
109
110    fn no_entries() -> HashMap<SlateId, EntryId> {
111        HashMap::new()
112    }
113
114    #[test]
115    fn upcoming_entered_links_to_the_entry() {
116        let entries = HashMap::from([(SlateId(1), EntryId(42))]);
117        let rows = open_contests(&[week1()], &entries, &HashSet::new(), NOW);
118        assert_eq!(rows.len(), 1);
119        assert!(matches!(rows[0].action, OpenAction::ViewEntry(EntryId(42))));
120        assert_eq!(
121            rows[0].status.as_deref(),
122            Some("Kicks off Sun, Sep 7 · 1:00 PM ET — locks in 3 days")
123        );
124    }
125
126    #[test]
127    fn stored_utc_kickoff_renders_eastern_wall_clock() {
128        // 17:00 UTC is 1:00 PM EDT; a raw UTC render would say 5:00 PM.
129        let k = datetime!(2025-09-07 17:00 UTC);
130        let rows = open_contests(
131            &[slate(1, "Week 1", k, false)],
132            &no_entries(),
133            &HashSet::new(),
134            datetime!(2025-09-04 12:00 UTC),
135        );
136        assert_eq!(
137            rows[0].status.as_deref(),
138            Some("Kicks off Sun, Sep 7 · 1:00 PM ET — locks in 3 days")
139        );
140    }
141
142    #[test]
143    fn upcoming_unentered_offers_the_draft_editor() {
144        let rows = open_contests(&[week1()], &no_entries(), &HashSet::new(), NOW);
145        assert_eq!(rows.len(), 1);
146        assert!(matches!(rows[0].action, OpenAction::Draft(false)));
147    }
148
149    #[test]
150    fn a_partial_draft_flips_the_action_to_resume() {
151        let resumable = HashSet::from([SlateId(1)]);
152        let rows = open_contests(&[week1()], &no_entries(), &resumable, NOW);
153        assert!(matches!(rows[0].action, OpenAction::Draft(true)));
154    }
155
156    #[test]
157    fn live_entered_watches_the_contest() {
158        // Kickoff has passed but the slate's last day is today: live.
159        let entries = HashMap::from([(SlateId(1), EntryId(42))]);
160        let rows = open_contests(
161            &[week1()],
162            &entries,
163            &HashSet::new(),
164            datetime!(2025 - 09 - 07 16:00 -4),
165        );
166        assert_eq!(rows.len(), 1);
167        assert!(matches!(rows[0].action, OpenAction::Live));
168        assert_eq!(
169            rows[0].status, None,
170            "live rows carry a badge, not a status line"
171        );
172    }
173
174    #[test]
175    fn live_unentered_is_dropped() {
176        let rows = open_contests(
177            &[week1()],
178            &no_entries(),
179            &HashSet::new(),
180            datetime!(2025 - 09 - 07 16:00 -4),
181        );
182        assert!(rows.is_empty());
183    }
184
185    #[test]
186    fn finished_contests_are_dropped_even_when_entered() {
187        let entries = HashMap::from([(SlateId(1), EntryId(42))]);
188        let rows = open_contests(
189            &[week1()],
190            &entries,
191            &HashSet::new(),
192            datetime!(2025 - 09 - 08 12:00 -4),
193        );
194        assert!(rows.is_empty());
195    }
196
197    #[test]
198    fn unpublished_slates_are_dropped() {
199        let undated = Slate {
200            id: SlateId(9),
201            season_week: SeasonWeek {
202                season: Season(2026),
203                week: Week(9),
204            },
205            name: "Week 9".to_string(),
206            kickoff: None,
207            multiday: false,
208        };
209        let rows = open_contests(&[undated], &no_entries(), &HashSet::new(), NOW);
210        assert!(rows.is_empty());
211    }
212
213    #[test]
214    fn rows_order_by_soonest_kickoff() {
215        // Thanksgiving week: Sunday slate listed after Thursday's.
216        let thu = datetime!(2025 - 11 - 27 13:00 -5);
217        let sun = datetime!(2025 - 11 - 30 13:00 -5);
218        let rows = open_contests(
219            &[
220                slate(1, "Sunday Slate", sun, false),
221                slate(2, "Thanksgiving", thu, false),
222            ],
223            &no_entries(),
224            &HashSet::new(),
225            datetime!(2025 - 11 - 25 12:00 -5),
226        );
227        let order: Vec<i64> = rows.iter().map(|r| r.contest.0).collect();
228        assert_eq!(order, vec![2, 1]);
229    }
230}